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:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
394
src/RynthCore.DecalBridge/BridgeFilter.cs
Normal file
394
src/RynthCore.DecalBridge/BridgeFilter.cs
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
// ============================================================================
|
||||
// RynthCore.DecalBridge - BridgeFilter.cs
|
||||
//
|
||||
// A Decal network filter written only against Decal's PUBLIC plugin API
|
||||
// (Decal.Adapter: FilterBase, CoreManager, WorldFilter, CharacterFilter, HooksWrapper).
|
||||
// It lets the RynthCore engine run in the same acclient.exe as Decal without the two
|
||||
// patching the same AC functions ("bridge mode", docs/DECAL_BRIDGE_PLAN.md):
|
||||
//
|
||||
// events -> engine: chat lines, chat-bar commands (and eats the engine's own
|
||||
// commands), login/logoff; optionally object create/release/change and
|
||||
// raw server messages. The engine says which kinds it wants (want mask).
|
||||
// commands <- engine: run on AC's main thread through Decal's public API - chat lines
|
||||
// (InvokeChatParser) and the salvage panel (SalvagePanelAdd/Salvage).
|
||||
//
|
||||
// A network filter (not a plugin) so it starts with Decal, before login.
|
||||
//
|
||||
// Idle unless RynthCore is in the same client: registering it (the launcher does, for
|
||||
// "Decal + RynthCore" accounts) makes every Decal client of that Windows user load it,
|
||||
// but until the RynthCore loader shows up in the process it only counts frames. It never
|
||||
// blocks, never throws into Decal, and holds nothing of the engine's.
|
||||
// RYNTHCORE_DECAL_BRIDGE=0 in a client's environment keeps it off entirely.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Decal.Adapter;
|
||||
using Decal.Adapter.Wrappers;
|
||||
|
||||
namespace RynthCore.DecalBridge
|
||||
{
|
||||
[FriendlyName("RynthCore Decal Bridge")]
|
||||
public sealed unsafe class BridgeFilter : FilterBase
|
||||
{
|
||||
private const string LogDir = @"C:\Games\RynthCore\Logs";
|
||||
private const string LoaderModule = "RynthCore.Loader.dll";
|
||||
private const int ArmCheckEveryFrames = 120; // ~2 s at 60 fps
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr GetModuleHandleW(string name);
|
||||
|
||||
private BridgeChannel _ch;
|
||||
private int _pid;
|
||||
private bool _disabled;
|
||||
private bool _worldWired;
|
||||
private bool _invoking; // true while a command of ours runs InvokeChatParser
|
||||
private int _frames;
|
||||
private string[] _prefixes = new string[0];
|
||||
private int _prefixStamp = -1;
|
||||
private long _serverMessages;
|
||||
private int _loggedServer;
|
||||
private int _loggedChatBar;
|
||||
private bool _devicePublished;
|
||||
|
||||
protected override void Startup()
|
||||
{
|
||||
_pid = Process.GetCurrentProcess().Id;
|
||||
if (Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE") == "0")
|
||||
{
|
||||
_disabled = true;
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
Core.RenderFrame += OnRenderFrame;
|
||||
TryArm();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("startup failed: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Shutdown()
|
||||
{
|
||||
if (_disabled)
|
||||
return;
|
||||
try
|
||||
{
|
||||
Core.RenderFrame -= OnRenderFrame;
|
||||
if (_ch != null)
|
||||
{
|
||||
ServerDispatch -= OnServerDispatch;
|
||||
Core.ChatBoxMessage -= OnChatBoxMessage;
|
||||
Core.CommandLineText -= OnCommandLineText;
|
||||
Core.ItemSelected -= OnItemSelected;
|
||||
Core.FilterInitComplete -= OnFilterInitComplete;
|
||||
Core.PluginInitComplete -= OnFilterInitComplete;
|
||||
}
|
||||
if (_worldWired)
|
||||
{
|
||||
Core.WorldFilter.CreateObject -= OnCreateObject;
|
||||
Core.WorldFilter.ReleaseObject -= OnReleaseObject;
|
||||
Core.WorldFilter.ChangeObject -= OnChangeObject;
|
||||
Core.CharacterFilter.LoginComplete -= OnLoginComplete;
|
||||
Core.CharacterFilter.Logoff -= OnLogoff;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
if (_ch != null)
|
||||
{
|
||||
Log("shutdown after " + _serverMessages + " server messages, " +
|
||||
_ch.ReadLong(BridgeLayout.OffRecords) + " records, " + _ch.ReadLong(BridgeLayout.OffDropped) + " dropped, " +
|
||||
_ch.ReadLong(BridgeLayout.OffCmdDone) + " commands run");
|
||||
_ch.WriteInt(BridgeLayout.OffBridgeState, 0);
|
||||
_ch.Dispose();
|
||||
_ch = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Arms once the RynthCore loader is in this client (injected with Decal, or later).
|
||||
private void TryArm()
|
||||
{
|
||||
if (_ch != null || GetModuleHandleW(LoaderModule) == IntPtr.Zero)
|
||||
return;
|
||||
BridgeChannel ch = BridgeChannel.OpenOrCreate(_pid);
|
||||
if (!ch.Valid)
|
||||
{
|
||||
Log("mapping has another protocol version (magic 0x" + ch.ReadInt(BridgeLayout.OffMagic).ToString("X8") +
|
||||
", version " + ch.ReadInt(BridgeLayout.OffVersion) + ", ours " + BridgeLayout.Version +
|
||||
") - the engine and the bridge are from different builds; staying idle.");
|
||||
ch.Dispose();
|
||||
_disabled = true;
|
||||
return;
|
||||
}
|
||||
_ch = ch;
|
||||
_ch.WriteInt(BridgeLayout.OffBridgePid, _pid);
|
||||
_ch.WriteString(BridgeRecordKind.Hello, BridgeLayout.Version, 0,
|
||||
"RynthCore Decal Bridge " + typeof(BridgeFilter).Assembly.GetName().Version + " on " +
|
||||
Environment.Version + " (" + (IntPtr.Size * 8) + "-bit)");
|
||||
ServerDispatch += OnServerDispatch;
|
||||
Core.ChatBoxMessage += OnChatBoxMessage;
|
||||
Core.CommandLineText += OnCommandLineText;
|
||||
Core.ItemSelected += OnItemSelected;
|
||||
// WorldFilter / CharacterFilter exist once Decal's filters are up.
|
||||
Core.FilterInitComplete += OnFilterInitComplete;
|
||||
Core.PluginInitComplete += OnFilterInitComplete;
|
||||
TryWireWorld();
|
||||
_ch.WriteInt(BridgeLayout.OffBridgeState, 1); // the engine waits for this
|
||||
Log("armed (RynthCore is in this client); mapping " + BridgeLayout.MappingName(_pid) + ", world wired=" + _worldWired);
|
||||
}
|
||||
|
||||
private void OnFilterInitComplete(object sender, EventArgs e)
|
||||
{
|
||||
TryWireWorld();
|
||||
}
|
||||
|
||||
private void TryWireWorld()
|
||||
{
|
||||
if (_worldWired) return;
|
||||
try
|
||||
{
|
||||
WorldFilter wf = Core.WorldFilter;
|
||||
CharacterFilter cf = Core.CharacterFilter;
|
||||
if (wf == null || cf == null) return;
|
||||
wf.CreateObject += OnCreateObject;
|
||||
wf.ReleaseObject += OnReleaseObject;
|
||||
wf.ChangeObject += OnChangeObject;
|
||||
cf.LoginComplete += OnLoginComplete;
|
||||
cf.Logoff += OnLogoff;
|
||||
_worldWired = true;
|
||||
Log("WorldFilter and CharacterFilter wired (Decal's world filters are up).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("wiring WorldFilter failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// ── once per frame, AC's main thread ─────────────────────────────────
|
||||
private void OnRenderFrame(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_disabled)
|
||||
return;
|
||||
if (_ch == null)
|
||||
{
|
||||
if (++_frames % ArmCheckEveryFrames == 0)
|
||||
TryArm();
|
||||
return;
|
||||
}
|
||||
if (!_devicePublished)
|
||||
PublishDevice();
|
||||
if (_ch.HasCommands)
|
||||
_ch.DrainCommands(RunCommand, 64);
|
||||
ServeReplay();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("frame handler failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// The device Decal renders with, through Decal's public IDecalCore.GetD3DDevice: an
|
||||
// address for the engine to read (its vtable says whether Decal wraps AC's device).
|
||||
// No reference is kept and nothing is called on it here.
|
||||
private void PublishDevice()
|
||||
{
|
||||
_devicePublished = true;
|
||||
try
|
||||
{
|
||||
Guid iid = new Guid("D0223B96-BF7A-43FD-92BD-A43B0D82B9EB"); // IID_IDirect3DDevice9
|
||||
object dev = Core.Decal.Underlying.GetD3DDevice(ref iid);
|
||||
if (dev == null) { Log("GetD3DDevice returned null"); return; }
|
||||
IntPtr unk = Marshal.GetIUnknownForObject(dev);
|
||||
IntPtr d3d;
|
||||
int hr = Marshal.QueryInterface(unk, ref iid, out d3d);
|
||||
if (hr >= 0 && d3d != IntPtr.Zero)
|
||||
{
|
||||
_ch.WriteInt(BridgeLayout.OffD3DDevice, d3d.ToInt32());
|
||||
Marshal.Release(d3d);
|
||||
}
|
||||
Marshal.Release(unk);
|
||||
Marshal.ReleaseComObject(dev);
|
||||
_ch.WriteInt(BridgeLayout.OffDecalHwnd, Core.Decal.Hwnd.ToInt32());
|
||||
Log("Decal's D3D device 0x" + _ch.ReadInt(BridgeLayout.OffD3DDevice).ToString("X8") + " (QI hr=0x" + hr.ToString("X8") +
|
||||
"), hwnd 0x" + Core.Decal.Hwnd.ToInt32().ToString("X"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("GetD3DDevice failed: " + ex.GetType().Name + ": " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// An engine generation that takes objects from the bridge starts with none (a hot
|
||||
// reload, or an engine injected late): it bumps the replay request.
|
||||
private void ServeReplay()
|
||||
{
|
||||
int want = _ch.ReadInt(BridgeLayout.OffReplayRequest);
|
||||
if (want == 0 || want == _ch.ReadInt(BridgeLayout.OffReplayDone) || !_worldWired)
|
||||
return;
|
||||
int n = 0;
|
||||
if (_ch.Wants(BridgeRecordKind.CreateObject))
|
||||
{
|
||||
foreach (WorldObject o in Core.WorldFilter.GetAll())
|
||||
{
|
||||
_ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)o.Id), 1, null, 0);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
_ch.WriteInt(BridgeLayout.OffReplayDone, want);
|
||||
Log("replayed " + n + " world objects for engine request " + want);
|
||||
}
|
||||
|
||||
private void RunCommand(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len)
|
||||
{
|
||||
string failure = null;
|
||||
try
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case BridgeRecordKind.CmdInvokeChatParser:
|
||||
string line = len >= 2 ? new string((char*)payload, 0, len / 2) : string.Empty;
|
||||
_invoking = true;
|
||||
try { Core.Actions.InvokeChatParser(line); }
|
||||
finally { _invoking = false; }
|
||||
break;
|
||||
case BridgeRecordKind.CmdSalvagePanelAdd:
|
||||
Core.Actions.SalvagePanelAdd(unchecked((int)arg0));
|
||||
break;
|
||||
case BridgeRecordKind.CmdSalvagePanelSalvage:
|
||||
Core.Actions.SalvagePanelSalvage();
|
||||
break;
|
||||
default:
|
||||
failure = "unknown command " + (int)kind;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failure = ex.GetType().Name + ": " + ex.Message;
|
||||
}
|
||||
if (failure != null)
|
||||
{
|
||||
Log("command " + kind + " failed: " + failure);
|
||||
_ch.WriteString(BridgeRecordKind.CommandResult, (uint)kind, 0, failure);
|
||||
}
|
||||
}
|
||||
|
||||
// ── forwarders (AC's main thread; never block, never throw) ──────────
|
||||
private void OnServerDispatch(object sender, NetworkMessageEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
_serverMessages++;
|
||||
if (!_ch.Wants(BridgeRecordKind.ServerMessage))
|
||||
return; // the engine reads these from its own hooks: don't copy them
|
||||
Message m = e.Message;
|
||||
byte[] raw = m.RawData;
|
||||
if (_loggedServer < 4)
|
||||
{
|
||||
_loggedServer++;
|
||||
Log("server message type=0x" + m.Type.ToString("X4") + " len=" + (raw == null ? 0 : raw.Length));
|
||||
}
|
||||
_ch.WriteBytes(BridgeRecordKind.ServerMessage, unchecked((uint)m.Type), 0, raw);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e)
|
||||
{
|
||||
try { _ch.WriteString(BridgeRecordKind.ChatText, unchecked((uint)e.Color), unchecked((uint)e.Target), e.Text); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnCommandLineText(object sender, ChatParserInterceptEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
// A line the engine sent through InvokeChatParser: it already went through the
|
||||
// engine's own dispatch; let Decal and AC have it.
|
||||
if (_invoking)
|
||||
return;
|
||||
string text = e.Text ?? string.Empty;
|
||||
// The engine's commands (and its plugins') must not reach the server: eat the
|
||||
// lines whose prefix the engine published; forward every line either way.
|
||||
bool eat = MatchesPrefix(text);
|
||||
if (eat) e.Eat = true;
|
||||
if (_loggedChatBar < 10)
|
||||
{
|
||||
_loggedChatBar++;
|
||||
Log("chat bar: '" + text + "' eaten=" + eat);
|
||||
}
|
||||
_ch.WriteString(BridgeRecordKind.ChatBarEnter, eat ? 1u : 0u, 0, text);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnItemSelected(object sender, ItemSelectedEventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.ItemSelected, unchecked((uint)e.ItemGuid), 0, null, 0); } catch { }
|
||||
}
|
||||
|
||||
private void OnCreateObject(object sender, CreateObjectEventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)e.New.Id), 0, null, 0); } catch { }
|
||||
}
|
||||
|
||||
private void OnReleaseObject(object sender, ReleaseObjectEventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.ReleaseObject, unchecked((uint)e.Released.Id), 0, null, 0); } catch { }
|
||||
}
|
||||
|
||||
private void OnChangeObject(object sender, ChangeObjectEventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.ChangeObject, unchecked((uint)e.Changed.Id), (uint)e.Change, null, 0); } catch { }
|
||||
}
|
||||
|
||||
private void OnLoginComplete(object sender, EventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.LoginComplete, unchecked((uint)Core.CharacterFilter.Id), 0, null, 0); } catch { }
|
||||
}
|
||||
|
||||
private void OnLogoff(object sender, LogoffEventArgs e)
|
||||
{
|
||||
try { _ch.Write(BridgeRecordKind.Logoff, (uint)e.Type, 0, null, 0); } catch { }
|
||||
}
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────────────
|
||||
private bool MatchesPrefix(string text)
|
||||
{
|
||||
if (_ch.ReadInt(BridgeLayout.OffEngineAttached) == 0)
|
||||
return false; // no engine to run it: let AC have the line
|
||||
// The engine rewrites the prefix list when it attaches; re-read it when it changes.
|
||||
int gen = _ch.ReadInt(BridgeLayout.OffEngineGeneration);
|
||||
if (gen != _prefixStamp)
|
||||
{
|
||||
_prefixStamp = gen;
|
||||
char* p = (char*)(_ch.Header + BridgeLayout.OffPrefixes);
|
||||
int n = 0;
|
||||
while (n < BridgeLayout.PrefixChars && p[n] != '\0') n++;
|
||||
_prefixes = new string(p, 0, n).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
foreach (string pre in _prefixes)
|
||||
{
|
||||
if (text.StartsWith(pre, StringComparison.OrdinalIgnoreCase) &&
|
||||
(text.Length == pre.Length || text[pre.Length] == ' '))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Log(string msg)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.AppendAllText(System.IO.Path.Combine(LogDir, "DecalBridge." + _pid + ".log"),
|
||||
"[" + DateTime.Now.ToString("HH:mm:ss.fff") + "] " + msg + Environment.NewLine);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
302
src/RynthCore.DecalBridge/BridgeProtocol.cs
Normal file
302
src/RynthCore.DecalBridge/BridgeProtocol.cs
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
// ============================================================================
|
||||
// RynthCore.DecalBridge - BridgeProtocol.cs
|
||||
//
|
||||
// The in-process channel between the Decal bridge filter (.NET Framework, Decal's
|
||||
// desktop CLR) and the RynthCore engine (CoreCLR, unloadable). Compiled into BOTH
|
||||
// assemblies (the engine links this file), so it stays C# 9 / net48-compatible.
|
||||
// docs/DECAL_BRIDGE_PLAN.md has the design.
|
||||
//
|
||||
// A named, pagefile-backed file mapping holds a header and two single-producer /
|
||||
// single-consumer byte rings:
|
||||
// event ring (bridge -> engine): producer = the bridge, on AC's main thread (Decal
|
||||
// raises its events there); consumer = the engine's plugin pump thread.
|
||||
// command ring (engine -> bridge): producer = the engine (any thread, serialised by
|
||||
// the engine); consumer = the bridge, on AC's main thread (RenderFrame),
|
||||
// which runs each command through Decal's public API.
|
||||
// Nothing crosses the runtimes but bytes: no function pointer, delegate or COM object
|
||||
// is ever handed from one runtime to the other. That is what makes it safe with the
|
||||
// unloadable engine - a generation that goes away leaves nothing behind that the
|
||||
// bridge could call into, and neither side ever blocks on the other (a full ring
|
||||
// drops the record and counts it). The mapping lives as long as either side holds it,
|
||||
// so the read positions survive an engine hot reload.
|
||||
//
|
||||
// The engine publishes which event kinds it wants (OffWantMask); the bridge writes
|
||||
// only those, so a stream the engine takes from its own hooks costs Decal nothing.
|
||||
//
|
||||
// Record: [int length (multiple of 4, header included)][ushort kind][ushort pad bytes]
|
||||
// [uint arg0][uint arg1][payload...]
|
||||
// Write/read positions are monotonic byte counts (64-bit, Interlocked on x86).
|
||||
//
|
||||
// Version 2 (2026-09-30): want mask, command ring, bridge hello/state fields.
|
||||
// ============================================================================
|
||||
#nullable disable
|
||||
using System;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.DecalBridge
|
||||
{
|
||||
internal enum BridgeRecordKind : ushort
|
||||
{
|
||||
Pad = 0,
|
||||
// ── events, bridge -> engine ──
|
||||
Hello = 1, // arg0 = protocol version, payload = UTF-16 bridge description (always written)
|
||||
ChatText = 2, // arg0 = Decal ChatBoxMessage.Color (AC chat type), arg1 = Target, payload = UTF-16 text
|
||||
ChatBarEnter = 3, // arg0 = 1 when the bridge ate the line, payload = UTF-16 text
|
||||
CreateObject = 4, // arg0 = object id, arg1 = 1 when part of a replay (WorldFilter.GetAll)
|
||||
ReleaseObject = 5, // arg0 = object id
|
||||
ChangeObject = 6, // arg0 = object id, arg1 = WorldChangeType
|
||||
ServerMessage = 7, // arg0 = message type (opcode), payload = Message.RawData
|
||||
LoginComplete = 8, // arg0 = character id
|
||||
Logoff = 9, // arg0 = LogoffEventType
|
||||
ItemSelected = 10, // arg0 = object id
|
||||
CommandResult = 11, // arg0 = command kind, arg1 = 1 ok / 0 failed, payload = UTF-16 detail (failures only)
|
||||
|
||||
// ── commands, engine -> bridge (run on AC's main thread through Decal's public API) ──
|
||||
CmdInvokeChatParser = 100, // payload = UTF-16 line -> Actions.InvokeChatParser
|
||||
CmdSalvagePanelAdd = 101, // arg0 = item id -> Actions.SalvagePanelAdd
|
||||
CmdSalvagePanelSalvage = 102,// -> Actions.SalvagePanelSalvage
|
||||
}
|
||||
|
||||
internal static unsafe class BridgeLayout
|
||||
{
|
||||
public const uint Magic = 0x42444352; // "RCDB"
|
||||
public const int Version = 2;
|
||||
public const int HeaderSize = 4096;
|
||||
public const int CommandRingSize = 64 * 1024;
|
||||
public const int EventRingSize = 16 * 1024 * 1024;
|
||||
public const int TotalSize = HeaderSize + CommandRingSize + EventRingSize;
|
||||
public const int RecordHeaderSize = 16;
|
||||
public const int MaxRecord = 256 * 1024;
|
||||
|
||||
// Header offsets.
|
||||
public const int OffMagic = 0;
|
||||
public const int OffVersion = 4;
|
||||
public const int OffBridgeState = 8; // 1 while a bridge is started (its "hello")
|
||||
public const int OffBridgeBeats = 12; // bridge: bumped per record written
|
||||
public const int OffWritePos = 16; // long, event ring, producer-owned
|
||||
public const int OffReadPos = 24; // long, event ring, consumer-owned
|
||||
public const int OffDropped = 32; // long, event records the bridge dropped (ring full)
|
||||
public const int OffRecords = 40; // long, event records written
|
||||
public const int OffEngineAttached = 48; // 1 while an engine generation drains
|
||||
public const int OffEngineGeneration = 52;
|
||||
public const int OffBridgePid = 56;
|
||||
public const int OffReplayRequest = 60; // engine -> bridge: bump to get WorldFilter.GetAll() as CreateObject records
|
||||
public const int OffReplayDone = 64; // bridge -> engine: the request value last served
|
||||
public const int OffWantMask = 68; // engine -> bridge: bit (1 << kind) for each event kind to forward
|
||||
public const int OffCmdWritePos = 72; // long, command ring, engine-owned
|
||||
public const int OffCmdReadPos = 80; // long, command ring, bridge-owned
|
||||
public const int OffCmdDropped = 88; // long, commands the engine dropped (ring full)
|
||||
public const int OffCmdDone = 96; // long, commands the bridge ran
|
||||
// Added in v2 without a version bump (zero from an older bridge = unknown):
|
||||
public const int OffD3DDevice = 104; // bridge -> engine: IDirect3DDevice9* Decal renders with (IDecalCore.GetD3DDevice), 0 = unknown
|
||||
public const int OffDecalHwnd = 108; // bridge -> engine: the game window as Decal knows it
|
||||
public const int OffPrefixes = 256; // engine -> bridge: ';'-separated chat prefixes to eat, UTF-16, 0-terminated
|
||||
public const int PrefixChars = 1024;
|
||||
|
||||
public static string MappingName(int pid) { return "Local\\RynthCore.DecalBridge.p" + pid; }
|
||||
|
||||
public static int Align4(int n) { return (n + 3) & ~3; }
|
||||
|
||||
public static uint Bit(BridgeRecordKind kind) { return (uint)kind < 32 ? 1u << (int)kind : 0u; }
|
||||
}
|
||||
|
||||
/// <summary>One side's view of the mapping (the bridge and the engine each open their own).</summary>
|
||||
internal sealed unsafe class BridgeChannel : IDisposable
|
||||
{
|
||||
private MemoryMappedFile _file;
|
||||
private MemoryMappedViewAccessor _view;
|
||||
private byte* _base;
|
||||
|
||||
public byte* Header { get { return _base; } }
|
||||
private byte* CommandRing { get { return _base + BridgeLayout.HeaderSize; } }
|
||||
private byte* EventRing { get { return _base + BridgeLayout.HeaderSize + BridgeLayout.CommandRingSize; } }
|
||||
|
||||
public static BridgeChannel OpenOrCreate(int pid)
|
||||
{
|
||||
var c = new BridgeChannel();
|
||||
c._file = MemoryMappedFile.CreateOrOpen(BridgeLayout.MappingName(pid), BridgeLayout.TotalSize);
|
||||
c._view = c._file.CreateViewAccessor(0, BridgeLayout.TotalSize);
|
||||
byte* p = null;
|
||||
c._view.SafeMemoryMappedViewHandle.AcquirePointer(ref p);
|
||||
c._base = p + c._view.PointerOffset;
|
||||
// The first opener stamps the header; the pages start zeroed either way.
|
||||
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffVersion), BridgeLayout.Version, 0);
|
||||
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffMagic), unchecked((int)BridgeLayout.Magic), 0);
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>True when some side already created the mapping for <paramref name="pid"/>.</summary>
|
||||
public static bool Exists(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MemoryMappedFile f = MemoryMappedFile.OpenExisting(BridgeLayout.MappingName(pid)))
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public int ReadInt(int off) { return Volatile.Read(ref *(int*)(_base + off)); }
|
||||
public void WriteInt(int off, int v) { Volatile.Write(ref *(int*)(_base + off), v); }
|
||||
public long ReadLong(int off) { return Interlocked.Read(ref *(long*)(_base + off)); }
|
||||
public void WriteLong(int off, long v) { Interlocked.Exchange(ref *(long*)(_base + off), v); }
|
||||
public void AddLong(int off, long v) { Interlocked.Add(ref *(long*)(_base + off), v); }
|
||||
|
||||
public bool Valid { get { return (uint)ReadInt(BridgeLayout.OffMagic) == BridgeLayout.Magic && ReadInt(BridgeLayout.OffVersion) == BridgeLayout.Version; } }
|
||||
|
||||
/// <summary>Whether the engine asked for <paramref name="kind"/> (Hello always goes).</summary>
|
||||
public bool Wants(BridgeRecordKind kind)
|
||||
{
|
||||
return kind == BridgeRecordKind.Hello || (unchecked((uint)ReadInt(BridgeLayout.OffWantMask)) & BridgeLayout.Bit(kind)) != 0;
|
||||
}
|
||||
|
||||
// ── event ring (bridge -> engine) ─────────────────────────────────────
|
||||
public bool Write(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
|
||||
{
|
||||
if (!Wants(kind))
|
||||
return false;
|
||||
bool ok = Put(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos,
|
||||
BridgeLayout.OffDropped, kind, arg0, arg1, payload, payloadLen);
|
||||
if (ok)
|
||||
{
|
||||
AddLong(BridgeLayout.OffRecords, 1);
|
||||
Interlocked.Increment(ref *(int*)(_base + BridgeLayout.OffBridgeBeats));
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
public bool WriteString(BridgeRecordKind kind, uint arg0, uint arg1, string text)
|
||||
{
|
||||
if (text == null) text = string.Empty;
|
||||
fixed (char* c = text)
|
||||
return Write(kind, arg0, arg1, (byte*)c, text.Length * 2);
|
||||
}
|
||||
|
||||
public bool WriteBytes(BridgeRecordKind kind, uint arg0, uint arg1, byte[] data)
|
||||
{
|
||||
if (data == null || data.Length == 0)
|
||||
return Write(kind, arg0, arg1, null, 0);
|
||||
fixed (byte* b = data)
|
||||
return Write(kind, arg0, arg1, b, data.Length);
|
||||
}
|
||||
|
||||
public delegate void RecordHandler(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen);
|
||||
|
||||
/// <summary>Hands every event written so far to <paramref name="handler"/> (payload valid only during the call).</summary>
|
||||
public int Drain(RecordHandler handler, int maxRecords)
|
||||
{
|
||||
return Take(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, handler, maxRecords);
|
||||
}
|
||||
|
||||
// ── command ring (engine -> bridge) ───────────────────────────────────
|
||||
/// <summary>Queues a command for the bridge. One producer at a time (the engine serialises).</summary>
|
||||
public bool WriteCommand(BridgeRecordKind kind, uint arg0, uint arg1, string text)
|
||||
{
|
||||
if (text == null)
|
||||
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
|
||||
BridgeLayout.OffCmdDropped, kind, arg0, arg1, null, 0);
|
||||
fixed (char* c = text)
|
||||
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
|
||||
BridgeLayout.OffCmdDropped, kind, arg0, arg1, (byte*)c, text.Length * 2);
|
||||
}
|
||||
|
||||
/// <summary>Bridge: runs every queued command through <paramref name="handler"/>.</summary>
|
||||
public int DrainCommands(RecordHandler handler, int maxRecords)
|
||||
{
|
||||
int n = Take(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, handler, maxRecords);
|
||||
if (n > 0) AddLong(BridgeLayout.OffCmdDone, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
public bool HasCommands { get { return ReadLong(BridgeLayout.OffCmdWritePos) != ReadLong(BridgeLayout.OffCmdReadPos); } }
|
||||
|
||||
// ── ring primitives ───────────────────────────────────────────────────
|
||||
private bool Put(byte* ring, int size, int offWrite, int offRead, int offDropped,
|
||||
BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
|
||||
{
|
||||
if (payloadLen < 0 || payloadLen > BridgeLayout.MaxRecord || payloadLen > size / 4)
|
||||
{
|
||||
AddLong(offDropped, 1);
|
||||
return false;
|
||||
}
|
||||
int recLen = BridgeLayout.Align4(BridgeLayout.RecordHeaderSize + payloadLen);
|
||||
long w = ReadLong(offWrite);
|
||||
long r = ReadLong(offRead);
|
||||
int pos = (int)(w % size);
|
||||
int tail = size - pos;
|
||||
int need = recLen + (tail < recLen ? tail : 0);
|
||||
if (need > size - (w - r))
|
||||
{
|
||||
AddLong(offDropped, 1);
|
||||
return false;
|
||||
}
|
||||
if (tail < recLen)
|
||||
{
|
||||
// Doesn't fit before the end: pad to the end, start again at 0. A tail shorter
|
||||
// than a record header is skipped by the reader without being read.
|
||||
if (tail >= BridgeLayout.RecordHeaderSize)
|
||||
{
|
||||
*(int*)(ring + pos) = tail;
|
||||
*(ushort*)(ring + pos + 4) = (ushort)BridgeRecordKind.Pad;
|
||||
}
|
||||
pos = 0;
|
||||
}
|
||||
byte* rec = ring + pos;
|
||||
*(int*)rec = recLen;
|
||||
*(ushort*)(rec + 4) = (ushort)kind;
|
||||
*(ushort*)(rec + 6) = (ushort)(recLen - BridgeLayout.RecordHeaderSize - payloadLen); // pad bytes
|
||||
*(uint*)(rec + 8) = arg0;
|
||||
*(uint*)(rec + 12) = arg1;
|
||||
for (int i = 0; i < payloadLen; i++)
|
||||
rec[BridgeLayout.RecordHeaderSize + i] = payload[i];
|
||||
WriteLong(offWrite, w + need); // publish (full fence)
|
||||
return true;
|
||||
}
|
||||
|
||||
private int Take(byte* ring, int size, int offWrite, int offRead, RecordHandler handler, int maxRecords)
|
||||
{
|
||||
long r = ReadLong(offRead);
|
||||
long w = ReadLong(offWrite);
|
||||
int n = 0;
|
||||
while (r < w && n < maxRecords)
|
||||
{
|
||||
int pos = (int)(r % size);
|
||||
int tail = size - pos;
|
||||
if (tail < BridgeLayout.RecordHeaderSize) { r += tail; continue; }
|
||||
int len = *(int*)(ring + pos);
|
||||
if (len < BridgeLayout.RecordHeaderSize || len > tail || (len & 3) != 0)
|
||||
{
|
||||
r = w; // corrupt: resynchronise at the writer
|
||||
break;
|
||||
}
|
||||
var kind = (BridgeRecordKind)(*(ushort*)(ring + pos + 4));
|
||||
if (kind != BridgeRecordKind.Pad)
|
||||
{
|
||||
int pad = *(ushort*)(ring + pos + 6) & 3;
|
||||
handler(kind, *(uint*)(ring + pos + 8), *(uint*)(ring + pos + 12),
|
||||
ring + pos + BridgeLayout.RecordHeaderSize, len - BridgeLayout.RecordHeaderSize - pad);
|
||||
n++;
|
||||
}
|
||||
r += len;
|
||||
}
|
||||
WriteLong(offRead, r);
|
||||
return n;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_view != null)
|
||||
{
|
||||
if (_base != null) _view.SafeMemoryMappedViewHandle.ReleasePointer();
|
||||
_view.Dispose();
|
||||
_view = null;
|
||||
}
|
||||
_base = null;
|
||||
if (_file != null) { _file.Dispose(); _file = null; }
|
||||
}
|
||||
}
|
||||
}
|
||||
71
src/RynthCore.DecalBridge/RynthCore.DecalBridge.csproj
Normal file
71
src/RynthCore.DecalBridge/RynthCore.DecalBridge.csproj
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthCore Decal Bridge: a Decal network filter that lets the RynthCore engine run in
|
||||
the same acclient.exe as Decal (docs/DECAL_BRIDGE_PLAN.md).
|
||||
|
||||
net48 / x86: it loads into Decal's desktop CLR inside the 32-bit client. Built only
|
||||
against Decal's public reference assemblies (Decal.Adapter and the interop PIAs it
|
||||
exposes in its signatures), never shipped with them (Private=false).
|
||||
|
||||
dotnet build -c Release (also part of RynthCore.sln)
|
||||
|
||||
Needs Decal installed (default C:\Program Files (x86)\Decal 3.0, or -p:DecalDir=...).
|
||||
Without it the project builds nothing useful: a warning, and an empty assembly under
|
||||
bin\<Configuration>-NoDecal\ (never the real output folder), so a machine without
|
||||
Decal can still build the whole solution.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<Platforms>AnyCPU;x86</Platforms>
|
||||
<OutputType>Library</OutputType>
|
||||
<AssemblyName>RynthCore.DecalBridge</AssemblyName>
|
||||
<RootNamespace>RynthCore.DecalBridge</RootNamespace>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||
<Deterministic>true</Deterministic>
|
||||
<Version>0.2.0</Version>
|
||||
<DecalDir Condition="'$(DecalDir)' == ''">C:\Program Files (x86)\Decal 3.0</DecalDir>
|
||||
<DecalAvailable Condition="Exists('$(DecalDir)\Decal.Adapter.dll')">true</DecalAvailable>
|
||||
<OutputPath>bin\$(Configuration)\</OutputPath>
|
||||
<OutputPath Condition="'$(DecalAvailable)' != 'true'">bin\$(Configuration)-NoDecal\</OutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(DecalAvailable)' == 'true'">
|
||||
<Reference Include="Decal.Adapter">
|
||||
<HintPath>$(DecalDir)\Decal.Adapter.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<!-- Public interop assemblies that appear in Decal.Adapter's own signatures. -->
|
||||
<Reference Include="Decal.Interop.Core"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Core.DLL</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Decal.Interop.Filters"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Filters.DLL</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Decal.Interop.Net"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Net.DLL</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Decal.Interop.Inject"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Inject.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Decal.Interop.D3DService"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Decal.Interop.Render"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Render.DLL</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="System.Drawing" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(DecalAvailable)' != 'true'">
|
||||
<Compile Remove="**\*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="WarnNoDecal" BeforeTargets="CoreCompile" Condition="'$(DecalAvailable)' != 'true' and '$(RequireDecal)' != 'true'">
|
||||
<Warning Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)' - the Decal bridge is not built (install Decal or pass -p:DecalDir=...)." />
|
||||
</Target>
|
||||
|
||||
<!-- Release builds (installer\Build-Installer.ps1) pass -p:RequireDecal=true: no Decal, no build. -->
|
||||
<Target Name="RequireDecal" BeforeTargets="BeforeBuild" Condition="'$(RequireDecal)' == 'true' and '$(DecalAvailable)' != 'true'">
|
||||
<Error Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)'. The release ships the Decal bridge, so it must be built against Decal's reference assemblies: install Decal 3.0 or pass -p:DecalDir=..." />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
Loading…
Reference in a new issue