Initial commit
A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Self-contained injection system that hooks D3D9 EndScene to render an ImGui overlay inside the AC client process.
This commit is contained in:
commit
80b71d295d
179 changed files with 52858 additions and 0 deletions
119
src/RynthCore.Engine/Compatibility/AcClientModule.cs
Normal file
119
src/RynthCore.Engine/Compatibility/AcClientModule.cs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal readonly struct AcClientTextSection
|
||||
{
|
||||
public AcClientTextSection(IntPtr moduleBase, int imageSize, int textBaseVa, byte[] bytes)
|
||||
{
|
||||
ModuleBase = moduleBase;
|
||||
ImageSize = imageSize;
|
||||
TextBaseVa = textBaseVa;
|
||||
Bytes = bytes;
|
||||
}
|
||||
|
||||
public IntPtr ModuleBase { get; }
|
||||
public int ImageSize { get; }
|
||||
public int TextBaseVa { get; }
|
||||
public byte[] Bytes { get; }
|
||||
}
|
||||
|
||||
internal static class AcClientModule
|
||||
{
|
||||
private const int DefaultTextRva = 0x1000;
|
||||
private const int MaxTextSectionBytes = 0x400000;
|
||||
private const int SuspiciousTextSectionBytes = 0x500000;
|
||||
private const ushort ImageDosSignature = 0x5A4D;
|
||||
private const uint ImageNtSignature = 0x00004550;
|
||||
private const int DosHeaderPeOffset = 0x3C;
|
||||
private const int NtOptionalHeaderOffset = 0x18;
|
||||
private const int OptionalHeaderSizeOfImageOffset = 0x38;
|
||||
private static bool _loggedBaseOnce;
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
|
||||
|
||||
public static bool TryReadTextSection(out AcClientTextSection textSection)
|
||||
{
|
||||
textSection = default;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
|
||||
if (moduleBase == IntPtr.Zero)
|
||||
moduleBase = GetModuleHandleW(null);
|
||||
|
||||
if (moduleBase == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Compat($"Compat: acclient.exe module not found (error {Marshal.GetLastWin32Error()}).");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryReadImageSize(moduleBase, out int imageSize))
|
||||
{
|
||||
RynthLog.Compat("Compat: failed to read acclient.exe PE headers.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_loggedBaseOnce)
|
||||
{
|
||||
_loggedBaseOnce = true;
|
||||
RynthLog.Compat($"Compat: acclient.exe base=0x{moduleBase.ToInt32():X8}, size=0x{imageSize:X}");
|
||||
}
|
||||
|
||||
int rawTextSize = imageSize - DefaultTextRva;
|
||||
int textSize = rawTextSize;
|
||||
if (textSize <= 0 || textSize > SuspiciousTextSectionBytes)
|
||||
{
|
||||
textSize = Math.Min(Math.Max(0, rawTextSize), MaxTextSectionBytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
textSize = Math.Min(textSize, MaxTextSectionBytes);
|
||||
}
|
||||
|
||||
if (textSize <= 0)
|
||||
{
|
||||
RynthLog.Compat("Compat: failed to derive a readable acclient .text window.");
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr textBase = IntPtr.Add(moduleBase, DefaultTextRva);
|
||||
byte[] bytes = new byte[textSize];
|
||||
Marshal.Copy(textBase, bytes, 0, bytes.Length);
|
||||
|
||||
textSection = new AcClientTextSection(
|
||||
moduleBase,
|
||||
imageSize,
|
||||
moduleBase.ToInt32() + DefaultTextRva,
|
||||
bytes);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: failed to read acclient text section - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadImageSize(IntPtr moduleBase, out int imageSize)
|
||||
{
|
||||
imageSize = 0;
|
||||
|
||||
if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature)
|
||||
return false;
|
||||
|
||||
int peOffset = Marshal.ReadInt32(moduleBase, DosHeaderPeOffset);
|
||||
if (peOffset <= 0)
|
||||
return false;
|
||||
|
||||
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
|
||||
if ((uint)Marshal.ReadInt32(ntHeaders) != ImageNtSignature)
|
||||
return false;
|
||||
|
||||
imageSize = Marshal.ReadInt32(ntHeaders, NtOptionalHeaderOffset + OptionalHeaderSizeOfImageOffset);
|
||||
return imageSize > DefaultTextRva;
|
||||
}
|
||||
}
|
||||
116
src/RynthCore.Engine/Compatibility/BusyCountHooks.cs
Normal file
116
src/RynthCore.Engine/Compatibility/BusyCountHooks.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class BusyCountHooks
|
||||
{
|
||||
private const int IncrementBusyCountVa = 0x00565610;
|
||||
private const int DecrementBusyCountVa = 0x00565630;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void BusyCountDelegate(IntPtr thisPtr);
|
||||
|
||||
private static BusyCountDelegate? _originalIncrementBusyCount;
|
||||
private static BusyCountDelegate? _incrementBusyCountDetour;
|
||||
private static BusyCountDelegate? _originalDecrementBusyCount;
|
||||
private static BusyCountDelegate? _decrementBusyCountDetour;
|
||||
private static IntPtr _incrementTargetAddress;
|
||||
private static IntPtr _decrementTargetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _incrementDispatchCount;
|
||||
private static int _decrementDispatchCount;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int incrementOff = IncrementBusyCountVa - textSection.TextBaseVa;
|
||||
int decrementOff = DecrementBusyCountVa - textSection.TextBaseVa;
|
||||
if (!LooksHookable(textSection.Bytes, incrementOff, out byte incrementByte))
|
||||
{
|
||||
_statusMessage = $"ClientUISystem::IncrementBusyCount looks invalid @ 0x{IncrementBusyCountVa:X8}.";
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!LooksHookable(textSection.Bytes, decrementOff, out byte decrementByte))
|
||||
{
|
||||
_statusMessage = $"ClientUISystem::DecrementBusyCount looks invalid @ 0x{DecrementBusyCountVa:X8}.";
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_incrementTargetAddress = new IntPtr(textSection.TextBaseVa + incrementOff);
|
||||
_incrementBusyCountDetour = IncrementBusyCountDetour;
|
||||
IntPtr incrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_incrementBusyCountDetour);
|
||||
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
|
||||
|
||||
_decrementTargetAddress = new IntPtr(textSection.TextBaseVa + decrementOff);
|
||||
_decrementBusyCountDetour = DecrementBusyCountDetour;
|
||||
IntPtr decrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_decrementBusyCountDetour);
|
||||
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
|
||||
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_incrementTargetAddress);
|
||||
MinHook.Enable(_decrementTargetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked busy-count seams @ 0x{_incrementTargetAddress.ToInt32():X8}/0x{_decrementTargetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat(
|
||||
$"Compat: busy-count hooks ready - increment=0x{_incrementTargetAddress.ToInt32():X8} (0x{incrementByte:X2}), decrement=0x{_decrementTargetAddress.ToInt32():X8} (0x{decrementByte:X2})");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void IncrementBusyCountDetour(IntPtr thisPtr)
|
||||
{
|
||||
_originalIncrementBusyCount!(thisPtr);
|
||||
|
||||
int count = Interlocked.Increment(ref _incrementDispatchCount);
|
||||
if (count <= 0)
|
||||
RynthLog.Compat($"Compat: busy count incremented #{count}");
|
||||
|
||||
PluginManager.QueueBusyCountIncremented();
|
||||
}
|
||||
|
||||
private static void DecrementBusyCountDetour(IntPtr thisPtr)
|
||||
{
|
||||
_originalDecrementBusyCount!(thisPtr);
|
||||
|
||||
int count = Interlocked.Increment(ref _decrementDispatchCount);
|
||||
if (count <= 0)
|
||||
RynthLog.Compat($"Compat: busy count decremented #{count}");
|
||||
|
||||
PluginManager.QueueBusyCountDecremented();
|
||||
}
|
||||
|
||||
private static bool LooksHookable(byte[] textBytes, int offset, out byte firstByte)
|
||||
{
|
||||
firstByte = 0;
|
||||
if (offset < 0 || offset >= textBytes.Length)
|
||||
return false;
|
||||
|
||||
firstByte = textBytes[offset];
|
||||
return firstByte is not (0x00 or 0xCC or 0xC3);
|
||||
}
|
||||
}
|
||||
412
src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs
Normal file
412
src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Captures the character list from the 0xF658 server packet, persists it per-account,
|
||||
/// and optionally performs a native auto-login sequence with click fallback.
|
||||
/// </summary>
|
||||
internal static class CharacterCaptureHooks
|
||||
{
|
||||
private const uint PostConnectReadyOpcode = 0x0000F7EA;
|
||||
private const uint CharacterListOpcode = 0x0000F658;
|
||||
private const int NetBlobBufPtrOffset = 0x2C;
|
||||
private const int NetBlobBufSizeOffset = 0x30;
|
||||
|
||||
// Auto-login click geometry (matches ThwargFilter LoginCharacterTools)
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const int XCharList = 121;
|
||||
private const int YTopOfBox = 209;
|
||||
private const int YBottomOfBox = 532;
|
||||
private const int AutoLoginDelayMs = 800;
|
||||
private const int AutoLoginWindowWaitMs = 10000;
|
||||
private const int AutoLoginWindowPollMs = 250;
|
||||
private const int AutoLoginAttempts = 3;
|
||||
private const int AutoLoginAttemptDelayMs = 600;
|
||||
private const int AutoLoginDoubleClickGapMs = 100;
|
||||
private const int DirectAutoLoginAttempts = 40;
|
||||
private const int DirectAutoLoginAttemptDelayMs = 250;
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
private static int _autoLoginScheduled;
|
||||
|
||||
public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false)
|
||||
{
|
||||
if (blob == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
|
||||
if (blobSize < 4)
|
||||
return;
|
||||
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
|
||||
if (opcode == PostConnectReadyOpcode)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: [{(isGameEvent ? "GameEvent" : "SmartBox")}] Observed post-connect packet (0xF7EA).");
|
||||
LogoBypassHooks.NotifyPostConnectObserved();
|
||||
return;
|
||||
}
|
||||
|
||||
if (opcode != CharacterListOpcode)
|
||||
return;
|
||||
|
||||
RynthLog.Compat($"CharacterCapture: [{(isGameEvent ? "GameEvent" : "SmartBox")}] Found CharacterList (0xF658)!");
|
||||
LogoBypassHooks.NotifyCharacterListObserved();
|
||||
(List<string> characters, int slotCount) = ParseAndSaveCharacterList(payloadPtr, blobSize);
|
||||
ScheduleAutoLoginIfRequested(characters, slotCount);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called from InnerDispatcherDetour where the buffer is a raw pre-login message (no blob wrapper).
|
||||
/// The first 4 bytes are the opcode.
|
||||
/// </summary>
|
||||
public static void ProcessRawCharacterMessage(IntPtr buffer, uint size)
|
||||
{
|
||||
if (buffer == IntPtr.Zero || size < 4)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(buffer));
|
||||
if (opcode == PostConnectReadyOpcode)
|
||||
{
|
||||
RynthLog.Compat("CharacterCapture: [InnerDispatcher] Observed post-connect packet (0xF7EA).");
|
||||
LogoBypassHooks.NotifyPostConnectObserved();
|
||||
return;
|
||||
}
|
||||
|
||||
if (opcode != CharacterListOpcode)
|
||||
return;
|
||||
|
||||
RynthLog.Compat("CharacterCapture: [InnerDispatcher] Processing 0xF658 raw buffer.");
|
||||
LogoBypassHooks.NotifyCharacterListObserved();
|
||||
(List<string> characters, int slotCount) = size >= 12
|
||||
? ParseAndSaveCharacterList(buffer, size)
|
||||
: (new List<string>(), 0);
|
||||
ScheduleAutoLoginIfRequested(characters, slotCount);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Raw error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static (List<string> characters, int slotCount) ParseAndSaveCharacterList(IntPtr payloadPtr, uint blobSize)
|
||||
{
|
||||
var characters = new List<string>();
|
||||
int slotCount = 0;
|
||||
|
||||
try
|
||||
{
|
||||
int offset = 4; // Skip opcode
|
||||
int characterCount = Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset));
|
||||
offset += 4;
|
||||
|
||||
if (characterCount < 0 || characterCount > 20)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Implausible character count {characterCount} - skipping.");
|
||||
return (characters, slotCount);
|
||||
}
|
||||
|
||||
characters = new List<string>(characterCount);
|
||||
for (int i = 0; i < characterCount; i++)
|
||||
{
|
||||
offset += 4; // Skip Character GUID
|
||||
short nameLen = Marshal.ReadInt16(IntPtr.Add(payloadPtr, offset));
|
||||
offset += 2;
|
||||
|
||||
if (nameLen > 0 && nameLen < 128)
|
||||
{
|
||||
byte[] nameBytes = new byte[nameLen];
|
||||
Marshal.Copy(IntPtr.Add(payloadPtr, offset), nameBytes, 0, nameLen);
|
||||
string name = Encoding.Default.GetString(nameBytes);
|
||||
characters.Add(name);
|
||||
}
|
||||
|
||||
offset += nameLen;
|
||||
if (offset % 4 != 0)
|
||||
offset += 4 - (offset % 4);
|
||||
offset += 4; // Skip Delete Timeout
|
||||
}
|
||||
|
||||
characters.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
slotCount = (int)blobSize > offset + 3
|
||||
? Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset))
|
||||
: characters.Count;
|
||||
|
||||
RynthLog.Compat($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
|
||||
|
||||
if (characters.Count > 0)
|
||||
{
|
||||
(string accountName, string serverName, _) = ReadLaunchContext();
|
||||
SaveCharacterList(characters, accountName, serverName);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Parse error: {ex.Message}");
|
||||
}
|
||||
|
||||
return (characters, slotCount);
|
||||
}
|
||||
|
||||
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContext()
|
||||
{
|
||||
try
|
||||
{
|
||||
string rootDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore");
|
||||
|
||||
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
|
||||
(string accountName, string serverName, string targetCharacter) processContext = ReadLaunchContextFile(processPath);
|
||||
if (!string.IsNullOrWhiteSpace(processContext.accountName) ||
|
||||
!string.IsNullOrWhiteSpace(processContext.serverName) ||
|
||||
!string.IsNullOrWhiteSpace(processContext.targetCharacter))
|
||||
{
|
||||
return processContext;
|
||||
}
|
||||
|
||||
SessionStateRecord? sessionHint = SessionStateStore.TryReadForProcess(Environment.ProcessId);
|
||||
if (sessionHint != null &&
|
||||
(!string.IsNullOrWhiteSpace(sessionHint.AccountName) ||
|
||||
!string.IsNullOrWhiteSpace(sessionHint.ServerName) ||
|
||||
!string.IsNullOrWhiteSpace(sessionHint.TargetCharacter)))
|
||||
{
|
||||
return (sessionHint.AccountName, sessionHint.ServerName, sessionHint.TargetCharacter);
|
||||
}
|
||||
|
||||
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (string.Empty, string.Empty, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
return (string.Empty, string.Empty, string.Empty);
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(filePath));
|
||||
JsonElement root = doc.RootElement;
|
||||
string accountName = root.TryGetProperty("AccountName", out JsonElement an) ? an.GetString() ?? string.Empty : string.Empty;
|
||||
string serverName = root.TryGetProperty("ServerName", out JsonElement sn) ? sn.GetString() ?? string.Empty : string.Empty;
|
||||
string target = root.TryGetProperty("TargetCharacter", out JsonElement tc) ? tc.GetString() ?? string.Empty : string.Empty;
|
||||
return (accountName, serverName, target);
|
||||
}
|
||||
|
||||
private static void SaveCharacterList(List<string> characters, string accountName, string serverName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(accountName))
|
||||
{
|
||||
CharacterCacheStore.Write(accountName, serverName, characters);
|
||||
RynthLog.Compat(
|
||||
!string.IsNullOrWhiteSpace(serverName)
|
||||
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
|
||||
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Info("CharacterCapture: Character list observed but no account name was available; character cache not written.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"CharacterCapture: Save error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ScheduleAutoLoginIfRequested(List<string> characters, int slotCount)
|
||||
{
|
||||
(_, _, string targetCharacter) = ReadLaunchContext();
|
||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
return;
|
||||
|
||||
if (Interlocked.Exchange(ref _autoLoginScheduled, 1) != 0)
|
||||
return;
|
||||
|
||||
List<string> fallbackCharacters = characters.Count > 0
|
||||
? new List<string>(characters)
|
||||
: [];
|
||||
int finalSlots = slotCount > 0 ? slotCount : fallbackCharacters.Count;
|
||||
int fallbackIndex = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
|
||||
int logoDelayMs = LogoBypassHooks.GetRecommendedAutoLoginDelayMs();
|
||||
int scheduledDelayMs = Math.Max(AutoLoginDelayMs, logoDelayMs);
|
||||
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.Sleep(scheduledDelayMs);
|
||||
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _autoLoginScheduled, 0);
|
||||
}
|
||||
})
|
||||
{
|
||||
Name = "RynthCore.AutoLogin",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
|
||||
RynthLog.Compat(
|
||||
fallbackIndex >= 0
|
||||
? $"CharacterCapture: Auto-login scheduled for '{targetCharacter}' in {scheduledDelayMs}ms (native direct login first, fallback slot index {fallbackIndex}, logoDelay={logoDelayMs}ms)."
|
||||
: $"CharacterCapture: Auto-login scheduled for '{targetCharacter}' in {scheduledDelayMs}ms (native direct login only so far, logoDelay={logoDelayMs}ms).");
|
||||
}
|
||||
|
||||
private static void PerformAutoLogin(List<string> fallbackCharacters, int slotCount, string targetCharacter)
|
||||
{
|
||||
string lastDirectStatus = "Direct login did not run.";
|
||||
for (int attempt = 1; attempt <= DirectAutoLoginAttempts; attempt++)
|
||||
{
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' skipped because login is already complete.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (CharacterManagementHooks.TryLogOnCharacter(targetCharacter, out string matchedCharacter, out uint avatarId, out string directStatus))
|
||||
{
|
||||
RynthLog.Compat(
|
||||
$"CharacterCapture: Direct auto-login succeeded for '{matchedCharacter}' (target '{targetCharacter}', avatar 0x{avatarId:X8}) on attempt {attempt}/{DirectAutoLoginAttempts}.");
|
||||
return;
|
||||
}
|
||||
|
||||
lastDirectStatus = directStatus;
|
||||
if (attempt < DirectAutoLoginAttempts)
|
||||
Thread.Sleep(DirectAutoLoginAttemptDelayMs);
|
||||
}
|
||||
|
||||
RynthLog.Compat($"CharacterCapture: Direct auto-login did not succeed for '{targetCharacter}' - {lastDirectStatus}");
|
||||
|
||||
int index = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
|
||||
if (index < 0 || slotCount <= 0)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: No click fallback is available for '{targetCharacter}' after direct login failure.");
|
||||
return;
|
||||
}
|
||||
|
||||
IntPtr hwnd = WaitForGameWindow();
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' - no visible game window found, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
SetForegroundWindow(hwnd);
|
||||
|
||||
float nameSize = (YBottomOfBox - YTopOfBox) / (float)slotCount;
|
||||
int yOffset = (int)(YTopOfBox + (nameSize / 2.0f) + (nameSize * index));
|
||||
|
||||
for (int attempt = 1; attempt <= AutoLoginAttempts; attempt++)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login attempt {attempt}/{AutoLoginAttempts} for '{targetCharacter}' at ({XCharList}, {yOffset}).");
|
||||
|
||||
PostMouseClick(hwnd, XCharList, yOffset);
|
||||
Thread.Sleep(AutoLoginDoubleClickGapMs);
|
||||
PostMouseClick(hwnd, XCharList, yOffset);
|
||||
|
||||
if (attempt < AutoLoginAttempts)
|
||||
Thread.Sleep(AutoLoginAttemptDelayMs);
|
||||
}
|
||||
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login double-click sequence complete for '{targetCharacter}'.");
|
||||
}
|
||||
|
||||
private static IntPtr WaitForGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
int elapsedMs = 0;
|
||||
while (elapsedMs < AutoLoginWindowWaitMs)
|
||||
{
|
||||
IntPtr hwnd = FindVisibleProcessWindow(pid);
|
||||
if (hwnd != IntPtr.Zero)
|
||||
return hwnd;
|
||||
|
||||
Thread.Sleep(AutoLoginWindowPollMs);
|
||||
elapsedMs += AutoLoginWindowPollMs;
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static IntPtr FindVisibleProcessWindow(uint pid)
|
||||
{
|
||||
IntPtr found = IntPtr.Zero;
|
||||
EnumWindows((hWnd, _) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint windowPid);
|
||||
if (windowPid == pid && IsWindowVisible(hWnd))
|
||||
{
|
||||
found = hWnd;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
private static IntPtr MakeLParam(int x, int y) =>
|
||||
(IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
|
||||
|
||||
private static void PostMouseClick(IntPtr hwnd, int x, int y)
|
||||
{
|
||||
IntPtr lParam = MakeLParam(x, y);
|
||||
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
|
||||
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
|
||||
Thread.Sleep(80);
|
||||
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
|
||||
}
|
||||
}
|
||||
260
src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs
Normal file
260
src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CharacterManagementHooks
|
||||
{
|
||||
private const int UIFlowInstanceVa = 0x0083E72C;
|
||||
private const int PlayerSystemVa = 0x0087119C;
|
||||
private const int UIFlowCurModeOffset = 0x8C;
|
||||
private const int UIFlowDataOffset = 0x98;
|
||||
private const int UIPersistantDataCharacterSetOffset = 0x04;
|
||||
private const int CharacterManagementUI = 0x1000000A;
|
||||
private const int GamePlayUI = 0x10000008;
|
||||
private const int MaxCharacterSlots = 20;
|
||||
|
||||
private const int UIFlowGetPersistantDataVa = 0x0051DFB0;
|
||||
private const int GetPlayerSystemVa = 0x0055E1D0;
|
||||
private const int LogOnCharacterVa = 0x00560600;
|
||||
private const int CharacterSetGetIdentityVa = 0x004E8B20;
|
||||
private const int CharacterSetGetNameVa = 0x004FE980;
|
||||
private const int CharacterSetGetGidVa = 0x004FE9B0;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate IntPtr UIFlowGetPersistantDataDelegate(IntPtr uiFlowPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetPlayerSystemDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate byte LogOnCharacterDelegate(IntPtr playerSystemPtr, uint avatarId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate IntPtr CharacterSetGetIdentityDelegate(IntPtr charSetPtr, int index);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate IntPtr CharacterSetGetNameDelegate(IntPtr charSetPtr, int index);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate uint CharacterSetGetGidDelegate(IntPtr charSetPtr, int index);
|
||||
|
||||
private static readonly object BindLock = new();
|
||||
private static bool _bindAttempted;
|
||||
private static bool _bound;
|
||||
private static string _statusMessage = "Not bound.";
|
||||
private static UIFlowGetPersistantDataDelegate? _uiFlowGetPersistantData;
|
||||
private static GetPlayerSystemDelegate? _getPlayerSystem;
|
||||
private static LogOnCharacterDelegate? _logOnCharacter;
|
||||
private static CharacterSetGetIdentityDelegate? _characterSetGetIdentity;
|
||||
private static CharacterSetGetNameDelegate? _characterSetGetName;
|
||||
private static CharacterSetGetGidDelegate? _characterSetGetGid;
|
||||
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool TryGetCurrentMode(out int mode)
|
||||
{
|
||||
mode = 0;
|
||||
IntPtr uiFlowPtr = GetUiFlowPointer();
|
||||
if (uiFlowPtr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
mode = Marshal.ReadInt32(IntPtr.Add(uiFlowPtr, UIFlowCurModeOffset));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out string status)
|
||||
{
|
||||
matchedCharacter = string.Empty;
|
||||
avatarId = 0;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
{
|
||||
status = "No target character requested.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!EnsureBound())
|
||||
{
|
||||
status = _statusMessage;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasMode = TryGetCurrentMode(out int mode);
|
||||
if (hasMode && mode == GamePlayUI)
|
||||
{
|
||||
status = "Client is already in GamePlayUI.";
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr charSetPtr = GetCharacterSetPointer();
|
||||
if (charSetPtr == IntPtr.Zero)
|
||||
{
|
||||
status = hasMode
|
||||
? mode == CharacterManagementUI
|
||||
? "CharacterManagementUI is active, but the character set is not available yet."
|
||||
: $"Current UI mode is 0x{mode:X8}; character set is not available yet."
|
||||
: "UIFlow/character set is not available yet.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var availableCharacters = new List<string>();
|
||||
for (int index = 0; index < MaxCharacterSlots; index++)
|
||||
{
|
||||
IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index);
|
||||
if (identityPtr == IntPtr.Zero)
|
||||
continue;
|
||||
|
||||
IntPtr namePtr = _characterSetGetName!(charSetPtr, index);
|
||||
string? candidateName = ReadAnsiString(namePtr);
|
||||
uint candidateAvatarId = _characterSetGetGid!(charSetPtr, index);
|
||||
if (string.IsNullOrWhiteSpace(candidateName) || candidateAvatarId == 0)
|
||||
continue;
|
||||
|
||||
availableCharacters.Add(candidateName);
|
||||
if (!string.Equals(candidateName, targetCharacter, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
|
||||
IntPtr playerSystemPtr = GetPlayerSystemPointer();
|
||||
if (playerSystemPtr == IntPtr.Zero)
|
||||
{
|
||||
status = "Player system is not available yet.";
|
||||
return false;
|
||||
}
|
||||
|
||||
byte result = _logOnCharacter!(playerSystemPtr, candidateAvatarId);
|
||||
if (result == 0)
|
||||
{
|
||||
status = hasMode
|
||||
? $"LogOnCharacter rejected avatar 0x{candidateAvatarId:X8} ('{candidateName}') while mode=0x{mode:X8}."
|
||||
: $"LogOnCharacter rejected avatar 0x{candidateAvatarId:X8} ('{candidateName}').";
|
||||
return false;
|
||||
}
|
||||
|
||||
matchedCharacter = candidateName;
|
||||
avatarId = candidateAvatarId;
|
||||
status = $"Issued LogOnCharacter for avatar 0x{candidateAvatarId:X8}.";
|
||||
return true;
|
||||
}
|
||||
|
||||
status = availableCharacters.Count > 0
|
||||
? $"Target '{targetCharacter}' not found in native character set [{string.Join(", ", availableCharacters)}]."
|
||||
: "Native character set is empty or not ready yet.";
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool EnsureBound()
|
||||
{
|
||||
lock (BindLock)
|
||||
{
|
||||
if (_bindAttempted)
|
||||
return _bound;
|
||||
|
||||
_bindAttempted = true;
|
||||
try
|
||||
{
|
||||
_uiFlowGetPersistantData = Marshal.GetDelegateForFunctionPointer<UIFlowGetPersistantDataDelegate>(new IntPtr(UIFlowGetPersistantDataVa));
|
||||
_getPlayerSystem = Marshal.GetDelegateForFunctionPointer<GetPlayerSystemDelegate>(new IntPtr(GetPlayerSystemVa));
|
||||
_logOnCharacter = Marshal.GetDelegateForFunctionPointer<LogOnCharacterDelegate>(new IntPtr(LogOnCharacterVa));
|
||||
_characterSetGetIdentity = Marshal.GetDelegateForFunctionPointer<CharacterSetGetIdentityDelegate>(new IntPtr(CharacterSetGetIdentityVa));
|
||||
_characterSetGetName = Marshal.GetDelegateForFunctionPointer<CharacterSetGetNameDelegate>(new IntPtr(CharacterSetGetNameVa));
|
||||
_characterSetGetGid = Marshal.GetDelegateForFunctionPointer<CharacterSetGetGidDelegate>(new IntPtr(CharacterSetGetGidVa));
|
||||
_bound = true;
|
||||
_statusMessage = "Bound.";
|
||||
RynthLog.Compat("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_bound = false;
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"CharacterManagement: Failed to bind native entry points - {ex.Message}");
|
||||
}
|
||||
|
||||
return _bound;
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr GetUiFlowPointer()
|
||||
{
|
||||
try
|
||||
{
|
||||
return Marshal.ReadIntPtr(new IntPtr(UIFlowInstanceVa));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr GetCharacterSetPointer()
|
||||
{
|
||||
IntPtr uiFlowPtr = GetUiFlowPointer();
|
||||
if (uiFlowPtr == IntPtr.Zero)
|
||||
return IntPtr.Zero;
|
||||
|
||||
IntPtr persistantDataPtr = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
persistantDataPtr = _uiFlowGetPersistantData!(uiFlowPtr);
|
||||
}
|
||||
catch
|
||||
{
|
||||
persistantDataPtr = IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (persistantDataPtr == IntPtr.Zero)
|
||||
{
|
||||
try
|
||||
{
|
||||
persistantDataPtr = Marshal.ReadIntPtr(IntPtr.Add(uiFlowPtr, UIFlowDataOffset));
|
||||
}
|
||||
catch
|
||||
{
|
||||
persistantDataPtr = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
return persistantDataPtr != IntPtr.Zero
|
||||
? IntPtr.Add(persistantDataPtr, UIPersistantDataCharacterSetOffset)
|
||||
: IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static IntPtr GetPlayerSystemPointer()
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr playerSystemPtr = _getPlayerSystem!();
|
||||
if (playerSystemPtr != IntPtr.Zero)
|
||||
return playerSystemPtr;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Fall back to the known global if the helper call is unavailable.
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Marshal.ReadIntPtr(new IntPtr(PlayerSystemVa));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ReadAnsiString(IntPtr ptr)
|
||||
{
|
||||
if (ptr == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
return Marshal.PtrToStringAnsi(ptr);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
517
src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs
Normal file
517
src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs
Normal file
|
|
@ -0,0 +1,517 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class ChatCallbackHooks
|
||||
{
|
||||
private enum IncomingChatMode
|
||||
{
|
||||
WrapperQueuedText,
|
||||
WrapperQueuedTextHostEat,
|
||||
AddTextToScrollHostEat
|
||||
}
|
||||
|
||||
private const int PsRefBufferWideDataOffset = 20;
|
||||
private const int MaxIncomingChatChars = 1024;
|
||||
private const int IncomingChatAddTextToScrollVa = 0x005649F0;
|
||||
private const int IncomingChatWrapperVa = 0x0058A000;
|
||||
private const int OutgoingChatVa = 0x005821A0;
|
||||
private const bool EnableIncomingHook = true;
|
||||
private const bool EnableOutgoingHook = true;
|
||||
private static IncomingChatMode CurrentIncomingMode => IncomingChatMode.AddTextToScrollHostEat;
|
||||
|
||||
private static readonly byte[] IncomingChatAddTextToScrollSignature =
|
||||
[
|
||||
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84,
|
||||
0x24, 0x54, 0x09, 0x00, 0x00, 0x53, 0x55, 0x56,
|
||||
0x33, 0xF6, 0x84, 0xC0, 0x57, 0x8B, 0xBC, 0x24,
|
||||
0x5C, 0x09, 0x00, 0x00, 0x89, 0x4C, 0x24, 0x24
|
||||
];
|
||||
|
||||
private static readonly byte[] IncomingChatWrapperSignature =
|
||||
[
|
||||
0xA1, 0xE4, 0x0B, 0x87, 0x00, 0x85, 0xC0, 0x75,
|
||||
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56,
|
||||
0x8B, 0x74, 0x24, 0x10, 0x83, 0xFE, 0x01, 0x74,
|
||||
0x0F
|
||||
];
|
||||
|
||||
private static readonly byte?[] OutgoingChatPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0x8B,
|
||||
0xF9, 0xE8, null, null, null, null, 0x85, 0xC0,
|
||||
0x8B, 0x74, 0x24, 0x20, 0x74, 0x30, 0x8B, 0x06,
|
||||
0x50, 0xFF, 0x15, null, null, null, null, 0x8B,
|
||||
0xD8, 0xC7, 0x44, 0x24, 0x20, 0x00, 0x00, 0x00,
|
||||
0x00, 0xE8, null, null, null, null, 0x8B, 0x08,
|
||||
0x8D, 0x54, 0x24, 0x20, 0x52, 0x53, 0x50, 0xFF,
|
||||
0x51, 0x20, 0x8B, 0x44, 0x24, 0x20, 0x85, 0xC0,
|
||||
0x0F, 0x85, null, null, null, null, 0x8B, 0x44,
|
||||
0x24, 0x24, 0x6A, 0x00
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate int IncomingChatWrapperDelegate(int flags, IntPtr text, int chatChannel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate int OutgoingChatDelegate(IntPtr thisPtr, IntPtr text, uint commandSource);
|
||||
|
||||
private static IncomingChatWrapperDelegate? _originalIncomingChatWrapper;
|
||||
private static IncomingChatWrapperDelegate? _incomingChatWrapperDetour;
|
||||
private static OutgoingChatDelegate? _originalOutgoingChat;
|
||||
private static OutgoingChatDelegate? _outgoingChatDetour;
|
||||
private static IntPtr _incomingAddress;
|
||||
private static IntPtr _originalIncomingChatAddTextPtr;
|
||||
private static IntPtr _outgoingAddress;
|
||||
private static IntPtr _outgoingChatTrampolinePtr;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _incomingChatSuppressionEnabled;
|
||||
private static int _incomingCallCount;
|
||||
|
||||
public static bool IncomingInstalled { get; private set; }
|
||||
public static bool OutgoingInstalled { get; private set; }
|
||||
public static bool IsInstalled => (!EnableIncomingHook || IncomingInstalled) && (!EnableOutgoingHook || OutgoingInstalled);
|
||||
public static string StatusMessage => _statusMessage;
|
||||
public static bool IsOutgoingHookReady => OutgoingInstalled && _originalOutgoingChat != null;
|
||||
internal static IntPtr OutgoingAddress => _outgoingAddress;
|
||||
|
||||
public static void SetIncomingChatSuppression(bool enabled)
|
||||
{
|
||||
Interlocked.Exchange(ref _incomingChatSuppressionEnabled, enabled ? 1 : 0);
|
||||
}
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string incomingMode = GetIncomingModeLabel(CurrentIncomingMode);
|
||||
string incomingStatus = EnableIncomingHook ? "unavailable" : "disabled";
|
||||
string outgoingStatus = EnableOutgoingHook ? "unavailable" : "disabled";
|
||||
bool incomingVerified = !EnableIncomingHook;
|
||||
|
||||
if (EnableIncomingHook && !IncomingInstalled)
|
||||
IncomingInstalled = TryInstallIncomingHook(textSection, out incomingStatus);
|
||||
|
||||
if (IncomingInstalled)
|
||||
{
|
||||
incomingVerified = true;
|
||||
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({incomingMode})";
|
||||
}
|
||||
|
||||
if (EnableOutgoingHook && !OutgoingInstalled)
|
||||
{
|
||||
if (TryResolveOutgoingOffset(textSection, incomingVerified, out int outgoingOff, out string outgoingResolution))
|
||||
{
|
||||
try
|
||||
{
|
||||
_outgoingAddress = new IntPtr(textSection.TextBaseVa + outgoingOff);
|
||||
_outgoingChatDetour = OutgoingChatDetour;
|
||||
IntPtr outgoingPtr = Marshal.GetFunctionPointerForDelegate(_outgoingChatDetour);
|
||||
_outgoingChatTrampolinePtr = MinHook.HookCreate(_outgoingAddress, outgoingPtr);
|
||||
_originalOutgoingChat = Marshal.GetDelegateForFunctionPointer<OutgoingChatDelegate>(_outgoingChatTrampolinePtr);
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_outgoingAddress);
|
||||
OutgoingInstalled = true;
|
||||
outgoingStatus = $"0x{_outgoingAddress.ToInt32():X8} ({outgoingResolution})";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
outgoingStatus = $"hook failed ({ex.Message})";
|
||||
RynthLog.Compat($"Compat: outgoing chat hook unavailable - {ex.Message}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
outgoingStatus = outgoingResolution;
|
||||
if (!outgoingResolution.StartsWith("skipped", StringComparison.Ordinal))
|
||||
RynthLog.Compat($"Compat: outgoing chat hook unavailable - {outgoingResolution}");
|
||||
}
|
||||
}
|
||||
|
||||
if (OutgoingInstalled && !outgoingStatus.StartsWith("0x", StringComparison.Ordinal))
|
||||
outgoingStatus = $"0x{_outgoingAddress.ToInt32():X8}";
|
||||
|
||||
if (!IncomingInstalled && !OutgoingInstalled)
|
||||
{
|
||||
_statusMessage = $"No chat hooks installed. incoming={incomingStatus}, outgoing={outgoingStatus}.";
|
||||
RynthLog.Compat($"Compat: chat callback hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
_statusMessage = $"Ready. incoming={incomingStatus}, outgoing={outgoingStatus}.";
|
||||
RynthLog.Compat($"Compat: chat callback hooks ready - incoming={incomingStatus}, outgoing={outgoingStatus}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: chat callback hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryInstallIncomingHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
if (TryInstallPreferredIncomingHook(textSection, out incomingStatus))
|
||||
return true;
|
||||
|
||||
if (CurrentIncomingMode is not IncomingChatMode.WrapperQueuedText and not IncomingChatMode.WrapperQueuedTextHostEat)
|
||||
{
|
||||
RynthLog.Compat("Compat: preferred incoming chat seam unavailable - falling back to wrapper path.");
|
||||
return TryInstallIncomingWrapperHook(textSection, out incomingStatus);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryInstallPreferredIncomingHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
return CurrentIncomingMode switch
|
||||
{
|
||||
IncomingChatMode.AddTextToScrollHostEat => TryInstallIncomingAddTextHook(textSection, out incomingStatus),
|
||||
IncomingChatMode.WrapperQueuedText => TryInstallIncomingWrapperHook(textSection, out incomingStatus),
|
||||
IncomingChatMode.WrapperQueuedTextHostEat => TryInstallIncomingWrapperHook(textSection, out incomingStatus),
|
||||
_ => TryInstallIncomingWrapperHook(textSection, out incomingStatus)
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryInstallIncomingWrapperHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
int incomingOff = IncomingChatWrapperVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatWrapperSignature))
|
||||
{
|
||||
incomingStatus = $"signature mismatch @ 0x{IncomingChatWrapperVa:X8}";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
|
||||
_incomingChatWrapperDetour = IncomingChatWrapperDetour;
|
||||
IntPtr incomingPtr = Marshal.GetFunctionPointerForDelegate(_incomingChatWrapperDetour);
|
||||
_originalIncomingChatWrapper = Marshal.GetDelegateForFunctionPointer<IncomingChatWrapperDelegate>(MinHook.HookCreate(_incomingAddress, incomingPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_incomingAddress);
|
||||
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({GetIncomingModeLabel(CurrentIncomingMode)})";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
incomingStatus = $"hook failed ({ex.Message})";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryInstallIncomingAddTextHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
int incomingOff = IncomingChatAddTextToScrollVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatAddTextToScrollSignature))
|
||||
{
|
||||
incomingStatus = $"signature mismatch @ 0x{IncomingChatAddTextToScrollVa:X8}";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
|
||||
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
|
||||
}
|
||||
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({GetIncomingModeLabel(CurrentIncomingMode)})";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
incomingStatus = $"hook failed ({ex.Message})";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int IncomingChatWrapperDetour(int flags, IntPtr text, int chatChannel)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CurrentIncomingMode switch
|
||||
{
|
||||
IncomingChatMode.WrapperQueuedText => QueueIncomingAfterOriginal(flags, text, chatChannel),
|
||||
IncomingChatMode.WrapperQueuedTextHostEat => QueueIncomingWithHostEat(flags, text, chatChannel),
|
||||
_ => _originalIncomingChatWrapper!(flags, text, chatChannel)
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: incoming wrapper detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
try { return _originalIncomingChatWrapper!(flags, text, chatChannel); } catch { return 0; }
|
||||
}
|
||||
}
|
||||
|
||||
// [UnmanagedCallersOnly] generates a true native thiscall entry point — no
|
||||
// delegate thunk, no hidden GC-transition overhead that the delegate-based
|
||||
// approach adds. This mirrors Chorizite's working ChatHooks pattern.
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
|
||||
{
|
||||
// 1. Read string BEFORE original — buffer may be freed after
|
||||
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
|
||||
|
||||
// 2. Call original
|
||||
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
|
||||
int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo);
|
||||
|
||||
// 3. Queue AFTER original returns — game state is consistent
|
||||
if (line != null)
|
||||
QueueIncomingChatLine(line, chatType);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static string? ReadIncomingChatLine(IntPtr pStringBase, uint chatType)
|
||||
{
|
||||
try
|
||||
{
|
||||
// PStringBase<ushort> is a 4-byte struct: a single pointer to
|
||||
// PSRefBufferCharData<ushort>. The char data (m_data) starts at
|
||||
// offset 0 in PSRefBufferCharData — no header fields before it.
|
||||
IntPtr charData = Marshal.ReadIntPtr(pStringBase);
|
||||
if (charData == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
int length = 0;
|
||||
while (length < MaxIncomingChatChars)
|
||||
{
|
||||
short ch = Marshal.ReadInt16(charData, length * 2);
|
||||
if (ch == 0)
|
||||
break;
|
||||
length++;
|
||||
}
|
||||
|
||||
string? line = length > 0
|
||||
? Marshal.PtrToStringUni(charData, length)?.TrimEnd('\r', '\n')
|
||||
: null;
|
||||
|
||||
int count = Interlocked.Increment(ref _incomingCallCount);
|
||||
if (count <= 0)
|
||||
RynthLog.Compat($"Compat: incoming chat #{count} type={chatType} len={length}");
|
||||
|
||||
return line;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static void QueueIncomingChatLine(string line, uint chatType)
|
||||
{
|
||||
try { PluginManager.QueueChatWindowText(line, chatType); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static int OutgoingChatDetour(IntPtr thisPtr, IntPtr text, uint commandSource)
|
||||
{
|
||||
try
|
||||
{
|
||||
string? line = ReadWidePString(text);
|
||||
|
||||
if (PluginManager.DispatchChatBarEnter(line))
|
||||
return 1;
|
||||
|
||||
return _originalOutgoingChat!(thisPtr, text, commandSource);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: outgoing chat detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
try { return _originalOutgoingChat!(thisPtr, text, commandSource); } catch { return 0; }
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ReadWidePString(IntPtr pStringBase)
|
||||
{
|
||||
if (pStringBase == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr firstPtr = Marshal.ReadIntPtr(pStringBase);
|
||||
if (firstPtr == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
// Some seams hand us a WidePString whose first field already points at
|
||||
// the wchar_t buffer. Others hand us a PSRefBuffer-backed PStringBase
|
||||
// that needs the +0x14 data offset. Probe both and keep the more sane one.
|
||||
string? direct = TryReadUtf16String(firstPtr);
|
||||
string? buffered = TryReadUtf16String(firstPtr + PsRefBufferWideDataOffset);
|
||||
return ChooseBestWideString(direct, buffered);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? TryReadUtf16String(IntPtr data)
|
||||
{
|
||||
if (data == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
int length = 0;
|
||||
while (length < MaxIncomingChatChars)
|
||||
{
|
||||
short ch = Marshal.ReadInt16(data, length * sizeof(char));
|
||||
if (ch == 0)
|
||||
break;
|
||||
|
||||
if (!IsLikelyWideChar((char)ch))
|
||||
return null;
|
||||
|
||||
length++;
|
||||
}
|
||||
|
||||
return length > 0 ? Marshal.PtrToStringUni(data, length) : string.Empty;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ChooseBestWideString(string? direct, string? buffered)
|
||||
{
|
||||
int directScore = ScoreCandidate(direct);
|
||||
int bufferedScore = ScoreCandidate(buffered);
|
||||
|
||||
if (directScore <= 0 && bufferedScore <= 0)
|
||||
return direct ?? buffered;
|
||||
|
||||
return directScore >= bufferedScore ? direct : buffered;
|
||||
}
|
||||
|
||||
private static int ScoreCandidate(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return 0;
|
||||
|
||||
int score = value.Length;
|
||||
foreach (char ch in value)
|
||||
{
|
||||
if (char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch))
|
||||
score += 2;
|
||||
else if (ch is '/' or '-' or '_' or '.' or '\'')
|
||||
score += 1;
|
||||
else if (char.IsControl(ch))
|
||||
score -= 8;
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
private static bool IsLikelyWideChar(char ch)
|
||||
{
|
||||
return !char.IsControl(ch) || ch is '\r' or '\n' or '\t';
|
||||
}
|
||||
|
||||
private static int QueueIncomingAfterOriginal(int flags, IntPtr text, int chatChannel)
|
||||
{
|
||||
int result = _originalIncomingChatWrapper!(flags, text, chatChannel);
|
||||
if (result != 0)
|
||||
PluginManager.QueueChatWindowText(ReadWidePString(text), unchecked((uint)chatChannel));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int QueueIncomingWithHostEat(int flags, IntPtr text, int chatChannel)
|
||||
{
|
||||
string? line = ReadWidePString(text);
|
||||
if (Volatile.Read(ref _incomingChatSuppressionEnabled) != 0)
|
||||
{
|
||||
PluginManager.QueueChatWindowText(line, unchecked((uint)chatChannel));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int result = _originalIncomingChatWrapper!(flags, text, chatChannel);
|
||||
if (result != 0)
|
||||
PluginManager.QueueChatWindowText(line, unchecked((uint)chatChannel));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetIncomingModeLabel(IncomingChatMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
IncomingChatMode.WrapperQueuedText => "wrapper-queued-text",
|
||||
IncomingChatMode.WrapperQueuedTextHostEat => "wrapper-queued-text-host-eat",
|
||||
IncomingChatMode.AddTextToScrollHostEat => "add-text-to-scroll-host-eat",
|
||||
_ => "wrapper-unknown"
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryResolveOutgoingOffset(
|
||||
AcClientTextSection textSection,
|
||||
bool fixedVaTrusted,
|
||||
out int outgoingOff,
|
||||
out string resolution)
|
||||
{
|
||||
outgoingOff = -1;
|
||||
resolution = "unresolved";
|
||||
|
||||
if (fixedVaTrusted)
|
||||
{
|
||||
int fixedOff = OutgoingChatVa - textSection.TextBaseVa;
|
||||
if (fixedOff >= 0 && fixedOff < textSection.Bytes.Length)
|
||||
{
|
||||
if (PatternScanner.VerifyPattern(textSection.Bytes, fixedOff, OutgoingChatPattern))
|
||||
{
|
||||
outgoingOff = fixedOff;
|
||||
resolution = "fixed-va";
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
byte entryByte = textSection.Bytes[fixedOff];
|
||||
if (IsLikelyExternalHookOpcode(entryByte))
|
||||
{
|
||||
resolution = $"skipped (prepatched-0x{entryByte:X2})";
|
||||
RynthLog.Compat($"Compat: outgoing chat entry at 0x{OutgoingChatVa:X8} appears prepatched (opcode 0x{entryByte:X2}) - skipping RynthCore outgoing hook to avoid conflicting with another injector.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int scannedOff = PatternScanner.FindPattern(textSection.Bytes, OutgoingChatPattern);
|
||||
if (scannedOff >= 0)
|
||||
{
|
||||
outgoingOff = scannedOff;
|
||||
resolution = "pattern-scan";
|
||||
return true;
|
||||
}
|
||||
|
||||
resolution = "resolution failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsLikelyExternalHookOpcode(byte opcode)
|
||||
{
|
||||
return opcode is 0xE9 or 0xE8 or 0xEB or 0x68 or 0xFF;
|
||||
}
|
||||
}
|
||||
249
src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs
Normal file
249
src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches chat commands by calling individual CM_Communication::Event_*
|
||||
/// functions directly. All are cdecl and use AC1Legacy::PStringBase<char>.
|
||||
/// Falls back to keyboard simulation for unrecognized slash commands.
|
||||
/// </summary>
|
||||
internal static unsafe class ChatCommandDispatcher
|
||||
{
|
||||
// CM_Communication::Event_* — all cdecl, all using AC1Legacy::PStringBase<char>
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventTalk =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A53E0;
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventEmote =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A4F40;
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventSoulEmote =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A5320;
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte> FnEventTalkDirectByName =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)0x006A55A0;
|
||||
private static readonly delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte> FnEventChannelBroadcast =
|
||||
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)0x006A4E50;
|
||||
|
||||
private const uint WM_KEYDOWN = 0x0100;
|
||||
private const uint WM_KEYUP = 0x0101;
|
||||
private const uint WM_CHAR = 0x0102;
|
||||
private const int VK_RETURN = 0x0D;
|
||||
|
||||
/// <summary>
|
||||
/// When true, all commands are dispatched via keyboard simulation
|
||||
/// rather than direct function calls.
|
||||
/// </summary>
|
||||
public static bool UseDirectChatInput { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AC1Legacy::PStringBase<char> for Event_* functions.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct LegacyPString
|
||||
{
|
||||
public IntPtr Buffer;
|
||||
|
||||
private static readonly IntPtr NullBufferVa = new(0x008EF11C);
|
||||
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void> Ctor =
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)0x0048C3E0;
|
||||
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, void> ClearFn =
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)0x004AB990;
|
||||
|
||||
public static LegacyPString Create(string text)
|
||||
{
|
||||
var value = new LegacyPString { Buffer = Marshal.ReadIntPtr(NullBufferVa) };
|
||||
byte[] bytes = new byte[text.Length + 1];
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
bytes[i] = (byte)text[i];
|
||||
fixed (byte* pBytes = bytes)
|
||||
Ctor(&value, pBytes);
|
||||
return value;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
fixed (LegacyPString* ptr = &this)
|
||||
ClearFn(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Dispatch(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
string trimmed = text.Trim();
|
||||
if (trimmed.Length == 0) return false;
|
||||
|
||||
// Expand shorthand: /s → /say, /t → /tell, /e → /emote
|
||||
trimmed = ExpandShorthand(trimmed);
|
||||
|
||||
// Direct Chat Input mode — everything goes through keyboard sim
|
||||
if (UseDirectChatInput)
|
||||
return SimulateChatInput(trimmed);
|
||||
|
||||
// /say message
|
||||
if (StartsWithCmd(trimmed, "/say "))
|
||||
return DispatchSay(trimmed.Substring(5));
|
||||
|
||||
// /emote message
|
||||
if (StartsWithCmd(trimmed, "/emote "))
|
||||
return DispatchEmote(trimmed.Substring(7));
|
||||
|
||||
// /e message (soul emote — client-side)
|
||||
if (StartsWithCmd(trimmed, "/me "))
|
||||
return DispatchSoulEmote(trimmed.Substring(4));
|
||||
|
||||
// /tell Name, message
|
||||
if (StartsWithCmd(trimmed, "/tell "))
|
||||
return DispatchTell(trimmed.Substring(6));
|
||||
|
||||
// /a message (allegiance channel broadcast)
|
||||
if (StartsWithCmd(trimmed, "/a "))
|
||||
return DispatchChannelBroadcast(1, trimmed.Substring(3));
|
||||
|
||||
// /f message (fellowship — use keyboard sim, no direct Event_*)
|
||||
if (StartsWithCmd(trimmed, "/f "))
|
||||
return SimulateChatInput(trimmed);
|
||||
|
||||
// Bare text → say
|
||||
if (!trimmed.StartsWith("/", StringComparison.Ordinal))
|
||||
return DispatchSay(trimmed);
|
||||
|
||||
// Everything else → keyboard simulation fallback
|
||||
return SimulateChatInput(trimmed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ChatDispatch: error - {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ExpandShorthand(string text)
|
||||
{
|
||||
if (StartsWithCmd(text, "/s ")) return "/say " + text.Substring(3);
|
||||
if (StartsWithCmd(text, "/t ")) return "/tell " + text.Substring(3);
|
||||
return text;
|
||||
}
|
||||
|
||||
private static bool DispatchSay(string message)
|
||||
{
|
||||
var ps = LegacyPString.Create(message);
|
||||
try
|
||||
{
|
||||
byte result = FnEventTalk(&ps);
|
||||
return result != 0;
|
||||
}
|
||||
finally { ps.Dispose(); }
|
||||
}
|
||||
|
||||
private static bool DispatchEmote(string emoteText)
|
||||
{
|
||||
var ps = LegacyPString.Create(emoteText);
|
||||
try
|
||||
{
|
||||
byte result = FnEventEmote(&ps);
|
||||
return result != 0;
|
||||
}
|
||||
finally { ps.Dispose(); }
|
||||
}
|
||||
|
||||
private static bool DispatchSoulEmote(string emoteText)
|
||||
{
|
||||
var ps = LegacyPString.Create(emoteText);
|
||||
try
|
||||
{
|
||||
byte result = FnEventSoulEmote(&ps);
|
||||
return result != 0;
|
||||
}
|
||||
finally { ps.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches /tell by parsing "Name, message" and calling Event_TalkDirectByName.
|
||||
/// </summary>
|
||||
private static bool DispatchTell(string args)
|
||||
{
|
||||
// Format: "PlayerName, message text"
|
||||
int commaIdx = args.IndexOf(',');
|
||||
if (commaIdx < 1)
|
||||
{
|
||||
return SimulateChatInput("/tell " + args);
|
||||
}
|
||||
|
||||
string targetName = args.Substring(0, commaIdx).Trim();
|
||||
string message = args.Substring(commaIdx + 1).TrimStart();
|
||||
|
||||
if (targetName.Length == 0 || message.Length == 0)
|
||||
return false;
|
||||
|
||||
var psMsg = LegacyPString.Create(message);
|
||||
var psTarget = LegacyPString.Create(targetName);
|
||||
try
|
||||
{
|
||||
byte result = FnEventTalkDirectByName(&psMsg, &psTarget);
|
||||
return result != 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
psMsg.Dispose();
|
||||
psTarget.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches a message to a Turbine chat channel via Event_ChannelBroadcast.
|
||||
/// Channel IDs: 1=Allegiance, 2=General, 3=Trade, 4=LFG, 5=Roleplay, 6=Society
|
||||
/// </summary>
|
||||
private static bool DispatchChannelBroadcast(uint channelId, string message)
|
||||
{
|
||||
if (message.Length == 0)
|
||||
return false;
|
||||
|
||||
var ps = LegacyPString.Create(message);
|
||||
try
|
||||
{
|
||||
byte result = FnEventChannelBroadcast(channelId, &ps);
|
||||
return result != 0;
|
||||
}
|
||||
finally { ps.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simulates keyboard input to type and submit a chat command.
|
||||
/// Used as fallback for commands without a direct Event_* function.
|
||||
/// </summary>
|
||||
private static bool SimulateChatInput(string command)
|
||||
{
|
||||
// Enter → opens chat input
|
||||
IntPtr enterDown = MakeKeyLParam(0x1C, false);
|
||||
IntPtr enterUp = MakeKeyLParam(0x1C, true);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
|
||||
// Type each character
|
||||
foreach (char c in command)
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
|
||||
|
||||
// Enter → submit
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IntPtr MakeKeyLParam(byte scanCode, bool keyUp)
|
||||
{
|
||||
int lParam = 1;
|
||||
lParam |= (scanCode << 16);
|
||||
if (keyUp)
|
||||
lParam |= (1 << 30) | (1 << 31);
|
||||
return new IntPtr(lParam);
|
||||
}
|
||||
|
||||
private static bool StartsWithCmd(string text, string prefix)
|
||||
=> text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
169
src/RynthCore.Engine/Compatibility/ClientActionHooks.cs
Normal file
169
src/RynthCore.Engine/Compatibility/ClientActionHooks.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal readonly record struct ClientActionHookStatus(
|
||||
bool CombatInitialized,
|
||||
bool MovementInitialized,
|
||||
bool CommandInterpreterInitialized,
|
||||
bool PlayerPhysicsInitialized,
|
||||
bool MeleeAvailable,
|
||||
bool MissileAvailable,
|
||||
bool ChangeCombatModeAvailable,
|
||||
bool CancelAttackAvailable,
|
||||
bool QueryHealthAvailable,
|
||||
bool DoMovementAvailable,
|
||||
bool StopMovementAvailable,
|
||||
bool JumpNonAutonomousAvailable,
|
||||
bool AutonomyLevelAvailable,
|
||||
bool SetAutoRunAvailable,
|
||||
bool TapJumpAvailable,
|
||||
bool SetMotionAvailable,
|
||||
bool GetPlayerHeadingAvailable,
|
||||
bool StopCompletelyAvailable,
|
||||
bool TurnToHeadingAvailable,
|
||||
string CombatStatus,
|
||||
string MovementStatus,
|
||||
string CommandInterpreterStatus);
|
||||
|
||||
internal static class ClientActionHooks
|
||||
{
|
||||
public static void Initialize()
|
||||
{
|
||||
Probe();
|
||||
}
|
||||
|
||||
public static void Probe()
|
||||
{
|
||||
RynthLog.Compat("Compat: probing RynthAi action hooks...");
|
||||
|
||||
bool combatReady = CombatActionHooks.Probe();
|
||||
bool movementReady = MovementActionHooks.Probe();
|
||||
bool cmdInterpReady = CommandInterpreterHooks.Probe();
|
||||
bool playerPhysicsReady = PlayerPhysicsHooks.Probe();
|
||||
bool objectReady = ClientObjectHooks.Probe();
|
||||
|
||||
RynthLog.Compat($"Compat: probe complete. combat={(combatReady ? "ready" : "off")}, movement={(movementReady ? "ready" : "off")}, local={(cmdInterpReady ? "ready" : "off")}, player={(playerPhysicsReady ? "ready" : "off")}, objects={(objectReady ? "ready" : "off")}");
|
||||
}
|
||||
|
||||
public static ClientActionHookStatus GetStatus()
|
||||
{
|
||||
return new ClientActionHookStatus(
|
||||
CombatActionHooks.IsInitialized,
|
||||
MovementActionHooks.IsInitialized,
|
||||
CommandInterpreterHooks.IsInitialized,
|
||||
PlayerPhysicsHooks.IsInitialized,
|
||||
CombatActionHooks.HasMeleeAttack,
|
||||
CombatActionHooks.HasMissileAttack,
|
||||
CombatActionHooks.HasChangeCombatMode,
|
||||
CombatActionHooks.HasCancelAttack,
|
||||
CombatActionHooks.HasQueryHealth,
|
||||
MovementActionHooks.HasDoMovement,
|
||||
MovementActionHooks.HasStopMovement,
|
||||
MovementActionHooks.HasJumpNonAutonomous,
|
||||
MovementActionHooks.HasAutonomyLevel,
|
||||
CommandInterpreterHooks.HasSetAutoRun,
|
||||
CommandInterpreterHooks.HasTapJump,
|
||||
CommandInterpreterHooks.HasSetMotion,
|
||||
PlayerPhysicsHooks.HasGetHeading,
|
||||
CommandInterpreterHooks.HasStopCompletely,
|
||||
PlayerPhysicsHooks.HasSetHeading || CommandInterpreterHooks.HasTurnToHeading,
|
||||
CombatActionHooks.StatusMessage,
|
||||
MovementActionHooks.StatusMessage,
|
||||
CommandInterpreterHooks.StatusMessage);
|
||||
}
|
||||
|
||||
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
|
||||
{
|
||||
return CombatActionHooks.MeleeAttack(targetId, attackHeight, powerLevel);
|
||||
}
|
||||
|
||||
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
|
||||
{
|
||||
return CombatActionHooks.MissileAttack(targetId, attackHeight, accuracyLevel);
|
||||
}
|
||||
|
||||
public static bool ChangeCombatMode(int combatMode)
|
||||
{
|
||||
return CombatActionHooks.ChangeCombatMode(combatMode);
|
||||
}
|
||||
|
||||
public static bool CancelAttack()
|
||||
{
|
||||
return CombatActionHooks.CancelAttack();
|
||||
}
|
||||
|
||||
public static bool QueryHealth(uint targetId)
|
||||
{
|
||||
return CombatActionHooks.QueryHealth(targetId);
|
||||
}
|
||||
|
||||
public static bool RequestId(uint objectId)
|
||||
{
|
||||
return CombatActionHooks.RequestId(objectId);
|
||||
}
|
||||
|
||||
public static bool CastSpell(uint targetId, int spellId)
|
||||
{
|
||||
return CombatActionHooks.CastSpell(targetId, spellId);
|
||||
}
|
||||
|
||||
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = MovementActionHooks.HoldKeyRun)
|
||||
{
|
||||
return MovementActionHooks.DoMovement(motion, speed, holdKey);
|
||||
}
|
||||
|
||||
public static bool StopMovement(uint motion, int holdKey = MovementActionHooks.HoldKeyRun)
|
||||
{
|
||||
return MovementActionHooks.StopMovement(motion, holdKey);
|
||||
}
|
||||
|
||||
public static bool JumpNonAutonomous(float extent)
|
||||
{
|
||||
return MovementActionHooks.JumpNonAutonomous(extent);
|
||||
}
|
||||
|
||||
public static bool SetAutonomyLevel(uint level)
|
||||
{
|
||||
return MovementActionHooks.SetAutonomyLevel(level);
|
||||
}
|
||||
|
||||
public static bool SetAutoRun(bool enabled)
|
||||
{
|
||||
return CommandInterpreterHooks.SetAutoRun(enabled);
|
||||
}
|
||||
|
||||
public static bool TapJump()
|
||||
{
|
||||
return CommandInterpreterHooks.TapJump();
|
||||
}
|
||||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
return CommandInterpreterHooks.SetMotion(motion, enabled);
|
||||
}
|
||||
|
||||
public static bool StopCompletely()
|
||||
{
|
||||
return CommandInterpreterHooks.StopCompletely();
|
||||
}
|
||||
|
||||
public static bool TurnToHeading(float headingDegrees)
|
||||
{
|
||||
// Direct quaternion write — instant snap, most reliable (uses proven SmartBox offsets).
|
||||
// Equivalent to old Decal Actions.Heading = value.
|
||||
if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees))
|
||||
return true;
|
||||
|
||||
// Fallback: command interpreter gradual turn
|
||||
return CommandInterpreterHooks.TurnToHeading(headingDegrees);
|
||||
}
|
||||
|
||||
public static bool TryGetPlayerHeading(out float headingDegrees)
|
||||
{
|
||||
return PlayerPhysicsHooks.TryGetPlayerHeading(out headingDegrees);
|
||||
}
|
||||
|
||||
public static bool TryGetObjectName(uint objectId, out string name)
|
||||
{
|
||||
return ClientObjectHooks.TryGetObjectName(objectId, out name);
|
||||
}
|
||||
}
|
||||
208
src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs
Normal file
208
src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks into the AC client's ClientCombatSystem — the high-level combat pipeline
|
||||
/// that handles turn-to-face, power bar build, and attack execution naturally.
|
||||
/// Contrast with CombatActionHooks which sends raw game actions (bypassing facing).
|
||||
/// </summary>
|
||||
internal static class ClientCombatHooks
|
||||
{
|
||||
// ── VAs from Chorizite ClientCombatSystem (confirmed from IDA .text comments) ──
|
||||
|
||||
/// <summary>Static cdecl: ClientCombatSystem* GetCombatSystem()</summary>
|
||||
private const int GetCombatSystemVa = 0x0056B210;
|
||||
|
||||
/// <summary>Global pointer: ClientCombatSystem* s_pCombatSystem</summary>
|
||||
private const int CombatSystemPtrVa = 0x0087166C;
|
||||
|
||||
// Thiscall instance methods on ClientCombatSystem:
|
||||
private const int SetRequestedAttackHeightVa = 0x0056D640;
|
||||
private const int StartAttackRequestVa = 0x0056CD90;
|
||||
private const int EndAttackRequestVa = 0x0056CE30;
|
||||
private const int PlayerInReadyPositionVa = 0x0056C570;
|
||||
private const int AutoTargetVa = 0x0056C9D0;
|
||||
|
||||
// Static cdecl CM_Combat function — notifies the client of height change (same as pressing Del/End/PgDn)
|
||||
private const int SendAttackHeightChangedVa = 0x006AAE10;
|
||||
|
||||
// ── Delegates ───────────────────────────────────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetCombatSystemDelegate();
|
||||
|
||||
// Thiscall: first param = this pointer (passed via ECX on x86)
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SetRequestedAttackHeightDelegate(IntPtr thisPtr, int attackHeight);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void StartAttackRequestDelegate(IntPtr thisPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void EndAttackRequestDelegate(IntPtr thisPtr, int attackHeight, float power);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate byte PlayerInReadyPositionDelegate(IntPtr thisPtr, byte considerAttackingReady);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void AutoTargetDelegate(IntPtr thisPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte SendAttackHeightChangedDelegate(int attackHeight);
|
||||
|
||||
// ── Function pointers ───────────────────────────────────────────────
|
||||
|
||||
private static GetCombatSystemDelegate? _getCombatSystem;
|
||||
private static SetRequestedAttackHeightDelegate? _setAttackHeight;
|
||||
private static StartAttackRequestDelegate? _startAttackRequest;
|
||||
private static EndAttackRequestDelegate? _endAttackRequest;
|
||||
private static PlayerInReadyPositionDelegate? _playerInReadyPosition;
|
||||
private static AutoTargetDelegate? _autoTarget;
|
||||
private static SendAttackHeightChangedDelegate? _sendAttackHeightChanged;
|
||||
|
||||
private static bool _initialized;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInitialized => _initialized;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
public static bool HasClientCombat => _startAttackRequest != null;
|
||||
|
||||
// ── Probe ───────────────────────────────────────────────────────────
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
try
|
||||
{
|
||||
_getCombatSystem = Marshal.GetDelegateForFunctionPointer<GetCombatSystemDelegate>(new IntPtr(GetCombatSystemVa));
|
||||
_setAttackHeight = Marshal.GetDelegateForFunctionPointer<SetRequestedAttackHeightDelegate>(new IntPtr(SetRequestedAttackHeightVa));
|
||||
_startAttackRequest = Marshal.GetDelegateForFunctionPointer<StartAttackRequestDelegate>(new IntPtr(StartAttackRequestVa));
|
||||
_endAttackRequest = Marshal.GetDelegateForFunctionPointer<EndAttackRequestDelegate>(new IntPtr(EndAttackRequestVa));
|
||||
_playerInReadyPosition = Marshal.GetDelegateForFunctionPointer<PlayerInReadyPositionDelegate>(new IntPtr(PlayerInReadyPositionVa));
|
||||
_autoTarget = Marshal.GetDelegateForFunctionPointer<AutoTargetDelegate>(new IntPtr(AutoTargetVa));
|
||||
_sendAttackHeightChanged = Marshal.GetDelegateForFunctionPointer<SendAttackHeightChangedDelegate>(new IntPtr(SendAttackHeightChangedVa));
|
||||
|
||||
// Verify the combat system singleton is accessible
|
||||
IntPtr cs = _getCombatSystem();
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
|
||||
RynthLog.Compat($"Compat: ClientCombat GetCombatSystem()=0x{cs:X8}, global=0x{globalPtr:X8}");
|
||||
if (cs == IntPtr.Zero && globalPtr == IntPtr.Zero)
|
||||
{
|
||||
_statusMessage = "GetCombatSystem returned null — client not ready.";
|
||||
RynthLog.Compat($"Compat: ClientCombat probe - {_statusMessage}");
|
||||
// Don't fail — the pointer may be valid after login
|
||||
}
|
||||
else
|
||||
{
|
||||
IntPtr used = cs != IntPtr.Zero ? cs : globalPtr;
|
||||
RynthLog.Compat($"Compat: ClientCombatSystem at 0x{used:X8}");
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
RynthLog.Compat("Compat: ClientCombat hooks ready — native attack pipeline available.");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: ClientCombat probe failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Initiate a native attack using the client's combat pipeline.
|
||||
/// Sets attack height then calls StartAttackRequest which begins
|
||||
/// auto-repeating attacks. The client handles turn-to-face naturally.
|
||||
/// Target must be selected via SelectItem first.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Initiate a native attack using the client's combat pipeline.
|
||||
/// Calls StartAttackRequest to begin the power bar, then EndAttackRequest
|
||||
/// to fire at the specified height and power. The client handles turn-to-face.
|
||||
/// Target must be selected via SelectItem first.
|
||||
/// </summary>
|
||||
public static bool NativeAttack(int attackHeight, float power)
|
||||
{
|
||||
if (_startAttackRequest == null || _endAttackRequest == null || _getCombatSystem == null)
|
||||
{
|
||||
RynthLog.Compat($"ClientCombat: NativeAttack — delegates null (start={_startAttackRequest != null}, end={_endAttackRequest != null}, getCS={_getCombatSystem != null})");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr cs = _getCombatSystem();
|
||||
if (cs == IntPtr.Zero)
|
||||
{
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
|
||||
if (globalPtr == IntPtr.Zero) return false;
|
||||
cs = globalPtr;
|
||||
}
|
||||
|
||||
// Notify client of height change via CM_Combat (same path as keyboard Del/End/PgDn)
|
||||
_sendAttackHeightChanged?.Invoke(attackHeight);
|
||||
_setAttackHeight!(cs, attackHeight);
|
||||
_startAttackRequest(cs);
|
||||
_endAttackRequest(cs, attackHeight, power);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ClientCombat: NativeAttack EXCEPTION - {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if the player is in a ready position to begin an attack.
|
||||
/// </summary>
|
||||
public static bool IsPlayerReady()
|
||||
{
|
||||
if (_playerInReadyPosition == null || _getCombatSystem == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr cs = _getCombatSystem();
|
||||
if (cs == IntPtr.Zero) return false;
|
||||
return _playerInReadyPosition(cs, 1) != 0;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Auto-target the nearest enemy using the client's targeting system.
|
||||
/// </summary>
|
||||
public static bool AutoTarget()
|
||||
{
|
||||
if (_autoTarget == null || _getCombatSystem == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr cs = _getCombatSystem();
|
||||
if (cs == IntPtr.Zero) return false;
|
||||
_autoTarget(cs);
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
_getCombatSystem = null;
|
||||
_setAttackHeight = null;
|
||||
_startAttackRequest = null;
|
||||
_endAttackRequest = null;
|
||||
_playerInReadyPosition = null;
|
||||
_autoTarget = null;
|
||||
_sendAttackHeightChanged = null;
|
||||
_initialized = false;
|
||||
}
|
||||
}
|
||||
608
src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs
Normal file
608
src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs
Normal file
|
|
@ -0,0 +1,608 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class ClientHelperHooks
|
||||
{
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetSelectedObjectDelegate(uint objectId, int reselect);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void GetItemIdDelegate(out uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetAcPluginDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UseObjectOnDelegate(IntPtr acPlugin, uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte UseWithTargetEventDelegate(uint objectId, uint targetId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UseEquippedItemDelegate(IntPtr acPlugin, uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
// NOTE: The stubs at 0x0055A9E0 / 0x0055AA00 are stdcall forwarders that
|
||||
// completely ignore their `this` parameter. They read args off the stack
|
||||
// starting at [ESP+0x08] and RET with full callee-cleanup (0x10 / 0x14).
|
||||
// We declare these stdcall so the caller pushes all 4/5 slots and the
|
||||
// callee cleanup matches — this lets us pass IntPtr.Zero as `this` and
|
||||
// avoid the DAT_00871054 global that's only set by the Decal plugin loader.
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate void MoveItemExternalDelegate(IntPtr acPlugin, uint objectId, uint targetContainerId, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate void MoveItemInternalDelegate(IntPtr acPlugin, uint objectId, uint targetContainerId, int slot, int amount);
|
||||
|
||||
// CM_Inventory::Event_StackableMerge — the canonical public API for
|
||||
// merging two stacks. Cdecl, returns bool. Confirmed via Chorizite map:
|
||||
// 002ABDD0 CM_Inventory::Event_StackableMerge(ulong,ulong,long)
|
||||
// live VA: 0x006ACDD0
|
||||
// This is the correct entry point — sends opcode 0x1A AND wires up the
|
||||
// client-side action queue properly. The earlier FUN_006AC950 was an
|
||||
// inner helper (packet-only), and FUN_0058E3C0 is the wield wrapper
|
||||
// (NOT merge — it tried to equip Pyreals).
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte EventStackableMergeDelegate(uint mergeFromId, uint mergeToId, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate byte InqPlayerCoordsDelegate(IntPtr playerSystem, out double northSouth, out double eastWest);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate uint GetPlayerIdDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate int AddTextToScrollDelegate(
|
||||
IntPtr clientSystem,
|
||||
ref WidePString text,
|
||||
uint chatType,
|
||||
byte unknown,
|
||||
IntPtr stringInfo);
|
||||
|
||||
private const int SetSelectedObjectVa = 0x0058D110;
|
||||
private const int SelectedIdVa = 0x00871E54;
|
||||
private const int PreviousSelectedIdVa = 0x00871E58;
|
||||
private const int GetAcPluginVa = 0x0055A740;
|
||||
private const int UseObjectOnVa = 0x0055A8C0;
|
||||
private const int UseEquippedItemVa = 0x0055A910;
|
||||
private const int MoveItemExternalVa = 0x0055A9E0;
|
||||
private const int MoveItemInternalVa = 0x0055AA00;
|
||||
// Globals read by FUN_00588f70 to decide whole-move (opcode 0x19) vs
|
||||
// split-to-slot (opcode 0x55). Normally set by UI drag-drop code; we
|
||||
// write them directly to force the split path for stack merges.
|
||||
private const int SplitAmountVa = 0x0081D7EC; // split_amount
|
||||
private const int TotalStackVa = 0x0081D7F0; // total_stack
|
||||
// CM_Inventory::Event_StackableMerge — public merge-stack API (from Chorizite map).
|
||||
private const int EventStackableMergeVa = 0x006ACDD0;
|
||||
private const int UseObjectVa = 0x00565750;
|
||||
private const int PlayerSystemVa = 0x0087119C;
|
||||
private const int InqPlayerCoordsVa = 0x00560E00;
|
||||
private const int UiSystemVa = 0x00871354;
|
||||
private const int GetPlayerIdVa = 0x0048E5F0;
|
||||
private const int CommunicationSystemVa = 0x00870BE4;
|
||||
private const int AddTextToScrollVa = 0x005649F0;
|
||||
private const int UseWithTargetEventVa = 0x006AD3E0;
|
||||
|
||||
private static SetSelectedObjectDelegate? _setSelectedObject;
|
||||
private static UseObjectDelegate? _useObject;
|
||||
private static GetAcPluginDelegate? _getAcPlugin;
|
||||
private static UseObjectOnDelegate? _useObjectOn;
|
||||
private static UseEquippedItemDelegate? _useEquippedItem;
|
||||
private static MoveItemExternalDelegate? _moveItemExternal;
|
||||
private static MoveItemInternalDelegate? _moveItemInternal;
|
||||
private static EventStackableMergeDelegate? _eventStackableMerge;
|
||||
private static InqPlayerCoordsDelegate? _inqPlayerCoords;
|
||||
private static GetPlayerIdDelegate? _getPlayerId;
|
||||
private static AddTextToScrollDelegate? _addTextToScroll;
|
||||
private static UseWithTargetEventDelegate? _useWithTargetEvent;
|
||||
private static bool _initialized;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _interactionLogCount;
|
||||
|
||||
public static bool IsInitialized => _initialized;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
public static bool HasSelectItem => _setSelectedObject != null;
|
||||
public static bool HasSetSelectedObjectId => _setSelectedObject != null;
|
||||
public static bool HasGetSelectedItemId => true;
|
||||
public static bool HasGetPreviousSelectedItemId => true;
|
||||
public static bool HasUseObject => _useObject != null;
|
||||
public static bool HasUseObjectOn => _useObjectOn != null;
|
||||
public static bool HasUseEquippedItem => _useEquippedItem != null;
|
||||
public static bool HasMoveItemExternal => _moveItemExternal != null;
|
||||
public static bool HasMoveItemInternal => _moveItemInternal != null;
|
||||
public static bool HasSplitStackInternal => _moveItemInternal != null;
|
||||
public static bool HasMergeStackInternal => _eventStackableMerge != null;
|
||||
public static bool HasGetCurCoords => _inqPlayerCoords != null;
|
||||
public static bool HasGetPlayerId => _getPlayerId != null;
|
||||
public static bool HasGetGroundContainerId => true;
|
||||
public static bool HasWriteToChat => _addTextToScroll != null;
|
||||
public static bool HasInvokeParser => true;
|
||||
private static int _currentGroundContainerId;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
try
|
||||
{
|
||||
_setSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(new IntPtr(SetSelectedObjectVa));
|
||||
_useObject = Marshal.GetDelegateForFunctionPointer<UseObjectDelegate>(new IntPtr(UseObjectVa));
|
||||
_getAcPlugin = Marshal.GetDelegateForFunctionPointer<GetAcPluginDelegate>(new IntPtr(GetAcPluginVa));
|
||||
_useObjectOn = Marshal.GetDelegateForFunctionPointer<UseObjectOnDelegate>(new IntPtr(UseObjectOnVa));
|
||||
_useEquippedItem = Marshal.GetDelegateForFunctionPointer<UseEquippedItemDelegate>(new IntPtr(UseEquippedItemVa));
|
||||
_moveItemExternal = Marshal.GetDelegateForFunctionPointer<MoveItemExternalDelegate>(new IntPtr(MoveItemExternalVa));
|
||||
_moveItemInternal = Marshal.GetDelegateForFunctionPointer<MoveItemInternalDelegate>(new IntPtr(MoveItemInternalVa));
|
||||
_eventStackableMerge = Marshal.GetDelegateForFunctionPointer<EventStackableMergeDelegate>(new IntPtr(EventStackableMergeVa));
|
||||
_inqPlayerCoords = Marshal.GetDelegateForFunctionPointer<InqPlayerCoordsDelegate>(new IntPtr(InqPlayerCoordsVa));
|
||||
_getPlayerId = Marshal.GetDelegateForFunctionPointer<GetPlayerIdDelegate>(new IntPtr(GetPlayerIdVa));
|
||||
_addTextToScroll = Marshal.GetDelegateForFunctionPointer<AddTextToScrollDelegate>(new IntPtr(AddTextToScrollVa));
|
||||
_useWithTargetEvent = Marshal.GetDelegateForFunctionPointer<UseWithTargetEventDelegate>(new IntPtr(UseWithTargetEventVa));
|
||||
_initialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
RynthLog.Compat("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers.");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: helper hooks failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SelectItem(uint objectId)
|
||||
{
|
||||
return SetSelectedObjectId(objectId);
|
||||
}
|
||||
|
||||
public static bool SetSelectedObjectId(uint objectId)
|
||||
{
|
||||
if (_setSelectedObject == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_setSelectedObject(objectId, 1);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static uint GetSelectedItemId()
|
||||
{
|
||||
return ReadUInt32(SelectedIdVa);
|
||||
}
|
||||
|
||||
public static uint GetPreviousSelectedItemId()
|
||||
{
|
||||
return ReadUInt32(PreviousSelectedIdVa);
|
||||
}
|
||||
|
||||
public static bool UseObject(uint objectId)
|
||||
{
|
||||
if (_useObject == null || !IsValidObjectId(objectId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr uiSystem = ReadPointer(UiSystemVa);
|
||||
if (uiSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
_useObject(uiSystem, objectId);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool UseObjectOn(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_useWithTargetEvent(sourceObjectId, targetObjectId);
|
||||
LogInteraction($"UseObjectOn invoked via Event_UseWithTargetEvent source=0x{sourceObjectId:X8} target=0x{targetObjectId:X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogInteraction($"UseObjectOn exception for 0x{sourceObjectId:X8} -> 0x{targetObjectId:X8}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr acPlugin = GetAcPlugin();
|
||||
if (acPlugin == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
_useEquippedItem(acPlugin, sourceObjectId, targetObjectId);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool MoveItemExternal(uint objectId, uint targetContainerId, int amount)
|
||||
{
|
||||
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
|
||||
// uninitialized Decal plugin pointer at DAT_00871054.
|
||||
_moveItemExternal(IntPtr.Zero, objectId, targetContainerId, amount);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (_moveItemInternal == null) return false;
|
||||
if (!IsValidObjectId(objectId)) return false;
|
||||
if (!IsValidContainerId(targetContainerId)) return false;
|
||||
if (slot < 0) return false;
|
||||
if (amount <= 0) return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
|
||||
// uninitialized Decal plugin pointer at DAT_00871054.
|
||||
//
|
||||
// Note: the stub → FUN_00588f70 picks between opcode 0x19
|
||||
// (PutItemInContainer — whole move, first empty slot) and opcode
|
||||
// 0x55 (StackableSplitToContainer — targets a specific slot) based
|
||||
// on DAT_0081d7ec vs DAT_0081d7f0. Default state (1/1) takes the
|
||||
// whole-move path, which is what AutoCram wants. For stack merges
|
||||
// where the slot must be honored, callers should use
|
||||
// SplitStackInternal instead.
|
||||
_moveItemInternal(IntPtr.Zero, objectId, targetContainerId, slot, amount);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Move a stack of items onto a specific slot in the target container, merging
|
||||
/// with any existing same-type stack at that slot. Used by AutoStack.
|
||||
///
|
||||
/// Implementation note: writes split_amount/total_stack globals (normally set
|
||||
/// by UI drag-drop code) so FUN_00588f70 takes the opcode 0x55 path
|
||||
/// (StackableSplitToContainer), which honors the slot parameter. The default
|
||||
/// MoveItemInternal path sends opcode 0x19 (PutItemInContainer) which ignores
|
||||
/// slot and lands the item in the first empty slot of the container.
|
||||
/// </summary>
|
||||
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (_moveItemInternal == null) return false;
|
||||
if (!IsValidObjectId(objectId)) return false;
|
||||
if (!IsValidContainerId(targetContainerId)) return false;
|
||||
if (slot < 0) return false;
|
||||
if (amount <= 0) return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Force split_amount < total_stack so FUN_00588f70 takes the split
|
||||
// path. The actual values aren't sent on the wire — FUN_00588f70
|
||||
// only uses them to pick which sub-function to dispatch to.
|
||||
Marshal.WriteInt32(new IntPtr(SplitAmountVa), amount);
|
||||
Marshal.WriteInt32(new IntPtr(TotalStackVa), amount + 1);
|
||||
|
||||
_moveItemInternal(IntPtr.Zero, objectId, targetContainerId, slot, amount);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merge two stacks of the same item type by calling the canonical
|
||||
/// public API CM_Inventory::Event_StackableMerge (cdecl) at 0x006ACDD0.
|
||||
/// Args: (mergeFromId, mergeToId, amount). This is the same entry point
|
||||
/// the legacy drag-drop UI ultimately calls — it sends opcode 0x1A and
|
||||
/// wires up the client-side action queue properly.
|
||||
///
|
||||
/// Supports split-merge: reads source.STACK_SIZE, target.STACK_SIZE, and
|
||||
/// MAX_STACK_SIZE from the PublicWeenieDesc fast-path and passes
|
||||
/// amount = min(sourceCount, max - targetCount). This lets a small chunk
|
||||
/// peel off a large source stack to top off a near-full target, instead
|
||||
/// of being limited to full-merges that fit entirely under the cap.
|
||||
/// </summary>
|
||||
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (_eventStackableMerge == null) return false;
|
||||
if (!IsValidObjectId(sourceObjectId)) return false;
|
||||
if (!IsValidObjectId(targetObjectId)) return false;
|
||||
|
||||
// Read counts via the PWD fast path (stypes 11/12 are served from
|
||||
// PublicWeenieDesc directly — no broken InqInt for inventory items).
|
||||
ClientObjectHooks.TryGetObjectIntProperty(sourceObjectId, 12 /* STACK_SIZE */, out int sourceCount);
|
||||
if (sourceCount <= 0) sourceCount = 1;
|
||||
|
||||
ClientObjectHooks.TryGetObjectIntProperty(targetObjectId, 12 /* STACK_SIZE */, out int targetCount);
|
||||
if (targetCount < 0) targetCount = 0;
|
||||
|
||||
ClientObjectHooks.TryGetObjectIntProperty(sourceObjectId, 11 /* MAX_STACK_SIZE */, out int maxStack);
|
||||
|
||||
int amount;
|
||||
if (maxStack > 0)
|
||||
{
|
||||
int room = maxStack - targetCount;
|
||||
if (room <= 0)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
|
||||
return false;
|
||||
}
|
||||
amount = Math.Min(sourceCount, room);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Couldn't read max — fall back to full source merge.
|
||||
amount = sourceCount;
|
||||
}
|
||||
|
||||
if (amount <= 0) return false;
|
||||
|
||||
try
|
||||
{
|
||||
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
|
||||
RynthLog.Compat($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
|
||||
return rv != 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetCurCoords(out double northSouth, out double eastWest)
|
||||
{
|
||||
northSouth = 0;
|
||||
eastWest = 0;
|
||||
|
||||
if (_inqPlayerCoords == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr playerSystem = ReadPointer(PlayerSystemVa);
|
||||
if (playerSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
// The live helper returns EW first and NS second.
|
||||
// Normalize it here so plugins see the same NS/EW basis that Decal's Coordinates() exposed.
|
||||
bool success = _inqPlayerCoords(playerSystem, out double first, out double second) != 0;
|
||||
if (!success)
|
||||
return false;
|
||||
|
||||
northSouth = second;
|
||||
eastWest = first;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
northSouth = 0;
|
||||
eastWest = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static uint GetPlayerId()
|
||||
{
|
||||
if (_getPlayerId == null)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return _getPlayerId();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static uint GetGroundContainerId()
|
||||
{
|
||||
return unchecked((uint)Volatile.Read(ref _currentGroundContainerId));
|
||||
}
|
||||
|
||||
public static void NotifyViewObjectContents(uint objectId)
|
||||
{
|
||||
if (!IsValidObjectId(objectId))
|
||||
return;
|
||||
|
||||
Interlocked.Exchange(ref _currentGroundContainerId, unchecked((int)objectId));
|
||||
}
|
||||
|
||||
public static void NotifyStopViewingObjectContents(uint objectId)
|
||||
{
|
||||
if (!IsValidObjectId(objectId))
|
||||
return;
|
||||
|
||||
int current = Volatile.Read(ref _currentGroundContainerId);
|
||||
if (unchecked((uint)current) == objectId)
|
||||
Interlocked.Exchange(ref _currentGroundContainerId, 0);
|
||||
}
|
||||
|
||||
private static bool IsValidObjectId(uint objectId)
|
||||
{
|
||||
return objectId != 0;
|
||||
}
|
||||
|
||||
private static bool IsValidContainerId(uint containerId)
|
||||
{
|
||||
return containerId != 0;
|
||||
}
|
||||
|
||||
public static bool WriteToChat(string? text, int chatType)
|
||||
{
|
||||
if (_addTextToScroll == null || string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr communicationSystem = ReadPointer(CommunicationSystemVa);
|
||||
if (communicationSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
string line = text.TrimEnd('\r', '\n');
|
||||
if (line.Length == 0)
|
||||
return false;
|
||||
|
||||
ushort[] chars = new ushort[line.Length + 1]; // +1 for null terminator (wcslen requirement)
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
chars[i] = line[i];
|
||||
|
||||
var wide = WidePString.Create(chars);
|
||||
try
|
||||
{
|
||||
return _addTextToScroll(
|
||||
communicationSystem,
|
||||
ref wide,
|
||||
unchecked((uint)chatType),
|
||||
0,
|
||||
IntPtr.Zero) != 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
wide.Dispose();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool InvokeParser(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
string line = text.TrimEnd('\r', '\n');
|
||||
if (line.Length == 0)
|
||||
return false;
|
||||
|
||||
RynthLog.Compat($"Compat: InvokeParser text='{line}'");
|
||||
return ChatCommandDispatcher.Dispatch(line);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: InvokeParser failed - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
_setSelectedObject = null;
|
||||
_useObject = null;
|
||||
_getAcPlugin = null;
|
||||
_useObjectOn = null;
|
||||
_useEquippedItem = null;
|
||||
_moveItemExternal = null;
|
||||
_moveItemInternal = null;
|
||||
_eventStackableMerge = null;
|
||||
_inqPlayerCoords = null;
|
||||
_getPlayerId = null;
|
||||
_addTextToScroll = null;
|
||||
_useWithTargetEvent = null;
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
private static IntPtr GetAcPlugin()
|
||||
{
|
||||
if (_getAcPlugin == null)
|
||||
return IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
return _getAcPlugin();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
private static void LogInteraction(string message)
|
||||
{
|
||||
if (_interactionLogCount >= 24)
|
||||
return;
|
||||
|
||||
_interactionLogCount++;
|
||||
RynthLog.Compat($"Compat: {message}");
|
||||
}
|
||||
|
||||
private static uint ReadUInt32(int address)
|
||||
{
|
||||
return unchecked((uint)Marshal.ReadInt32(new IntPtr(address)));
|
||||
}
|
||||
|
||||
private static IntPtr ReadPointer(int address)
|
||||
{
|
||||
return Marshal.ReadIntPtr(new IntPtr(address));
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct WidePString
|
||||
{
|
||||
private static readonly IntPtr NullWideBufferVa = new(0x00818340);
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, ushort*, void> Ctor = (delegate* unmanaged[Thiscall]<WidePString*, ushort*, void>)0x00402730;
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, void> Dtor = (delegate* unmanaged[Thiscall]<WidePString*, void>)0x004011B0;
|
||||
|
||||
public IntPtr CharBuffer;
|
||||
|
||||
public static WidePString Create(ushort[] chars)
|
||||
{
|
||||
var value = new WidePString
|
||||
{
|
||||
CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa)
|
||||
};
|
||||
|
||||
fixed (ushort* pChars = chars)
|
||||
Ctor(&value, pChars);
|
||||
return value;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
fixed (WidePString* ptr = &this)
|
||||
Dtor(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
1134
src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs
Normal file
1134
src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs
Normal file
File diff suppressed because it is too large
Load diff
672
src/RynthCore.Engine/Compatibility/CombatActionHooks.cs
Normal file
672
src/RynthCore.Engine/Compatibility/CombatActionHooks.cs
Normal file
|
|
@ -0,0 +1,672 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CombatActionHooks
|
||||
{
|
||||
private const int QueryHealthResponseVa = 0x006AA900;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool TargetedMeleeAttackDelegate(uint targetId, int attackHeight, float powerLevel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool TargetedMissileAttackDelegate(uint targetId, int attackHeight, float accuracyLevel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool ChangeCombatModeDelegate(int combatMode);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool CancelAttackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool QueryHealthDelegate(uint targetId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool RequestIdDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool CastSpellDelegate(uint targetId, int spellId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate uint QueryHealthResponseDelegate(IntPtr uiQueueManager, IntPtr buffer, uint size);
|
||||
|
||||
public const int AttackHeightHigh = 1;
|
||||
public const int AttackHeightMedium = 2;
|
||||
public const int AttackHeightLow = 3;
|
||||
|
||||
public const int CombatModeNonCombat = 1;
|
||||
public const int CombatModeMelee = 2;
|
||||
public const int CombatModeMissile = 4;
|
||||
public const int CombatModeMagic = 8;
|
||||
|
||||
private static readonly byte[] CombatPrologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
|
||||
|
||||
private static TargetedMeleeAttackDelegate? _meleeAttack;
|
||||
private static TargetedMissileAttackDelegate? _missileAttack;
|
||||
private static ChangeCombatModeDelegate? _changeCombatMode;
|
||||
private static CancelAttackDelegate? _cancelAttack;
|
||||
private static QueryHealthDelegate? _queryHealth;
|
||||
private static RequestIdDelegate? _requestId;
|
||||
private static CastSpellDelegate? _castSpell;
|
||||
private static QueryHealthResponseDelegate? _queryHealthResponseDetour;
|
||||
private static QueryHealthResponseDelegate? _originalQueryHealthResponse;
|
||||
private static QueryHealthResponseDelegate? _identifyObjectDetour;
|
||||
private static QueryHealthResponseDelegate? _originalIdentifyObject;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
public static bool HasMeleeAttack => _meleeAttack != null;
|
||||
public static bool HasMissileAttack => _missileAttack != null;
|
||||
public static bool HasChangeCombatMode => _changeCombatMode != null;
|
||||
public static bool HasCancelAttack => _cancelAttack != null;
|
||||
public static bool HasQueryHealth => _queryHealth != null;
|
||||
public static bool HasRequestId => _requestId != null;
|
||||
public static bool HasCastSpell => _castSpell != null;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
Reset();
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte[] text = textSection.Bytes;
|
||||
|
||||
byte[] cancelOpcode = [0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00];
|
||||
int cancelOpcodeOff = PatternScanner.FindPattern(text, cancelOpcode);
|
||||
if (cancelOpcodeOff < 0)
|
||||
{
|
||||
_statusMessage = "CancelAttack opcode 0x1B7 not found.";
|
||||
RynthLog.Compat("Compat: combat probe failed - CancelAttack opcode 0x1B7 not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int cancelFuncOff = PatternScanner.FindPrologueBefore(text, cancelOpcodeOff, CombatPrologue);
|
||||
if (cancelFuncOff < 0)
|
||||
{
|
||||
_statusMessage = "CancelAttack prologue not found.";
|
||||
RynthLog.Compat("Compat: combat probe failed - CancelAttack prologue not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int regionStart = Math.Max(0, cancelOpcodeOff - 0x500);
|
||||
int regionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x500);
|
||||
|
||||
byte[] changeModeOpcode = [0xC7, 0x02, 0x53, 0x00, 0x00, 0x00];
|
||||
int changeModeOff = PatternScanner.FindPatternInRegion(text, changeModeOpcode, regionStart, regionEnd);
|
||||
int changeModeFuncOff = changeModeOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, changeModeOff, CombatPrologue)
|
||||
: -1;
|
||||
|
||||
byte[] queryHealthOpcode = [0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00];
|
||||
int queryHealthOff = PatternScanner.FindPatternInRegion(text, queryHealthOpcode, regionStart, regionEnd);
|
||||
int queryHealthFuncOff = queryHealthOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, queryHealthOff, CombatPrologue)
|
||||
: -1;
|
||||
|
||||
byte[] meleeOpcode = [0xC7, 0x02, 0x08, 0x00, 0x00, 0x00];
|
||||
int meleeOff = PatternScanner.FindPatternInRegion(text, meleeOpcode, regionStart, regionEnd);
|
||||
int meleeFuncOff = meleeOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, meleeOff, CombatPrologue)
|
||||
: -1;
|
||||
|
||||
byte[] missileOpcode = [0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00];
|
||||
int missileOff = PatternScanner.FindPatternInRegion(text, missileOpcode, regionStart, regionEnd);
|
||||
int missileFuncOff = missileOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, missileOff, CombatPrologue)
|
||||
: -1;
|
||||
|
||||
// RequestId / IdentifyObject — game action 0xC8
|
||||
// Search wider region since it may not be near the combat actions
|
||||
int wideRegionStart = Math.Max(0, cancelOpcodeOff - 0x2000);
|
||||
int wideRegionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x2000);
|
||||
byte[] requestIdOpcode = [0xC7, 0x02, 0xC8, 0x00, 0x00, 0x00];
|
||||
int requestIdOff = PatternScanner.FindPatternInRegion(text, requestIdOpcode, wideRegionStart, wideRegionEnd);
|
||||
int requestIdFuncOff = requestIdOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, requestIdOff, CombatPrologue)
|
||||
: -1;
|
||||
|
||||
// CastSpell — search full text section for known candidate opcodes
|
||||
// Candidates: 0x4A (cast targeted), 0x48, 0x55, 0x5D
|
||||
int castSpellFuncOff = -1;
|
||||
int castSpellOff = -1;
|
||||
byte[][] castSpellCandidates = [
|
||||
[0xC7, 0x02, 0x4A, 0x00, 0x00, 0x00],
|
||||
[0xC7, 0x02, 0x48, 0x00, 0x00, 0x00],
|
||||
[0xC7, 0x02, 0x55, 0x00, 0x00, 0x00],
|
||||
[0xC7, 0x02, 0x5D, 0x00, 0x00, 0x00],
|
||||
];
|
||||
foreach (byte[] candidate in castSpellCandidates)
|
||||
{
|
||||
int off = PatternScanner.FindPattern(text, candidate);
|
||||
if (off >= 0)
|
||||
{
|
||||
int funcOff = PatternScanner.FindPrologueBefore(text, off, CombatPrologue);
|
||||
if (funcOff >= 0)
|
||||
{
|
||||
castSpellOff = off;
|
||||
castSpellFuncOff = funcOff;
|
||||
RynthLog.Compat($"Compat: CastSpell candidate opcode=0x{candidate[2]:X2} matched at text+0x{off:X}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (changeModeFuncOff < 0 || queryHealthFuncOff < 0 || meleeFuncOff < 0 || missileFuncOff < 0)
|
||||
{
|
||||
_statusMessage =
|
||||
$"Incomplete. mode={changeModeFuncOff >= 0}, health={queryHealthFuncOff >= 0}, melee={meleeFuncOff >= 0}, missile={missileFuncOff >= 0}.";
|
||||
RynthLog.Compat($"Compat: combat probe incomplete - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!PatternScanner.VerifyBytes(text, cancelFuncOff, CombatPrologue) ||
|
||||
!PatternScanner.VerifyBytes(text, changeModeFuncOff, CombatPrologue) ||
|
||||
!PatternScanner.VerifyBytes(text, queryHealthFuncOff, CombatPrologue) ||
|
||||
!PatternScanner.VerifyBytes(text, meleeFuncOff, CombatPrologue) ||
|
||||
!PatternScanner.VerifyBytes(text, missileFuncOff, CombatPrologue))
|
||||
{
|
||||
_statusMessage = "Prologue verification failed.";
|
||||
RynthLog.Compat("Compat: combat probe failed - prologue verification failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int cancelVa = textSection.TextBaseVa + cancelFuncOff;
|
||||
int changeModeVa = textSection.TextBaseVa + changeModeFuncOff;
|
||||
int queryHealthVa = textSection.TextBaseVa + queryHealthFuncOff;
|
||||
int meleeVa = textSection.TextBaseVa + meleeFuncOff;
|
||||
int missileVa = textSection.TextBaseVa + missileFuncOff;
|
||||
|
||||
_cancelAttack = Marshal.GetDelegateForFunctionPointer<CancelAttackDelegate>(new IntPtr(cancelVa));
|
||||
_changeCombatMode = Marshal.GetDelegateForFunctionPointer<ChangeCombatModeDelegate>(new IntPtr(changeModeVa));
|
||||
_queryHealth = Marshal.GetDelegateForFunctionPointer<QueryHealthDelegate>(new IntPtr(queryHealthVa));
|
||||
_meleeAttack = Marshal.GetDelegateForFunctionPointer<TargetedMeleeAttackDelegate>(new IntPtr(meleeVa));
|
||||
_missileAttack = Marshal.GetDelegateForFunctionPointer<TargetedMissileAttackDelegate>(new IntPtr(missileVa));
|
||||
|
||||
if (requestIdFuncOff >= 0)
|
||||
{
|
||||
int requestIdVa = textSection.TextBaseVa + requestIdFuncOff;
|
||||
_requestId = Marshal.GetDelegateForFunctionPointer<RequestIdDelegate>(new IntPtr(requestIdVa));
|
||||
RynthLog.Compat($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: RequestId (IdentifyObject 0xC8) not found — target appraisal unavailable.");
|
||||
}
|
||||
|
||||
if (castSpellFuncOff >= 0)
|
||||
{
|
||||
int castSpellVa = textSection.TextBaseVa + castSpellFuncOff;
|
||||
_castSpell = Marshal.GetDelegateForFunctionPointer<CastSpellDelegate>(new IntPtr(castSpellVa));
|
||||
RynthLog.Compat($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: CastSpell (0x4A) not found — magic combat unavailable.");
|
||||
}
|
||||
|
||||
InstallQueryHealthResponseHook();
|
||||
InstallInnerDispatcherHook();
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
|
||||
RynthLog.Compat($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: combat probe failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
|
||||
{
|
||||
if (_meleeAttack == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _meleeAttack(targetId, attackHeight, Math.Clamp(powerLevel, 0f, 1f));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
|
||||
{
|
||||
if (_missileAttack == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _missileAttack(targetId, attackHeight, Math.Clamp(accuracyLevel, 0f, 1f));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ChangeCombatMode(int combatMode)
|
||||
{
|
||||
if (_changeCombatMode == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _changeCombatMode(combatMode);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CancelAttack()
|
||||
{
|
||||
if (_cancelAttack == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _cancelAttack();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool QueryHealth(uint targetId)
|
||||
{
|
||||
if (_queryHealth == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _queryHealth(targetId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool RequestId(uint objectId)
|
||||
{
|
||||
if (_requestId == null || objectId == 0)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _requestId(objectId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CastSpell(uint targetId, int spellId)
|
||||
{
|
||||
if (_castSpell == null || targetId == 0 || spellId <= 0)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _castSpell(targetId, spellId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static int MapAttackHeight(int uiHeight)
|
||||
{
|
||||
return uiHeight switch
|
||||
{
|
||||
0 => AttackHeightLow,
|
||||
2 => AttackHeightHigh,
|
||||
_ => AttackHeightMedium
|
||||
};
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
_meleeAttack = null;
|
||||
_missileAttack = null;
|
||||
_changeCombatMode = null;
|
||||
_cancelAttack = null;
|
||||
_queryHealth = null;
|
||||
_requestId = null;
|
||||
_castSpell = null;
|
||||
_queryHealthResponseDetour = null;
|
||||
_originalQueryHealthResponse = null;
|
||||
_identifyObjectDetour = null;
|
||||
_originalIdentifyObject = null;
|
||||
IsInitialized = false;
|
||||
}
|
||||
|
||||
/// Hooks the inner game-event dispatcher at its entry point. The dispatcher is thiscall
|
||||
/// with RET 8: uint __thiscall Dispatch(void* buffer, uint size). We intercept 0xC9
|
||||
/// (IdentifyObject response) events and parse the CreatureProfile for health/maxHealth.
|
||||
/// </summary>
|
||||
private static IntPtr _originalInnerDispatcherPtr;
|
||||
|
||||
private static void InstallInnerDispatcherHook()
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
return;
|
||||
|
||||
byte[] text = textSection.Bytes;
|
||||
int textBase = textSection.TextBaseVa;
|
||||
|
||||
// Find the call to QueryHealthResponse to anchor the inner dispatcher region
|
||||
int anchorOff = -1;
|
||||
for (int i = 0; i < text.Length - 5; i++)
|
||||
{
|
||||
if (text[i] != 0xE8) continue;
|
||||
int rel = BitConverter.ToInt32(text, i + 1);
|
||||
if (textBase + i + 5 + rel == QueryHealthResponseVa)
|
||||
{
|
||||
anchorOff = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (anchorOff < 0)
|
||||
{
|
||||
RynthLog.Compat("Compat: dispatch scan - no CALL to QueryHealthResponse found.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the inner dispatcher function entry by searching backward for SUB ESP, 0x1C0
|
||||
int subEspOff = -1;
|
||||
for (int i = anchorOff; i >= Math.Max(0, anchorOff - 0x1000); i--)
|
||||
{
|
||||
if (text[i] == 0x81 && text[i + 1] == 0xEC &&
|
||||
text[i + 2] == 0xC0 && text[i + 3] == 0x01 &&
|
||||
text[i + 4] == 0x00 && text[i + 5] == 0x00)
|
||||
{
|
||||
subEspOff = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (subEspOff < 0)
|
||||
{
|
||||
RynthLog.Compat("Compat: inner dispatcher SUB ESP not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
int funcEntryVa = textBase + subEspOff;
|
||||
RynthLog.Compat($"Compat: inner dispatcher entry @ 0x{funcEntryVa:X8}");
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint> pDetour = &InnerDispatcherDetour;
|
||||
MinHook.Hook(new IntPtr(funcEntryVa), (IntPtr)pDetour, out _originalInnerDispatcherPtr);
|
||||
RynthLog.Compat($"Compat: inner dispatcher hook installed @ 0x{funcEntryVa:X8}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: inner dispatcher hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static unsafe uint InnerDispatcherDetour(IntPtr thisPtr, IntPtr buffer, uint size)
|
||||
{
|
||||
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint>)_originalInnerDispatcherPtr;
|
||||
|
||||
try
|
||||
{
|
||||
if (buffer != IntPtr.Zero && size >= 4)
|
||||
{
|
||||
uint eventType = unchecked((uint)Marshal.ReadInt32(buffer));
|
||||
|
||||
// Intercept IdentifyObject response (0xC9)
|
||||
if (eventType == 0xC9 && size >= 16)
|
||||
TryParseIdentifyResponse(buffer, size);
|
||||
|
||||
// Intercept character list packet (0xF658) — login screen
|
||||
if (eventType == 0xF7EA || eventType == 0xF658)
|
||||
CharacterCaptureHooks.ProcessRawCharacterMessage(buffer, size);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
return pOriginal(thisPtr, buffer, size);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the IdentifyObject response (game event 0xC9) to extract health/maxHealth
|
||||
/// from the CreatureProfile section.
|
||||
/// Layout: [eventType(4)][objectId(4)][flags(4)][success(4)][sections based on flags...]
|
||||
/// Wire serialization order (matches ACE, NOT flag-bit order):
|
||||
/// 0x0001 IntStatsTable, 0x1000 Int64StatsTable, 0x0002 BoolStatsTable,
|
||||
/// 0x0004 FloatStatsTable, 0x0008 StringStatsTable, 0x0010 SpellBook,
|
||||
/// 0x0020 ArmorProfile, 0x0040 CreatureProfile, 0x0080 WeaponProfile,
|
||||
/// 0x0100 HookProfile, ...
|
||||
/// </summary>
|
||||
private static void TryParseIdentifyResponse(IntPtr buffer, uint size)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Header: eventType(4) + objectId(4) + flags(4) + success(4) = 16 bytes
|
||||
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
|
||||
uint flags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 8)));
|
||||
uint success = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 12)));
|
||||
|
||||
if (success == 0 || objectId == 0)
|
||||
return;
|
||||
|
||||
// CreatureProfile = flag 0x1000 in the retail client
|
||||
if ((flags & 0x1000) == 0)
|
||||
return;
|
||||
|
||||
int offset = 16; // Past the header
|
||||
int iSize = (int)size;
|
||||
|
||||
// Skip sections in wire order before CreatureProfile (0x1000):
|
||||
// 0x0001 - IntStatsTable: PHashTable<uint,int> = header(4) + count*8
|
||||
if ((flags & 0x0001) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0002 - BoolStatsTable: PHashTable<uint,int> = header(4) + count*8
|
||||
if ((flags & 0x0002) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0004 - FloatStatsTable: PHashTable<uint,double> = header(4) + count*12
|
||||
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
|
||||
return;
|
||||
// 0x0008 - StringStatsTable: PHashTable<uint,string> — variable
|
||||
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
|
||||
return;
|
||||
// 0x0010 - SpellBook: header(4) + count*4
|
||||
if ((flags & 0x0010) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 4))
|
||||
return;
|
||||
// 0x0020, 0x0040, 0x0080 — unknown fixed sections; bail if present
|
||||
if ((flags & 0x00E0) != 0)
|
||||
return;
|
||||
// 0x0100 - Int64StatsTable: PHashTable<uint,int32> = header(4) + count*8
|
||||
// (retail client serialises "Int64" properties as 32-bit values)
|
||||
if ((flags & 0x0100) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0200, 0x0400, 0x0800 — unknown sections; bail if present
|
||||
if ((flags & 0x0E00) != 0)
|
||||
return;
|
||||
|
||||
// 0x1000 - CreatureProfile layout:
|
||||
// flags(4), health(4), maxHealth(4),
|
||||
// strength(4), endurance(4), quickness(4), coordination(4), focus(4), self(4),
|
||||
// stamina(4), maxStamina(4), mana(4), maxMana(4)
|
||||
// Total: 4 + 12*4 = 52 bytes
|
||||
if (offset + 52 > iSize)
|
||||
return;
|
||||
|
||||
// Skip the 4-byte CreatureProfile header/flags
|
||||
offset += 4;
|
||||
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
|
||||
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
|
||||
// Skip 6 primary attributes (str, end, quick, coord, focus, self) = 24 bytes
|
||||
// Layout: stamina(4), mana(4), maxStamina(4), maxMana(4)
|
||||
uint stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 32)));
|
||||
uint mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
|
||||
uint maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
|
||||
uint maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
|
||||
|
||||
if (maxHealth > 0 && maxHealth < 1_000_000 && objectId != 0)
|
||||
{
|
||||
var vitals = new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana);
|
||||
ObjectQualityCache.SetCreatureVitals(objectId, vitals);
|
||||
|
||||
if (ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr pWeenie) && pWeenie != IntPtr.Zero)
|
||||
ObjectQualityCache.SetMaxHealth(pWeenie, maxHealth);
|
||||
|
||||
float ratio = maxHealth > 0 ? (float)health / maxHealth : 0f;
|
||||
PluginManager.QueueUpdateHealth(objectId, ratio, health, maxHealth);
|
||||
|
||||
// If this is the player, seed exact max vitals
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId != 0 && objectId == playerId)
|
||||
PlayerVitalsHooks.SeedMaxVitalsFromIdentify(maxHealth, maxStamina, maxMana);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Skips a packed hash table with fixed-size entries.</summary>
|
||||
private static bool SkipPackedHashTable(IntPtr buffer, int size, ref int offset, int entrySize)
|
||||
{
|
||||
if (offset + 4 > size) return false;
|
||||
ushort entryCount = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
|
||||
offset += 4; // header: count(2) + buckets(2)
|
||||
int dataSize = entryCount * entrySize;
|
||||
offset += dataSize;
|
||||
return offset <= size;
|
||||
}
|
||||
|
||||
/// <summary>Skips a packed hash table with string values (variable length).</summary>
|
||||
private static bool SkipStringHashTable(IntPtr buffer, int size, ref int offset)
|
||||
{
|
||||
if (offset + 4 > size) return false;
|
||||
ushort entryCount = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
|
||||
offset += 4; // header
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
if (offset + 6 > size) return false;
|
||||
offset += 4; // key (uint32)
|
||||
// AC packed string: ushort length, then chars, then padding to 4-byte boundary
|
||||
ushort strLen = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
|
||||
offset += 2;
|
||||
offset += strLen;
|
||||
// Align to 4-byte boundary (from the start of the string field, which is offset-2-strLen)
|
||||
int totalStringField = 2 + strLen;
|
||||
int padding = (4 - (totalStringField % 4)) % 4;
|
||||
offset += padding;
|
||||
}
|
||||
return offset <= size;
|
||||
}
|
||||
|
||||
private static void InstallQueryHealthResponseHook()
|
||||
{
|
||||
if (_originalQueryHealthResponse != null)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
return;
|
||||
|
||||
IntPtr responsePtr = new(QueryHealthResponseVa);
|
||||
int textStart = textSection.TextBaseVa;
|
||||
int textEnd = textStart + textSection.Bytes.Length;
|
||||
int responseVa = responsePtr.ToInt32();
|
||||
if (responseVa < textStart || responseVa >= textEnd)
|
||||
{
|
||||
RynthLog.Compat($"Compat: query-health-response hook skipped - invalid address 0x{QueryHealthResponseVa:X8}");
|
||||
return;
|
||||
}
|
||||
|
||||
_queryHealthResponseDetour = QueryHealthResponseDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_queryHealthResponseDetour);
|
||||
IntPtr originalPtr = MinHook.HookCreate(responsePtr, detourPtr);
|
||||
_originalQueryHealthResponse = Marshal.GetDelegateForFunctionPointer<QueryHealthResponseDelegate>(originalPtr);
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(responsePtr);
|
||||
RynthLog.Compat($"Compat: query-health-response hook ready - Handle_Combat__QueryHealthResponse=0x{QueryHealthResponseVa:X8}");
|
||||
}
|
||||
|
||||
private static uint QueryHealthResponseDetour(IntPtr uiQueueManager, IntPtr buffer, uint size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (buffer != IntPtr.Zero && size >= 12)
|
||||
{
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(buffer));
|
||||
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
|
||||
float healthRatio = Marshal.PtrToStructure<float>(IntPtr.Add(buffer, 8));
|
||||
|
||||
// Resolve absolute health: first check the cache, then try a direct
|
||||
// read via InqAttribute2ndStruct (works after an IdentifyObject response
|
||||
// has populated the weenie's qualities). This detour runs on the game
|
||||
// thread so the direct read is safe.
|
||||
uint maxHealth = 0;
|
||||
uint currentHealth = 0;
|
||||
if (ClientObjectHooks.TryGetWeenieObjectPtr(targetId, out IntPtr pWeenie))
|
||||
{
|
||||
if (ObjectQualityCache.TryGetMaxHealth(pWeenie, out uint cached))
|
||||
{
|
||||
maxHealth = cached;
|
||||
}
|
||||
else if (PlayerVitalsHooks.TryReadObjectMaxHealth(pWeenie, out uint queried) && queried > 0)
|
||||
{
|
||||
maxHealth = queried;
|
||||
ObjectQualityCache.SetMaxHealth(pWeenie, queried);
|
||||
}
|
||||
|
||||
if (maxHealth > 0)
|
||||
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
|
||||
}
|
||||
|
||||
// If this response is for the player, derive true MaxHealth from the ratio.
|
||||
// e.g. health=92541, ratio=0.925 → trueMax ≈ 99999
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f)
|
||||
PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio);
|
||||
|
||||
PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
return _originalQueryHealthResponse != null
|
||||
? _originalQueryHealthResponse(uiQueueManager, buffer, size)
|
||||
: 0;
|
||||
}
|
||||
|
||||
}
|
||||
115
src/RynthCore.Engine/Compatibility/CombatModeHooks.cs
Normal file
115
src/RynthCore.Engine/Compatibility/CombatModeHooks.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CombatModeHooks
|
||||
{
|
||||
private const int SetCombatModeVa = 0x0056CB80;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SetCombatModeDelegate(IntPtr thisPtr, int newCombatMode, int playerRequested);
|
||||
|
||||
private static SetCombatModeDelegate? _originalSetCombatMode;
|
||||
private static SetCombatModeDelegate? _setCombatModeDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _lastObservedCombatMode;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = SetCombatModeVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
|
||||
{
|
||||
_statusMessage = $"ClientCombatSystem::SetCombatMode VA out of range @ 0x{SetCombatModeVa:X8}.";
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
byte firstByte = textSection.Bytes[funcOff];
|
||||
if (firstByte is 0x00 or 0xCC or 0xC3)
|
||||
{
|
||||
_statusMessage = $"ClientCombatSystem::SetCombatMode looks invalid @ 0x{SetCombatModeVa:X8} (opcode 0x{firstByte:X2}).";
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_setCombatModeDetour = SetCombatModeDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setCombatModeDetour);
|
||||
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked ClientCombatSystem::SetCombatMode @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat($"Compat: combat-mode hook ready - SetCombatMode=0x{_targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetCombatModeDetour(IntPtr thisPtr, int newCombatMode, int playerRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
_originalSetCombatMode!(thisPtr, newCombatMode, playerRequested);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: combat-mode detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
throw;
|
||||
}
|
||||
|
||||
int currentCombatMode = NormalizeCombatMode(newCombatMode);
|
||||
int previousCombatMode = Interlocked.Exchange(ref _lastObservedCombatMode, currentCombatMode);
|
||||
if (currentCombatMode == previousCombatMode)
|
||||
return;
|
||||
|
||||
PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode);
|
||||
}
|
||||
|
||||
private static int NormalizeCombatMode(int combatMode)
|
||||
{
|
||||
return combatMode switch
|
||||
{
|
||||
CombatActionHooks.CombatModeNonCombat => CombatActionHooks.CombatModeNonCombat,
|
||||
CombatActionHooks.CombatModeMelee => CombatActionHooks.CombatModeMelee,
|
||||
CombatActionHooks.CombatModeMissile => CombatActionHooks.CombatModeMissile,
|
||||
CombatActionHooks.CombatModeMagic => CombatActionHooks.CombatModeMagic,
|
||||
_ => combatMode
|
||||
};
|
||||
}
|
||||
|
||||
private static string FormatCombatMode(int combatMode)
|
||||
{
|
||||
return combatMode switch
|
||||
{
|
||||
CombatActionHooks.CombatModeNonCombat => "noncombat(1)",
|
||||
CombatActionHooks.CombatModeMelee => "melee(2)",
|
||||
CombatActionHooks.CombatModeMissile => "missile(4)",
|
||||
CombatActionHooks.CombatModeMagic => "magic(8)",
|
||||
_ => combatMode.ToString()
|
||||
};
|
||||
}
|
||||
}
|
||||
302
src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs
Normal file
302
src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CommandInterpreterHooks
|
||||
{
|
||||
private const int VtblCommenceJumpIndex = 16;
|
||||
private const int VtblDoJumpIndex = 17;
|
||||
private const int VtblSetAutoRunIndex = 51;
|
||||
private const int ReferenceAccCmdInterpCommenceJump = 0x0058BFD0;
|
||||
private const int ReferenceAccCmdInterpDoJump = 0x0058BFF0;
|
||||
private const int ReferenceAccCmdInterpSetMotion = 0x0058C140;
|
||||
private const int ReferenceCommandInterpreterSetAutoRun = 0x006B5790;
|
||||
private const int ReferenceCommandInterpreterStopCompletely = 0x006B4A90;
|
||||
private const int ReferenceCommandInterpreterTurnToHeading = 0x006B54B0;
|
||||
private const int SetMotionOffsetFromCommenceJump = ReferenceAccCmdInterpSetMotion - ReferenceAccCmdInterpCommenceJump;
|
||||
private const int SetMotionOffsetFromDoJump = ReferenceAccCmdInterpSetMotion - ReferenceAccCmdInterpDoJump;
|
||||
private const int StopCompletelyOffsetFromSetAutoRun = ReferenceCommandInterpreterStopCompletely - ReferenceCommandInterpreterSetAutoRun;
|
||||
private const int TurnToHeadingOffsetFromSetAutoRun = ReferenceCommandInterpreterTurnToHeading - ReferenceCommandInterpreterSetAutoRun;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void CommenceJumpDelegate(IntPtr thisPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void DoJumpDelegate(IntPtr thisPtr, int autonomous);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SetAutoRunDelegate(IntPtr thisPtr, int val, int applyMovement);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SetMotionDelegate(IntPtr thisPtr, uint motion, int enabled);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void StopCompletelyDelegate(IntPtr thisPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void TurnToHeadingDelegate(IntPtr thisPtr, float headingDegrees);
|
||||
|
||||
private static IntPtr _smartboxStaticAddr;
|
||||
private static IntPtr _boundCmdInterp;
|
||||
private static CommenceJumpDelegate? _commenceJump;
|
||||
private static DoJumpDelegate? _doJump;
|
||||
private static SetAutoRunDelegate? _setAutoRun;
|
||||
private static SetMotionDelegate? _setMotion;
|
||||
private static StopCompletelyDelegate? _stopCompletely;
|
||||
private static TurnToHeadingDelegate? _turnToHeading;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
public static bool HasTapJump => _commenceJump != null && _doJump != null;
|
||||
public static bool HasSetAutoRun => _setAutoRun != null;
|
||||
public static bool HasSetMotion => _setMotion != null;
|
||||
public static bool HasStopCompletely => _stopCompletely != null;
|
||||
public static bool HasTurnToHeading => _turnToHeading != null;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
Reset();
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out _))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!SmartBoxLocator.Probe())
|
||||
{
|
||||
_statusMessage = SmartBoxLocator.StatusMessage;
|
||||
return false;
|
||||
}
|
||||
|
||||
RynthLog.Compat($"Compat: command interpreter found {SmartBoxLocator.CandidateCount} SmartBox candidate(s).");
|
||||
|
||||
if (!TryBindDelegates())
|
||||
{
|
||||
if (string.IsNullOrEmpty(_statusMessage))
|
||||
_statusMessage = "cmdinterp unavailable.";
|
||||
|
||||
RynthLog.Compat($"Compat: command interpreter probe pending - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
RynthLog.Compat($"Compat: command interpreter hooks ready - smartbox=0x{_smartboxStaticAddr.ToInt32():X8}, cmdinterp=0x{_boundCmdInterp.ToInt32():X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: command interpreter probe failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetAutoRun(bool enabled)
|
||||
{
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
if (!TryBindDelegates() || _setMotion == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_setMotion(_boundCmdInterp, motion, enabled ? 1 : 0);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool StopCompletely()
|
||||
{
|
||||
if (!TryBindDelegates() || _stopCompletely == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_stopCompletely(_boundCmdInterp);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TurnToHeading(float headingDegrees)
|
||||
{
|
||||
if (!TryBindDelegates() || _turnToHeading == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_turnToHeading(_boundCmdInterp, headingDegrees);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TapJump()
|
||||
{
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Mirror the normal keyboard jump path: key-down starts charge,
|
||||
// key-up immediately executes an autonomous tap jump.
|
||||
_commenceJump!(_boundCmdInterp);
|
||||
_doJump!(_boundCmdInterp, 1);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryBindDelegates()
|
||||
{
|
||||
IntPtr selectedStaticAddr = IntPtr.Zero;
|
||||
IntPtr smartBox = IntPtr.Zero;
|
||||
IntPtr cmdInterp = IntPtr.Zero;
|
||||
IntPtr vtable = IntPtr.Zero;
|
||||
|
||||
if (!SmartBoxLocator.TryGetSmartBox(out smartBox, out selectedStaticAddr, out string smartBoxFailure))
|
||||
{
|
||||
_statusMessage = smartBoxFailure;
|
||||
RynthLog.Compat($"Compat: command interpreter bind pending - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
cmdInterp = Marshal.ReadIntPtr(smartBox + SmartBoxLocator.SmartBoxCmdInterpOffset);
|
||||
if (cmdInterp == IntPtr.Zero)
|
||||
{
|
||||
uint playerId = unchecked((uint)Marshal.ReadInt32(smartBox + SmartBoxLocator.SmartBoxPlayerIdOffset));
|
||||
IntPtr player = Marshal.ReadIntPtr(smartBox + SmartBoxLocator.SmartBoxPlayerOffset);
|
||||
_statusMessage = playerId != 0 || player != IntPtr.Zero
|
||||
? $"CommandInterpreter not ready (playerId=0x{playerId:X8}, player=0x{player.ToInt32():X8})."
|
||||
: "SmartBox active but player not ready.";
|
||||
RynthLog.Compat($"Compat: command interpreter bind pending - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
vtable = Marshal.ReadIntPtr(cmdInterp);
|
||||
if (!SmartBoxLocator.IsPointerInModule(vtable))
|
||||
{
|
||||
_statusMessage = $"CommandInterpreter vtable looks invalid (0x{vtable.ToInt32():X8}).";
|
||||
RynthLog.Compat($"Compat: command interpreter bind failed - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: command interpreter bind pending - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cmdInterp == _boundCmdInterp &&
|
||||
_commenceJump != null &&
|
||||
_doJump != null &&
|
||||
_setAutoRun != null &&
|
||||
_setMotion != null &&
|
||||
_stopCompletely != null &&
|
||||
_turnToHeading != null)
|
||||
{
|
||||
_smartboxStaticAddr = selectedStaticAddr;
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
|
||||
IntPtr commenceJumpPtr = Marshal.ReadIntPtr(vtable, VtblCommenceJumpIndex * IntPtr.Size);
|
||||
IntPtr doJumpPtr = Marshal.ReadIntPtr(vtable, VtblDoJumpIndex * IntPtr.Size);
|
||||
IntPtr setAutoRunPtr = Marshal.ReadIntPtr(vtable, VtblSetAutoRunIndex * IntPtr.Size);
|
||||
IntPtr setMotionPtr = ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
|
||||
IntPtr stopCompletelyPtr = AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
|
||||
IntPtr turnToHeadingPtr = AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
|
||||
|
||||
if (!SmartBoxLocator.IsPointerInModule(commenceJumpPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(doJumpPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(setAutoRunPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(setMotionPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(stopCompletelyPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(turnToHeadingPtr))
|
||||
{
|
||||
_statusMessage =
|
||||
$"CommandInterpreter pointers look invalid (commence=0x{commenceJumpPtr.ToInt32():X8}, doJump=0x{doJumpPtr.ToInt32():X8}, autorun=0x{setAutoRunPtr.ToInt32():X8}, setMotion=0x{setMotionPtr.ToInt32():X8}, stop=0x{stopCompletelyPtr.ToInt32():X8}, turn=0x{turnToHeadingPtr.ToInt32():X8}).";
|
||||
RynthLog.Compat($"Compat: command interpreter bind failed - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_commenceJump = Marshal.GetDelegateForFunctionPointer<CommenceJumpDelegate>(commenceJumpPtr);
|
||||
_doJump = Marshal.GetDelegateForFunctionPointer<DoJumpDelegate>(doJumpPtr);
|
||||
_setAutoRun = Marshal.GetDelegateForFunctionPointer<SetAutoRunDelegate>(setAutoRunPtr);
|
||||
_setMotion = Marshal.GetDelegateForFunctionPointer<SetMotionDelegate>(setMotionPtr);
|
||||
_stopCompletely = Marshal.GetDelegateForFunctionPointer<StopCompletelyDelegate>(stopCompletelyPtr);
|
||||
_turnToHeading = Marshal.GetDelegateForFunctionPointer<TurnToHeadingDelegate>(turnToHeadingPtr);
|
||||
|
||||
_smartboxStaticAddr = selectedStaticAddr;
|
||||
_boundCmdInterp = cmdInterp;
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
RynthLog.Compat(
|
||||
$"Compat: command interpreter bound - smartboxStatic=0x{selectedStaticAddr.ToInt32():X8}, smartbox=0x{smartBox.ToInt32():X8}, cmdinterp=0x{cmdInterp.ToInt32():X8}, setMotion=0x{setMotionPtr.ToInt32():X8}, stop=0x{stopCompletelyPtr.ToInt32():X8}, turn=0x{turnToHeadingPtr.ToInt32():X8}, autorun=0x{setAutoRunPtr.ToInt32():X8}");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IntPtr ResolveSetMotionPointer(IntPtr commenceJumpPtr, IntPtr doJumpPtr)
|
||||
{
|
||||
IntPtr fromCommenceJump = AddOffset(commenceJumpPtr, SetMotionOffsetFromCommenceJump);
|
||||
IntPtr fromDoJump = AddOffset(doJumpPtr, SetMotionOffsetFromDoJump);
|
||||
return fromCommenceJump == fromDoJump ? fromCommenceJump : IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static IntPtr AddOffset(IntPtr address, int offset)
|
||||
{
|
||||
return new IntPtr(address.ToInt64() + offset);
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
_smartboxStaticAddr = IntPtr.Zero;
|
||||
_boundCmdInterp = IntPtr.Zero;
|
||||
_commenceJump = null;
|
||||
_doJump = null;
|
||||
_setAutoRun = null;
|
||||
_setMotion = null;
|
||||
_stopCompletely = null;
|
||||
_turnToHeading = null;
|
||||
IsInitialized = false;
|
||||
_statusMessage = "Not probed yet.";
|
||||
}
|
||||
}
|
||||
84
src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs
Normal file
84
src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CreateObjectHooks
|
||||
{
|
||||
private const int CreateObjectVa = 0x005594B0;
|
||||
private static readonly byte[] CreateObjectSignature =
|
||||
[
|
||||
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1,
|
||||
0x8B, 0x8E, 0x8C, 0x00, 0x00, 0x00, 0x8B, 0x96,
|
||||
0x88, 0x00, 0x00, 0x00, 0x8B, 0xC5, 0xD3, 0xE8,
|
||||
0x8B, 0x8E, 0x90, 0x00, 0x00, 0x00, 0x33, 0xC5
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate IntPtr CreateObjectDelegate(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc);
|
||||
|
||||
private static CreateObjectDelegate? _originalCreateObject;
|
||||
private static CreateObjectDelegate? _createObjectDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _dispatchCount;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = CreateObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, CreateObjectSignature))
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::CreateObject signature mismatch @ 0x{CreateObjectVa:X8}.";
|
||||
RynthLog.Compat($"Compat: create-object hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_createObjectDetour = CreateObjectDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createObjectDetour);
|
||||
_originalCreateObject = Marshal.GetDelegateForFunctionPointer<CreateObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked ACCObjectMaint::CreateObject @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat($"Compat: create-object hook ready - CreateObject=0x{_targetAddress.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: create-object hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr CreateObjectDetour(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc)
|
||||
{
|
||||
IntPtr result = _originalCreateObject!(thisPtr, objectId, visualDesc, physicsDesc, weenieDesc);
|
||||
if (result == IntPtr.Zero || objectId == 0)
|
||||
return result;
|
||||
|
||||
int count = Interlocked.Increment(ref _dispatchCount);
|
||||
if (count <= 0)
|
||||
RynthLog.Compat($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
|
||||
|
||||
PluginManager.QueueCreateObject(objectId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
77
src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs
Normal file
77
src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class DeleteObjectHooks
|
||||
{
|
||||
private const int DeleteObjectVa = 0x00558330;
|
||||
private static readonly byte[] DeleteObjectSignature =
|
||||
[
|
||||
0x56, 0x57, 0x8B, 0xF9, 0xE8, 0x67, 0x2D, 0x00,
|
||||
0x00, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C, 0x74,
|
||||
0x0C, 0xE8, 0xFA, 0x23, 0x00, 0x00, 0x8B, 0x08,
|
||||
0x56, 0x50, 0xFF, 0x51, 0x24, 0x56, 0xE8
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate int DeleteObjectDelegate(IntPtr thisPtr, uint objectId);
|
||||
|
||||
private static DeleteObjectDelegate? _originalDeleteObject;
|
||||
private static DeleteObjectDelegate? _deleteObjectDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = DeleteObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DeleteObjectSignature))
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::DeleteObject signature mismatch @ 0x{DeleteObjectVa:X8}.";
|
||||
RynthLog.Compat($"Compat: delete-object hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_deleteObjectDetour = DeleteObjectDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_deleteObjectDetour);
|
||||
_originalDeleteObject = Marshal.GetDelegateForFunctionPointer<DeleteObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked ACCObjectMaint::DeleteObject @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat($"Compat: delete-object hook ready - DeleteObject=0x{_targetAddress.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: delete-object hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
|
||||
{
|
||||
if (objectId != 0)
|
||||
PluginManager.QueueDeleteObject(objectId);
|
||||
|
||||
return _originalDeleteObject!(thisPtr, objectId);
|
||||
}
|
||||
}
|
||||
196
src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs
Normal file
196
src/RynthCore.Engine/Compatibility/EnchantmentHooks.cs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the player's active spell enchantments from the CEnchantmentRegistry.
|
||||
///
|
||||
/// Hookless approach: reads the registry directly from the player's CACQualities struct.
|
||||
///
|
||||
/// Path: PlayerVitalsHooks.KnownPlayerQualitiesPtr → CACQualities+0x70 → CEnchantmentRegistry*
|
||||
/// Offset 0x70 confirmed by disassembling CACQualities::EnchantAttribute2nd (0x0058FEC0):
|
||||
/// 8B 49 70 = mov ecx, [ecx+0x70] ; reads _enchantment_reg from this (CACQualities*)
|
||||
///
|
||||
/// CEnchantmentRegistry layout (from Chorizite + PDB):
|
||||
/// +0 PackObj (vtable, 4 bytes)
|
||||
/// +4 PackableList<Enchantment>* _mult_list
|
||||
/// +8 PackableList<Enchantment>* _add_list
|
||||
/// +12 PackableList<Enchantment>* _cooldown_list
|
||||
/// +16 Enchantment* _vitae
|
||||
/// +20 uint m_cHelpfulEnchantments
|
||||
/// +24 uint m_cHarmfulEnchantments
|
||||
///
|
||||
/// Enchantment struct (sizeof=72, pack 4):
|
||||
/// +0 PackObj (vtable) +4 _id (uint)
|
||||
/// +8 m_SpellSetID +12 _spell_category
|
||||
/// +16 _power_level +20 _start_time (double)
|
||||
/// +28 _duration (double) +36 _caster (uint)
|
||||
/// +40 _degrade_modifier +44 _degrade_limit
|
||||
/// +48 _last_time_degraded +56 StatMod(16 bytes)
|
||||
///
|
||||
/// PackableLLNode<Enchantment>: data(72) + next*(4) + prev*(4)
|
||||
/// </summary>
|
||||
internal static class EnchantmentHooks
|
||||
{
|
||||
// Offset of _enchantment_reg within CACQualities
|
||||
// Confirmed by disassembly: mov ecx, [ecx+0x70] at 0x0058FEC0
|
||||
private const int QualitiesRegistryOffset = 0x70;
|
||||
|
||||
// CEnchantmentRegistry offsets
|
||||
private const int RegistryMultListOffset = 4;
|
||||
private const int RegistryAddListOffset = 8;
|
||||
private const int RegistryCooldownListOffset = 12;
|
||||
|
||||
// PackableList<Enchantment>: +0=vtable, +4=head, +8=tail, +12=curNum
|
||||
private const int ListHeadOffset = 4;
|
||||
|
||||
// Enchantment fields within each PackableLLNode
|
||||
// MSVC x86 pack(8): doubles are 8-byte aligned, inserting 4 bytes padding after _power_level
|
||||
private const int EnchantmentIdOffset = 4; // _id (uint)
|
||||
private const int EnchantmentStartTimeOffset = 24; // _start_time (double) — padded from +20 to +24
|
||||
private const int EnchantmentDurationOffset = 32; // _duration (double)
|
||||
// sizeof(Enchantment) = 80 with MSVC padding; PackableLLNode has next* and prev* after data
|
||||
private const int NodeNextOffset = 80; // next*
|
||||
|
||||
private static bool _initialized;
|
||||
private static bool _loggedFirstRead;
|
||||
|
||||
public static bool IsInitialized => _initialized;
|
||||
|
||||
public static bool Initialize()
|
||||
{
|
||||
if (_initialized) return true;
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Compat("Compat: enchantment reader ready (hookless, CACQualities+0x70)");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads active enchantments from the player's CEnchantmentRegistry.
|
||||
/// Returns count written, 0 if no enchantments, -1 if player qualities not available.
|
||||
/// Expiry times are server-time seconds (subtract current server time for remaining).
|
||||
/// </summary>
|
||||
public static unsafe int ReadPlayerEnchantments(uint* spellIds, double* expiryTimes, int maxCount)
|
||||
{
|
||||
if (maxCount <= 0) return 0;
|
||||
|
||||
// Get player's CACQualities pointer (set by login hooks)
|
||||
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
|
||||
if (qualPtr == IntPtr.Zero) return -1;
|
||||
|
||||
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
|
||||
|
||||
if (!_loggedFirstRead && count > 0)
|
||||
{
|
||||
_loggedFirstRead = true;
|
||||
RynthLog.Compat($"[EnchRead] first player read: {count} enchantments");
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads active enchantments from any game object's CEnchantmentRegistry.
|
||||
/// Path: GetWeenieObject(objectId) → weenie+qualitiesOffset → CACQualities+0x70.
|
||||
/// Returns count written, 0 if no enchantments, -1 if object not found or has no registry.
|
||||
///
|
||||
/// Uses VirtualQuery to validate every pointer before dereferencing — critical because
|
||||
/// AccessViolationException cannot be caught in NativeAOT/.NET 5+.
|
||||
/// </summary>
|
||||
public static unsafe int ReadObjectEnchantments(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
|
||||
{
|
||||
if (maxCount <= 0) return 0;
|
||||
|
||||
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr))
|
||||
return -1;
|
||||
|
||||
// Navigate weenie → CACQualities via the probed/fallback offset
|
||||
IntPtr qualAddr = weeniePtr + ClientObjectHooks.WeenieQualitiesOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(qualAddr, 4))
|
||||
return -1;
|
||||
IntPtr qualPtr = Marshal.ReadIntPtr(qualAddr);
|
||||
if (qualPtr == IntPtr.Zero) return -1;
|
||||
|
||||
// Validate: CACQualities inherits PackObj → vtable must point into acclient.exe.
|
||||
if (!SmartBoxLocator.IsMemoryReadable(qualPtr, 4))
|
||||
return -1;
|
||||
IntPtr vtable = Marshal.ReadIntPtr(qualPtr);
|
||||
if (!SmartBoxLocator.IsPointerInModule(vtable))
|
||||
return -1;
|
||||
|
||||
// Validate the enchantment registry pointer
|
||||
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
|
||||
return -1;
|
||||
IntPtr regPtr = Marshal.ReadIntPtr(regAddr);
|
||||
if (regPtr == IntPtr.Zero) return 0;
|
||||
|
||||
// Validate registry vtable
|
||||
if (!SmartBoxLocator.IsMemoryReadable(regPtr, 4))
|
||||
return -1;
|
||||
IntPtr regVtable = Marshal.ReadIntPtr(regPtr);
|
||||
if (!SmartBoxLocator.IsPointerInModule(regVtable))
|
||||
return -1;
|
||||
|
||||
return ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Core: reads enchantments from a CACQualities pointer's enchantment registry.
|
||||
/// </summary>
|
||||
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
|
||||
{
|
||||
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
|
||||
return -1;
|
||||
IntPtr registryPtr = Marshal.ReadIntPtr(regAddr);
|
||||
|
||||
if (registryPtr == IntPtr.Zero) return 0;
|
||||
|
||||
int count = 0;
|
||||
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
|
||||
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);
|
||||
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count);
|
||||
return count;
|
||||
}
|
||||
|
||||
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count)
|
||||
{
|
||||
if (!SmartBoxLocator.IsMemoryReadable(listPtrAddress, 4))
|
||||
return count;
|
||||
IntPtr listPtr = Marshal.ReadIntPtr(listPtrAddress);
|
||||
if (listPtr == IntPtr.Zero) return count;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(listPtr + ListHeadOffset, 4))
|
||||
return count;
|
||||
IntPtr nodePtr = Marshal.ReadIntPtr(listPtr + ListHeadOffset);
|
||||
|
||||
int guard = 0;
|
||||
while (nodePtr != IntPtr.Zero && guard++ < 512 && count < maxCount)
|
||||
{
|
||||
// Validate entire node is readable before accessing any field
|
||||
if (!SmartBoxLocator.IsMemoryReadable(nodePtr, NodeNextOffset + 4))
|
||||
break;
|
||||
|
||||
// _id field is enchantment ID: (layer << 16) | spellId — mask to get spell ID
|
||||
uint spellId = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentIdOffset)) & 0xFFFF;
|
||||
long startBits = Marshal.ReadInt64(nodePtr + EnchantmentStartTimeOffset);
|
||||
long durBits = Marshal.ReadInt64(nodePtr + EnchantmentDurationOffset);
|
||||
double start = BitConverter.Int64BitsToDouble(startBits);
|
||||
double duration = BitConverter.Int64BitsToDouble(durBits);
|
||||
|
||||
if (spellId != 0)
|
||||
{
|
||||
spellIds[count] = spellId;
|
||||
expiryTimes[count] = duration > 0 ? start + duration : double.MaxValue;
|
||||
count++;
|
||||
}
|
||||
|
||||
nodePtr = Marshal.ReadIntPtr(nodePtr + NodeNextOffset);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
73
src/RynthCore.Engine/Compatibility/LauncherSettings.cs
Normal file
73
src/RynthCore.Engine/Compatibility/LauncherSettings.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class LauncherSettings
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static bool _loaded;
|
||||
private static bool _allowMultipleClients;
|
||||
private static string _statusMessage = "Launcher settings not loaded.";
|
||||
|
||||
public static bool AllowMultipleClientsEnabled
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _allowMultipleClients;
|
||||
}
|
||||
}
|
||||
|
||||
public static string StatusMessage
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _statusMessage;
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureLoaded()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (_loaded)
|
||||
return;
|
||||
|
||||
_loaded = true;
|
||||
|
||||
try
|
||||
{
|
||||
string settingsPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"appsettings.json");
|
||||
|
||||
if (!File.Exists(settingsPath))
|
||||
{
|
||||
_statusMessage = $"Launcher settings file not found ({settingsPath}).";
|
||||
return;
|
||||
}
|
||||
|
||||
using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(settingsPath));
|
||||
if (!document.RootElement.TryGetProperty("AllowMultipleClients", out JsonElement property) ||
|
||||
(property.ValueKind != JsonValueKind.True && property.ValueKind != JsonValueKind.False))
|
||||
{
|
||||
_statusMessage = "AllowMultipleClients not present in launcher settings.";
|
||||
return;
|
||||
}
|
||||
|
||||
_allowMultipleClients = property.GetBoolean();
|
||||
_statusMessage = _allowMultipleClients
|
||||
? "AllowMultipleClients enabled in launcher settings."
|
||||
: "AllowMultipleClients disabled in launcher settings.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = $"Failed to read launcher settings - {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
128
src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs
Normal file
128
src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class LoginLifecycleHooks
|
||||
{
|
||||
private const int ExpectedImageSize = 0x56D000;
|
||||
private static readonly byte?[] SendLoginCompletePattern =
|
||||
[
|
||||
0x6A, 0x01, 0xC6, 0x86, null, null, null, null,
|
||||
0x01, 0xE8, null, null, null, null, 0x8B, 0x0D,
|
||||
null, null, null, null, 0x83, 0xC4, 0x04, 0x6A,
|
||||
0x00, 0x6A, 0x0B, 0xE8
|
||||
];
|
||||
|
||||
private static readonly byte[] SendLoginCompletePrologue = [0x56, 0x8B, 0xF1];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SendLoginCompleteNotificationDelegate(IntPtr thisPtr);
|
||||
|
||||
private static SendLoginCompleteNotificationDelegate? _originalSendLoginCompleteNotification;
|
||||
private static SendLoginCompleteNotificationDelegate? _sendLoginCompleteNotificationDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static long _nextStatusLogTick;
|
||||
private static bool _waitingLogged;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static bool HasObservedLoginComplete { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static event Action? LoginComplete;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int imageSize = textSection.ImageSize;
|
||||
if (imageSize != ExpectedImageSize)
|
||||
RynthLog.Compat($"Compat: login lifecycle hook using unverified acclient image size 0x{imageSize:X} (expected 0x{ExpectedImageSize:X}).");
|
||||
|
||||
int callSiteOff = PatternScanner.FindPattern(textSection.Bytes, SendLoginCompletePattern);
|
||||
if (callSiteOff < 0)
|
||||
{
|
||||
_statusMessage = "SendLoginCompleteNotification call site pattern not found.";
|
||||
RynthLog.Compat($"Compat: login lifecycle hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = PatternScanner.FindPrologueBefore(
|
||||
textSection.Bytes,
|
||||
callSiteOff,
|
||||
SendLoginCompletePrologue,
|
||||
maxDistance: 0x100);
|
||||
|
||||
if (funcOff < 0)
|
||||
{
|
||||
_statusMessage = "SendLoginCompleteNotification prologue not found.";
|
||||
RynthLog.Compat($"Compat: login lifecycle hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_sendLoginCompleteNotificationDetour = SendLoginCompleteNotificationDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendLoginCompleteNotificationDetour);
|
||||
_originalSendLoginCompleteNotification = Marshal.GetDelegateForFunctionPointer<SendLoginCompleteNotificationDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked SendLoginCompleteNotification @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
_nextStatusLogTick = Environment.TickCount64 + 3000;
|
||||
RynthLog.Compat(
|
||||
$"Compat: login lifecycle hook ready - SendLoginCompleteNotification=0x{_targetAddress.ToInt32():X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: login lifecycle hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Poll()
|
||||
{
|
||||
if (HasObservedLoginComplete || !IsInstalled)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextStatusLogTick)
|
||||
return;
|
||||
|
||||
_nextStatusLogTick = now + 3000;
|
||||
if (!_waitingLogged)
|
||||
{
|
||||
_waitingLogged = true;
|
||||
RynthLog.Compat("Compat: login lifecycle awaiting SendLoginCompleteNotification.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SendLoginCompleteNotificationDetour(IntPtr thisPtr)
|
||||
{
|
||||
_originalSendLoginCompleteNotification!(thisPtr);
|
||||
SignalLoginComplete("CPlayerSystem::SendLoginCompleteNotification");
|
||||
}
|
||||
|
||||
private static void SignalLoginComplete(string source)
|
||||
{
|
||||
if (HasObservedLoginComplete)
|
||||
return;
|
||||
|
||||
HasObservedLoginComplete = true;
|
||||
_statusMessage = $"Login complete observed via {source}.";
|
||||
RynthLog.Compat($"Compat: login complete observed via {source}.");
|
||||
LoginComplete?.Invoke();
|
||||
}
|
||||
}
|
||||
263
src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs
Normal file
263
src/RynthCore.Engine/Compatibility/LogoBypassHooks.cs
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the post-connect pre-character signal, then sends the same dismiss
|
||||
/// clicks Thwarg uses to advance past the startup logo screens. This must be
|
||||
/// started early so the client window is available before the login sequence runs.
|
||||
/// </summary>
|
||||
internal static class LogoBypassHooks
|
||||
{
|
||||
private const int IdlePollMs = 50;
|
||||
private const int TimeoutSeconds = 30;
|
||||
private const int HwndPollMs = 200;
|
||||
private const int HwndPollMaxMs = 10_000;
|
||||
private const int ScheduledDismissClicks = 2;
|
||||
private const int PostConnectDismissStartDelayMs = 1000;
|
||||
private const int CharacterListDismissStartDelayMs = 300;
|
||||
private const int DismissRepeatDelayMs = 300;
|
||||
private const int AutoLoginAfterDismissDelayMs = 900;
|
||||
private const int DismissClickX = 350;
|
||||
private const int DismissClickY = 100;
|
||||
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private static volatile bool _started;
|
||||
private static readonly object StateLock = new();
|
||||
private static int _pendingDismissClicks;
|
||||
private static long _nextDismissTick;
|
||||
private static long _recommendedAutoLoginTick;
|
||||
|
||||
/// <summary>
|
||||
/// Call early in InitWorker, before D3D9/Win32Backend are initialized.
|
||||
/// Reads <c>SkipLoginLogos</c> from <c>launch_context.json</c>; does nothing if false or missing.
|
||||
/// </summary>
|
||||
public static void Start()
|
||||
{
|
||||
if (_started)
|
||||
return;
|
||||
|
||||
if (!ReadSkipLogosFromContext())
|
||||
return;
|
||||
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Compat("LogoBypass: Login already complete at start - skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
_started = true;
|
||||
lock (StateLock)
|
||||
{
|
||||
_pendingDismissClicks = 0;
|
||||
_nextDismissTick = 0;
|
||||
_recommendedAutoLoginTick = 0;
|
||||
}
|
||||
|
||||
var thread = new Thread(BypassThread)
|
||||
{
|
||||
Name = "RynthCore.LogoBypass",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
|
||||
RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
|
||||
}
|
||||
|
||||
public static void NotifyCharacterListObserved()
|
||||
{
|
||||
ScheduleDismissClicks("Character-list signal", CharacterListDismissStartDelayMs);
|
||||
}
|
||||
|
||||
public static void NotifyPostConnectObserved()
|
||||
{
|
||||
ScheduleDismissClicks("Post-connect signal", PostConnectDismissStartDelayMs);
|
||||
}
|
||||
|
||||
public static int GetRecommendedAutoLoginDelayMs()
|
||||
{
|
||||
lock (StateLock)
|
||||
{
|
||||
if (_recommendedAutoLoginTick == 0)
|
||||
return 0;
|
||||
|
||||
long remaining = _recommendedAutoLoginTick - Environment.TickCount64;
|
||||
return remaining > 0 ? (int)Math.Min(remaining, int.MaxValue) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void BypassThread()
|
||||
{
|
||||
IntPtr hwnd = PollForGameWindow();
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Compat("LogoBypass: Could not find game HWND - giving up.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.Compat($"LogoBypass: Found game HWND 0x{hwnd:X8} - awaiting post-connect or character-list signal.");
|
||||
BypassLoop(hwnd);
|
||||
}
|
||||
|
||||
private static void ScheduleDismissClicks(string triggerName, int startDelayMs)
|
||||
{
|
||||
if (!_started)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
bool scheduled = false;
|
||||
lock (StateLock)
|
||||
{
|
||||
if (_pendingDismissClicks <= 0 && (_recommendedAutoLoginTick == 0 || now >= _recommendedAutoLoginTick))
|
||||
{
|
||||
_pendingDismissClicks = ScheduledDismissClicks;
|
||||
_nextDismissTick = now + startDelayMs;
|
||||
_recommendedAutoLoginTick = _nextDismissTick
|
||||
+ ((ScheduledDismissClicks - 1L) * DismissRepeatDelayMs)
|
||||
+ AutoLoginAfterDismissDelayMs;
|
||||
scheduled = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (scheduled)
|
||||
{
|
||||
RynthLog.Compat(
|
||||
$"LogoBypass: {triggerName} observed - scheduling {ScheduledDismissClicks} dismiss click(s) at ({DismissClickX}, {DismissClickY}) with {startDelayMs}ms start delay.");
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr PollForGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
int elapsed = 0;
|
||||
while (elapsed < HwndPollMaxMs)
|
||||
{
|
||||
IntPtr found = IntPtr.Zero;
|
||||
EnumWindows((hWnd, _) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint windowPid);
|
||||
if (windowPid == pid && IsWindowVisible(hWnd))
|
||||
{
|
||||
found = hWnd;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
if (found != IntPtr.Zero)
|
||||
return found;
|
||||
|
||||
Thread.Sleep(HwndPollMs);
|
||||
elapsed += HwndPollMs;
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static void BypassLoop(IntPtr hwnd)
|
||||
{
|
||||
DateTime deadline = DateTime.UtcNow.AddSeconds(TimeoutSeconds);
|
||||
try
|
||||
{
|
||||
while (!LoginLifecycleHooks.HasObservedLoginComplete &&
|
||||
DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (TryTakeDueDismissClick())
|
||||
SendDismissInput(hwnd);
|
||||
else
|
||||
Thread.Sleep(IdlePollMs);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete" : "timeout";
|
||||
RynthLog.Compat($"LogoBypass: Stopped ({reason}).");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryTakeDueDismissClick()
|
||||
{
|
||||
lock (StateLock)
|
||||
{
|
||||
if (_pendingDismissClicks <= 0)
|
||||
return false;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextDismissTick)
|
||||
return false;
|
||||
|
||||
_pendingDismissClicks--;
|
||||
_nextDismissTick = _pendingDismissClicks > 0 ? now + DismissRepeatDelayMs : 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SendDismissInput(IntPtr hwnd)
|
||||
{
|
||||
IntPtr lParam = MakeLParam(DismissClickX, DismissClickY);
|
||||
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
|
||||
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
|
||||
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
|
||||
RynthLog.Compat($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}).");
|
||||
}
|
||||
|
||||
private static IntPtr MakeLParam(int x, int y) =>
|
||||
(IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
|
||||
|
||||
private static bool ReadSkipLogosFromContext()
|
||||
{
|
||||
try
|
||||
{
|
||||
string rootDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore");
|
||||
|
||||
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
|
||||
bool? processValue = ReadSkipLogosFromFile(processPath);
|
||||
if (processValue.HasValue)
|
||||
return processValue.Value;
|
||||
|
||||
return ReadSkipLogosFromFile(Path.Combine(rootDir, "launch_context.json")) ?? false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? ReadSkipLogosFromFile(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
return doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el) ? el.GetBoolean() : null;
|
||||
}
|
||||
}
|
||||
210
src/RynthCore.Engine/Compatibility/MovementActionHooks.cs
Normal file
210
src/RynthCore.Engine/Compatibility/MovementActionHooks.cs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class MovementActionHooks
|
||||
{
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool DoMovementCommandDelegate(uint motion, float speed, int holdKey);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool StopMovementCommandDelegate(uint motion, int holdKey);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool JumpNonAutonomousDelegate(float extent);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool AutonomyLevelDelegate(uint level);
|
||||
|
||||
public const uint MotionWalkForward = 0x45000005;
|
||||
public const uint MotionWalkBackward = 0x45000006;
|
||||
public const uint MotionRunForward = 0x41000003;
|
||||
public const uint MotionTurnRight = 0x6500000D;
|
||||
public const uint MotionTurnLeft = 0x6500000E;
|
||||
public const uint MotionSidestepRight = 0x6500000F;
|
||||
public const uint MotionSidestepLeft = 0x65000010;
|
||||
|
||||
public const int HoldKeyNone = 0;
|
||||
public const int HoldKeyRun = 1;
|
||||
public const int HoldKeyAutorun = 2;
|
||||
|
||||
private static readonly byte[] MovementPrologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
|
||||
|
||||
private static DoMovementCommandDelegate? _doMovement;
|
||||
private static StopMovementCommandDelegate? _stopMovement;
|
||||
private static JumpNonAutonomousDelegate? _jumpNonAutonomous;
|
||||
private static AutonomyLevelDelegate? _autonomyLevel;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
public static bool HasDoMovement => _doMovement != null;
|
||||
public static bool HasStopMovement => _stopMovement != null;
|
||||
public static bool HasJumpNonAutonomous => _jumpNonAutonomous != null;
|
||||
public static bool HasAutonomyLevel => _autonomyLevel != null;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
Reset();
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte[] text = textSection.Bytes;
|
||||
|
||||
byte[] stopOpcode = [0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00];
|
||||
int stopOpcodeOff = PatternScanner.FindPattern(text, stopOpcode);
|
||||
if (stopOpcodeOff < 0)
|
||||
{
|
||||
_statusMessage = "StopMovement opcode 0xF661 not found.";
|
||||
RynthLog.Compat("Compat: movement probe failed - StopMovement opcode 0xF661 not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int stopFuncOff = PatternScanner.FindPrologueBefore(text, stopOpcodeOff, MovementPrologue);
|
||||
if (stopFuncOff < 0)
|
||||
{
|
||||
_statusMessage = "StopMovement prologue not found.";
|
||||
RynthLog.Compat("Compat: movement probe failed - StopMovement prologue not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int regionStart = Math.Max(0, stopOpcodeOff - 0x700);
|
||||
int regionEnd = Math.Min(text.Length, stopOpcodeOff + 0x300);
|
||||
|
||||
byte[] doOpcode = [0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00];
|
||||
int doOpcodeOff = PatternScanner.FindPatternInRegion(text, doOpcode, regionStart, regionEnd);
|
||||
int doFuncOff = doOpcodeOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, doOpcodeOff, MovementPrologue)
|
||||
: -1;
|
||||
|
||||
byte[] jumpOpcode = [0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00];
|
||||
int jumpOpcodeOff = PatternScanner.FindPatternInRegion(text, jumpOpcode, regionStart, regionEnd);
|
||||
int jumpFuncOff = jumpOpcodeOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, jumpOpcodeOff, MovementPrologue)
|
||||
: -1;
|
||||
|
||||
byte[] autonomyOpcode = [0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00];
|
||||
int autonomyOpcodeOff = PatternScanner.FindPatternInRegion(text, autonomyOpcode, regionStart, regionEnd);
|
||||
int autonomyFuncOff = autonomyOpcodeOff >= 0
|
||||
? PatternScanner.FindPrologueBefore(text, autonomyOpcodeOff, MovementPrologue)
|
||||
: -1;
|
||||
|
||||
if (doFuncOff < 0)
|
||||
{
|
||||
_statusMessage = "DoMovement opcode 0xF61E not found.";
|
||||
RynthLog.Compat("Compat: movement probe incomplete - DoMovement opcode 0xF61E not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int stopVa = textSection.TextBaseVa + stopFuncOff;
|
||||
int doVa = textSection.TextBaseVa + doFuncOff;
|
||||
_stopMovement = Marshal.GetDelegateForFunctionPointer<StopMovementCommandDelegate>(new IntPtr(stopVa));
|
||||
_doMovement = Marshal.GetDelegateForFunctionPointer<DoMovementCommandDelegate>(new IntPtr(doVa));
|
||||
|
||||
if (jumpFuncOff >= 0)
|
||||
{
|
||||
int jumpVa = textSection.TextBaseVa + jumpFuncOff;
|
||||
_jumpNonAutonomous = Marshal.GetDelegateForFunctionPointer<JumpNonAutonomousDelegate>(new IntPtr(jumpVa));
|
||||
RynthLog.Compat($"Compat: movement jump hook ready - jump=0x{jumpVa:X8}");
|
||||
}
|
||||
|
||||
if (autonomyFuncOff >= 0)
|
||||
{
|
||||
int autonomyVa = textSection.TextBaseVa + autonomyFuncOff;
|
||||
_autonomyLevel = Marshal.GetDelegateForFunctionPointer<AutonomyLevelDelegate>(new IntPtr(autonomyVa));
|
||||
RynthLog.Compat($"Compat: movement autonomy hook ready - autonomy=0x{autonomyVa:X8}");
|
||||
}
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = jumpFuncOff >= 0 && autonomyFuncOff >= 0
|
||||
? "Ready."
|
||||
: $"Partial. jump={jumpFuncOff >= 0}, autonomy={autonomyFuncOff >= 0}.";
|
||||
|
||||
RynthLog.Compat($"Compat: movement hooks ready - stop=0x{stopVa:X8}, move=0x{doVa:X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: movement probe failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (_doMovement == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _doMovement(motion, speed, holdKey);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (_stopMovement == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _stopMovement(motion, holdKey);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool JumpNonAutonomous(float extent)
|
||||
{
|
||||
if (_jumpNonAutonomous == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _jumpNonAutonomous(Math.Clamp(extent, 0f, 1f));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetAutonomyLevel(uint level)
|
||||
{
|
||||
if (_autonomyLevel == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return _autonomyLevel(level);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
_doMovement = null;
|
||||
_stopMovement = null;
|
||||
_jumpNonAutonomous = null;
|
||||
_autonomyLevel = null;
|
||||
IsInitialized = false;
|
||||
}
|
||||
}
|
||||
204
src/RynthCore.Engine/Compatibility/MultiClientHooks.cs
Normal file
204
src/RynthCore.Engine/Compatibility/MultiClientHooks.cs
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class MultiClientHooks
|
||||
{
|
||||
private const int ExpectedImageSize = 0x56D000;
|
||||
private const int IsAlreadyRunningVa = 0x004122A0;
|
||||
private const int OpenDataFileVa = 0x00675920;
|
||||
private const uint OpenDataFileSharedAccessFlag = 0x4;
|
||||
|
||||
private static readonly byte?[] IsAlreadyRunningSignature =
|
||||
[
|
||||
0x56, 0x68, 0x30, 0x58, 0x79, 0x00, 0x6A, 0x01,
|
||||
0x6A, 0x00, 0x6A, 0x00, 0x8B, 0xF1, 0xFF, 0x15
|
||||
];
|
||||
|
||||
private static readonly byte?[] OpenDataFileSignature =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x10, 0x53, 0x55, 0x8B, 0x6C,
|
||||
0x24, 0x0C, 0x56, 0x57, 0x8B, 0xF1, 0x50, 0x8B,
|
||||
0xC8, 0x8B, 0x44, 0x24, 0x20, 0x6A, 0x00, 0x80,
|
||||
0xE1, 0x02, 0x80, 0xF9, 0x02, 0x50, 0x6A, 0x00
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate byte IsAlreadyRunningDelegate(IntPtr thisPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate uint OpenDataFileDelegate(
|
||||
IntPtr allocator,
|
||||
IntPtr fileInfo,
|
||||
IntPtr fileName,
|
||||
IntPtr pathToUse,
|
||||
uint openFlags,
|
||||
IntPtr transactionInfo);
|
||||
|
||||
private static IsAlreadyRunningDelegate? _detour;
|
||||
private static IsAlreadyRunningDelegate? _originalIsAlreadyRunning;
|
||||
private static OpenDataFileDelegate? _openDataFileDetour;
|
||||
private static OpenDataFileDelegate? _originalOpenDataFile;
|
||||
private static IntPtr _targetAddress;
|
||||
private static IntPtr _openDataFileAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsEnabled { get; private set; }
|
||||
public static bool IsAlreadyRunningInstalled { get; private set; }
|
||||
public static bool OpenDataFileInstalled { get; private set; }
|
||||
public static bool IsInstalled => IsAlreadyRunningInstalled && OpenDataFileInstalled;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsAlreadyRunningInstalled && OpenDataFileInstalled)
|
||||
return;
|
||||
|
||||
bool allowMultipleClients = LauncherSettings.AllowMultipleClientsEnabled;
|
||||
IsEnabled = allowMultipleClients;
|
||||
_statusMessage = LauncherSettings.StatusMessage;
|
||||
|
||||
if (!allowMultipleClients)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client bypass skipped - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (textSection.ImageSize != ExpectedImageSize)
|
||||
RynthLog.Compat($"Compat: multi-client hook using unverified acclient image size 0x{textSection.ImageSize:X} (expected 0x{ExpectedImageSize:X}).");
|
||||
|
||||
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
_statusMessage = $"Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
|
||||
{
|
||||
byte? expected = IsAlreadyRunningSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
_statusMessage = $"Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
TryInstallIsAlreadyRunningHook(textSection);
|
||||
TryInstallOpenDataFileHook(textSection);
|
||||
|
||||
if (!IsAlreadyRunningInstalled && !OpenDataFileInstalled)
|
||||
{
|
||||
_statusMessage = "No multi-client compatibility hooks installed.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsInstalled)
|
||||
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{IsAlreadyRunningVa:X8} and CLBlockAllocator::OpenDataFile @ 0x{OpenDataFileVa:X8}.";
|
||||
else
|
||||
_statusMessage = $"Partial install. alreadyRunning={IsAlreadyRunningInstalled}, dataFile={OpenDataFileInstalled}.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryInstallIsAlreadyRunningHook(AcClientTextSection textSection)
|
||||
{
|
||||
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
|
||||
{
|
||||
byte? expected = IsAlreadyRunningSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_targetAddress = new IntPtr(IsAlreadyRunningVa);
|
||||
_detour = IsAlreadyRunningDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
|
||||
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsAlreadyRunningInstalled = true;
|
||||
RynthLog.Compat($"Compat: multi-client hook ready - IsAlreadyRunning=0x{IsAlreadyRunningVa:X8}");
|
||||
}
|
||||
|
||||
private static void TryInstallOpenDataFileHook(AcClientTextSection textSection)
|
||||
{
|
||||
int funcOff = OpenDataFileVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + OpenDataFileSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile VA 0x{OpenDataFileVa:X8} is outside the readable text window.");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < OpenDataFileSignature.Length; i++)
|
||||
{
|
||||
byte? expected = OpenDataFileSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile signature mismatch at 0x{OpenDataFileVa + i:X8}.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_openDataFileAddress = new IntPtr(OpenDataFileVa);
|
||||
_openDataFileDetour = OpenDataFileDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
|
||||
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(MinHook.HookCreate(_openDataFileAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_openDataFileAddress);
|
||||
|
||||
OpenDataFileInstalled = true;
|
||||
RynthLog.Compat($"Compat: multi-client data-file hook ready - CLBlockAllocator::OpenDataFile=0x{OpenDataFileVa:X8}");
|
||||
}
|
||||
|
||||
private static byte IsAlreadyRunningDetour(IntPtr thisPtr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static uint OpenDataFileDetour(
|
||||
IntPtr allocator,
|
||||
IntPtr fileInfo,
|
||||
IntPtr fileName,
|
||||
IntPtr pathToUse,
|
||||
uint openFlags,
|
||||
IntPtr transactionInfo)
|
||||
{
|
||||
return _originalOpenDataFile!(
|
||||
allocator,
|
||||
fileInfo,
|
||||
fileName,
|
||||
pathToUse,
|
||||
openFlags | OpenDataFileSharedAccessFlag,
|
||||
transactionInfo);
|
||||
}
|
||||
}
|
||||
60
src/RynthCore.Engine/Compatibility/ObjectQualityCache.cs
Normal file
60
src/RynthCore.Engine/Compatibility/ObjectQualityCache.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal readonly record struct CreatureVitals(
|
||||
uint Health, uint MaxHealth,
|
||||
uint Stamina, uint MaxStamina,
|
||||
uint Mana, uint MaxMana);
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight cache for creature vitals keyed by CWeenieObject pointer.
|
||||
/// Populated from IdentifyObject (0xC9) CreatureProfile responses so that
|
||||
/// QueryHealthResponse can resolve absolute health values, and plugins can
|
||||
/// query target stamina/mana.
|
||||
/// </summary>
|
||||
internal static class ObjectQualityCache
|
||||
{
|
||||
private static readonly Dictionary<IntPtr, uint> _maxHealthByPtr = new();
|
||||
private static readonly Dictionary<uint, CreatureVitals> _vitalsByObjectId = new();
|
||||
private static readonly object _lock = new();
|
||||
|
||||
public static void SetMaxHealth(IntPtr objectPtr, uint maxHealth)
|
||||
{
|
||||
if (objectPtr == IntPtr.Zero)
|
||||
return;
|
||||
lock (_lock)
|
||||
_maxHealthByPtr[objectPtr] = maxHealth;
|
||||
}
|
||||
|
||||
public static bool TryGetMaxHealth(IntPtr objectPtr, out uint maxHealth)
|
||||
{
|
||||
if (objectPtr == IntPtr.Zero)
|
||||
{
|
||||
maxHealth = 0;
|
||||
return false;
|
||||
}
|
||||
lock (_lock)
|
||||
return _maxHealthByPtr.TryGetValue(objectPtr, out maxHealth);
|
||||
}
|
||||
|
||||
public static void SetCreatureVitals(uint objectId, CreatureVitals vitals)
|
||||
{
|
||||
if (objectId == 0)
|
||||
return;
|
||||
lock (_lock)
|
||||
_vitalsByObjectId[objectId] = vitals;
|
||||
}
|
||||
|
||||
public static bool TryGetCreatureVitals(uint objectId, out CreatureVitals vitals)
|
||||
{
|
||||
if (objectId == 0)
|
||||
{
|
||||
vitals = default;
|
||||
return false;
|
||||
}
|
||||
lock (_lock)
|
||||
return _vitalsByObjectId.TryGetValue(objectId, out vitals);
|
||||
}
|
||||
}
|
||||
109
src/RynthCore.Engine/Compatibility/PatternScanner.cs
Normal file
109
src/RynthCore.Engine/Compatibility/PatternScanner.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class PatternScanner
|
||||
{
|
||||
public static int FindPattern(byte[] data, byte[] pattern)
|
||||
{
|
||||
return FindPatternInRegion(data, pattern, 0, data.Length);
|
||||
}
|
||||
|
||||
public static int FindPattern(byte[] data, byte?[] pattern)
|
||||
{
|
||||
return FindPatternInRegion(data, pattern, 0, data.Length);
|
||||
}
|
||||
|
||||
public static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end)
|
||||
{
|
||||
int limit = Math.Min(end, data.Length) - pattern.Length;
|
||||
for (int i = Math.Max(0, start); i <= limit; i++)
|
||||
{
|
||||
bool match = true;
|
||||
for (int j = 0; j < pattern.Length; j++)
|
||||
{
|
||||
if (data[i + j] == pattern[j])
|
||||
continue;
|
||||
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (match)
|
||||
return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int FindPatternInRegion(byte[] data, byte?[] pattern, int start, int end)
|
||||
{
|
||||
int limit = Math.Min(end, data.Length) - pattern.Length;
|
||||
for (int i = Math.Max(0, start); i <= limit; i++)
|
||||
{
|
||||
bool match = true;
|
||||
for (int j = 0; j < pattern.Length; j++)
|
||||
{
|
||||
byte? expected = pattern[j];
|
||||
if (expected.HasValue && data[i + j] != expected.Value)
|
||||
{
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (match)
|
||||
return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int FindPrologueBefore(byte[] data, int opcodeOffset, byte[] prologue, int maxDistance = 300)
|
||||
{
|
||||
for (int back = 1; back < maxDistance; back++)
|
||||
{
|
||||
int pos = opcodeOffset - back;
|
||||
if (pos < 1 || pos + prologue.Length > data.Length)
|
||||
continue;
|
||||
|
||||
if (!VerifyBytes(data, pos, prologue))
|
||||
continue;
|
||||
|
||||
byte prev = data[pos - 1];
|
||||
if (prev == 0xCC || prev == 0x90 || prev == 0xC3)
|
||||
return pos;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static bool VerifyBytes(byte[] data, int offset, byte[] expected)
|
||||
{
|
||||
if (offset < 0 || offset + expected.Length > data.Length)
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < expected.Length; i++)
|
||||
{
|
||||
if (data[offset + i] != expected[i])
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool VerifyPattern(byte[] data, int offset, byte?[] expected)
|
||||
{
|
||||
if (offset < 0 || offset + expected.Length > data.Length)
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < expected.Length; i++)
|
||||
{
|
||||
byte? value = expected[i];
|
||||
if (value.HasValue && data[offset + i] != value.Value)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
283
src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs
Normal file
283
src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class PlayerPhysicsHooks
|
||||
{
|
||||
private const int PhysicsPositionOffset = 0x48;
|
||||
private const int PositionObjCellIdOffset = 0x04;
|
||||
private const int PositionQwOffset = 0x08;
|
||||
private const int PositionQxOffset = 0x0C;
|
||||
private const int PositionQyOffset = 0x10;
|
||||
private const int PositionQzOffset = 0x14;
|
||||
private const int PositionOriginXOffset = 0x3C;
|
||||
private const int PositionOriginYOffset = 0x40;
|
||||
private const int PositionOriginZOffset = 0x44;
|
||||
private const int ReferencePhysicsGetHeading = 0x00512010;
|
||||
private const int ReferencePhysicsSetHeading = 0x00514C60;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate float PhysicsGetHeadingDelegate(IntPtr physicsObjPtr);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void PhysicsSetHeadingDelegate(IntPtr physicsObjPtr, float headingDegrees, int sendEvent);
|
||||
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static PhysicsGetHeadingDelegate? _getHeading;
|
||||
private static PhysicsSetHeadingDelegate? _setHeading;
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
public static bool HasGetHeading => _getHeading != null;
|
||||
public static bool HasSetHeading => _setHeading != null;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
bool ready = SmartBoxLocator.Probe();
|
||||
IsInitialized = ready;
|
||||
_statusMessage = ready ? "Ready." : SmartBoxLocator.StatusMessage;
|
||||
|
||||
if (ready)
|
||||
{
|
||||
BindPhysicsDelegates();
|
||||
RynthLog.Compat($"Compat: player physics ready - smartbox candidates={SmartBoxLocator.CandidateCount}");
|
||||
}
|
||||
|
||||
return ready;
|
||||
}
|
||||
|
||||
public static bool TryGetPlayerPose(
|
||||
out uint objCellId,
|
||||
out float x,
|
||||
out float y,
|
||||
out float z,
|
||||
out float qw,
|
||||
out float qx,
|
||||
out float qy,
|
||||
out float qz)
|
||||
{
|
||||
objCellId = 0;
|
||||
x = y = z = 0;
|
||||
qw = 1f;
|
||||
qx = qy = qz = 0;
|
||||
|
||||
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
|
||||
{
|
||||
_statusMessage = failure;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr pos = player + PhysicsPositionOffset;
|
||||
objCellId = unchecked((uint)Marshal.ReadInt32(pos + PositionObjCellIdOffset));
|
||||
qw = ReadFloat(pos + PositionQwOffset);
|
||||
qx = ReadFloat(pos + PositionQxOffset);
|
||||
qy = ReadFloat(pos + PositionQyOffset);
|
||||
qz = ReadFloat(pos + PositionQzOffset);
|
||||
x = ReadFloat(pos + PositionOriginXOffset);
|
||||
y = ReadFloat(pos + PositionOriginYOffset);
|
||||
z = ReadFloat(pos + PositionOriginZOffset);
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetPlayerHeading(out float headingDegrees)
|
||||
{
|
||||
headingDegrees = 0;
|
||||
|
||||
if (!EnsurePhysicsDelegates())
|
||||
return false;
|
||||
|
||||
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
|
||||
{
|
||||
_statusMessage = failure;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
headingDegrees = NormalizeDecalHeading(_getHeading!(player));
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetPlayerHeading(float headingDegrees)
|
||||
{
|
||||
if (!EnsurePhysicsDelegates() || _setHeading == null)
|
||||
return false;
|
||||
|
||||
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
|
||||
{
|
||||
_statusMessage = failure;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_setHeading(player, NormalizePhysicsHeading(headingDegrees), 1);
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the player heading by directly writing the orientation quaternion
|
||||
/// in the player's CPhysicsObj position struct. This is an instant snap —
|
||||
/// equivalent to old Decal <c>Actions.Heading = value</c>.
|
||||
///
|
||||
/// Uses the same SmartBox memory offsets we read from in TryGetPlayerPose,
|
||||
/// so it's reliable whenever pose reads work. Does not depend on any
|
||||
/// hardcoded function VAs.
|
||||
/// </summary>
|
||||
public static bool SetPlayerHeadingDirect(float decalHeadingDeg)
|
||||
{
|
||||
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
|
||||
{
|
||||
_statusMessage = failure;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Convert Decal heading (0°=N, clockwise) to physics yaw (0°=N, counter-clockwise)
|
||||
double physYawDeg = -decalHeadingDeg;
|
||||
double physYawRad = physYawDeg * (Math.PI / 180.0);
|
||||
|
||||
// Yaw-only quaternion: q = (cos(yaw/2), 0, 0, sin(yaw/2))
|
||||
float newQw = (float)Math.Cos(physYawRad * 0.5);
|
||||
float newQz = (float)Math.Sin(physYawRad * 0.5);
|
||||
|
||||
IntPtr pos = player + PhysicsPositionOffset;
|
||||
WriteFloat(pos + PositionQwOffset, newQw);
|
||||
WriteFloat(pos + PositionQzOffset, newQz);
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteFloat(IntPtr address, float value)
|
||||
{
|
||||
Marshal.WriteInt32(address, BitConverter.SingleToInt32Bits(value));
|
||||
}
|
||||
|
||||
private static float ReadFloat(IntPtr address)
|
||||
{
|
||||
int bits = Marshal.ReadInt32(address);
|
||||
return BitConverter.Int32BitsToSingle(bits);
|
||||
}
|
||||
|
||||
// CPhysicsObj heading is rotated 90 degrees from the Decal/VTank basis
|
||||
// used by old RynthAi Actions.Heading. Normalize here so plugins can stay
|
||||
// on the original T1 heading math.
|
||||
private static float NormalizeDecalHeading(float physicsHeading)
|
||||
{
|
||||
return NormalizeDegrees(90f - physicsHeading);
|
||||
}
|
||||
|
||||
private static float NormalizePhysicsHeading(float decalHeading)
|
||||
{
|
||||
return NormalizeDegrees(90f - decalHeading);
|
||||
}
|
||||
|
||||
private static float NormalizeDegrees(float heading)
|
||||
{
|
||||
while (heading < 0f)
|
||||
heading += 360f;
|
||||
|
||||
while (heading >= 360f)
|
||||
heading -= 360f;
|
||||
|
||||
return heading;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes live NS/EW coordinates from the player's physics pose
|
||||
/// (objCellId + local x,y) using the classic in-game coordinate basis.
|
||||
/// This keeps steering and overlays on the same source of truth and
|
||||
/// avoids stale cached coordinate reads while running.
|
||||
/// </summary>
|
||||
public static bool TryGetLiveCoords(out double northSouth, out double eastWest)
|
||||
{
|
||||
northSouth = 0;
|
||||
eastWest = 0;
|
||||
|
||||
if (!TryGetPlayerPose(out uint objCellId, out float x, out float y, out _, out _, out _, out _, out _))
|
||||
return false;
|
||||
|
||||
int lbX = (int)((objCellId >> 24) & 0xFF);
|
||||
int lbY = (int)((objCellId >> 16) & 0xFF);
|
||||
|
||||
// Match the classic radar/coordinates basis exactly:
|
||||
// EW = ((Landcell >> 24) * 8 + X / 24 - 1019.5) / 10
|
||||
// NS = (((Landcell >> 16) & 0xFF) * 8 + Y / 24 - 1019.5) / 10
|
||||
eastWest = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
|
||||
northSouth = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool EnsurePhysicsDelegates()
|
||||
{
|
||||
if (_getHeading != null && _setHeading != null)
|
||||
return true;
|
||||
|
||||
if (!SmartBoxLocator.Probe())
|
||||
{
|
||||
_statusMessage = SmartBoxLocator.StatusMessage;
|
||||
return false;
|
||||
}
|
||||
|
||||
return BindPhysicsDelegates();
|
||||
}
|
||||
|
||||
private static bool BindPhysicsDelegates()
|
||||
{
|
||||
if (_getHeading != null && _setHeading != null)
|
||||
return true;
|
||||
|
||||
IntPtr getHeadingPtr = new(ReferencePhysicsGetHeading);
|
||||
IntPtr setHeadingPtr = new(ReferencePhysicsSetHeading);
|
||||
if (!SmartBoxLocator.IsPointerInModule(getHeadingPtr) || !SmartBoxLocator.IsPointerInModule(setHeadingPtr))
|
||||
{
|
||||
_statusMessage =
|
||||
$"Physics heading pointers look invalid (get=0x{getHeadingPtr.ToInt32():X8}, set=0x{setHeadingPtr.ToInt32():X8}).";
|
||||
RynthLog.Compat($"Compat: player physics heading bind failed - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_getHeading = Marshal.GetDelegateForFunctionPointer<PhysicsGetHeadingDelegate>(getHeadingPtr);
|
||||
_setHeading = Marshal.GetDelegateForFunctionPointer<PhysicsSetHeadingDelegate>(setHeadingPtr);
|
||||
RynthLog.Compat(
|
||||
$"Compat: player heading hooks ready - get=0x{getHeadingPtr.ToInt32():X8}, set=0x{setHeadingPtr.ToInt32():X8}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
459
src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs
Normal file
459
src/RynthCore.Engine/Compatibility/PlayerVitalsHooks.cs
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal readonly record struct PlayerVitalsSnapshot(
|
||||
uint Health,
|
||||
uint MaxHealth,
|
||||
uint Stamina,
|
||||
uint MaxStamina,
|
||||
uint Mana,
|
||||
uint MaxMana);
|
||||
|
||||
internal static class PlayerVitalsHooks
|
||||
{
|
||||
/// <summary>
|
||||
/// The player's CACQualities* (== PlayerDesc*), set when SendNoticePlayerDescReceived fires.
|
||||
/// Used by EnchantmentHooks to filter UpdateEnchantment/RemoveEnchantment to the player only.
|
||||
/// </summary>
|
||||
internal static IntPtr KnownPlayerQualitiesPtr { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Allows other internal hooks to populate the qualities ptr when discovered
|
||||
/// via an alternative path (e.g. mid-session injection before the login hook fires).
|
||||
/// </summary>
|
||||
internal static void SetKnownPlayerQualitiesPtr(IntPtr ptr)
|
||||
{
|
||||
if (ptr != IntPtr.Zero)
|
||||
KnownPlayerQualitiesPtr = ptr;
|
||||
}
|
||||
|
||||
private const int UpdateAttribute2ndVa = 0x00559900;
|
||||
private const int UpdateAttribute2ndLevelVa = 0x00559920;
|
||||
private const int PrivateUpdateAttribute2ndVa = 0x00559B20;
|
||||
private const int PrivateUpdateAttribute2ndLevelVa = 0x00559B50;
|
||||
private const int OnStatUpdatedIntVa = 0x0058ED50;
|
||||
private const int InqAttribute2ndStructVa = 0x005927F0;
|
||||
private const int SendNoticePlayerDescReceivedVa = 0x0047A200;
|
||||
private const int MaxUpdateLogs = 18;
|
||||
|
||||
private const uint MaxHealthType = 1;
|
||||
private const uint HealthType = 2;
|
||||
private const uint MaxStaminaType = 3;
|
||||
private const uint StaminaType = 4;
|
||||
private const uint MaxManaType = 5;
|
||||
private const uint ManaType = 6;
|
||||
|
||||
private static readonly object CacheLock = new();
|
||||
private static IntPtr _originalUpdateAttribute2ndPtr;
|
||||
private static IntPtr _originalUpdateAttribute2ndLevelPtr;
|
||||
private static IntPtr _originalPrivateUpdateAttribute2ndPtr;
|
||||
private static IntPtr _originalPrivateUpdateAttribute2ndLevelPtr;
|
||||
private static IntPtr _originalOnStatUpdatedIntPtr;
|
||||
private static IntPtr _originalSendNoticePlayerDescReceivedPtr;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _updateLogCount;
|
||||
private static int _seedLogCount;
|
||||
private static PlayerVitalsSnapshot _snapshot;
|
||||
private static InqAttribute2ndStructDelegate? _inqAttribute2ndStruct;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out _))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr updateAttributePtr = new(UpdateAttribute2ndVa);
|
||||
IntPtr updatePtr = new(UpdateAttribute2ndLevelVa);
|
||||
IntPtr privateUpdateAttributePtr = new(PrivateUpdateAttribute2ndVa);
|
||||
IntPtr privateUpdatePtr = new(PrivateUpdateAttribute2ndLevelVa);
|
||||
IntPtr onStatUpdatedIntPtr = new(OnStatUpdatedIntVa);
|
||||
IntPtr inqAttribute2ndStructPtr = new(InqAttribute2ndStructVa);
|
||||
IntPtr sendNoticePlayerDescReceivedPtr = new(SendNoticePlayerDescReceivedVa);
|
||||
|
||||
if (!SmartBoxLocator.IsPointerInModule(updateAttributePtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(updatePtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(privateUpdateAttributePtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(privateUpdatePtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(onStatUpdatedIntPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(inqAttribute2ndStructPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(sendNoticePlayerDescReceivedPtr))
|
||||
{
|
||||
_statusMessage =
|
||||
$"Attribute2nd handlers look invalid (update=0x{updateAttributePtr.ToInt32():X8}, level=0x{updatePtr.ToInt32():X8}, private=0x{privateUpdateAttributePtr.ToInt32():X8}, privateLevel=0x{privateUpdatePtr.ToInt32():X8}, stat=0x{onStatUpdatedIntPtr.ToInt32():X8}, inq2nd=0x{inqAttribute2ndStructPtr.ToInt32():X8}, playerDesc=0x{sendNoticePlayerDescReceivedPtr.ToInt32():X8}).";
|
||||
RynthLog.Compat($"Compat: player vitals hooks failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
_inqAttribute2ndStruct = Marshal.GetDelegateForFunctionPointer<InqAttribute2ndStructDelegate>(inqAttribute2ndStructPtr);
|
||||
|
||||
unsafe
|
||||
{
|
||||
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, SecondaryAttributeNative*, uint> updateAttributeDetour = &HandleUpdateAttribute2ndDetour;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, int, uint> updateDetour = &HandleUpdateAttribute2ndLevelDetour;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, SecondaryAttributeNative*, uint> privateUpdateAttributeDetour = &HandlePrivateUpdateAttribute2ndDetour;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, int, uint> privateUpdateDetour = &HandlePrivateUpdateAttribute2ndLevelDetour;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, uint, int, void> onStatUpdatedIntDetour = &HandleOnStatUpdatedIntDetour;
|
||||
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, byte> sendNoticePlayerDescReceivedDetour = &HandleSendNoticePlayerDescReceivedDetour;
|
||||
|
||||
MinHook.Hook(updateAttributePtr, (IntPtr)updateAttributeDetour, out _originalUpdateAttribute2ndPtr);
|
||||
MinHook.Hook(updatePtr, (IntPtr)updateDetour, out _originalUpdateAttribute2ndLevelPtr);
|
||||
MinHook.Hook(privateUpdateAttributePtr, (IntPtr)privateUpdateAttributeDetour, out _originalPrivateUpdateAttribute2ndPtr);
|
||||
MinHook.Hook(privateUpdatePtr, (IntPtr)privateUpdateDetour, out _originalPrivateUpdateAttribute2ndLevelPtr);
|
||||
MinHook.Hook(onStatUpdatedIntPtr, (IntPtr)onStatUpdatedIntDetour, out _originalOnStatUpdatedIntPtr);
|
||||
MinHook.Hook(sendNoticePlayerDescReceivedPtr, (IntPtr)sendNoticePlayerDescReceivedDetour, out _originalSendNoticePlayerDescReceivedPtr);
|
||||
}
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = "Hooks installed.";
|
||||
RynthLog.Compat($"Compat: player vitals hooks ready - update=0x{UpdateAttribute2ndVa:X8}, level=0x{UpdateAttribute2ndLevelVa:X8}, private=0x{PrivateUpdateAttribute2ndVa:X8}, privateLevel=0x{PrivateUpdateAttribute2ndLevelVa:X8}, stat=0x{OnStatUpdatedIntVa:X8}, playerDesc=0x{SendNoticePlayerDescReceivedVa:X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: player vitals hooks failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads MaxHealth from any CWeenieObject via InqAttribute2ndStruct.
|
||||
/// Must be called from the game thread (detours, not render thread).
|
||||
/// </summary>
|
||||
public static unsafe bool TryReadObjectMaxHealth(IntPtr weeniePtr, out uint maxHealth)
|
||||
{
|
||||
maxHealth = 0;
|
||||
if (_inqAttribute2ndStruct == null || weeniePtr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
SecondaryAttributeNative maxValue = default;
|
||||
if (_inqAttribute2ndStruct(weeniePtr, MaxHealthType, &maxValue) != 0 && maxValue._currentLevel > 0)
|
||||
{
|
||||
maxHealth = maxValue._currentLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryGetSnapshot(out PlayerVitalsSnapshot snapshot)
|
||||
{
|
||||
lock (CacheLock)
|
||||
{
|
||||
snapshot = _snapshot;
|
||||
return snapshot.Health > 0 || snapshot.MaxHealth > 0 ||
|
||||
snapshot.Stamina > 0 || snapshot.MaxStamina > 0 ||
|
||||
snapshot.Mana > 0 || snapshot.MaxMana > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when the player's own IdentifyObject (0xC9) response arrives,
|
||||
/// providing exact max vitals from the CreatureProfile section.
|
||||
/// </summary>
|
||||
public static void SeedMaxVitalsFromIdentify(uint maxHealth, uint maxStamina, uint maxMana)
|
||||
{
|
||||
if (maxHealth == 0 && maxStamina == 0 && maxMana == 0)
|
||||
return;
|
||||
|
||||
lock (CacheLock)
|
||||
{
|
||||
_snapshot = _snapshot with
|
||||
{
|
||||
MaxHealth = maxHealth > 0 ? maxHealth : _snapshot.MaxHealth,
|
||||
MaxStamina = maxStamina > 0 ? maxStamina : _snapshot.MaxStamina,
|
||||
MaxMana = maxMana > 0 ? maxMana : _snapshot.MaxMana
|
||||
};
|
||||
RynthLog.Compat($"Compat: player max vitals from identify hp={maxHealth} st={maxStamina} mn={maxMana}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called from QueryHealthResponseDetour when the player's own health ratio arrives.
|
||||
/// Computes trueMax = currentHealth / ratio, giving an accurate max immediately
|
||||
/// instead of waiting for regen to converge.
|
||||
/// </summary>
|
||||
public static void UpdateMaxFromHealthRatio(float healthRatio)
|
||||
{
|
||||
if (healthRatio <= 0f || healthRatio > 1f)
|
||||
return;
|
||||
|
||||
lock (CacheLock)
|
||||
{
|
||||
if (_snapshot.Health == 0)
|
||||
return;
|
||||
|
||||
uint derivedMax = (uint)Math.Round(_snapshot.Health / (double)healthRatio);
|
||||
if (derivedMax > _snapshot.MaxHealth)
|
||||
{
|
||||
_snapshot = _snapshot with { MaxHealth = derivedMax };
|
||||
RynthLog.Compat($"Compat: player MaxHealth derived from ratio={healthRatio:0.000} hp={_snapshot.Health} → max={derivedMax}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint HandleUpdateAttribute2ndDetour(IntPtr thisPtr, byte wts, uint sender, uint stype, SecondaryAttributeNative* val)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, SecondaryAttributeNative*, uint>)_originalUpdateAttribute2ndPtr;
|
||||
uint result = original(thisPtr, wts, sender, stype, val);
|
||||
UpdateCacheFromAttribute(sender, stype, val, isPrivate: false);
|
||||
return result;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint HandleUpdateAttribute2ndLevelDetour(IntPtr thisPtr, byte wts, uint sender, uint stype, int val)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, int, uint>)_originalUpdateAttribute2ndLevelPtr;
|
||||
uint result = original(thisPtr, wts, sender, stype, val);
|
||||
UpdateCache(sender, stype, val, isPrivate: false);
|
||||
return result;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint HandlePrivateUpdateAttribute2ndDetour(IntPtr thisPtr, byte wts, uint stype, SecondaryAttributeNative* val)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, SecondaryAttributeNative*, uint>)_originalPrivateUpdateAttribute2ndPtr;
|
||||
uint result = original(thisPtr, wts, stype, val);
|
||||
UpdateCacheFromAttribute(0, stype, val, isPrivate: true);
|
||||
return result;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint HandlePrivateUpdateAttribute2ndLevelDetour(IntPtr thisPtr, byte wts, uint stype, int val)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, int, uint>)_originalPrivateUpdateAttribute2ndLevelPtr;
|
||||
uint result = original(thisPtr, wts, stype, val);
|
||||
UpdateCache(0, stype, val, isPrivate: true);
|
||||
return result;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe void HandleOnStatUpdatedIntDetour(IntPtr thisPtr, uint stype, int val)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, uint, int, void>)_originalOnStatUpdatedIntPtr;
|
||||
original(thisPtr, stype, val);
|
||||
|
||||
// Cache MaxHealth for every object — used by CombatActionHooks to resolve the
|
||||
// absolute target health from the healthRatio in QueryHealthResponse packets.
|
||||
if (stype == MaxHealthType && val > 0)
|
||||
ObjectQualityCache.SetMaxHealth(thisPtr, unchecked((uint)val));
|
||||
|
||||
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out uint playerId, out _))
|
||||
return;
|
||||
|
||||
if (player == IntPtr.Zero || thisPtr != player)
|
||||
return;
|
||||
|
||||
UpdateCache(playerId, stype, val, isPrivate: false);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static unsafe byte HandleSendNoticePlayerDescReceivedDetour(IntPtr playerDescPtr, IntPtr playerModulePtr)
|
||||
{
|
||||
var original = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, byte>)_originalSendNoticePlayerDescReceivedPtr;
|
||||
byte result = original(playerDescPtr, playerModulePtr);
|
||||
SeedSnapshotFromQualities(playerDescPtr);
|
||||
ClientObjectHooks.SetKnownPlayerQualitiesPtr(playerDescPtr);
|
||||
KnownPlayerQualitiesPtr = playerDescPtr;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static unsafe void UpdateCacheFromAttribute(uint sender, uint stype, SecondaryAttributeNative* val, bool isPrivate)
|
||||
{
|
||||
if (val == null)
|
||||
return;
|
||||
|
||||
UpdateCache(sender, stype, unchecked((int)val->_currentLevel), isPrivate);
|
||||
|
||||
// For max-vital types (MaxHealth=1, MaxStamina=3, MaxMana=5), _currentLevel is the
|
||||
// effective buffed maximum — that's already handled by the UpdateCache call above.
|
||||
//
|
||||
// For current-vital types (Health=2, Stamina=4, Mana=6), do NOT derive max from
|
||||
// _initLevel + _levelFromCp — that's the unbuffed base max and would overwrite the
|
||||
// correct buffed value set by the seed or a direct MaxHealth update.
|
||||
}
|
||||
|
||||
private static void UpdateCache(uint sender, uint stype, int val, bool isPrivate)
|
||||
{
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId == 0)
|
||||
return;
|
||||
|
||||
if (!isPrivate && sender != playerId)
|
||||
return;
|
||||
|
||||
if (val < 0)
|
||||
return;
|
||||
|
||||
uint value = unchecked((uint)val);
|
||||
bool changed = false;
|
||||
|
||||
lock (CacheLock)
|
||||
{
|
||||
PlayerVitalsSnapshot current = _snapshot;
|
||||
PlayerVitalsSnapshot updated = stype switch
|
||||
{
|
||||
MaxHealthType => current with { MaxHealth = value },
|
||||
HealthType => current with { Health = value },
|
||||
MaxStaminaType => current with { MaxStamina = value },
|
||||
StaminaType => current with { Stamina = value },
|
||||
MaxManaType => current with { MaxMana = value },
|
||||
ManaType => current with { Mana = value },
|
||||
_ => current
|
||||
};
|
||||
|
||||
// "Highest value seen" — if a current vital exceeds the stored max,
|
||||
// bump the max. Over time this converges to the true maximum as the
|
||||
// player regenerates.
|
||||
if (stype == HealthType && updated.Health > updated.MaxHealth)
|
||||
updated = updated with { MaxHealth = updated.Health };
|
||||
if (stype == StaminaType && updated.Stamina > updated.MaxStamina)
|
||||
updated = updated with { MaxStamina = updated.Stamina };
|
||||
if (stype == ManaType && updated.Mana > updated.MaxMana)
|
||||
updated = updated with { MaxMana = updated.Mana };
|
||||
|
||||
changed = !EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated);
|
||||
if (changed)
|
||||
_snapshot = updated;
|
||||
}
|
||||
|
||||
if (changed && _updateLogCount < 0)
|
||||
{
|
||||
_updateLogCount++;
|
||||
string scope = isPrivate ? "private" : $"sender=0x{sender:X8}";
|
||||
RynthLog.Compat($"Compat: player vital update #{_updateLogCount} {scope} stype={stype} value={value}");
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe void SeedSnapshotFromQualities(IntPtr playerDescPtr)
|
||||
{
|
||||
if (playerDescPtr == IntPtr.Zero || _inqAttribute2ndStruct == null)
|
||||
return;
|
||||
|
||||
if (!TryReadSecondary(playerDescPtr, HealthType, out uint health, out uint maxHealth) &&
|
||||
!TryReadSecondary(playerDescPtr, StaminaType, out uint stamina, out uint maxStamina) &&
|
||||
!TryReadSecondary(playerDescPtr, ManaType, out uint mana, out uint maxMana))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TryReadSecondary(playerDescPtr, HealthType, out health, out maxHealth);
|
||||
TryReadSecondary(playerDescPtr, StaminaType, out stamina, out maxStamina);
|
||||
TryReadSecondary(playerDescPtr, ManaType, out mana, out maxMana);
|
||||
|
||||
bool changed = false;
|
||||
lock (CacheLock)
|
||||
{
|
||||
PlayerVitalsSnapshot current = _snapshot;
|
||||
// Use "highest seen" for max vitals — seed values from InqAttribute2ndStruct
|
||||
// return current health as max, so never overwrite a higher known max.
|
||||
uint bestMaxHealth = maxHealth != 0 ? Math.Max(maxHealth, current.MaxHealth) : current.MaxHealth;
|
||||
uint bestMaxStamina = maxStamina != 0 ? Math.Max(maxStamina, current.MaxStamina) : current.MaxStamina;
|
||||
uint bestMaxMana = maxMana != 0 ? Math.Max(maxMana, current.MaxMana) : current.MaxMana;
|
||||
|
||||
// Also ensure current vital doesn't exceed max
|
||||
if (health > bestMaxHealth) bestMaxHealth = health;
|
||||
if (stamina > bestMaxStamina) bestMaxStamina = stamina;
|
||||
if (mana > bestMaxMana) bestMaxMana = mana;
|
||||
|
||||
PlayerVitalsSnapshot updated = current with
|
||||
{
|
||||
Health = health != 0 ? health : current.Health,
|
||||
MaxHealth = bestMaxHealth,
|
||||
Stamina = stamina != 0 ? stamina : current.Stamina,
|
||||
MaxStamina = bestMaxStamina,
|
||||
Mana = mana != 0 ? mana : current.Mana,
|
||||
MaxMana = bestMaxMana
|
||||
};
|
||||
|
||||
changed = !EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated);
|
||||
if (changed)
|
||||
_snapshot = updated;
|
||||
}
|
||||
|
||||
if (changed && _seedLogCount < 1)
|
||||
{
|
||||
_seedLogCount++;
|
||||
RynthLog.Compat($"Compat: player vitals seeded from player desc #{_seedLogCount} hp={health}/{maxHealth} st={stamina}/{maxStamina} mn={mana}/{maxMana}");
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe bool TryReadSecondary(IntPtr playerDescPtr, uint stype, out uint current, out uint max)
|
||||
{
|
||||
current = 0;
|
||||
max = 0;
|
||||
|
||||
if (_inqAttribute2ndStruct == null)
|
||||
return false;
|
||||
|
||||
SecondaryAttributeNative value = default;
|
||||
if (_inqAttribute2ndStruct(playerDescPtr, stype, &value) == 0)
|
||||
return false;
|
||||
|
||||
current = value._currentLevel;
|
||||
|
||||
// Query the max-vital attribute type (e.g. MaxHealth=1 for Health=2) to get the
|
||||
// buffed effective maximum via its _currentLevel. Fall back to the base formula
|
||||
// (_initLevel + _levelFromCp) if the max-vital query fails or returns zero.
|
||||
uint maxStype = ToMaxStatType(stype);
|
||||
if (maxStype != stype)
|
||||
{
|
||||
SecondaryAttributeNative maxValue = default;
|
||||
if (_inqAttribute2ndStruct(playerDescPtr, maxStype, &maxValue) != 0 && maxValue._currentLevel != 0)
|
||||
{
|
||||
max = maxValue._currentLevel;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
max = value._initLevel + value._levelFromCp;
|
||||
return current != 0 || max != 0;
|
||||
}
|
||||
|
||||
private static uint ToMaxStatType(uint stype)
|
||||
{
|
||||
return stype switch
|
||||
{
|
||||
HealthType => MaxHealthType,
|
||||
StaminaType => MaxStaminaType,
|
||||
ManaType => MaxManaType,
|
||||
_ => stype
|
||||
};
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct AttributeNative
|
||||
{
|
||||
public IntPtr _packObj;
|
||||
public uint _levelFromCp;
|
||||
public uint _initLevel;
|
||||
public uint _cpSpent;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct SecondaryAttributeNative
|
||||
{
|
||||
public AttributeNative _attribute;
|
||||
public uint _currentLevel;
|
||||
|
||||
public uint _levelFromCp => _attribute._levelFromCp;
|
||||
public uint _initLevel => _attribute._initLevel;
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private unsafe delegate int InqAttribute2ndStructDelegate(IntPtr thisPtr, uint stype, SecondaryAttributeNative* retval);
|
||||
}
|
||||
83
src/RynthCore.Engine/Compatibility/RawOpcodeTracker.cs
Normal file
83
src/RynthCore.Engine/Compatibility/RawOpcodeTracker.cs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe store for raw opcode observations captured by RawPacketHooks.
|
||||
/// Populated on the network receive thread; read on the ImGui render thread.
|
||||
/// </summary>
|
||||
internal static class RawOpcodeTracker
|
||||
{
|
||||
public struct OpcodeEntry
|
||||
{
|
||||
public int Count;
|
||||
public int LastPayloadLen;
|
||||
public byte[] LastSample; // up to 16 bytes of the most recent payload
|
||||
}
|
||||
|
||||
// Opcodes already handled by SmartBoxHooks — shown only when ShowKnown is true.
|
||||
private static readonly HashSet<ushort> KnownOpcodes =
|
||||
[
|
||||
0xF74B, 0xF74C, 0xF74E, 0xF7DB, 0xF7B0, 0xF658
|
||||
];
|
||||
|
||||
private static readonly object _lock = new();
|
||||
private static readonly Dictionary<ushort, OpcodeEntry> _entries = new();
|
||||
|
||||
public static bool Frozen;
|
||||
public static bool ShowKnown = false;
|
||||
public static bool ShowUnknown = true;
|
||||
|
||||
public static bool IsKnown(ushort opcode) => KnownOpcodes.Contains(opcode);
|
||||
|
||||
public static unsafe void Track(ushort opcode, byte* payload, int payloadLen)
|
||||
{
|
||||
if (Frozen) return;
|
||||
|
||||
int sampleLen = payloadLen < 16 ? payloadLen : 16;
|
||||
byte[] sample = new byte[sampleLen];
|
||||
for (int i = 0; i < sampleLen; i++)
|
||||
sample[i] = payload[i];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (_entries.TryGetValue(opcode, out OpcodeEntry existing))
|
||||
{
|
||||
existing.Count++;
|
||||
existing.LastPayloadLen = payloadLen;
|
||||
existing.LastSample = sample;
|
||||
_entries[opcode] = existing;
|
||||
}
|
||||
else
|
||||
{
|
||||
_entries[opcode] = new OpcodeEntry
|
||||
{
|
||||
Count = 1,
|
||||
LastPayloadLen = payloadLen,
|
||||
LastSample = sample
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Clear()
|
||||
{
|
||||
lock (_lock)
|
||||
_entries.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Returns a snapshot of all tracked entries sorted by opcode for rendering.</summary>
|
||||
public static (ushort Opcode, OpcodeEntry Entry)[] GetSnapshot()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var result = new (ushort, OpcodeEntry)[_entries.Count];
|
||||
int i = 0;
|
||||
foreach (var kv in _entries)
|
||||
result[i++] = (kv.Key, kv.Value);
|
||||
Array.Sort(result, (a, b) => a.Item1.CompareTo(b.Item1));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
86
src/RynthCore.Engine/Compatibility/RawPacketHooks.cs
Normal file
86
src/RynthCore.Engine/Compatibility/RawPacketHooks.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks the game's recvfrom socket function to intercept all S2C UDP packets.
|
||||
///
|
||||
/// The acclient.exe data segment holds a pointer to the recvfrom implementation:
|
||||
/// RecvFrom @ *(int*)0x007935AC
|
||||
/// SendTo @ *(int*)0x007935A4 (not hooked — S2C discovery only)
|
||||
///
|
||||
/// We read the function address, install a MinHook detour, call through to the
|
||||
/// original on every receive, then hand the buffer to RawPacketParser for
|
||||
/// opcode extraction. The hook is purely read-only and never modifies traffic.
|
||||
/// </summary>
|
||||
internal static class RawPacketHooks
|
||||
{
|
||||
private const int RecvFromPtrAddr = unchecked((int)0x007935AC);
|
||||
|
||||
private static IntPtr _originalRecvFromPtr;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled) return;
|
||||
|
||||
unsafe
|
||||
{
|
||||
IntPtr fnPtrAddr = new IntPtr(RecvFromPtrAddr);
|
||||
if (!SmartBoxLocator.IsMemoryReadable(fnPtrAddr, 4))
|
||||
{
|
||||
RynthLog.Compat("RawPacket: RecvFrom pointer address 0x007935AC not readable — skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
IntPtr recvFromAddr = Marshal.ReadIntPtr(fnPtrAddr);
|
||||
if (recvFromAddr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Compat("RawPacket: RecvFrom pointer is null — skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int> pDetour = &RecvFromDetour;
|
||||
MinHook.Hook(recvFromAddr, (IntPtr)pDetour, out _originalRecvFromPtr);
|
||||
IsInstalled = true;
|
||||
RynthLog.Compat($"RawPacket: RecvFrom hook installed @ 0x{recvFromAddr.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"RawPacket: MinHook failed — {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
|
||||
private static unsafe int RecvFromDetour(
|
||||
IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen)
|
||||
{
|
||||
delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int> original =
|
||||
(delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int>)_originalRecvFromPtr;
|
||||
|
||||
int bytesRead = original(s, buf, len, flags, from, fromlen);
|
||||
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
// Managed exceptions (bounds errors, etc.) CAN be caught in NativeAOT.
|
||||
// This guard prevents any parser bug from crashing the client.
|
||||
try
|
||||
{
|
||||
RawPacketParser.Parse((byte*)buf, bytesRead);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// silently swallow — never affect game traffic
|
||||
}
|
||||
}
|
||||
|
||||
return bytesRead;
|
||||
}
|
||||
}
|
||||
64
src/RynthCore.Engine/Compatibility/RawPacketParser.cs
Normal file
64
src/RynthCore.Engine/Compatibility/RawPacketParser.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Minimal parser for Asheron's Call S2C UDP packets.
|
||||
///
|
||||
/// Packet layout:
|
||||
/// [Header — 20 bytes]
|
||||
/// +0 SeqNo uint32
|
||||
/// +4 RecID uint32
|
||||
/// +8 Checksum uint32
|
||||
/// +12 Flags uint32
|
||||
/// +16 Time uint16
|
||||
/// +18 Size uint16
|
||||
///
|
||||
/// [One or more BlobFragments follow, contiguously]
|
||||
/// BlobFragHeader (16 bytes):
|
||||
/// +0 BlobId uint64
|
||||
/// +8 NumFrags uint16
|
||||
/// +10 FragSize uint16 ← payload bytes immediately following this header
|
||||
/// +12 FragIndex uint16
|
||||
/// +14 QueueID uint16 ← THIS IS THE OPCODE
|
||||
///
|
||||
/// [FragSize bytes of payload]
|
||||
/// [Next BlobFragHeader starts immediately after]
|
||||
///
|
||||
/// Checksum validation is intentionally skipped — we are read-only observers.
|
||||
/// </summary>
|
||||
internal static class RawPacketParser
|
||||
{
|
||||
private const int PacketHeaderSize = 20;
|
||||
private const int BlobHeaderSize = 16;
|
||||
private const int FragSizeOffset = 10;
|
||||
private const int QueueIdOffset = 14;
|
||||
private const int MaxBlobsPerPacket = 64; // guard against malformed packets
|
||||
|
||||
public static unsafe void Parse(byte* data, int length)
|
||||
{
|
||||
if (length < PacketHeaderSize)
|
||||
return;
|
||||
|
||||
int offset = PacketHeaderSize;
|
||||
int blobCount = 0;
|
||||
|
||||
while (offset + BlobHeaderSize <= length && blobCount++ < MaxBlobsPerPacket)
|
||||
{
|
||||
ushort fragSize = (ushort)(data[offset + FragSizeOffset] | (data[offset + FragSizeOffset + 1] << 8));
|
||||
ushort queueId = (ushort)(data[offset + QueueIdOffset] | (data[offset + QueueIdOffset + 1] << 8));
|
||||
|
||||
int payloadStart = offset + BlobHeaderSize;
|
||||
int payloadEnd = payloadStart + fragSize;
|
||||
|
||||
// Bounds check before touching any payload bytes
|
||||
if (payloadEnd > length || payloadEnd < payloadStart)
|
||||
break;
|
||||
|
||||
if (queueId != 0)
|
||||
RawOpcodeTracker.Track(queueId, data + payloadStart, fragSize);
|
||||
|
||||
offset = payloadEnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
97
src/RynthCore.Engine/Compatibility/SelectedTargetHooks.cs
Normal file
97
src/RynthCore.Engine/Compatibility/SelectedTargetHooks.cs
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class SelectedTargetHooks
|
||||
{
|
||||
private const int SetSelectedObjectVa = 0x0058D110;
|
||||
private const int SelectedIdVa = 0x00871E54;
|
||||
private static readonly byte[] SetSelectedObjectSignature =
|
||||
[
|
||||
0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54,
|
||||
0x1E, 0x87, 0x00, 0x56, 0x8B, 0x74, 0x24, 0x08,
|
||||
0x57, 0x8B, 0xF8, 0x75, 0x04, 0x3B, 0xC6, 0x74,
|
||||
0x7A, 0x85, 0xC0, 0x74, 0x14, 0x50, 0xE8
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetSelectedObjectDelegate(uint selectedId, int reselect);
|
||||
|
||||
private static SetSelectedObjectDelegate? _originalSetSelectedObject;
|
||||
private static SetSelectedObjectDelegate? _setSelectedObjectDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = SetSelectedObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, SetSelectedObjectSignature))
|
||||
{
|
||||
_statusMessage = $"ACCWeenieObject::SetSelectedObject signature mismatch @ 0x{SetSelectedObjectVa:X8}.";
|
||||
RynthLog.Compat($"Compat: selected-target hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_setSelectedObjectDetour = SetSelectedObjectDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setSelectedObjectDetour);
|
||||
_originalSetSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked ACCWeenieObject::SetSelectedObject @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat(
|
||||
$"Compat: selected-target hook ready - SetSelectedObject=0x{_targetAddress.ToInt32():X8}, selectedId=0x{SelectedIdVa:X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: selected-target hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetSelectedObjectDetour(uint selectedId, int reselect)
|
||||
{
|
||||
uint previousTargetId = ReadUInt32(SelectedIdVa);
|
||||
|
||||
try
|
||||
{
|
||||
_originalSetSelectedObject!(selectedId, reselect);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: selected-target detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
throw;
|
||||
}
|
||||
|
||||
uint currentTargetId = ReadUInt32(SelectedIdVa);
|
||||
if (currentTargetId == previousTargetId)
|
||||
return;
|
||||
|
||||
PluginManager.QueueSelectedTargetChange(currentTargetId, previousTargetId);
|
||||
}
|
||||
|
||||
private static uint ReadUInt32(int address)
|
||||
{
|
||||
return unchecked((uint)Marshal.ReadInt32(new IntPtr(address)));
|
||||
}
|
||||
}
|
||||
146
src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs
Normal file
146
src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class SessionStateRegistry
|
||||
{
|
||||
private static bool _initialized;
|
||||
private static bool _loginRecorded;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_initialized)
|
||||
return;
|
||||
|
||||
_initialized = true;
|
||||
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
|
||||
}
|
||||
|
||||
public static void Poll()
|
||||
{
|
||||
if (_loginRecorded || !LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
return;
|
||||
|
||||
TryWriteLoginState();
|
||||
}
|
||||
|
||||
private static void OnLoginComplete()
|
||||
{
|
||||
TryWriteLoginState();
|
||||
}
|
||||
|
||||
private static void TryWriteLoginState()
|
||||
{
|
||||
if (_loginRecorded)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
SessionStateRecord? existingRecord = SessionStateStore.TryReadForProcess(Environment.ProcessId);
|
||||
(string accountName, string serverName, string targetCharacter) = ReadLaunchContext();
|
||||
|
||||
accountName = Coalesce(accountName, existingRecord?.AccountName);
|
||||
serverName = Coalesce(serverName, existingRecord?.ServerName);
|
||||
targetCharacter = Coalesce(targetCharacter, existingRecord?.TargetCharacter);
|
||||
|
||||
string characterName = ResolveCharacterName(targetCharacter);
|
||||
if (string.IsNullOrWhiteSpace(characterName))
|
||||
characterName = Coalesce(existingRecord?.CharacterName, targetCharacter);
|
||||
|
||||
var record = new SessionStateRecord
|
||||
{
|
||||
ProcessId = Environment.ProcessId,
|
||||
AccountName = accountName,
|
||||
ServerName = serverName,
|
||||
TargetCharacter = targetCharacter,
|
||||
CharacterName = characterName,
|
||||
LaunchStartedAtUtc = existingRecord?.LaunchStartedAtUtc ?? GetProcessStartTimeUtc(),
|
||||
LoginCompletedAtUtc = DateTime.UtcNow,
|
||||
IsLoggedIn = true
|
||||
};
|
||||
|
||||
SessionStateStore.WriteForProcess(Environment.ProcessId, record);
|
||||
if (!string.IsNullOrWhiteSpace(accountName) && !string.IsNullOrWhiteSpace(characterName))
|
||||
CharacterCacheStore.UpsertCharacter(accountName, serverName, characterName);
|
||||
|
||||
_loginRecorded = true;
|
||||
RynthLog.Compat($"SessionState: recorded login session for PID {Environment.ProcessId} account='{accountName}' character='{characterName}'.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"SessionState: failed to record login session - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveCharacterName(string fallbackCharacter)
|
||||
{
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId != 0 && ClientObjectHooks.TryGetObjectName(playerId, out string actualName) && !string.IsNullOrWhiteSpace(actualName))
|
||||
return actualName;
|
||||
|
||||
return fallbackCharacter ?? string.Empty;
|
||||
}
|
||||
|
||||
private static DateTime GetProcessStartTimeUtc()
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process process = Process.GetCurrentProcess();
|
||||
return process.StartTime.ToUniversalTime();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContext()
|
||||
{
|
||||
try
|
||||
{
|
||||
string rootDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore");
|
||||
|
||||
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
|
||||
(string accountName, string serverName, string targetCharacter) processContext = ReadLaunchContextFile(processPath);
|
||||
if (!string.IsNullOrWhiteSpace(processContext.accountName) ||
|
||||
!string.IsNullOrWhiteSpace(processContext.serverName) ||
|
||||
!string.IsNullOrWhiteSpace(processContext.targetCharacter))
|
||||
{
|
||||
return processContext;
|
||||
}
|
||||
|
||||
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (string.Empty, string.Empty, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
return (string.Empty, string.Empty, string.Empty);
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(filePath));
|
||||
JsonElement root = doc.RootElement;
|
||||
string accountName = root.TryGetProperty("AccountName", out JsonElement an) ? an.GetString() ?? string.Empty : string.Empty;
|
||||
string serverName = root.TryGetProperty("ServerName", out JsonElement sn) ? sn.GetString() ?? string.Empty : string.Empty;
|
||||
string target = root.TryGetProperty("TargetCharacter", out JsonElement tc) ? tc.GetString() ?? string.Empty : string.Empty;
|
||||
return (accountName, serverName, target);
|
||||
}
|
||||
|
||||
private static string Coalesce(string? primary, string? fallback)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(primary))
|
||||
return primary.Trim();
|
||||
|
||||
return fallback?.Trim() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
279
src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs
Normal file
279
src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class SmartBoxHooks
|
||||
{
|
||||
private const int NetBlobBufPtrOffset = 0x2C;
|
||||
private const int NetBlobBufSizeOffset = 0x30;
|
||||
private const uint PositionUpdateOpcode = 0x0000F74C;
|
||||
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
|
||||
private const uint VectorUpdateOpcode = 0x0000F74E;
|
||||
private const uint UpdateObjectOpcode = 0x0000F7DB;
|
||||
private const uint GameEventOpcode = 0x0000F7B0;
|
||||
|
||||
// ACSmartBox::DispatchSmartBoxEvent
|
||||
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
|
||||
private static readonly byte?[] DispatchSmartBoxEventPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
|
||||
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
|
||||
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
|
||||
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
|
||||
];
|
||||
|
||||
// ACGame::DispatchGameEvent
|
||||
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
|
||||
private static readonly byte?[] DispatchGameEventPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
|
||||
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
|
||||
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
|
||||
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
|
||||
];
|
||||
|
||||
private static IntPtr _originalDispatchSmartBoxEventPtr;
|
||||
private static IntPtr _originalDispatchGameEventPtr;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
private static readonly object _initLock = new();
|
||||
public static void Initialize()
|
||||
{
|
||||
lock (_initLock)
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
var hookedAddresses = new HashSet<IntPtr>();
|
||||
|
||||
// Hook SmartBox Event
|
||||
int sbOff = PatternScanner.FindPattern(textSection.Bytes, DispatchSmartBoxEventPattern);
|
||||
if (sbOff >= 0)
|
||||
{
|
||||
IntPtr sbAddr = new IntPtr(textSection.TextBaseVa + sbOff);
|
||||
if (hookedAddresses.Add(sbAddr))
|
||||
{
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint> pSbDetour = &DispatchSmartBoxEventDetour;
|
||||
MinHook.Hook(sbAddr, (IntPtr)pSbDetour, out _originalDispatchSmartBoxEventPtr);
|
||||
RynthLog.Compat($"Compat: smartbox hook ready @ 0x{sbAddr.ToInt32():X8}");
|
||||
}
|
||||
}
|
||||
else RynthLog.Compat("Compat: smartbox pattern not found.");
|
||||
|
||||
// Hook Game Event
|
||||
int geOff = PatternScanner.FindPattern(textSection.Bytes, DispatchGameEventPattern);
|
||||
if (geOff >= 0)
|
||||
{
|
||||
IntPtr geAddr = new IntPtr(textSection.TextBaseVa + geOff);
|
||||
if (hookedAddresses.Add(geAddr))
|
||||
{
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint> pGeDetour = &DispatchGameEventDetour;
|
||||
MinHook.Hook(geAddr, (IntPtr)pGeDetour, out _originalDispatchGameEventPtr);
|
||||
RynthLog.Compat($"Compat: game-event hook ready @ 0x{geAddr.ToInt32():X8}");
|
||||
}
|
||||
else RynthLog.Compat("Compat: game-event pattern matched already-hooked address.");
|
||||
}
|
||||
else RynthLog.Compat("Compat: game-event pattern not found.");
|
||||
}
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = "Hooks installed.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: hooks failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint DispatchSmartBoxEventDetour(IntPtr thisPtr, IntPtr blob)
|
||||
{
|
||||
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint>)_originalDispatchSmartBoxEventPtr;
|
||||
|
||||
if (!LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: false);
|
||||
return pOriginal(thisPtr, blob);
|
||||
}
|
||||
|
||||
SmartBoxEventInfo info = ReadSmartBoxEventInfo(blob);
|
||||
uint status = pOriginal(thisPtr, blob);
|
||||
|
||||
TryQueueHealthUpdate(blob, info);
|
||||
|
||||
// Game events arrive as 0xF7B0 wrapper: [F7B0][playerId][seq][innerEventType][...]
|
||||
// Check for IdentifyObject response (inner event 0xC9) after the original processes it.
|
||||
if (info.Opcode == GameEventOpcode)
|
||||
TryHandleGameEvent(blob, info);
|
||||
else if (info.Opcode == 0xC9 && info.RawObjectId != 0)
|
||||
TryCacheVitalsFromIdentify(info.RawObjectId);
|
||||
|
||||
if (info.RawObjectId != 0 &&
|
||||
(info.Opcode == PositionUpdateOpcode ||
|
||||
info.Opcode == PlayerPositionUpdateOpcode ||
|
||||
info.Opcode == VectorUpdateOpcode ||
|
||||
info.Opcode == UpdateObjectOpcode))
|
||||
{
|
||||
PluginManager.QueueUpdateObject(info.RawObjectId);
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe uint DispatchGameEventDetour(IntPtr thisPtr, IntPtr blob)
|
||||
{
|
||||
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint>)_originalDispatchGameEventPtr;
|
||||
|
||||
// Log game event opcodes for discovery
|
||||
SmartBoxEventInfo info = ReadSmartBoxEventInfo(blob);
|
||||
TryQueueHealthUpdate(blob, info);
|
||||
|
||||
// Always attempt capture from game events (pre-login)
|
||||
CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: true);
|
||||
|
||||
uint result = pOriginal(thisPtr, blob);
|
||||
|
||||
// After the original handler processes 0xC9 (IdentifyObject response),
|
||||
// the weenie's qualities are populated — read maxHealth and cache it.
|
||||
if (info.Opcode == 0xC9 && info.RawObjectId != 0)
|
||||
TryCacheVitalsFromIdentify(info.RawObjectId);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
|
||||
{
|
||||
if (blob == IntPtr.Zero)
|
||||
return default;
|
||||
|
||||
try
|
||||
{
|
||||
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
|
||||
if (blobSize < sizeof(uint))
|
||||
return new SmartBoxEventInfo(0, 0, blobSize);
|
||||
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return new SmartBoxEventInfo(0, 0, blobSize);
|
||||
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
|
||||
uint rawObjectId = blobSize >= 8
|
||||
? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))))
|
||||
: 0;
|
||||
return new SmartBoxEventInfo(opcode, rawObjectId, blobSize);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryQueueHealthUpdate(IntPtr blob, SmartBoxEventInfo info)
|
||||
{
|
||||
if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 4)));
|
||||
float ratio = Marshal.PtrToStructure<float>(IntPtr.Add(payloadPtr, 8));
|
||||
|
||||
uint maxHealth = 0;
|
||||
uint currentHealth = 0;
|
||||
if (ClientObjectHooks.TryGetWeenieObjectPtr(targetId, out IntPtr pWeenie))
|
||||
{
|
||||
if (ObjectQualityCache.TryGetMaxHealth(pWeenie, out uint cached))
|
||||
{
|
||||
maxHealth = cached;
|
||||
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
|
||||
}
|
||||
}
|
||||
|
||||
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static int _identifyLogCount;
|
||||
|
||||
private static void TryHandleGameEvent(IntPtr blob, SmartBoxEventInfo info)
|
||||
{
|
||||
// 0xF7B0 game event layout: [0xF7B0(4)][playerId(4)][sequence(4)][innerEventType(4)][eventData...]
|
||||
// Minimum size: 16 bytes for the header
|
||||
if (blob == IntPtr.Zero || info.BlobSize < 16)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
uint innerEvent = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 12)));
|
||||
|
||||
// 0xC9 = IdentifyObject response
|
||||
// Layout after inner event type: [objectId(4)][flags(4)][success(4)][data...]
|
||||
if (innerEvent == 0xC9 && info.BlobSize >= 20)
|
||||
{
|
||||
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 16)));
|
||||
if (objectId != 0)
|
||||
TryCacheVitalsFromIdentify(objectId);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryCacheVitalsFromIdentify(uint objectId)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr pWeenie) || pWeenie == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
// We're on the game thread (DispatchGameEvent), so InqAttribute2ndStruct is safe.
|
||||
if (PlayerVitalsHooks.TryReadObjectMaxHealth(pWeenie, out uint maxHealth) && maxHealth > 0)
|
||||
{
|
||||
ObjectQualityCache.SetMaxHealth(pWeenie, maxHealth);
|
||||
|
||||
int count = Interlocked.Increment(ref _identifyLogCount);
|
||||
if (count <= 12)
|
||||
RynthLog.Compat($"Compat: identify 0xC9 obj=0x{objectId:X8} maxHealth={maxHealth}");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct SmartBoxEventInfo(uint Opcode, uint RawObjectId, uint BlobSize);
|
||||
}
|
||||
350
src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs
Normal file
350
src/RynthCore.Engine/Compatibility/SmartBoxLocator.cs
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class SmartBoxLocator
|
||||
{
|
||||
public const int SmartBoxCmdInterpOffset = 0xB8;
|
||||
public const int SmartBoxPlayerIdOffset = 0xF4;
|
||||
public const int SmartBoxPlayerOffset = 0xF8;
|
||||
|
||||
private static IntPtr _smartboxStaticAddr;
|
||||
private static IntPtr _moduleBase;
|
||||
private static int _imageSize;
|
||||
private static readonly List<IntPtr> _smartboxStaticCandidates = [];
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
// ─── VirtualQuery-based memory validation ────────────────────────────
|
||||
[DllImport("kernel32.dll", SetLastError = false)]
|
||||
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MEMORY_BASIC_INFORMATION
|
||||
{
|
||||
public IntPtr BaseAddress;
|
||||
public IntPtr AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public IntPtr RegionSize;
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
}
|
||||
|
||||
private const uint MEM_COMMIT = 0x1000;
|
||||
private const uint PAGE_NOACCESS = 0x01;
|
||||
private const uint PAGE_GUARD = 0x100;
|
||||
private const uint READABLE_MASK = 0x02 | 0x04 | 0x08 | 0x20 | 0x40 | 0x80;
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the given memory range is committed and readable without triggering an AV.
|
||||
/// Uses VirtualQuery — safe to call on any address including unmapped pages.
|
||||
/// Critical for NativeAOT where AccessViolationException cannot be caught.
|
||||
/// </summary>
|
||||
public static bool IsMemoryReadable(IntPtr address, int size)
|
||||
{
|
||||
if (address == IntPtr.Zero || size <= 0)
|
||||
return false;
|
||||
|
||||
if (VirtualQuery(address, out MEMORY_BASIC_INFORMATION mbi,
|
||||
Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
|
||||
return false;
|
||||
|
||||
if (mbi.State != MEM_COMMIT)
|
||||
return false;
|
||||
if ((mbi.Protect & PAGE_NOACCESS) != 0)
|
||||
return false;
|
||||
if ((mbi.Protect & PAGE_GUARD) != 0)
|
||||
return false;
|
||||
if ((mbi.Protect & READABLE_MASK) == 0)
|
||||
return false;
|
||||
|
||||
// Ensure the committed region covers the full requested range
|
||||
int regionEnd = mbi.BaseAddress.ToInt32() + mbi.RegionSize.ToInt32();
|
||||
int requestEnd = address.ToInt32() + size;
|
||||
return requestEnd <= regionEnd;
|
||||
}
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
public static int CandidateCount => _smartboxStaticCandidates.Count;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
Reset();
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_moduleBase = textSection.ModuleBase;
|
||||
_imageSize = textSection.ImageSize;
|
||||
|
||||
CollectSmartBoxCandidates(textSection.Bytes, textSection.TextBaseVa, textSection.ModuleBase.ToInt32());
|
||||
if (_smartboxStaticCandidates.Count == 0)
|
||||
{
|
||||
_statusMessage = "SmartBox::smartbox static not found.";
|
||||
RynthLog.Compat("Compat: smartbox locator probe failed - SmartBox::smartbox static not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
_smartboxStaticAddr = _smartboxStaticCandidates[0];
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Reset();
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: smartbox locator probe failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetSmartBox(out IntPtr smartBox, out IntPtr smartboxStaticAddr, out string failure)
|
||||
{
|
||||
smartBox = IntPtr.Zero;
|
||||
smartboxStaticAddr = IntPtr.Zero;
|
||||
failure = string.Empty;
|
||||
|
||||
if ((!IsInitialized || _smartboxStaticCandidates.Count == 0) && !Probe())
|
||||
{
|
||||
failure = _statusMessage;
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (IntPtr candidate in EnumerateCandidates())
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr resolved = Marshal.ReadIntPtr(candidate);
|
||||
if (resolved == IntPtr.Zero)
|
||||
{
|
||||
failure = "SmartBox instance not ready.";
|
||||
continue;
|
||||
}
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(resolved);
|
||||
if (!IsPointerInModule(vtable))
|
||||
{
|
||||
failure = $"SmartBox vtable looks invalid (0x{vtable.ToInt32():X8}).";
|
||||
continue;
|
||||
}
|
||||
|
||||
smartBox = resolved;
|
||||
smartboxStaticAddr = candidate;
|
||||
_smartboxStaticAddr = candidate;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failure = ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(failure))
|
||||
failure = "SmartBox instance not ready.";
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryGetPlayer(out IntPtr player, out uint playerId, out string failure)
|
||||
{
|
||||
player = IntPtr.Zero;
|
||||
playerId = 0;
|
||||
|
||||
if (!TryGetSmartBox(out IntPtr smartBox, out _, out failure))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
player = Marshal.ReadIntPtr(smartBox + SmartBoxPlayerOffset);
|
||||
playerId = unchecked((uint)Marshal.ReadInt32(smartBox + SmartBoxPlayerIdOffset));
|
||||
|
||||
if (player == IntPtr.Zero)
|
||||
{
|
||||
failure = playerId != 0
|
||||
? $"Player pointer not ready (playerId=0x{playerId:X8})."
|
||||
: "Player pointer not ready.";
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(player);
|
||||
if (!IsPointerInModule(vtable))
|
||||
{
|
||||
failure = $"Player vtable looks invalid (0x{vtable.ToInt32():X8}).";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failure = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsPointerInModule(IntPtr ptr)
|
||||
{
|
||||
if (ptr == IntPtr.Zero || _moduleBase == IntPtr.Zero || _imageSize <= 0)
|
||||
return false;
|
||||
|
||||
int value = ptr.ToInt32();
|
||||
int start = _moduleBase.ToInt32();
|
||||
int end = start + _imageSize;
|
||||
return value >= start && value < end;
|
||||
}
|
||||
|
||||
private static IEnumerable<IntPtr> EnumerateCandidates()
|
||||
{
|
||||
if (_smartboxStaticAddr != IntPtr.Zero)
|
||||
yield return _smartboxStaticAddr;
|
||||
|
||||
foreach (IntPtr candidate in _smartboxStaticCandidates)
|
||||
{
|
||||
if (candidate == _smartboxStaticAddr)
|
||||
continue;
|
||||
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CollectSmartBoxCandidates(byte[] text, int textBaseVa, int imageBase)
|
||||
{
|
||||
_smartboxStaticCandidates.Clear();
|
||||
|
||||
HashSet<int> seen = [];
|
||||
AddCandidates(FindCmdInterpReferenceCandidates(text, imageBase), seen);
|
||||
AddCandidates(FindCleanupPatternCandidates(text, textBaseVa, imageBase), seen);
|
||||
}
|
||||
|
||||
private static void AddCandidates(IEnumerable<IntPtr> candidates, HashSet<int> seen)
|
||||
{
|
||||
foreach (IntPtr candidate in candidates)
|
||||
{
|
||||
int value = candidate.ToInt32();
|
||||
if (value == 0 || !seen.Add(value))
|
||||
continue;
|
||||
|
||||
_smartboxStaticCandidates.Add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<IntPtr> FindCleanupPatternCandidates(byte[] text, int textBaseVa, int imageBase)
|
||||
{
|
||||
int dataLo = imageBase + 0x400000;
|
||||
int dataHi = imageBase + 0x510000;
|
||||
|
||||
for (int i = 0; i < text.Length - 12; i++)
|
||||
{
|
||||
if (text[i] != 0xC7 || text[i + 1] != 0x05)
|
||||
continue;
|
||||
|
||||
int addr = BitConverter.ToInt32(text, i + 2);
|
||||
if (addr < dataLo || addr > dataHi)
|
||||
continue;
|
||||
|
||||
if (BitConverter.ToInt32(text, i + 6) != 0 || text[i + 10] != 0xC3)
|
||||
continue;
|
||||
|
||||
byte[] loadPat = new byte[5];
|
||||
loadPat[0] = 0xA1;
|
||||
BitConverter.GetBytes(addr).CopyTo(loadPat, 1);
|
||||
|
||||
for (int back = 5; back < 40; back++)
|
||||
{
|
||||
int j = i - back;
|
||||
if (j < 0)
|
||||
break;
|
||||
|
||||
if (!PatternScanner.VerifyBytes(text, j, loadPat))
|
||||
continue;
|
||||
|
||||
for (int k = j + 5; k < j + 10 && k < text.Length - 1; k++)
|
||||
{
|
||||
if (text[k] != 0x85 || text[k + 1] != 0xC0)
|
||||
continue;
|
||||
|
||||
bool hasDtorCall = false;
|
||||
for (int m = k; m < i - 2 && m < text.Length - 3; m++)
|
||||
{
|
||||
if (text[m] == 0x6A && text[m + 1] == 0x01 &&
|
||||
text[m + 2] == 0xFF && text[m + 3] == 0x10)
|
||||
{
|
||||
hasDtorCall = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasDtorCall)
|
||||
{
|
||||
yield return new IntPtr(addr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<IntPtr> FindCmdInterpReferenceCandidates(byte[] text, int imageBase)
|
||||
{
|
||||
int dataLo = imageBase + 0x400000;
|
||||
int dataHi = imageBase + 0x510000;
|
||||
|
||||
for (int i = 0; i < text.Length - 24; i++)
|
||||
{
|
||||
if (text[i] != 0xA1)
|
||||
continue;
|
||||
|
||||
int addr = BitConverter.ToInt32(text, i + 1);
|
||||
if (addr < dataLo || addr > dataHi)
|
||||
continue;
|
||||
|
||||
bool hasNullCheck = false;
|
||||
for (int k = i + 5; k < i + 10 && k < text.Length - 1; k++)
|
||||
{
|
||||
if (text[k] == 0x85 && text[k + 1] == 0xC0)
|
||||
{
|
||||
hasNullCheck = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasNullCheck)
|
||||
continue;
|
||||
|
||||
for (int k = i + 5; k < i + 24 && k < text.Length - 6; k++)
|
||||
{
|
||||
if (text[k] != 0x8B)
|
||||
continue;
|
||||
|
||||
byte modrm = text[k + 1];
|
||||
if ((modrm & 0xC7) != 0x80)
|
||||
continue;
|
||||
|
||||
if (BitConverter.ToInt32(text, k + 2) != SmartBoxCmdInterpOffset)
|
||||
continue;
|
||||
|
||||
yield return new IntPtr(addr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
_smartboxStaticAddr = IntPtr.Zero;
|
||||
_moduleBase = IntPtr.Zero;
|
||||
_imageSize = 0;
|
||||
_smartboxStaticCandidates.Clear();
|
||||
IsInitialized = false;
|
||||
_statusMessage = "Not probed yet.";
|
||||
}
|
||||
}
|
||||
103
src/RynthCore.Engine/Compatibility/TimeSyncHooks.cs
Normal file
103
src/RynthCore.Engine/Compatibility/TimeSyncHooks.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks ClientNet::HandleTimeSynch to track the server time/wall-clock relationship.
|
||||
/// Used to convert Enchantment._start_time (server seconds) into remaining wall-clock seconds.
|
||||
///
|
||||
/// ClientNet::HandleTimeSynch signature (thiscall):
|
||||
/// void __thiscall ClientNet::HandleTimeSynch(ClientNet *this, CTimeSyncHeader *pHdr, CNetLayerPacket *pkt)
|
||||
///
|
||||
/// COptionalHeader layout (4-byte packing, 24 bytes):
|
||||
/// +0 Turbine_RefCount _ref (vfptr=4, m_cRef=4)
|
||||
/// +8 UInt32 m_dwMask
|
||||
/// +12 UInt32 m_Flags
|
||||
/// +16 Char* m_pData
|
||||
/// +20 UInt32 m_cbData
|
||||
/// CTimeSyncHeader layout:
|
||||
/// +0 COptionalHeader (24 bytes)
|
||||
/// +24 Double m_time ← server time in seconds
|
||||
/// </summary>
|
||||
internal static class TimeSyncHooks
|
||||
{
|
||||
private const int HandleTimeSynchVa = 0x005448F0;
|
||||
private const int TimeSyncHeaderMTimeOffset = 24;
|
||||
|
||||
private static IntPtr _originalHandleTimeSynch;
|
||||
private static bool _initialized;
|
||||
|
||||
// Server-time / wall-clock reference pair, updated each time sync arrives.
|
||||
private static double _lastServerTime;
|
||||
private static long _lastWallClockTicks;
|
||||
|
||||
public static bool IsInitialized => _initialized;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the estimated current server time in seconds.
|
||||
/// Returns 0 if no time sync has been received yet.
|
||||
/// </summary>
|
||||
public static double GetCurrentServerTime()
|
||||
{
|
||||
long wallTicks = _lastWallClockTicks;
|
||||
if (wallTicks == 0)
|
||||
return 0;
|
||||
|
||||
double elapsed = (DateTime.UtcNow.Ticks - wallTicks) / (double)TimeSpan.TicksPerSecond;
|
||||
return _lastServerTime + elapsed;
|
||||
}
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_initialized)
|
||||
return;
|
||||
|
||||
var ptr = new IntPtr(HandleTimeSynchVa);
|
||||
if (!SmartBoxLocator.IsPointerInModule(ptr))
|
||||
{
|
||||
RynthLog.Compat($"Compat: time-sync hook pointer looks invalid (0x{HandleTimeSynchVa:X8})");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, void> detour = &HandleTimeSynchDetour;
|
||||
MinHook.Hook(ptr, (IntPtr)detour, out _originalHandleTimeSynch);
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Compat($"Compat: time-sync hook ready - HandleTimeSynch=0x{HandleTimeSynchVa:X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: time-sync hook failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe void HandleTimeSynchDetour(IntPtr thisPtr, IntPtr pHdr, IntPtr pkt)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (pHdr != IntPtr.Zero)
|
||||
{
|
||||
long bits = Marshal.ReadInt64(pHdr + TimeSyncHeaderMTimeOffset);
|
||||
double serverTime = BitConverter.Int64BitsToDouble(bits);
|
||||
if (serverTime > 0)
|
||||
{
|
||||
_lastServerTime = serverTime;
|
||||
_lastWallClockTicks = DateTime.UtcNow.Ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, void>)_originalHandleTimeSynch;
|
||||
original(thisPtr, pHdr, pkt);
|
||||
}
|
||||
}
|
||||
122
src/RynthCore.Engine/Compatibility/UiLifecycleHooks.cs
Normal file
122
src/RynthCore.Engine/Compatibility/UiLifecycleHooks.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class UiLifecycleHooks
|
||||
{
|
||||
private static readonly byte?[] SetUiReadyPattern =
|
||||
[
|
||||
0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x75,
|
||||
0x16, 0x8B, 0x0D, null, null, null, null, 0x85,
|
||||
0xC9, 0x74, 0x0C, 0x8B, 0x41, 0x04, 0x85, 0xC0,
|
||||
0x74, 0x05, 0xE8, null, null, null, null, 0x89,
|
||||
0x35, null, null, null, null, 0x5E, 0xC3
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetUiReadyDelegate(int isReady);
|
||||
|
||||
private static SetUiReadyDelegate? _originalSetUiReady;
|
||||
private static SetUiReadyDelegate? _setUiReadyDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static IntPtr _uiReadyFlagAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static long _nextStatusLogTick;
|
||||
private static bool _waitingLogged;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static bool HasObservedUiInitialized { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
internal static IntPtr UiReadyFlagAddress => _uiReadyFlagAddress;
|
||||
|
||||
public static event Action? UiInitialized;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int funcOff = PatternScanner.FindPattern(textSection.Bytes, SetUiReadyPattern);
|
||||
if (funcOff < 0)
|
||||
{
|
||||
_statusMessage = "APIManager::SetUIReady pattern not found.";
|
||||
RynthLog.Compat($"Compat: UI lifecycle hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_uiReadyFlagAddress = new IntPtr(BitConverter.ToInt32(textSection.Bytes, funcOff + 33));
|
||||
_setUiReadyDetour = SetUiReadyDetour;
|
||||
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setUiReadyDetour);
|
||||
_originalSetUiReady = Marshal.GetDelegateForFunctionPointer<SetUiReadyDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked SetUIReady @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
_nextStatusLogTick = Environment.TickCount64 + 3000;
|
||||
|
||||
RynthLog.Compat(
|
||||
$"Compat: UI lifecycle hook ready - SetUIReady=0x{_targetAddress.ToInt32():X8}, uiReadyFlag=0x{_uiReadyFlagAddress.ToInt32():X8}");
|
||||
|
||||
if (_uiReadyFlagAddress != IntPtr.Zero && Marshal.ReadInt32(_uiReadyFlagAddress) != 0)
|
||||
{
|
||||
HasObservedUiInitialized = true;
|
||||
_statusMessage = "UI ready already active (late attach).";
|
||||
RynthLog.Compat("Compat: UI lifecycle already active at inject time.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: UI lifecycle hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Poll()
|
||||
{
|
||||
if (HasObservedUiInitialized || !IsInstalled)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextStatusLogTick)
|
||||
return;
|
||||
|
||||
_nextStatusLogTick = now + 3000;
|
||||
if (!_waitingLogged)
|
||||
{
|
||||
_waitingLogged = true;
|
||||
RynthLog.Compat("Compat: UI lifecycle awaiting SetUIReady(1).");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetUiReadyDetour(int isReady)
|
||||
{
|
||||
_originalSetUiReady!(isReady);
|
||||
if (isReady != 0)
|
||||
SignalUiInitialized("APIManager::SetUIReady(1)");
|
||||
}
|
||||
|
||||
private static void SignalUiInitialized(string source)
|
||||
{
|
||||
if (HasObservedUiInitialized)
|
||||
return;
|
||||
|
||||
HasObservedUiInitialized = true;
|
||||
_statusMessage = $"UI initialized observed via {source}.";
|
||||
RynthLog.Compat($"Compat: UI initialized observed via {source}.");
|
||||
UiInitialized?.Invoke();
|
||||
}
|
||||
}
|
||||
260
src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs
Normal file
260
src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class UpdateObjectInventoryHooks
|
||||
{
|
||||
private const int UpdateObjectInventoryExpectedVa = 0x0055A190;
|
||||
private static readonly byte[] UpdateObjectInventorySignature =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x50, 0xE8, 0x96, 0xE7,
|
||||
0xFA, 0xFF, 0x8B, 0x4C, 0x24, 0x08, 0x51, 0x8D,
|
||||
0x48, 0x3C, 0xE8, 0x69, 0xFF, 0xFF, 0xFF, 0xC2,
|
||||
0x08, 0x00
|
||||
];
|
||||
|
||||
// Derived from UpdateObjectInventory disasm: lea ecx, [eax+0x3C]
|
||||
// The instruction at sig offset 15 (8D 48 3C) encodes the inventory offset.
|
||||
private const int WeenieObjectInventoryOffset = 0x3C;
|
||||
|
||||
// CObjectInventory layout from Chorizite:
|
||||
// LongHashData (12) + IDList _itemsList + IDList _containersList + ...
|
||||
private const int ObjectInventoryItemsListOffset = 0x0C;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UpdateObjectInventoryDelegate(IntPtr thisPtr, uint objectId, IntPtr newInventory);
|
||||
|
||||
private static UpdateObjectInventoryDelegate? _originalUpdateObjectInventory;
|
||||
private static UpdateObjectInventoryDelegate? _updateObjectInventoryDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int updateFuncOff = ResolveUpdateObjectInventoryOffset(textSection.Bytes, textSection.TextBaseVa, out bool updateUsedScan);
|
||||
if (updateFuncOff < 0)
|
||||
{
|
||||
_statusMessage = "ACCObjectMaint::UpdateObjectInventory signature not found.";
|
||||
RynthLog.Compat($"Compat: update-object-inventory hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + updateFuncOff);
|
||||
_updateObjectInventoryDetour = UpdateObjectInventoryDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_updateObjectInventoryDetour);
|
||||
_originalUpdateObjectInventory = Marshal.GetDelegateForFunctionPointer<UpdateObjectInventoryDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage =
|
||||
$"Hooked ACCObjectMaint::UpdateObjectInventory @ 0x{_targetAddress.ToInt32():X8}" +
|
||||
$"{(updateUsedScan ? " (pattern)" : string.Empty)}.";
|
||||
RynthLog.Compat($"Compat: update-object-inventory hook ready - {_statusMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: update-object-inventory hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int ResolveUpdateObjectInventoryOffset(byte[] text, int textBaseVa, out bool usedPatternScan)
|
||||
{
|
||||
usedPatternScan = false;
|
||||
|
||||
int expectedOff = UpdateObjectInventoryExpectedVa - textBaseVa;
|
||||
if (PatternScanner.VerifyBytes(text, expectedOff, UpdateObjectInventorySignature))
|
||||
return expectedOff;
|
||||
|
||||
int scannedOff = PatternScanner.FindPattern(text, UpdateObjectInventorySignature);
|
||||
if (scannedOff >= 0)
|
||||
{
|
||||
usedPatternScan = true;
|
||||
return scannedOff;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static void UpdateObjectInventoryDetour(IntPtr thisPtr, uint objectId, IntPtr newInventory)
|
||||
{
|
||||
_originalUpdateObjectInventory!(thisPtr, objectId, newInventory);
|
||||
if (objectId == 0)
|
||||
return;
|
||||
|
||||
PluginManager.QueueUpdateObjectInventory(objectId);
|
||||
}
|
||||
|
||||
public static unsafe int GetContainerContents(uint containerId, uint* itemIds, int maxCount)
|
||||
{
|
||||
if (itemIds == null || maxCount <= 0)
|
||||
return 0;
|
||||
|
||||
return GetContainerContents(containerId, new Span<uint>(itemIds, maxCount));
|
||||
}
|
||||
|
||||
private static bool _hasLoggedVtableScan;
|
||||
|
||||
/// <summary>
|
||||
/// Scan weenie object memory in 4-byte steps, logging every in-module pointer (vtable).
|
||||
/// This reveals the sub-object layout — each vtable pointer marks a base class or embedded object.
|
||||
/// </summary>
|
||||
private static void LogWeenieVtableScan(uint containerId, IntPtr weeniePtr)
|
||||
{
|
||||
if (_hasLoggedVtableScan) return;
|
||||
_hasLoggedVtableScan = true;
|
||||
|
||||
RynthLog.Compat($"Compat: === Vtable scan of weenie 0x{containerId:X8} at 0x{weeniePtr.ToInt32():X8} ===");
|
||||
for (int off = 0; off < 0x80; off += 4)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr addr = weeniePtr + off;
|
||||
if (!IsReadablePointer(addr))
|
||||
{
|
||||
RynthLog.Compat($"Compat: +0x{off:X2} UNREADABLE");
|
||||
continue;
|
||||
}
|
||||
|
||||
IntPtr val = Marshal.ReadIntPtr(addr);
|
||||
bool inModule = SmartBoxLocator.IsPointerInModule(val);
|
||||
bool readable = val != IntPtr.Zero && IsReadablePointer(val);
|
||||
|
||||
if (inModule)
|
||||
RynthLog.Compat($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8} [VTABLE - in module]");
|
||||
else if (readable && val.ToInt32() > 0x10000)
|
||||
RynthLog.Compat($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8} [heap ptr]");
|
||||
else
|
||||
RynthLog.Compat($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
RynthLog.Compat($"Compat: +0x{off:X2} ACCESS VIOLATION");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Also log what's at the current offset we're using
|
||||
try
|
||||
{
|
||||
IntPtr invPtr = Marshal.ReadIntPtr(weeniePtr + WeenieObjectInventoryOffset);
|
||||
RynthLog.Compat($"Compat: Current WeenieObjectInventoryOffset=0x{WeenieObjectInventoryOffset:X2} -> 0x{invPtr.ToInt32():X8} readable={IsReadablePointer(invPtr)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Failed to read at inventory offset: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetContainerContents(uint containerId, Span<uint> itemIds)
|
||||
{
|
||||
RynthLog.Compat($"Compat: GetContainerContents ENTER id=0x{containerId:X8} maxCount={itemIds.Length}");
|
||||
|
||||
if (containerId == 0 || itemIds.Length == 0)
|
||||
return 0;
|
||||
|
||||
// Brute-force scan: iterate known object IDs and check containerID ownership.
|
||||
// The embedded CObjectInventory at weenie+0x3C is often empty (especially for
|
||||
// the player object), so we scan all objects and match by ownership instead.
|
||||
return ScanByContainerId(containerId, itemIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scan a range of object IDs, calling GetWeenieObject for each, and return
|
||||
/// those whose containerID matches the target. This discovers items that were
|
||||
/// created before the plugin loaded (e.g. pack contents at login).
|
||||
/// </summary>
|
||||
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
|
||||
{
|
||||
int written = 0;
|
||||
|
||||
// Scan dynamic object range (0x80000001 – 0x8000FFFF)
|
||||
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
|
||||
{
|
||||
if (id == containerId) continue;
|
||||
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out _, out _))
|
||||
continue;
|
||||
if (cid == containerId)
|
||||
itemIds[written++] = id;
|
||||
}
|
||||
|
||||
RynthLog.Compat($"Compat: ScanByContainerId(0x{containerId:X8}) found {written} item(s) in 0x8000xxxx range.");
|
||||
return written;
|
||||
}
|
||||
|
||||
private static int WalkIdList(uint containerId, IntPtr idList, Span<uint> dest, int expectedCount, string label)
|
||||
{
|
||||
IntPtr node = Marshal.ReadIntPtr(idList + 0x08); // first node
|
||||
int written = 0;
|
||||
int walked = 0;
|
||||
|
||||
while (node != IntPtr.Zero && written < expectedCount && written < dest.Length && walked < 2048)
|
||||
{
|
||||
walked++;
|
||||
uint itemId = unchecked((uint)Marshal.ReadInt32(node));
|
||||
if (itemId != 0)
|
||||
{
|
||||
dest[written++] = itemId;
|
||||
RynthLog.Compat($"Compat: {label}[{written - 1}] = 0x{itemId:X8}");
|
||||
}
|
||||
|
||||
node = Marshal.ReadIntPtr(node + 0x08); // next node
|
||||
}
|
||||
|
||||
RynthLog.Compat($"Compat: GetContainerContents(0x{containerId:X8}) walked {walked} {label} node(s), wrote {written}.");
|
||||
return written;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MEMORY_BASIC_INFORMATION
|
||||
{
|
||||
public IntPtr BaseAddress;
|
||||
public IntPtr AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public IntPtr RegionSize;
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
}
|
||||
|
||||
private const uint MemCommit = 0x1000;
|
||||
private const uint PageNoAccess = 0x01;
|
||||
private const uint PageGuard = 0x100;
|
||||
|
||||
private static bool IsReadablePointer(IntPtr ptr)
|
||||
{
|
||||
if (ptr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
if (VirtualQuery(ptr, out MEMORY_BASIC_INFORMATION mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
|
||||
return false;
|
||||
|
||||
if (mbi.State != MemCommit)
|
||||
return false;
|
||||
|
||||
return (mbi.Protect & (PageNoAccess | PageGuard)) == 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class UpdateObjectServerDispatchHooks
|
||||
{
|
||||
private const int DispatchSbUpdateObjectVa = 0x006AD710;
|
||||
private const int NetBlobBufPtrOffset = 0x2C;
|
||||
private const int NetBlobBufSizeOffset = 0x30;
|
||||
private const uint UpdateObjectOpcode = 0x0000F7DB;
|
||||
private static readonly byte[] DispatchSbUpdateObjectSignature =
|
||||
[
|
||||
0x81, 0xEC, 0xB8, 0x01, 0x00, 0x00, 0x53, 0x8B,
|
||||
0x9C, 0x24, 0xC4, 0x01, 0x00, 0x00, 0x85, 0xDB,
|
||||
0x74, 0x0B, 0x8B, 0x84, 0x24, 0xC0, 0x01, 0x00,
|
||||
0x00, 0x85, 0xC0, 0x75, 0x0D, 0xB8, 0x03, 0x00,
|
||||
0x00, 0x00
|
||||
];
|
||||
|
||||
private static IntPtr _originalDispatchSbUpdateObjectPtr;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _dispatchCount;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = DispatchSbUpdateObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DispatchSbUpdateObjectSignature))
|
||||
{
|
||||
_statusMessage = $"CM_Physics::DispatchSB_UpdateObject signature mismatch @ 0x{DispatchSbUpdateObjectVa:X8}.";
|
||||
RynthLog.Compat($"Compat: update-object hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbUpdateObjectDetour;
|
||||
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbUpdateObjectPtr);
|
||||
}
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked CM_Physics::DispatchSB_UpdateObject @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat($"Compat: update-object hook ready - DispatchSB_UpdateObject=0x{_targetAddress.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: update-object hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static unsafe uint DispatchSbUpdateObjectDetour(IntPtr smartBoxPtr, IntPtr blob)
|
||||
{
|
||||
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbUpdateObjectPtr;
|
||||
uint objectId = TryReadUpdatedObjectId(blob);
|
||||
|
||||
uint status = pOriginal(smartBoxPtr, blob);
|
||||
if (!LoginLifecycleHooks.HasObservedLoginComplete || objectId == 0)
|
||||
return status;
|
||||
|
||||
int count = Interlocked.Increment(ref _dispatchCount);
|
||||
if (count <= 8)
|
||||
RynthLog.Compat($"Compat: update object #{count} id=0x{objectId:X8} status={status}");
|
||||
|
||||
PluginManager.QueueUpdateObject(objectId);
|
||||
return status;
|
||||
}
|
||||
|
||||
private static uint TryReadUpdatedObjectId(IntPtr blob)
|
||||
{
|
||||
if (blob == IntPtr.Zero)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
|
||||
if (blobSize < 8)
|
||||
return 0;
|
||||
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return 0;
|
||||
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
|
||||
if (opcode != UpdateObjectOpcode)
|
||||
return 0;
|
||||
|
||||
return unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class VectorUpdateServerDispatchHooks
|
||||
{
|
||||
private const int DispatchSbVectorUpdateVa = 0x006ADC80;
|
||||
private const int NetBlobBufPtrOffset = 0x2C;
|
||||
private const int NetBlobBufSizeOffset = 0x30;
|
||||
private const uint VectorUpdateOpcode = 0x0000F74E;
|
||||
private static readonly byte[] DispatchSbVectorUpdateSignature =
|
||||
[
|
||||
0x83, 0xEC, 0x20, 0x53, 0x8B, 0x5C, 0x24, 0x2C,
|
||||
0x85, 0xDB, 0x74, 0x08, 0x8B, 0x44, 0x24, 0x28,
|
||||
0x85, 0xC0, 0x75, 0x0A, 0xB8, 0x03, 0x00, 0x00,
|
||||
0x00, 0x5B, 0x83, 0xC4, 0x20, 0xC3
|
||||
];
|
||||
|
||||
private static IntPtr _originalDispatchSbVectorUpdatePtr;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = DispatchSbVectorUpdateVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DispatchSbVectorUpdateSignature))
|
||||
{
|
||||
_statusMessage = $"CM_Physics::DispatchSB_VectorUpdate signature mismatch @ 0x{DispatchSbVectorUpdateVa:X8}.";
|
||||
RynthLog.Compat($"Compat: vector-update hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbVectorUpdateDetour;
|
||||
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbVectorUpdatePtr);
|
||||
}
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked CM_Physics::DispatchSB_VectorUpdate @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat($"Compat: vector-update hook ready - DispatchSB_VectorUpdate=0x{_targetAddress.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: vector-update hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static unsafe uint DispatchSbVectorUpdateDetour(IntPtr smartBoxPtr, IntPtr blob)
|
||||
{
|
||||
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbVectorUpdatePtr;
|
||||
VectorUpdateInfo info = ReadVectorUpdateInfo(blob);
|
||||
|
||||
uint status = pOriginal(smartBoxPtr, blob);
|
||||
if (!LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
return status;
|
||||
|
||||
if (info.Opcode != VectorUpdateOpcode || info.RawObjectId == 0)
|
||||
return status;
|
||||
|
||||
PluginManager.QueueUpdateObject(info.RawObjectId);
|
||||
return status;
|
||||
}
|
||||
|
||||
private static VectorUpdateInfo ReadVectorUpdateInfo(IntPtr blob)
|
||||
{
|
||||
if (blob == IntPtr.Zero)
|
||||
return default;
|
||||
|
||||
try
|
||||
{
|
||||
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
|
||||
if (blobSize < 8)
|
||||
return new VectorUpdateInfo(0, 0, blobSize);
|
||||
|
||||
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||
if (payloadPtr == IntPtr.Zero)
|
||||
return new VectorUpdateInfo(0, 0, blobSize);
|
||||
|
||||
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
|
||||
uint rawObjectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))));
|
||||
return new VectorUpdateInfo(opcode, rawObjectId, blobSize);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct VectorUpdateInfo(uint Opcode, uint RawObjectId, uint BlobSize);
|
||||
}
|
||||
130
src/RynthCore.Engine/Compatibility/ViewObjectContentsHooks.cs
Normal file
130
src/RynthCore.Engine/Compatibility/ViewObjectContentsHooks.cs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class ViewObjectContentsHooks
|
||||
{
|
||||
private const int ViewObjectContentsVa = 0x005596B0;
|
||||
private const int StopViewingObjectContentsVa = 0x00559770;
|
||||
private static readonly byte[] ViewObjectContentsSignature =
|
||||
[
|
||||
0x53, 0x8B, 0x5C, 0x24, 0x08, 0x56, 0x57, 0x53,
|
||||
0x8B, 0xF9, 0xE8, 0x71, 0xF2, 0xFA, 0xFF, 0x8B,
|
||||
0xF0, 0x85, 0xF6, 0x75, 0x57
|
||||
];
|
||||
private static readonly byte[] StopViewingObjectContentsSignature =
|
||||
[
|
||||
0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x57, 0x8B,
|
||||
0xF1, 0xE8, 0x62, 0xF1, 0xFA, 0xFF, 0x85, 0xC0,
|
||||
0x74, 0x07, 0xC7, 0x40, 0x50, 0x00, 0x00, 0x00,
|
||||
0x00
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void ViewObjectContentsDelegate(IntPtr thisPtr, uint objectId, IntPtr newContents);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void StopViewingObjectContentsDelegate(IntPtr thisPtr, uint objectId);
|
||||
|
||||
private static ViewObjectContentsDelegate? _originalViewObjectContents;
|
||||
private static ViewObjectContentsDelegate? _viewObjectContentsDetour;
|
||||
private static StopViewingObjectContentsDelegate? _originalStopViewingObjectContents;
|
||||
private static StopViewingObjectContentsDelegate? _stopViewingObjectContentsDetour;
|
||||
private static IntPtr _viewTargetAddress;
|
||||
private static IntPtr _stopTargetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _viewDispatchCount;
|
||||
private static int _stopDispatchCount;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
int viewOff = ViewObjectContentsVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, viewOff, ViewObjectContentsSignature))
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::ViewObjectContents signature mismatch @ 0x{ViewObjectContentsVa:X8}.";
|
||||
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
int stopOff = StopViewingObjectContentsVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, stopOff, StopViewingObjectContentsSignature))
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::StopViewingObjectContents signature mismatch @ 0x{StopViewingObjectContentsVa:X8}.";
|
||||
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_viewTargetAddress = new IntPtr(textSection.TextBaseVa + viewOff);
|
||||
_viewObjectContentsDetour = ViewObjectContentsDetour;
|
||||
IntPtr viewDetourPtr = Marshal.GetFunctionPointerForDelegate(_viewObjectContentsDetour);
|
||||
_originalViewObjectContents = Marshal.GetDelegateForFunctionPointer<ViewObjectContentsDelegate>(MinHook.HookCreate(_viewTargetAddress, viewDetourPtr));
|
||||
|
||||
_stopTargetAddress = new IntPtr(textSection.TextBaseVa + stopOff);
|
||||
_stopViewingObjectContentsDetour = StopViewingObjectContentsDetour;
|
||||
IntPtr stopDetourPtr = Marshal.GetFunctionPointerForDelegate(_stopViewingObjectContentsDetour);
|
||||
_originalStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<StopViewingObjectContentsDelegate>(MinHook.HookCreate(_stopTargetAddress, stopDetourPtr));
|
||||
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_viewTargetAddress);
|
||||
MinHook.Enable(_stopTargetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked contents view seams @ 0x{_viewTargetAddress.ToInt32():X8}/0x{_stopTargetAddress.ToInt32():X8}.";
|
||||
RynthLog.Compat(
|
||||
$"Compat: view-object-contents hooks ready - view=0x{_viewTargetAddress.ToInt32():X8}, stop=0x{_stopTargetAddress.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: view-object-contents hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ViewObjectContentsDetour(IntPtr thisPtr, uint objectId, IntPtr newContents)
|
||||
{
|
||||
_originalViewObjectContents!(thisPtr, objectId, newContents);
|
||||
if (objectId == 0)
|
||||
return;
|
||||
|
||||
ClientHelperHooks.NotifyViewObjectContents(objectId);
|
||||
|
||||
int count = Interlocked.Increment(ref _viewDispatchCount);
|
||||
if (count <= 0)
|
||||
RynthLog.Compat($"Compat: view contents #{count} id=0x{objectId:X8} contents=0x{newContents.ToInt32():X8}");
|
||||
|
||||
PluginManager.QueueViewObjectContents(objectId);
|
||||
}
|
||||
|
||||
private static void StopViewingObjectContentsDetour(IntPtr thisPtr, uint objectId)
|
||||
{
|
||||
_originalStopViewingObjectContents!(thisPtr, objectId);
|
||||
if (objectId == 0)
|
||||
return;
|
||||
|
||||
ClientHelperHooks.NotifyStopViewingObjectContents(objectId);
|
||||
|
||||
int count = Interlocked.Increment(ref _stopDispatchCount);
|
||||
if (count <= 5)
|
||||
RynthLog.Compat($"Compat: stop view contents #{count} id=0x{objectId:X8}");
|
||||
|
||||
PluginManager.QueueStopViewingObjectContents(objectId);
|
||||
}
|
||||
}
|
||||
227
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
227
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class D3D9Bootstrapper
|
||||
{
|
||||
private const uint D3DSdkVersion = 32;
|
||||
private const int PollIntervalMs = 50;
|
||||
private const int BootstrapFallbackMs = 15000;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr Direct3DCreate9Delegate(uint sdkVersion);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
private static int _started;
|
||||
private static bool _d3dCreateHookInstalled;
|
||||
private static bool _createDeviceHookInstalled;
|
||||
private static bool _realDeviceObserved;
|
||||
private static Direct3DCreate9Delegate? _originalDirect3DCreate9;
|
||||
private static Direct3DCreate9Delegate? _direct3DCreate9Detour;
|
||||
private static CreateDeviceDelegate? _originalCreateDevice;
|
||||
private static CreateDeviceDelegate? _createDeviceDetour;
|
||||
private static IntPtr _createDeviceTarget;
|
||||
private static IntPtr _direct3DCreate9Target;
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
var thread = new Thread(BootstrapWorker)
|
||||
{
|
||||
Name = "RynthCore.D3D9Bootstrap",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private static void BootstrapWorker()
|
||||
{
|
||||
try
|
||||
{
|
||||
// This runs after character login, so d3d9.dll and the game's
|
||||
// device are fully initialized. Use the NULLREF throwaway device
|
||||
// for vtable discovery — it's safe post-login because the
|
||||
// d3d9-on-d3d12 wrapper has finished all its one-time init work.
|
||||
IntPtr earlyModule = GetModuleHandleA("d3d9.dll");
|
||||
if (earlyModule != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device.");
|
||||
EndSceneHook.Install("post-login-vtable");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Waiting for d3d9.dll so RynthCore can hook the real device creation path.");
|
||||
DateTime fallbackDeadline = DateTime.UtcNow.AddMilliseconds(BootstrapFallbackMs);
|
||||
|
||||
while (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module != IntPtr.Zero)
|
||||
{
|
||||
TryHookDirect3DCreate9(d3d9Module);
|
||||
if (_realDeviceObserved || EndSceneHook.IsInstalled())
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow >= fallbackDeadline)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Real CreateDevice path was not observed in time. Falling back to shared vtable discovery.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
return;
|
||||
}
|
||||
|
||||
Thread.Sleep(PollIntervalMs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: FATAL bootstrap error: {ex}");
|
||||
if (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Attempting fallback EndScene install after bootstrap failure.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryHookDirect3DCreate9(IntPtr d3d9Module)
|
||||
{
|
||||
if (_d3dCreateHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr direct3DCreate9Addr = GetProcAddress(d3d9Module, "Direct3DCreate9");
|
||||
if (direct3DCreate9Addr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 export unavailable (error {Marshal.GetLastWin32Error()}).");
|
||||
return;
|
||||
}
|
||||
|
||||
_direct3DCreate9Target = direct3DCreate9Addr;
|
||||
_direct3DCreate9Detour = Direct3DCreate9Detour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_direct3DCreate9Detour);
|
||||
|
||||
_originalDirect3DCreate9 = Marshal.GetDelegateForFunctionPointer<Direct3DCreate9Delegate>(MinHook.HookCreate(direct3DCreate9Addr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(direct3DCreate9Addr);
|
||||
_d3dCreateHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked Direct3DCreate9 @ 0x{direct3DCreate9Addr:X8}");
|
||||
}
|
||||
|
||||
private static IntPtr Direct3DCreate9Detour(uint sdkVersion)
|
||||
{
|
||||
IntPtr direct3D9 = _originalDirect3DCreate9!(sdkVersion);
|
||||
|
||||
if (sdkVersion != D3DSdkVersion)
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
|
||||
|
||||
if (direct3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
TryHookCreateDevice(direct3D9);
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
private static void TryHookCreateDevice(IntPtr direct3D9)
|
||||
{
|
||||
if (_createDeviceHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(direct3D9);
|
||||
_createDeviceTarget = Marshal.ReadIntPtr(vtable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
if (_createDeviceTarget == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: IDirect3D9::CreateDevice pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
_createDeviceDetour = CreateDeviceDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createDeviceDetour);
|
||||
|
||||
_originalCreateDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(MinHook.HookCreate(_createDeviceTarget, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_createDeviceTarget);
|
||||
_createDeviceHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked IDirect3D9::CreateDevice @ 0x{_createDeviceTarget:X8}");
|
||||
}
|
||||
|
||||
private static void RemoveBootstrapHooks()
|
||||
{
|
||||
if (_d3dCreateHookInstalled && _direct3DCreate9Target != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
_d3dCreateHookInstalled = false;
|
||||
}
|
||||
|
||||
if (_createDeviceHookInstalled && _createDeviceTarget != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
_createDeviceHookInstalled = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int CreateDeviceDetour(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice)
|
||||
{
|
||||
int hr = _originalCreateDevice!(
|
||||
pD3D9,
|
||||
adapter,
|
||||
deviceType,
|
||||
hFocusWindow,
|
||||
behaviorFlags,
|
||||
pPresentationParameters,
|
||||
out ppDevice);
|
||||
|
||||
if (hr >= 0 && ppDevice != IntPtr.Zero)
|
||||
{
|
||||
_realDeviceObserved = true;
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Observed real device creation (device=0x{ppDevice:X8}, hwnd=0x{hFocusWindow:X8}, hr=0x{hr:X8}).");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.InstallFromDevice(ppDevice);
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: CreateDevice returned hr=0x{hr:X8}, device=0x{ppDevice:X8}");
|
||||
}
|
||||
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
593
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
593
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
|
|
@ -0,0 +1,593 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/D3D9VTable.cs
|
||||
// Creates a throwaway D3D9 device to harvest vtable function pointers.
|
||||
// The vtable is shared across all IDirect3DDevice9 instances in the process,
|
||||
// so the addresses we read here apply to the game's real device.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DDevice9 vtable indices (x86, standard d3d9.h order).
|
||||
/// </summary>
|
||||
internal static class DeviceVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int GetCreationParameters = 9;
|
||||
public const int CreateAdditionalSwapChain = 13;
|
||||
public const int Reset = 16;
|
||||
public const int GetBackBuffer = 18;
|
||||
public const int CreateTexture = 23;
|
||||
public const int BeginScene = 41;
|
||||
public const int EndScene = 42;
|
||||
public const int Clear = 43;
|
||||
public const int SetTransform = 44;
|
||||
public const int GetTransform = 45;
|
||||
public const int GetRenderTarget = 38;
|
||||
public const int SetViewport = 47;
|
||||
public const int GetViewport = 48;
|
||||
public const int GetTexture = 64;
|
||||
public const int SetRenderState = 57;
|
||||
public const int GetRenderState = 58;
|
||||
public const int SetTexture = 65;
|
||||
public const int GetTextureStageState = 66;
|
||||
public const int SetTextureStageState = 67;
|
||||
public const int GetSamplerState = 68;
|
||||
public const int SetSamplerState = 69;
|
||||
public const int SetScissorRect = 75;
|
||||
public const int GetScissorRect = 76;
|
||||
public const int DrawPrimitive = 81;
|
||||
public const int DrawIndexedPrimitive = 82;
|
||||
public const int DrawPrimitiveUP = 83;
|
||||
public const int DrawIndexedPrimitiveUP = 84;
|
||||
public const int SetFVF = 89;
|
||||
public const int GetFVF = 90;
|
||||
public const int SetVertexShader = 92;
|
||||
public const int GetVertexShader = 93;
|
||||
public const int SetStreamSource = 100;
|
||||
public const int GetStreamSource = 101;
|
||||
public const int SetIndices = 104;
|
||||
public const int GetIndices = 105;
|
||||
public const int SetPixelShader = 107;
|
||||
public const int GetPixelShader = 108;
|
||||
public const int CreateStateBlock = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DStateBlock9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class StateBlockVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int Capture = 4;
|
||||
public const int Apply = 5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DTexture9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class TextureVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int LockRect = 19;
|
||||
public const int UnlockRect = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3D9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class D3D9VTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int CreateDevice = 16;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the IDirect3DDevice9 vtable by creating (and immediately releasing)
|
||||
/// a temporary device + hidden window.
|
||||
/// Also provides <see cref="ScanModuleForDeviceVTable"/> which finds the vtable
|
||||
/// by scanning d3d9.dll's module image — no device creation required.
|
||||
/// </summary>
|
||||
internal static unsafe class D3D9VTable
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3D_SDK_VERSION = 32;
|
||||
private const uint D3DDEVTYPE_HAL = 1;
|
||||
private const uint D3DDEVTYPE_NULLREF = 4;
|
||||
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
|
||||
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
|
||||
private const uint D3DFMT_UNKNOWN = 0;
|
||||
private const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
|
||||
// ─── Win32 ────────────────────────────────────────────────────────
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateWindowExA(
|
||||
uint dwExStyle, string lpClassName, string lpWindowName,
|
||||
uint dwStyle, int x, int y, int nWidth, int nHeight,
|
||||
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
// ─── D3D9 ─────────────────────────────────────────────────────────
|
||||
[DllImport("d3d9.dll")]
|
||||
private static extern IntPtr Direct3DCreate9(uint SDKVersion);
|
||||
|
||||
// ─── COM Release delegate ─────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseDelegate(IntPtr pThis);
|
||||
|
||||
// ─── IDirect3D9::CreateDevice delegate ────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint Adapter,
|
||||
uint DeviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint BehaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
// ─── D3DPRESENT_PARAMETERS (x86 layout) ───────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat; // D3DFORMAT
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType; // D3DMULTISAMPLE_TYPE
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect; // D3DSWAPEFFECT
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed; // BOOL
|
||||
public int EnableAutoDepthStencil; // BOOL
|
||||
public uint AutoDepthStencilFormat; // D3DFORMAT
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temp D3D9 device and returns a copy of the device vtable
|
||||
/// (array of function pointers). Returns null on failure.
|
||||
/// </summary>
|
||||
public static IntPtr[]? GetDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hWnd = IntPtr.Zero;
|
||||
IntPtr pD3D9 = IntPtr.Zero;
|
||||
IntPtr pDevice = IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
// Create a hidden window
|
||||
hWnd = CreateWindowExA(
|
||||
0, "STATIC", "RynthCore_D3D9_Temp", 0,
|
||||
0, 0, 1, 1,
|
||||
IntPtr.Zero, IntPtr.Zero,
|
||||
GetModuleHandleA(null), IntPtr.Zero);
|
||||
|
||||
if (hWnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Failed to create temp window.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create IDirect3D9
|
||||
pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
|
||||
if (pD3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Direct3DCreate9 failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Set up present parameters
|
||||
var pp = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = 1,
|
||||
BackBufferHeight = 1,
|
||||
BackBufferFormat = D3DFMT_UNKNOWN,
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = hWnd,
|
||||
Windowed = 1, // TRUE
|
||||
};
|
||||
|
||||
// Call IDirect3D9::CreateDevice via vtable
|
||||
IntPtr d3d9VTable = Marshal.ReadIntPtr(pD3D9); // pD3D9->lpVtbl
|
||||
IntPtr createDeviceAddr = Marshal.ReadIntPtr(d3d9VTable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(createDeviceAddr);
|
||||
|
||||
IntPtr ppAlloc = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
|
||||
// Try NULLREF device first — it doesn't touch the GPU, avoiding
|
||||
// race conditions with the game's render thread on the real HAL device.
|
||||
int hr = createDevice(
|
||||
pD3D9,
|
||||
0, // D3DADAPTER_DEFAULT
|
||||
D3DDEVTYPE_NULLREF,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: NULLREF device failed (hr=0x{hr:X8}), trying HAL fallback.");
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
hr = createDevice(
|
||||
pD3D9,
|
||||
0,
|
||||
D3DDEVTYPE_HAL,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
}
|
||||
|
||||
Marshal.FreeHGlobal(ppAlloc);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: CreateDevice failed, HRESULT=0x{hr:X8}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read the device vtable
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice); // pDevice->lpVtbl
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = Marshal.ReadIntPtr(deviceVTable, i * IntPtr.Size);
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Captured {numEntries} entries. " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}");
|
||||
|
||||
return vtable;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Exception: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Release the temp device and D3D9 object
|
||||
if (pDevice != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, DeviceVTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pDevice);
|
||||
}
|
||||
|
||||
if (pD3D9 != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pD3D9);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, D3D9VTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pD3D9);
|
||||
}
|
||||
|
||||
if (hWnd != IntPtr.Zero)
|
||||
DestroyWindow(hWnd);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans the loaded d3d9.dll module image for the IDirect3DDevice9 vtable
|
||||
/// without creating any D3D9 objects. This avoids the thread-safety hazard
|
||||
/// of creating a throwaway device while the game's real device is rendering.
|
||||
/// Returns null if the scan cannot find a valid candidate.
|
||||
/// </summary>
|
||||
public static IntPtr[]? ScanModuleForDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hModule = GetModuleHandleA("d3d9.dll");
|
||||
if (hModule == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
const int MaxReasonableModuleSize = 50 * 1024 * 1024;
|
||||
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > MaxReasonableModuleSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: d3d9.dll PE headers unusable (imageSize=0x{imageSize:X}) — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int baseAddr = hModule.ToInt32();
|
||||
int vtableByteLen = numEntries * 4; // x86 pointer size
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Reading d3d9.dll (0x{baseAddr:X8}, 0x{imageSize:X} bytes)...");
|
||||
|
||||
// Copy module into managed memory page-by-page, skipping any
|
||||
// uncommitted pages. SizeOfImage can exceed committed memory
|
||||
// and NativeAOT cannot catch the resulting AccessViolationException.
|
||||
byte[] image = new byte[imageSize];
|
||||
int readableBytes = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < imageSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, imageSize - off);
|
||||
IntPtr addr = IntPtr.Add(hModule, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, image, off, chunk);
|
||||
readableBytes += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (readableBytes < vtableByteLen + 0x1000)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {readableBytes} readable bytes in d3d9.dll — too small for vtable scan.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning d3d9.dll ({readableBytes} readable bytes) for {numEntries}-entry device vtable...");
|
||||
|
||||
// Collect ALL candidate vtables. d3d9.dll on Windows 11 can contain
|
||||
// multiple vtables (inner implementation + outer proxy). The game's
|
||||
// device typically uses the LAST one (the outer proxy layer).
|
||||
IntPtr[]? bestCandidate = null;
|
||||
int bestOffset = 0;
|
||||
int candidateCount = 0;
|
||||
|
||||
for (int off = 0x1000; off <= imageSize - vtableByteLen; off += 4)
|
||||
{
|
||||
// Fast reject: first 3 entries (QueryInterface, AddRef, Release) must be in-module
|
||||
int p0 = BitConverter.ToInt32(image, off);
|
||||
if ((uint)(p0 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p1 = BitConverter.ToInt32(image, off + 4);
|
||||
if ((uint)(p1 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p2 = BitConverter.ToInt32(image, off + 8);
|
||||
if ((uint)(p2 - baseAddr) >= (uint)imageSize) continue;
|
||||
|
||||
// QI, AddRef, Release must be distinct functions
|
||||
if (p0 == p1 || p1 == p2) continue;
|
||||
|
||||
// Count in-module pointers across all entries
|
||||
int inModule = 3;
|
||||
for (int i = 3; i < numEntries; i++)
|
||||
{
|
||||
int ptr = BitConverter.ToInt32(image, off + i * 4);
|
||||
if ((uint)(ptr - baseAddr) < (uint)imageSize)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
// Require ≥95% in-module (113 of 119)
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// EndScene (42) and BeginScene (41) must differ
|
||||
int esPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.EndScene * 4);
|
||||
int bsPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.BeginScene * 4);
|
||||
if (esPtr == bsPtr) continue;
|
||||
|
||||
// Verify EndScene starts with a hookable function prologue
|
||||
int esOff = esPtr - baseAddr;
|
||||
if ((uint)esOff >= (uint)(imageSize - 3)) continue;
|
||||
if (!IsRecognizedPrologue(image, esOff)) continue;
|
||||
|
||||
candidateCount++;
|
||||
|
||||
// Build candidate array
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(image, off + i * 4));
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Candidate #{candidateCount} at d3d9+0x{off:X}: " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
|
||||
bestCandidate = vtable;
|
||||
bestOffset = off;
|
||||
}
|
||||
|
||||
if (bestCandidate != null)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Using candidate #{candidateCount} (last of {candidateCount}) at d3d9+0x{bestOffset:X}: " +
|
||||
$"EndScene=0x{bestCandidate[DeviceVTableIndex.EndScene]:X8}");
|
||||
return bestCandidate;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9VTable: Module scan found no device vtable candidates.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsRecognizedPrologue(byte[] image, int offset)
|
||||
{
|
||||
byte b = image[offset];
|
||||
if (b == 0x55) return true; // push ebp
|
||||
if (b == 0x8B && image[offset + 1] == 0xFF) return true; // mov edi,edi (hot-patch)
|
||||
if (b == 0x83 && image[offset + 1] == 0xEC) return true; // sub esp, imm8
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the game's existing IDirect3DDevice9 by scanning process heap memory
|
||||
/// for a live COM object whose vtable is in d3d9.dll with 119 entries.
|
||||
/// Completely read-only — no D3D9 API calls, no thread-safety hazards.
|
||||
/// Returns null if no device is found.
|
||||
/// </summary>
|
||||
public static IntPtr[]? FindExistingDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!TryReadModuleImageSize(d3d9Module, out int d3d9Size) || d3d9Size < 0x2000)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll PE headers unusable — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int d3d9Base = d3d9Module.ToInt32();
|
||||
int d3d9End = d3d9Base + d3d9Size;
|
||||
int vtableByteLen = numEntries * 4;
|
||||
|
||||
// Pre-read d3d9.dll image so vtable validation reads from safe managed memory
|
||||
byte[] d3d9Image = new byte[d3d9Size];
|
||||
int d3d9Readable = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < d3d9Size; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, d3d9Size - off);
|
||||
IntPtr addr = IntPtr.Add(d3d9Module, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, d3d9Image, off, chunk);
|
||||
d3d9Readable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (d3d9Readable < vtableByteLen + PageSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {d3d9Readable} readable bytes in d3d9.dll — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning process heap for live D3D9 device (d3d9=0x{d3d9Base:X8}, size=0x{d3d9Size:X})...");
|
||||
|
||||
int regionsScanned = 0;
|
||||
long bytesScanned = 0;
|
||||
int d3d9Pointers = 0;
|
||||
|
||||
IntPtr scanAddr = new IntPtr(0x10000);
|
||||
|
||||
while (scanAddr.ToInt32() > 0 && scanAddr.ToInt32() < 0x7FFE0000)
|
||||
{
|
||||
if (!VirtualQueryWrapped(scanAddr, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type))
|
||||
break;
|
||||
|
||||
if (regionSize <= 0) break;
|
||||
IntPtr nextAddr = new IntPtr(regionBase + regionSize);
|
||||
|
||||
// Only scan committed, readable, private (heap) memory
|
||||
bool committed = (state & 0x1000) != 0; // MEM_COMMIT
|
||||
bool readable = protect != 0 && (protect & 0x01) == 0 && (protect & 0x100) == 0; // !NOACCESS, !GUARD
|
||||
bool isPrivate = (type & 0x20000) != 0; // MEM_PRIVATE
|
||||
|
||||
if (!committed || !readable || !isPrivate || regionSize < 128)
|
||||
{
|
||||
scanAddr = nextAddr;
|
||||
continue;
|
||||
}
|
||||
|
||||
regionsScanned++;
|
||||
|
||||
// Safe page-by-page copy of this region
|
||||
byte[] regionData = new byte[regionSize];
|
||||
int regionReadable = 0;
|
||||
for (int off = 0; off < regionSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, regionSize - off);
|
||||
IntPtr pageAddr = new IntPtr(regionBase + off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(pageAddr, chunk))
|
||||
{
|
||||
Marshal.Copy(pageAddr, regionData, off, chunk);
|
||||
regionReadable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
bytesScanned += regionReadable;
|
||||
|
||||
// Scan each dword for a vtable pointer into d3d9.dll
|
||||
for (int off = 0; off <= regionReadable - 4; off += 4)
|
||||
{
|
||||
int value = BitConverter.ToInt32(regionData, off);
|
||||
if (value < d3d9Base || value >= d3d9End) continue;
|
||||
|
||||
d3d9Pointers++;
|
||||
|
||||
// Check if this is a 119-entry device vtable
|
||||
int vtableOffset = value - d3d9Base;
|
||||
if (vtableOffset + vtableByteLen > d3d9Readable) continue;
|
||||
|
||||
int inModule = 0;
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
{
|
||||
int entry = BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4);
|
||||
if (entry >= d3d9Base && entry < d3d9End)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// BeginScene and EndScene must differ
|
||||
int bs = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.BeginScene * 4);
|
||||
int es = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.EndScene * 4);
|
||||
if (bs == es) continue;
|
||||
|
||||
// EndScene must have a hookable prologue
|
||||
int esOff = es - d3d9Base;
|
||||
if ((uint)esOff >= (uint)(d3d9Readable - 3)) continue;
|
||||
if (!IsRecognizedPrologue(d3d9Image, esOff)) continue;
|
||||
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4));
|
||||
|
||||
int objectAddr = regionBase + off;
|
||||
RynthLog.D3D9($"D3D9VTable: Found live device at 0x{objectAddr:X8}, vtable=0x{value:X8} (d3d9+0x{vtableOffset:X}), " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
RynthLog.D3D9($"D3D9VTable: Heap scan stats: {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers checked.");
|
||||
return vtable;
|
||||
}
|
||||
|
||||
scanAddr = nextAddr;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: No live device found — {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── VirtualQuery wrapper ─────────────────────────────────────────
|
||||
[DllImport("kernel32.dll", SetLastError = false)]
|
||||
private static extern int VirtualQuery(IntPtr lpAddress, byte[] lpBuffer, int dwLength);
|
||||
|
||||
private static bool VirtualQueryWrapped(IntPtr address, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type)
|
||||
{
|
||||
regionBase = 0; regionSize = 0; state = 0; protect = 0; type = 0;
|
||||
byte[] buf = new byte[28]; // MEMORY_BASIC_INFORMATION on x86
|
||||
int result = VirtualQuery(address, buf, 28);
|
||||
if (result == 0) return false;
|
||||
|
||||
regionBase = BitConverter.ToInt32(buf, 0); // BaseAddress
|
||||
regionSize = BitConverter.ToInt32(buf, 12); // RegionSize
|
||||
state = BitConverter.ToUInt32(buf, 16); // State
|
||||
protect = BitConverter.ToUInt32(buf, 20); // Protect
|
||||
type = BitConverter.ToUInt32(buf, 24); // Type
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadModuleImageSize(IntPtr moduleBase, out int imageSize)
|
||||
{
|
||||
imageSize = 0;
|
||||
try
|
||||
{
|
||||
if ((ushort)Marshal.ReadInt16(moduleBase) != 0x5A4D) return false; // MZ
|
||||
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
|
||||
if (peOffset <= 0) return false;
|
||||
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
|
||||
if ((uint)Marshal.ReadInt32(ntHeaders) != 0x00004550) return false; // PE\0\0
|
||||
imageSize = Marshal.ReadInt32(ntHeaders, 0x18 + 0x38); // SizeOfImage
|
||||
return imageSize > 0x1000;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
313
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
313
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class EndSceneHook
|
||||
{
|
||||
private const int MaxOffscreenSkipLogs = 3;
|
||||
private const int MaxOffscreenSkipsBeforeFallback = 120;
|
||||
private const int OffscreenFallbackDelayMs = 3000;
|
||||
private const int UiInitWarmupFrames = 180;
|
||||
|
||||
// ── FPS Governor — set by plugins via API ───────────────────────
|
||||
internal static bool FpsLimitEnabled;
|
||||
internal static int FpsTargetFocused = 60;
|
||||
internal static int FpsTargetBackground = 30;
|
||||
private static readonly Stopwatch _fpsTimer = Stopwatch.StartNew();
|
||||
private static bool _fpsLimiterLoggedOnce;
|
||||
private static int _fpsDebugCounter;
|
||||
private static long _fpsCounterStart;
|
||||
private static int _fpsCounterFrames;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int EndSceneDelegate(IntPtr pDevice);
|
||||
|
||||
private static EndSceneDelegate? _originalEndScene;
|
||||
private static EndSceneDelegate? _hookDelegate;
|
||||
private static IntPtr _endSceneAddr;
|
||||
private static bool _installed;
|
||||
private static int _frameCount;
|
||||
private static int _renderCount;
|
||||
private static int _skipCount;
|
||||
private static int _uiFrameCount;
|
||||
private static bool _offscreenFilterDisabled;
|
||||
private static bool _uiActivated;
|
||||
private static bool _warmupLogged;
|
||||
private static long _installTick;
|
||||
private static long _firstOffscreenTick;
|
||||
private static string _installSource = "uninitialized";
|
||||
|
||||
public static void Install()
|
||||
{
|
||||
Install("fallback-vtable");
|
||||
}
|
||||
|
||||
public static void Install(string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
ResetInstallState(installSource);
|
||||
|
||||
// Vtable discovery uses a NULLREF device to avoid GPU contention
|
||||
// with the game's render thread. Retry once on failure.
|
||||
const int maxAttempts = 2;
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Discovering D3D9 vtable (attempt {attempt}/{maxAttempts})...");
|
||||
|
||||
if (attempt > 1)
|
||||
System.Threading.Thread.Sleep(500);
|
||||
|
||||
IntPtr[]? vtable = D3D9VTable.GetDeviceVTable();
|
||||
if (vtable != null)
|
||||
{
|
||||
IntPtr endSceneAddress = vtable[DeviceVTableIndex.EndScene];
|
||||
RynthLog.D3D9($"EndSceneHook: EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: Vtable discovery returned null on attempt {attempt}.");
|
||||
}
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
|
||||
}
|
||||
|
||||
public static void InstallFromDevice(IntPtr pDevice)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Real-device install skipped because the device pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState("real-device");
|
||||
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr endSceneAddress = Marshal.ReadIntPtr(deviceVTable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
RynthLog.D3D9($"EndSceneHook: Using real D3D9 device 0x{pDevice:X8}; EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static void InstallFromAddress(IntPtr endSceneAddress, string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (endSceneAddress == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Address install skipped because EndScene was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState(installSource);
|
||||
RynthLog.D3D9($"EndSceneHook: Using explicit EndScene address 0x{endSceneAddress:X8} from {installSource}.");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static bool IsInstalled()
|
||||
{
|
||||
return _installed;
|
||||
}
|
||||
|
||||
public static int GetRenderCount()
|
||||
{
|
||||
return _renderCount;
|
||||
}
|
||||
|
||||
public static void Uninstall()
|
||||
{
|
||||
if (!_installed)
|
||||
return;
|
||||
|
||||
ImGuiController.Shutdown();
|
||||
|
||||
int status = MinHook.MH_DisableHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Disable = {MinHook.StatusString(status)}");
|
||||
|
||||
status = MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Remove = {MinHook.StatusString(status)}");
|
||||
|
||||
_installed = false;
|
||||
_originalEndScene = null;
|
||||
_offscreenFilterDisabled = false;
|
||||
}
|
||||
|
||||
private static void ResetInstallState(string installSource)
|
||||
{
|
||||
_installSource = installSource;
|
||||
_frameCount = 0;
|
||||
_renderCount = 0;
|
||||
_skipCount = 0;
|
||||
_uiFrameCount = 0;
|
||||
_offscreenFilterDisabled = false;
|
||||
_uiActivated = false;
|
||||
_warmupLogged = false;
|
||||
_installTick = Environment.TickCount64;
|
||||
_firstOffscreenTick = 0;
|
||||
}
|
||||
|
||||
private static void InstallFromEndSceneAddress(IntPtr endSceneAddress)
|
||||
{
|
||||
_endSceneAddr = endSceneAddress;
|
||||
|
||||
_hookDelegate = new EndSceneDelegate(EndSceneDetour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
|
||||
try
|
||||
{
|
||||
_originalEndScene = Marshal.GetDelegateForFunctionPointer<EndSceneDelegate>(MinHook.HookCreate(_endSceneAddr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_endSceneAddr);
|
||||
_installed = true;
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: INSTALLED successfully via {_installSource}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: MinHook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int EndSceneDetour(IntPtr pDevice)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
|
||||
{
|
||||
if (_firstOffscreenTick == 0)
|
||||
_firstOffscreenTick = Environment.TickCount64;
|
||||
|
||||
if (_skipCount < MaxOffscreenSkipLogs)
|
||||
RynthLog.D3D9("EndSceneHook: Skipping offscreen EndScene pass.");
|
||||
_skipCount++;
|
||||
|
||||
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
|
||||
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_offscreenFilterDisabled = true;
|
||||
RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms.");
|
||||
}
|
||||
|
||||
_renderCount++;
|
||||
_frameCount++;
|
||||
|
||||
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
|
||||
{
|
||||
long installElapsedMs = Environment.TickCount64 - _installTick;
|
||||
RynthLog.D3D9($"EndSceneHook: First render after offscreen fallback ({_skipCount} skip(s), {installElapsedMs}ms since install).");
|
||||
}
|
||||
|
||||
if (_renderCount == 1 && _skipCount > 0)
|
||||
RynthLog.D3D9($"EndSceneHook: First backbuffer frame after skipping {_skipCount} offscreen pass(es).");
|
||||
|
||||
// On first backbuffer frame, verify we hooked the right function by
|
||||
// reading the device's own vtable. A mismatch means the module scan
|
||||
// found an internal/proxy vtable, not the one the game's device uses.
|
||||
if (_renderCount == 1)
|
||||
{
|
||||
IntPtr deviceVtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
bool match = actualEndScene == _endSceneAddr;
|
||||
RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}");
|
||||
|
||||
if (!match && actualEndScene != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Rehooking at the device's actual EndScene address.");
|
||||
MinHook.MH_DisableHook(_endSceneAddr);
|
||||
MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
_installed = false;
|
||||
|
||||
InstallFromEndSceneAddress(actualEndScene);
|
||||
if (_installed)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: Rehook failed — continuing with original hook.");
|
||||
// Restore state so we don't keep trying
|
||||
_installed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_uiActivated)
|
||||
{
|
||||
if (!_warmupLogged)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
|
||||
_warmupLogged = true;
|
||||
}
|
||||
|
||||
if (_renderCount < UiInitWarmupFrames)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_uiActivated = true;
|
||||
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
|
||||
}
|
||||
|
||||
ImGuiController.OnEndScene(pDevice);
|
||||
_uiFrameCount++;
|
||||
|
||||
if (_uiFrameCount == 60)
|
||||
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: Frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
|
||||
// ── FPS Governor (matches proven NexSuite2 pattern) ─────────
|
||||
if (FpsLimitEnabled)
|
||||
{
|
||||
IntPtr fgWnd = GetForegroundWindow();
|
||||
GetWindowThreadProcessId(fgWnd, out uint fgPid);
|
||||
uint thisPid = GetCurrentProcessId();
|
||||
bool isFocused = fgPid == thisPid;
|
||||
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
|
||||
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
|
||||
|
||||
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
|
||||
Thread.Sleep(isFocused ? 0 : 1);
|
||||
_fpsTimer.Restart();
|
||||
|
||||
if (!_fpsLimiterLoggedOnce)
|
||||
{
|
||||
_fpsLimiterLoggedOnce = true;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, pid={thisPid}");
|
||||
}
|
||||
|
||||
// Periodic FPS measurement — log every 60 seconds
|
||||
_fpsCounterFrames++;
|
||||
long now = Environment.TickCount64;
|
||||
if (_fpsCounterStart == 0) _fpsCounterStart = now;
|
||||
long elapsedMs = now - _fpsCounterStart;
|
||||
if (elapsedMs >= 60_000)
|
||||
{
|
||||
double measuredFps = _fpsCounterFrames * 1000.0 / elapsedMs;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS={measuredFps:F1} (target={targetFps}, {(isFocused ? "focused" : "background")})");
|
||||
_fpsCounterFrames = 0;
|
||||
_fpsCounterStart = now;
|
||||
}
|
||||
}
|
||||
|
||||
return _originalEndScene!(pDevice);
|
||||
}
|
||||
}
|
||||
286
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
286
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/GameMatrixCapture.cs
|
||||
// Captures the game's camera transform and perspective Projection matrix
|
||||
// for WorldToScreen projection.
|
||||
//
|
||||
// AC sets View=identity and World=identity — it transforms all vertices
|
||||
// on the CPU before sending to D3D9. Only the Projection matrix is real.
|
||||
//
|
||||
// Strategy:
|
||||
// - Hook SetTransform to capture the perspective Projection matrix.
|
||||
// - Read the camera position + rotation from SmartBox memory.
|
||||
// - Build the View matrix manually, then ViewProj = View * Proj.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class GameMatrixCapture
|
||||
{
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTransformD(IntPtr dev, uint state, float* pMatrix);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, int* pViewport);
|
||||
|
||||
// SetTransform hook
|
||||
private static SetTransformD? _originalSetTransform;
|
||||
private static SetTransformD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
|
||||
// Viewport
|
||||
private static GetViewportD? _getViewport;
|
||||
private static bool _viewportCached;
|
||||
private static uint _vpWidth;
|
||||
private static uint _vpHeight;
|
||||
private static bool _hasViewport;
|
||||
|
||||
// Captured Projection matrix
|
||||
private static readonly float[] _perspProj = new float[16];
|
||||
private static bool _hasProj;
|
||||
|
||||
// Computed matrices
|
||||
private static readonly float[] _viewMatrix = new float[16];
|
||||
private static readonly float[] _viewProj = new float[16];
|
||||
private static bool _hasValidViewProj;
|
||||
|
||||
// Camera frame from SmartBox memory (same layout as UB Camera.cs)
|
||||
private const int CameraFrameOffset = 0x08;
|
||||
private const int CamRotOffset = 0x18; // 3x3 rotation matrix
|
||||
private const int CamPosOffset = 0x3C; // position (x, y, z)
|
||||
|
||||
// Diagnostics
|
||||
private static int _framesSinceLog;
|
||||
private static bool _loggedFirstCapture;
|
||||
|
||||
public static bool HasCapturedFrame => _hasValidViewProj;
|
||||
public static uint ViewportWidth => _vpWidth;
|
||||
public static uint ViewportHeight => _vpHeight;
|
||||
|
||||
/// <summary>Copy the 4x4 View matrix (row-major) into the destination.</summary>
|
||||
public static void GetViewMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _viewMatrix)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copy the 4x4 Projection matrix (row-major) into the destination.</summary>
|
||||
public static void GetProjectionMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _perspProj)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
private static int SetTransformDetour(IntPtr dev, uint state, float* pMatrix)
|
||||
{
|
||||
if (pMatrix != null && state == D3DTS_PROJECTION)
|
||||
{
|
||||
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
|
||||
if (isPerspective)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
_perspProj[i] = pMatrix[i];
|
||||
_hasProj = true;
|
||||
}
|
||||
}
|
||||
return _originalSetTransform!(dev, state, pMatrix);
|
||||
}
|
||||
|
||||
public static void CaptureFrame(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_hookInstalled)
|
||||
InstallHook(pDevice);
|
||||
|
||||
// Read viewport
|
||||
if (!_viewportCached)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_getViewport = Marshal.GetDelegateForFunctionPointer<GetViewportD>(
|
||||
Marshal.ReadIntPtr(vtable, DeviceVTableIndex.GetViewport * IntPtr.Size));
|
||||
_viewportCached = true;
|
||||
}
|
||||
|
||||
int* vp = stackalloc int[6];
|
||||
if (_getViewport!(pDevice, vp) >= 0 && vp[2] > 0 && vp[3] > 0)
|
||||
{
|
||||
_vpWidth = (uint)vp[2];
|
||||
_vpHeight = (uint)vp[3];
|
||||
_hasViewport = true;
|
||||
}
|
||||
|
||||
if (_hasProj)
|
||||
BuildViewProjFromCamera();
|
||||
|
||||
_framesSinceLog++;
|
||||
if (_framesSinceLog >= 3000)
|
||||
{
|
||||
_framesSinceLog = 0;
|
||||
RynthLog.D3D9($"GameMatrixCapture: valid={_hasValidViewProj} vp={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildViewProjFromCamera()
|
||||
{
|
||||
if (!SmartBoxLocator.TryGetSmartBox(out IntPtr smartBox, out _, out _))
|
||||
return;
|
||||
|
||||
IntPtr camFrame = smartBox + CameraFrameOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(camFrame + CamPosOffset, 12))
|
||||
return;
|
||||
|
||||
// Read 3x3 rotation matrix
|
||||
float m11 = ReadFloat(camFrame + CamRotOffset + 0);
|
||||
float m12 = ReadFloat(camFrame + CamRotOffset + 4);
|
||||
float m13 = ReadFloat(camFrame + CamRotOffset + 8);
|
||||
float m21 = ReadFloat(camFrame + CamRotOffset + 12);
|
||||
float m22 = ReadFloat(camFrame + CamRotOffset + 16);
|
||||
float m23 = ReadFloat(camFrame + CamRotOffset + 20);
|
||||
float m31 = ReadFloat(camFrame + CamRotOffset + 24);
|
||||
float m32 = ReadFloat(camFrame + CamRotOffset + 28);
|
||||
float m33 = ReadFloat(camFrame + CamRotOffset + 32);
|
||||
|
||||
// Read position (AC physics: x=EW, y=NS, z=height)
|
||||
float cx = ReadFloat(camFrame + CamPosOffset + 0);
|
||||
float cy = ReadFloat(camFrame + CamPosOffset + 4);
|
||||
float cz = ReadFloat(camFrame + CamPosOffset + 8);
|
||||
|
||||
if (cx == 0f && cy == 0f && cz == 0f)
|
||||
return;
|
||||
|
||||
// View matrix rotation block (D3D Y-up, with AC Y/Z swap).
|
||||
// AC camera rows: row1=Right, row2=Forward, row3=Up
|
||||
// After Y/Z component swap → D3D basis vectors as columns:
|
||||
// col0 = Right_d3d = (m11, m13, m12)
|
||||
// col1 = Up_d3d = (m31, m33, m32)
|
||||
// col2 = Forward_d3d = (m21, m23, m22)
|
||||
_viewMatrix[0] = m11; _viewMatrix[1] = m31; _viewMatrix[2] = m21; _viewMatrix[3] = 0;
|
||||
_viewMatrix[4] = m13; _viewMatrix[5] = m33; _viewMatrix[6] = m23; _viewMatrix[7] = 0;
|
||||
_viewMatrix[8] = m12; _viewMatrix[9] = m32; _viewMatrix[10] = m22; _viewMatrix[11] = 0;
|
||||
|
||||
// Translation = -CamPos_D3D * R_view
|
||||
// CamPos_D3D = (cx, cz, cy) after Y/Z swap
|
||||
float px = cx; // EW
|
||||
float py = cz; // height (D3D Y)
|
||||
float pz = cy; // NS (D3D Z)
|
||||
|
||||
_viewMatrix[12] = -(px * _viewMatrix[0] + py * _viewMatrix[4] + pz * _viewMatrix[8]);
|
||||
_viewMatrix[13] = -(px * _viewMatrix[1] + py * _viewMatrix[5] + pz * _viewMatrix[9]);
|
||||
_viewMatrix[14] = -(px * _viewMatrix[2] + py * _viewMatrix[6] + pz * _viewMatrix[10]);
|
||||
_viewMatrix[15] = 1;
|
||||
|
||||
// ViewProj = View * Projection
|
||||
fixed (float* v = _viewMatrix)
|
||||
fixed (float* p = _perspProj)
|
||||
fixed (float* r = _viewProj)
|
||||
{
|
||||
for (int row = 0; row < 4; row++)
|
||||
for (int col = 0; col < 4; col++)
|
||||
r[row * 4 + col] =
|
||||
v[row * 4 + 0] * p[0 * 4 + col] +
|
||||
v[row * 4 + 1] * p[1 * 4 + col] +
|
||||
v[row * 4 + 2] * p[2 * 4 + col] +
|
||||
v[row * 4 + 3] * p[3 * 4 + col];
|
||||
}
|
||||
|
||||
if (!_loggedFirstCapture)
|
||||
{
|
||||
_loggedFirstCapture = true;
|
||||
RynthLog.D3D9($"GameMatrixCapture: camera pos=({cx:F2},{cy:F2},{cz:F2}) [EW,NS,Z]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row0=[{_viewMatrix[0]:F4}, {_viewMatrix[1]:F4}, {_viewMatrix[2]:F4}, {_viewMatrix[3]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row1=[{_viewMatrix[4]:F4}, {_viewMatrix[5]:F4}, {_viewMatrix[6]:F4}, {_viewMatrix[7]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row2=[{_viewMatrix[8]:F4}, {_viewMatrix[9]:F4}, {_viewMatrix[10]:F4}, {_viewMatrix[11]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row3=[{_viewMatrix[12]:F4}, {_viewMatrix[13]:F4}, {_viewMatrix[14]:F4}, {_viewMatrix[15]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
|
||||
_hasValidViewProj = true;
|
||||
}
|
||||
|
||||
private static float ReadFloat(IntPtr address)
|
||||
{
|
||||
int bits = Marshal.ReadInt32(address);
|
||||
return BitConverter.Int32BitsToSingle(bits);
|
||||
}
|
||||
|
||||
public static bool WorldToScreen(float wx, float wy, float wz, out float sx, out float sy)
|
||||
{
|
||||
sx = 0f;
|
||||
sy = 0f;
|
||||
|
||||
if (!_hasValidViewProj || _vpWidth == 0 || _vpHeight == 0)
|
||||
return false;
|
||||
|
||||
float clipX = wx * _viewProj[0] + wy * _viewProj[4] + wz * _viewProj[8] + _viewProj[12];
|
||||
float clipY = wx * _viewProj[1] + wy * _viewProj[5] + wz * _viewProj[9] + _viewProj[13];
|
||||
float clipW = wx * _viewProj[3] + wy * _viewProj[7] + wz * _viewProj[11] + _viewProj[15];
|
||||
|
||||
if (clipW <= 0.001f)
|
||||
return false;
|
||||
|
||||
float ndcX = clipX / clipW;
|
||||
float ndcY = clipY / clipW;
|
||||
|
||||
sx = (ndcX + 1.0f) * 0.5f * _vpWidth;
|
||||
sy = (1.0f - ndcY) * 0.5f * _vpHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int WorldToScreenCallback(float wx, float wy, float wz, float* sx, float* sy)
|
||||
{
|
||||
bool result = WorldToScreen(wx, wy, wz, out float screenX, out float screenY);
|
||||
*sx = screenX;
|
||||
*sy = screenY;
|
||||
return result ? 1 : 0;
|
||||
}
|
||||
|
||||
public static int GetViewportSizeCallback(uint* width, uint* height)
|
||||
{
|
||||
if (!_hasViewport || _vpWidth == 0 || _vpHeight == 0)
|
||||
return 0;
|
||||
|
||||
*width = _vpWidth;
|
||||
*height = _vpHeight;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void InstallHook(IntPtr pDevice)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new SetTransformD(SetTransformDetour);
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalSetTransform = Marshal.GetDelegateForFunctionPointer<SetTransformD>(MinHook.HookCreate(setTransformAddr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(setTransformAddr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("GameMatrixCapture: SetTransform hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"GameMatrixCapture: SetTransform hook FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderInjector.cs
|
||||
// Hooks DrawIndexedPrimitive to inject nav marker rendering at the
|
||||
// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers
|
||||
// so they appear after the 3D world but before the game's UI pass.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderInjector
|
||||
{
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawIndexedPrimitiveD(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount);
|
||||
|
||||
private static DrawIndexedPrimitiveD? _originalDIP;
|
||||
private static DrawIndexedPrimitiveD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
private static bool _inRender;
|
||||
|
||||
// Per-frame transition detection
|
||||
private static uint _lastZEnable;
|
||||
private static bool _markersRenderedThisFrame;
|
||||
private static bool _seen3D;
|
||||
|
||||
public static bool RenderedThisFrame => _markersRenderedThisFrame;
|
||||
|
||||
public static void ResetFrame()
|
||||
{
|
||||
_markersRenderedThisFrame = false;
|
||||
_seen3D = false;
|
||||
_lastZEnable = 0;
|
||||
}
|
||||
|
||||
public static void Install(IntPtr pDevice)
|
||||
{
|
||||
if (_hookInstalled) return;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalDIP = Marshal.GetDelegateForFunctionPointer<DrawIndexedPrimitiveD>(
|
||||
MinHook.HookCreate(addr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(addr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"Nav3DRenderInjector: Hook install FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int Detour(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount)
|
||||
{
|
||||
if (_inRender)
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
|
||||
ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable);
|
||||
|
||||
if (zEnable != 0)
|
||||
_seen3D = true;
|
||||
|
||||
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
|
||||
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
|
||||
{
|
||||
_markersRenderedThisFrame = true;
|
||||
_inRender = true;
|
||||
try
|
||||
{
|
||||
ImGuiBackend.DX9Backend.RenderNav3D(dev);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
_inRender = false;
|
||||
}
|
||||
|
||||
_lastZEnable = zEnable;
|
||||
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
}
|
||||
}
|
||||
84
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
84
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderer.cs
|
||||
// Data store for 3D navigation markers. Plugins submit geometry each frame
|
||||
// via AddRing/AddLine; DX9Backend.RenderNav3D reads it during EndScene.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderer
|
||||
{
|
||||
private const int MaxRings = 128;
|
||||
private const int MaxLines = 128;
|
||||
|
||||
// Ring: center(x,y,z) + radius + thickness + color
|
||||
private static readonly float[] _ringX = new float[MaxRings];
|
||||
private static readonly float[] _ringY = new float[MaxRings];
|
||||
private static readonly float[] _ringZ = new float[MaxRings];
|
||||
private static readonly float[] _ringRadius = new float[MaxRings];
|
||||
private static readonly float[] _ringThick = new float[MaxRings];
|
||||
private static readonly uint[] _ringColor = new uint[MaxRings];
|
||||
private static int _ringCount;
|
||||
|
||||
// Line: endpoints + thickness + color
|
||||
private static readonly float[] _lineX1 = new float[MaxLines];
|
||||
private static readonly float[] _lineY1 = new float[MaxLines];
|
||||
private static readonly float[] _lineZ1 = new float[MaxLines];
|
||||
private static readonly float[] _lineX2 = new float[MaxLines];
|
||||
private static readonly float[] _lineY2 = new float[MaxLines];
|
||||
private static readonly float[] _lineZ2 = new float[MaxLines];
|
||||
private static readonly float[] _lineThick = new float[MaxLines];
|
||||
private static readonly uint[] _lineColor = new uint[MaxLines];
|
||||
private static int _lineCount;
|
||||
|
||||
public static int RingCount => _ringCount;
|
||||
public static int LineCount => _lineCount;
|
||||
|
||||
public static void ClearFrame()
|
||||
{
|
||||
_ringCount = 0;
|
||||
_lineCount = 0;
|
||||
}
|
||||
|
||||
public static void AddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
|
||||
{
|
||||
if (_ringCount >= MaxRings) return;
|
||||
int i = _ringCount++;
|
||||
_ringX[i] = wx; _ringY[i] = wy; _ringZ[i] = wz;
|
||||
_ringRadius[i] = radius;
|
||||
_ringThick[i] = thickness;
|
||||
_ringColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
{
|
||||
if (_lineCount >= MaxLines) return;
|
||||
int i = _lineCount++;
|
||||
_lineX1[i] = x1; _lineY1[i] = y1; _lineZ1[i] = z1;
|
||||
_lineX2[i] = x2; _lineY2[i] = y2; _lineZ2[i] = z2;
|
||||
_lineThick[i] = thickness;
|
||||
_lineColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void GetRing(int i, out float x, out float y, out float z,
|
||||
out float radius, out float thickness, out uint color)
|
||||
{
|
||||
x = _ringX[i]; y = _ringY[i]; z = _ringZ[i];
|
||||
radius = _ringRadius[i]; thickness = _ringThick[i]; color = _ringColor[i];
|
||||
}
|
||||
|
||||
public static void GetLine(int i, out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2, out float thickness, out uint color)
|
||||
{
|
||||
x1 = _lineX1[i]; y1 = _lineY1[i]; z1 = _lineZ1[i];
|
||||
x2 = _lineX2[i]; y2 = _lineY2[i]; z2 = _lineZ2[i];
|
||||
thickness = _lineThick[i]; color = _lineColor[i];
|
||||
}
|
||||
|
||||
// C ABI callbacks for plugin contract
|
||||
public static void Nav3DClearCallback() => ClearFrame();
|
||||
public static void Nav3DAddRingCallback(float wx, float wy, float wz, float radius, float thickness, uint color)
|
||||
=> AddRing(wx, wy, wz, radius, thickness, color);
|
||||
public static void Nav3DAddLineCallback(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint color)
|
||||
=> AddLine(x1, y1, z1, x2, y2, z2, thickness, color);
|
||||
}
|
||||
485
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
485
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - D3D9/OverlayTextureRenderer.cs
|
||||
// Consumes BGRA frames from OverlayFrameBuffer and composites them onto
|
||||
// the D3D9 back buffer as a fullscreen alpha-blended quad.
|
||||
//
|
||||
// Called at the end of OnEndScene, after ImGui has already rendered.
|
||||
// Uses D3DFVF_XYZRHW | D3DFVF_TEX1 (pre-transformed vertices) so no
|
||||
// projection matrix setup is needed.
|
||||
//
|
||||
// Pixel format: Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — no swizzle.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class OverlayTextureRenderer
|
||||
{
|
||||
private static readonly Guid IID_IDirect3DDevice9Ex = new("B18B10CE-2649-405A-870F-95F777D4313A");
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────────
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
private const uint D3DUSAGE_RENDERTARGET = 0x00000001;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21;
|
||||
private const uint D3DPOOL_DEFAULT = 0;
|
||||
private const uint D3DPOOL_MANAGED = 1;
|
||||
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
|
||||
private const uint D3DTSS_COLOROP = 1;
|
||||
private const uint D3DTSS_COLORARG1 = 2;
|
||||
private const uint D3DTSS_COLORARG2 = 3;
|
||||
private const uint D3DTSS_ALPHAOP = 4;
|
||||
private const uint D3DTSS_ALPHAARG1 = 5;
|
||||
private const uint D3DTSS_ALPHAARG2 = 6;
|
||||
|
||||
private const uint D3DTOP_MODULATE = 4;
|
||||
private const uint D3DTA_TEXTURE = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
||||
private const uint D3DSAMP_MINFILTER = 5;
|
||||
private const uint D3DSAMP_MAGFILTER = 6;
|
||||
private const uint D3DTEXF_LINEAR = 2;
|
||||
private const uint D3DTEXF_POINT = 1;
|
||||
|
||||
// D3DFVF_XYZRHW | D3DFVF_TEX1
|
||||
private const uint FVF = 0x004 | 0x100;
|
||||
|
||||
// ─── Vertex (pre-transformed screen-space + UV) ────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct QuadVertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public float U, V;
|
||||
}
|
||||
|
||||
// ─── D3D9 struct ──────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DVIEWPORT9
|
||||
{
|
||||
public uint X, Y, Width, Height;
|
||||
public float MinZ, MaxZ;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DLOCKED_RECT
|
||||
{
|
||||
public int Pitch;
|
||||
public IntPtr pBits;
|
||||
}
|
||||
|
||||
// ─── Vtable delegates ─────────────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr pShared);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetSamplerStateD(IntPtr dev, uint sampler, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFD(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateD(IntPtr dev, uint state, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetVertexShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetPixelShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, D3DVIEWPORT9* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseD(IntPtr pObj);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int QueryInterfaceD(IntPtr pObj, Guid* riid, out IntPtr ppvObject);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexLockRectD(IntPtr pTex, uint level, D3DLOCKED_RECT* pLocked, IntPtr pRect, uint flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexUnlockRectD(IntPtr pTex, uint level);
|
||||
|
||||
// ─── Cached delegates ─────────────────────────────────────────────────
|
||||
private static CreateTextureD? _createTexture;
|
||||
private static SetTextureD? _setTexture;
|
||||
private static SetTextureStageStateD? _setTexStageState;
|
||||
private static SetSamplerStateD? _setSamplerState;
|
||||
private static SetFVFD? _setFVF;
|
||||
private static SetRenderStateD? _setRenderState;
|
||||
private static GetRenderStateD? _getRenderState;
|
||||
private static SetVertexShaderD? _setVertexShader;
|
||||
private static GetVertexShaderD? _getVertexShader;
|
||||
private static SetPixelShaderD? _setPixelShader;
|
||||
private static GetPixelShaderD? _getPixelShader;
|
||||
private static GetViewportD? _getViewport;
|
||||
private static DrawPrimitiveUPD? _drawPrimitiveUP;
|
||||
private static QueryInterfaceD? _queryInterface;
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────────
|
||||
private static IntPtr _texture;
|
||||
private static IntPtr _sharedTextureHandle;
|
||||
private static int _texW;
|
||||
private static int _texH;
|
||||
private static bool _delegatesCached;
|
||||
private static bool _sharedInteropProbed;
|
||||
private static bool _sharedInteropSupported;
|
||||
|
||||
// ─── Public entry point ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Called from EndScene (D3D9 render thread) after ImGui has rendered.
|
||||
/// Uploads any pending Avalonia frame to the texture and draws it.
|
||||
/// </summary>
|
||||
public static void Render(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_delegatesCached)
|
||||
{
|
||||
CacheDelegates(pDevice);
|
||||
_delegatesCached = true;
|
||||
}
|
||||
|
||||
// Learn as early as possible whether this game device can consume shared
|
||||
// textures. That lets the producer stay on software submissions only on
|
||||
// unsupported clients instead of discovering it mid-session.
|
||||
if (OverlaySurfaceBridge.ActiveSupportsGpuInterop && !_sharedInteropProbed)
|
||||
EnsureSharedInteropSupport(pDevice);
|
||||
|
||||
// Upload new frame if one is available
|
||||
if (OverlaySurfaceBridge.TryConsume(out OverlaySurfaceFrame? frame) && frame != null)
|
||||
{
|
||||
switch (frame.Kind)
|
||||
{
|
||||
case OverlaySurfaceKind.SoftwareBgra32 when frame.SoftwarePixels != null:
|
||||
UploadFrame(pDevice, frame.SoftwarePixels, frame.Width, frame.Height);
|
||||
break;
|
||||
case OverlaySurfaceKind.AngleSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "ANGLE", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("ANGLE", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.DxgiSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "DXGI", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("DXGI", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.D3D9SharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "D3D9Ex", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("D3D9Ex", frame.SharedTexture);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
DrawQuad(pDevice);
|
||||
}
|
||||
|
||||
private static void LogSharedTextureStub(string label, OverlaySharedTextureDescriptor? descriptor)
|
||||
{
|
||||
if (descriptor == null)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: {label} shared texture frame arrived without a descriptor.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: {label} shared texture interop is not implemented yet " +
|
||||
$"(handle=0x{descriptor.Value.SharedHandle:X8}, size={descriptor.Value.Width}x{descriptor.Value.Height}, adapterLuid=0x{descriptor.Value.AdapterLuid:X}).");
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
ReleaseTexture();
|
||||
_delegatesCached = false;
|
||||
_sharedInteropProbed = false;
|
||||
_sharedInteropSupported = false;
|
||||
}
|
||||
|
||||
// ─── Upload ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void UploadFrame(IntPtr pDevice, byte[] pixels, int w, int h)
|
||||
{
|
||||
// Recreate texture if dimensions changed
|
||||
if (_texture == IntPtr.Zero || w != _texW || h != _texH || _sharedTextureHandle != IntPtr.Zero)
|
||||
{
|
||||
ReleaseTexture();
|
||||
|
||||
int hr = _createTexture!(pDevice, (uint)w, (uint)h, 1, 0,
|
||||
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out _texture, IntPtr.Zero);
|
||||
|
||||
if (hr < 0 || _texture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: CreateTexture({w}x{h}) failed HRESULT=0x{hr:X8}");
|
||||
return;
|
||||
}
|
||||
|
||||
_texW = w;
|
||||
_texH = h;
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: Created {w}x{h} overlay texture.");
|
||||
}
|
||||
|
||||
// Lock → copy → unlock
|
||||
var lockRect = GetTexMethod<TexLockRectD>(_texture, TextureVTableIndex.LockRect);
|
||||
var unlockRect = GetTexMethod<TexUnlockRectD>(_texture, TextureVTableIndex.UnlockRect);
|
||||
|
||||
D3DLOCKED_RECT locked;
|
||||
if (lockRect(_texture, 0, &locked, IntPtr.Zero, 0) < 0)
|
||||
return;
|
||||
|
||||
// Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — direct copy, no swizzle
|
||||
int srcStride = w * 4;
|
||||
for (int row = 0; row < h; row++)
|
||||
{
|
||||
IntPtr dst = locked.pBits + row * locked.Pitch;
|
||||
fixed (byte* src = pixels)
|
||||
Buffer.MemoryCopy(src + row * srcStride, (void*)dst, srcStride, srcStride);
|
||||
}
|
||||
|
||||
unlockRect(_texture, 0);
|
||||
}
|
||||
|
||||
private static bool TryUseSharedTexture(IntPtr pDevice, string label, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
if (descriptor.SharedHandle == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
if (!EnsureSharedInteropSupport(pDevice))
|
||||
return false;
|
||||
|
||||
if (_texture != IntPtr.Zero &&
|
||||
_sharedTextureHandle == descriptor.SharedHandle &&
|
||||
_texW == descriptor.Width &&
|
||||
_texH == descriptor.Height)
|
||||
{
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
return true;
|
||||
}
|
||||
|
||||
IntPtr openedTexture = IntPtr.Zero;
|
||||
IntPtr sharedHandle = descriptor.SharedHandle;
|
||||
uint usage = descriptor.Usage != 0 ? (uint)descriptor.Usage : D3DUSAGE_RENDERTARGET;
|
||||
uint format = descriptor.PixelFormat != 0 ? (uint)descriptor.PixelFormat : D3DFMT_A8R8G8B8;
|
||||
int hr = _createTexture!(
|
||||
pDevice,
|
||||
(uint)descriptor.Width,
|
||||
(uint)descriptor.Height,
|
||||
1,
|
||||
usage,
|
||||
format,
|
||||
D3DPOOL_DEFAULT,
|
||||
out openedTexture,
|
||||
new IntPtr(&sharedHandle));
|
||||
|
||||
if (hr < 0 || openedTexture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Failed to open {label} shared texture handle 0x{descriptor.SharedHandle:X8}, HRESULT=0x{hr:X8}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
ReleaseTexture();
|
||||
_texture = openedTexture;
|
||||
_sharedTextureHandle = descriptor.SharedHandle;
|
||||
_texW = descriptor.Width;
|
||||
_texH = descriptor.Height;
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Opened {label} shared texture handle 0x{descriptor.SharedHandle:X8} ({descriptor.Width}x{descriptor.Height}).");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool EnsureSharedInteropSupport(IntPtr pDevice)
|
||||
{
|
||||
if (_sharedInteropProbed)
|
||||
return _sharedInteropSupported;
|
||||
|
||||
_sharedInteropProbed = true;
|
||||
|
||||
if (_queryInterface == null)
|
||||
{
|
||||
RynthLog.D3D9("OverlayTextureRenderer: Shared-texture probe unavailable because QueryInterface is not cached.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr exDevice = IntPtr.Zero;
|
||||
Guid iid = IID_IDirect3DDevice9Ex;
|
||||
int hr = _queryInterface(pDevice, &iid, out exDevice);
|
||||
if (hr >= 0 && exDevice != IntPtr.Zero)
|
||||
{
|
||||
_sharedInteropSupported = true;
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is available on the active game device.");
|
||||
ReleaseComObject(exDevice);
|
||||
return true;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is unavailable on the active game device; software fallback will remain active.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Draw ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void DrawQuad(IntPtr pDevice)
|
||||
{
|
||||
// Get current viewport to size the quad
|
||||
D3DVIEWPORT9 vp;
|
||||
if (_getViewport!(pDevice, &vp) < 0)
|
||||
return;
|
||||
|
||||
float W = vp.Width;
|
||||
float H = vp.Height;
|
||||
|
||||
// Tell the Avalonia thread what the current viewport size is so it can
|
||||
// keep the canvas sized correctly (prevents stretch/scale artifacts).
|
||||
int viewportWidth = (int)W;
|
||||
int viewportHeight = (int)H;
|
||||
bool viewportChanged =
|
||||
AvaloniaOverlay.ViewportWidth != viewportWidth ||
|
||||
AvaloniaOverlay.ViewportHeight != viewportHeight;
|
||||
AvaloniaOverlay.ViewportWidth = viewportWidth;
|
||||
AvaloniaOverlay.ViewportHeight = viewportHeight;
|
||||
if (viewportChanged)
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
|
||||
// Save render states we will change
|
||||
_getRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, out uint savedAlpha);
|
||||
_getRenderState!(pDevice, D3DRS_SRCBLEND, out uint savedSrcBlend);
|
||||
_getRenderState!(pDevice, D3DRS_DESTBLEND, out uint savedDstBlend);
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint savedZ);
|
||||
_getRenderState!(pDevice, D3DRS_CULLMODE, out uint savedCull);
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint savedLighting);
|
||||
_getRenderState!(pDevice, D3DRS_COLORWRITEENABLE, out uint savedColorWrite);
|
||||
_getVertexShader!(pDevice, out IntPtr savedVS);
|
||||
_getPixelShader!(pDevice, out IntPtr savedPS);
|
||||
|
||||
try
|
||||
{
|
||||
// Set up fixed-function alpha-blended state
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
_setPixelShader!(pDevice, IntPtr.Zero);
|
||||
|
||||
_setFVF!(pDevice, FVF);
|
||||
_setTexture!(pDevice, 0, _texture);
|
||||
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
|
||||
|
||||
QuadVertex* verts = stackalloc QuadVertex[4];
|
||||
verts[0] = new QuadVertex { X = 0, Y = 0, Z = 0, RHW = 1, U = 0, V = 0 };
|
||||
verts[1] = new QuadVertex { X = W, Y = 0, Z = 0, RHW = 1, U = 1, V = 0 };
|
||||
verts[2] = new QuadVertex { X = 0, Y = H, Z = 0, RHW = 1, U = 0, V = 1 };
|
||||
verts[3] = new QuadVertex { X = W, Y = H, Z = 0, RHW = 1, U = 1, V = 1 };
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2,
|
||||
new IntPtr(verts), (uint)sizeof(QuadVertex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restore changed state
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, savedAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, savedSrcBlend);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, savedDstBlend);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, savedZ);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, savedCull);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, savedLighting);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, savedColorWrite);
|
||||
_setVertexShader!(pDevice, savedVS);
|
||||
_setPixelShader!(pDevice, savedPS);
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero);
|
||||
|
||||
if (savedVS != IntPtr.Zero) ReleaseComObject(savedVS);
|
||||
if (savedPS != IntPtr.Zero) ReleaseComObject(savedPS);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void ReleaseTexture()
|
||||
{
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
var release = GetTexMethod<ReleaseD>(_texture, TextureVTableIndex.Release);
|
||||
release(_texture);
|
||||
_texture = IntPtr.Zero;
|
||||
_sharedTextureHandle = IntPtr.Zero;
|
||||
_texW = 0;
|
||||
_texH = 0;
|
||||
}
|
||||
|
||||
private static void ReleaseComObject(IntPtr pObj)
|
||||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
|
||||
var rel = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size));
|
||||
rel(pObj);
|
||||
}
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_createTexture = Get<CreateTextureD>(vtable, DeviceVTableIndex.CreateTexture);
|
||||
_setTexture = Get<SetTextureD>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_setTexStageState = Get<SetTextureStageStateD>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_setSamplerState = Get<SetSamplerStateD>(vtable, DeviceVTableIndex.SetSamplerState);
|
||||
_setFVF = Get<SetFVFD>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_setRenderState = Get<SetRenderStateD>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateD>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setVertexShader = Get<SetVertexShaderD>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_getVertexShader = Get<GetVertexShaderD>(vtable, DeviceVTableIndex.GetVertexShader);
|
||||
_setPixelShader = Get<SetPixelShaderD>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_getPixelShader = Get<GetPixelShaderD>(vtable, DeviceVTableIndex.GetPixelShader);
|
||||
_getViewport = Get<GetViewportD>(vtable, DeviceVTableIndex.GetViewport);
|
||||
_drawPrimitiveUP = Get<DrawPrimitiveUPD>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_queryInterface = Get<QueryInterfaceD>(vtable, 0);
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static T GetTexMethod<T>(IntPtr pTex, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pTex);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
}
|
||||
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/TestRenderer.cs
|
||||
// Draws a small colored rectangle in the top-left corner of the game.
|
||||
// Pure D3D9 via vtable calls — no dependencies on any overlay framework.
|
||||
//
|
||||
// Uses pre-transformed vertices (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) so no
|
||||
// world/view/projection matrices needed. The rectangle is screen-space.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class TestRenderer
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFVF_XYZRHW = 0x0004;
|
||||
private const uint D3DFVF_DIFFUSE = 0x0040;
|
||||
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
|
||||
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
|
||||
// D3DRENDERSTATETYPE
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
|
||||
// D3DBLEND
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
|
||||
// D3DTRANSFORMSTATETYPE
|
||||
private const uint D3DTS_WORLD = 256;
|
||||
private const uint D3DTS_VIEW = 2;
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
// ─── Vertex structure ─────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Vertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public uint Color; // ARGB
|
||||
|
||||
public Vertex(float x, float y, uint color)
|
||||
{
|
||||
X = x; Y = y; Z = 0f; RHW = 1f;
|
||||
Color = color;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Device method delegates (COM/stdcall) ────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateDelegate(IntPtr pDevice, uint state, uint value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateDelegate(IntPtr pDevice, uint state, out uint pValue);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureDelegate(IntPtr pDevice, uint stage, IntPtr pTexture);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFDelegate(IntPtr pDevice, uint fvf);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPDelegate(
|
||||
IntPtr pDevice, uint primitiveType, uint primitiveCount,
|
||||
IntPtr pVertexStreamZeroData, uint vertexStreamZeroStride);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateDelegate(IntPtr pDevice, uint stage, uint type, uint value);
|
||||
|
||||
// ─── Cached delegates (created once from vtable on first frame) ──
|
||||
private static SetRenderStateDelegate? _setRenderState;
|
||||
private static GetRenderStateDelegate? _getRenderState;
|
||||
private static SetTextureDelegate? _setTexture;
|
||||
private static SetFVFDelegate? _setFVF;
|
||||
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
|
||||
private static SetVertexShaderDelegate? _setVertexShader;
|
||||
private static SetPixelShaderDelegate? _setPixelShader;
|
||||
private static SetTextureStageStateDelegate? _setTextureStageState;
|
||||
private static bool _delegatesCached;
|
||||
|
||||
// ─── Rectangle config ─────────────────────────────────────────────
|
||||
// Bright green semi-transparent rectangle, top-left corner
|
||||
private const float RectX = 10f;
|
||||
private const float RectY = 10f;
|
||||
private const float RectW = 120f;
|
||||
private const float RectH = 40f;
|
||||
private const uint RectColor = 0xCC00FF00; // ARGB: green, ~80% opaque
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public static void Draw(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero) return;
|
||||
|
||||
// Cache vtable delegates on first call
|
||||
if (!_delegatesCached)
|
||||
CacheDelegates(pDevice);
|
||||
|
||||
// Save render states we'll modify
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint oldLighting);
|
||||
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint oldAlphaBlend);
|
||||
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint oldSrcBlend);
|
||||
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint oldDestBlend);
|
||||
_getRenderState(pDevice, D3DRS_ZENABLE, out uint oldZEnable);
|
||||
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint oldFogEnable);
|
||||
|
||||
// Set up for 2D overlay drawing
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0); // no lighting
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, 0); // no depth test
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, 0); // no fog
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1); // alpha blend on
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero); // no texture
|
||||
_setVertexShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setPixelShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setFVF!(pDevice, D3DFVF_CUSTOM);
|
||||
|
||||
// Build quad (triangle strip: TL, TR, BL, BR)
|
||||
var verts = stackalloc Vertex[4];
|
||||
verts[0] = new Vertex(RectX, RectY, RectColor);
|
||||
verts[1] = new Vertex(RectX + RectW, RectY, RectColor);
|
||||
verts[2] = new Vertex(RectX, RectY + RectH, RectColor);
|
||||
verts[3] = new Vertex(RectX + RectW, RectY + RectH, RectColor);
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2, (IntPtr)verts, (uint)sizeof(Vertex));
|
||||
|
||||
// Restore saved render states
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, oldLighting);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, oldAlphaBlend);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, oldSrcBlend);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, oldDestBlend);
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, oldZEnable);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, oldFogEnable);
|
||||
}
|
||||
|
||||
// ─── Internals ────────────────────────────────────────────────────
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
|
||||
_setRenderState = GetMethod<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = GetMethod<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setTexture = GetMethod<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_setFVF = GetMethod<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_drawPrimitiveUP = GetMethod<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_setVertexShader = GetMethod<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_setPixelShader = GetMethod<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_setTextureStageState = GetMethod<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
|
||||
_delegatesCached = true;
|
||||
RynthLog.D3D9("TestRenderer: D3D9 delegates cached.");
|
||||
}
|
||||
|
||||
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
}
|
||||
363
src/RynthCore.Engine/EntryPoint.cs
Normal file
363
src/RynthCore.Engine/EntryPoint.cs
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - EntryPoint.cs
|
||||
// NativeAOT exported function. Called by the injector after LoadLibrary.
|
||||
// Spawns init on a background thread to avoid loader-lock issues.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Collections.Generic;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
public static class EntryPoint
|
||||
{
|
||||
internal const string BuildStamp = "2026-03-30-v54-patternscan";
|
||||
private const int MaxRecentLogLines = 256;
|
||||
private static int _initialized;
|
||||
private static bool _imGuiResolverConfigured;
|
||||
private static IntPtr _imGuiNativeHandle;
|
||||
private static readonly object LogLock = new();
|
||||
private static readonly Queue<string> RecentLogLines = new();
|
||||
|
||||
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
|
||||
internal static bool VerboseLogging = false;
|
||||
|
||||
/// <summary>Set by ImGuiController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
|
||||
internal static volatile IntPtr GameHwnd;
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthCoreInit")]
|
||||
public static uint Initialize(IntPtr lpParam)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
|
||||
return 1;
|
||||
|
||||
try
|
||||
{
|
||||
RynthLog.Info($"RynthCoreInit called (build {BuildStamp}) - spawning init thread...");
|
||||
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
|
||||
|
||||
var thread = new Thread(InitWorker)
|
||||
{
|
||||
Name = "RynthCore.Init",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"FATAL in RynthCoreInit: {ex}");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleA(string lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetModuleFileNameW(IntPtr hModule, char[] lpFilename, uint nSize);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr LoadLibraryW(string lpLibFileName);
|
||||
|
||||
private static string? GetEngineDirectory()
|
||||
{
|
||||
IntPtr hEngine = GetModuleHandleA("RynthCore.Engine.dll");
|
||||
if (hEngine == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
var buffer = new char[512];
|
||||
uint length = GetModuleFileNameW(hEngine, buffer, (uint)buffer.Length);
|
||||
if (length == 0)
|
||||
return null;
|
||||
|
||||
return Path.GetDirectoryName(new string(buffer, 0, (int)length));
|
||||
}
|
||||
|
||||
private static bool PreloadNativeDll(string engineDir, string dllName)
|
||||
{
|
||||
foreach (string path in GetNativeDllCandidates(engineDir, dllName))
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
continue;
|
||||
|
||||
long fileSize = TryGetFileSize(path);
|
||||
RynthLog.Verbose(fileSize > 0
|
||||
? $"Preload: Loading {path} ({fileSize} bytes)"
|
||||
: $"Preload: Loading {path}");
|
||||
|
||||
IntPtr handle = LoadLibraryW(path);
|
||||
if (handle != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Verbose($"Preload: {dllName} OK (0x{handle:X8})");
|
||||
return true;
|
||||
}
|
||||
|
||||
RynthLog.Info($"Preload: FAILED to load {path} (error {Marshal.GetLastWin32Error()})");
|
||||
}
|
||||
|
||||
RynthLog.Info($"Preload: FAILED to find/load {dllName} from RynthCore directories.");
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool ConfigureImGuiNativeLibrary(string engineDir)
|
||||
{
|
||||
if (_imGuiResolverConfigured)
|
||||
return _imGuiNativeHandle != IntPtr.Zero;
|
||||
|
||||
foreach (string path in GetImGuiNativeCandidates(engineDir))
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
continue;
|
||||
|
||||
long fileSize = TryGetFileSize(path);
|
||||
RynthLog.Verbose(fileSize > 0
|
||||
? $"ImGuiNative: Loading {path} ({fileSize} bytes)"
|
||||
: $"ImGuiNative: Loading {path}");
|
||||
|
||||
_imGuiNativeHandle = LoadLibraryW(path);
|
||||
if (_imGuiNativeHandle == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Info($"ImGuiNative: FAILED to load {path} (error {Marshal.GetLastWin32Error()})");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
NativeLibrary.SetDllImportResolver(typeof(ImGui).Assembly, ResolveImGuiNativeLibrary);
|
||||
RynthLog.Verbose($"ImGuiNative: Resolver configured (0x{_imGuiNativeHandle:X8})");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
RynthLog.Info($"ImGuiNative: Resolver already set - {ex.Message}");
|
||||
}
|
||||
|
||||
_imGuiResolverConfigured = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
RynthLog.Info("ImGuiNative: FAILED to find/load a private cimgui runtime.");
|
||||
return false;
|
||||
}
|
||||
|
||||
private static IntPtr ResolveImGuiNativeLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
|
||||
{
|
||||
if (!string.Equals(libraryName, "cimgui", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(libraryName, "cimgui.dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
return _imGuiNativeHandle;
|
||||
}
|
||||
|
||||
private static string[] GetNativeDllCandidates(string engineDir, string dllName)
|
||||
{
|
||||
var candidates = new List<string>();
|
||||
foreach (string directory in GetEngineSearchDirectories(engineDir))
|
||||
AddCandidate(candidates, Path.Combine(directory, dllName));
|
||||
|
||||
return candidates.ToArray();
|
||||
}
|
||||
|
||||
private static string[] GetImGuiNativeCandidates(string engineDir)
|
||||
{
|
||||
var candidates = new List<string>();
|
||||
foreach (string directory in GetEngineSearchDirectories(engineDir))
|
||||
{
|
||||
AddCandidate(candidates, Path.Combine(directory, "RynthCore.cimgui.dll"));
|
||||
AddCandidate(candidates, Path.Combine(directory, "cimgui.dll"));
|
||||
}
|
||||
|
||||
return candidates.ToArray();
|
||||
}
|
||||
|
||||
private static IEnumerable<string> GetEngineSearchDirectories(string engineDir)
|
||||
{
|
||||
var directories = new List<string>();
|
||||
AddCandidate(directories, engineDir);
|
||||
|
||||
string normalizedEngineDir = Path.GetFullPath(engineDir);
|
||||
bool engineDirIsRuntime = string.Equals(
|
||||
Path.GetFileName(Path.TrimEndingDirectorySeparator(normalizedEngineDir)),
|
||||
"Runtime",
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (engineDirIsRuntime)
|
||||
{
|
||||
string? rootDir = Directory.GetParent(normalizedEngineDir)?.FullName;
|
||||
AddCandidate(directories, Path.Combine(normalizedEngineDir, "Native"));
|
||||
AddCandidate(directories, rootDir);
|
||||
if (!string.IsNullOrWhiteSpace(rootDir))
|
||||
AddCandidate(directories, Path.Combine(rootDir, "Native"));
|
||||
}
|
||||
else
|
||||
{
|
||||
string runtimeDir = Path.Combine(normalizedEngineDir, "Runtime");
|
||||
AddCandidate(directories, runtimeDir);
|
||||
AddCandidate(directories, Path.Combine(normalizedEngineDir, "Native"));
|
||||
AddCandidate(directories, Path.Combine(runtimeDir, "Native"));
|
||||
}
|
||||
|
||||
return directories;
|
||||
}
|
||||
|
||||
private static void AddCandidate(List<string> candidates, string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
return;
|
||||
|
||||
string fullPath = Path.GetFullPath(path);
|
||||
if (!candidates.Exists(existing => string.Equals(existing, fullPath, StringComparison.OrdinalIgnoreCase)))
|
||||
candidates.Add(fullPath);
|
||||
}
|
||||
|
||||
private static long TryGetFileSize(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new FileInfo(path).Length;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitWorker()
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthLog.Verbose("Init thread started.");
|
||||
|
||||
string? engineDir = GetEngineDirectory();
|
||||
if (engineDir == null)
|
||||
{
|
||||
RynthLog.Info("FATAL: Could not determine engine directory.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.Verbose($"Engine directory: {engineDir}");
|
||||
|
||||
if (!PreloadNativeDll(engineDir, "minhook.x86.dll"))
|
||||
{
|
||||
RynthLog.Info("FATAL: minhook.x86.dll required - aborting.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ConfigureImGuiNativeLibrary(engineDir))
|
||||
{
|
||||
RynthLog.Info("WARNING: cimgui runtime not found - ImGui will not be available.");
|
||||
RynthLog.Info(" Ship RynthCore.cimgui.dll (or cimgui.dll) alongside RynthCore.Engine.dll");
|
||||
}
|
||||
|
||||
RunInitStep("RynthAi action hooks", ClientActionHooks.Initialize);
|
||||
RunInitStep("client helper hooks", () => ClientHelperHooks.Probe());
|
||||
RunInitStep("login lifecycle hooks", LoginLifecycleHooks.Initialize);
|
||||
RunInitStep("session state registry", SessionStateRegistry.Initialize);
|
||||
RunInitStep("UI lifecycle hooks", UiLifecycleHooks.Initialize);
|
||||
RunInitStep("logo bypass", LogoBypassHooks.Start);
|
||||
RunInitStep("busy-count hooks", BusyCountHooks.Initialize);
|
||||
RunInitStep("combat-mode hooks", CombatModeHooks.Initialize);
|
||||
RunInitStep("client combat hooks", () => ClientCombatHooks.Probe());
|
||||
RunInitStep("selected-target hooks", SelectedTargetHooks.Initialize);
|
||||
RunInitStep("smartbox hooks", SmartBoxHooks.Initialize);
|
||||
RunInitStep("player vitals hooks", PlayerVitalsHooks.Initialize);
|
||||
RunInitStep("enchantment hooks", () => EnchantmentHooks.Initialize());
|
||||
RunInitStep("time-sync hook", TimeSyncHooks.Initialize);
|
||||
RunInitStep("create-object hooks", CreateObjectHooks.Initialize);
|
||||
RunInitStep("delete-object hooks", DeleteObjectHooks.Initialize);
|
||||
RunInitStep("update-object hooks", UpdateObjectServerDispatchHooks.Initialize);
|
||||
RunInitStep("vector-update hooks", VectorUpdateServerDispatchHooks.Initialize);
|
||||
RunInitStep("update-object-inventory hooks", UpdateObjectInventoryHooks.Initialize);
|
||||
RunInitStep("view-object-contents hooks", ViewObjectContentsHooks.Initialize);
|
||||
RunInitStep("chat callback hooks", ChatCallbackHooks.Initialize);
|
||||
RunInitStep("raw packet hooks", RawPacketHooks.Initialize);
|
||||
PluginManager.LoadPlugins(engineDir);
|
||||
|
||||
// Defer D3D9 hooking until after character login. By that point
|
||||
// the game's device is fully initialized and stable, avoiding the
|
||||
// race condition that intermittently crashes NULLREF device creation
|
||||
// on Win11's d3d9-on-d3d12 wrapper.
|
||||
LoginLifecycleHooks.LoginComplete += () =>
|
||||
{
|
||||
RynthLog.D3D9("D3D9: Login complete — starting D3D9 bootstrapper.");
|
||||
D3D9Bootstrapper.Start();
|
||||
};
|
||||
|
||||
// Avalonia overlay and its native dependencies (Skia, HarfBuzz, ANGLE)
|
||||
// are disabled. The ImGui shell handles all UI. Re-enable when needed.
|
||||
// PreloadNativeDll(engineDir, "libSkiaSharp.dll");
|
||||
// PreloadNativeDll(engineDir, "libHarfBuzzSharp.dll");
|
||||
// PreloadNativeDll(engineDir, "av_libglesv2.dll");
|
||||
// OverlayHost.RegisterPanel("Status", StatusPanel.Create);
|
||||
// OverlayHost.RegisterPanel("Log", LogPanel.Create);
|
||||
// OverlayHost.RegisterPanel("Hello Box", HelloBoxPanel.Create);
|
||||
// AvaloniaOverlay.Start();
|
||||
RynthLog.Info("RynthCore bootstrap initialized.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"FATAL in InitWorker: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RunInitStep(string name, Action action)
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: {name} failed during init - {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly string LogPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
|
||||
"RynthCore.log");
|
||||
|
||||
internal static void Log(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = $"[{DateTime.Now:HH:mm:ss.fff}] [pid:{Environment.ProcessId}] {message}";
|
||||
|
||||
lock (LogLock)
|
||||
{
|
||||
RecentLogLines.Enqueue(line);
|
||||
while (RecentLogLines.Count > MaxRecentLogLines)
|
||||
RecentLogLines.Dequeue();
|
||||
}
|
||||
|
||||
File.AppendAllText(LogPath, line + Environment.NewLine);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
internal static void LogVerbose(string message)
|
||||
{
|
||||
if (VerboseLogging)
|
||||
Log(message);
|
||||
}
|
||||
|
||||
internal static string[] GetRecentLogLines()
|
||||
{
|
||||
lock (LogLock)
|
||||
return RecentLogLines.ToArray();
|
||||
}
|
||||
}
|
||||
129
src/RynthCore.Engine/Hooking/MinHook.cs
Normal file
129
src/RynthCore.Engine/Hooking/MinHook.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — Hooking/MinHook.cs
|
||||
// Minimal P/Invoke wrapper for MinHook (minhook.x86.dll).
|
||||
//
|
||||
// Get the DLL from:
|
||||
// https://github.com/TsudaKageworthy/minhook/releases
|
||||
// Download minhook.x86.dll → place next to RynthCore.Engine.dll
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Hooking;
|
||||
|
||||
internal static class MinHook
|
||||
{
|
||||
private const string DLL = "minhook.x86.dll";
|
||||
|
||||
// ─── Status codes (must match MinHook's MH_STATUS enum) ────────────
|
||||
public const int MH_OK = 0;
|
||||
public const int MH_ERROR_ALREADY_INITIALIZED = 1;
|
||||
public const int MH_ERROR_NOT_INITIALIZED = 2;
|
||||
|
||||
// ─── Core API ─────────────────────────────────────────────────────
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_Initialize();
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_Uninitialize();
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_CreateHook(
|
||||
IntPtr pTarget,
|
||||
IntPtr pDetour,
|
||||
out IntPtr ppOriginal);
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_RemoveHook(IntPtr pTarget);
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_EnableHook(IntPtr pTarget);
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
public static extern int MH_DisableHook(IntPtr pTarget);
|
||||
|
||||
/// <summary>Enable/disable all hooks at once.</summary>
|
||||
public static readonly IntPtr MH_ALL_HOOKS = IntPtr.Zero;
|
||||
|
||||
// ─── Status to string ─────────────────────────────────────────────
|
||||
|
||||
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
|
||||
private static extern IntPtr MH_StatusToString(int status);
|
||||
|
||||
public static string StatusString(int status)
|
||||
{
|
||||
IntPtr ptr = MH_StatusToString(status);
|
||||
return ptr != IntPtr.Zero
|
||||
? Marshal.PtrToStringAnsi(ptr) ?? $"Unknown({status})"
|
||||
: $"Unknown({status})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Race-safe hook install for <c>[UnmanagedCallersOnly]</c> detours that store the
|
||||
/// original as an <c>IntPtr</c> field.
|
||||
///
|
||||
/// Writes <paramref name="original"/> (the trampoline pointer) BEFORE enabling the
|
||||
/// hook so a detour that fires immediately on the game thread never reads a zero
|
||||
/// original pointer. A memory barrier separates the write from MH_EnableHook.
|
||||
/// Throws on failure.
|
||||
/// </summary>
|
||||
public static void Hook(IntPtr target, IntPtr detour, out IntPtr original)
|
||||
{
|
||||
EnsureInitialized();
|
||||
|
||||
// MH_CreateHook writes the trampoline through the ref — the caller's field
|
||||
// is populated here, before the hook goes live.
|
||||
int status = MH_CreateHook(target, detour, out original);
|
||||
if (status != MH_OK)
|
||||
throw new InvalidOperationException($"MH_CreateHook failed: {StatusString(status)}");
|
||||
|
||||
// Full fence: ensure the write above is globally visible before
|
||||
// MH_EnableHook patches the target instruction.
|
||||
Thread.MemoryBarrier();
|
||||
|
||||
status = MH_EnableHook(target);
|
||||
if (status != MH_OK)
|
||||
throw new InvalidOperationException($"MH_EnableHook failed: {StatusString(status)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Race-safe hook install for delegate-based detours (two-step pattern).
|
||||
/// Call this first, then build and store the original delegate, add a
|
||||
/// <c>Thread.MemoryBarrier()</c>, then call <see cref="Enable"/>.
|
||||
///
|
||||
/// <code>
|
||||
/// IntPtr trampoline = MinHook.HookCreate(target, detourPtr);
|
||||
/// _originalDelegate = Marshal.GetDelegateForFunctionPointer<T>(trampoline);
|
||||
/// Thread.MemoryBarrier();
|
||||
/// MinHook.Enable(target);
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static IntPtr HookCreate(IntPtr target, IntPtr detour)
|
||||
{
|
||||
EnsureInitialized();
|
||||
|
||||
int status = MH_CreateHook(target, detour, out IntPtr original);
|
||||
if (status != MH_OK)
|
||||
throw new InvalidOperationException($"MH_CreateHook failed: {StatusString(status)}");
|
||||
|
||||
return original;
|
||||
}
|
||||
|
||||
/// <summary>Enables a hook previously created with <see cref="HookCreate"/>.</summary>
|
||||
public static void Enable(IntPtr target)
|
||||
{
|
||||
int status = MH_EnableHook(target);
|
||||
if (status != MH_OK)
|
||||
throw new InvalidOperationException($"MH_EnableHook failed: {StatusString(status)}");
|
||||
}
|
||||
|
||||
private static void EnsureInitialized()
|
||||
{
|
||||
int status = MH_Initialize();
|
||||
if (status != MH_OK && status != MH_ERROR_ALREADY_INITIALIZED)
|
||||
throw new InvalidOperationException($"MH_Initialize failed: {StatusString(status)}");
|
||||
}
|
||||
}
|
||||
1256
src/RynthCore.Engine/ImGui/DX9Backend.cs
Normal file
1256
src/RynthCore.Engine/ImGui/DX9Backend.cs
Normal file
File diff suppressed because it is too large
Load diff
270
src/RynthCore.Engine/ImGui/ImGuiController.cs
Normal file
270
src/RynthCore.Engine/ImGui/ImGuiController.cs
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/ImGuiController.cs
|
||||
// Top-level orchestrator: creates context, initializes backends,
|
||||
// and drives the NewFrame -> UI -> Render cycle from EndScene.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class ImGuiController
|
||||
{
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private static bool _initialized;
|
||||
private static bool _initFailed;
|
||||
private static bool _pluginsInitialized;
|
||||
private static IntPtr _context;
|
||||
private static IntPtr _gameHwnd;
|
||||
private static long _lastFrameTicks;
|
||||
private static int _frameCount;
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
{
|
||||
if (_initialized)
|
||||
return true;
|
||||
|
||||
// Prefer the actual D3D device window so startup does not latch onto a splash/loading HWND.
|
||||
_gameHwnd = DX9Backend.GetDeviceWindow(pDevice);
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("ImGuiController: D3D device window unavailable, falling back to EnumWindows.");
|
||||
_gameHwnd = FindGameWindow();
|
||||
}
|
||||
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("ImGuiController: Could not find game window.");
|
||||
return false;
|
||||
}
|
||||
|
||||
RynthLog.Render($"ImGuiController: Game HWND = 0x{_gameHwnd:X8}");
|
||||
EntryPoint.GameHwnd = _gameHwnd;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
if (previousContext != IntPtr.Zero)
|
||||
RynthLog.Render($"ImGuiController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
|
||||
|
||||
_context = ImGuiNET.ImGui.CreateContext();
|
||||
bool initSucceeded = false;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
|
||||
ImGuiNET.ImGui.StyleColorsDark();
|
||||
|
||||
if (!Win32Backend.Init(_gameHwnd))
|
||||
return false;
|
||||
|
||||
if (!DX9Backend.Init(pDevice))
|
||||
return false;
|
||||
|
||||
_lastFrameTicks = Stopwatch.GetTimestamp();
|
||||
_initialized = true;
|
||||
initSucceeded = true;
|
||||
|
||||
RynthLog.Render("ImGuiController: Fully initialized - RynthCore shell active.");
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!initSucceeded && _context != IntPtr.Zero)
|
||||
{
|
||||
ImGuiNET.ImGui.DestroyContext(_context);
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_initialized)
|
||||
return;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
IntPtr contextToDestroy = _context;
|
||||
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
|
||||
|
||||
PluginManager.ShutdownAll();
|
||||
OverlayTextureRenderer.Shutdown();
|
||||
DX9Backend.Shutdown();
|
||||
Win32Backend.Shutdown();
|
||||
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
||||
|
||||
_initialized = false;
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext == contextToDestroy ? IntPtr.Zero : previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void OnEndScene(IntPtr pDevice)
|
||||
{
|
||||
if (_initFailed)
|
||||
return;
|
||||
|
||||
if (!_initialized)
|
||||
{
|
||||
if (!Init(pDevice))
|
||||
{
|
||||
_initFailed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
bool frameStarted = false;
|
||||
bool frameEnded = false;
|
||||
|
||||
try
|
||||
{
|
||||
// Capture the game's View/Projection matrices before ImGui touches them
|
||||
GameMatrixCapture.CaptureFrame(pDevice);
|
||||
|
||||
// Install the SetRenderState hook that injects Nav3D rendering
|
||||
// before the game's 2D UI pass (once, after DX9Backend is ready)
|
||||
Nav3DRenderInjector.Install(pDevice);
|
||||
bool nav3DAlreadyRendered = Nav3DRenderInjector.RenderedThisFrame;
|
||||
Nav3DRenderInjector.ResetFrame();
|
||||
|
||||
// Initialize plugins once ImGui is fully ready
|
||||
if (!_pluginsInitialized)
|
||||
{
|
||||
_pluginsInitialized = true;
|
||||
PluginManager.InitPlugins(_context, pDevice, _gameHwnd);
|
||||
}
|
||||
|
||||
_frameCount++;
|
||||
DX9Backend.NewFrame();
|
||||
Win32Backend.NewFrame();
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
|
||||
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
|
||||
{
|
||||
DX9Backend.GetViewportSize(pDevice, out int vpW, out int vpH);
|
||||
if (vpW > 1 && vpH > 1)
|
||||
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
|
||||
}
|
||||
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
|
||||
_lastFrameTicks = now;
|
||||
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
|
||||
|
||||
// Drain queued host/plugin callbacks before opening the Dear ImGui frame.
|
||||
// This keeps heavy world-update bursts from stretching an already-active frame.
|
||||
// Drain queued host/plugin callbacks before opening the Dear ImGui frame.
|
||||
// This keeps heavy world-update bursts from stretching an already-active frame.
|
||||
PluginManager.ProcessPendingActions(_context, pDevice, _gameHwnd);
|
||||
|
||||
// Plugin tick (per-frame logic, before ImGui drawing)
|
||||
PluginManager.TickAll();
|
||||
|
||||
ImGuiNET.ImGui.NewFrame();
|
||||
frameStarted = true;
|
||||
RynthCoreShell.Render(_frameCount);
|
||||
|
||||
// Plugin render (ImGui draw calls)
|
||||
PluginManager.RenderAll();
|
||||
|
||||
bool captureMouse =
|
||||
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
|
||||
ImGuiNET.ImGui.IsAnyItemActive();
|
||||
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
|
||||
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
frameEnded = true;
|
||||
ImGuiNET.ImGui.Render();
|
||||
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
|
||||
|
||||
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
|
||||
// Frame diagnostics suppressed — ImGui is stable.
|
||||
|
||||
// Nav markers were rendered by Nav3DRenderInjector at the 3D→UI
|
||||
// transition. Fallback to EndScene if transition wasn't detected.
|
||||
if (!nav3DAlreadyRendered)
|
||||
DX9Backend.RenderNav3D(pDevice);
|
||||
|
||||
DX9Backend.RenderDrawData(drawData, pDevice);
|
||||
|
||||
// Composite the Avalonia overlay frame on top of ImGui
|
||||
OverlayTextureRenderer.Render(pDevice);
|
||||
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
ImGuiNET.ImGui.UpdatePlatformWindows();
|
||||
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Keep Dear ImGui's frame state balanced so the next frame does not assert.
|
||||
if (frameStarted && !frameEnded && ImGuiNET.ImGui.GetCurrentContext() == _context)
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
RynthLog.Render($"ImGuiController: frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr FindGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
IntPtr found = IntPtr.Zero;
|
||||
|
||||
EnumWindows((hWnd, _) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint windowPid);
|
||||
if (windowPid == pid && IsWindowVisible(hWnd))
|
||||
{
|
||||
found = hWnd;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
1037
src/RynthCore.Engine/ImGui/RynthCoreShell.cs
Normal file
1037
src/RynthCore.Engine/ImGui/RynthCoreShell.cs
Normal file
File diff suppressed because it is too large
Load diff
941
src/RynthCore.Engine/ImGui/Win32Backend.cs
Normal file
941
src/RynthCore.Engine/ImGui/Win32Backend.cs
Normal file
|
|
@ -0,0 +1,941 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — ImGui/Win32Backend.cs
|
||||
// Subclasses the game's WndProc to forward mouse/keyboard input to ImGui.
|
||||
// Implements the equivalent of imgui_impl_win32.cpp in pure C#.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class Win32Backend
|
||||
{
|
||||
// ─── Win32 messages ───────────────────────────────────────────────
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_SETFOCUS = 0x0007;
|
||||
private const uint WM_KILLFOCUS = 0x0008;
|
||||
private const uint WM_ACTIVATEAPP = 0x001C;
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
private const uint WM_RBUTTONDOWN = 0x0204;
|
||||
private const uint WM_RBUTTONUP = 0x0205;
|
||||
private const uint WM_MBUTTONDOWN = 0x0207;
|
||||
private const uint WM_MBUTTONUP = 0x0208;
|
||||
private const uint WM_MOUSEWHEEL = 0x020A;
|
||||
private const uint WM_MOUSEHWHEEL = 0x020E;
|
||||
private const uint WM_KEYDOWN = 0x0100;
|
||||
private const uint WM_KEYUP = 0x0101;
|
||||
private const uint WM_SYSKEYDOWN = 0x0104;
|
||||
private const uint WM_SYSKEYUP = 0x0105;
|
||||
private const uint WM_CHAR = 0x0102;
|
||||
private const uint WM_SETCURSOR = 0x0020;
|
||||
private const uint WM_XBUTTONDOWN = 0x020B;
|
||||
private const uint WM_XBUTTONUP = 0x020C;
|
||||
|
||||
private const int GWL_WNDPROC = -4;
|
||||
private const uint GA_ROOT = 2;
|
||||
private const int HTCLIENT = 1;
|
||||
|
||||
private const int VK_CONTROL = 0x11;
|
||||
private const int VK_SHIFT = 0x10;
|
||||
private const int VK_MENU = 0x12; // Alt
|
||||
private const int VK_LWIN = 0x5B;
|
||||
private const int VK_RWIN = 0x5C;
|
||||
private const int VK_INSERT = 0x2D;
|
||||
|
||||
// ─── Win32 P/Invoke ───────────────────────────────────────────────
|
||||
// On x86, SetWindowLongPtr doesn't exist — use SetWindowLong
|
||||
[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
|
||||
private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "CallWindowProcA")]
|
||||
private static extern IntPtr CallWindowProcA(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetCursorPos(out POINT lpPoint);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern short GetKeyState(int nVirtKey);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern short GetAsyncKeyState(int vKey);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetCapture(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ReleaseCapture();
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct POINT { public int X, Y; }
|
||||
|
||||
private readonly struct OverlayPoint
|
||||
{
|
||||
public OverlayPoint(int x, int y)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
}
|
||||
|
||||
public int X { get; }
|
||||
public int Y { get; }
|
||||
}
|
||||
|
||||
private readonly struct AvaloniaMessagePoint
|
||||
{
|
||||
public AvaloniaMessagePoint(int x, int y)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
}
|
||||
|
||||
public int X { get; }
|
||||
public int Y { get; }
|
||||
}
|
||||
|
||||
private readonly struct QueuedInputMessage
|
||||
{
|
||||
public readonly uint Msg;
|
||||
public readonly IntPtr WParam;
|
||||
public readonly IntPtr LParam;
|
||||
|
||||
public QueuedInputMessage(uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
Msg = msg;
|
||||
WParam = wParam;
|
||||
LParam = lParam;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── WndProc delegate ─────────────────────────────────────────────
|
||||
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
private static WndProcDelegate? _wndProcDelegate;
|
||||
private static IntPtr _originalWndProc;
|
||||
private static IntPtr _gameHwnd;
|
||||
private static bool _initialized;
|
||||
|
||||
/// <summary>Custom WM_USER message for deferred chat command dispatch.</summary>
|
||||
internal const uint WM_RYNTHCORE_CHAT = 0x0400 + 0x5243; // WM_USER + "RC"
|
||||
|
||||
/// <summary>The game's main window handle.</summary>
|
||||
public static IntPtr GameHwnd => _gameHwnd;
|
||||
|
||||
/// <summary>
|
||||
/// Sends a message directly to the game's original WndProc, bypassing our subclass.
|
||||
/// </summary>
|
||||
public static IntPtr SendToGameWndProc(uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
||||
return IntPtr.Zero;
|
||||
return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam);
|
||||
}
|
||||
private static readonly bool[] _mouseButtons = new bool[5];
|
||||
private static readonly object _inputLock = new();
|
||||
private static readonly Queue<QueuedInputMessage> _pendingInput = new();
|
||||
private static volatile bool _wantCaptureMouse;
|
||||
private static volatile bool _wantCaptureKeyboard;
|
||||
private static bool _hasMouseCapture;
|
||||
private static bool _uiCaptureEnabled;
|
||||
private static bool _hasFocus;
|
||||
private static bool _focusInitialized;
|
||||
private static bool _insertWasDown;
|
||||
private static bool _avaloniaHasMouse; // cursor is currently over the Avalonia panel
|
||||
private static int _lastPanelClientX; // last game-client pos over the panel (for wheel)
|
||||
private static int _lastPanelClientY;
|
||||
|
||||
// Panel drag / resize tracked entirely in physical coords here —
|
||||
// avoids any dependency on Avalonia's off-screen coordinate system.
|
||||
private static bool _avIsDragging;
|
||||
private static bool _avIsResizing;
|
||||
private static bool _avIsButtonCapture;
|
||||
private static bool _avHasNativeCapture;
|
||||
private static int _avPrevPhysX;
|
||||
private static int _avPrevPhysY;
|
||||
private static double _avDragResidualX;
|
||||
private static double _avDragResidualY;
|
||||
private static string? _pendingBarButtonTitle;
|
||||
private static int _lastKnownClientWidth;
|
||||
private static int _lastKnownClientHeight;
|
||||
private static int _lastAvaloniaMessageX;
|
||||
private static int _lastAvaloniaMessageY;
|
||||
private static int _avaloniaDebugLogCount;
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public static bool Init(IntPtr hWnd)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
_gameHwnd = hWnd;
|
||||
_uiCaptureEnabled = true;
|
||||
_hasFocus = false;
|
||||
_focusInitialized = false;
|
||||
_wantCaptureMouse = false;
|
||||
_wantCaptureKeyboard = false;
|
||||
_insertWasDown = false;
|
||||
|
||||
// Subclass the window
|
||||
_wndProcDelegate = WndProcHook;
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate);
|
||||
_originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr);
|
||||
|
||||
if (_originalWndProc == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render($"Win32Backend: SetWindowLongPtr failed (error {Marshal.GetLastWin32Error()})");
|
||||
return false;
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Render("Win32Backend: Initialized (WndProc subclassed).");
|
||||
RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release).");
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_initialized) return;
|
||||
|
||||
// Restore original WndProc
|
||||
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
|
||||
lock (_inputLock)
|
||||
_pendingInput.Clear();
|
||||
Array.Clear(_mouseButtons, 0, _mouseButtons.Length);
|
||||
_wantCaptureMouse = false;
|
||||
_wantCaptureKeyboard = false;
|
||||
if (_hasMouseCapture)
|
||||
{
|
||||
ReleaseCapture();
|
||||
_hasMouseCapture = false;
|
||||
}
|
||||
_uiCaptureEnabled = false;
|
||||
_hasFocus = false;
|
||||
_focusInitialized = false;
|
||||
_insertWasDown = false;
|
||||
_avaloniaHasMouse = false;
|
||||
_avIsDragging = false;
|
||||
_avIsResizing = false;
|
||||
_avIsButtonCapture = false;
|
||||
ReleaseAvaloniaNativeCapture();
|
||||
_avDragResidualX = 0;
|
||||
_avDragResidualY = 0;
|
||||
_pendingBarButtonTitle = null;
|
||||
_lastKnownClientWidth = 0;
|
||||
_lastKnownClientHeight = 0;
|
||||
AvaloniaOverlay.HasPointerCapture = false;
|
||||
AvaloniaOverlay.IsDragInProgress = false;
|
||||
AvaloniaOverlay.DragCommitPending = false;
|
||||
AvaloniaOverlay.DragOffsetX = 0;
|
||||
AvaloniaOverlay.DragOffsetY = 0;
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
private static int _newFrameLogCount;
|
||||
|
||||
public static void NewFrame()
|
||||
{
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Update display size
|
||||
GetClientRect(_gameHwnd, out RECT rect);
|
||||
int w = rect.Right - rect.Left;
|
||||
int h = rect.Bottom - rect.Top;
|
||||
|
||||
_newFrameLogCount++;
|
||||
|
||||
AvaloniaOverlay.ClientPixelWidth = w;
|
||||
AvaloniaOverlay.ClientPixelHeight = h;
|
||||
if ((_lastKnownClientWidth != w || _lastKnownClientHeight != h) && w > 1 && h > 1)
|
||||
{
|
||||
_lastKnownClientWidth = w;
|
||||
_lastKnownClientHeight = h;
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
}
|
||||
|
||||
// If GetClientRect returns 0x0 or 1x1, the HWND might be wrong.
|
||||
// DisplaySize will be set from D3D viewport in ImGuiController instead.
|
||||
if (w > 1 && h > 1)
|
||||
io.DisplaySize = new System.Numerics.Vector2(w, h);
|
||||
|
||||
FlushQueuedInput(io);
|
||||
|
||||
// Always refresh the cursor position relative to the device window.
|
||||
GetCursorPos(out POINT cursorPos);
|
||||
ScreenToClient(_gameHwnd, ref cursorPos);
|
||||
io.AddMousePosEvent(cursorPos.X, cursorPos.Y);
|
||||
SyncFocusState(io);
|
||||
|
||||
bool insertDown = (GetAsyncKeyState(VK_INSERT) & 0x8000) != 0;
|
||||
if (insertDown && !_insertWasDown)
|
||||
{
|
||||
_uiCaptureEnabled = !_uiCaptureEnabled;
|
||||
RynthLog.Render($"Win32Backend: ImGui capture {(_uiCaptureEnabled ? "ENABLED" : "DISABLED")} (Insert)");
|
||||
}
|
||||
_insertWasDown = insertDown;
|
||||
|
||||
// Mouse button state comes from WndProc messages only (via FlushQueuedInput).
|
||||
// GetAsyncKeyState(VK_LBUTTON) is unreliable in AC's context (reports stuck True).
|
||||
|
||||
bool anyMouseButtonDown =
|
||||
_mouseButtons[0] || _mouseButtons[1] || _mouseButtons[2] || _mouseButtons[3] || _mouseButtons[4];
|
||||
if (_wantCaptureMouse && anyMouseButtonDown && !_hasMouseCapture)
|
||||
{
|
||||
SetCapture(_gameHwnd);
|
||||
_hasMouseCapture = true;
|
||||
}
|
||||
else if ((!_wantCaptureMouse || !anyMouseButtonDown) && _hasMouseCapture)
|
||||
{
|
||||
ReleaseCapture();
|
||||
_hasMouseCapture = false;
|
||||
}
|
||||
|
||||
// Update modifier keys
|
||||
io.AddKeyEvent(ImGuiKey.ModCtrl, (GetKeyState(VK_CONTROL) & 0x8000) != 0);
|
||||
io.AddKeyEvent(ImGuiKey.ModShift, (GetKeyState(VK_SHIFT) & 0x8000) != 0);
|
||||
io.AddKeyEvent(ImGuiKey.ModAlt, (GetKeyState(VK_MENU) & 0x8000) != 0);
|
||||
io.AddKeyEvent(ImGuiKey.ModSuper, ((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & 0x8000) != 0);
|
||||
}
|
||||
|
||||
// ─── WndProc Hook ─────────────────────────────────────────────────
|
||||
|
||||
private static int _wndProcLogCount;
|
||||
|
||||
private static IntPtr WndProcHook(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
try
|
||||
{
|
||||
_wndProcLogCount++;
|
||||
|
||||
// ── Avalonia panel hit-test & input forwarding ────────────────
|
||||
if (IsMouseMessage(msg))
|
||||
{
|
||||
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
|
||||
if (handled)
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
else if (IsKeyMessage(msg) && _avaloniaHasMouse)
|
||||
{
|
||||
// Keyboard goes to Avalonia only while the cursor is over the panel.
|
||||
IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd;
|
||||
if (avHwnd != IntPtr.Zero)
|
||||
{
|
||||
PostMessage(avHwnd, msg, wParam, lParam);
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
if (IsMouseMessage(msg) || IsKeyMessage(msg) || IsFocusMessage(msg))
|
||||
EnqueueInput(msg, wParam, lParam);
|
||||
|
||||
// If ImGui wants mouse input, eat mouse messages so the game doesn't get them
|
||||
if (_wantCaptureMouse && IsMouseMessage(msg))
|
||||
return IntPtr.Zero;
|
||||
|
||||
// If ImGui wants keyboard input, eat keyboard messages
|
||||
if (_wantCaptureKeyboard && IsKeyMessage(msg))
|
||||
return IntPtr.Zero;
|
||||
|
||||
// ── Background FPS unlock: lie to AC so it never idle-throttles ──
|
||||
if (msg == WM_ACTIVATEAPP && EndSceneHook.FpsLimitEnabled)
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)1, lParam);
|
||||
|
||||
// Pass through to original WndProc
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Render($"Win32Backend.WndProcHook: {ex.GetType().Name}: {ex.Message}");
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
|
||||
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery).
|
||||
/// </summary>
|
||||
private static bool TryForwardToAvalonia(uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd;
|
||||
if (avHwnd == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
// ── Pointer-capture mode: panel drag or resize in progress ────────────
|
||||
if (AvaloniaOverlay.HasPointerCapture)
|
||||
{
|
||||
if (msg == WM_MOUSEMOVE)
|
||||
{
|
||||
short cx = (short)((long)lParam & 0xFFFF);
|
||||
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
OverlayPoint overlayPoint = ClientToOverlayPoint(cx, cy);
|
||||
int dx = overlayPoint.X - _avPrevPhysX;
|
||||
int dy = overlayPoint.Y - _avPrevPhysY;
|
||||
_avPrevPhysX = overlayPoint.X;
|
||||
_avPrevPhysY = overlayPoint.Y;
|
||||
_lastPanelClientX = overlayPoint.X;
|
||||
_lastPanelClientY = overlayPoint.Y;
|
||||
|
||||
if (_avIsDragging)
|
||||
{
|
||||
int logicalDx = ConvertClientDeltaToLogical(dx, ref _avDragResidualX);
|
||||
int logicalDy = ConvertClientDeltaToLogical(dy, ref _avDragResidualY);
|
||||
if (logicalDx != 0 || logicalDy != 0)
|
||||
AvaloniaOverlay.MoveBarByPhys(logicalDx, logicalDy);
|
||||
return true;
|
||||
}
|
||||
else if (_avIsResizing)
|
||||
{
|
||||
int logicalDx = ConvertClientDeltaToLogical(dx, ref _avDragResidualX);
|
||||
int logicalDy = ConvertClientDeltaToLogical(dy, ref _avDragResidualY);
|
||||
if (logicalDx != 0 || logicalDy != 0)
|
||||
AvaloniaOverlay.ResizePanelByPhys(logicalDx, logicalDy);
|
||||
}
|
||||
else if (_avIsButtonCapture)
|
||||
{
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
AvaloniaMessagePoint messagePoint = ClientToAvaloniaMessagePoint(overlayPoint.X, overlayPoint.Y);
|
||||
_lastAvaloniaMessageX = messagePoint.X;
|
||||
_lastAvaloniaMessageY = messagePoint.Y;
|
||||
PostOverlayMouseMessage(avHwnd, msg, wParam, messagePoint.X, messagePoint.Y);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg == WM_LBUTTONUP)
|
||||
{
|
||||
short upClientX = (short)((long)lParam & 0xFFFF);
|
||||
short upClientY = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
OverlayPoint releasePoint = ClientToOverlayPoint(upClientX, upClientY);
|
||||
_lastPanelClientX = releasePoint.X;
|
||||
_lastPanelClientY = releasePoint.Y;
|
||||
|
||||
if (_avIsButtonCapture &&
|
||||
!string.IsNullOrEmpty(_pendingBarButtonTitle) &&
|
||||
AvaloniaOverlay.TryGetBarButtonTitleAt(releasePoint.X, releasePoint.Y, out string? releasedButtonTitle) &&
|
||||
string.Equals(_pendingBarButtonTitle, releasedButtonTitle, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
AvaloniaOverlay.ActivateBarButton(releasedButtonTitle!);
|
||||
}
|
||||
|
||||
AvaloniaOverlay.IsDragInProgress = false;
|
||||
_avIsDragging = false;
|
||||
_avIsResizing = false;
|
||||
_avIsButtonCapture = false;
|
||||
ReleaseAvaloniaNativeCapture();
|
||||
_pendingBarButtonTitle = null;
|
||||
AvaloniaOverlay.HasPointerCapture = false;
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL)
|
||||
{
|
||||
int avScreenX = AvaloniaOverlay.AvaloniaWindowLeft + _lastAvaloniaMessageX;
|
||||
int avScreenY = AvaloniaOverlay.AvaloniaWindowTop + _lastAvaloniaMessageY;
|
||||
PostMessage(avHwnd, msg, wParam, new IntPtr((avScreenY << 16) | (avScreenX & 0xFFFF)));
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
short rawX = (short)((long)lParam & 0xFFFF);
|
||||
short rawY = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
OverlayPoint forwardedPoint = ClientToOverlayPoint(rawX, rawY);
|
||||
AvaloniaMessagePoint capturedMessagePoint = ClientToAvaloniaMessagePoint(forwardedPoint.X, forwardedPoint.Y);
|
||||
_lastAvaloniaMessageX = capturedMessagePoint.X;
|
||||
_lastAvaloniaMessageY = capturedMessagePoint.Y;
|
||||
PostOverlayMouseMessage(avHwnd, msg, wParam, capturedMessagePoint.X, capturedMessagePoint.Y);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Normal mode: hit-test position-carrying messages ──────────────────
|
||||
if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP
|
||||
|| msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP
|
||||
|| msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP
|
||||
|| msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
|
||||
{
|
||||
short cx = (short)((long)lParam & 0xFFFF);
|
||||
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
OverlayPoint overlayPoint = ClientToOverlayPoint(cx, cy);
|
||||
bool over = AvaloniaOverlay.IsOverPanel(overlayPoint.X, overlayPoint.Y);
|
||||
|
||||
if (over != _avaloniaHasMouse)
|
||||
{
|
||||
_avaloniaHasMouse = over;
|
||||
}
|
||||
|
||||
if (!over)
|
||||
{
|
||||
if (msg == WM_LBUTTONUP)
|
||||
_pendingBarButtonTitle = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_lastPanelClientX = overlayPoint.X;
|
||||
_lastPanelClientY = overlayPoint.Y;
|
||||
|
||||
if (AvaloniaOverlay.TryGetBarButtonTitleAt(overlayPoint.X, overlayPoint.Y, out string? barButtonTitle))
|
||||
{
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
{
|
||||
LogAvaloniaPointerDebug("button-down", cx, cy, overlayPoint.X, overlayPoint.Y);
|
||||
_pendingBarButtonTitle = barButtonTitle;
|
||||
_avIsButtonCapture = true;
|
||||
_avPrevPhysX = overlayPoint.X;
|
||||
_avPrevPhysY = overlayPoint.Y;
|
||||
_avDragResidualX = 0;
|
||||
_avDragResidualY = 0;
|
||||
_lastPanelClientX = overlayPoint.X;
|
||||
_lastPanelClientY = overlayPoint.Y;
|
||||
AvaloniaOverlay.HasPointerCapture = true;
|
||||
AcquireAvaloniaNativeCapture();
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg == WM_LBUTTONUP)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(_pendingBarButtonTitle) &&
|
||||
string.Equals(_pendingBarButtonTitle, barButtonTitle, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
AvaloniaOverlay.ActivateBarButton(barButtonTitle!);
|
||||
}
|
||||
|
||||
_avIsButtonCapture = false;
|
||||
_pendingBarButtonTitle = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg == WM_MOUSEMOVE || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
|
||||
return true;
|
||||
}
|
||||
else if (msg == WM_LBUTTONUP)
|
||||
{
|
||||
_avIsButtonCapture = false;
|
||||
_pendingBarButtonTitle = null;
|
||||
}
|
||||
|
||||
// Detect header drag and resize-grip on left-button press
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
{
|
||||
// PanelPhys* are in Avalonia-origin coords; add DragOffset for screen coords.
|
||||
int physLeft = AvaloniaOverlay.PanelPhysLeft + AvaloniaOverlay.DragOffsetX;
|
||||
int physTop = AvaloniaOverlay.PanelPhysTop + AvaloniaOverlay.DragOffsetY;
|
||||
int physRight = AvaloniaOverlay.PanelPhysRight + AvaloniaOverlay.DragOffsetX;
|
||||
int physBottom = AvaloniaOverlay.PanelPhysBottom + AvaloniaOverlay.DragOffsetY;
|
||||
|
||||
bool withinBar =
|
||||
overlayPoint.X >= physLeft &&
|
||||
overlayPoint.X <= physRight &&
|
||||
overlayPoint.Y >= physTop &&
|
||||
overlayPoint.Y <= physBottom;
|
||||
|
||||
// Shell resizing is disabled for now because the previous hit-test
|
||||
// region was swallowing normal control clicks across the popup area.
|
||||
bool onGrip = false;
|
||||
|
||||
// Drag zone is only the left ~32px of the bar header ("RC").
|
||||
// Everything else should flow through to Avalonia controls normally.
|
||||
bool onHeader = withinBar && overlayPoint.X <= physLeft + 32;
|
||||
|
||||
if (onGrip || onHeader)
|
||||
{
|
||||
LogAvaloniaPointerDebug(onHeader ? "drag-start" : "resize-start", cx, cy, overlayPoint.X, overlayPoint.Y);
|
||||
_pendingBarButtonTitle = null;
|
||||
_avIsDragging = onHeader;
|
||||
_avIsResizing = onGrip;
|
||||
_avIsButtonCapture = false;
|
||||
_avPrevPhysX = overlayPoint.X;
|
||||
_avPrevPhysY = overlayPoint.Y;
|
||||
_avDragResidualX = 0;
|
||||
_avDragResidualY = 0;
|
||||
AvaloniaOverlay.HasPointerCapture = true;
|
||||
AcquireAvaloniaNativeCapture();
|
||||
|
||||
if (onHeader)
|
||||
{
|
||||
AvaloniaOverlay.IsDragInProgress = true;
|
||||
AvaloniaOverlay.DragOffsetX = 0;
|
||||
AvaloniaOverlay.DragOffsetY = 0;
|
||||
}
|
||||
|
||||
// Do NOT PostMessage WM_LBUTTONDOWN to Avalonia here.
|
||||
// Doing so causes Avalonia to call SetCapture(avHwnd) internally,
|
||||
// which hijacks WM_LBUTTONUP away from our WndProc — HasPointerCapture
|
||||
// then never gets cleared and release requires a second click.
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
AvaloniaMessagePoint messagePoint = ClientToAvaloniaMessagePoint(overlayPoint.X, overlayPoint.Y);
|
||||
_lastAvaloniaMessageX = messagePoint.X;
|
||||
_lastAvaloniaMessageY = messagePoint.Y;
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
LogAvaloniaPointerDebug("forward-down", cx, cy, overlayPoint.X, overlayPoint.Y, messagePoint.X, messagePoint.Y);
|
||||
PostOverlayMouseMessage(avHwnd, msg, wParam, messagePoint.X, messagePoint.Y);
|
||||
if (msg != WM_MOUSEMOVE || AvaloniaOverlay.ShouldUseCustomSkiaProducer)
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Scroll: forward while cursor is over the panel ────────────────────
|
||||
if ((msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL) && _avaloniaHasMouse)
|
||||
{
|
||||
int avScreenX = AvaloniaOverlay.AvaloniaWindowLeft + _lastAvaloniaMessageX;
|
||||
int avScreenY = AvaloniaOverlay.AvaloniaWindowTop + _lastAvaloniaMessageY;
|
||||
PostMessage(avHwnd, msg, wParam, new IntPtr((avScreenY << 16) | (avScreenX & 0xFFFF)));
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ImGuiKey VkToImGuiKey(int vk)
|
||||
{
|
||||
return vk switch
|
||||
{
|
||||
0x09 => ImGuiKey.Tab,
|
||||
0x25 => ImGuiKey.LeftArrow,
|
||||
0x27 => ImGuiKey.RightArrow,
|
||||
0x26 => ImGuiKey.UpArrow,
|
||||
0x28 => ImGuiKey.DownArrow,
|
||||
0x21 => ImGuiKey.PageUp,
|
||||
0x22 => ImGuiKey.PageDown,
|
||||
0x24 => ImGuiKey.Home,
|
||||
0x23 => ImGuiKey.End,
|
||||
0x2D => ImGuiKey.Insert,
|
||||
0x2E => ImGuiKey.Delete,
|
||||
0x08 => ImGuiKey.Backspace,
|
||||
0x20 => ImGuiKey.Space,
|
||||
0x0D => ImGuiKey.Enter,
|
||||
0x1B => ImGuiKey.Escape,
|
||||
0x6A => ImGuiKey.KeypadMultiply,
|
||||
0x6B => ImGuiKey.KeypadAdd,
|
||||
0x6D => ImGuiKey.KeypadSubtract,
|
||||
0x6E => ImGuiKey.KeypadDecimal,
|
||||
0x6F => ImGuiKey.KeypadDivide,
|
||||
0xBE => ImGuiKey.Period,
|
||||
0xBC => ImGuiKey.Comma,
|
||||
0xBD => ImGuiKey.Minus,
|
||||
0xBB => ImGuiKey.Equal,
|
||||
0xBA => ImGuiKey.Semicolon,
|
||||
0xBF => ImGuiKey.Slash,
|
||||
0xC0 => ImGuiKey.GraveAccent,
|
||||
0xDB => ImGuiKey.LeftBracket,
|
||||
0xDC => ImGuiKey.Backslash,
|
||||
0xDD => ImGuiKey.RightBracket,
|
||||
0xDE => ImGuiKey.Apostrophe,
|
||||
0x14 => ImGuiKey.CapsLock,
|
||||
0x91 => ImGuiKey.ScrollLock,
|
||||
0x90 => ImGuiKey.NumLock,
|
||||
0x2C => ImGuiKey.PrintScreen,
|
||||
0x13 => ImGuiKey.Pause,
|
||||
>= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30), // 0-9
|
||||
>= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41), // A-Z
|
||||
>= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60), // Numpad 0-9
|
||||
>= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70), // F1-F12
|
||||
0x10 => ImGuiKey.LeftShift,
|
||||
0x11 => ImGuiKey.LeftCtrl,
|
||||
0x12 => ImGuiKey.LeftAlt,
|
||||
0x5B => ImGuiKey.LeftSuper,
|
||||
_ => ImGuiKey.None,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool IsMouseMessage(uint msg)
|
||||
{
|
||||
return msg >= WM_MOUSEMOVE && msg <= WM_MBUTTONUP
|
||||
|| msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL
|
||||
|| msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP;
|
||||
}
|
||||
|
||||
private static bool IsKeyMessage(uint msg)
|
||||
{
|
||||
return msg == WM_KEYDOWN || msg == WM_KEYUP
|
||||
|| msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP
|
||||
|| msg == WM_CHAR;
|
||||
}
|
||||
|
||||
private static bool IsFocusMessage(uint msg)
|
||||
{
|
||||
return msg == WM_SETFOCUS || msg == WM_KILLFOCUS || msg == WM_ACTIVATEAPP;
|
||||
}
|
||||
|
||||
private static void AddMousePosFromLParam(ImGuiIOPtr io, IntPtr lParam)
|
||||
{
|
||||
short x = (short)((long)lParam & 0xFFFF);
|
||||
short y = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
io.AddMousePosEvent(x, y);
|
||||
}
|
||||
|
||||
private static void UpdateMouseButton(ImGuiIOPtr io, int buttonIndex, int virtualKey)
|
||||
{
|
||||
bool isDown = (GetAsyncKeyState(virtualKey) & 0x8000) != 0;
|
||||
SetMouseButtonState(io, buttonIndex, isDown);
|
||||
}
|
||||
|
||||
public static void UpdateCaptureFlags(bool wantMouse, bool wantKeyboard)
|
||||
{
|
||||
// ImGui.NET's WantCaptureMouse/WantCaptureKeyboard read from wrong native
|
||||
// offsets (struct layout mismatch, same class of bug as ImDrawCmd stride).
|
||||
// Use _uiCaptureEnabled directly — Insert key gives user explicit control.
|
||||
_wantCaptureMouse = _uiCaptureEnabled && _hasFocus && wantMouse;
|
||||
_wantCaptureKeyboard = _uiCaptureEnabled && _hasFocus && wantKeyboard;
|
||||
}
|
||||
|
||||
public static bool IsUiCaptureEnabled()
|
||||
{
|
||||
return _uiCaptureEnabled;
|
||||
}
|
||||
|
||||
private static OverlayPoint ClientToOverlayPoint(int clientX, int clientY)
|
||||
{
|
||||
if (!GetClientRect(_gameHwnd, out RECT rect))
|
||||
return new OverlayPoint(clientX, clientY);
|
||||
|
||||
int clientW = Math.Max(1, rect.Right - rect.Left);
|
||||
int clientH = Math.Max(1, rect.Bottom - rect.Top);
|
||||
|
||||
// Avalonia hit-testing and bar layout live in the logical game-client space.
|
||||
// Do not map through the submitted surface pixel size here: the custom Skia
|
||||
// producer may render a higher-resolution frame (for DPI / scaling), which
|
||||
// would make drag deltas and hit locations move faster than the actual mouse.
|
||||
return new OverlayPoint(
|
||||
Math.Clamp(clientX, 0, clientW),
|
||||
Math.Clamp(clientY, 0, clientH));
|
||||
}
|
||||
|
||||
private static void PostOverlayMouseMessage(IntPtr hwnd, uint msg, IntPtr wParam, int overlayX, int overlayY)
|
||||
{
|
||||
PostMessage(hwnd, msg, wParam, new IntPtr(((overlayY & 0xFFFF) << 16) | (overlayX & 0xFFFF)));
|
||||
}
|
||||
|
||||
private static int ConvertClientDeltaToLogical(int clientDelta, ref double residual)
|
||||
{
|
||||
float scale = AvaloniaOverlay.InputScale;
|
||||
if (scale <= 1.001f)
|
||||
return clientDelta;
|
||||
|
||||
double logicalDelta = (clientDelta / (double)scale) + residual;
|
||||
int rounded = (int)Math.Truncate(logicalDelta);
|
||||
residual = logicalDelta - rounded;
|
||||
return rounded;
|
||||
}
|
||||
|
||||
private static AvaloniaMessagePoint ClientToAvaloniaMessagePoint(int clientX, int clientY)
|
||||
{
|
||||
// Win32 mouse-message lParams are always in client physical pixels.
|
||||
// The off-screen Avalonia top-level is now sized in logical units that
|
||||
// match the live game surface after RenderScaling is applied, so Avalonia
|
||||
// can perform its normal physical->logical conversion internally.
|
||||
return new AvaloniaMessagePoint(clientX, clientY);
|
||||
}
|
||||
|
||||
private static void LogAvaloniaPointerDebug(string phase, int clientX, int clientY, int overlayX, int overlayY, int? messageX = null, int? messageY = null)
|
||||
{
|
||||
// Suppressed — these diagnostics are no longer needed for stable operation.
|
||||
}
|
||||
|
||||
private static void AcquireAvaloniaNativeCapture()
|
||||
{
|
||||
if (_avHasNativeCapture)
|
||||
return;
|
||||
|
||||
SetCapture(_gameHwnd);
|
||||
_avHasNativeCapture = true;
|
||||
}
|
||||
|
||||
private static void ReleaseAvaloniaNativeCapture()
|
||||
{
|
||||
if (!_avHasNativeCapture)
|
||||
return;
|
||||
|
||||
ReleaseCapture();
|
||||
_avHasNativeCapture = false;
|
||||
}
|
||||
|
||||
private static void EnqueueInput(uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
lock (_inputLock)
|
||||
_pendingInput.Enqueue(new QueuedInputMessage(msg, wParam, lParam));
|
||||
}
|
||||
|
||||
private static void FlushQueuedInput(ImGuiIOPtr io)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
QueuedInputMessage message;
|
||||
lock (_inputLock)
|
||||
{
|
||||
if (_pendingInput.Count == 0) break;
|
||||
message = _pendingInput.Dequeue();
|
||||
}
|
||||
|
||||
switch (message.Msg)
|
||||
{
|
||||
case WM_MOUSEMOVE:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
break;
|
||||
|
||||
case WM_LBUTTONDOWN:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 0, true);
|
||||
break;
|
||||
|
||||
case WM_LBUTTONUP:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 0, false);
|
||||
break;
|
||||
|
||||
case WM_RBUTTONDOWN:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 1, true);
|
||||
break;
|
||||
|
||||
case WM_RBUTTONUP:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 1, false);
|
||||
break;
|
||||
|
||||
case WM_MBUTTONDOWN:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 2, true);
|
||||
break;
|
||||
|
||||
case WM_MBUTTONUP:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, 2, false);
|
||||
break;
|
||||
|
||||
case WM_XBUTTONDOWN:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, GetXButtonIndex(message.WParam), true);
|
||||
break;
|
||||
|
||||
case WM_XBUTTONUP:
|
||||
AddMousePosFromLParam(io, message.LParam);
|
||||
SetMouseButtonState(io, GetXButtonIndex(message.WParam), false);
|
||||
break;
|
||||
|
||||
case WM_MOUSEWHEEL:
|
||||
io.AddMouseWheelEvent(0f, (short)((long)message.WParam >> 16) / 120f);
|
||||
break;
|
||||
|
||||
case WM_MOUSEHWHEEL:
|
||||
io.AddMouseWheelEvent((short)((long)message.WParam >> 16) / 120f, 0f);
|
||||
break;
|
||||
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
{
|
||||
ImGuiKey key = VkToImGuiKey((int)(long)message.WParam);
|
||||
if (key != ImGuiKey.None)
|
||||
io.AddKeyEvent(key, true);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
{
|
||||
ImGuiKey key = VkToImGuiKey((int)(long)message.WParam);
|
||||
if (key != ImGuiKey.None)
|
||||
io.AddKeyEvent(key, false);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_CHAR:
|
||||
{
|
||||
uint ch = (uint)(long)message.WParam;
|
||||
if (ch > 0 && ch < 0x10000)
|
||||
io.AddInputCharacter(ch);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SETFOCUS:
|
||||
ApplyFocusState(io, true);
|
||||
break;
|
||||
|
||||
case WM_KILLFOCUS:
|
||||
ApplyFocusState(io, false);
|
||||
break;
|
||||
|
||||
case WM_ACTIVATEAPP:
|
||||
ApplyFocusState(io, message.WParam != IntPtr.Zero);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SyncFocusState(ImGuiIOPtr io)
|
||||
{
|
||||
IntPtr rootWindow = GetAncestor(_gameHwnd, GA_ROOT);
|
||||
IntPtr targetWindow = rootWindow != IntPtr.Zero ? rootWindow : _gameHwnd;
|
||||
bool isFocused = GetForegroundWindow() == targetWindow;
|
||||
|
||||
if (!_focusInitialized || isFocused != _hasFocus)
|
||||
ApplyFocusState(io, isFocused);
|
||||
}
|
||||
|
||||
private static void ApplyFocusState(ImGuiIOPtr io, bool isFocused)
|
||||
{
|
||||
if (_focusInitialized && _hasFocus == isFocused)
|
||||
return;
|
||||
|
||||
_focusInitialized = true;
|
||||
_hasFocus = isFocused;
|
||||
io.AddFocusEvent(isFocused);
|
||||
|
||||
if (isFocused)
|
||||
return;
|
||||
|
||||
for (int buttonIndex = 0; buttonIndex < _mouseButtons.Length; buttonIndex++)
|
||||
SetMouseButtonState(io, buttonIndex, false);
|
||||
|
||||
if (_hasMouseCapture)
|
||||
{
|
||||
ReleaseCapture();
|
||||
_hasMouseCapture = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetMouseButtonState(ImGuiIOPtr io, int buttonIndex, bool isDown)
|
||||
{
|
||||
if (_mouseButtons[buttonIndex] == isDown) return;
|
||||
|
||||
_mouseButtons[buttonIndex] = isDown;
|
||||
io.AddMouseButtonEvent(buttonIndex, isDown);
|
||||
}
|
||||
|
||||
private static int GetXButtonIndex(IntPtr wParam)
|
||||
{
|
||||
int button = ((int)(long)wParam >> 16) & 0xFFFF;
|
||||
return button == 1 ? 3 : 4;
|
||||
}
|
||||
}
|
||||
BIN
src/RynthCore.Engine/Native/cimgui.dll
Normal file
BIN
src/RynthCore.Engine/Native/cimgui.dll
Normal file
Binary file not shown.
BIN
src/RynthCore.Engine/Native/minhook.x86.dll
Normal file
BIN
src/RynthCore.Engine/Native/minhook.x86.dll
Normal file
Binary file not shown.
58
src/RynthCore.Engine/Plugins/LoadedPlugin.cs
Normal file
58
src/RynthCore.Engine/Plugins/LoadedPlugin.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/LoadedPlugin.cs
|
||||
// Represents a single plugin DLL that has been loaded and had its exports
|
||||
// resolved. Holds the module handle and cached delegates.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal sealed class LoadedPlugin
|
||||
{
|
||||
public string SourceFilePath { get; init; } = "";
|
||||
public string FilePath { get; init; } = "";
|
||||
public string FileName { get; init; } = "";
|
||||
public IntPtr ModuleHandle { get; init; }
|
||||
|
||||
// ─── Required exports ────────────────────────────────────────────
|
||||
public PluginInitDelegate? Init { get; set; }
|
||||
public PluginShutdownDelegate? Shutdown { get; set; }
|
||||
|
||||
// ─── Optional exports ────────────────────────────────────────────
|
||||
public PluginNameDelegate? GetName { get; set; }
|
||||
public PluginVersionDelegate? GetVersion { get; set; }
|
||||
public PluginOnLoginCompleteDelegate? OnLoginComplete { get; set; }
|
||||
public PluginOnUIInitializedDelegate? OnUIInitialized { get; set; }
|
||||
public PluginOnBusyCountIncrementedDelegate? OnBusyCountIncremented { get; set; }
|
||||
public PluginOnBusyCountDecrementedDelegate? OnBusyCountDecremented { get; set; }
|
||||
public PluginOnSelectedTargetChangeDelegate? OnSelectedTargetChange { get; set; }
|
||||
public PluginOnCombatModeChangeDelegate? OnCombatModeChange { get; set; }
|
||||
public IntPtr OnSmartBoxEventPtr { get; set; }
|
||||
public PluginOnSmartBoxEventDelegate? OnSmartBoxEvent { get; set; }
|
||||
public PluginOnDeleteObjectDelegate? OnDeleteObject { get; set; }
|
||||
public PluginOnCreateObjectDelegate? OnCreateObject { get; set; }
|
||||
public IntPtr OnUpdateObjectPtr { get; set; }
|
||||
public PluginOnUpdateObjectDelegate? OnUpdateObject { get; set; }
|
||||
public PluginOnUpdateObjectInventoryDelegate? OnUpdateObjectInventory { get; set; }
|
||||
public PluginOnViewObjectContentsDelegate? OnViewObjectContents { get; set; }
|
||||
public PluginOnStopViewingObjectContentsDelegate? OnStopViewingObjectContents { get; set; }
|
||||
public IntPtr OnUpdateHealthPtr { get; set; }
|
||||
public PluginOnUpdateHealthDelegate? OnUpdateHealth { get; set; }
|
||||
public IntPtr OnChatWindowTextPtr { get; set; }
|
||||
public PluginOnChatWindowTextDelegate? OnChatWindowText { get; set; }
|
||||
public PluginOnChatBarEnterDelegate? OnChatBarEnter { get; set; }
|
||||
public PluginBarActionDelegate? OnBarAction { get; set; }
|
||||
public PluginOnEnchantmentAddedDelegate? OnEnchantmentAdded { get; set; }
|
||||
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
|
||||
public PluginTickDelegate? Tick { get; set; }
|
||||
public PluginRenderDelegate? Render { get; set; }
|
||||
|
||||
// ─── Runtime state ───────────────────────────────────────────────
|
||||
public bool Initialized { get; set; }
|
||||
public bool LoginCompleteDispatched { get; set; }
|
||||
public bool UIInitializedDispatched { get; set; }
|
||||
public bool Failed { get; set; }
|
||||
public string DisplayName { get; set; } = "";
|
||||
public string VersionString { get; set; } = "";
|
||||
}
|
||||
617
src/RynthCore.Engine/Plugins/PluginContract.cs
Normal file
617
src/RynthCore.Engine/Plugins/PluginContract.cs
Normal file
|
|
@ -0,0 +1,617 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/PluginContract.cs
|
||||
// Defines the C ABI contract between RynthCore and plugin DLLs.
|
||||
//
|
||||
// A plugin DLL must export at least:
|
||||
// int RynthPluginInit(RynthCoreAPI* api) — return 0 on success
|
||||
// void RynthPluginShutdown()
|
||||
//
|
||||
// Optional exports:
|
||||
// const char* RynthPluginName() — human-readable name
|
||||
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
|
||||
// void RynthPluginTick() — per-frame logic (before render)
|
||||
// void RynthPluginRender() — per-frame ImGui drawing
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// The host API struct passed to every plugin at init time.
|
||||
/// Plugins receive a pointer to this and can call back into RynthCore.
|
||||
/// Layout must stay ABI-stable — append new fields at the end only.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct RynthCoreAPI
|
||||
{
|
||||
/// <summary>API version. Plugins should check this before using later fields.</summary>
|
||||
public uint Version;
|
||||
|
||||
/// <summary>ImGui context pointer — plugin must call igSetCurrentContext before drawing.</summary>
|
||||
public IntPtr ImGuiContext;
|
||||
|
||||
/// <summary>IDirect3DDevice9* — the game's active D3D device.</summary>
|
||||
public IntPtr D3DDevice;
|
||||
|
||||
/// <summary>HWND of the game window.</summary>
|
||||
public IntPtr GameHwnd;
|
||||
|
||||
/// <summary>Function pointer: void Log(const char* message)</summary>
|
||||
public IntPtr LogFn;
|
||||
|
||||
/// <summary>Function pointer: void ProbeClientHooks()</summary>
|
||||
public IntPtr ProbeClientHooksFn;
|
||||
|
||||
/// <summary>Function pointer: uint GetClientHookFlags()</summary>
|
||||
public IntPtr GetClientHookFlagsFn;
|
||||
|
||||
/// <summary>Function pointer: int ChangeCombatMode(int combatMode)</summary>
|
||||
public IntPtr ChangeCombatModeFn;
|
||||
|
||||
/// <summary>Function pointer: int CancelAttack()</summary>
|
||||
public IntPtr CancelAttackFn;
|
||||
|
||||
/// <summary>Function pointer: int QueryHealth(uint targetId)</summary>
|
||||
public IntPtr QueryHealthFn;
|
||||
|
||||
/// <summary>Function pointer: int MeleeAttack(uint targetId, int attackHeight, float powerLevel)</summary>
|
||||
public IntPtr MeleeAttackFn;
|
||||
|
||||
/// <summary>Function pointer: int MissileAttack(uint targetId, int attackHeight, float accuracyLevel)</summary>
|
||||
public IntPtr MissileAttackFn;
|
||||
|
||||
/// <summary>Function pointer: int DoMovement(uint motion, float speed, int holdKey)</summary>
|
||||
public IntPtr DoMovementFn;
|
||||
|
||||
/// <summary>Function pointer: int StopMovement(uint motion, int holdKey)</summary>
|
||||
public IntPtr StopMovementFn;
|
||||
|
||||
/// <summary>Function pointer: int JumpNonAutonomous(float extent)</summary>
|
||||
public IntPtr JumpNonAutonomousFn;
|
||||
|
||||
/// <summary>Function pointer: int SetAutonomyLevel(uint level)</summary>
|
||||
public IntPtr SetAutonomyLevelFn;
|
||||
|
||||
/// <summary>Function pointer: int SetAutoRun(int enabled)</summary>
|
||||
public IntPtr SetAutoRunFn;
|
||||
|
||||
/// <summary>Function pointer: int TapJump()</summary>
|
||||
public IntPtr TapJumpFn;
|
||||
|
||||
/// <summary>Function pointer: void SetIncomingChatSuppression(int enabled)</summary>
|
||||
public IntPtr SetIncomingChatSuppressionFn;
|
||||
|
||||
/// <summary>Function pointer: int SelectItem(uint objectId)</summary>
|
||||
public IntPtr SelectItemFn;
|
||||
|
||||
/// <summary>Function pointer: int SetSelectedObjectId(uint objectId)</summary>
|
||||
public IntPtr SetSelectedObjectIdFn;
|
||||
|
||||
/// <summary>Function pointer: uint GetSelectedItemId()</summary>
|
||||
public IntPtr GetSelectedItemIdFn;
|
||||
|
||||
/// <summary>Function pointer: uint GetPreviousSelectedItemId()</summary>
|
||||
public IntPtr GetPreviousSelectedItemIdFn;
|
||||
|
||||
/// <summary>Function pointer: uint GetPlayerId()</summary>
|
||||
public IntPtr GetPlayerIdFn;
|
||||
|
||||
/// <summary>Function pointer: uint GetGroundContainerId()</summary>
|
||||
public IntPtr GetGroundContainerIdFn;
|
||||
|
||||
/// <summary>Function pointer: int GetCurCoords(double* northSouth, double* eastWest)</summary>
|
||||
public IntPtr GetCurCoordsFn;
|
||||
|
||||
/// <summary>Function pointer: int UseObject(uint objectId)</summary>
|
||||
public IntPtr UseObjectFn;
|
||||
|
||||
/// <summary>Function pointer: int UseObjectOn(uint sourceObjectId, uint targetObjectId)</summary>
|
||||
public IntPtr UseObjectOnFn;
|
||||
|
||||
/// <summary>Function pointer: int UseEquippedItem(uint sourceObjectId, uint targetObjectId)</summary>
|
||||
public IntPtr UseEquippedItemFn;
|
||||
|
||||
/// <summary>Function pointer: int MoveItemExternal(uint objectId, uint targetContainerId, int amount)</summary>
|
||||
public IntPtr MoveItemExternalFn;
|
||||
|
||||
/// <summary>Function pointer: int MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)</summary>
|
||||
public IntPtr MoveItemInternalFn;
|
||||
|
||||
/// <summary>Function pointer: int WriteToChat(const wchar_t* textUtf16, int chatType)</summary>
|
||||
public IntPtr WriteToChatFn;
|
||||
|
||||
/// <summary>Function pointer: int GetPlayerPose(uint* objCellId, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz)</summary>
|
||||
public IntPtr GetPlayerPoseFn;
|
||||
|
||||
/// <summary>Function pointer: int SetMotion(uint motion, int enabled)</summary>
|
||||
public IntPtr SetMotionFn;
|
||||
|
||||
/// <summary>Function pointer: int StopCompletely()</summary>
|
||||
public IntPtr StopCompletelyFn;
|
||||
|
||||
/// <summary>Function pointer: int TurnToHeading(float headingDegrees)</summary>
|
||||
public IntPtr TurnToHeadingFn;
|
||||
|
||||
/// <summary>Function pointer: int GetPlayerHeading(float* headingDegrees)</summary>
|
||||
public IntPtr GetPlayerHeadingFn;
|
||||
|
||||
/// <summary>Function pointer: const char* GetObjectName(uint objectId)</summary>
|
||||
public IntPtr GetObjectNameFn;
|
||||
|
||||
/// <summary>Function pointer: int GetPlayerVitals(uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)</summary>
|
||||
public IntPtr GetPlayerVitalsFn;
|
||||
|
||||
/// <summary>Function pointer: int GetObjectPosition(uint objectId, uint* objCellId, float* x, float* y, float* z)</summary>
|
||||
public IntPtr GetObjectPositionFn;
|
||||
|
||||
/// <summary>Function pointer: int RequestId(uint objectId) — sends appraisal/identify request to server</summary>
|
||||
public IntPtr RequestIdFn;
|
||||
|
||||
/// <summary>Function pointer: int GetTargetVitals(uint objectId, uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)</summary>
|
||||
public IntPtr GetTargetVitalsFn;
|
||||
|
||||
/// <summary>Function pointer: int CastSpell(uint targetId, int spellId)</summary>
|
||||
public IntPtr CastSpellFn;
|
||||
|
||||
/// <summary>Function pointer: int GetItemType(uint objectId, uint* typeFlags)</summary>
|
||||
public IntPtr GetItemTypeFn;
|
||||
|
||||
/// <summary>Function pointer: int GetObjectIntProperty(uint objectId, uint stype, int* value)</summary>
|
||||
public IntPtr GetObjectIntPropertyFn;
|
||||
|
||||
/// <summary>Function pointer: int GetObjectBoolProperty(uint objectId, uint stype, int* value) — returns 1 if property exists, value is 0/1</summary>
|
||||
public IntPtr GetObjectBoolPropertyFn;
|
||||
|
||||
/// <summary>Function pointer: int ObjectIsAttackable(uint objectId) — calls ClientCombatSystem::ObjectIsAttackable, returns 1 if attackable</summary>
|
||||
public IntPtr ObjectIsAttackableFn;
|
||||
|
||||
/// <summary>Function pointer: int GetObjectSkill(uint objectId, uint skillStype, int* buffed, int* training)</summary>
|
||||
public IntPtr GetObjectSkillFn;
|
||||
|
||||
/// <summary>Function pointer: int IsSpellKnown(uint objectId, uint spellId) — returns 1 if in spell book</summary>
|
||||
public IntPtr IsSpellKnownFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int ReadPlayerEnchantments(uint* spellIds, double* expiryTimes, int maxCount)
|
||||
/// Fills arrays with active player enchantments. expiryTimes are in server-time seconds.
|
||||
/// Returns number written, or -1 if not available (not logged in / no registry).
|
||||
/// </summary>
|
||||
public IntPtr ReadPlayerEnchantmentsFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: double GetServerTime()
|
||||
/// Returns estimated current server time in seconds. Returns 0 if no time sync received yet.
|
||||
/// </summary>
|
||||
public IntPtr GetServerTimeFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int ReadObjectEnchantments(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
|
||||
/// Reads enchantments from any game object (armor, weapon, etc.) by ID.
|
||||
/// Returns number written, 0 if no enchantments, -1 if object not found or has no registry.
|
||||
/// </summary>
|
||||
public IntPtr ReadObjectEnchantmentsFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int WorldToScreen(float worldX, float worldY, float worldZ, float* screenX, float* screenY)
|
||||
/// Projects a 3D game-world position to 2D screen coordinates.
|
||||
/// World coordinates are in the same space as GetObjectPosition returns.
|
||||
/// Returns 1 if on screen, 0 if behind camera or unavailable.
|
||||
/// </summary>
|
||||
public IntPtr WorldToScreenFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int GetViewportSize(uint* width, uint* height)
|
||||
/// Returns the current D3D9 viewport dimensions.
|
||||
/// Returns 1 on success, 0 if not available yet.
|
||||
/// </summary>
|
||||
public IntPtr GetViewportSizeFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: void Nav3DClear()
|
||||
/// Clears the 3D nav marker submission buffer. Call once per frame before adding markers.
|
||||
/// </summary>
|
||||
public IntPtr Nav3DClearFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: void Nav3DAddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
|
||||
/// Submits a flat 3D ring at the given world position. Coordinates are D3D: X=EW, Y=height, Z=NS.
|
||||
/// Color is ARGB (D3DCOLOR format).
|
||||
/// </summary>
|
||||
public IntPtr Nav3DAddRingFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
/// Submits a flat 3D line between two world positions. Coordinates are D3D: X=EW, Y=height, Z=NS.
|
||||
/// </summary>
|
||||
public IntPtr Nav3DAddLineFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int InvokeChatParser(const wchar_t* textUtf16)
|
||||
/// Passes text to the AC outgoing chat parser as if the player typed it.
|
||||
/// Returns 1 on success, 0 if the hook is not installed yet.
|
||||
/// </summary>
|
||||
public IntPtr InvokeChatParserFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int GetObjectDoubleProperty(uint objectId, uint stype, double* value)
|
||||
/// Reads an STypeFloat (double) property from any game object.
|
||||
/// Returns 1 on success, 0 if undefined.
|
||||
/// </summary>
|
||||
public IntPtr GetObjectDoublePropertyFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: IntPtr GetObjectStringProperty(uint objectId, uint stype)
|
||||
/// Returns pointer to ANSI string data, or IntPtr.Zero if undefined.
|
||||
/// </summary>
|
||||
public IntPtr GetObjectStringPropertyFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int GetObjectWielderInfo(uint objectId, uint* wielderID, uint* location)
|
||||
/// Reads PublicWeenieDesc._wielderID and _location from the weenie struct.
|
||||
/// </summary>
|
||||
public IntPtr GetObjectWielderInfoFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int NativeAttack(int attackHeight, float power)
|
||||
/// Uses the client's native combat pipeline (ClientCombatSystem) which handles
|
||||
/// turn-to-face and attack execution naturally. Requires target to be selected first.
|
||||
/// Returns 1 on success, 0 if not available.
|
||||
/// </summary>
|
||||
public IntPtr NativeAttackFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int IsPlayerReady()
|
||||
/// Returns 1 if the player is in a ready position to begin an attack.
|
||||
/// </summary>
|
||||
public IntPtr IsPlayerReadyFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: void SetFpsLimit(int enabled, int focusedFps, int backgroundFps)
|
||||
/// Controls the engine-level EndScene frame governor.
|
||||
/// </summary>
|
||||
public IntPtr SetFpsLimitFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int GetContainerContents(uint containerId, uint* itemIds, int maxCount)
|
||||
/// Writes contained item IDs into the provided buffer and returns the number written.
|
||||
/// </summary>
|
||||
public IntPtr GetContainerContentsFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int GetObjectOwnershipInfo(uint objectId, uint* containerID, uint* wielderID, uint* location)
|
||||
/// Reads PublicWeenieDesc ownership fields from the weenie struct.
|
||||
/// </summary>
|
||||
public IntPtr GetObjectOwnershipInfoFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
/// Moves a stack of items onto a specific slot in the target container, merging
|
||||
/// with any existing same-type stack at that slot. Unlike MoveItemInternal which
|
||||
/// sends opcode 0x19 (whole move, first empty slot), this sends opcode 0x55
|
||||
/// (StackableSplitToContainer) which honors the slot parameter.
|
||||
/// </summary>
|
||||
public IntPtr SplitStackInternalFn;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer: int MergeStackInternal(uint sourceObjectId, uint targetObjectId)
|
||||
/// Merges two stacks of the same item type by sending opcode 0x1A (STACKABLE_MERGE).
|
||||
/// This is the real merge path used by drag-drop UI — opcode 0x55 (split-to-slot)
|
||||
/// creates new stacks instead of merging, so AutoStack must use this entry point.
|
||||
/// </summary>
|
||||
public IntPtr MergeStackInternalFn;
|
||||
}
|
||||
|
||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
public const uint Current = 34;
|
||||
}
|
||||
|
||||
internal static class ClientActionHookFlags
|
||||
{
|
||||
public const uint CombatInitialized = 1u << 0;
|
||||
public const uint MovementInitialized = 1u << 1;
|
||||
public const uint MeleeAttack = 1u << 2;
|
||||
public const uint MissileAttack = 1u << 3;
|
||||
public const uint ChangeCombatMode = 1u << 4;
|
||||
public const uint CancelAttack = 1u << 5;
|
||||
public const uint QueryHealth = 1u << 6;
|
||||
public const uint DoMovement = 1u << 7;
|
||||
public const uint StopMovement = 1u << 8;
|
||||
public const uint JumpNonAutonomous = 1u << 9;
|
||||
public const uint SetAutonomyLevel = 1u << 10;
|
||||
public const uint SetAutoRun = 1u << 11;
|
||||
public const uint TapJump = 1u << 12;
|
||||
public const uint SetMotion = 1u << 13;
|
||||
public const uint StopCompletely = 1u << 14;
|
||||
public const uint TurnToHeading = 1u << 15;
|
||||
public const uint GetPlayerHeading = 1u << 16;
|
||||
}
|
||||
|
||||
// ─── Delegate types matching the plugin's exported functions ────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int PluginInitDelegate(ref RynthCoreAPI api);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginShutdownDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr PluginNameDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr PluginVersionDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnLoginCompleteDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnUIInitializedDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnBusyCountIncrementedDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnBusyCountDecrementedDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnSelectedTargetChangeDelegate(uint currentTargetId, uint previousTargetId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnCombatModeChangeDelegate(int currentCombatMode, int previousCombatMode);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnSmartBoxEventDelegate(uint opcode, uint blobSize, uint status);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnDeleteObjectDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnCreateObjectDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnUpdateObjectDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnUpdateObjectInventoryDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnViewObjectContentsDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnStopViewingObjectContentsDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnUpdateHealthDelegate(uint targetId, float healthRatio, uint currentHealth, uint maxHealth);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnChatWindowTextDelegate(IntPtr textUtf16, int chatType, IntPtr eatFlag);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnChatBarEnterDelegate(IntPtr textUtf16, IntPtr eatFlag);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginBarActionDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginTickDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginRenderDelegate();
|
||||
|
||||
// ─── Log callback that plugins can call ─────────────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void LogCallbackDelegate(IntPtr messageUtf8);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void ProbeClientHooksCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate uint GetClientHookFlagsCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int ChangeCombatModeCallbackDelegate(int combatMode);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int CancelAttackCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int QueryHealthCallbackDelegate(uint targetId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int MeleeAttackCallbackDelegate(uint targetId, int attackHeight, float powerLevel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int MissileAttackCallbackDelegate(uint targetId, int attackHeight, float accuracyLevel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int NativeAttackCallbackDelegate(int attackHeight, float power);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int IsPlayerReadyCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void SetFpsLimitCallbackDelegate(int enabled, int focusedFps, int backgroundFps);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int DoMovementCallbackDelegate(uint motion, float speed, int holdKey);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int StopMovementCallbackDelegate(uint motion, int holdKey);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int JumpNonAutonomousCallbackDelegate(float extent);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SetAutonomyLevelCallbackDelegate(uint level);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SetAutoRunCallbackDelegate(int enabled);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TapJumpCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SetMotionCallbackDelegate(uint motion, int enabled);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int StopCompletelyCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TurnToHeadingCallbackDelegate(float headingDegrees);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetPlayerHeadingCallbackDelegate(float* headingDegrees);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void SetIncomingChatSuppressionCallbackDelegate(int enabled);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SelectItemCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SetSelectedObjectIdCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate uint GetItemIdCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetCurCoordsCallbackDelegate(double* northSouth, double* eastWest);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int UseObjectCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int UseObjectOnCallbackDelegate(uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int UseEquippedItemCallbackDelegate(uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int MoveItemExternalCallbackDelegate(uint objectId, uint targetContainerId, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int MoveItemInternalCallbackDelegate(uint objectId, uint targetContainerId, int slot, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int SplitStackInternalCallbackDelegate(uint objectId, uint targetContainerId, int slot, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int MergeStackInternalCallbackDelegate(uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int WriteToChatCallbackDelegate(IntPtr textUtf16, int chatType);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetPlayerPoseCallbackDelegate(
|
||||
uint* objCellId,
|
||||
float* x,
|
||||
float* y,
|
||||
float* z,
|
||||
float* qw,
|
||||
float* qx,
|
||||
float* qy,
|
||||
float* qz);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr GetObjectNameCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetPlayerVitalsCallbackDelegate(
|
||||
uint* health,
|
||||
uint* maxHealth,
|
||||
uint* stamina,
|
||||
uint* maxStamina,
|
||||
uint* mana,
|
||||
uint* maxMana);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectPositionCallbackDelegate(
|
||||
uint objectId,
|
||||
uint* objCellId,
|
||||
float* x,
|
||||
float* y,
|
||||
float* z);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int RequestIdCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetTargetVitalsCallbackDelegate(
|
||||
uint objectId,
|
||||
uint* health,
|
||||
uint* maxHealth,
|
||||
uint* stamina,
|
||||
uint* maxStamina,
|
||||
uint* mana,
|
||||
uint* maxMana);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int CastSpellCallbackDelegate(uint targetId, int spellId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetItemTypeCallbackDelegate(uint objectId, uint* typeFlags);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectIntPropertyCallbackDelegate(uint objectId, uint stype, int* value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectBoolPropertyCallbackDelegate(uint objectId, uint stype, int* value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int ObjectIsAttackableCallbackDelegate(uint objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectSkillCallbackDelegate(uint objectId, uint skillStype, int* buffed, int* training);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int IsSpellKnownCallbackDelegate(uint objectId, uint spellId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnEnchantmentAddedDelegate(uint spellId, double durationSeconds);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginOnEnchantmentRemovedDelegate(uint enchantmentId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int ReadPlayerEnchantmentsCallbackDelegate(uint* spellIds, double* expiryTimes, int maxCount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate double GetServerTimeCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int ReadObjectEnchantmentsCallbackDelegate(uint objectId, uint* spellIds, double* expiryTimes, int maxCount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WorldToScreenCallbackDelegate(float worldX, float worldY, float worldZ, float* screenX, float* screenY);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetViewportSizeCallbackDelegate(uint* width, uint* height);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void Nav3DClearCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void Nav3DAddRingCallbackDelegate(float wx, float wy, float wz, float radius, float thickness, uint colorArgb);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void Nav3DAddLineCallbackDelegate(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int InvokeChatParserCallbackDelegate(IntPtr textUtf16);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectDoublePropertyCallbackDelegate(uint objectId, uint stype, double* value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr GetObjectStringPropertyCallbackDelegate(uint objectId, uint stype);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectWielderInfoCallbackDelegate(uint objectId, uint* wielderID, uint* location);
|
||||
internal unsafe delegate int GetContainerContentsCallbackDelegate(uint containerId, uint* itemIds, int maxCount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetObjectOwnershipInfoCallbackDelegate(uint objectId, uint* containerID, uint* wielderID, uint* location);
|
||||
367
src/RynthCore.Engine/Plugins/PluginLoader.cs
Normal file
367
src/RynthCore.Engine/Plugins/PluginLoader.cs
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/PluginLoader.cs
|
||||
// Scans the Plugins directory, loads each DLL, and resolves exports.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal static class PluginLoader
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr LoadLibraryW(string lpLibFileName);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool FreeLibrary(IntPtr hModule);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
/// <summary>
|
||||
/// Scans <paramref name="pluginsDir"/> for *.dll files, loads each one,
|
||||
/// and resolves the plugin contract exports.
|
||||
/// Returns only plugins that have the two required exports (Init + Shutdown).
|
||||
/// </summary>
|
||||
public static List<LoadedPlugin> LoadAll(string pluginsDir, string shadowRootDir, int generation)
|
||||
{
|
||||
var plugins = new List<LoadedPlugin>();
|
||||
|
||||
if (!Directory.Exists(pluginsDir))
|
||||
{
|
||||
RynthLog.Verbose($"PluginLoader: Creating plugins directory: {pluginsDir}");
|
||||
try { Directory.CreateDirectory(pluginsDir); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: Failed to create directory: {ex.Message}");
|
||||
return plugins;
|
||||
}
|
||||
return plugins;
|
||||
}
|
||||
|
||||
string sessionShadowDir = PrepareShadowDirectory(shadowRootDir, generation);
|
||||
|
||||
string[] dllFiles;
|
||||
try { dllFiles = Directory.GetFiles(pluginsDir, "*.dll"); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: Failed to enumerate {pluginsDir}: {ex.Message}");
|
||||
return plugins;
|
||||
}
|
||||
|
||||
Array.Sort(dllFiles, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (dllFiles.Length == 0)
|
||||
{
|
||||
RynthLog.Verbose("PluginLoader: No plugin DLLs found.");
|
||||
return plugins;
|
||||
}
|
||||
|
||||
RynthLog.Verbose($"PluginLoader: Found {dllFiles.Length} DLL(s) in {pluginsDir}");
|
||||
|
||||
foreach (string dllPath in dllFiles)
|
||||
{
|
||||
var plugin = TryLoad(dllPath, sessionShadowDir);
|
||||
if (plugin != null)
|
||||
plugins.Add(plugin);
|
||||
}
|
||||
|
||||
RynthLog.Verbose($"PluginLoader: {plugins.Count} plugin(s) loaded successfully.");
|
||||
return plugins;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unloads a plugin by freeing its DLL.
|
||||
/// </summary>
|
||||
public static void Unload(LoadedPlugin plugin)
|
||||
{
|
||||
if (plugin.ModuleHandle != IntPtr.Zero)
|
||||
{
|
||||
FreeLibrary(plugin.ModuleHandle);
|
||||
RynthLog.Verbose($"PluginLoader: Unloaded {plugin.FileName}");
|
||||
}
|
||||
|
||||
TryDeleteFile(plugin.FilePath);
|
||||
TryDeleteFile(Path.ChangeExtension(plugin.FilePath, ".pdb"));
|
||||
TryDeleteEmptyDirectory(Path.GetDirectoryName(plugin.FilePath));
|
||||
}
|
||||
|
||||
public static void CleanupShadowCopies(string shadowRootDir)
|
||||
{
|
||||
if (!Directory.Exists(shadowRootDir))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
foreach (string dir in Directory.GetDirectories(shadowRootDir))
|
||||
TryDeleteDirectory(dir);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Verbose($"PluginLoader: Shadow cleanup skipped ({ex.Message})");
|
||||
}
|
||||
}
|
||||
|
||||
private static LoadedPlugin? TryLoad(string sourcePath, string sessionShadowDir)
|
||||
{
|
||||
string fileName = Path.GetFileName(sourcePath);
|
||||
RynthLog.Verbose($"PluginLoader: Loading {fileName}...");
|
||||
|
||||
string shadowPath;
|
||||
try
|
||||
{
|
||||
shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})");
|
||||
return null;
|
||||
}
|
||||
|
||||
IntPtr handle = LoadLibraryW(shadowPath);
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Resolve required exports
|
||||
IntPtr initPtr = GetProcAddress(handle, "RynthPluginInit");
|
||||
IntPtr shutdownPtr = GetProcAddress(handle, "RynthPluginShutdown");
|
||||
|
||||
if (initPtr == IntPtr.Zero || shutdownPtr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: {fileName} missing required exports (RynthPluginInit/RynthPluginShutdown) — skipping.");
|
||||
FreeLibrary(handle);
|
||||
return null;
|
||||
}
|
||||
|
||||
var plugin = new LoadedPlugin
|
||||
{
|
||||
SourceFilePath = sourcePath,
|
||||
FilePath = shadowPath,
|
||||
FileName = fileName,
|
||||
ModuleHandle = handle,
|
||||
Init = Marshal.GetDelegateForFunctionPointer<PluginInitDelegate>(initPtr),
|
||||
Shutdown = Marshal.GetDelegateForFunctionPointer<PluginShutdownDelegate>(shutdownPtr),
|
||||
DisplayName = fileName
|
||||
};
|
||||
|
||||
// Resolve optional exports
|
||||
IntPtr namePtr = GetProcAddress(handle, "RynthPluginName");
|
||||
if (namePtr != IntPtr.Zero)
|
||||
plugin.GetName = Marshal.GetDelegateForFunctionPointer<PluginNameDelegate>(namePtr);
|
||||
|
||||
IntPtr versionPtr = GetProcAddress(handle, "RynthPluginVersion");
|
||||
if (versionPtr != IntPtr.Zero)
|
||||
plugin.GetVersion = Marshal.GetDelegateForFunctionPointer<PluginVersionDelegate>(versionPtr);
|
||||
|
||||
IntPtr onLoginCompletePtr = GetProcAddress(handle, "RynthPluginOnLoginComplete");
|
||||
if (onLoginCompletePtr != IntPtr.Zero)
|
||||
plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer<PluginOnLoginCompleteDelegate>(onLoginCompletePtr);
|
||||
|
||||
IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized");
|
||||
if (onUiInitializedPtr != IntPtr.Zero)
|
||||
plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer<PluginOnUIInitializedDelegate>(onUiInitializedPtr);
|
||||
|
||||
IntPtr onBusyCountIncrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountIncremented");
|
||||
if (onBusyCountIncrementedPtr != IntPtr.Zero)
|
||||
plugin.OnBusyCountIncremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountIncrementedDelegate>(onBusyCountIncrementedPtr);
|
||||
|
||||
IntPtr onBusyCountDecrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountDecremented");
|
||||
if (onBusyCountDecrementedPtr != IntPtr.Zero)
|
||||
plugin.OnBusyCountDecremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountDecrementedDelegate>(onBusyCountDecrementedPtr);
|
||||
|
||||
IntPtr onSelectedTargetChangePtr = GetProcAddress(handle, "RynthPluginOnSelectedTargetChange");
|
||||
if (onSelectedTargetChangePtr != IntPtr.Zero)
|
||||
plugin.OnSelectedTargetChange = Marshal.GetDelegateForFunctionPointer<PluginOnSelectedTargetChangeDelegate>(onSelectedTargetChangePtr);
|
||||
|
||||
IntPtr onCombatModeChangePtr = GetProcAddress(handle, "RynthPluginOnCombatModeChange");
|
||||
if (onCombatModeChangePtr != IntPtr.Zero)
|
||||
plugin.OnCombatModeChange = Marshal.GetDelegateForFunctionPointer<PluginOnCombatModeChangeDelegate>(onCombatModeChangePtr);
|
||||
|
||||
IntPtr onSmartBoxEventPtr = GetProcAddress(handle, "RynthPluginOnSmartBoxEvent");
|
||||
if (onSmartBoxEventPtr != IntPtr.Zero)
|
||||
{
|
||||
plugin.OnSmartBoxEventPtr = onSmartBoxEventPtr;
|
||||
plugin.OnSmartBoxEvent = Marshal.GetDelegateForFunctionPointer<PluginOnSmartBoxEventDelegate>(onSmartBoxEventPtr);
|
||||
}
|
||||
|
||||
IntPtr onDeleteObjectPtr = GetProcAddress(handle, "RynthPluginOnDeleteObject");
|
||||
if (onDeleteObjectPtr != IntPtr.Zero)
|
||||
plugin.OnDeleteObject = Marshal.GetDelegateForFunctionPointer<PluginOnDeleteObjectDelegate>(onDeleteObjectPtr);
|
||||
|
||||
IntPtr onCreateObjectPtr = GetProcAddress(handle, "RynthPluginOnCreateObject");
|
||||
if (onCreateObjectPtr != IntPtr.Zero)
|
||||
plugin.OnCreateObject = Marshal.GetDelegateForFunctionPointer<PluginOnCreateObjectDelegate>(onCreateObjectPtr);
|
||||
|
||||
IntPtr onUpdateObjectPtr = GetProcAddress(handle, "RynthPluginOnUpdateObject");
|
||||
if (onUpdateObjectPtr != IntPtr.Zero)
|
||||
{
|
||||
plugin.OnUpdateObjectPtr = onUpdateObjectPtr;
|
||||
plugin.OnUpdateObject = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectDelegate>(onUpdateObjectPtr);
|
||||
}
|
||||
|
||||
IntPtr onUpdateObjectInventoryPtr = GetProcAddress(handle, "RynthPluginOnUpdateObjectInventory");
|
||||
if (onUpdateObjectInventoryPtr != IntPtr.Zero)
|
||||
plugin.OnUpdateObjectInventory = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectInventoryDelegate>(onUpdateObjectInventoryPtr);
|
||||
|
||||
IntPtr onViewObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnViewObjectContents");
|
||||
if (onViewObjectContentsPtr != IntPtr.Zero)
|
||||
plugin.OnViewObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnViewObjectContentsDelegate>(onViewObjectContentsPtr);
|
||||
|
||||
IntPtr onStopViewingObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnStopViewingObjectContents");
|
||||
if (onStopViewingObjectContentsPtr != IntPtr.Zero)
|
||||
plugin.OnStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnStopViewingObjectContentsDelegate>(onStopViewingObjectContentsPtr);
|
||||
|
||||
IntPtr onUpdateHealthPtr = GetProcAddress(handle, "RynthPluginOnUpdateHealth");
|
||||
if (onUpdateHealthPtr != IntPtr.Zero)
|
||||
{
|
||||
plugin.OnUpdateHealthPtr = onUpdateHealthPtr;
|
||||
plugin.OnUpdateHealth = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateHealthDelegate>(onUpdateHealthPtr);
|
||||
}
|
||||
|
||||
IntPtr onChatWindowTextPtr = GetProcAddress(handle, "RynthPluginOnChatWindowText");
|
||||
if (onChatWindowTextPtr != IntPtr.Zero)
|
||||
{
|
||||
plugin.OnChatWindowTextPtr = onChatWindowTextPtr;
|
||||
plugin.OnChatWindowText = Marshal.GetDelegateForFunctionPointer<PluginOnChatWindowTextDelegate>(onChatWindowTextPtr);
|
||||
}
|
||||
|
||||
IntPtr onChatBarEnterPtr = GetProcAddress(handle, "RynthPluginOnChatBarEnter");
|
||||
if (onChatBarEnterPtr != IntPtr.Zero)
|
||||
plugin.OnChatBarEnter = Marshal.GetDelegateForFunctionPointer<PluginOnChatBarEnterDelegate>(onChatBarEnterPtr);
|
||||
|
||||
IntPtr onBarActionPtr = GetProcAddress(handle, "RynthPluginOnBarAction");
|
||||
if (onBarActionPtr != IntPtr.Zero)
|
||||
plugin.OnBarAction = Marshal.GetDelegateForFunctionPointer<PluginBarActionDelegate>(onBarActionPtr);
|
||||
|
||||
IntPtr onEnchantmentAddedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentAdded");
|
||||
if (onEnchantmentAddedPtr != IntPtr.Zero)
|
||||
plugin.OnEnchantmentAdded = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentAddedDelegate>(onEnchantmentAddedPtr);
|
||||
|
||||
IntPtr onEnchantmentRemovedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentRemoved");
|
||||
if (onEnchantmentRemovedPtr != IntPtr.Zero)
|
||||
plugin.OnEnchantmentRemoved = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentRemovedDelegate>(onEnchantmentRemovedPtr);
|
||||
|
||||
IntPtr tickPtr = GetProcAddress(handle, "RynthPluginTick");
|
||||
if (tickPtr != IntPtr.Zero)
|
||||
plugin.Tick = Marshal.GetDelegateForFunctionPointer<PluginTickDelegate>(tickPtr);
|
||||
|
||||
IntPtr renderPtr = GetProcAddress(handle, "RynthPluginRender");
|
||||
if (renderPtr != IntPtr.Zero)
|
||||
plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr);
|
||||
|
||||
// Read name/version from the plugin if available
|
||||
if (plugin.GetName != null)
|
||||
{
|
||||
IntPtr strPtr = plugin.GetName();
|
||||
if (strPtr != IntPtr.Zero)
|
||||
plugin.DisplayName = Marshal.PtrToStringAnsi(strPtr) ?? fileName;
|
||||
}
|
||||
|
||||
if (plugin.GetVersion != null)
|
||||
{
|
||||
IntPtr strPtr = plugin.GetVersion();
|
||||
if (strPtr != IntPtr.Zero)
|
||||
plugin.VersionString = Marshal.PtrToStringAnsi(strPtr) ?? "";
|
||||
}
|
||||
|
||||
string ver = string.IsNullOrEmpty(plugin.VersionString) ? "" : $" v{plugin.VersionString}";
|
||||
string caps = BuildCapsList(plugin);
|
||||
RynthLog.Verbose($"PluginLoader: {plugin.DisplayName}{ver} loaded ({caps})");
|
||||
|
||||
return plugin;
|
||||
}
|
||||
|
||||
private static string PrepareShadowDirectory(string shadowRootDir, int generation)
|
||||
{
|
||||
string sessionDir = Path.Combine(shadowRootDir, $"session-{generation:D4}-pid{Environment.ProcessId}");
|
||||
Directory.CreateDirectory(sessionDir);
|
||||
return sessionDir;
|
||||
}
|
||||
|
||||
private static string CreateShadowCopy(string sourcePath, string sessionShadowDir)
|
||||
{
|
||||
string fileName = Path.GetFileName(sourcePath);
|
||||
string shadowPath = Path.Combine(sessionShadowDir, fileName);
|
||||
File.Copy(sourcePath, shadowPath, true);
|
||||
|
||||
string sourcePdb = Path.ChangeExtension(sourcePath, ".pdb");
|
||||
string shadowPdb = Path.ChangeExtension(shadowPath, ".pdb");
|
||||
if (File.Exists(sourcePdb))
|
||||
File.Copy(sourcePdb, shadowPdb, true);
|
||||
|
||||
return shadowPath;
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteEmptyDirectory(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
if (Directory.GetFileSystemEntries(path).Length == 0)
|
||||
Directory.Delete(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteDirectory(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(path, true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCapsList(LoadedPlugin p)
|
||||
{
|
||||
var parts = new List<string>(4) { "init", "shutdown" };
|
||||
if (p.OnLoginComplete != null) parts.Add("login");
|
||||
if (p.OnUIInitialized != null) parts.Add("ui");
|
||||
if (p.OnBusyCountIncremented != null) parts.Add("busy+");
|
||||
if (p.OnBusyCountDecremented != null) parts.Add("busy-");
|
||||
if (p.OnSelectedTargetChange != null) parts.Add("target");
|
||||
if (p.OnCombatModeChange != null) parts.Add("combat-mode");
|
||||
if (p.OnSmartBoxEvent != null) parts.Add("smartbox");
|
||||
if (p.OnCreateObject != null) parts.Add("create");
|
||||
if (p.OnDeleteObject != null) parts.Add("delete");
|
||||
if (p.OnUpdateObject != null) parts.Add("update-object");
|
||||
if (p.OnUpdateObjectInventory != null) parts.Add("inventory");
|
||||
if (p.OnViewObjectContents != null) parts.Add("contents-open");
|
||||
if (p.OnStopViewingObjectContents != null) parts.Add("contents-close");
|
||||
if (p.OnUpdateHealth != null || p.OnUpdateHealthPtr != IntPtr.Zero) parts.Add("health");
|
||||
if (p.OnChatWindowText != null) parts.Add("chat-in");
|
||||
if (p.OnChatBarEnter != null) parts.Add("chat-out");
|
||||
if (p.OnBarAction != null) parts.Add("bar");
|
||||
if (p.Tick != null) parts.Add("tick");
|
||||
if (p.Render != null) parts.Add("render");
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
}
|
||||
2104
src/RynthCore.Engine/Plugins/PluginManager.cs
Normal file
2104
src/RynthCore.Engine/Plugins/PluginManager.cs
Normal file
File diff suppressed because it is too large
Load diff
114
src/RynthCore.Engine/RynthCore.Engine.csproj
Normal file
114
src/RynthCore.Engine/RynthCore.Engine.csproj
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<NativeLib>Shared</NativeLib>
|
||||
<RootNamespace>RynthCore.Engine</RootNamespace>
|
||||
<AssemblyName>RynthCore.Engine</AssemblyName>
|
||||
|
||||
<!-- NativeAOT settings -->
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
|
||||
<StackTraceSupport>false</StackTraceSupport>
|
||||
|
||||
<!-- Keep ImGui.NET's P/Invoke bindings intact -->
|
||||
<TrimMode>link</TrimMode>
|
||||
|
||||
<Platforms>x86</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<StackTraceSupport>true</StackTraceSupport>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
|
||||
<PackageReference Include="Avalonia" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Skia" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Prevent trimmer from removing ImGui.NET's DllImport methods -->
|
||||
<!-- Root Avalonia assemblies so the AOT trimmer keeps them intact -->
|
||||
<ItemGroup>
|
||||
<TrimmerRootAssembly Include="ImGui.NET" />
|
||||
<TrimmerRootAssembly Include="Avalonia" />
|
||||
<TrimmerRootAssembly Include="Avalonia.Base" />
|
||||
<TrimmerRootAssembly Include="Avalonia.Desktop" />
|
||||
<TrimmerRootAssembly Include="Avalonia.Win32" />
|
||||
<TrimmerRootAssembly Include="Avalonia.Skia" />
|
||||
<TrimmerRootAssembly Include="Avalonia.Themes.Simple" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<BundledNativeDll Include="Native\cimgui.dll" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<BundledSupportDll Include="Native\minhook.x86.dll" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyBundledNativeDlls" AfterTargets="Build">
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(OutputPath)Native\%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(OutputPath)Native\RynthCore.%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(OutputPath)%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(OutputPath)RynthCore.%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
|
||||
<Target Name="CopyBundledNativeDllsToPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(PublishDir)Native\%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(PublishDir)Native\RynthCore.%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(PublishDir)%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledNativeDll)"
|
||||
DestinationFiles="@(BundledNativeDll->'$(PublishDir)RynthCore.%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
<Copy
|
||||
SourceFiles="@(BundledSupportDll)"
|
||||
DestinationFiles="@(BundledSupportDll->'$(PublishDir)%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
|
||||
<Target Name="CopyBundledSupportDlls" AfterTargets="Build">
|
||||
<Copy
|
||||
SourceFiles="@(BundledSupportDll)"
|
||||
DestinationFiles="@(BundledSupportDll->'$(OutputPath)%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
62
src/RynthCore.Engine/RynthLog.cs
Normal file
62
src/RynthCore.Engine/RynthLog.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
namespace RynthCore.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Centralised logging — every log call in the Engine routes through here.
|
||||
/// Toggle categories on/off at runtime to suppress entire subsystems.
|
||||
/// Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
|
||||
/// </summary>
|
||||
internal static class RynthLog
|
||||
{
|
||||
// ── Category toggles (flip to false to silence a subsystem) ──────────
|
||||
|
||||
internal static bool D3D9Enabled = false;
|
||||
internal static bool CompatEnabled = true;
|
||||
internal static bool RenderEnabled = false; // ImGui, DX9Backend, Win32Backend
|
||||
internal static bool PluginEnabled = true;
|
||||
internal static bool UIEnabled = false;
|
||||
|
||||
// ── Category methods ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
|
||||
internal static void D3D9(string msg)
|
||||
{
|
||||
if (D3D9Enabled) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary>
|
||||
internal static void Compat(string msg)
|
||||
{
|
||||
if (CompatEnabled) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
|
||||
internal static void Render(string msg)
|
||||
{
|
||||
if (RenderEnabled) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary>
|
||||
internal static void Plugin(string msg)
|
||||
{
|
||||
if (PluginEnabled) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>UI / Avalonia overlay subsystem.</summary>
|
||||
internal static void UI(string msg)
|
||||
{
|
||||
if (UIEnabled) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>Verbose-only log (any category). Only written when VerboseLogging is on.</summary>
|
||||
internal static void Verbose(string msg)
|
||||
{
|
||||
if (EntryPoint.VerboseLogging) Write(msg);
|
||||
}
|
||||
|
||||
/// <summary>Always-on log for critical / uncategorised messages.</summary>
|
||||
internal static void Info(string msg) => Write(msg);
|
||||
|
||||
// ── Sink ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Write(string message) => EntryPoint.Log(message);
|
||||
}
|
||||
128
src/RynthCore.Engine/UI/AngleOverlaySurfaceBridge.cs
Normal file
128
src/RynthCore.Engine/UI/AngleOverlaySurfaceBridge.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal sealed class AngleOverlaySurfaceBridge : IOverlaySurfaceBridge
|
||||
{
|
||||
private readonly object _sync = new();
|
||||
private readonly SoftwareOverlaySurfaceBridge _softwareFallback = new();
|
||||
private OverlaySurfaceFrame? _pendingSharedFrame;
|
||||
private IntPtr _activeSharedHandle;
|
||||
private IntPtr _lastProbedSharedHandle;
|
||||
private bool _sharedInteropUnavailable;
|
||||
private int _loggedSoftwareFallback;
|
||||
private int _loggedSharedTexture;
|
||||
private int _loggedSharedUnavailable;
|
||||
|
||||
public string Name => "angle-preferred-hybrid";
|
||||
public bool SupportsGpuInterop => true;
|
||||
public bool ShouldAttemptSharedTextures => !_sharedInteropUnavailable;
|
||||
|
||||
public void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _loggedSoftwareFallback, 1) == 0)
|
||||
{
|
||||
RynthLog.UI("AngleOverlaySurfaceBridge: Using software frames as a fallback until native shared textures are available.");
|
||||
}
|
||||
|
||||
_softwareFallback.SubmitSoftwareFrame(pixelData, byteCount, width, height);
|
||||
}
|
||||
|
||||
public void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
if (_sharedInteropUnavailable)
|
||||
return;
|
||||
|
||||
if (Interlocked.Exchange(ref _loggedSharedTexture, 1) == 0)
|
||||
{
|
||||
RynthLog.UI($"AngleOverlaySurfaceBridge: Received first {kind} shared texture submission.");
|
||||
}
|
||||
|
||||
lock (_sync)
|
||||
{
|
||||
if (descriptor.SharedHandle != IntPtr.Zero &&
|
||||
_activeSharedHandle != IntPtr.Zero &&
|
||||
descriptor.SharedHandle != _activeSharedHandle)
|
||||
{
|
||||
// A new shared handle usually means the producer recreated its texture.
|
||||
// Pause shared consumption until the renderer confirms it opened the new one.
|
||||
_activeSharedHandle = IntPtr.Zero;
|
||||
}
|
||||
|
||||
_pendingSharedFrame = new OverlaySurfaceFrame(kind, descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifySharedTextureOpened(IntPtr sharedHandle)
|
||||
{
|
||||
if (sharedHandle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
lock (_sync)
|
||||
{
|
||||
_activeSharedHandle = sharedHandle;
|
||||
_lastProbedSharedHandle = sharedHandle;
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifySharedTextureUnavailable()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_sharedInteropUnavailable = true;
|
||||
_pendingSharedFrame = null;
|
||||
_activeSharedHandle = IntPtr.Zero;
|
||||
_lastProbedSharedHandle = IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _loggedSharedUnavailable, 1) == 0)
|
||||
{
|
||||
RynthLog.UI("AngleOverlaySurfaceBridge: Shared-texture consumption is unavailable on this client; staying on software frames.");
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryConsume(out OverlaySurfaceFrame? frame)
|
||||
{
|
||||
if (_sharedInteropUnavailable)
|
||||
return _softwareFallback.TryConsume(out frame);
|
||||
|
||||
OverlaySurfaceFrame? sharedProbeFrame = null;
|
||||
bool sharedIsActive;
|
||||
|
||||
lock (_sync)
|
||||
{
|
||||
sharedIsActive = _activeSharedHandle != IntPtr.Zero;
|
||||
|
||||
if (_pendingSharedFrame?.SharedTexture is OverlaySharedTextureDescriptor descriptor &&
|
||||
descriptor.SharedHandle != IntPtr.Zero)
|
||||
{
|
||||
if (_activeSharedHandle != IntPtr.Zero && descriptor.SharedHandle == _activeSharedHandle)
|
||||
{
|
||||
_pendingSharedFrame = null;
|
||||
sharedIsActive = true;
|
||||
}
|
||||
else if (descriptor.SharedHandle != _lastProbedSharedHandle)
|
||||
{
|
||||
_lastProbedSharedHandle = descriptor.SharedHandle;
|
||||
sharedProbeFrame = _pendingSharedFrame;
|
||||
_pendingSharedFrame = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sharedProbeFrame != null)
|
||||
{
|
||||
frame = sharedProbeFrame;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sharedIsActive)
|
||||
{
|
||||
frame = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
return _softwareFallback.TryConsume(out frame);
|
||||
}
|
||||
}
|
||||
1105
src/RynthCore.Engine/UI/AvaloniaOverlay.cs
Normal file
1105
src/RynthCore.Engine/UI/AvaloniaOverlay.cs
Normal file
File diff suppressed because it is too large
Load diff
15
src/RynthCore.Engine/UI/IOverlaySurfaceBridge.cs
Normal file
15
src/RynthCore.Engine/UI/IOverlaySurfaceBridge.cs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal interface IOverlaySurfaceBridge
|
||||
{
|
||||
string Name { get; }
|
||||
bool SupportsGpuInterop { get; }
|
||||
bool ShouldAttemptSharedTextures { get; }
|
||||
void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height);
|
||||
void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor);
|
||||
void NotifySharedTextureOpened(IntPtr sharedHandle);
|
||||
void NotifySharedTextureUnavailable();
|
||||
bool TryConsume(out OverlaySurfaceFrame? frame);
|
||||
}
|
||||
354
src/RynthCore.Engine/UI/OverlayD3D9SharedTexturePublisher.cs
Normal file
354
src/RynthCore.Engine/UI/OverlayD3D9SharedTexturePublisher.cs
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.D3D9;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal sealed unsafe class OverlayD3D9SharedTexturePublisher : IDisposable
|
||||
{
|
||||
private const uint D3D_SDK_VERSION = 32;
|
||||
private const uint D3DDEVTYPE_HAL = 1;
|
||||
private const uint D3DCREATE_FPU_PRESERVE = 0x00000002;
|
||||
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
|
||||
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
|
||||
private const uint D3DFMT_UNKNOWN = 0;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21;
|
||||
private const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
private const uint D3DPOOL_DEFAULT = 0;
|
||||
private const uint D3DUSAGE_DYNAMIC = 0x00000200;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat;
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType;
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect;
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed;
|
||||
public int EnableAutoDepthStencil;
|
||||
public uint AutoDepthStencilFormat;
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DLOCKED_RECT
|
||||
{
|
||||
public int Pitch;
|
||||
public IntPtr pBits;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Luid
|
||||
{
|
||||
public uint LowPart;
|
||||
public int HighPart;
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceExD(
|
||||
IntPtr pD3D9Ex,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
IntPtr pFullscreenDisplayMode,
|
||||
out IntPtr ppReturnedDeviceInterface);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetAdapterLuidD(IntPtr pD3D9Ex, uint adapter, out Luid luid);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateTextureD(
|
||||
IntPtr device,
|
||||
uint width,
|
||||
uint height,
|
||||
uint levels,
|
||||
uint usage,
|
||||
uint format,
|
||||
uint pool,
|
||||
out IntPtr texture,
|
||||
IntPtr sharedHandle);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int LockRectD(IntPtr texture, uint level, D3DLOCKED_RECT* lockedRect, IntPtr rect, uint flags);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int UnlockRectD(IntPtr texture, uint level);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseD(IntPtr pObj);
|
||||
|
||||
[DllImport("d3d9.dll")]
|
||||
private static extern int Direct3DCreate9Ex(uint sdkVersion, out IntPtr direct3D9Ex);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateWindowExA(
|
||||
uint dwExStyle,
|
||||
string lpClassName,
|
||||
string lpWindowName,
|
||||
uint dwStyle,
|
||||
int x,
|
||||
int y,
|
||||
int nWidth,
|
||||
int nHeight,
|
||||
IntPtr hWndParent,
|
||||
IntPtr hMenu,
|
||||
IntPtr hInstance,
|
||||
IntPtr lpParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
private IntPtr _windowHandle;
|
||||
private IntPtr _d3d9Ex;
|
||||
private IntPtr _deviceEx;
|
||||
private IntPtr _texture;
|
||||
private IntPtr _sharedHandle;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private long _adapterLuid;
|
||||
private bool _loggedAvailability;
|
||||
|
||||
public bool TryUpload(
|
||||
IntPtr pixelData,
|
||||
int byteCount,
|
||||
int width,
|
||||
int height,
|
||||
int rowPitch,
|
||||
out OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
descriptor = default;
|
||||
|
||||
if (pixelData == IntPtr.Zero || byteCount <= 0 || width <= 0 || height <= 0 || rowPitch <= 0)
|
||||
return false;
|
||||
|
||||
if (!EnsureDevice())
|
||||
return false;
|
||||
|
||||
if (!EnsureTexture(width, height))
|
||||
return false;
|
||||
|
||||
var lockRect = GetTextureMethod<LockRectD>(_texture, TextureVTableIndex.LockRect);
|
||||
var unlockRect = GetTextureMethod<UnlockRectD>(_texture, TextureVTableIndex.UnlockRect);
|
||||
|
||||
D3DLOCKED_RECT locked;
|
||||
int hr = lockRect(_texture, 0, &locked, IntPtr.Zero, 0);
|
||||
if (hr < 0 || locked.pBits == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: LockRect failed, HRESULT=0x{hr:X8}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int bytesPerRow = Math.Min(rowPitch, locked.Pitch);
|
||||
for (int row = 0; row < height; row++)
|
||||
{
|
||||
IntPtr sourceRow = pixelData + (row * rowPitch);
|
||||
IntPtr targetRow = locked.pBits + (row * locked.Pitch);
|
||||
Buffer.MemoryCopy((void*)sourceRow, (void*)targetRow, bytesPerRow, bytesPerRow);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlockRect(_texture, 0);
|
||||
}
|
||||
|
||||
descriptor = new OverlaySharedTextureDescriptor(
|
||||
_sharedHandle,
|
||||
_adapterLuid,
|
||||
width,
|
||||
height,
|
||||
(int)D3DFMT_A8R8G8B8,
|
||||
rowPitch,
|
||||
(int)D3DUSAGE_DYNAMIC);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ReleaseTexture();
|
||||
ReleaseComObject(ref _deviceEx);
|
||||
ReleaseComObject(ref _d3d9Ex);
|
||||
|
||||
if (_windowHandle != IntPtr.Zero)
|
||||
{
|
||||
DestroyWindow(_windowHandle);
|
||||
_windowHandle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
private bool EnsureDevice()
|
||||
{
|
||||
if (_deviceEx != IntPtr.Zero)
|
||||
return true;
|
||||
|
||||
_windowHandle = CreateWindowExA(
|
||||
0,
|
||||
"STATIC",
|
||||
"RynthCore_D3D9_SharedTexture",
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
IntPtr.Zero,
|
||||
IntPtr.Zero,
|
||||
GetModuleHandleA(null),
|
||||
IntPtr.Zero);
|
||||
|
||||
if (_windowHandle == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.UI("OverlayD3D9SharedTexturePublisher: Failed to create helper window.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int hr = Direct3DCreate9Ex(D3D_SDK_VERSION, out _d3d9Ex);
|
||||
if (hr < 0 || _d3d9Ex == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: Direct3DCreate9Ex failed, HRESULT=0x{hr:X8}.");
|
||||
Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr d3d9ExVTable = Marshal.ReadIntPtr(_d3d9Ex);
|
||||
var createDeviceEx = Marshal.GetDelegateForFunctionPointer<CreateDeviceExD>(
|
||||
Marshal.ReadIntPtr(d3d9ExVTable, 20 * IntPtr.Size));
|
||||
var getAdapterLuid = Marshal.GetDelegateForFunctionPointer<GetAdapterLuidD>(
|
||||
Marshal.ReadIntPtr(d3d9ExVTable, 21 * IntPtr.Size));
|
||||
|
||||
var presentParameters = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = 1,
|
||||
BackBufferHeight = 1,
|
||||
BackBufferFormat = D3DFMT_UNKNOWN,
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = _windowHandle,
|
||||
Windowed = 1
|
||||
};
|
||||
|
||||
IntPtr parametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
|
||||
try
|
||||
{
|
||||
Marshal.StructureToPtr(presentParameters, parametersPtr, false);
|
||||
hr = createDeviceEx(
|
||||
_d3d9Ex,
|
||||
0,
|
||||
D3DDEVTYPE_HAL,
|
||||
_windowHandle,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
|
||||
parametersPtr,
|
||||
IntPtr.Zero,
|
||||
out _deviceEx);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(parametersPtr);
|
||||
}
|
||||
|
||||
if (hr < 0 || _deviceEx == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: CreateDeviceEx failed, HRESULT=0x{hr:X8}.");
|
||||
Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (getAdapterLuid(_d3d9Ex, 0, out Luid luid) >= 0)
|
||||
{
|
||||
_adapterLuid = ((long)luid.HighPart << 32) | luid.LowPart;
|
||||
}
|
||||
|
||||
if (!_loggedAvailability)
|
||||
{
|
||||
_loggedAvailability = true;
|
||||
RynthLog.UI("OverlayD3D9SharedTexturePublisher: D3D9Ex shared-texture upload path is available.");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool EnsureTexture(int width, int height)
|
||||
{
|
||||
if (_texture != IntPtr.Zero && _width == width && _height == height && _sharedHandle != IntPtr.Zero)
|
||||
return true;
|
||||
|
||||
ReleaseTexture();
|
||||
|
||||
var createTexture = GetDeviceMethod<CreateTextureD>(_deviceEx, DeviceVTableIndex.CreateTexture);
|
||||
IntPtr sharedHandle = IntPtr.Zero;
|
||||
int hr = createTexture(
|
||||
_deviceEx,
|
||||
(uint)width,
|
||||
(uint)height,
|
||||
1,
|
||||
D3DUSAGE_DYNAMIC,
|
||||
D3DFMT_A8R8G8B8,
|
||||
D3DPOOL_DEFAULT,
|
||||
out _texture,
|
||||
new IntPtr(&sharedHandle));
|
||||
|
||||
if (hr < 0 || _texture == IntPtr.Zero || sharedHandle == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.UI(
|
||||
$"OverlayD3D9SharedTexturePublisher: CreateTexture failed for {width}x{height}, HRESULT=0x{hr:X8}, handle=0x{sharedHandle:X8}.");
|
||||
ReleaseTexture();
|
||||
return false;
|
||||
}
|
||||
|
||||
_sharedHandle = sharedHandle;
|
||||
_width = width;
|
||||
_height = height;
|
||||
RynthLog.UI(
|
||||
$"OverlayD3D9SharedTexturePublisher: Created shared upload texture {width}x{height}, handle=0x{_sharedHandle:X8}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ReleaseTexture()
|
||||
{
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
ReleaseComObject(ref _texture);
|
||||
_sharedHandle = IntPtr.Zero;
|
||||
_width = 0;
|
||||
_height = 0;
|
||||
}
|
||||
|
||||
private static void ReleaseComObject(ref IntPtr obj)
|
||||
{
|
||||
if (obj == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(obj);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
|
||||
Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size));
|
||||
release(obj);
|
||||
obj = IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static T GetDeviceMethod<T>(IntPtr device, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(device);
|
||||
IntPtr address = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(address);
|
||||
}
|
||||
|
||||
private static T GetTextureMethod<T>(IntPtr texture, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(texture);
|
||||
IntPtr address = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(address);
|
||||
}
|
||||
}
|
||||
72
src/RynthCore.Engine/UI/OverlayFrameBuffer.cs
Normal file
72
src/RynthCore.Engine/UI/OverlayFrameBuffer.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/OverlayFrameBuffer.cs
|
||||
// Lock-minimised pixel handoff from the Avalonia UI thread to the D3D9
|
||||
// render thread. Avalonia submits a captured BGRA frame; EndScene consumes
|
||||
// it once, uploads to a D3D9 texture, then re-uses that texture until the
|
||||
// next submit.
|
||||
//
|
||||
// Thread model:
|
||||
// Writer: Avalonia STA thread (DispatcherTimer ~30 fps)
|
||||
// Reader: D3D9 render thread (EndScene ~60 fps)
|
||||
//
|
||||
// The submitted buffer is replaced atomically (pointer swap). The reader
|
||||
// holds a reference for the duration of the upload, preventing GC collection
|
||||
// even if the writer has already posted a newer frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class OverlayFrameBuffer
|
||||
{
|
||||
private sealed class Frame
|
||||
{
|
||||
public readonly byte[] Pixels;
|
||||
public readonly int Width;
|
||||
public readonly int Height;
|
||||
|
||||
public Frame(byte[] pixels, int w, int h)
|
||||
{
|
||||
Pixels = pixels;
|
||||
Width = w;
|
||||
Height = h;
|
||||
}
|
||||
}
|
||||
|
||||
// Written by Avalonia thread, read by D3D9 thread.
|
||||
// Interlocked.Exchange gives the sequential-consistency guarantee we need.
|
||||
private static Frame? _pending;
|
||||
|
||||
/// <summary>
|
||||
/// Submit a new BGRA frame from the Avalonia UI thread.
|
||||
/// The pixel array is copied so the caller can reuse its bitmap lock buffer.
|
||||
/// </summary>
|
||||
public static void Submit(IntPtr pixelData, int byteCount, int w, int h)
|
||||
{
|
||||
var buf = new byte[byteCount];
|
||||
System.Runtime.InteropServices.Marshal.Copy(pixelData, buf, 0, byteCount);
|
||||
Interlocked.Exchange(ref _pending, new Frame(buf, w, h));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consume the latest pending frame from the D3D9 render thread.
|
||||
/// Returns true if a new frame is available; the caller owns the byte array
|
||||
/// until the next call (no further synchronisation required).
|
||||
/// </summary>
|
||||
public static bool TryConsume(out byte[]? pixels, out int w, out int h)
|
||||
{
|
||||
Frame? frame = Interlocked.Exchange(ref _pending, null);
|
||||
if (frame == null)
|
||||
{
|
||||
pixels = null; w = 0; h = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
pixels = frame.Pixels;
|
||||
w = frame.Width;
|
||||
h = frame.Height;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
26
src/RynthCore.Engine/UI/OverlayHost.cs
Normal file
26
src/RynthCore.Engine/UI/OverlayHost.cs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/OverlayHost.cs
|
||||
// Static registry for overlay panels. Engine code registers panels before
|
||||
// AvaloniaOverlay.Start() is called; the window reads them at creation time.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class OverlayHost
|
||||
{
|
||||
private static readonly List<(string Title, Func<Control> Factory)> _panels = new();
|
||||
|
||||
/// <summary>
|
||||
/// Register a panel tab. Call before AvaloniaOverlay.Start().
|
||||
/// Factory is invoked on the Avalonia UI thread when the window is created.
|
||||
/// </summary>
|
||||
internal static void RegisterPanel(string title, Func<Control> factory)
|
||||
=> _panels.Add((title, factory));
|
||||
|
||||
internal static IReadOnlyList<(string Title, Func<Control> Factory)> GetPanels()
|
||||
=> _panels;
|
||||
}
|
||||
262
src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs
Normal file
262
src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Avalonia;
|
||||
using Avalonia.Platform;
|
||||
using Avalonia.Skia;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal sealed class OverlaySkiaPlatformGraphics : IPlatformGraphicsWithFeatures
|
||||
{
|
||||
private readonly OverlaySkiaGpuContext _sharedContext = new();
|
||||
|
||||
public bool UsesSharedContext => true;
|
||||
|
||||
public IPlatformGraphicsContext CreateContext() => _sharedContext;
|
||||
|
||||
public IPlatformGraphicsContext GetSharedContext() => _sharedContext;
|
||||
|
||||
public object? TryGetFeature(Type featureType) => _sharedContext.TryGetFeature(featureType);
|
||||
}
|
||||
|
||||
internal sealed class OverlaySkiaGpuContext : ISkiaGpu
|
||||
{
|
||||
private static readonly IDisposable NoopLease = new NoopDisposable();
|
||||
private readonly object _sync = new();
|
||||
private OverlaySkiaRenderTarget? _renderTarget;
|
||||
|
||||
public bool IsLost => false;
|
||||
|
||||
public IDisposable EnsureCurrent() => NoopLease;
|
||||
|
||||
public object? TryGetFeature(Type featureType) => null;
|
||||
|
||||
public ISkiaGpuRenderTarget? TryCreateRenderTarget(IEnumerable<object> surfaces)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_renderTarget ??= new OverlaySkiaRenderTarget();
|
||||
return _renderTarget;
|
||||
}
|
||||
}
|
||||
|
||||
public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session)
|
||||
{
|
||||
if (size.Width <= 0 || size.Height <= 0)
|
||||
return null;
|
||||
|
||||
return new OverlaySkiaSurface(size.Width, size.Height);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_renderTarget?.Dispose();
|
||||
_renderTarget = null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NoopDisposable : IDisposable
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
|
||||
{
|
||||
private readonly object _sync = new();
|
||||
private OverlayD3D9SharedTexturePublisher? _sharedTexturePublisher;
|
||||
private SKSurface? _surface;
|
||||
private byte[]? _softwareBuffer;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _loggedSharedTextureDisabled;
|
||||
|
||||
public bool IsCorrupted => false;
|
||||
|
||||
public ISkiaGpuRenderSession BeginRenderingSession()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
EnsureSurface();
|
||||
if (_surface == null)
|
||||
throw new InvalidOperationException("Overlay Skia render surface could not be created.");
|
||||
|
||||
_surface.Canvas.Clear(SKColors.Transparent);
|
||||
return new OverlaySkiaRenderSession(this, _surface, _width, _height);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_surface?.Dispose();
|
||||
_surface = null;
|
||||
_softwareBuffer = null;
|
||||
_sharedTexturePublisher?.Dispose();
|
||||
_width = 0;
|
||||
_height = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] RentSoftwareBuffer(int byteCount)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_softwareBuffer == null || _softwareBuffer.Length != byteCount)
|
||||
_softwareBuffer = new byte[byteCount];
|
||||
|
||||
return _softwareBuffer;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TrySubmitSharedTexture(
|
||||
IntPtr pixelData,
|
||||
int byteCount,
|
||||
int width,
|
||||
int height,
|
||||
int rowPitch,
|
||||
out OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (!AvaloniaOverlay.UseAnglePreferredBridge || !OverlaySurfaceBridge.ShouldAttemptSharedTextures)
|
||||
{
|
||||
if (_sharedTexturePublisher != null)
|
||||
{
|
||||
_sharedTexturePublisher.Dispose();
|
||||
_sharedTexturePublisher = null;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _loggedSharedTextureDisabled, 1) == 0)
|
||||
{
|
||||
RynthLog.UI("OverlaySkiaRenderTarget: Shared-texture uploads disabled for this session; continuing with software submissions.");
|
||||
}
|
||||
|
||||
descriptor = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
_sharedTexturePublisher ??= new OverlayD3D9SharedTexturePublisher();
|
||||
return _sharedTexturePublisher.TryUpload(pixelData, byteCount, width, height, rowPitch, out descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureSurface()
|
||||
{
|
||||
int width = AvaloniaOverlay.ClientPixelWidth > 1 ? AvaloniaOverlay.ClientPixelWidth : AvaloniaOverlay.ViewportWidth;
|
||||
int height = AvaloniaOverlay.ClientPixelHeight > 1 ? AvaloniaOverlay.ClientPixelHeight : AvaloniaOverlay.ViewportHeight;
|
||||
|
||||
if (width <= 1 || height <= 1)
|
||||
{
|
||||
width = _width > 1 ? _width : 1;
|
||||
height = _height > 1 ? _height : 1;
|
||||
}
|
||||
|
||||
if (_surface != null && width == _width && height == _height)
|
||||
return;
|
||||
|
||||
_surface?.Dispose();
|
||||
_width = width;
|
||||
_height = height;
|
||||
|
||||
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
|
||||
_surface = SKSurface.Create(info);
|
||||
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height}.");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OverlaySkiaRenderSession : ISkiaGpuRenderSession
|
||||
{
|
||||
private static int _loggedTinyBootstrapFrame;
|
||||
private readonly OverlaySkiaRenderTarget _owner;
|
||||
private readonly SKSurface _surface;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private bool _disposed;
|
||||
|
||||
public OverlaySkiaRenderSession(OverlaySkiaRenderTarget owner, SKSurface surface, int width, int height)
|
||||
{
|
||||
_owner = owner;
|
||||
_surface = surface;
|
||||
_width = width;
|
||||
_height = height;
|
||||
}
|
||||
|
||||
public GRContext GrContext => null!;
|
||||
public double ScaleFactor => 1.0d;
|
||||
public SKSurface SkSurface => _surface;
|
||||
public GRSurfaceOrigin SurfaceOrigin => GRSurfaceOrigin.TopLeft;
|
||||
|
||||
public unsafe void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (_width <= 1 || _height <= 1)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _loggedTinyBootstrapFrame, 1) == 0)
|
||||
{
|
||||
RynthLog.UI("OverlaySkiaRenderSession: Skipping tiny bootstrap frame until the game surface reports a real size.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!AvaloniaOverlay.ShouldUseCustomSkiaProducer)
|
||||
return;
|
||||
|
||||
var info = new SKImageInfo(_width, _height, SKColorType.Bgra8888, SKAlphaType.Premul);
|
||||
byte[] pixels = _owner.RentSoftwareBuffer(info.BytesSize);
|
||||
|
||||
fixed (byte* pixelPtr = pixels)
|
||||
{
|
||||
if (!_surface.ReadPixels(info, (IntPtr)pixelPtr, info.RowBytes, 0, 0))
|
||||
{
|
||||
RynthLog.UI("OverlaySkiaRenderSession: Failed to read pixels from custom render target.");
|
||||
return;
|
||||
}
|
||||
|
||||
AvaloniaOverlay.SurfacePixelWidth = _width;
|
||||
AvaloniaOverlay.SurfacePixelHeight = _height;
|
||||
if (_owner.TrySubmitSharedTexture((IntPtr)pixelPtr, pixels.Length, _width, _height, info.RowBytes, out OverlaySharedTextureDescriptor sharedDescriptor))
|
||||
{
|
||||
OverlaySurfaceBridge.SubmitSharedTexture(OverlaySurfaceKind.D3D9SharedTexture, sharedDescriptor);
|
||||
}
|
||||
|
||||
OverlaySurfaceBridge.SubmitSoftwareFrame((IntPtr)pixelPtr, pixels.Length, _width, _height);
|
||||
AvaloniaOverlay.NotifyCustomFrameSubmitted(_width, _height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OverlaySkiaSurface : ISkiaSurface
|
||||
{
|
||||
public OverlaySkiaSurface(int width, int height)
|
||||
{
|
||||
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
|
||||
Surface = SKSurface.Create(info) ?? throw new InvalidOperationException("Unable to create Skia surface.");
|
||||
}
|
||||
|
||||
public bool CanBlit => true;
|
||||
public SKSurface Surface { get; }
|
||||
|
||||
public void Blit(SKCanvas canvas)
|
||||
{
|
||||
using var snapshot = Surface.Snapshot();
|
||||
canvas.DrawImage(snapshot, 0, 0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Surface.Dispose();
|
||||
}
|
||||
}
|
||||
64
src/RynthCore.Engine/UI/OverlaySurfaceBridge.cs
Normal file
64
src/RynthCore.Engine/UI/OverlaySurfaceBridge.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class OverlaySurfaceBridge
|
||||
{
|
||||
private static readonly IOverlaySurfaceBridge SoftwareBridge = new SoftwareOverlaySurfaceBridge();
|
||||
private static readonly IOverlaySurfaceBridge AngleBridge = new AngleOverlaySurfaceBridge();
|
||||
private static IOverlaySurfaceBridge _activeBridge = SoftwareBridge;
|
||||
private static bool _loggedSelection;
|
||||
|
||||
public static string ActiveName => _activeBridge.Name;
|
||||
public static bool ActiveSupportsGpuInterop => _activeBridge.SupportsGpuInterop;
|
||||
public static bool ShouldAttemptSharedTextures => _activeBridge.ShouldAttemptSharedTextures;
|
||||
|
||||
public static void UseSoftwareFallback()
|
||||
{
|
||||
_activeBridge = SoftwareBridge;
|
||||
_loggedSelection = false;
|
||||
}
|
||||
|
||||
public static void UseAngleStub()
|
||||
{
|
||||
_activeBridge = AngleBridge;
|
||||
_loggedSelection = false;
|
||||
}
|
||||
|
||||
public static void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
|
||||
{
|
||||
LogSelectionOnce();
|
||||
_activeBridge.SubmitSoftwareFrame(pixelData, byteCount, width, height);
|
||||
}
|
||||
|
||||
public static void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
LogSelectionOnce();
|
||||
_activeBridge.SubmitSharedTexture(kind, descriptor);
|
||||
}
|
||||
|
||||
public static void NotifySharedTextureOpened(IntPtr sharedHandle)
|
||||
{
|
||||
_activeBridge.NotifySharedTextureOpened(sharedHandle);
|
||||
}
|
||||
|
||||
public static void NotifySharedTextureUnavailable()
|
||||
{
|
||||
_activeBridge.NotifySharedTextureUnavailable();
|
||||
}
|
||||
|
||||
public static bool TryConsume(out OverlaySurfaceFrame? frame)
|
||||
{
|
||||
LogSelectionOnce();
|
||||
return _activeBridge.TryConsume(out frame);
|
||||
}
|
||||
|
||||
private static void LogSelectionOnce()
|
||||
{
|
||||
if (_loggedSelection)
|
||||
return;
|
||||
|
||||
_loggedSelection = true;
|
||||
RynthLog.UI($"OverlaySurfaceBridge: Active path = {ActiveName} (gpuInterop={ActiveSupportsGpuInterop}).");
|
||||
}
|
||||
}
|
||||
45
src/RynthCore.Engine/UI/OverlaySurfaceFrame.cs
Normal file
45
src/RynthCore.Engine/UI/OverlaySurfaceFrame.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal enum OverlaySurfaceKind
|
||||
{
|
||||
SoftwareBgra32 = 0,
|
||||
AngleSharedTexture = 1,
|
||||
DxgiSharedTexture = 2,
|
||||
D3D9SharedTexture = 3
|
||||
}
|
||||
|
||||
internal readonly record struct OverlaySharedTextureDescriptor(
|
||||
IntPtr SharedHandle,
|
||||
long AdapterLuid,
|
||||
int Width,
|
||||
int Height,
|
||||
int PixelFormat,
|
||||
int RowPitch,
|
||||
int Usage);
|
||||
|
||||
internal sealed class OverlaySurfaceFrame
|
||||
{
|
||||
public OverlaySurfaceFrame(byte[] pixels, int width, int height)
|
||||
{
|
||||
Kind = OverlaySurfaceKind.SoftwareBgra32;
|
||||
SoftwarePixels = pixels;
|
||||
Width = width;
|
||||
Height = height;
|
||||
}
|
||||
|
||||
public OverlaySurfaceFrame(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor sharedTexture)
|
||||
{
|
||||
Kind = kind;
|
||||
SharedTexture = sharedTexture;
|
||||
Width = sharedTexture.Width;
|
||||
Height = sharedTexture.Height;
|
||||
}
|
||||
|
||||
public OverlaySurfaceKind Kind { get; }
|
||||
public byte[]? SoftwarePixels { get; }
|
||||
public OverlaySharedTextureDescriptor? SharedTexture { get; }
|
||||
public int Width { get; }
|
||||
public int Height { get; }
|
||||
}
|
||||
102
src/RynthCore.Engine/UI/Panels/HelloBoxPanel.cs
Normal file
102
src/RynthCore.Engine/UI/Panels/HelloBoxPanel.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Panels/HelloBoxPanel.cs
|
||||
// Shows live status from the HelloBox plugin. Resolves the plugin's
|
||||
// RynthPluginGetStatusText export via GetProcAddress on the module handle —
|
||||
// no changes to the plugin contract needed.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class HelloBoxPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetStatusTextFn();
|
||||
|
||||
private static GetStatusTextFn? _getStatusText;
|
||||
|
||||
internal static Control Create()
|
||||
{
|
||||
TryBindDelegate();
|
||||
|
||||
var textBlock = new TextBlock
|
||||
{
|
||||
FontFamily = new FontFamily("Consolas,Courier New,monospace"),
|
||||
FontSize = 10,
|
||||
Foreground = new SolidColorBrush(Color.FromArgb(200, 210, 210, 210)),
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
Margin = new Avalonia.Thickness(8, 6)
|
||||
};
|
||||
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
|
||||
Content = textBlock
|
||||
};
|
||||
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getStatusText == null)
|
||||
TryBindDelegate();
|
||||
|
||||
string text;
|
||||
if (_getStatusText != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getStatusText();
|
||||
text = Marshal.PtrToStringAnsi(ptr) ?? "(empty)";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
text = $"Error reading status: {ex.Message}";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(p => p.DisplayName.Contains("Hello"));
|
||||
text = plugin == null
|
||||
? "Hello Box plugin not loaded."
|
||||
: $"Hello Box loaded ({plugin.DisplayName}) but RynthPluginGetStatusText not found.";
|
||||
}
|
||||
|
||||
if (textBlock.Text != text)
|
||||
textBlock.Text = text;
|
||||
};
|
||||
scroll.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
timer.Start();
|
||||
|
||||
return scroll;
|
||||
}
|
||||
|
||||
private static void TryBindDelegate()
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(p => p.DisplayName.Contains("Hello"));
|
||||
if (plugin == null)
|
||||
return;
|
||||
|
||||
IntPtr fn = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetStatusText");
|
||||
if (fn == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (_getStatusText != null)
|
||||
return;
|
||||
|
||||
_getStatusText = Marshal.GetDelegateForFunctionPointer<GetStatusTextFn>(fn);
|
||||
RynthLog.UI($"HelloBoxPanel: bound RynthPluginGetStatusText for '{plugin.DisplayName}'.");
|
||||
}
|
||||
}
|
||||
91
src/RynthCore.Engine/UI/Panels/LogPanel.cs
Normal file
91
src/RynthCore.Engine/UI/Panels/LogPanel.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Panels/LogPanel.cs
|
||||
// Scrollable log viewer. Polls EntryPoint.GetRecentLogLines() every second.
|
||||
// Auto-scroll follows the tail; checkbox to pin scroll position.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class LogPanel
|
||||
{
|
||||
internal static Control Create()
|
||||
{
|
||||
var listBox = new ListBox
|
||||
{
|
||||
FontSize = 10,
|
||||
FontFamily = new FontFamily("Consolas,Courier New,monospace"),
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Avalonia.Thickness(0)
|
||||
};
|
||||
ScrollViewer.SetHorizontalScrollBarVisibility(listBox, ScrollBarVisibility.Disabled);
|
||||
|
||||
var autoScrollCheck = new CheckBox
|
||||
{
|
||||
Content = "Auto-scroll",
|
||||
IsChecked = true,
|
||||
Margin = new Avalonia.Thickness(4, 0, 0, 0)
|
||||
};
|
||||
|
||||
var clearButton = new Button
|
||||
{
|
||||
Content = "Clear",
|
||||
Margin = new Avalonia.Thickness(4, 0, 0, 0)
|
||||
};
|
||||
|
||||
string[]? _clearedSnapshot = null;
|
||||
clearButton.Click += (_, _) =>
|
||||
{
|
||||
_clearedSnapshot = EntryPoint.GetRecentLogLines();
|
||||
listBox.ItemsSource = Array.Empty<string>();
|
||||
};
|
||||
|
||||
var toolbar = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Children = { autoScrollCheck, clearButton }
|
||||
};
|
||||
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
|
||||
Content = listBox
|
||||
};
|
||||
|
||||
var root = new DockPanel();
|
||||
DockPanel.SetDock(toolbar, Dock.Bottom);
|
||||
root.Children.Add(toolbar);
|
||||
root.Children.Add(scroll);
|
||||
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
string[] lines = EntryPoint.GetRecentLogLines();
|
||||
|
||||
// If cleared, only show lines that arrived after the clear snapshot
|
||||
if (_clearedSnapshot != null)
|
||||
{
|
||||
int clearCount = _clearedSnapshot.Length;
|
||||
if (lines.Length > clearCount)
|
||||
lines = lines[clearCount..];
|
||||
else
|
||||
lines = Array.Empty<string>();
|
||||
}
|
||||
|
||||
listBox.ItemsSource = lines;
|
||||
|
||||
if (autoScrollCheck.IsChecked == true && lines.Length > 0)
|
||||
scroll.ScrollToEnd();
|
||||
};
|
||||
timer.Start();
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
1296
src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs
Normal file
1296
src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs
Normal file
File diff suppressed because it is too large
Load diff
101
src/RynthCore.Engine/UI/Panels/StatusPanel.cs
Normal file
101
src/RynthCore.Engine/UI/Panels/StatusPanel.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Panels/StatusPanel.cs
|
||||
// Shows engine build info, game HWND, and the loaded plugin list.
|
||||
// Refreshes on demand (Refresh button) — not polled continuously.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class StatusPanel
|
||||
{
|
||||
internal static Control Create()
|
||||
{
|
||||
var content = new StackPanel { Spacing = 4 };
|
||||
|
||||
var refreshButton = new Button { Content = "Refresh", HorizontalAlignment = HorizontalAlignment.Left };
|
||||
refreshButton.Click += (_, _) => Populate(content);
|
||||
|
||||
var root = new DockPanel { Margin = new Avalonia.Thickness(8) };
|
||||
DockPanel.SetDock(refreshButton, Dock.Bottom);
|
||||
root.Children.Add(refreshButton);
|
||||
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
Content = content
|
||||
};
|
||||
root.Children.Add(scroll);
|
||||
|
||||
Populate(content);
|
||||
return root;
|
||||
}
|
||||
|
||||
private static void Populate(StackPanel panel)
|
||||
{
|
||||
panel.Children.Clear();
|
||||
|
||||
AddHeader(panel, "Engine");
|
||||
AddRow(panel, "Build", EntryPoint.BuildStamp);
|
||||
AddRow(panel, "Game HWND", $"0x{EntryPoint.GameHwnd:X8}");
|
||||
AddRow(panel, "Plugin dir", PluginManager.PluginDirectory);
|
||||
|
||||
panel.Children.Add(new Border
|
||||
{
|
||||
Height = 1,
|
||||
Background = new SolidColorBrush(Color.FromArgb(60, 255, 255, 255)),
|
||||
Margin = new Avalonia.Thickness(0, 6, 0, 6)
|
||||
});
|
||||
|
||||
var plugins = PluginManager.Plugins;
|
||||
AddHeader(panel, $"Plugins ({plugins.Count})");
|
||||
|
||||
if (plugins.Count == 0)
|
||||
{
|
||||
AddRow(panel, "", "None loaded");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var p in plugins)
|
||||
{
|
||||
string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending";
|
||||
string version = p.VersionString.Length > 0 ? $" v{p.VersionString}" : "";
|
||||
AddRow(panel, p.DisplayName + version, state, p.Failed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddHeader(StackPanel panel, string text)
|
||||
{
|
||||
panel.Children.Add(new TextBlock
|
||||
{
|
||||
Text = text,
|
||||
FontSize = 11,
|
||||
FontWeight = FontWeight.Bold,
|
||||
Foreground = new SolidColorBrush(Color.FromArgb(200, 140, 200, 255)),
|
||||
Margin = new Avalonia.Thickness(0, 4, 0, 2)
|
||||
});
|
||||
}
|
||||
|
||||
private static void AddRow(StackPanel panel, string label, string value, bool error = false)
|
||||
{
|
||||
var color = error
|
||||
? Color.FromArgb(220, 255, 100, 100)
|
||||
: Color.FromArgb(200, 210, 210, 210);
|
||||
|
||||
string display = label.Length > 0 ? $"{label}: {value}" : value;
|
||||
|
||||
panel.Children.Add(new TextBlock
|
||||
{
|
||||
Text = display,
|
||||
FontSize = 11,
|
||||
Foreground = new SolidColorBrush(color),
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
});
|
||||
}
|
||||
}
|
||||
57
src/RynthCore.Engine/UI/SoftwareOverlaySurfaceBridge.cs
Normal file
57
src/RynthCore.Engine/UI/SoftwareOverlaySurfaceBridge.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal sealed class SoftwareOverlaySurfaceBridge : IOverlaySurfaceBridge
|
||||
{
|
||||
private sealed class PendingFrame
|
||||
{
|
||||
public PendingFrame(byte[] pixels, int width, int height)
|
||||
{
|
||||
Frame = new OverlaySurfaceFrame(pixels, width, height);
|
||||
}
|
||||
|
||||
public OverlaySurfaceFrame Frame { get; }
|
||||
}
|
||||
|
||||
private PendingFrame? _pending;
|
||||
|
||||
public string Name => "software-bgra32";
|
||||
public bool SupportsGpuInterop => false;
|
||||
public bool ShouldAttemptSharedTextures => false;
|
||||
|
||||
public void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
|
||||
{
|
||||
var buffer = new byte[byteCount];
|
||||
Marshal.Copy(pixelData, buffer, 0, byteCount);
|
||||
Interlocked.Exchange(ref _pending, new PendingFrame(buffer, width, height));
|
||||
}
|
||||
|
||||
public void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
RynthLog.UI($"SoftwareOverlaySurfaceBridge: Ignoring {kind} shared texture submission while software bridge is active.");
|
||||
}
|
||||
|
||||
public void NotifySharedTextureOpened(IntPtr sharedHandle)
|
||||
{
|
||||
}
|
||||
|
||||
public void NotifySharedTextureUnavailable()
|
||||
{
|
||||
}
|
||||
|
||||
public bool TryConsume(out OverlaySurfaceFrame? frame)
|
||||
{
|
||||
PendingFrame? pending = Interlocked.Exchange(ref _pending, null);
|
||||
if (pending == null)
|
||||
{
|
||||
frame = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
frame = pending.Frame;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue