RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -0,0 +1,36 @@
# Build-Loader.ps1
# Compiles the native RynthCore.Loader.dll (x86 MSVC) into native\Loader\bin.
# Does not deploy: copy it to Runtime\ yourself (a running client keeps the old loader
# until it restarts; the loader is injected once per process).
$ErrorActionPreference = "Stop"
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" `
-latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
-property installationPath 2>$null
if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 }
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
$src = $PSScriptRoot
$out = Join-Path $src "bin"
$obj = Join-Path $out "obj"
New-Item -ItemType Directory -Path $out, $obj -Force | Out-Null
Write-Host "Compiling RynthCore.Loader.dll (MSVC $vcVer, x86)..."
Push-Location $obj
try {
& $cl /nologo /O2 /MT /GS /W4 /wd4100 /LD /Zi "$src\Loader.c" "$src\Hooks.c" "$src\Clr.c" "$src\Services.c" user32.lib `
/link /MACHINE:X86 /DEF:"$src\Loader.def" /DEBUG /OPT:REF /OUT:"$out\RynthCore.Loader.dll" /PDB:"$out\RynthCore.Loader.pdb"
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
} finally { Pop-Location }
$size = (Get-Item "$out\RynthCore.Loader.dll").Length
Write-Host "Built: $out\RynthCore.Loader.dll ($size bytes)"

175
native/Loader/Clr.c Normal file
View file

@ -0,0 +1,175 @@
// ============================================================================
// Clr.c - hosts CoreCLR once, from the app-local runtime in Runtime\dotnet\, and
// talks to RynthCore.Shim.dll (default ALC), which owns the collectible
// AssemblyLoadContext each engine generation lives in.
//
// The raw coreclr_* API is used (no hostfxr, runtimeconfig.json or deps.json): the
// TPA list is every managed DLL in Runtime\dotnet\ plus the Shim. The engine and its
// own dependencies (Avalonia, ImGui.NET, ...) are NOT on the TPA list: the Shim loads
// them into the engine's collectible ALC, so they go away with it.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName,
int propertyCount, const char** propertyKeys, const char** propertyValues,
void** hostHandle, unsigned int* domainId);
typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId,
const char* assemblyName, const char* typeName, const char* methodName, void** fn);
// Shared with RynthCore.Shim (ShimHost.cs): keep the layouts in step.
typedef struct LoaderApi {
int size;
void (__stdcall *log)(const char* level, const char* utf8);
int (__stdcall *freeMb)(int* largestMb);
const char* loaderDir;
int (__stdcall *hookCount)(void);
} LoaderApi;
typedef struct ShimApi {
int size;
int (__stdcall *loadEngine)(int generation, const char* stagedPathUtf8);
int (__stdcall *unloadEngine)(void); // 1 = the ALC was freed
void* (__stdcall *engineExport)(const char* nameUtf8);
} ShimApi;
typedef int (__stdcall *shim_init_fn)(LoaderApi* api, ShimApi* out);
static LoaderApi g_loaderApi;
static ShimApi g_shim;
static int g_started;
int __stdcall RcHooks_Count(void);
static void __stdcall ShimLog(const char* level, const char* utf8) { LoaderLog(level ? level : "INF", "[shim] %s", utf8); }
static int __stdcall ShimFreeMb(int* largestMb)
{
long largest;
long free = LoaderFreeAddressSpaceMb(&largest);
if (largestMb) *largestMb = (int)largest;
return (int)free;
}
static int IsNativeRuntimeFile(const char* n)
{
static const char* natives[] = {
"coreclr.dll", "clrjit.dll", "clrgc.dll", "clrgcexp.dll", "hostfxr.dll", "hostpolicy.dll",
"mscordaccore.dll", "mscordbi.dll", "mscorrc.dll", "clretwrc.dll", "msquic.dll",
"System.IO.Compression.Native.dll", "Microsoft.DiaSymReader.Native.x86.dll",
};
for (int i = 0; i < (int)(sizeof natives / sizeof natives[0]); i++)
if (!_stricmp(n, natives[i])) return 1;
return !_strnicmp(n, "mscordaccore_", 13);
}
static int AppendDlls(char* tpa, size_t cap, const char* dir)
{
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir);
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA(pattern, &fd);
if (h == INVALID_HANDLE_VALUE) return 0;
int n = 0;
do {
if (IsNativeRuntimeFile(fd.cFileName)) continue;
strcat_s(tpa, cap, dir);
strcat_s(tpa, cap, "\\");
strcat_s(tpa, cap, fd.cFileName);
strcat_s(tpa, cap, ";");
n++;
} while (FindNextFileA(h, &fd));
FindClose(h);
return n;
}
int ClrStart(const char* loaderDir)
{
if (g_started) return 0;
char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH], shimPath[MAX_PATH];
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", loaderDir);
_snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir);
_snprintf_s(shimPath, sizeof shimPath, _TRUNCATE, "%s\\RynthCore.Shim.dll", loaderDir);
if (GetFileAttributesA(shimPath) == INVALID_FILE_ATTRIBUTES) {
LoaderLog("ERR", "CLR: %s is missing", shimPath);
return 1;
}
long free0 = LoaderFreeAddressSpaceMb(NULL);
DWORD t0 = GetTickCount();
HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!clr) {
LoaderLog("ERR", "CLR: LoadLibrary %s failed (error %lu)", coreclrPath, GetLastError());
return 2;
}
coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize");
coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate");
if (!init || !create) return 3;
static char tpa[128 * 1024];
tpa[0] = 0;
int count = AppendDlls(tpa, sizeof tpa, runtimeDir);
strcat_s(tpa, sizeof tpa, shimPath);
strcat_s(tpa, sizeof tpa, ";");
char nativeDirs[2 * MAX_PATH + 4], baseDir[MAX_PATH + 2];
_snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", loaderDir, runtimeDir);
_snprintf_s(baseDir, sizeof baseDir, _TRUNCATE, "%s\\", loaderDir);
const char* keys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "APP_CONTEXT_BASE_DIRECTORY",
"System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", "System.GC.RetainVM",
};
// Concurrent (background) GC on: the engine and the managed plugins share this one GC,
// and with it off every gen2 (~every 10 s, driven by large allocations) was a fully
// blocking 55-66 ms pause that AC's main thread hit whenever it was in managed code.
const char* values[] = {
tpa, "", nativeDirs, baseDir,
"false", "true", "true", "false",
};
char exePath[MAX_PATH];
GetModuleFileNameA(NULL, exePath, MAX_PATH);
void* hostHandle = NULL;
unsigned int domainId = 0;
int hr = init(exePath, "RynthCore", (int)(sizeof keys / sizeof keys[0]), keys, values, &hostHandle, &domainId);
if (hr < 0) {
LoaderLog("ERR", "CLR: coreclr_initialize failed 0x%08x", hr);
return 4;
}
shim_init_fn shimInit = NULL;
hr = create(hostHandle, domainId, "RynthCore.Shim", "RynthCore.Shim.ShimHost", "Init", (void**)&shimInit);
if (hr < 0 || !shimInit) {
LoaderLog("ERR", "CLR: RynthCore.Shim.ShimHost.Init not found (0x%08x)", hr);
return 5;
}
g_loaderApi.size = sizeof g_loaderApi;
g_loaderApi.log = ShimLog;
g_loaderApi.freeMb = ShimFreeMb;
g_loaderApi.loaderDir = LoaderDirectory();
g_loaderApi.hookCount = RcHooks_Count;
g_shim.size = sizeof g_shim;
int rc = shimInit(&g_loaderApi, &g_shim);
if (rc != 0 || !g_shim.loadEngine || !g_shim.unloadEngine || !g_shim.engineExport) {
LoaderLog("ERR", "CLR: Shim init failed (rc=%d)", rc);
return 6;
}
g_started = 1;
LoaderLog("INF", "CLR: CoreCLR up in %lu ms from %s (%d framework assemblies), %ld MB of address space used.",
GetTickCount() - t0, runtimeDir, count, free0 - LoaderFreeAddressSpaceMb(NULL));
return 0;
}
int ClrLoadEngine(int generation, const char* stagedPath)
{
return g_started ? g_shim.loadEngine(generation, stagedPath) : -1;
}
void ClrUnloadEngine(void)
{
if (g_started) g_shim.unloadEngine();
}
void* ClrEngineExport(const char* name)
{
return g_started ? g_shim.engineExport(name) : NULL;
}

332
native/Loader/Hooks.c Normal file
View file

@ -0,0 +1,332 @@
// ============================================================================
// Hooks.c - MinHook facade with permanent stubs
//
// Exports MinHook's API (MH_Initialize, MH_CreateHook, MH_EnableHook, ...) with the
// same signatures and status codes, so the engine's Hooking/MinHook.cs can call either
// this facade or minhook.x86.dll.
//
// The difference: nothing native ever points at engine code directly. For every target
// the facade allocates a permanent 6-byte stub, `jmp dword ptr [slot]`, and installs the
// real MinHook hook once, with the stub as the detour. The slot holds either the
// engine's detour (hook enabled) or MinHook's trampoline (hook disabled: a transparent
// pass-through to the original, whatever the calling convention). A reload only
// re-points slots, so an engine generation can be unloaded as soon as no thread is
// inside its code, and the next generation's MH_CreateHook for the same target reuses
// the same stub and gets the same trampoline back.
//
// Hooks are "owned" by the generation that created them: MH_CreateHook on a target
// created by an earlier generation succeeds (no MH_ERROR_ALREADY_CREATED), and
// HooksPassThroughAll() (every reload) turns every slot back into a pass-through and
// takes the patch out of the target (MinHook disable: original bytes back), so the next
// generation's pattern scans see AC's real prologues; its MH_CreateHook puts it back.
// The stub and trampoline are never freed, so a thread still returning through them is
// safe.
//
// Patching is batched. Every MinHook enable/disable freezes all the process's threads
// (a system-wide thread snapshot, ~100 ms here), and an engine installs ~60 hooks: one
// freeze each made up ~7 s of every reload. The facade records which targets should be
// patched and applies them in one queued MinHook freeze: straight after the engine's
// init export returns (HooksFlush; on a first launch AC's main thread is still suspended
// then), on every reload, and ~20 ms after the last change otherwise (a background
// flusher). A hook's slot is set at once; its patch follows within that window.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
#define MH_OK 0
#define MH_ERROR_ALREADY_INITIALIZED 1
#define MH_ERROR_NOT_INITIALIZED 2
#define MH_ERROR_ALREADY_CREATED 3
#define MH_ERROR_NOT_CREATED 4
#define MH_ERROR_ENABLED 5
#define MH_ERROR_DISABLED 6
#define MH_ERROR_MEMORY_ALLOC 9
#define MH_UNKNOWN -1
#define MAX_HOOKS 1024
#define STUB_SIZE 8
typedef int (__stdcall *mh_init_fn)(void);
typedef int (__stdcall *mh_create_fn)(void* target, void* detour, void** original);
typedef int (__stdcall *mh_target_fn)(void* target);
typedef const char* (__stdcall *mh_status_fn)(int status);
typedef struct HookEntry {
void* target;
void* trampoline; // MinHook's call-the-original trampoline (never freed)
void* detour; // the owning generation's detour, or NULL once removed
int generation; // generation that last created it
int created; // created (and not removed) by `generation`
int enabled; // slot == detour
int patched; // MinHook's jump is in the target
int want; // it should be (applied by the next flush)
} HookEntry;
static CRITICAL_SECTION g_lock;
static int g_ready;
static int g_generation;
static HMODULE g_minhook;
static mh_init_fn p_init;
static mh_create_fn p_create;
static mh_target_fn p_enable;
static mh_target_fn p_disable;
static mh_target_fn p_queueDisable;
static mh_target_fn p_queueEnable;
static mh_init_fn p_applyQueued;
static mh_status_fn p_status;
static HookEntry g_hooks[MAX_HOOKS];
static void* volatile g_slots[MAX_HOOKS];
static unsigned char* g_stubs;
static int g_count;
static HANDLE g_dirtyEvent;
static volatile DWORD g_lastChange;
static void FlushLocked(const char* why);
static DWORD WINAPI Flusher(LPVOID unused)
{
(void)unused;
for (;;) {
WaitForSingleObject(g_dirtyEvent, INFINITE);
do Sleep(20); while (GetTickCount() - g_lastChange < 20); // settle: one freeze per burst
EnterCriticalSection(&g_lock);
FlushLocked("batched");
LeaveCriticalSection(&g_lock);
}
}
int HooksInit(const char* loaderDir)
{
InitializeCriticalSection(&g_lock);
char path[MAX_PATH];
_snprintf_s(path, sizeof path, _TRUNCATE, "%s\\minhook.x86.dll", loaderDir);
g_minhook = LoadLibraryA(path);
if (!g_minhook) g_minhook = LoadLibraryA("minhook.x86.dll");
if (!g_minhook) return 0;
p_init = (mh_init_fn)GetProcAddress(g_minhook, "MH_Initialize");
p_create = (mh_create_fn)GetProcAddress(g_minhook, "MH_CreateHook");
p_enable = (mh_target_fn)GetProcAddress(g_minhook, "MH_EnableHook");
p_disable = (mh_target_fn)GetProcAddress(g_minhook, "MH_DisableHook");
p_queueDisable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueDisableHook");
p_queueEnable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueEnableHook");
p_applyQueued = (mh_init_fn)GetProcAddress(g_minhook, "MH_ApplyQueued");
p_status = (mh_status_fn)GetProcAddress(g_minhook, "MH_StatusToString");
if (!p_init || !p_create || !p_enable || !p_disable) return 0;
int st = p_init();
if (st != MH_OK && st != MH_ERROR_ALREADY_INITIALIZED) {
LoaderLog("ERR", "Hooks: MH_Initialize = %d", st);
return 0;
}
g_stubs = (unsigned char*)VirtualAlloc(NULL, MAX_HOOKS * STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!g_stubs) return 0;
g_dirtyEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
if (p_queueEnable && p_queueDisable && p_applyQueued && g_dirtyEvent) {
HANDLE t = CreateThread(NULL, 0, Flusher, NULL, 0, NULL);
if (t) CloseHandle(t);
}
g_ready = 1;
LoaderLog("INF", "Hooks: MinHook facade ready (%s, %d stub slots, %s patching).", path, MAX_HOOKS,
p_queueEnable ? "batched" : "per-hook");
return 1;
}
void HooksBeginGeneration(int generation)
{
EnterCriticalSection(&g_lock);
g_generation = generation;
LeaveCriticalSection(&g_lock);
}
static void SetPatched(int i, int patched)
{
HookEntry* e = &g_hooks[i];
if (e->patched == patched) return;
int st = patched ? p_enable(e->target) : p_disable(e->target);
if (st == MH_OK) e->patched = patched;
else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st);
}
// Records whether target i should be patched; the next flush applies it. (Caller holds g_lock.)
static void Want(int i, int patched)
{
HookEntry* e = &g_hooks[i];
e->want = patched;
if (e->want == e->patched) return;
if (!p_queueEnable || !p_queueDisable || !p_applyQueued || !g_dirtyEvent) {
SetPatched(i, patched); // no queue in this MinHook: one at a time
return;
}
g_lastChange = GetTickCount();
SetEvent(g_dirtyEvent);
}
// Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.)
static void FlushLocked(const char* why)
{
static int queued[MAX_HOOKS];
int n = 0;
for (int i = 0; i < g_count; i++) {
HookEntry* e = &g_hooks[i];
if (e->want == e->patched) continue;
int st = e->want ? p_queueEnable(e->target) : p_queueDisable(e->target);
if (st == MH_OK) queued[n++] = i;
else SetPatched(i, e->want);
}
if (n == 0) return;
DWORD t0 = GetTickCount();
int st = p_applyQueued();
if (st == MH_OK) {
for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want;
LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why);
} else {
LoaderLog("ERR", "Hooks: MH_ApplyQueued (%d, %s) = %d; applying one at a time.", n, why, st);
for (int k = 0; k < n; k++) SetPatched(queued[k], g_hooks[queued[k]].want);
}
}
void HooksFlush(void)
{
if (!g_ready) return;
EnterCriticalSection(&g_lock);
FlushLocked("engine init");
LeaveCriticalSection(&g_lock);
}
static void SetSlot(int i, int enabled)
{
HookEntry* e = &g_hooks[i];
e->enabled = enabled;
InterlockedExchangePointer((PVOID volatile*)&g_slots[i], enabled ? e->detour : e->trampoline);
}
void HooksPassThroughAll(void)
{
if (!g_ready) return;
EnterCriticalSection(&g_lock);
int live = 0;
for (int i = 0; i < g_count; i++) {
if (g_hooks[i].enabled) live++;
SetSlot(i, 0);
Want(i, 0);
g_hooks[i].created = 0;
g_hooks[i].detour = NULL;
}
FlushLocked("reload"); // AC's own prologues back, now
LeaveCriticalSection(&g_lock);
LoaderLog("INF", "Hooks: %d hook(s) now pass straight through (%d were still enabled).", g_count, live);
}
static int Find(void* target)
{
for (int i = 0; i < g_count; i++)
if (g_hooks[i].target == target) return i;
return -1;
}
// --- MinHook API ------------------------------------------------------------
int __stdcall MH_Initialize(void) { return g_ready ? MH_ERROR_ALREADY_INITIALIZED : MH_ERROR_NOT_INITIALIZED; }
// Hooks outlive every engine generation; "uninitialize" only turns them into pass-throughs.
int __stdcall MH_Uninitialize(void) { HooksPassThroughAll(); return MH_OK; }
int __stdcall MH_CreateHook(void* target, void* detour, void** original)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
int i = Find(target);
if (i >= 0) {
HookEntry* e = &g_hooks[i];
if (e->created && e->generation == g_generation) {
st = MH_ERROR_ALREADY_CREATED;
} else {
e->detour = detour;
e->generation = g_generation;
e->created = 1;
SetSlot(i, 0);
Want(i, 1);
if (original) *original = e->trampoline;
}
} else if (g_count >= MAX_HOOKS) {
st = MH_ERROR_MEMORY_ALLOC;
} else {
i = g_count;
unsigned char* stub = g_stubs + i * STUB_SIZE;
void* volatile* slot = &g_slots[i];
stub[0] = 0xFF; stub[1] = 0x25; // jmp dword ptr [slot]
*(void* volatile**)(stub + 2) = slot;
stub[6] = 0xCC; stub[7] = 0xCC;
FlushInstructionCache(GetCurrentProcess(), stub, STUB_SIZE);
void* tramp = NULL;
st = p_create(target, stub, &tramp);
if (st == MH_OK) {
HookEntry* e = &g_hooks[i];
e->target = target;
e->trampoline = tramp;
e->detour = detour;
e->generation = g_generation;
e->created = 1;
e->enabled = 0;
*slot = tramp; // pass-through until the engine enables it
g_count++;
e->patched = 0;
Want(i, 1); // the patch goes in (slot passes through)
st = MH_OK;
if (original) *original = tramp;
}
}
LeaveCriticalSection(&g_lock);
return st;
}
int __stdcall MH_RemoveHook(void* target)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
int i = Find(target);
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
else {
SetSlot(i, 0);
Want(i, 0); // original bytes back, like MinHook's remove
g_hooks[i].created = 0;
g_hooks[i].detour = NULL;
}
LeaveCriticalSection(&g_lock);
return st;
}
static int SetEnabled(void* target, int enable)
{
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
int st = MH_OK;
EnterCriticalSection(&g_lock);
if (target == NULL) { // MH_ALL_HOOKS
for (int i = 0; i < g_count; i++)
if (g_hooks[i].created && g_hooks[i].enabled != enable) SetSlot(i, enable);
} else {
int i = Find(target);
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
else if (g_hooks[i].enabled == enable) st = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED;
else SetSlot(i, enable);
}
LeaveCriticalSection(&g_lock);
return st;
}
int __stdcall MH_EnableHook(void* target) { return SetEnabled(target, 1); }
int __stdcall MH_DisableHook(void* target) { return SetEnabled(target, 0); }
const char* __stdcall MH_StatusToString(int status)
{
if (p_status) return p_status(status);
return status == MH_OK ? "MH_OK" : "MH_UNKNOWN";
}
// Lets the engine tell this facade from minhook.x86.dll (and an old NativeAOT loader).
int __stdcall RcHooks_Version(void) { return 1; }
int __stdcall RcHooks_Count(void) { return g_count; }

407
native/Loader/Loader.c Normal file
View file

@ -0,0 +1,407 @@
// ============================================================================
// RynthCore.Loader.dll - native loader (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 1)
//
// Injected into acclient.exe by RynthCore.Injector / the launcher, which call the
// RynthCoreInit export on a remote thread (same contract as the old NativeAOT loader).
//
// Two engine hosts, chosen by looking at Runtime\RynthCore.Engine.dll:
// - NativeAOT engine (a native DLL exporting RynthCoreEngineInit): staged to
// .engine_loads\, LoadLibrary'd, never freed. Today's behaviour.
// - Managed engine (a PE with a CLR header): the loader starts CoreCLR once from
// Runtime\dotnet\ and hands the engine to RynthCore.Shim.dll (default ALC), which
// loads each generation into a collectible AssemblyLoadContext and unloads it on
// reload, so a reload gives its memory back.
//
// Either way the loader owns the reload event, the file watcher, the address-space
// guard and a MinHook facade (Hooks.c): every hook is installed once, through a
// permanent stub, and a reload only re-points the stub.
// ============================================================================
#include "Loader.h"
#include <stdio.h>
#include <stdarg.h>
#define ENGINE_DLL_NAME "RynthCore.Engine.dll"
#define ENGINE_INIT_EXPORT "RynthCoreEngineInit"
#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown"
#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused"
#define LOG_DIR "C:\\Games\\RynthCore\\Logs"
#define STAGING_SUBDIR ".engine_loads"
#define MIN_RELOAD_INTERVAL_MS 1500
// A managed engine gives its memory back on reload, so the guard only has to keep
// room for one more generation; the NativeAOT engine leaks every generation.
#define MIN_FREE_MB_AOT 1200
#define MIN_FREE_MB_CLR 500
typedef unsigned int (__stdcall *engine_u32_fn)(void* param);
typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb);
static volatile LONG g_initialized;
static char g_loaderDir[MAX_PATH];
static char g_enginePath[MAX_PATH];
static int g_engineIsManaged;
static HMODULE g_engineModule; // NativeAOT host only
static int g_initCount;
static HANDLE g_reloadEvent;
static FILETIME g_canonicalWrite;
static volatile LONG g_reloadInFlight;
static volatile ULONGLONG g_lastReloadDone;
static CRITICAL_SECTION g_logLock;
// ---------------------------------------------------------------------------
// Logging: same per-client file and line format as the engine (LogPaths.cs).
// ---------------------------------------------------------------------------
void LoaderLog(const char* level, const char* fmt, ...)
{
char msg[3072];
va_list ap;
va_start(ap, fmt);
_vsnprintf_s(msg, sizeof msg, _TRUNCATE, fmt, ap);
va_end(ap);
SYSTEMTIME t;
GetLocalTime(&t);
char line[3300];
int n = _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] [%s] [loader] %s\r\n",
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), level, msg);
if (n < 0) n = (int)strlen(line);
char path[MAX_PATH];
_snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId());
EnterCriticalSection(&g_logLock);
CreateDirectoryA("C:\\Games\\RynthCore", NULL);
CreateDirectoryA(LOG_DIR, NULL);
for (int attempt = 0; attempt < 4; attempt++) {
HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h != INVALID_HANDLE_VALUE) {
DWORD written;
WriteFile(h, line, (DWORD)n, &written, NULL);
CloseHandle(h);
break;
}
Sleep(5);
}
LeaveCriticalSection(&g_logLock);
OutputDebugStringA(line);
}
// ---------------------------------------------------------------------------
// Address space
// ---------------------------------------------------------------------------
long LoaderFreeAddressSpaceMb(long* largestMb)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress;
unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress;
unsigned long long total = 0, largest = 0;
MEMORY_BASIC_INFORMATION mbi;
while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) {
if (mbi.RegionSize == 0) break;
if (mbi.State == MEM_FREE) {
total += mbi.RegionSize;
if (mbi.RegionSize > largest) largest = mbi.RegionSize;
}
p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize;
}
if (largestMb) *largestMb = (long)(largest / (1024 * 1024));
return (long)(total / (1024 * 1024));
}
// ---------------------------------------------------------------------------
// Engine file: staging and kind
// ---------------------------------------------------------------------------
static int FileLastWrite(const char* path, FILETIME* out)
{
WIN32_FILE_ATTRIBUTE_DATA d;
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &d)) return 0;
*out = d.ftLastWriteTime;
return 1;
}
// 1 = the file is a .NET assembly (PE with a CLR header), 0 = native, -1 = unreadable.
static int IsManagedPe(const char* path)
{
HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) return -1;
unsigned char buf[4096];
DWORD read = 0;
BOOL ok = ReadFile(h, buf, sizeof buf, &read, NULL);
CloseHandle(h);
if (!ok || read < sizeof(IMAGE_DOS_HEADER)) return -1;
IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)buf;
if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 ||
(DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32) > read) return -1;
IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(buf + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE) return -1;
if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0;
if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) return 0;
return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0;
}
static void CleanStaleStagingFiles(const char* stagingDir)
{
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb
WIN32_FIND_DATAA fd;
HANDLE f = FindFirstFileA(pattern, &fd);
if (f == INVALID_HANDLE_VALUE) return;
do {
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName);
DeleteFileA(p); // fails for files a live process still maps: fine
} while (FindNextFileA(f, &fd));
FindClose(f);
}
// Copies the canonical engine to .engine_loads\RynthCore.Engine.p<pid>.gen<N>.dll so the
// canonical file is never locked (a developer can copy over it) and every generation is
// a distinct module/assembly path.
static int StageEngine(int generation, char* stagedPath, size_t cap)
{
char stagingDir[MAX_PATH];
_snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir);
CreateDirectoryA(stagingDir, NULL);
CleanStaleStagingFiles(stagingDir);
_snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll",
stagingDir, GetCurrentProcessId(), generation);
if (!CopyFileA(g_enginePath, stagedPath, FALSE)) {
LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError());
return 0;
}
if (g_engineIsManaged) {
// The debug symbols travel with the assembly so stack traces keep line numbers.
char srcPdb[MAX_PATH], dstPdb[MAX_PATH];
_snprintf_s(srcPdb, sizeof srcPdb, _TRUNCATE, "%s\\RynthCore.Engine.pdb", g_loaderDir);
_snprintf_s(dstPdb, sizeof dstPdb, _TRUNCATE, "%.*s.pdb", (int)(strlen(stagedPath) - 4), stagedPath);
CopyFileA(srcPdb, dstPdb, FALSE);
}
LoaderLog("INF", "Staged engine for gen %d at %s", generation, stagedPath);
return 1;
}
// ---------------------------------------------------------------------------
// Engine calls, whichever host
// ---------------------------------------------------------------------------
static void* EngineExport(const char* name)
{
if (g_engineIsManaged) return ClrEngineExport(name);
return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL;
}
static unsigned int LoadAndInitEngine(void)
{
g_initCount++;
HooksBeginGeneration(g_initCount);
char staged[MAX_PATH];
if (!StageEngine(g_initCount, staged, sizeof staged)) return 11;
if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite);
if (g_engineIsManaged) {
int rc = ClrLoadEngine(g_initCount, staged);
if (rc != 0) {
LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc);
return 4;
}
} else {
HMODULE m = LoadLibraryA(staged);
if (!m) {
LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError());
return 4;
}
g_engineModule = m;
LoaderLog("INF", "Engine module loaded at 0x%08p from %s", (void*)m, staged);
}
engine_u32_fn init = (engine_u32_fn)EngineExport(ENGINE_INIT_EXPORT);
if (!init) {
LoaderLog("ERR", "Engine missing export '%s'", ENGINE_INIT_EXPORT);
return 5;
}
unsigned int rc = init((void*)(INT_PTR)g_initCount);
// The hooks the engine installed during init go in now, in one freeze, before the
// injector resumes AC's main thread (first launch) or the new generation runs.
HooksFlush();
LoaderLog("INF", ENGINE_INIT_EXPORT "(initCount=%d) returned %u.", g_initCount, rc);
return rc;
}
static void Reload(void)
{
long largest;
long freeBefore = LoaderFreeAddressSpaceMb(&largest);
LoaderLog("INF", "Reload requested (gen %d, %ld MB free, largest %ld MB).", g_initCount, freeBefore, largest);
engine_u32_fn shutdown = (engine_u32_fn)EngineExport(ENGINE_SHUTDOWN_EXPORT);
if (shutdown) {
unsigned int rc = shutdown(NULL);
LoaderLog("INF", ENGINE_SHUTDOWN_EXPORT " returned %u.", rc);
} else {
LoaderLog("WRN", "Engine has no '%s' export; skipping graceful shutdown.", ENGINE_SHUTDOWN_EXPORT);
}
// Whatever the engine left enabled now passes straight through to AC.
HooksPassThroughAll();
ServicesReleaseAll();
Sleep(150);
if (g_engineIsManaged) {
ClrUnloadEngine();
} else if (g_engineModule) {
// A NativeAOT module can't be freed (its runtime keeps threads with frames in it).
LoaderLog("INF", "Reload: NativeAOT engine 0x%08p left mapped (can't unload).", (void*)g_engineModule);
g_engineModule = NULL;
}
unsigned int rc = LoadAndInitEngine();
long freeAfter = LoaderFreeAddressSpaceMb(&largest);
LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).",
rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore);
}
// ---------------------------------------------------------------------------
// Reload triggers: the engine's named event, and the canonical DLL changing on disk
// ---------------------------------------------------------------------------
static DWORD WINAPI ReloadWatcher(LPVOID unused)
{
(void)unused;
for (;;) {
if (WaitForSingleObject(g_reloadEvent, INFINITE) != WAIT_OBJECT_0) { Sleep(100); continue; }
ULONGLONG last = g_lastReloadDone;
if (last != 0 && GetTickCount64() - last < MIN_RELOAD_INTERVAL_MS) {
LoaderLog("INF", "ReloadWatcher: signal %llu ms after the last reload; coalesced.", GetTickCount64() - last);
continue;
}
long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT;
long freeMb = LoaderFreeAddressSpaceMb(NULL);
if (freeMb < minFree) {
LoaderLog("WRN", "ReloadWatcher: reload REFUSED - only %ld MB of address space free (need %ld MB). "
"Restart the client to load the new engine.", freeMb, minFree);
engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT);
if (refused) refused((int)freeMb);
continue;
}
if (InterlockedCompareExchange(&g_reloadInFlight, 1, 0) != 0) {
LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced.");
continue;
}
Reload();
g_lastReloadDone = GetTickCount64();
InterlockedExchange(&g_reloadInFlight, 0);
int drained = 0;
while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++;
if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained);
}
}
static DWORD WINAPI FileWatcher(LPVOID unused)
{
(void)unused;
for (;;) {
Sleep(1000);
FILETIME now;
if (!FileLastWrite(g_enginePath, &now) || CompareFileTime(&now, &g_canonicalWrite) <= 0) continue;
// Let the writer (cp, dotnet publish) finish before staging from it.
Sleep(500);
FILETIME stable;
if (!FileLastWrite(g_enginePath, &stable) || CompareFileTime(&stable, &now) != 0) continue;
LoaderLog("INF", "FileWatcher: %s changed; signaling reload.", g_enginePath);
g_canonicalWrite = stable;
SetEvent(g_reloadEvent);
}
}
// ---------------------------------------------------------------------------
// Exports
// ---------------------------------------------------------------------------
const char* LoaderDirectory(void) { return g_loaderDir; }
int LoaderGeneration(void) { return g_initCount; }
unsigned int __stdcall RynthCoreInit(void* param)
{
(void)param;
if (InterlockedCompareExchange(&g_initialized, 1, 0) != 0) {
LoaderLog("WRN", "RynthCoreInit called twice; ignoring the second call.");
return 1;
}
HMODULE self = NULL;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)&RynthCoreInit, &self);
GetModuleFileNameA(self, g_loaderDir, MAX_PATH);
char* slash = strrchr(g_loaderDir, '\\');
if (slash) *slash = 0;
LoaderLog("INF", "RynthCoreInit (native loader %s) starting in %s.", LOADER_VERSION, g_loaderDir);
{
// Test clients (tools\TestClient, scripts\Test-Clr*.ps1) say so first, so monitors can skip them.
char tag[128];
if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", tag, sizeof tag) > 0)
LoaderLog("INF", "TestClient: %s", tag);
}
_snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, g_loaderDir);
int managed = IsManagedPe(g_enginePath);
if (managed < 0) {
LoaderLog("ERR", "FATAL: engine DLL not found or unreadable at %s", g_enginePath);
return 3;
}
g_engineIsManaged = managed;
long largest;
long freeMb = LoaderFreeAddressSpaceMb(&largest);
LoaderLog("INF", "Engine is %s; %ld MB of address space free (largest %ld MB).",
managed ? "a managed assembly: hosting CoreCLR" : "NativeAOT", freeMb, largest);
if (!HooksInit(g_loaderDir)) {
LoaderLog("ERR", "FATAL: MinHook could not be loaded from %s", g_loaderDir);
return 6;
}
if (managed) {
int rc = ClrStart(g_loaderDir);
if (rc != 0) {
LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc);
return 7;
}
}
unsigned int rc = LoadAndInitEngine();
if (rc != 0) return rc;
char eventName[128];
_snprintf_s(eventName, sizeof eventName, _TRUNCATE, "Local\\RynthCore.Engine.RequestReload.p%lu", GetCurrentProcessId());
g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, eventName);
if (!g_reloadEvent) {
LoaderLog("WRN", "CreateEvent failed (error %lu); reload disabled.", GetLastError());
return 0;
}
HANDLE t = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL);
if (t) CloseHandle(t);
t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL);
if (t) CloseHandle(t);
LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved)
{
(void)h; (void)reserved;
if (reason == DLL_PROCESS_ATTACH) {
InitializeCriticalSection(&g_logLock);
DisableThreadLibraryCalls(h);
}
return TRUE;
}

16
native/Loader/Loader.def Normal file
View file

@ -0,0 +1,16 @@
LIBRARY "RynthCore.Loader.dll"
EXPORTS
RynthCoreInit
MH_Initialize
MH_Uninitialize
MH_CreateHook
MH_RemoveHook
MH_EnableHook
MH_DisableHook
MH_StatusToString
RcHooks_Version
RcHooks_Count
RcSubclass_Install
RcSubclass_Release
RcApiStub
RcServices_Version

26
native/Loader/Loader.h Normal file
View file

@ -0,0 +1,26 @@
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define LOADER_VERSION "2.0"
// Loader.c
void LoaderLog(const char* level, const char* fmt, ...);
long LoaderFreeAddressSpaceMb(long* largestMb);
const char* LoaderDirectory(void);
int LoaderGeneration(void);
// Hooks.c: MinHook facade (see the header comment there)
int HooksInit(const char* loaderDir);
void HooksBeginGeneration(int generation);
void HooksPassThroughAll(void);
void HooksFlush(void);
// Services.c: permanent window subclass + plugin API stubs
void ServicesReleaseAll(void);
// Clr.c: CoreCLR host for a managed engine
int ClrStart(const char* loaderDir);
int ClrLoadEngine(int generation, const char* stagedPath);
void ClrUnloadEngine(void);
void* ClrEngineExport(const char* name);

176
native/Loader/Services.c Normal file
View file

@ -0,0 +1,176 @@
// ============================================================================
// Services.c - the other native entry points the engine hands out, made permanent
// (docs/UNLOADABLE_ENGINE_PLAN.md: "nothing native points into collectible code").
//
// 1. Window subclass: RcSubclass_Install puts the loader's own WndProc on a window,
// once for the life of the process, and forwards to the current engine's handler.
// RcSubclass_Release (and every reload) makes it a pure pass-through to the window's
// previous proc. The engine never has to unhook, so a foreign subclasser stacked on
// top of us (Decal, DirectInput) can never be ripped out of the chain, and nothing
// in the chain ever points at an unloaded engine.
//
// 2. Plugin API stubs: RcApiStub(index, fn) returns a permanent stub for table slot
// `index` that jumps to `fn`. Plugins copy the table and can't give it back; after a
// reload the slots are empty until the next engine fills them, and a plugin thread
// that calls one in between waits (any calling convention: registers and stack are
// untouched) and then runs the new engine's function.
// ============================================================================
#include "Loader.h"
// --- 1. window subclass --------------------------------------------------------
#define MAX_SUBCLASSED 16
typedef LRESULT (CALLBACK *wndproc_fn)(HWND, UINT, WPARAM, LPARAM);
typedef struct Subclass {
HWND hwnd;
WNDPROC previous; // the proc we replaced (AC's, or whoever was there)
wndproc_fn volatile handler; // current engine's handler, or NULL = pass-through
} Subclass;
static Subclass g_subclassed[MAX_SUBCLASSED];
static volatile LONG g_subclassCount;
static CRITICAL_SECTION g_servicesLock;
static int g_servicesReady;
static void EnsureServices(void)
{
if (!g_servicesReady) {
InitializeCriticalSection(&g_servicesLock);
g_servicesReady = 1;
}
}
static Subclass* FindSubclass(HWND hwnd)
{
LONG n = g_subclassCount;
for (LONG i = 0; i < n; i++)
if (g_subclassed[i].hwnd == hwnd) return &g_subclassed[i];
return NULL;
}
static LRESULT CALLBACK LoaderWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l)
{
Subclass* s = FindSubclass(hwnd);
if (!s) return DefWindowProcA(hwnd, msg, w, l);
wndproc_fn h = s->handler;
if (h) return h(hwnd, msg, w, l);
return CallWindowProcA(s->previous, hwnd, msg, w, l);
}
// Returns 1 and the window's previous proc (what the engine's handler must forward to).
int __stdcall RcSubclass_Install(HWND hwnd, void* handler, void** previousOut)
{
EnsureServices();
int ok = 1;
EnterCriticalSection(&g_servicesLock);
Subclass* s = FindSubclass(hwnd);
if (!s) {
if (g_subclassCount >= MAX_SUBCLASSED) ok = 0;
else {
s = &g_subclassed[g_subclassCount];
s->hwnd = hwnd;
s->handler = NULL;
SetLastError(0);
s->previous = (WNDPROC)SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)(LONG_PTR)LoaderWndProc);
if (!s->previous) {
LoaderLog("ERR", "Subclass: SetWindowLong on 0x%p failed (error %lu)", (void*)hwnd, GetLastError());
ok = 0;
} else {
InterlockedIncrement(&g_subclassCount);
LoaderLog("INF", "Subclass: 0x%p subclassed for good (previous proc 0x%p).", (void*)hwnd, (void*)s->previous);
}
}
}
if (ok) {
s->handler = (wndproc_fn)handler;
if (previousOut) *previousOut = (void*)s->previous;
}
LeaveCriticalSection(&g_servicesLock);
return ok;
}
int __stdcall RcSubclass_Release(HWND hwnd)
{
Subclass* s = FindSubclass(hwnd);
if (!s) return 0;
s->handler = NULL;
return 1;
}
// --- 2. plugin API stubs --------------------------------------------------------
#define MAX_API_STUBS 512
#define API_STUB_SIZE 32
static void* volatile g_apiSlots[MAX_API_STUBS];
static unsigned char* g_apiStubs;
static volatile LONG g_apiWaitLogged;
// Called from a stub whose slot is empty (between engine generations). Blocks until the
// next engine fills the table. stdcall, one argument; the stub saves every register.
static void __stdcall ApiWait(int index)
{
DWORD start = GetTickCount();
int logged = 0;
while (g_apiSlots[index] == NULL) {
Sleep(10);
if (!logged && GetTickCount() - start > 10000) {
logged = 1;
LoaderLog("WRN", "ApiStub: a plugin thread has waited 10 s for API slot %d (no engine loaded?).", index);
}
}
}
static void BuildApiStub(int i)
{
unsigned char* p = g_apiStubs + i * API_STUB_SIZE;
unsigned char* start = p;
void* volatile* slot = &g_apiSlots[i];
*p++ = 0xA1; *(void* volatile**)p = slot; p += 4; // mov eax, [slot]
*p++ = 0x85; *p++ = 0xC0; // test eax, eax
*p++ = 0x74; *p++ = 0x02; // jz +2 (wait)
*p++ = 0xFF; *p++ = 0xE0; // jmp eax
*p++ = 0x60; // pushad
*p++ = 0x68; *(int*)p = i; p += 4; // push i
*p++ = 0xE8; *(int*)p = (int)((unsigned char*)ApiWait - (p + 4)); p += 4; // call ApiWait
*p++ = 0x61; // popad
*p++ = 0xE9; *(int*)p = (int)(start - (p + 4)); p += 4; // jmp start
while (p < start + API_STUB_SIZE) *p++ = 0xCC;
}
void* __stdcall RcApiStub(int index, void* fn)
{
EnsureServices();
if (index < 0 || index >= MAX_API_STUBS) return fn;
EnterCriticalSection(&g_servicesLock);
if (!g_apiStubs) {
g_apiStubs = (unsigned char*)VirtualAlloc(NULL, MAX_API_STUBS * API_STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (g_apiStubs) {
for (int i = 0; i < MAX_API_STUBS; i++) BuildApiStub(i);
FlushInstructionCache(GetCurrentProcess(), g_apiStubs, MAX_API_STUBS * API_STUB_SIZE);
}
}
LeaveCriticalSection(&g_servicesLock);
if (!g_apiStubs) return fn;
// Already one of ours (a table wrapped twice): never point a slot at a stub.
if ((unsigned char*)fn >= g_apiStubs && (unsigned char*)fn < g_apiStubs + MAX_API_STUBS * API_STUB_SIZE)
return fn;
InterlockedExchangePointer((PVOID volatile*)&g_apiSlots[index], fn);
return g_apiStubs + index * API_STUB_SIZE;
}
// Every reload: nothing we hand out may keep pointing into the old engine.
void ServicesReleaseAll(void)
{
EnsureServices();
EnterCriticalSection(&g_servicesLock);
for (LONG i = 0; i < g_subclassCount; i++) g_subclassed[i].handler = NULL;
for (int i = 0; i < MAX_API_STUBS; i++) g_apiSlots[i] = NULL;
LeaveCriticalSection(&g_servicesLock);
LoaderLog("INF", "Services: %ld window subclass(es) pass through, plugin API slots emptied until the next engine.", g_subclassCount);
}
int __stdcall RcServices_Version(void) { return 1; }

2
native/cimgui/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
# Applied with git apply to an LF checkout: keep the bytes as committed.
*.patch -text

3
native/cimgui/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
_src/
_build/
_textedit/

View file

@ -0,0 +1,47 @@
# RynthCore cimgui build: upstream cimgui 1.91.6dock (fetched into _src by
# scripts/Build-Cimgui.ps1) plus rynth_imconfig.h and rynth_cimgui_ext.cpp,
# and ImGuiColorTextEdit (fetched into _textedit, patched by
# textedit-rynth.patch) with its C exports in rynth_textedit_ext.cpp.
# Output: a 32-bit cimgui.dll whose structs match ImGui.NET 1.91.6.1.
cmake_minimum_required(VERSION 3.15)
cmake_policy(SET CMP0091 NEW)
project(rynth_cimgui CXX)
set(CMAKE_CXX_STANDARD 17)
# Static CRT, like the stock ImGui.NET native build: no VC++ redistributable needed.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set(SRC ${CMAKE_CURRENT_SOURCE_DIR}/_src)
set(TEXTEDIT ${CMAKE_CURRENT_SOURCE_DIR}/_textedit)
add_library(cimgui SHARED
${SRC}/cimgui.cpp
${SRC}/imgui/imgui.cpp
${SRC}/imgui/imgui_draw.cpp
${SRC}/imgui/imgui_demo.cpp
${SRC}/imgui/imgui_tables.cpp
${SRC}/imgui/imgui_widgets.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rynth_cimgui_ext.cpp
${TEXTEDIT}/TextEditor.cpp
${TEXTEDIT}/LanguageDefinitions.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rynth_textedit_ext.cpp
)
# Same defines as upstream cimgui's CMakeLists, except the user config.
target_compile_definitions(cimgui PRIVATE
IMGUI_USER_CONFIG=\"rynth_imconfig.h\"
IMGUI_DISABLE_OBSOLETE_FUNCTIONS=1
"IMGUI_IMPL_API=extern \"C\" __declspec(dllexport)"
)
target_include_directories(cimgui PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${SRC}
${SRC}/imgui
${TEXTEDIT}
${CMAKE_CURRENT_SOURCE_DIR}/textedit_shim
)
# ImGuiColorTextEdit uses std::string/printf-style code MSVC warns about.
set_source_files_properties(${TEXTEDIT}/TextEditor.cpp ${TEXTEDIT}/LanguageDefinitions.cpp
PROPERTIES COMPILE_OPTIONS "/wd4244;/wd4267;/wd4018;/wd4305")
set_target_properties(cimgui PROPERTIES PREFIX "")
target_link_libraries(cimgui imm32)

View file

@ -0,0 +1,118 @@
// ============================================================================
// RynthCore cimgui build - extra exports compiled into cimgui.dll.
//
// RynthImGui_BuildTag identifies this build (the engine refuses others).
// RynthImGui_GetLayout sizes/offsets/enum counts the engine compares
// against ImGui.NET's structs before creating a
// context (see ImGuiSelfTest.cs; same index order).
// RynthImGui_ReportAssert IM_ASSERT target (rynth_imconfig.h); records into
// a ring buffer the engine polls from AC's thread.
// ============================================================================
#include "imgui.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#define RYNTH_EXPORT extern "C" __declspec(dllexport)
// ---- Build tag -------------------------------------------------------------
// Bump the trailing number whenever the layout table or config changes.
RYNTH_EXPORT const char* RynthImGui_BuildTag(void)
{
return "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4";
}
// ---- Layout table ------------------------------------------------------------
// Index order is a contract with ImGuiSelfTest.ExpectedLayout(); append only.
RYNTH_EXPORT int RynthImGui_GetLayout(int* out, int capacity)
{
const int values[] =
{
1, // 0 table version
(int)sizeof(ImTextureID), // 1
(int)sizeof(ImWchar), // 2
(int)sizeof(ImDrawIdx), // 3
(int)sizeof(ImDrawVert), // 4
(int)sizeof(ImDrawCmd), // 5
(int)offsetof(ImDrawCmd, TextureId), // 6
(int)offsetof(ImDrawCmd, VtxOffset), // 7
(int)offsetof(ImDrawCmd, IdxOffset), // 8
(int)offsetof(ImDrawCmd, ElemCount), // 9
(int)offsetof(ImDrawCmd, UserCallback), // 10
(int)sizeof(ImDrawList), // 11
(int)offsetof(ImDrawList, VtxBuffer), // 12
(int)sizeof(ImDrawData), // 13
(int)offsetof(ImDrawData, CmdLists), // 14
(int)offsetof(ImDrawData, DisplayPos), // 15
(int)offsetof(ImDrawData, DisplaySize), // 16
(int)sizeof(ImFontAtlas), // 17
(int)offsetof(ImFontAtlas, TexID), // 18
(int)sizeof(ImFont), // 19
(int)sizeof(ImFontGlyph), // 20
(int)sizeof(ImFontConfig), // 21
(int)sizeof(ImGuiIO), // 22
(int)offsetof(ImGuiIO, Fonts), // 23
(int)offsetof(ImGuiIO, WantCaptureMouse), // 24
(int)offsetof(ImGuiIO, WantTextInput), // 25
(int)sizeof(ImGuiStyle), // 26
(int)sizeof(ImGuiViewport), // 27
(int)sizeof(ImGuiPlatformIO), // 28
(int)sizeof(ImGuiInputTextCallbackData), // 29
(int)sizeof(ImGuiListClipper), // 30
(int)sizeof(ImGuiPayload), // 31
(int)sizeof(ImGuiTableSortSpecs), // 32
(int)sizeof(ImGuiTableColumnSortSpecs), // 33
(int)sizeof(ImGuiStorage), // 34
(int)sizeof(ImGuiWindowClass), // 35
(int)sizeof(ImGuiSizeCallbackData), // 36
(int)ImGuiCol_COUNT, // 37
(int)ImGuiKey_NamedKey_END, // 38
(int)ImGuiStyleVar_COUNT, // 39
(int)ImGuiMouseCursor_COUNT, // 40
};
const int count = (int)(sizeof(values) / sizeof(values[0]));
if (out != NULL)
for (int i = 0; i < count && i < capacity; i++)
out[i] = values[i];
return count;
}
// ---- Soft asserts ------------------------------------------------------------
// ImGui runs on one thread (AC's render thread); the engine polls on the same
// thread, so plain statics are enough. The ring keeps the last 16 failures.
static const int kAssertSlots = 16;
static const int kAssertTextLen = 256;
static int g_assertCount;
static char g_assertText[kAssertSlots][kAssertTextLen];
extern "C" void RynthImGui_ReportAssert(const char* expr, const char* file, int line)
{
const char* base = file;
for (const char* p = file; *p; p++)
if (*p == '\\' || *p == '/')
base = p + 1;
char* slot = g_assertText[g_assertCount % kAssertSlots];
_snprintf_s(slot, kAssertTextLen, _TRUNCATE, "%s:%d: %s", base, line, expr);
g_assertCount++;
}
// Total failures since load (monotonic; wraps only after 2^31).
RYNTH_EXPORT int RynthImGui_GetAssertCount(void)
{
return g_assertCount;
}
// Copies failure number `index` (0-based, < count) into buf. Returns the
// length copied, or -1 when that entry was already overwritten or not yet made.
RYNTH_EXPORT int RynthImGui_GetAssertText(int index, char* buf, int capacity)
{
if (buf == NULL || capacity <= 0 || index < 0 || index >= g_assertCount || index < g_assertCount - kAssertSlots)
return -1;
const char* src = g_assertText[index % kAssertSlots];
int len = (int)strnlen(src, kAssertTextLen);
if (len >= capacity) len = capacity - 1;
memcpy(buf, src, (size_t)len);
buf[len] = '\0';
return len;
}

View file

@ -0,0 +1,26 @@
// ============================================================================
// RynthCore cimgui build - Dear ImGui user config (IMGUI_USER_CONFIG).
// Replaces upstream cimgui's cimconfig.h (which only did #undef NDEBUG).
// ============================================================================
#pragma once
// ImGui.NET 1.91.6.1 declares ImTextureID as IntPtr (pointer-sized). Dear ImGui
// 1.91.4+ defaults it to ImU64, which on x86 makes ImDrawCmd, ImDrawList and
// ImFontAtlas wider than ImGui.NET's structs and shifts every by-value texture
// argument (SetTexID, Image, AddImage, ...). This is why the stock NuGet x86
// cimgui.dll does not match its own wrapper. A named typedef (not a bare
// "void*" macro) keeps functional casts like ImTextureID() valid.
typedef void* RynthImTextureID;
#define ImTextureID RynthImTextureID
// Soft asserts. A failed IM_ASSERT is recorded in a small native ring buffer
// (rynth_cimgui_ext.cpp) that the engine polls and logs; control flow then
// continues exactly as in a release build with asserts compiled out. The
// handler never calls into managed code (a managed exception inside a native
// frame fail-fasts the process).
#ifdef __cplusplus
extern "C"
#endif
void RynthImGui_ReportAssert(const char* expr, const char* file, int line);
#define IM_ASSERT(_EXPR) do { if (!(_EXPR)) RynthImGui_ReportAssert(#_EXPR, __FILE__, __LINE__); } while (0)

View file

@ -0,0 +1,308 @@
// ============================================================================
// RynthCore cimgui build - C exports for ImGuiColorTextEdit (santaclose fork,
// fetched into _textedit and patched by textedit-rynth.patch).
//
// The engine P/Invokes these by hand (ImGui/TextEditorNative.cs). Every call
// is made on AC's render thread inside an ImGui frame (Create reads the style,
// so it needs a current context too). Strings are UTF-8; returned pointers
// stay valid until the next call of the same export.
//
// Languages: 1 = Meta (.af source: coloured by the tokenizer below from the
// vocabulary the engine passes in), 2 = Lua (the fork's own definition).
// ============================================================================
#include <algorithm>
#include <string>
#include <unordered_set>
#include "TextEditor.h"
#define RYNTH_EXPORT extern "C" __declspec(dllexport)
struct RynthTextEditAccess
{
typedef TextEditor::PaletteIndex PI;
static std::unordered_set<std::string>& StructWords() { static std::unordered_set<std::string> s; return s; }
static std::unordered_set<std::string>& ConditionWords() { static std::unordered_set<std::string> s; return s; }
static std::unordered_set<std::string>& ActionWords() { static std::unordered_set<std::string> s; return s; }
static bool IsWordStart(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; }
static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
static bool IsWordChar(char c) { return IsWordStart(c) || IsDigit(c); }
// Mirrors MetaSourceEditor.MetaColorizer: "~~" comments to the end of the
// line, braces, numbers (hex and signed too), STATE:/IF:/DO:/NAV: (the
// colon included), condition keywords, action keywords.
static bool TokenizeMeta(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PI& color)
{
while (in_begin < in_end && (*in_begin == ' ' || *in_begin == '\t'))
in_begin++;
if (in_begin == in_end)
{
out_begin = out_end = in_end;
color = PI::Default;
return true;
}
const char* p = in_begin;
out_begin = p;
char c = *p;
if (c == '~' && p + 1 < in_end && p[1] == '~')
{
out_end = in_end;
color = PI::Comment;
return true;
}
if (c == '{' || c == '}')
{
out_end = p + 1;
color = PI::Punctuation;
return true;
}
if (IsDigit(c) || (c == '-' && p + 1 < in_end && IsDigit(p[1])))
{
p++;
while (p < in_end && (IsWordChar(*p) || *p == '.'))
p++;
out_end = p;
color = PI::Number;
return true;
}
if (IsWordStart(c))
{
p++;
while (p < in_end && IsWordChar(*p))
p++;
std::string word(in_begin, p);
std::transform(word.begin(), word.end(), word.begin(), [](char ch) { return (char)::toupper((unsigned char)ch); });
color = PI::Default;
if (p < in_end && *p == ':' && StructWords().count(word) != 0)
{
p++;
color = PI::Keyword;
}
else if (ConditionWords().count(word) != 0)
color = PI::KnownIdentifier;
else if (ActionWords().count(word) != 0)
color = PI::PreprocIdentifier;
out_end = p;
return true;
}
// Anything else (punctuation, UTF-8 bytes): one byte, default colour.
out_end = p + 1;
color = PI::Default;
return true;
}
static const TextEditor::LanguageDefinition& MetaLanguage()
{
static TextEditor::LanguageDefinition def;
static bool built = false;
if (!built)
{
built = true;
def.mName = "Meta";
def.mTokenize = &TokenizeMeta;
def.mSingleLineComment = "~~"; // Ctrl+/ toggles "~~"
// An empty block-comment start matches everywhere in ColorizeInternal,
// so give it one that never occurs in text.
def.mCommentStart = "\x01\x02";
def.mCommentEnd = "\x02\x01";
def.mPreprocChar = '\x01';
def.mCaseSensitive = false;
def.mTokenizerOwnsComments = true; // TokenizeMeta colours "~~" itself
}
return def;
}
static void SetLanguage(TextEditor* ed, int language)
{
if (language == 1)
{
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None);
ed->mLanguageDefinition = &MetaLanguage();
ed->Colorize();
}
else if (language == 2)
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::Lua);
else
ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None);
}
static void SetPalette(TextEditor* ed, const ImU32* colors, int count)
{
int n = std::min(count, (int)PI::Max);
for (int i = 0; i < n; i++)
ed->mPalette[i] = colors[i];
}
static void CursorScreenPos(TextEditor* ed, float* x, float* y)
{
TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates();
*x = ed->mTextOrigin.x + ed->mTextStart + ed->TextDistanceToLineStart(at);
*y = ed->mTextOrigin.y + (at.mLine + 1) * ed->mCharAdvance.y;
}
static std::string LinePrefix(TextEditor* ed)
{
TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates();
return ed->GetText(TextEditor::Coordinates(at.mLine, 0), at);
}
// Completion: replace the `bytes` characters before the cursor with `text`,
// as one undo step.
static void ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* text)
{
if (ed->mReadOnly)
return;
ed->ClearExtraCursors();
ed->ClearSelections();
TextEditor::Coordinates end = ed->GetSanitizedCursorCoordinates();
int endIndex = ed->GetCharacterIndexR(end);
int startIndex = std::max(0, endIndex - std::max(0, bytes));
TextEditor::Coordinates start(end.mLine, ed->GetCharacterColumn(end.mLine, startIndex));
TextEditor::UndoRecord u;
u.mBefore = ed->mState;
if (start < end)
{
ed->SetSelection(start, end);
u.mOperations.push_back({ ed->GetSelectedText(), start, end, TextEditor::UndoOperationType::Delete });
ed->DeleteSelection();
}
TextEditor::Coordinates insertAt = ed->GetSanitizedCursorCoordinates();
ed->InsertTextAtCursor(text);
u.mOperations.push_back({ std::string(text), insertAt, ed->GetSanitizedCursorCoordinates(), TextEditor::UndoOperationType::Add });
u.mAfter = ed->mState;
ed->AddUndo(u);
}
};
static void FillWordSet(std::unordered_set<std::string>& set, const char* words)
{
set.clear();
if (words == nullptr)
return;
std::string current;
for (const char* p = words;; p++)
{
if (*p == '\n' || *p == '\0')
{
if (!current.empty())
set.insert(current);
current.clear();
if (*p == '\0')
break;
}
else
current.push_back((char)::toupper((unsigned char)*p));
}
}
RYNTH_EXPORT TextEditor* RynthTE_Create(void)
{
TextEditor* ed = new TextEditor();
ed->SetShowWhitespacesEnabled(false);
return ed;
}
RYNTH_EXPORT void RynthTE_Destroy(TextEditor* ed)
{
delete ed;
}
/// Newline-separated words, matched case-insensitively. Applies to every Meta editor.
RYNTH_EXPORT void RynthTE_SetMetaVocabulary(const char* structWords, const char* conditionWords, const char* actionWords)
{
FillWordSet(RynthTextEditAccess::StructWords(), structWords);
FillWordSet(RynthTextEditAccess::ConditionWords(), conditionWords);
FillWordSet(RynthTextEditAccess::ActionWords(), actionWords);
}
RYNTH_EXPORT void RynthTE_SetLanguage(TextEditor* ed, int language)
{
RynthTextEditAccess::SetLanguage(ed, language);
}
/// `count` ImU32 colours in TextEditor::PaletteIndex order.
RYNTH_EXPORT void RynthTE_SetPalette(TextEditor* ed, const ImU32* colors, int count)
{
RynthTextEditAccess::SetPalette(ed, colors, count);
}
RYNTH_EXPORT void RynthTE_SetOptions(TextEditor* ed, int readOnly, int showWhitespaces, int showLineNumbers, int tabSize)
{
ed->SetReadOnlyEnabled(readOnly != 0);
ed->SetShowWhitespacesEnabled(showWhitespaces != 0);
ed->SetShowLineNumbersEnabled(showLineNumbers != 0);
ed->SetTabSize(tabSize);
}
RYNTH_EXPORT void RynthTE_SetText(TextEditor* ed, const char* utf8)
{
ed->SetText(utf8 != nullptr ? std::string(utf8) : std::string());
}
RYNTH_EXPORT const char* RynthTE_GetText(TextEditor* ed, int* length)
{
static std::string text;
text = ed->GetText();
if (length != nullptr)
*length = (int)text.size();
return text.c_str();
}
RYNTH_EXPORT unsigned RynthTE_GetChangeCount(TextEditor* ed)
{
return ed->GetChangeCount();
}
/// Draws the editor as a child window; returns whether it has keyboard focus.
RYNTH_EXPORT int RynthTE_Render(TextEditor* ed, const char* id, float width, float height, int border)
{
return ed->Render(id, false, ImVec2(width, height), border != 0) ? 1 : 0;
}
RYNTH_EXPORT void RynthTE_GetCursor(TextEditor* ed, int* line, int* column)
{
ed->GetCursorPosition(*line, *column);
}
RYNTH_EXPORT void RynthTE_SetCursor(TextEditor* ed, int line, int charIndex)
{
ed->SetCursorPosition(line, charIndex);
}
/// Screen position of the bottom-left corner of the cursor's cell (valid after Render).
RYNTH_EXPORT void RynthTE_GetCursorScreenPos(TextEditor* ed, float* x, float* y)
{
RynthTextEditAccess::CursorScreenPos(ed, x, y);
}
/// The cursor's line up to the cursor.
RYNTH_EXPORT const char* RynthTE_GetLinePrefix(TextEditor* ed, int* length)
{
static std::string prefix;
prefix = RynthTextEditAccess::LinePrefix(ed);
if (length != nullptr)
*length = (int)prefix.size();
return prefix.c_str();
}
RYNTH_EXPORT void RynthTE_ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* utf8)
{
RynthTextEditAccess::ReplaceBeforeCursor(ed, bytes, utf8 != nullptr ? utf8 : "");
}
/// While set, the editor ignores Up/Down/PageUp/PageDown/Enter/Tab/Escape (the host's completion list uses them).
RYNTH_EXPORT void RynthTE_SetCompletionKeysHeld(TextEditor* ed, int held)
{
ed->SetCompletionKeysHeld(held != 0);
}
RYNTH_EXPORT void RynthTE_RequestFocus(TextEditor* ed)
{
ed->RequestFocus();
}

View file

@ -0,0 +1,129 @@
diff --git a/TextEditor.cpp b/TextEditor.cpp
index 013111f..9cd55a1 100644
--- a/TextEditor.cpp
+++ b/TextEditor.cpp
@@ -325,13 +325,19 @@ void TextEditor::Paste()
void TextEditor::Undo(int aSteps)
{
while (CanUndo() && aSteps-- > 0)
+ {
mUndoBuffer[--mUndoIndex].Undo(this);
+ ++mChangeCount;
+ }
}
void TextEditor::Redo(int aSteps)
{
while (CanRedo() && aSteps-- > 0)
+ {
mUndoBuffer[mUndoIndex++].Redo(this);
+ ++mChangeCount;
+ }
}
void TextEditor::SetText(const std::string& aText)
@@ -355,6 +361,7 @@ void TextEditor::SetText(const std::string& aText)
mUndoBuffer.clear();
mUndoIndex = 0;
+ ++mChangeCount;
Colorize();
}
@@ -392,6 +399,7 @@ void TextEditor::SetTextLines(const std::vector<std::string>& aLines)
mUndoBuffer.clear();
mUndoIndex = 0;
+ ++mChangeCount;
Colorize();
}
@@ -428,6 +436,11 @@ bool TextEditor::Render(const char* aTitle, bool aParentIsFocused, const ImVec2&
ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavInputs);
+ if (mFocusRequested)
+ {
+ ImGui::SetWindowFocus();
+ mFocusRequested = false;
+ }
bool isFocused = ImGui::IsWindowFocused();
HandleKeyboardInputs(aParentIsFocused);
HandleMouseInputs();
@@ -1993,7 +2006,12 @@ void TextEditor::HandleKeyboardInputs(bool aParentIsFocused)
io.WantCaptureKeyboard = true;
io.WantTextInput = true;
- if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z))
+ if (mCompletionKeysHeld && (ImGui::IsKeyPressed(ImGuiKey_UpArrow) || ImGui::IsKeyPressed(ImGuiKey_DownArrow) ||
+ ImGui::IsKeyPressed(ImGuiKey_PageUp) || ImGui::IsKeyPressed(ImGuiKey_PageDown) ||
+ ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter) ||
+ ImGui::IsKeyPressed(ImGuiKey_Tab) || ImGui::IsKeyPressed(ImGuiKey_Escape)))
+ ; // the host's completion list owns these keys
+ else if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z))
Undo();
else if (!mReadOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_Backspace))
Undo();
@@ -2238,6 +2256,7 @@ void TextEditor::Render(bool aParentIsFocused)
}
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
+ mTextOrigin = cursorScreenPos;
mScrollX = ImGui::GetScrollX();
mScrollY = ImGui::GetScrollY();
UpdateViewVariables(mScrollX, mScrollY);
@@ -2549,6 +2568,7 @@ void TextEditor::AddUndo(UndoRecord& aValue)
mUndoBuffer.resize((size_t)(mUndoIndex + 1));
mUndoBuffer.back() = aValue;
++mUndoIndex;
+ ++mChangeCount;
}
// TODO
@@ -2687,6 +2707,8 @@ void TextEditor::ColorizeInternal()
if (mLines.empty() || mLanguageDefinition == nullptr)
return;
+ if (mCheckComments && mLanguageDefinition->mTokenizerOwnsComments)
+ mCheckComments = false;
if (mCheckComments)
{
auto endLine = mLines.size();
diff --git a/TextEditor.h b/TextEditor.h
index 19ad61b..6883412 100644
--- a/TextEditor.h
+++ b/TextEditor.h
@@ -97,6 +97,14 @@ public:
void ImGuiDebugPanel(const std::string& panelName = "Debug");
void UnitTests();
+ // RynthCore (native/cimgui/textedit-rynth.patch): a text change counter, a
+ // hold-off on the keys the host's completion list uses, a focus request,
+ // and access for the C exports in rynth_textedit_ext.cpp.
+ inline unsigned GetChangeCount() const { return mChangeCount; }
+ inline void SetCompletionKeysHeld(bool aValue) { mCompletionKeysHeld = aValue; }
+ inline void RequestFocus() { mFocusRequested = true; }
+ friend struct RynthTextEditAccess;
+
private:
// ------------- Generic utils ------------- //
@@ -280,6 +288,7 @@ private:
TokenizeCallback mTokenize = nullptr;
std::vector<TokenRegexString> mTokenRegexStrings;
bool mCaseSensitive = true;
+ bool mTokenizerOwnsComments = false; // RynthCore: skip the whole-text comment scan
static const LanguageDefinition& Cpp();
static const LanguageDefinition& Hlsl();
@@ -452,6 +461,10 @@ private:
Palette mPalette;
LanguageDefinitionId mLanguageDefinitionId;
const LanguageDefinition* mLanguageDefinition = nullptr;
+ unsigned mChangeCount = 0;
+ bool mCompletionKeysHeld = false;
+ bool mFocusRequested = false;
+ ImVec2 mTextOrigin;
inline bool IsHorizontalScrollbarVisible() const { return mCurrentSpaceWidth > mContentWidth; }
inline bool IsVerticalScrollbarVisible() const { return mCurrentSpaceHeight > mContentHeight; }

View file

@ -0,0 +1,13 @@
// RynthCore: ImGuiColorTextEdit (santaclose fork) includes <boost/regex.hpp>.
// Its regex path only runs for languages without a hand-written tokenizer, and
// the two we use (Meta, Lua) both have one, so std::regex stands in for Boost.
#pragma once
#include <regex>
namespace boost
{
using std::regex;
using std::cmatch;
using std::regex_search;
namespace regex_constants = std::regex_constants;
}