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);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue