merge: bring feat/full-installer into SK-local
Integrates the aelrynth snapshot port (main), the full installer, the tmds.dbus advisory fix and all launcher/engine work into SK-local. Conflict resolutions: - Logging: keep SK-local's level-based logging (EngineLogLevel, ShouldLog, engine.json LoggingLevel) and adopt full-installer's tagged WRN/ERR, LastIssue and per-PID logs; the Desktop rolling log is superseded. - Launcher: keep the inject-all-sessions toggle and Logging level combo alongside the new stagger/crash-relaunch/stuck-client options; the LoggingLevel is now written through EngineJsonStore.SetString. - PluginManager: keep SK-local's basename/canonical-path de-duplication, drop the default-directory scan (opt-in via PluginPaths). - Injector, installer, CI workflow, BUILD.md: take full-installer. - Solution: add DesktopLog + Loader, drop the stale Plugins/RynthAi stub. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
36ffa94252
256 changed files with 62130 additions and 3382 deletions
59
.github/workflows/ci-statusagent.yml
vendored
Normal file
59
.github/workflows/ci-statusagent.yml
vendored
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
name: CI — StatusAgent build
|
||||
|
||||
# Builds on a Windows runner so the (otherwise Windows/NativeAOT-only) code is
|
||||
# actually compiled in CI, and publishes a standalone RynthCore.StatusAgent.exe
|
||||
# as a downloadable artifact. Runs on PRs that touch source + on manual dispatch.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'src/**'
|
||||
- '.github/workflows/ci-statusagent.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
# ── Compile-check the engine-side changes (managed build; no ILC/AOT link,
|
||||
# no RynthSuite needed — this just verifies the C# compiles). ──────────
|
||||
- name: Compile-check RynthCore.Engine
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet build src/RynthCore.Engine/RynthCore.Engine.csproj -c Release
|
||||
if ($LASTEXITCODE -ne 0) { throw "RynthCore.Engine failed to compile" }
|
||||
|
||||
# ── Build + publish the StatusAgent as a standalone single-file exe so it
|
||||
# runs on the gaming PC with no .NET install. ──────────────────────────
|
||||
- name: Publish RynthCore.StatusAgent (self-contained win-x64)
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet publish src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj `
|
||||
-c Release -r win-x64 --self-contained true `
|
||||
-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true `
|
||||
-o publish/StatusAgent
|
||||
if ($LASTEXITCODE -ne 0) { throw "RynthCore.StatusAgent failed to publish" }
|
||||
Get-ChildItem publish/StatusAgent | Format-Table Name,Length
|
||||
|
||||
- name: Smoke test (--once --dry-run)
|
||||
shell: pwsh
|
||||
run: |
|
||||
# No status files / no AC running on the runner, so this just proves the
|
||||
# exe starts, reads cleanly, and exits 0 in local print-only mode.
|
||||
./publish/StatusAgent/RynthCore.StatusAgent.exe --once --dry-run --verbose
|
||||
if ($LASTEXITCODE -ne 0) { throw "StatusAgent smoke test exited $LASTEXITCODE" }
|
||||
|
||||
- name: Upload StatusAgent artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: RynthCore.StatusAgent-win-x64
|
||||
path: publish/StatusAgent/**
|
||||
if-no-files-found: error
|
||||
109
.github/workflows/release.yml
vendored
109
.github/workflows/release.yml
vendored
|
|
@ -10,6 +10,10 @@ on:
|
|||
description: 'Version number (e.g. 0.3) — creates tag v<version>'
|
||||
required: true
|
||||
default: '0.3'
|
||||
rynthsuite_ref:
|
||||
description: 'RynthSuite ref to build against (tag/branch/SHA). Blank = matching version tag, else default branch.'
|
||||
required: false
|
||||
default: ''
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
|
@ -31,27 +35,75 @@ jobs:
|
|||
- name: Checkout RynthCore
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Checkout RynthSuite (sibling of RynthCore)
|
||||
# Pin the sibling to the matching version tag so a tagged release is
|
||||
# REPRODUCIBLE (otherwise it builds against whatever RynthSuite main is at
|
||||
# build time — PluginContractVersion skew is one push away). Falls back to
|
||||
# the default branch (with a CI warning) if the matching tag doesn't exist
|
||||
# yet, e.g. a manual dispatch before RynthSuite is tagged.
|
||||
- name: Checkout RynthSuite (sibling, pinned)
|
||||
shell: pwsh
|
||||
run: |
|
||||
$parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent
|
||||
$dest = "$parent\RynthSuite"
|
||||
Write-Host "Cloning RynthSuite to: $dest"
|
||||
if ("${{ github.event_name }}" -eq "push") { $want = "${{ github.ref_name }}" }
|
||||
else { $want = "v${{ github.event.inputs.version }}" }
|
||||
$override = "${{ github.event.inputs.rynthsuite_ref }}"
|
||||
if ($override) { $want = $override }
|
||||
Write-Host "Cloning RynthSuite to: $dest (pin target: $want)"
|
||||
# Sibling fork on the same GitHub owner (BlankenshipG in this environment).
|
||||
# Canonical public source is https://aelrynth.com/git/RynthSuite.git — CI uses
|
||||
# the GitHub sibling so the release build matches this fork pair.
|
||||
# If RynthSuite is private, set a GH_PAT secret and use the token URL:
|
||||
# git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/tombohar/RynthSuite.git $dest
|
||||
git clone https://github.com/tombohar/RynthSuite.git $dest
|
||||
# git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/${{ github.repository_owner }}/RynthSuite.git $dest
|
||||
git clone "https://github.com/${{ github.repository_owner }}/RynthSuite.git" $dest
|
||||
if ($LASTEXITCODE -ne 0) { throw "git clone RynthSuite failed" }
|
||||
git -C $dest fetch --tags --quiet
|
||||
if ($want -and (git -C $dest rev-parse --verify --quiet "$want^{commit}")) {
|
||||
git -C $dest checkout --quiet $want
|
||||
if ($LASTEXITCODE -ne 0) { throw "checkout RynthSuite $want failed" }
|
||||
Write-Host "RynthSuite pinned to: $want"
|
||||
} else {
|
||||
Write-Host "::warning::RynthSuite ref '$want' not found; building against default branch HEAD (NOT reproducible)"
|
||||
}
|
||||
Write-Host "RynthSuite at commit: $(git -C $dest rev-parse HEAD)"
|
||||
|
||||
# ── Toolchain ─────────────────────────────────────────────────────────────
|
||||
- name: Setup .NET 9
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '9.0.x'
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Install Inno Setup 6
|
||||
run: choco install innosetup --yes --no-progress
|
||||
shell: pwsh
|
||||
|
||||
- name: Setup Python (for validation gates)
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
# ── Validation gates (fail the release before building if any trips) ───────
|
||||
# Gate 1: off-thread AC-mutator check — guards the off-thread-mutation AV
|
||||
# class (the root of the 2026-06 crash week). Pure source scan, no binary.
|
||||
# Gate 2: LootSdk golden tests — 60+ assertions on the loot-profile parser
|
||||
# that ships in the bundled plugin (run against the pinned RynthSuite).
|
||||
# Gate 3 (pe_pattern CHECK) is LOCAL-ONLY: it needs the 1.4 GB acclient.exe
|
||||
# that CI doesn't have, so it runs as a pre-deploy gate in Deploy-RynthCore.ps1.
|
||||
- name: Validation gates
|
||||
shell: pwsh
|
||||
run: |
|
||||
$parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent
|
||||
Write-Host "== Gate 1: off-thread AC-mutator check =="
|
||||
python "$env:GITHUB_WORKSPACE\tools\check_offthread_mutators.py"
|
||||
if ($LASTEXITCODE -ne 0) { throw "off-thread mutator gate FAILED — an AC mutator is reachable off the main thread" }
|
||||
|
||||
Write-Host "== Gate 2: LootSdk golden tests =="
|
||||
dotnet run --project "$parent\RynthSuite\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release
|
||||
if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" }
|
||||
|
||||
Write-Host "== Gate 3: pe_pattern CHECK — LOCAL ONLY =="
|
||||
Write-Host " (skipped in CI: needs the 1.4 GB acclient.exe; runs pre-deploy via Deploy-RynthCore.ps1)"
|
||||
|
||||
# ── Determine version ──────────────────────────────────────────────────────
|
||||
- name: Resolve version
|
||||
id: ver
|
||||
|
|
@ -99,18 +151,43 @@ jobs:
|
|||
body: |
|
||||
## Installation
|
||||
|
||||
1. Download **RynthBundle-Setup-${{ steps.ver.outputs.version }}.exe** below and run it
|
||||
2. Start Asheron's Call and log in to your character
|
||||
3. Open **RynthCore** from the Start Menu or Desktop shortcut
|
||||
4. Click **Inject Running AC** in the launcher
|
||||
5. The RynthAi panel will appear inside the AC window
|
||||
1. Download **RynthCore-Setup.exe** below and run it
|
||||
2. Open **RynthCore** from the Start Menu or Desktop shortcut
|
||||
|
||||
---
|
||||
|
||||
**First-time setup** — in the RynthCore launcher:
|
||||
- Set your `acclient.exe` path under **Runtime Paths** if prompted
|
||||
- The plugin auto-loads from `C:\Games\RynthCore\Runtime\Plugins\`
|
||||
## ⚠ Important first-time setup
|
||||
|
||||
Loot, nav, and meta profiles go in `C:\Games\RynthSuite\RynthAi\`
|
||||
### 1. Second AC client install (required for multi-client coexistence)
|
||||
|
||||
Log file: `%USERPROFILE%\Desktop\RynthCore.log`
|
||||
If you also play Asheron's Call through ThwargLauncher or another launcher, you **must** keep a separate copy of the AC client for RynthCore launches. Otherwise the two stacks fight over the same DAT files and one of them will fail with "cannot access the data files."
|
||||
|
||||
Run this once in PowerShell:
|
||||
|
||||
```powershell
|
||||
robocopy "C:\Turbine\Asheron's Call" "C:\Games\RynthCore\AcClient" /E /MT:8 /NFL /NDL /NJH /NJS /NP /XF "acclient_*.log" "acclient.log"
|
||||
```
|
||||
|
||||
Then in the RynthCore launcher, set **AC Client Path** to:
|
||||
```
|
||||
C:\Games\RynthCore\AcClient\acclient.exe
|
||||
```
|
||||
|
||||
(~1.4 GB extra disk. The two installs share `Documents\Asheron's Call\UserPreferences.ini` so multi-port stays in sync.)
|
||||
|
||||
### 2. Add the RynthAi plugin (opt-in)
|
||||
|
||||
The installer drops the plugin DLL at `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll`. The engine does **not** auto-scan a Plugins folder. To enable RynthAi:
|
||||
|
||||
- Open the launcher → **Plugins** tab → **Add Plugin DLL**
|
||||
- Browse to `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll`
|
||||
- Launch AC. The RynthAi panel appears inside the AC window.
|
||||
|
||||
Loot, nav, and meta profiles also live under `C:\Games\RynthSuite\RynthAi\`.
|
||||
|
||||
---
|
||||
|
||||
## Logs
|
||||
|
||||
- Unified RynthCore log: `C:\Games\RynthCore\Logs\RynthCore.log`
|
||||
- Crash dumps and engine init traces show up there with `[loader]`, `[engine]`, `[plugin]`, and `[compat]` tags.
|
||||
|
|
|
|||
9
.gitignore
vendored
9
.gitignore
vendored
|
|
@ -3,6 +3,8 @@
|
|||
**/obj/
|
||||
artifacts/
|
||||
TestResults/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
|
||||
# IDE and local tooling
|
||||
.vs/
|
||||
|
|
@ -42,5 +44,10 @@ scratch/
|
|||
# Installer build artifacts
|
||||
installer/staging/
|
||||
installer/Output/
|
||||
# Prior bundle installers archived on version bump (see installer/previous-release/last-built-version.txt)
|
||||
installer/Releases/
|
||||
|
||||
# Process Monitor / debug log dumps (session junk)
|
||||
*.PML
|
||||
Logfile*.XML
|
||||
# Archived installers (Build-Installer.ps1 keeps the previous release here; only the version marker is tracked)
|
||||
installer/previous-release/*.exe
|
||||
|
|
|
|||
202
BUILD.md
202
BUILD.md
|
|
@ -4,59 +4,78 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl
|
|||
|
||||
## Prerequisites
|
||||
|
||||
- Windows 10/11
|
||||
- .NET 9 SDK (x86)
|
||||
- Visual Studio 2022 Build Tools with the .NET desktop and C++ desktop workloads (required by the NativeAOT ILC linker)
|
||||
- Windows 10 or 11
|
||||
- **.NET 10 SDK (x86)**
|
||||
- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker)
|
||||
- Asheron's Call client installed
|
||||
|
||||
## Projects
|
||||
|
||||
| Project | Type | Output |
|
||||
|---------|------|--------|
|
||||
| `src/RynthCore.Engine` | NativeAOT x86 DLL | Injected into acclient.exe — hooks D3D9 EndScene, hosts ImGui overlay |
|
||||
| `src/RynthCore.Injector` | Console app | Injects the engine DLL via LoadLibrary + CreateRemoteThread |
|
||||
| `src/RynthCore.App.Avalonia` | Avalonia desktop app | Desktop launcher — server/account profiles, plugin management, launches + injects |
|
||||
| `src/RynthCore.PluginSdk` | Class library | Public host API surface for plugins |
|
||||
| `src/RynthCore.PluginCore` | Class library | Runtime helpers for plugin bootstrap/lifecycle |
|
||||
| `src/RynthCore.App` | Shared source | Model and service files linked by both the Avalonia app and the Engine (not a standalone project) |
|
||||
| `src/RynthCore.Loader` | NativeAOT x86 DLL | Injected into acclient.exe — owns `RynthCoreInit` export and hot-loads the Engine. |
|
||||
| `src/RynthCore.Engine` | NativeAOT x86 DLL | The runtime engine — pattern-scans `acclient.exe` hooks, hosts D3D9/ImGui overlay, runs plugins. |
|
||||
| `src/RynthCore.Injector` | x86 console | Standalone CLI injector via `LoadLibrary` + `CreateRemoteThread`. The launcher embeds the same `EngineInjectionService` directly. |
|
||||
| `src/RynthCore.App.Avalonia` | Avalonia desktop app | The launcher — server/account profiles, plugin management, suspended-launch + early-inject. |
|
||||
| `src/RynthCore.PluginSdk` | Class library | Public host API surface for plugins. |
|
||||
| `src/RynthCore.PluginCore` | Class library | `RynthPluginBase` + lifecycle dispatch helpers. |
|
||||
| `src/RynthCore.App` | Shared source | Service classes linked into both Engine and Avalonia launcher (not a standalone build target). |
|
||||
|
||||
All projects target **`net10.0-windows`**. NativeAOT projects (Loader, Engine, plugins) are `x86` only with `RuntimeIdentifier=win-x86` and `PublishAot=true`.
|
||||
|
||||
## Publish Commands
|
||||
|
||||
### Launcher (Avalonia)
|
||||
### Whole solution
|
||||
|
||||
```bash
|
||||
cd C:\Projects\RynthCore\src\RynthCore.App.Avalonia
|
||||
dotnet build -c Release
|
||||
```powershell
|
||||
dotnet build .\RynthCore.sln -c Release
|
||||
```
|
||||
|
||||
Output: `bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.dll`
|
||||
This compiles every project including the Loader (which is now in the .sln). Note: `dotnet build` is enough for the launcher and SDK projects, but **NativeAOT projects require `dotnet publish`** to actually produce the native DLL with exports — see below.
|
||||
|
||||
### Engine (NativeAOT — slow first build, ~2 min)
|
||||
### Loader (NativeAOT x86 — small, fast)
|
||||
|
||||
```powershell
|
||||
dotnet publish .\src\RynthCore.Loader\RynthCore.Loader.csproj -c Release
|
||||
```
|
||||
|
||||
Output: `src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Loader.dll`
|
||||
|
||||
### Engine (NativeAOT x86 — slow first build, ~2 min)
|
||||
|
||||
Requires `vswhere.exe` on PATH. If the build fails with `'vswhere.exe' is not recognized`, add the VS Installer directory:
|
||||
|
||||
```bash
|
||||
set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\Installer
|
||||
```powershell
|
||||
$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer"
|
||||
```
|
||||
|
||||
```bash
|
||||
cd C:\Projects\RynthCore\src\RynthCore.Engine
|
||||
dotnet publish -c Release
|
||||
```powershell
|
||||
dotnet publish .\src\RynthCore.Engine\RynthCore.Engine.csproj -c Release
|
||||
```
|
||||
|
||||
Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Engine.dll` (~26 MB)
|
||||
Output: `src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Engine.dll` (~26 MB)
|
||||
|
||||
### Launcher (Avalonia)
|
||||
|
||||
```powershell
|
||||
dotnet build .\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release
|
||||
```
|
||||
|
||||
Output: `src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.dll`
|
||||
|
||||
### RynthAi Plugin (NativeAOT — separate repo)
|
||||
|
||||
Always clean first — incremental builds can silently skip NativeAOT and produce a stale DLL.
|
||||
Always clean first — incremental NativeAOT builds can silently skip recompilation and produce a stale DLL.
|
||||
|
||||
```bash
|
||||
```powershell
|
||||
cd C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi
|
||||
rmdir /s /q obj\Release bin\Release 2>nul
|
||||
Remove-Item -Recurse -Force obj\Release, bin\Release -ErrorAction SilentlyContinue
|
||||
dotnet publish -c Release
|
||||
```
|
||||
|
||||
Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll` (~7 MB)
|
||||
Output: `bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll` (~7 MB)
|
||||
|
||||
The plugin's MSBuild target also copies the published DLL into the engine's `bin\...\Plugins\` folder so a freshly built engine picks it up automatically.
|
||||
|
||||
## Deploy
|
||||
|
||||
|
|
@ -64,82 +83,97 @@ Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll
|
|||
|
||||
```
|
||||
C:\Games\RynthCore\
|
||||
├── RynthCore.exe ← Launcher (renamed from RynthCore.App.Avalonia.exe)
|
||||
├── RynthCore.App.Avalonia.dll ← Launcher assembly
|
||||
├── RynthCore.exe ← Launcher (renamed from RynthCore.App.Avalonia.exe)
|
||||
├── RynthCore.App.Avalonia.dll ← Launcher assembly
|
||||
├── RynthCore.App.Avalonia.deps.json
|
||||
├── RynthCore.App.Avalonia.runtimeconfig.json
|
||||
├── Avalonia.*.dll ← Avalonia framework DLLs
|
||||
├── Avalonia.*.dll ← Avalonia framework DLLs
|
||||
└── Runtime\
|
||||
├── RynthCore.Engine.dll ← Engine (NativeAOT x86)
|
||||
├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint
|
||||
├── cimgui.dll ← ImGui C bindings (x86, docking branch)
|
||||
├── RynthCore.Loader.dll ← Loader (NativeAOT x86) — injection target
|
||||
├── RynthCore.Engine.dll ← Engine (NativeAOT x86)
|
||||
├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint
|
||||
├── cimgui.dll ← ImGui C bindings (x86, docking branch)
|
||||
└── Plugins\
|
||||
└── *.dll ← Plugin DLLs (built-in directory)
|
||||
└── *.dll ← Built-in plugin directory
|
||||
|
||||
C:\Games\RynthSuite\RynthAi\
|
||||
├── RynthCore.Plugin.RynthAi.dll ← RynthAi plugin (recommended deploy location)
|
||||
├── NavProfiles\ ← Navigation profiles
|
||||
├── LootProfiles\ ← Loot profiles
|
||||
└── Metas\ ← Meta files
|
||||
├── RynthCore.Plugin.RynthAi.dll ← RynthAi plugin (recommended deploy location)
|
||||
├── NavProfiles\ ← Navigation profiles
|
||||
├── LootProfiles\ ← Loot profiles
|
||||
└── Metas\ ← Meta files
|
||||
```
|
||||
|
||||
The injector's saved-path resolver prefers `Runtime\RynthCore.Loader.dll`. It falls back to `Runtime\RynthCore.Engine.dll` for legacy direct-load setups, and walks parent directories and sibling layouts (`Runtime\Engine\`, `Runtime\Native\`, etc.) so manual layouts continue to work.
|
||||
|
||||
### Deploy Launcher
|
||||
|
||||
The launcher can stay open while you replace its DLL.
|
||||
|
||||
```bash
|
||||
copy src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.dll C:\Games\RynthCore\
|
||||
copy src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.deps.json C:\Games\RynthCore\
|
||||
```powershell
|
||||
copy src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.dll C:\Games\RynthCore\
|
||||
copy src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.deps.json C:\Games\RynthCore\
|
||||
```
|
||||
|
||||
Restart the launcher after deploying.
|
||||
|
||||
### Deploy Engine
|
||||
### Deploy Loader + Engine
|
||||
|
||||
**AC must be closed** — the running client holds a file lock on the engine DLL.
|
||||
**AC must be closed** — the running client holds a file lock on the Loader and Engine DLLs.
|
||||
|
||||
```bash
|
||||
copy src\RynthCore.Engine\bin\Release\net9.0-windows\win-x86\publish\RynthCore.Engine.dll C:\Games\RynthCore\Runtime\
|
||||
```powershell
|
||||
copy src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Loader.dll C:\Games\RynthCore\Runtime\
|
||||
copy src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Engine.dll C:\Games\RynthCore\Runtime\
|
||||
```
|
||||
|
||||
If you only changed Engine source, you can deploy just `RynthCore.Engine.dll` and rely on the Loader's hot-reload to swap it in (click **RL** on the overlay bar with AC running).
|
||||
|
||||
### Deploy RynthAi Plugin
|
||||
|
||||
**AC can stay open** — plugins are shadow-copied at load time, so the file is not locked.
|
||||
|
||||
The recommended deploy location is `C:\Games\RynthSuite\RynthAi\` — alongside the plugin's data files. Add this path in the launcher's **Plugins** tab. Paths are persisted to `%AppData%\RynthCore\engine.json`.
|
||||
**Plugin discovery is opt-in:** the engine no longer auto-scans `Runtime\Plugins\` for DLLs. Plugins load only from paths the user has added via the launcher's **Plugins** tab → "Add Plugin DLL". Those paths are persisted to `%AppData%\RynthCore\engine.json` as `PluginPaths` and read by the engine on each (re)init.
|
||||
|
||||
```bash
|
||||
copy C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthSuite\RynthAi\
|
||||
Deploy the plugin DLL to its canonical home and add the full path in the launcher:
|
||||
|
||||
```
|
||||
C:\Games\RynthSuite\RynthAi\
|
||||
├── RynthCore.Plugin.RynthAi.dll ← add this path in launcher's Plugins tab
|
||||
├── NavProfiles\
|
||||
├── LootProfiles\
|
||||
└── Metas\
|
||||
```
|
||||
|
||||
Alternatively, deploy to the engine's built-in plugin directory:
|
||||
|
||||
```bash
|
||||
copy ... C:\Games\RynthCore\Runtime\Plugins\
|
||||
```powershell
|
||||
copy C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthSuite\RynthAi\
|
||||
```
|
||||
|
||||
After deploying a plugin with AC running, click **RL** on the RynthCore overlay bar to hot-reload.
|
||||
After deploying the DLL:
|
||||
|
||||
1. Open the RynthCore launcher
|
||||
2. **Plugins** tab → **Add Plugin DLL** → select `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll`
|
||||
3. Launch AC (cold start) — the engine picks up the new path on init.
|
||||
|
||||
If AC is already running, click **RL** on the RynthCore overlay bar to hot-reload the engine; it re-reads `engine.json` and loads the newly-added plugin path.
|
||||
|
||||
## Verify
|
||||
|
||||
| File | Expected Size | If Wrong |
|
||||
|------|--------------|----------|
|
||||
| `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — check for `Generating native code` in build output |
|
||||
| `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | If ~1 MB, you built the stale stub at `C:\Projects\RynthCore\Plugins\` instead of `C:\Projects\RynthSuite\Plugins\` |
|
||||
| `Runtime\RynthCore.Loader.dll` | small (~1–2 MB) | NativeAOT didn't run — check for `Generating native code` in build output |
|
||||
| `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — same diagnosis |
|
||||
| `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | Built `dotnet build` instead of `dotnet publish` |
|
||||
| `Runtime\cimgui.dll` | ~1.5 MB | Must match ImGui.NET 1.91.6.1 |
|
||||
|
||||
To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the `native\` directory.
|
||||
To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory.
|
||||
|
||||
## Installer
|
||||
|
||||
The `installer/` directory contains an Inno Setup script and a PowerShell build script that publishes the launcher, engine, **injector**, all discovered `RynthSuite` plugins, **ub-Rythai** (`RynthCore.Plugin.UbRythai`) when `..\ub-Rythai\` is present, and the RynthSuite tools, stages the output, and produces a single **`RynthBundle-Setup.exe`**.
|
||||
The `installer/` directory contains an Inno Setup script and a PowerShell build script that publishes all required projects, stages the output, and produces a single `RynthBundle-Setup.exe`.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [Inno Setup 6](https://jrsoftware.org/isdl.php) installed to the default location (`C:\Program Files (x86)\Inno Setup 6\`)
|
||||
- All build prerequisites listed above (matching .NET SDK for the solution, VS Build Tools for NativeAOT as needed)
|
||||
- **RynthCore.exe** and **Runtime\RynthCore.Injector.exe** are published **self-contained** (they bundle .NET 10 x86) — no separate Desktop Runtime install is required to run the launcher or injector from the install folder.
|
||||
- **LootEditor** and **MonsterEditor** remain framework-dependent (x64). If either fails to start, install [.NET Desktop Runtime 10 x64](https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime).
|
||||
- All build prerequisites listed above (.NET 10 SDK, VS Build Tools)
|
||||
|
||||
### Build the full release + installer (recommended)
|
||||
|
||||
|
|
@ -161,7 +195,7 @@ cd C:\Projects\RynthCore\installer
|
|||
.\Build-Installer.ps1 -Version 0.4.2
|
||||
```
|
||||
|
||||
This runs publish steps for launcher (self-contained x86) + engine (NativeAOT) + injector (self-contained x86) + all `RynthCore.Plugin.*` projects under RynthSuite, bundles the RynthSuite tools (`LootEditor`, `MonsterEditor`) as framework-dependent win-x64 apps (x64 runtime may be required for those two), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer.
|
||||
This runs `dotnet publish` for the Launcher, Loader, Engine, and RynthAi plugin (from RynthSuite), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer.
|
||||
|
||||
Output: `installer\Output\RynthBundle-Setup.exe` (or `installer\Output\RynthBundle-Setup-<version>.exe` when `-Version` is set — Inno **`OutputBaseFilename`** is versioned so the compile is not blocked by a locked `RynthBundle-Setup.exe`; the script then copies to the canonical name when possible).
|
||||
|
||||
|
|
@ -185,23 +219,45 @@ After a **successful** Inno compile, `last-built-version.txt` is updated to the
|
|||
|
||||
### What the installer does
|
||||
|
||||
- On **interactive** installs, shows an **advisory** wizard page after **Welcome** that checks for **.NET 10 (x64)** in the registry (see `RynthCore.iss` `[Code]`): **(1)** `Microsoft.WindowsDesktop.App` 10+ under `HKLM\SOFTWARE\dotnet\shared\...`, **(2)** `InstalledManifests\x64` keys containing `Manifest-10.`, **(3)** `sharedhost` **Version** 10+ under `SOFTWARE\dotnet\Setup\InstalledVersions\x64\` (and the parallel `SOFTWARE\Microsoft\dotnet\Setup\...` path). The same logic is implemented in C# as **`RynthCore.DesktopLog.NetDesktopX64Prerequisite`**; the launcher reports it in the activity line and `RynthCore-Launcher.log`. **Next is never disabled** for missing x64 runtime — install can complete; Loot/Monster may not start until you install the desktop/runtime from the linked page. On 32-bit Windows the page explains the tools are N/A. **Silent** installs skip that page.
|
||||
- Installs the launcher and injector (self-contained x86 — .NET 10 is bundled with `RynthCore.exe` and `RynthCore.Injector.exe`), the engine, and native dependencies under `C:\Games\RynthCore` (user-selectable; default matches this layout)
|
||||
- Installs all default `RynthSuite` plugin DLLs and **ub-Rythai** (when built) into `Runtime\Plugins` so they auto-load on first inject
|
||||
- Installs `RynthCore.LootEditor` and `RynthCore.MonsterEditor` into `Tools\` as framework-dependent apps (requires .NET Desktop Runtime x64).
|
||||
- Installs the launcher, loader, engine, and native dependencies to `C:\Games\RynthCore` (user-selectable)
|
||||
- Creates data directories under `C:\Games\RynthSuite\RynthAi\` (NavProfiles, LootProfiles, MetaFiles, etc.) — these are preserved on uninstall
|
||||
- Adds Start Menu and optional Desktop shortcuts
|
||||
- Warns if `acclient.exe` is running (the engine DLL would be locked)
|
||||
- Warns if `acclient.exe` is running (the engine + loader DLLs would be locked)
|
||||
- Shows getting-started instructions on the finish page
|
||||
|
||||
## Multi-Client Coexistence (with ThwargLauncher etc.)
|
||||
|
||||
If you also run AC through ThwargLauncher, aclauncher, or any other launcher that may not patch AC's `OpenDataFile` for shared access, the two stacks will fight over the same DAT files. Once one launcher's clients have the DATs locked exclusively, the other can't open them — symptom is **"cannot access the data files"** when launching from the second launcher.
|
||||
|
||||
**Required setup**: a second AC client install for RynthCore launches.
|
||||
|
||||
```
|
||||
C:\Turbine\Asheron's Call\ ← left untouched, used by ThwargLauncher etc.
|
||||
C:\Games\RynthCore\AcClient\ ← full copy of the AC client (~1.4 GB), used by RynthCore
|
||||
```
|
||||
|
||||
Setup:
|
||||
|
||||
```powershell
|
||||
robocopy "C:\Turbine\Asheron's Call" "C:\Games\RynthCore\AcClient" /E /MT:8 /NFL /NDL /NJH /NJS /NP `
|
||||
/XF "acclient_*.log" "acclient.log"
|
||||
```
|
||||
|
||||
Then in the RynthCore launcher:
|
||||
|
||||
1. Set **AC Client Path** to `C:\Games\RynthCore\AcClient\acclient.exe`
|
||||
2. Click somewhere else / save so the change persists
|
||||
|
||||
The two installs share `Documents\Asheron's Call\UserPreferences.ini` (it's user-scoped), so `ComputeUniquePort=True` applies to all instances regardless of which install they came from.
|
||||
|
||||
If your AC client ever gets a real-world patch, apply it to both copies (or `robocopy /MIR` to re-sync from the canonical install).
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`dotnet publish`, not `dotnet build` for Engine and Plugins.** NativeAOT only runs during `dotnet publish`. A `dotnet build` produces a valid managed DLL that compiles fine but has no unmanaged exports and will be silently ignored by the engine. The Avalonia launcher is the exception — `dotnet build` is fine since it's a normal .NET app.
|
||||
- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every publish to guarantee a fresh compile.
|
||||
- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\`. The injector resolves `Runtime\RynthCore.Engine.dll` by default.
|
||||
- **Two RynthAi projects exist.** The real plugin is at `C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\`. There is a stale stub at `C:\Projects\RynthCore\Plugins\RynthCore.Plugin.RynthAi\` — do not build or deploy from there.
|
||||
- **Engine publish copies a stale plugin** into the engine's publish output. Always deploy the plugin from the RynthSuite path last.
|
||||
- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes.
|
||||
- **vswhere.exe must be on PATH** for NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing.
|
||||
|
||||
|
||||
- **`dotnet publish`, not `dotnet build` for Loader, Engine, and plugins.** NativeAOT only runs during `dotnet publish`. A `dotnet build` produces a valid managed DLL that compiles fine but has no unmanaged exports and will be silently ignored. The Avalonia launcher is the exception — `dotnet build` is fine since it's a normal .NET app.
|
||||
- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile.
|
||||
- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default.
|
||||
- **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC.
|
||||
- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2.
|
||||
- **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing.
|
||||
- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm.
|
||||
|
|
|
|||
12
Changelog/2026-10-04-aelrynth-sync.md
Normal file
12
Changelog/2026-10-04-aelrynth-sync.md
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
# Changelog — 2026-10-04 (upstream snapshot)
|
||||
|
||||
## feat: port aelrynth git snapshot onto GitHub history
|
||||
|
||||
Applied `upstream/main` (`9b5e276`, RynthCore as of 2026-09-27, release 2026.9.27.2) as a new commit on top of BlankenshipG `main`. Histories are unrelated, so this is a tree overlay — not a fast-forward or force-replace.
|
||||
|
||||
- Added aelrynth-only product code: Loader, StatusAgent, HookManifest/HookResolver, DComp overlay, SEH trampoline, signed updater, vendor/trade API (PluginContract +16 functions)
|
||||
- Overlapping engine/launcher files taken from aelrynth (newer than origin 2026-04-25)
|
||||
- Kept unique origin-only trees: `Plugins/RynthAi/` (Decal-era), `Plugins/RynthCore.Plugin.RynthAi/` stub, `AGENTS.md`/`CLAUDE.md`, `ImGuiController.cs`, `OverlayFrameBuffer.cs`
|
||||
- Re-applied dead-link fixes: installer + CI clone URLs point at aelrynth.com / `${{ github.repository_owner }}` siblings
|
||||
|
||||
No PluginSdk version bump (still 0.2.0 on both trees). Packaged aelrynth installer (2026.10.4.3) is newer than this git tip.
|
||||
9
Changelog/2026-10-04-aelrynth-urls.md
Normal file
9
Changelog/2026-10-04-aelrynth-urls.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# Changelog — 2026-10-04 (docs/CI)
|
||||
|
||||
## fix: point dead tombohar URLs at aelrynth / sibling fork
|
||||
|
||||
- `installer/RynthCore.iss` `AppPublisherURL` → https://aelrynth.com/rynth.html
|
||||
- `.github/workflows/release.yml` sibling clone → `github.com/${{ github.repository_owner }}/RynthSuite`
|
||||
- Canonical public git remains https://aelrynth.com/git/RynthCore.git (see product page)
|
||||
|
||||
No engine/SDK version bump (docs and CI URL-only).
|
||||
68
Changelog/2026-10-04-full-installer-2026.10.4.2.md
Normal file
68
Changelog/2026-10-04-full-installer-2026.10.4.2.md
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
# RynthCore 2026.10.4.2: full RynthCore + RynthSuite installer
|
||||
|
||||
**Release date:** 2026-10-04
|
||||
**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.2.exe` (also copied to `RynthCore-Setup.exe`)
|
||||
**Previous release:** `2026.10.4.1` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.1.exe`)
|
||||
**Branch:** `feat/full-installer` (local test build, not on `main`), based on `fix/tmds-dbus-advisory`
|
||||
**Bundled RynthSuite:** RynthAi `0.5.3`, Loot Editor, Monster Editor (from RynthSuite `feat/ilt-hub`)
|
||||
|
||||
## Why: the launcher would not start
|
||||
|
||||
On 2026-10-04 an old **RynthBundle 0.4.7** installer was run over the 2026.10.3.4 install. It replaced
|
||||
`RynthCore.App.Avalonia.dll` with the 0.4.x build, which needs `RynthCore.DesktopLog.dll`, but left the newer
|
||||
`RynthCore.App.Avalonia.deps.json`, which does not list it. The renamed apphost (`RynthCore.exe`) loads exactly
|
||||
what the deps.json lists, so .NET failed at startup with `FileNotFoundException: RynthCore.DesktopLog`
|
||||
(Event Log, .NET Runtime 1026). The new installer fixes such an install in place (see **Cleanup** below).
|
||||
|
||||
## One installer, two folders you choose
|
||||
|
||||
- **Wizard pages:**
|
||||
- **Select Destination Location** picks the RynthCore folder (default `C:\Games\RynthCore`).
|
||||
- **Select Components** offers Full, RynthCore only, or Custom. RynthCore is always installed; RynthAi and the
|
||||
Monster Editor are optional.
|
||||
- **Select RynthSuite Location** picks the RynthSuite folder. It defaults to a `RynthSuite` folder next to
|
||||
the RynthCore folder you picked, or the folder used last time. The page is skipped when no Suite component is selected.
|
||||
- **Silent installs:** `RynthCore-Setup-2026.10.4.2.exe /SILENT /DIR="D:\Games\RynthCore" /SUITEDIR="D:\Games\RynthSuite"`.
|
||||
Without `/SUITEDIR` the Suite goes next to `/DIR`, or to the previously used folder.
|
||||
- **Registry:** both folders are written to `Software\Rynth` (`CoreDir`, `SuiteDir`). That is HKCU for per-user installs
|
||||
and HKLM for all-users installs. All of RynthCore and RynthSuite now read them.
|
||||
- **Plugin auto-registration:** the installer leaves `PendingPluginRegistration` with the RynthAi DLL path. On the next
|
||||
start the launcher adds it to the Plugins list (replacing any stale entry with the same file name whose file is gone),
|
||||
syncs `engine.json` and clears the value. A fresh install therefore loads RynthAi with no manual setup.
|
||||
- **Shortcuts:** RynthCore, Loot Editor, Monster Editor, RynthSuite folder, Uninstall, and an optional desktop icon.
|
||||
|
||||
### Cleanup of older layouts
|
||||
Before copying, the installer deletes leftovers from 0.4.x and RynthBundle installs in the RynthCore folder:
|
||||
root `*.dll`/`*.json`/`*.pdb`, `RynthCore.App.Avalonia.exe`, old `Runtime\*.dll`/`*.json`, `Runtime\RynthCore.Injector.exe`
|
||||
and `Runtime\Plugins\`. Then it lays down a complete, matching set. User data (`Logs`, settings in `%APPDATA%\RynthCore`,
|
||||
everything under `<SuiteDir>\RynthAi`) is never touched, and the RynthSuite data folders survive an uninstall.
|
||||
|
||||
## Code: no more hard-coded `C:\Games\...`
|
||||
|
||||
New `src/RynthCore.App/RynthInstallPaths.cs`, linked into the launcher, engine, loader, injector and status agent.
|
||||
It resolves the folders in this order: `RYNTHCORE_DIR`/`RYNTHSUITE_DIR` environment variables, then HKCU, then HKLM
|
||||
(32-bit view), then the old `C:\Games\...` defaults. It uses a direct `RegGetValueW` P/Invoke, so it is NativeAOT-safe.
|
||||
The engine resolves it on its init worker, never under the loader lock.
|
||||
|
||||
| Was | Now |
|
||||
|---|---|
|
||||
| `C:\Games\RynthCore\Logs` (launcher, loader, injector, engine) | `<CoreDir>\Logs` |
|
||||
| `C:\Games\RynthCore\AcClient\acclient.exe` (injector) | `<CoreDir>\AcClient\acclient.exe` |
|
||||
| `C:\Games\RynthSuite\RynthAi\imgui.ini`, MetaFiles | `<SuiteDir>\RynthAi\...` |
|
||||
| Status agent defaults | derived from the resolved folders |
|
||||
|
||||
## Build script (`installer\Build-Installer.ps1`)
|
||||
- **Publishes:** launcher, Engine, Loader, the RynthAi plugin, the Loot Editor, and now the **Monster Editor**
|
||||
(self-contained win-x86).
|
||||
- **Staging:** RynthCore goes to `staging\core`, RynthSuite to `staging\suite\RynthAi` (plugin plus `MonsterEditor\`).
|
||||
- **Versions:** the RynthAi plugin is no longer stamped with the installer version. It keeps its own semantic version
|
||||
(0.5.3), and everything else gets `-p:Version=<installer version>`.
|
||||
- **New check:** every project assembly listed in the launcher's `deps.json` must be staged next to it. This guards
|
||||
directly against the DesktopLog failure above.
|
||||
- **Previous release:** `installer\previous-release\last-built-version.txt` tracks the last build. When the version
|
||||
changes, that build's installer is archived to `previous-release\` (git-ignored) before the new one is built.
|
||||
- **Output:** `RynthCore-Setup-<version>.exe`, plus a `RynthCore-Setup.exe` copy.
|
||||
|
||||
## Not included
|
||||
RynthChat, RynthJuice, RynthNav, RynthTracker and RynthVision are experimental and stay out of the installer.
|
||||
RynthNav and RynthJuice still hard-code `C:\Games\RynthCore`.
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
# RynthCore 2026.10.4.3: experimental plugins as optional installer components
|
||||
|
||||
**Release date:** 2026-10-04
|
||||
**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.3.exe` (also copied to `RynthCore-Setup.exe`)
|
||||
**Previous release:** `2026.10.4.2` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.2.exe`)
|
||||
**Branch:** `feat/full-installer` (local test build, not on `main`)
|
||||
|
||||
## What's new
|
||||
|
||||
The **Select Components** page has a new **RynthSuite: Experimental plugins** group. Each plugin is unchecked by
|
||||
default in every install type; ticking one switches the install to Custom.
|
||||
|
||||
| Component | Installs to | Version |
|
||||
|---|---|---|
|
||||
| `experimental\rynthchat` | `<RynthSuite>\RynthChat\RynthCore.Plugin.RynthChat.dll` | 0.1.1 |
|
||||
| `experimental\rynthjuice` | `<RynthSuite>\RynthJuice\RynthCore.Plugin.RynthJuice.dll` | 0.1.1 |
|
||||
| `experimental\rynthnav` | `<RynthSuite>\RynthNav\RynthCore.Plugin.RynthNav.dll`, plus `<RynthCore>\NavData\` | 0.5.5 |
|
||||
| `experimental\rynthtracker` | `<RynthSuite>\RynthTracker\RynthCore.Plugin.RynthTracker.dll` | 0.1.1 |
|
||||
| `experimental\rynthvision` | `<RynthSuite>\RynthVision\RynthCore.Plugin.RynthVision.dll` | 0.1.1 |
|
||||
|
||||
- **Registration:** every selected plugin (RynthAi included) goes into `Software\Rynth\PendingPluginRegistration`
|
||||
as a `;`-separated list. On next start the launcher adds them all to its Plugins list and syncs `engine.json`.
|
||||
- **Suite folder page:** shown whenever any RynthSuite component is selected, experimental ones included.
|
||||
- **RynthNav data:** the installer creates `<RynthCore>\NavData` (kept on uninstall). It ships the starter
|
||||
`portals.tsv` from `RynthNav.PortalGraph` only when that folder has none, so a newer generated file is never overwritten.
|
||||
Navmesh tiles (`nav_XXXX.tile`) are **not** shipped; bake them with `RynthNav.Baker --tiled` (its default output
|
||||
is `C:\Games\RynthCore\NavData`; pass `--out` for a different RynthCore folder).
|
||||
- **Silent installs:** pick components with `/COMPONENTS`, for example
|
||||
`/COMPONENTS="core,rynthai,monstereditor,experimental\rynthnav,experimental\rynthvision"`.
|
||||
|
||||
## Build script (`installer\Build-Installer.ps1`)
|
||||
- New step **7/7** publishes the five plugins (NativeAOT, x86), each keeping its own version.
|
||||
- RynthJuice, RynthNav and RynthVision set `<PublishDir>` to the live `C:\Games\RynthSuite\<Name>\` for dev hot-reload.
|
||||
The build overrides it to each project's `bin\...\publish\`, so building an installer never touches a live install.
|
||||
- Staging: `staging\suite\<Name>\` per plugin and `staging\navdata\portals.tsv`. All of them are in the required-files check.
|
||||
|
||||
## Upgrade notes
|
||||
- Re-running the installer without an experimental plugin does not remove one installed earlier. Uninstall
|
||||
RynthCore, or delete `<RynthSuite>\<Name>\` and its row in the launcher's Plugins tab.
|
||||
- These plugins are work in progress and may change or break between builds.
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
# RynthCore 2026.10.4.4: .NET 10 check with automatic download and install
|
||||
|
||||
**Release date:** 2026-10-04
|
||||
**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.4.exe` (also copied to `RynthCore-Setup.exe`)
|
||||
**Previous release:** `2026.10.4.3` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.3.exe`)
|
||||
**Branch:** `feat/full-installer` (local test build, not on `main`)
|
||||
|
||||
## Installer: .NET 10 Desktop Runtime (x86)
|
||||
|
||||
- **Detection:** setup looks for a 10.x `Microsoft.WindowsDesktop.App` under `Program Files (x86)\dotnet\shared\`, or its
|
||||
registration in `HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App` (32-bit view).
|
||||
x86 matches RynthCore's x86 launcher and tools. The Desktop Runtime also contains the base .NET runtime.
|
||||
- **When it's missing,** the Tasks page shows a **Prerequisites** task, checked by default: *Download and install the
|
||||
Microsoft .NET 10 Desktop Runtime (x86)*. When the runtime is already there, the task is not shown at all.
|
||||
- **Install:** on leaving the Ready page, setup downloads the latest 10.x runtime from Microsoft
|
||||
(`https://aka.ms/dotnet/10.0/windowsdesktop-runtime-win-x86.exe`, about 55 MB) with a progress page, then runs it
|
||||
with `/install /quiet /norestart`. The runtime's own installer asks for administrator approval (UAC) when setup
|
||||
isn't elevated.
|
||||
- **Silent installs** run the same step just before the files are copied, without a progress page. Skip it with
|
||||
`/MERGETASKS="!installdotnet"`. That's useful offline, or for the launcher's silent self-update when no one is
|
||||
there to approve UAC.
|
||||
- **Never blocking:** exit codes 0, 3010, 1641 and 1638 (a newer runtime is already installed) count as success. A
|
||||
failed download, a cancelled UAC prompt (1602) or any other error is logged and shown in a message box with the
|
||||
manual download link, and the RynthCore install carries on.
|
||||
|
||||
Why it isn't required: the launcher, Loot Editor and Monster Editor are self-contained (they bundle .NET 10.0.5), and the
|
||||
engine, loader and plugins are NativeAOT. The shared runtime is a safety net for framework-dependent add-ons and tools.
|
||||
Earlier blocking .NET pages (0.4.x) had to be made advisory for exactly this reason.
|
||||
|
||||
## Build script: .NET 10 SDK
|
||||
|
||||
`Build-Installer.ps1` needs a .NET 10 SDK to publish, so before building (skipped with `-SkipBuild`) it:
|
||||
1. uses the `dotnet` on PATH if it lists a 10.x SDK;
|
||||
2. otherwise reuses an earlier per-user install in `%LOCALAPPDATA%\Microsoft\dotnet`;
|
||||
3. otherwise downloads Microsoft's `dotnet-install.ps1`, **checks its Authenticode signature** (must be valid and signed
|
||||
by Microsoft Corporation), and installs the latest 10.0 SDK per-user. No admin is needed. Then it uses that SDK for the
|
||||
rest of the build (`DOTNET_ROOT` and `PATH` are set for this session only).
|
||||
|
||||
Pass `-NoDotNetInstall` to fail with a download link instead of installing.
|
||||
|
||||
**Tested:** in an isolated session with no `dotnet` on PATH, the script verified the signature, installed SDK 10.0.401 to
|
||||
a scratch folder and found it again on a second run without re-downloading.
|
||||
|
||||
NativeAOT publishing also needs the Visual Studio C++ build tools ("Desktop development with C++"). The script doesn't
|
||||
install those.
|
||||
|
||||
## Not tested end to end
|
||||
The runtime download and install path in the installer was compiled but not run on the build machine. That machine already
|
||||
has the x86 Desktop Runtime 10.0.7, so the task stays hidden there. Running it would have meant installing 10.0.12
|
||||
machine-wide.
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
# RynthCore 2026.10.4.5: installer only reuses a RynthSuite folder from the same install mode
|
||||
|
||||
**Release date:** 2026-10-04
|
||||
**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.5.exe` (also copied to `RynthCore-Setup.exe`)
|
||||
**Previous release:** `2026.10.4.4` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.4.exe`). Don't
|
||||
use 2026.10.4.4 for a per-user install on a machine that also has an all-users install (see below).
|
||||
**Branch:** `feat/full-installer` (local test build, not on `main`)
|
||||
|
||||
## Fix
|
||||
|
||||
To pre-fill the **Select RynthSuite Location** page, the installer used to read `Software\Rynth\SuiteDir` from HKCU **and
|
||||
then HKLM**. A per-user install on a machine that already had an all-users install therefore adopted the all-users
|
||||
RynthSuite folder. The two installs then shared those files, and **uninstalling the per-user install deleted the
|
||||
all-users install's RynthAi DLL and Monster Editor.**
|
||||
|
||||
The lookup now reads only the hive of the current install mode (Inno's `HKA`: HKCU for per-user, HKLM for all-users),
|
||||
matching how `GetPreviousData` and `UsePreviousAppDir` already behave. A per-user install with no per-user history
|
||||
defaults to a `RynthSuite` folder next to its RynthCore folder again.
|
||||
|
||||
The runtime resolver (`RynthInstallPaths`: HKCU, then HKLM) is unchanged. A per-user install's own values still
|
||||
take precedence for that user.
|
||||
|
||||
## Found by
|
||||
A per-user test install of 2026.10.4.4 into a scratch folder on the build machine, which had an all-users 2026.10.4.3
|
||||
install in `C:\Games`. The test install wrote into `C:\Games\RynthSuite` and its uninstall removed
|
||||
`RynthAi\RynthCore.Plugin.RynthAi.dll` and the Monster Editor. Both were restored right away from the same-source build
|
||||
(RynthAi 0.5.3, 217 Monster Editor files). User data folders, the experimental plugins and `C:\Games\RynthCore` were not affected.
|
||||
|
||||
## Also in this build
|
||||
Everything from 2026.10.4.4: the .NET 10 Desktop Runtime check with automatic download and install in the installer,
|
||||
and the .NET 10 SDK check with per-user auto-install in `Build-Installer.ps1`.
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
# Installer 2026.10.4.6 — RynthAi tool launch buttons
|
||||
|
||||
**Date:** 2026-10-04
|
||||
**Branch:** `feat/full-installer` (testing only — not merged to `main`)
|
||||
|
||||
## Changes
|
||||
- Bundles **RynthAi 0.5.4**, which adds **Loot Editor** and **Monster Editor** launch buttons to the
|
||||
in-game Items window and the Advanced Settings → Looting page. No more launching the editors from
|
||||
the shell or Explorer while playing.
|
||||
- No installer script changes; tool locations are unchanged (`<CoreDir>\Tools\LootEditor`,
|
||||
`<SuiteDir>\RynthAi\MonsterEditor`), and RynthAi finds them through the registered install paths.
|
||||
|
||||
## Build
|
||||
- `installer\Build-Installer.ps1 -Version 2026.10.4.6`
|
||||
- Previous installer archived: `installer\previous-release\RynthCore-Setup-2026.10.4.5.exe`
|
||||
- Output: `installer\Output\RynthCore-Setup-2026.10.4.6.exe`
|
||||
26
Changelog/2026-10-04-tmds-dbus-advisory.md
Normal file
26
Changelog/2026-10-04-tmds-dbus-advisory.md
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# Security: pin Tmds.DBus.Protocol 0.21.3 (NU1903)
|
||||
|
||||
**Date:** 2026-10-04
|
||||
**Branch:** `fix/tmds-dbus-advisory` (based on `main`; not merged)
|
||||
**Advisory:** NU1903 / [GHSA-xrw6-gwf8-vvr9](https://github.com/advisories/GHSA-xrw6-gwf8-vvr9) (high severity)
|
||||
|
||||
## Problem
|
||||
Avalonia 11.x (through `Avalonia.FreeDesktop`) depends on `Tmds.DBus.Protocol` 0.20.x, which has a
|
||||
known vulnerability. NuGet restore reported NU1903 for every project that references Avalonia.
|
||||
|
||||
## Fix
|
||||
A direct `PackageReference` to `Tmds.DBus.Protocol` **0.21.3** overrides the vulnerable transitive version:
|
||||
|
||||
- `src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj`
|
||||
- `src/RynthCore.Engine/RynthCore.Engine.csproj`
|
||||
|
||||
The same pin is in RynthSuite (`Tools/RynthCore.LootEditor`, `Tools/RynthCore.MonsterEditor`) on `feat/ilt-hub`.
|
||||
|
||||
## Verification
|
||||
- `dotnet restore` / `dotnet list package --include-transitive` resolve `Tmds.DBus.Protocol 0.21.3` in all projects.
|
||||
- No NU190x warnings remain.
|
||||
- RynthAi 0.5.2 builds and publishes (NativeAOT) against this branch.
|
||||
|
||||
## Notes
|
||||
- No runtime behaviour change on Windows. D-Bus is only used by Avalonia on Linux desktops.
|
||||
- Drop the explicit pin once Avalonia ships a release that depends on a fixed version.
|
||||
93
README.md
93
README.md
|
|
@ -1,60 +1,70 @@
|
|||
# RynthCore
|
||||
|
||||
RynthCore is a modern .NET 9 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, an injector, a desktop launcher, and a plugin surface.
|
||||
RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API.
|
||||
|
||||
The project is currently focused on three things:
|
||||
The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/rynth.html) (`git clone https://aelrynth.com/git/RynthSuite.git`).
|
||||
|
||||
- launching and injecting the RynthCore engine into `acclient.exe`
|
||||
- hosting in-game UI through an embedded overlay stack
|
||||
- building a RynthCore-native plugin API with hooks for chat, combat, targeting, movement, object, and UI events
|
||||
## What it does
|
||||
|
||||
- Launches `acclient.exe` (suspended if needed) and injects the RynthCore loader
|
||||
- Hosts in-game UI through an embedded ImGui overlay, with a parallel Avalonia overlay stack for floating panels (and for Decal coexistence mode where ImGui is disabled)
|
||||
- Exposes a growing plugin host API with hooks for chat, combat, targeting, movement, object lifecycle, vendor/trade, vitals, enchantments, and UI events
|
||||
- Hot-reloads plugin DLLs without restarting AC; hot-reloads the engine itself via the loader DLL
|
||||
- Detects Decal/UBService/VTank coexistence and degrades gracefully (skips D3D9 path, drives plugin tick from a worker thread)
|
||||
|
||||
## Solution layout
|
||||
|
||||
The repository currently ships these main projects:
|
||||
|
||||
- `src/RynthCore.Engine` - x86 NativeAOT runtime injected into the game client
|
||||
- `src/RynthCore.Injector` - process launch and DLL injection service
|
||||
- `src/RynthCore.App` - Windows desktop launcher
|
||||
- `src/RynthCore.App.Avalonia` - Avalonia launcher preview and profile manager
|
||||
- `src/RynthCore.PluginSdk` - public host API surface for plugins
|
||||
- `src/RynthCore.PluginCore` - runtime helpers for plugin bootstrap/lifecycle
|
||||
- `Plugins/RynthCore.Plugin.HelloBox` - sample plugin used for end-to-end testing
|
||||
|
||||
## Current capabilities
|
||||
|
||||
- injects `RynthCore.Engine.dll` into the x86 Asheron's Call client
|
||||
- hosts overlay panels inside the game process
|
||||
- includes launcher/profile flows for servers, accounts, and saved launch targets
|
||||
- exposes a growing plugin host API for chat, target, combat, movement, object, and UI-related hooks
|
||||
- includes legal guardrails and hook planning docs
|
||||
```
|
||||
RynthCore.sln
|
||||
├── src/RynthCore.Loader x86 NativeAOT DLL — injection target.
|
||||
│ Owns RynthCoreInit; loads + reloads
|
||||
│ the Engine.
|
||||
├── src/RynthCore.Engine x86 NativeAOT DLL — the runtime
|
||||
│ injected into acclient.exe. Pattern-
|
||||
│ scanned hooks, D3D9 + ImGui + Avalonia
|
||||
│ overlays, plugin manager, crash logger.
|
||||
├── src/RynthCore.Injector x86 console — Win32 LoadLibrary +
|
||||
│ CreateRemoteThread injector with a
|
||||
│ suspended-launch / early-inject path.
|
||||
├── src/RynthCore.App.Avalonia Desktop launcher (Avalonia 11.2.3,
|
||||
│ Fluent theme). Profile management,
|
||||
│ server status, launches and injects.
|
||||
├── src/RynthCore.App Shared service classes linked into
|
||||
│ both Engine and Avalonia launcher
|
||||
│ via <Compile Include /> — not built
|
||||
│ standalone.
|
||||
├── src/RynthCore.PluginSdk Public host API surface for plugins.
|
||||
└── src/RynthCore.PluginCore RynthPluginBase + lifecycle helpers.
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Windows
|
||||
- .NET 9 SDK
|
||||
- Visual Studio 2022 with the .NET desktop and C++ desktop workloads
|
||||
- Windows 10 or 11
|
||||
- **.NET 10 SDK (x86)**
|
||||
- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (the C++ tools are required by the NativeAOT ILC linker)
|
||||
- Asheron's Call client installed (default: `C:\Turbine\Asheron's Call\`)
|
||||
|
||||
The engine project targets `win-x86` and uses NativeAOT. A bundled `cimgui.dll` is included under `src/RynthCore.Engine/Native/`.
|
||||
The Engine, Loader, and plugin projects target `net10.0-windows` with `RuntimeIdentifier=win-x86` and `PublishAot=true`. A bundled `cimgui.dll` ships under `src/RynthCore.Engine/Native/`.
|
||||
|
||||
## Build
|
||||
|
||||
From the repository root:
|
||||
|
||||
```powershell
|
||||
$env:DOTNET_CLI_HOME = "$PWD\\.dotnet-home"
|
||||
$env:DOTNET_CLI_HOME = "$PWD\.dotnet-home"
|
||||
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
|
||||
dotnet build .\RynthCore.sln -c Release
|
||||
```
|
||||
|
||||
To publish the main runtime pieces individually:
|
||||
To publish the runtime pieces individually (use **`publish`**, not `build`, for any NativeAOT project):
|
||||
|
||||
```powershell
|
||||
dotnet publish .\src\RynthCore.Loader\RynthCore.Loader.csproj -c Release
|
||||
dotnet publish .\src\RynthCore.Engine\RynthCore.Engine.csproj -c Release
|
||||
dotnet publish .\src\RynthCore.App\RynthCore.App.csproj -c Release -r win-x86
|
||||
dotnet publish .\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release
|
||||
```
|
||||
|
||||
For a clean local deployment, keep the launcher at the top level of `C:\Games\RynthCore` and place the injectable engine payload under `C:\Games\RynthCore\Runtime\`. The injector now resolves `Runtime\RynthCore.Engine.dll` by default, which keeps the game folder tidier while still allowing manual overrides.
|
||||
For a clean local deployment, keep the launcher at the top level of `C:\Games\RynthCore\` and place the injectable engine and loader payloads under `C:\Games\RynthCore\Runtime\`. The injector's saved-path resolver prefers `Runtime\RynthCore.Loader.dll`, falls back to `Runtime\RynthCore.Engine.dll` for legacy direct-load setups, and walks up sibling directories so manual layouts still work.
|
||||
|
||||
You can produce that layout with:
|
||||
|
||||
|
|
@ -62,18 +72,21 @@ You can produce that layout with:
|
|||
.\scripts\Deploy-RynthCore.ps1
|
||||
```
|
||||
|
||||
For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`](BUILD.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- `BUILD.md` — full build, deploy, and installer instructions
|
||||
- `CLAUDE.md` — project memory file (architecture orientation, technical facts, common pitfalls)
|
||||
- `docs/ACCLIENT_HOOK_INVENTORY.md` — hook target inventory against the user's live `acclient.exe`
|
||||
- `docs/PLUGIN_HOOK_MATRIX.md` — clean-room hook surface matrix
|
||||
- `docs/LEGAL_COMPATIBILITY.md` — project policy on Decal/VTank compatibility
|
||||
- `docs/archive/` — archived plans and one-off utilities
|
||||
|
||||
## Repository notes
|
||||
|
||||
- local settings and machine-specific files are ignored through `.gitignore`
|
||||
- generated `bin/`, `obj/`, `.vs/`, and `.dotnet-home/` content should not be committed
|
||||
- launcher data such as profiles and runtime state is expected to live outside the repository
|
||||
- compatibility planning and legal guardrails live in `docs/`
|
||||
|
||||
See:
|
||||
|
||||
- `docs/ACCLIENT_HOOK_INVENTORY.md`
|
||||
- `docs/PLUGIN_HOOK_MATRIX.md`
|
||||
- `docs/LEGAL_COMPATIBILITY.md`
|
||||
- Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore`
|
||||
- Plugin code lives in the [RynthSuite](https://aelrynth.com/rynth.html) repo as a sibling clone (`git clone https://aelrynth.com/git/RynthSuite.git`)
|
||||
|
||||
## Security and secrets
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
|
|
@ -9,7 +9,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\R
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DesktopLog", "src\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj", "{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Plugin.RynthAi", "Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj", "{A1B2C3D4-0005-0005-0005-000000000005}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
|
|
@ -19,6 +19,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.PluginSdk", "src\
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.PluginCore", "src\RynthCore.PluginCore\RynthCore.PluginCore.csproj", "{A72E31D3-5D91-4C39-A30C-A96A492BBE82}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookManifest", "src\RynthCore.HookManifest\RynthCore.HookManifest.csproj", "{C1A2B3D4-0007-0007-0007-000000000007}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.StatusAgent", "src\RynthCore.StatusAgent\RynthCore.StatusAgent.csproj", "{A1B2C3D4-000A-000A-000A-00000000000A}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core", "tools\HookResolver.Core\RynthCore.HookResolver.Core.csproj", "{C1A2B3D4-0008-0008-0008-000000000008}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x86 = Debug|x86
|
||||
|
|
@ -65,18 +75,18 @@ Global
|
|||
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|x86.Build.0 = Debug|x86
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|x86.ActiveCfg = Release|x86
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|x86.Build.0 = Release|x86
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-0005-0005-0005-000000000005}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|x86.ActiveCfg = Release|x86
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|x86.Build.0 = Release|x86
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-0006-0006-0006-000000000006}.Release|x64.Build.0 = Release|Any CPU
|
||||
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
|
|
@ -113,6 +123,54 @@ Global
|
|||
{A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x86.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|x86.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0008-0008-0008-000000000008}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x86.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
@ -122,5 +180,8 @@ Global
|
|||
{BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
|
||||
{C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
|
|
|||
225
docs/STATUS_AGENT.md
Normal file
225
docs/STATUS_AGENT.md
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
# RynthCore Status Agent
|
||||
|
||||
Surface live RynthCore client status (running / in-world / actively botting,
|
||||
plus fps, plugin-pump rate, memory, vitals) to an external app — e.g. a phone
|
||||
dashboard — so you can confirm a multi-box session is healthy without remoting
|
||||
into the PC.
|
||||
|
||||
It is built in two deliberately separated halves:
|
||||
|
||||
1. **Engine status export** — opt-in, **default OFF**. When enabled, the engine
|
||||
writes a small **local** JSON file per client. It never opens a network
|
||||
connection.
|
||||
2. **`RynthCore.StatusAgent.exe`** — a separate, optional program that runs **on
|
||||
your own PC**, reads those local files, and forwards a rolled-up payload to
|
||||
**an endpoint you configure**. It is not injected into the game, not in the
|
||||
installer, and sends nothing until you give it a URL.
|
||||
|
||||
---
|
||||
|
||||
## Privacy / "this isn't spyware"
|
||||
|
||||
This feature is designed so that distributing RynthCore to other people changes
|
||||
nothing for them unless they explicitly turn it on, and even then nothing leaves
|
||||
their machine:
|
||||
|
||||
- **Default off.** With `EnableStatusExport` absent or `false`, the engine writes
|
||||
no status file and behaves exactly as before.
|
||||
- **No telemetry from the game.** `acclient.exe` / the engine never opens a
|
||||
socket for this feature. The most it ever does is write a local file under
|
||||
`C:\Games\RynthCore\Logs\status\`, right next to the logs it already writes.
|
||||
- **The network half runs on the operator's PC, by the operator.** Only
|
||||
`RynthCore.StatusAgent.exe` makes outbound requests, only to the URL **you**
|
||||
put in **your** config, and only while you choose to run it. With no URL set it
|
||||
runs in local print-only mode and sends nothing.
|
||||
- **Nothing is bundled.** The installer does not ship or auto-start the agent.
|
||||
|
||||
If you hand RynthCore to someone else, they get the default-off engine and no
|
||||
agent — there is no path by which your build reaches into their PC.
|
||||
|
||||
---
|
||||
|
||||
## Turning it on (operator setup)
|
||||
|
||||
### 1. Enable the engine status export
|
||||
|
||||
Add to **your** `%APPDATA%\RynthCore\engine.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"EnableStatusExport": true
|
||||
}
|
||||
```
|
||||
|
||||
(Or set the env var `RYNTHCORE_STATUS_EXPORT=1` before launching AC for a
|
||||
one-session test without editing the file.) Picked up on next client launch.
|
||||
|
||||
The engine then writes, once per second, per running client:
|
||||
|
||||
```
|
||||
C:\Games\RynthCore\Logs\status\RynthCore.<pid>.status.json
|
||||
```
|
||||
|
||||
### 2. Build and run the agent
|
||||
|
||||
```powershell
|
||||
dotnet publish .\src\RynthCore.StatusAgent\RynthCore.StatusAgent.csproj -c Release
|
||||
.\src\RynthCore.StatusAgent\bin\Release\net10.0-windows\RynthCore.StatusAgent.exe
|
||||
```
|
||||
|
||||
On first run it writes a config template to
|
||||
`%APPDATA%\RynthCore\statusagent.json` and runs in **local print-only mode**
|
||||
(reads + prints status, sends nothing) until you set an endpoint.
|
||||
|
||||
Useful flags: `--once` (one cycle then exit), `--dry-run` (read + print, never
|
||||
POST), `--verbose` (print the full payload), `--interval N`, `--config PATH`,
|
||||
`--help`.
|
||||
|
||||
To keep it running unattended, launch it at login (Task Scheduler "At log on",
|
||||
or a Startup-folder shortcut).
|
||||
|
||||
### 3. Point it at your backend
|
||||
|
||||
Edit `%APPDATA%\RynthCore\statusagent.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Endpoint": "https://your-backend.example.com/api/rynthcore/status",
|
||||
"AuthHeaderName": "Authorization",
|
||||
"AuthHeaderValue": "Bearer YOUR_TOKEN",
|
||||
"IntervalSeconds": 5,
|
||||
"TimeoutSeconds": 15,
|
||||
"StatusDirectory": "C:\\Games\\RynthCore\\Logs\\status",
|
||||
"LogDirectory": "C:\\Games\\RynthCore\\Logs",
|
||||
"UseHeartbeatLogFallback": true,
|
||||
"StaleAfterSeconds": 12,
|
||||
"DropDeadAfterSeconds": 300,
|
||||
"Host": "",
|
||||
"ServeHttp": false,
|
||||
"ServePrefix": "http://127.0.0.1:8740/",
|
||||
"ServeToken": "",
|
||||
"WriteAggregateFile": true
|
||||
}
|
||||
```
|
||||
|
||||
- **Endpoint** — required to **push**. Empty = no POST.
|
||||
- **AuthHeaderName/Value** — optional; sent as a request header if both set.
|
||||
- **UseHeartbeatLogFallback** — when a running client has no status file (e.g.
|
||||
`EnableStatusExport` is off), derive basic status from its heartbeat log line.
|
||||
You get run/idle/loading/hung detection but no macro/profile/vitals.
|
||||
- **Host** — label for this machine; empty uses the machine name.
|
||||
- **ServeHttp / ServePrefix / ServeToken** — opt-in **pull** endpoint (see below).
|
||||
- **WriteAggregateFile** — also drop the latest rollup to
|
||||
`Logs\status\aggregate.json` (for file-sync delivery or debugging).
|
||||
|
||||
## Three ways to get it to the app — pick one (or several)
|
||||
|
||||
The agent produces one payload per cycle and can deliver it three ways at once;
|
||||
they're all opt-in, so use whichever fits the app you end up building:
|
||||
|
||||
1. **Push (POST).** Set `Endpoint` (+ optional auth). The agent POSTs the JSON to
|
||||
your server, which the app reads. Best when you already run a backend.
|
||||
2. **Pull (serve).** Set `ServeHttp: true`. The agent serves the latest JSON at
|
||||
`GET <ServePrefix>status` — **no backend needed**, the app just fetches a URL:
|
||||
- `http://127.0.0.1:8740/` (default) — this PC only.
|
||||
- `http://+:8740/` — reachable on the LAN, and from anywhere if the PC is on
|
||||
a private mesh like **Tailscale** (phone hits `http://<tailscale-ip>:8740/status`).
|
||||
A `+` bind needs a one-time `netsh http add urlacl url=http://+:8740/ user=Everyone`
|
||||
(or run the agent elevated).
|
||||
- `ServeToken` is required: with it empty the server stays off, on any bind.
|
||||
Every route but `/healthz` then needs `Authorization: Bearer <token>` (or `?token=`).
|
||||
Use the same token as your DrakBot remote and one DrakRemote entry shows both.
|
||||
- `GET /healthz` returns `ok` for uptime checks.
|
||||
3. **File sync.** Leave `WriteAggregateFile: true` and point iCloud/Dropbox/etc.
|
||||
at `Logs\status\aggregate.json`; the app reads the synced copy.
|
||||
|
||||
For a phone dashboard with no server, **pull + Tailscale** is the lowest-friction
|
||||
path: turn on `ServeHttp`, bind to `http://+:8740/`, and fetch
|
||||
`http://<pc-tailscale-ip>:8740/status` from the app.
|
||||
|
||||
---
|
||||
|
||||
## Backend payload contract
|
||||
|
||||
The agent sends an HTTP **POST** to `Endpoint` with
|
||||
`Content-Type: application/json` and (if configured) your auth header. Body:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"schema": "rynthcore.status-agent/1",
|
||||
"host": "DESKTOP-XYZ",
|
||||
"agentVersion": "1.0.0",
|
||||
"generatedAtUtc": "2026-06-20T12:34:56.789+00:00",
|
||||
"clientCount": 2,
|
||||
"clients": [
|
||||
{
|
||||
"pid": 1234,
|
||||
"host": "DESKTOP-XYZ",
|
||||
"account": "myacct",
|
||||
"character": "Gandalf",
|
||||
"server": "Coldeve",
|
||||
"state": "botting", // see state table below
|
||||
"healthy": true, // false for wedged/hung/dead
|
||||
"ageSec": 0.4, // seconds since this snapshot refreshed
|
||||
"source": "status-file", // or "heartbeat-log" (basic fallback)
|
||||
"uptimeSec": 3600,
|
||||
"fps": 60, // 0 while in-world = render thread dead
|
||||
"pluginTicksPerSec": 30, // 0 while macro on = bot pump wedged
|
||||
"workingSetMB": 540,
|
||||
"inWorld": true,
|
||||
"macroRunning": true,
|
||||
"currentState": "Killing",
|
||||
"botAction": "Cast War",
|
||||
"profile": "Default",
|
||||
"navProfile": "DiforsaPatrol",
|
||||
"lootProfile": "Salvage",
|
||||
"metaProfile": "",
|
||||
"target": "Drudge Skulker",
|
||||
"player": { "hp": 100, "maxHp": 120, "st": 80, "maxSt": 110, "mn": 60, "maxMn": 90 },
|
||||
"queueDropped": 0,
|
||||
"reconciles": 12,
|
||||
"forceClears": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`bot`-derived fields (`macroRunning`, `profile`, `target`, `player`, …) are only
|
||||
populated for `source: "status-file"` clients. For `heartbeat-log` clients they
|
||||
are empty/false.
|
||||
|
||||
### Client `state` values
|
||||
|
||||
| state | meaning | healthy |
|
||||
|-----------|------------------------------------------------------|---------|
|
||||
| `botting` | in-world, macro running, plugin pump alive | ✅ |
|
||||
| `idle` | in-world, macro stopped | ✅ |
|
||||
| `running` | in-world, rendering (macro state unknown — log path) | ✅ |
|
||||
| `loading` | process up, at login / char-select (not in-world) | ✅ |
|
||||
| `wedged` | macro on but plugin pump at 0/s — bot stalled | ❌ |
|
||||
| `hung` | in-world but fps 0, or snapshot frozen — client stuck| ❌ |
|
||||
| `dead` | process gone (crash/exit) | ❌ |
|
||||
|
||||
A simple phone view: green if every client is `healthy`, red if any is
|
||||
`wedged`/`hung`/`dead`, and show each character's `state` + `character` name.
|
||||
|
||||
---
|
||||
|
||||
## Removing the feature entirely
|
||||
|
||||
Everything is tagged `[status-export]` in the engine — `grep -r "[status-export]"
|
||||
src` finds every touch point.
|
||||
|
||||
1. Delete `src/RynthCore.StatusAgent/` and remove its `Project(...)` line and the
|
||||
`{A1B2C3D4-000A-...}` config block from `RynthCore.sln`.
|
||||
2. Delete `src/RynthCore.Engine/Compatibility/StatusSnapshotWriter.cs`.
|
||||
3. Remove the `StatusSnapshotWriter.Write(...)` call in
|
||||
`Compatibility/HeartbeatLogger.cs`.
|
||||
4. Remove the `[status-export]` region in `LogPaths.cs` (status dir helpers + the
|
||||
status-prune block in `PruneOldLogs`).
|
||||
5. Remove `EnableStatusExport` from `Plugins/EngineSettings.cs` (field, property,
|
||||
load, save).
|
||||
6. Remove the `LastAccountName/LastCharacterName/LastServerName` members and their
|
||||
assignment in `Compatibility/SessionStateRegistry.cs`.
|
||||
|
||||
The engine builds and behaves exactly as before.
|
||||
|
|
@ -1,75 +1,140 @@
|
|||
#Requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Builds RynthCore + RynthSuite release outputs and produces RynthBundle-Setup.exe via Inno Setup.
|
||||
Builds RynthCore + RynthSuite from source and produces the full installer
|
||||
(RynthCore-Setup-<version>.exe) via Inno Setup.
|
||||
|
||||
.DESCRIPTION
|
||||
1. Publishes the Avalonia launcher (self-contained, x86 — bundles .NET; no global runtime for RynthCore.exe)
|
||||
0. Makes sure a .NET 10 SDK is available; installs one per-user when missing (see -NoDotNetInstall)
|
||||
1. Publishes the Avalonia launcher (self-contained, x86)
|
||||
2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min)
|
||||
3. Publishes RynthCore.Injector (self-contained, x86)
|
||||
4. Publishes every RynthCore.Plugin.* project under RynthSuite (NativeAOT, x86), plus
|
||||
ub-Rythai (RynthCore.Plugin.UbRythai) when ../ub-Rythai/... exists or -UbRythaiPluginProject is set
|
||||
5. Optionally publishes LootEditor and MonsterEditor (framework-dependent, x64)
|
||||
6. Stages all output under installer\staging\app\ (recursive trees for tools and launcher)
|
||||
7. Invokes ISCC.exe to produce installer\Output\RynthBundle-Setup.exe
|
||||
3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects
|
||||
4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) from RynthSuite
|
||||
5. Publishes the Loot Editor (self-contained, x86)
|
||||
6. Publishes the Monster Editor (self-contained, x86) from RynthSuite
|
||||
7. Publishes the experimental plugins (RynthChat, RynthJuice, RynthNav, RynthTracker,
|
||||
RynthVision; NativeAOT, x86) -- optional components in the installer
|
||||
8. Stages RynthCore under installer\staging\core\ and RynthSuite under
|
||||
installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll,
|
||||
and checks every required runtime file is there
|
||||
9. Archives the previous installer (installer\previous-release\) when -Version changes
|
||||
10. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup-<version>.exe
|
||||
(and a RynthCore-Setup.exe copy)
|
||||
|
||||
The installer lets the user choose both the RynthCore and the RynthSuite folders; the
|
||||
code resolves them at runtime from HKA\Software\Rynth (see src\RynthCore.App\RynthInstallPaths.cs).
|
||||
|
||||
.PARAMETER Configuration
|
||||
Build configuration. Default: Release
|
||||
|
||||
.PARAMETER IsccPath
|
||||
Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 location.
|
||||
Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 locations.
|
||||
Install Inno Setup from: https://jrsoftware.org/isdl.php
|
||||
|
||||
.PARAMETER RynthSuiteRoot
|
||||
RynthSuite repo root. Default: the sibling ..\RynthSuite next to this RynthCore repo.
|
||||
|
||||
.PARAMETER Version
|
||||
Release version yyyy.m.d.n (e.g. 2026.10.4.2). Stamped into the launcher/engine/tools,
|
||||
release.txt and the installer. Omit for a dev build.
|
||||
|
||||
.PARAMETER SkipBuild
|
||||
Skip dotnet publish steps and just re-run ISCC against the existing staging directory.
|
||||
Skip dotnet publish steps and just re-stage + re-run ISCC against existing publish output.
|
||||
|
||||
.PARAMETER NoDotNetInstall
|
||||
Fail instead of auto-installing when no .NET 10 SDK is found. By default a missing SDK is
|
||||
installed per-user (no admin) to %LOCALAPPDATA%\Microsoft\dotnet via Microsoft's signed
|
||||
dotnet-install.ps1, and used for this build.
|
||||
#>
|
||||
param(
|
||||
[string]$Configuration = "Release",
|
||||
[string]$IsccPath = "C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
|
||||
[string]$IsccPath = "",
|
||||
# Explicit path to the RynthSuite repo root. When omitted, defaults to the
|
||||
# sibling directory of RynthCore (i.e. ..\RynthSuite relative to this repo).
|
||||
[string]$RynthSuiteRoot = "",
|
||||
# Version string injected into the installer (e.g. "0.3"). When omitted,
|
||||
# Version string injected into the installer (yyyy.m.d.n). When omitted,
|
||||
# the version defined in RynthCore.iss is used as-is.
|
||||
[string]$Version = "",
|
||||
# Include RynthSuite desktop tools (LootEditor + MonsterEditor) in setup.
|
||||
[switch]$IncludeSuiteTools = $true,
|
||||
# Full path to RynthCore.Plugin.UbRythai.csproj. Empty = default sibling ..\ub-Rythai\...
|
||||
[string]$UbRythaiPluginProject = "",
|
||||
# Omit ub-Rythai from the bundle (e.g. CI without that checkout).
|
||||
[switch]$SkipUbRythai,
|
||||
[switch]$SkipBuild
|
||||
[switch]$SkipBuild,
|
||||
[switch]$NoDotNetInstall
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-StrictMode -Off
|
||||
|
||||
function Copy-PublishTree {
|
||||
param(
|
||||
[string]$SourceRoot,
|
||||
[string]$DestRoot,
|
||||
[switch]$ExcludePdb
|
||||
)
|
||||
if (-not (Test-Path $SourceRoot)) {
|
||||
throw "Publish output not found: $SourceRoot"
|
||||
}
|
||||
$srcFull = (Resolve-Path $SourceRoot).Path
|
||||
# Normalize trailing separator so substring math is safe on Windows
|
||||
if (-not $srcFull.EndsWith([IO.Path]::DirectorySeparatorChar)) {
|
||||
$srcFull += [IO.Path]::DirectorySeparatorChar
|
||||
}
|
||||
Get-ChildItem $SourceRoot -Recurse -File | ForEach-Object {
|
||||
if ($ExcludePdb -and $_.Extension -eq '.pdb') { return }
|
||||
$rel = $_.FullName.Substring($srcFull.Length)
|
||||
$target = Join-Path $DestRoot $rel
|
||||
$parent = Split-Path $target -Parent
|
||||
if ($parent -and -not (Test-Path $parent)) {
|
||||
New-Item -ItemType Directory -Path $parent -Force | Out-Null
|
||||
}
|
||||
Copy-Item -LiteralPath $_.FullName -Destination $target -Force
|
||||
# Release number for release.txt, which the launcher's updater reads
|
||||
# (RynthUpdater.InstalledCoreRelease). -Version yyyy.m.d.n → yyyymmddnn; a dev build
|
||||
# without -Version records 0 ("unknown", so any published release reads as newer).
|
||||
# Checked here, before the builds, so a typo fails in a second rather than at the end.
|
||||
$release = 0
|
||||
if ($Version) {
|
||||
$p = $Version.Split('.')
|
||||
if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' }) -or [int]$p[1] -gt 12 -or [int]$p[2] -gt 31 -or [int]$p[3] -gt 99) {
|
||||
throw "-Version must be yyyy.m.d.n (e.g. 2026.9.26.3), got '$Version'"
|
||||
}
|
||||
$release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3]
|
||||
}
|
||||
|
||||
# Stamp the core builds and tools with the release, so the launcher, the engine log and the
|
||||
# in-game Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit.
|
||||
# The RynthAi plugin keeps its own semantic version (RynthCore.Plugin.RynthAi.csproj), so it
|
||||
# is published WITHOUT these args.
|
||||
$VersionArgs = @()
|
||||
if ($Version) { $VersionArgs = @("-p:Version=$Version") }
|
||||
|
||||
# ── .NET 10 SDK check (auto-install when missing) ───────────────────────────
|
||||
# Every project targets net10.0, so publishing needs a .NET 10 SDK. Returns $true when the
|
||||
# 'dotnet' on PATH lists a 10.x SDK.
|
||||
function Test-DotNet10Sdk {
|
||||
$cmd = Get-Command dotnet -ErrorAction SilentlyContinue
|
||||
if (-not $cmd) { return $false }
|
||||
$sdks = & $cmd.Source --list-sdks 2>$null
|
||||
return [bool]($sdks | Where-Object { $_ -match '^10\.' })
|
||||
}
|
||||
|
||||
# Makes a .NET 10 SDK available for this build: uses the one on PATH, else a previous per-user
|
||||
# auto-install, else installs one per-user (no admin) with Microsoft's dotnet-install.ps1, whose
|
||||
# Authenticode signature must verify as Microsoft before it is run.
|
||||
function Initialize-DotNet10Sdk {
|
||||
if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found ($((Get-Command dotnet).Source))"; return }
|
||||
|
||||
$userDotNet = Join-Path $env:LOCALAPPDATA "Microsoft\dotnet"
|
||||
if (Test-Path (Join-Path $userDotNet "dotnet.exe")) {
|
||||
$env:DOTNET_ROOT = $userDotNet
|
||||
$env:PATH = "$userDotNet;$env:PATH"
|
||||
if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found per-user install ($userDotNet)"; return }
|
||||
}
|
||||
|
||||
if ($NoDotNetInstall) {
|
||||
throw "No .NET 10 SDK found. Install it from https://dotnet.microsoft.com/download/dotnet/10.0 or re-run without -NoDotNetInstall."
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host ".NET 10 SDK not found -- installing it per-user to $userDotNet ..." -ForegroundColor Yellow
|
||||
$installScript = Join-Path $env:TEMP "dotnet-install.ps1"
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||
Invoke-WebRequest -Uri "https://dot.net/v1/dotnet-install.ps1" -OutFile $installScript -UseBasicParsing
|
||||
$sig = Get-AuthenticodeSignature $installScript
|
||||
if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notmatch 'O=Microsoft Corporation') {
|
||||
Remove-Item $installScript -Force -ErrorAction SilentlyContinue
|
||||
throw "dotnet-install.ps1 signature check failed ($($sig.Status)); not running it."
|
||||
}
|
||||
|
||||
# Separate process so the script runs under Bypass regardless of this session's execution policy.
|
||||
& powershell -NoProfile -ExecutionPolicy Bypass -File $installScript -Channel 10.0 -InstallDir $userDotNet
|
||||
$installExit = $LASTEXITCODE
|
||||
Remove-Item $installScript -Force -ErrorAction SilentlyContinue
|
||||
if ($installExit -ne 0) { throw "dotnet-install.ps1 failed (exit $installExit)" }
|
||||
|
||||
$env:DOTNET_ROOT = $userDotNet
|
||||
$env:PATH = "$userDotNet;$env:PATH"
|
||||
if (-not (Test-DotNet10Sdk)) { throw ".NET 10 SDK install finished but 'dotnet --list-sdks' still shows no 10.x SDK." }
|
||||
Write-Host ".NET 10 SDK: installed ($userDotNet)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Only the publish steps need the SDK; -SkipBuild just re-stages and re-runs ISCC.
|
||||
if (-not $SkipBuild) { Initialize-DotNet10Sdk }
|
||||
|
||||
$ScriptDir = $PSScriptRoot
|
||||
$RepoRoot = Split-Path $ScriptDir -Parent # e.g. C:\Projects\RynthCore
|
||||
$ProjectsRoot = Split-Path $RepoRoot -Parent # e.g. C:\Projects
|
||||
|
|
@ -79,58 +144,38 @@ if (-not $RynthSuiteRoot) {
|
|||
$RynthSuiteRoot = "$ProjectsRoot\RynthSuite"
|
||||
}
|
||||
|
||||
$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj"
|
||||
$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj"
|
||||
$InjectorProject = "$RepoRoot\src\RynthCore.Injector\RynthCore.Injector.csproj"
|
||||
$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj"
|
||||
$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj"
|
||||
$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj"
|
||||
$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj"
|
||||
$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj"
|
||||
$MonsterEditorProject = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\RynthCore.MonsterEditor.csproj"
|
||||
|
||||
$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish"
|
||||
$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
$InjectorPublish = "$RepoRoot\src\RynthCore.Injector\bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish"
|
||||
$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish"
|
||||
$MonsterEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\bin\$Configuration\net10.0\win-x86\publish"
|
||||
|
||||
$PluginProjects = @()
|
||||
$pluginProjectFiles = Get-ChildItem -Path "$RynthSuiteRoot\Plugins" -Filter "RynthCore.Plugin.*.csproj" -File -Recurse -ErrorAction SilentlyContinue
|
||||
foreach ($pluginProject in $pluginProjectFiles) {
|
||||
$pluginName = [IO.Path]::GetFileNameWithoutExtension($pluginProject.Name)
|
||||
$PluginProjects += [pscustomobject]@{
|
||||
Name = $pluginName
|
||||
ProjectPath = $pluginProject.FullName
|
||||
PublishPath = Join-Path $pluginProject.DirectoryName "bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
DllPath = Join-Path (Join-Path $pluginProject.DirectoryName "bin\$Configuration\net10.0-windows\win-x86\publish") "$pluginName.dll"
|
||||
}
|
||||
}
|
||||
# Experimental RynthSuite plugins (optional installer components). Each installs to
|
||||
# <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll and keeps its own semantic version.
|
||||
$ExperimentalPlugins = @('RynthChat', 'RynthJuice', 'RynthNav', 'RynthTracker', 'RynthVision')
|
||||
function Get-ExperimentalProject([string]$Name) { "$RynthSuiteRoot\Plugins\RynthCore.Plugin.$Name\RynthCore.Plugin.$Name.csproj" }
|
||||
function Get-ExperimentalPublish([string]$Name) { "$RynthSuiteRoot\Plugins\RynthCore.Plugin.$Name\bin\$Configuration\net10.0-windows\win-x86\publish" }
|
||||
# RynthNav's starter portal list (shipped into <RynthCore>\NavData, never overwritten).
|
||||
$NavPortalsTsv = "$RynthSuiteRoot\Tools\RynthNav.PortalGraph\Data\portals.tsv"
|
||||
|
||||
# ub-Rythai ships from a sibling repo (same layout as RynthSuite/README.md); publish + stage into Runtime\Plugins.
|
||||
if (-not $SkipUbRythai) {
|
||||
if ($UbRythaiPluginProject) {
|
||||
$ubRythaiProj = $UbRythaiPluginProject
|
||||
}
|
||||
else {
|
||||
$ubRythaiProj = "$ProjectsRoot\ub-Rythai\RynthCore.Plugin.UbRythai\RynthCore.Plugin.UbRythai.csproj"
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $ubRythaiProj) {
|
||||
$ubDir = Split-Path $ubRythaiProj -Parent
|
||||
$ubName = "RynthCore.Plugin.UbRythai"
|
||||
$PluginProjects += [pscustomobject]@{
|
||||
Name = $ubName
|
||||
ProjectPath = $ubRythaiProj
|
||||
PublishPath = Join-Path $ubDir "bin\$Configuration\net10.0-windows\win-x86\publish"
|
||||
DllPath = Join-Path (Join-Path $ubDir "bin\$Configuration\net10.0-windows\win-x86\publish") "$ubName.dll"
|
||||
}
|
||||
Write-Host "ub-Rythai plugin included: $ubRythaiProj" -ForegroundColor DarkCyan
|
||||
}
|
||||
else {
|
||||
$warn = "ub-Rythai project not found (optional): $ubRythaiProj - RynthCore.Plugin.UbRythai.dll will be omitted. Clone next to RynthCore or pass -UbRythaiPluginProject."
|
||||
Write-Warning $warn
|
||||
}
|
||||
}
|
||||
|
||||
$StagingDir = "$ScriptDir\staging\app"
|
||||
# staging\core → {app} (user-chosen RynthCore folder)
|
||||
# staging\suite → {code:GetSuiteDir} (user-chosen RynthSuite folder)
|
||||
$StagingRoot = "$ScriptDir\staging"
|
||||
$CoreStaging = "$StagingRoot\core"
|
||||
$SuiteStaging = "$StagingRoot\suite"
|
||||
|
||||
# ── Validate projects ───────────────────────────────────────────────────────
|
||||
foreach ($p in @($LauncherProject, $EngineProject, $InjectorProject)) {
|
||||
$allProjects = @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) +
|
||||
@($ExperimentalPlugins | ForEach-Object { Get-ExperimentalProject $_ })
|
||||
foreach ($p in $allProjects) {
|
||||
if (-not (Test-Path $p)) {
|
||||
throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs."
|
||||
}
|
||||
|
|
@ -154,50 +199,51 @@ if (-not $SkipBuild) {
|
|||
|
||||
$step++
|
||||
Write-Host ""
|
||||
# Self-contained: ship .NET 10 with the apphost so RynthCore.exe does not require a machine-wide
|
||||
# Desktop Runtime (avoids the official apphost "You must install .NET" dialog on clean PCs).
|
||||
Write-Host "[$step/$totalSteps] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan
|
||||
# RollForward=Disable: host must use bundled runtimes only (avoids probing %ProgramFiles%\dotnet\shared\...).
|
||||
dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true `
|
||||
-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable
|
||||
Write-Host "[1/7] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan
|
||||
dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
$step++
|
||||
Write-Host ""
|
||||
Write-Host "[$step/$totalSteps] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan
|
||||
dotnet publish $EngineProject -c $Configuration
|
||||
Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan
|
||||
dotnet publish $EngineProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
$step++
|
||||
# ── 3. Loader (NativeAOT, small) ──────────────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[$step/$totalSteps] Publishing Injector (self-contained, x86)..." -ForegroundColor Cyan
|
||||
dotnet publish $InjectorProject -c $Configuration -r win-x86 --self-contained true `
|
||||
-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable
|
||||
if ($LASTEXITCODE -ne 0) { throw "Injector publish failed (exit $LASTEXITCODE)" }
|
||||
Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan
|
||||
dotnet publish $LoaderProject -c $Configuration @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
foreach ($plugin in $PluginProjects) {
|
||||
$step++
|
||||
Write-Host ""
|
||||
Write-Host "[$step/$totalSteps] Publishing plugin: $($plugin.Name) (NativeAOT)..." -ForegroundColor Cyan
|
||||
dotnet publish $plugin.ProjectPath -c $Configuration
|
||||
if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed for $($plugin.Name) (exit $LASTEXITCODE)" }
|
||||
}
|
||||
# ── 4. RynthAi plugin (NativeAOT; keeps its own version) ─────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[4/7] Publishing RynthAi plugin (NativeAOT)..." -ForegroundColor Cyan
|
||||
dotnet publish $PluginProject -c $Configuration
|
||||
if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
if ($IncludeSuiteTools) {
|
||||
if (-not (Test-Path "$RepoRoot\installer\_toolpublish")) {
|
||||
New-Item -ItemType Directory -Path "$RepoRoot\installer\_toolpublish" -Force | Out-Null
|
||||
}
|
||||
$step++
|
||||
Write-Host ""
|
||||
Write-Host "[$step/$totalSteps] Publishing LootEditor (framework-dependent x64)..." -ForegroundColor Cyan
|
||||
dotnet publish $LootEditorProject -c $Configuration -r win-x64 --self-contained false --output "$RepoRoot\installer\_toolpublish\LootEditor"
|
||||
if ($LASTEXITCODE -ne 0) { throw "LootEditor publish failed (exit $LASTEXITCODE)" }
|
||||
# ── 5. Loot Editor (self-contained Avalonia tool) ─────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[5/7] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan
|
||||
dotnet publish $LootEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Loot Editor publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
$step++
|
||||
Write-Host ""
|
||||
Write-Host "[$step/$totalSteps] Publishing MonsterEditor (framework-dependent x64)..." -ForegroundColor Cyan
|
||||
dotnet publish $MonsterEditorProject -c $Configuration -r win-x64 --self-contained false --output "$RepoRoot\installer\_toolpublish\MonsterEditor"
|
||||
if ($LASTEXITCODE -ne 0) { throw "MonsterEditor publish failed (exit $LASTEXITCODE)" }
|
||||
# ── 6. Monster Editor (self-contained Avalonia tool) ──────────────────────
|
||||
Write-Host ""
|
||||
Write-Host "[6/7] Publishing Monster Editor (self-contained, x86)..." -ForegroundColor Cyan
|
||||
dotnet publish $MonsterEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Monster Editor publish failed (exit $LASTEXITCODE)" }
|
||||
|
||||
# ── 7. Experimental plugins (NativeAOT; optional components) ──────────────
|
||||
# RynthJuice/RynthNav/RynthVision set <PublishDir> to the live C:\Games\RynthSuite\<Name>\
|
||||
# folder for dev hot-reload; override it so an installer build never touches a live install.
|
||||
# A trailing '/' (not '\') keeps the argument intact when the path contains spaces.
|
||||
Write-Host ""
|
||||
Write-Host "[7/7] Publishing experimental plugins (NativeAOT)..." -ForegroundColor Cyan
|
||||
foreach ($name in $ExperimentalPlugins) {
|
||||
Write-Host " $name"
|
||||
$publishDir = (Get-ExperimentalPublish $name) + '/'
|
||||
dotnet publish (Get-ExperimentalProject $name) -c $Configuration "-p:PublishDir=$publishDir"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$name publish failed (exit $LASTEXITCODE)" }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -205,108 +251,153 @@ if (-not $SkipBuild) {
|
|||
Write-Host ""
|
||||
Write-Host "Staging files..." -ForegroundColor Cyan
|
||||
|
||||
if (Test-Path "$ScriptDir\staging") {
|
||||
Remove-Item "$ScriptDir\staging" -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path "$StagingDir\Runtime\Native" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$StagingDir\Runtime\Plugins" -Force | Out-Null
|
||||
if ($IncludeSuiteTools) {
|
||||
New-Item -ItemType Directory -Path "$StagingDir\Tools\LootEditor" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$StagingDir\Tools\MonsterEditor" -Force | Out-Null
|
||||
if (Test-Path $StagingRoot) {
|
||||
Remove-Item $StagingRoot -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path "$CoreStaging\Runtime\Native" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$CoreStaging\Tools\LootEditor" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$SuiteStaging\RynthAi\MonsterEditor" -Force | Out-Null
|
||||
|
||||
# Document runtime prerequisites: launcher + injector are self-contained; editor tools are FDD x64.
|
||||
$prereqPath = Join-Path $StagingDir "RynthCore-Prerequisites.txt"
|
||||
Set-Content -LiteralPath $prereqPath -Encoding UTF8 -Value @"
|
||||
RynthCore Runtime Prerequisites
|
||||
==============================
|
||||
|
||||
RynthCore.exe and Runtime\RynthCore.Injector.exe are published self-contained (they bundle .NET 10
|
||||
x86). You do not need a separate .NET Desktop Runtime install to run the launcher or injector from
|
||||
this folder.
|
||||
|
||||
The optional suite tools (Loot Editor / Monster Editor) are framework-dependent x64. If they show
|
||||
a missing-runtime dialog, install:
|
||||
|
||||
- .NET Desktop Runtime 10 x64:
|
||||
https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime
|
||||
"@
|
||||
|
||||
# Launcher (self-contained — copy full tree, then rename launcher host + host metadata files)
|
||||
if (-not (Test-Path $LauncherPublish)) {
|
||||
throw "Launcher publish not found: $LauncherPublish`nRun without -SkipBuild first."
|
||||
}
|
||||
Copy-PublishTree -SourceRoot $LauncherPublish -DestRoot $StagingDir -ExcludePdb
|
||||
$avExe = "$StagingDir\RynthCore.App.Avalonia.exe"
|
||||
if (Test-Path $avExe) {
|
||||
Move-Item -LiteralPath $avExe -Destination "$StagingDir\RynthCore.exe" -Force
|
||||
# Keep host metadata filenames in sync with the renamed apphost.
|
||||
# If these remain as RynthCore.App.Avalonia.* the apphost can fail runtime resolution
|
||||
# and show a ".NET install required" prompt even when .NET 10 is already installed.
|
||||
$avRuntimeConfig = "$StagingDir\RynthCore.App.Avalonia.runtimeconfig.json"
|
||||
if (Test-Path $avRuntimeConfig) {
|
||||
Move-Item -LiteralPath $avRuntimeConfig -Destination "$StagingDir\RynthCore.runtimeconfig.json" -Force
|
||||
# Copies a publish folder (files + subfolders) without .pdb files.
|
||||
function Copy-PublishTree([string]$Source, [string]$Dest) {
|
||||
if (-not (Test-Path $Source)) { throw "Publish output not found: $Source" }
|
||||
foreach ($file in (Get-ChildItem $Source -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName (Join-Path $Dest $file.Name) -Force
|
||||
}
|
||||
$avDeps = "$StagingDir\RynthCore.App.Avalonia.deps.json"
|
||||
if (Test-Path $avDeps) {
|
||||
Move-Item -LiteralPath $avDeps -Destination "$StagingDir\RynthCore.deps.json" -Force
|
||||
foreach ($dir in (Get-ChildItem $Source -Directory)) {
|
||||
Copy-Item $dir.FullName $Dest -Recurse -Force
|
||||
Get-ChildItem (Join-Path $Dest $dir.Name) -Recurse -File -Filter '*.pdb' | Remove-Item -Force
|
||||
}
|
||||
} else {
|
||||
throw "Expected launcher executable not found after publish: RynthCore.App.Avalonia.exe under $LauncherPublish"
|
||||
}
|
||||
|
||||
# Launcher root files (rename .exe → RynthCore.exe; drop .pdb)
|
||||
foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
$destName = if ($file.Name -eq 'RynthCore.App.Avalonia.exe') { 'RynthCore.exe' } else { $file.Name }
|
||||
Copy-Item $file.FullName "$CoreStaging\$destName" -Force
|
||||
}
|
||||
|
||||
# Engine runtime files (into Runtime\, skip .pdb)
|
||||
foreach ($file in (Get-ChildItem "$EnginePublish" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force
|
||||
Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force
|
||||
}
|
||||
|
||||
# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it
|
||||
# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's
|
||||
# launcher can't auto-find an engine to inject.
|
||||
$loaderDll = "$LoaderPublish\RynthCore.Loader.dll"
|
||||
if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" }
|
||||
Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force
|
||||
|
||||
# SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1),
|
||||
# NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays
|
||||
# false and CombatActionHooks.CastSpell fails closed on every targeted cast, which
|
||||
# includes self-buffs (the plugin passes the player id): the bot says "Casting: X"
|
||||
# and nothing happens. Same missing/stale checks as scripts\Deploy-RynthCore.ps1.
|
||||
$sehDll = "$RepoRoot\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll"
|
||||
$sehSrc = "$RepoRoot\native\SehTrampoline\SehTrampoline.c"
|
||||
if (-not (Test-Path $sehDll)) { throw "SEH trampoline not found at: $sehDll`nBuild it with native\SehTrampoline\Build-SehTrampoline.ps1" }
|
||||
if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $sehDll).LastWriteTime) {
|
||||
throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c is newer). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1"
|
||||
}
|
||||
Copy-Item $sehDll "$CoreStaging\Runtime\" -Force
|
||||
|
||||
# Engine Native subfolder
|
||||
if (Test-Path "$EnginePublish\Native") {
|
||||
foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) {
|
||||
if ($file.Extension -eq '.pdb') { continue }
|
||||
Copy-Item $file.FullName "$StagingDir\Runtime\Native\$($file.Name)" -Force
|
||||
Copy-Item $file.FullName "$CoreStaging\Runtime\Native\$($file.Name)" -Force
|
||||
}
|
||||
}
|
||||
|
||||
# Injector (self-contained x86) — full publish tree into Runtime\ next to the engine
|
||||
if (-not (Test-Path $InjectorPublish)) {
|
||||
throw "Injector publish not found: $InjectorPublish`nRun without -SkipBuild, or publish RynthCore.Injector for $Configuration|win-x86."
|
||||
}
|
||||
Copy-PublishTree -SourceRoot $InjectorPublish -DestRoot "$StagingDir\Runtime" -ExcludePdb
|
||||
# Loot Editor → <RynthCore>\Tools\LootEditor (the launcher/engine look for it there)
|
||||
Copy-PublishTree $LootEditorPublish "$CoreStaging\Tools\LootEditor"
|
||||
|
||||
# Plugin DLLs only (cimgui.dll excluded — already in Runtime from Engine)
|
||||
foreach ($plugin in $PluginProjects) {
|
||||
if (-not (Test-Path $plugin.DllPath)) {
|
||||
throw "Plugin DLL not found at: $($plugin.DllPath)"
|
||||
}
|
||||
# RynthAi plugin DLL → <RynthSuite>\RynthAi (next to its data dirs; the installer hands the
|
||||
# path to the launcher via HKA\Software\Rynth\PendingPluginRegistration).
|
||||
$pluginDll = "$PluginPublish\RynthCore.Plugin.RynthAi.dll"
|
||||
if (-not (Test-Path $pluginDll)) { throw "Plugin DLL not found at: $pluginDll" }
|
||||
Copy-Item $pluginDll "$SuiteStaging\RynthAi\" -Force
|
||||
|
||||
Copy-Item $plugin.DllPath "$StagingDir\Runtime\Plugins\" -Force
|
||||
# Monster Editor → <RynthSuite>\RynthAi\MonsterEditor (RynthAi's dashboard launches it from there)
|
||||
Copy-PublishTree $MonsterEditorPublish "$SuiteStaging\RynthAi\MonsterEditor"
|
||||
|
||||
# Experimental plugins → <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll (the NativeAOT DLL is self-contained;
|
||||
# cimgui.dll is provided by the engine's Runtime folder).
|
||||
foreach ($name in $ExperimentalPlugins) {
|
||||
$dll = Join-Path (Get-ExperimentalPublish $name) "RynthCore.Plugin.$name.dll"
|
||||
if (-not (Test-Path $dll)) { throw "$name DLL not found at: $dll" }
|
||||
New-Item -ItemType Directory -Path "$SuiteStaging\$name" -Force | Out-Null
|
||||
Copy-Item $dll "$SuiteStaging\$name\" -Force
|
||||
}
|
||||
|
||||
if ($IncludeSuiteTools) {
|
||||
foreach ($tool in @(
|
||||
@{ Source = "$RepoRoot\installer\_toolpublish\LootEditor"; Dest = "$StagingDir\Tools\LootEditor" },
|
||||
@{ Source = "$RepoRoot\installer\_toolpublish\MonsterEditor"; Dest = "$StagingDir\Tools\MonsterEditor" }
|
||||
)) {
|
||||
if (-not (Test-Path $tool.Source)) {
|
||||
throw "Tool publish output not found: $($tool.Source)"
|
||||
}
|
||||
# FDD x64 tools — copy the full tree (runtimes\ from NuGet, not a bundled .NET host)
|
||||
Copy-PublishTree -SourceRoot $tool.Source -DestRoot $tool.Dest -ExcludePdb
|
||||
}
|
||||
}
|
||||
# RynthNav starter data → <RynthCore>\NavData (staged apart from core so it is only installed with RynthNav).
|
||||
if (-not (Test-Path $NavPortalsTsv)) { throw "RynthNav portals.tsv not found at: $NavPortalsTsv" }
|
||||
New-Item -ItemType Directory -Path "$StagingRoot\navdata" -Force | Out-Null
|
||||
Copy-Item $NavPortalsTsv "$StagingRoot\navdata\" -Force
|
||||
|
||||
# release.txt — which core release this install is ($release, from -Version at the top).
|
||||
Set-Content -Path "$CoreStaging\release.txt" -Value @($release, $Version) -Encoding ASCII
|
||||
|
||||
# Everything a working install needs. The 2026-09-25 public installer went out
|
||||
# without the Loader and the SEH trampoline because nothing checked.
|
||||
$required = @(
|
||||
"$CoreStaging\RynthCore.exe",
|
||||
"$CoreStaging\RynthCore.App.Avalonia.dll",
|
||||
"$CoreStaging\RynthCore.App.Avalonia.deps.json",
|
||||
"$CoreStaging\RynthCore.App.Avalonia.runtimeconfig.json",
|
||||
"$CoreStaging\Runtime\RynthCore.Loader.dll",
|
||||
"$CoreStaging\Runtime\RynthCore.Engine.dll",
|
||||
"$CoreStaging\Runtime\RynthCore.SehTrampoline.dll",
|
||||
"$CoreStaging\Runtime\minhook.x86.dll",
|
||||
"$CoreStaging\Runtime\cimgui.dll",
|
||||
"$CoreStaging\Tools\LootEditor\RynthCore.LootEditor.exe",
|
||||
"$SuiteStaging\RynthAi\RynthCore.Plugin.RynthAi.dll",
|
||||
"$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe",
|
||||
"$StagingRoot\navdata\portals.tsv"
|
||||
) + @($ExperimentalPlugins | ForEach-Object { "$SuiteStaging\$_\RynthCore.Plugin.$_.dll" })
|
||||
$missing = @($required | Where-Object { -not (Test-Path $_) })
|
||||
if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" }
|
||||
|
||||
# Every assembly the launcher's deps.json lists must be staged next to it — a launcher DLL whose
|
||||
# deps.json doesn't match is exactly the "Could not load RynthCore.DesktopLog" failure of 2026-10-04.
|
||||
$depsJson = Get-Content "$CoreStaging\RynthCore.App.Avalonia.deps.json" -Raw | ConvertFrom-Json
|
||||
$projectLibs = $depsJson.libraries.PSObject.Properties | Where-Object { $_.Value.type -eq 'project' } | ForEach-Object { ($_.Name -split '/')[0] }
|
||||
$missingLibs = @($projectLibs | Where-Object { -not (Test-Path "$CoreStaging\$_.dll") })
|
||||
if ($missingLibs.Count -gt 0) { throw "Launcher deps.json references project assemblies that were not staged:`n $($missingLibs -join "`n ")" }
|
||||
|
||||
# Report staged sizes
|
||||
$engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll"
|
||||
$engineDll = "$CoreStaging\Runtime\RynthCore.Engine.dll"
|
||||
if (Test-Path $engineDll) {
|
||||
$sizeMb = [math]::Round((Get-Item $engineDll).Length / 1MB, 1)
|
||||
Write-Host " Engine.dll: ${sizeMb} MB"
|
||||
}
|
||||
$totalMb = [math]::Round((Get-ChildItem "$StagingDir" -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1)
|
||||
Write-Host " Total staged: ${totalMb} MB"
|
||||
$coreMb = [math]::Round((Get-ChildItem $CoreStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1)
|
||||
$suiteMb = [math]::Round((Get-ChildItem $SuiteStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1)
|
||||
Write-Host " Staged: RynthCore ${coreMb} MB, RynthSuite ${suiteMb} MB"
|
||||
|
||||
Write-Host "Staging complete: $StagingDir" -ForegroundColor Green
|
||||
Write-Host "Staging complete: $StagingRoot" -ForegroundColor Green
|
||||
|
||||
# ── Archive the previous installer when -Version bumps ─────────────────────
|
||||
# installer\previous-release\last-built-version.txt records the last version built; when a new
|
||||
# -Version is built, that version's installer is copied to previous-release\ first.
|
||||
$previousReleaseDir = Join-Path $ScriptDir "previous-release"
|
||||
$lastVersionFile = Join-Path $previousReleaseDir "last-built-version.txt"
|
||||
if ($Version) {
|
||||
New-Item -ItemType Directory -Path $previousReleaseDir -Force | Out-Null
|
||||
$lastVer = if (Test-Path $lastVersionFile) { (Get-Content $lastVersionFile -Raw).Trim() } else { "" }
|
||||
if ($lastVer -and $lastVer -ne $Version) {
|
||||
$prevExe = Join-Path $ScriptDir "Output\RynthCore-Setup-$lastVer.exe"
|
||||
if (-not (Test-Path $prevExe)) { $prevExe = Join-Path $ScriptDir "Output\RynthCore-Setup.exe" }
|
||||
if (Test-Path $prevExe) {
|
||||
$archive = Join-Path $previousReleaseDir "RynthCore-Setup-$lastVer.exe"
|
||||
Write-Host "Archiving previous installer ($lastVer) -> $archive" -ForegroundColor Cyan
|
||||
Copy-Item $prevExe $archive -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# ── Archive prior bundle when -Version bumps ────────────────────────────────
|
||||
# Copies installer\Output\RynthBundle-Setup.exe to previous-release\ using the
|
||||
|
|
@ -344,13 +435,18 @@ if ($Version) {
|
|||
}
|
||||
|
||||
# ── Inno Setup ───────────────────────────────────────────────────────────────
|
||||
if (-not (Test-Path $IsccPath)) {
|
||||
# Auto-detect ISCC if not specified: try standard install location then user-local.
|
||||
if (-not $IsccPath) {
|
||||
$candidates = @(
|
||||
"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
|
||||
"$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe"
|
||||
)
|
||||
foreach ($c in $candidates) { if (Test-Path $c) { $IsccPath = $c; break } }
|
||||
}
|
||||
if (-not $IsccPath -or -not (Test-Path $IsccPath)) {
|
||||
Write-Host ""
|
||||
Write-Warning "Inno Setup compiler not found at:"
|
||||
Write-Warning " $IsccPath"
|
||||
Write-Warning "Install Inno Setup 6 from: https://jrsoftware.org/isdl.php"
|
||||
Write-Warning "Then re-run this script, or invoke ISCC manually:"
|
||||
Write-Warning " `"$IsccPath`" `"$ScriptDir\RynthCore.iss`""
|
||||
Write-Warning "Inno Setup compiler not found. Install Inno Setup 6 from: https://jrsoftware.org/isdl.php"
|
||||
Write-Warning "Or pass -IsccPath to this script explicitly."
|
||||
exit 0
|
||||
}
|
||||
|
||||
|
|
@ -366,15 +462,14 @@ $issSource = "$ScriptDir\RynthCore.iss"
|
|||
# Source, staging\) still resolve from the installer\ directory.
|
||||
$issTmp = "$ScriptDir\RynthCore.tmp.iss"
|
||||
$issContent = Get-Content $issSource -Raw
|
||||
$installerExeName = "RynthBundle-Setup"
|
||||
$outputName = "RynthCore-Setup"
|
||||
if ($Version) {
|
||||
$versionTrim = $Version.Trim()
|
||||
$issContent = $issContent -replace 'AppVersion=0\.0\.0', "AppVersion=$versionTrim"
|
||||
# Versioned .exe avoids Inno error 32 when Output\RynthBundle-Setup.exe is open in Explorer or AV.
|
||||
$fnSuffix = Get-SafeVersionFileSuffix -Ver $versionTrim
|
||||
$installerExeName = "RynthBundle-Setup-$fnSuffix"
|
||||
$issContent = $issContent -replace 'OutputBaseFilename=RynthBundle-Setup', "OutputBaseFilename=$installerExeName"
|
||||
Write-Host " Version override: $versionTrim (OutputBaseFilename=$installerExeName)"
|
||||
# Versioned .exe avoids Inno error 32 when Output\RynthCore-Setup.exe is open in Explorer or AV.
|
||||
$outputName = "RynthCore-Setup-$Version"
|
||||
$issContent = $issContent -replace 'AppVersion=0\.0\.0', "AppVersion=$Version"
|
||||
$issContent = $issContent -replace 'AppVerName=RynthCore \+ RynthSuite 0\.0\.0', "AppVerName=RynthCore + RynthSuite $Version"
|
||||
$issContent = $issContent -replace 'OutputBaseFilename=RynthCore-Setup', "OutputBaseFilename=$outputName"
|
||||
Write-Host " Version override: $Version"
|
||||
}
|
||||
Set-Content -Path $issTmp -Value $issContent -Encoding UTF8
|
||||
|
||||
|
|
@ -385,25 +480,14 @@ try {
|
|||
Remove-Item $issTmp -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
$builtInstaller = Join-Path $ScriptDir "Output\$installerExeName.exe"
|
||||
# Best-effort copy to the legacy canonical name for scripts that expect RynthBundle-Setup.exe.
|
||||
if ($Version -and (Test-Path -LiteralPath $builtInstaller)) {
|
||||
$canonicalInstaller = Join-Path $ScriptDir "Output\RynthBundle-Setup.exe"
|
||||
try {
|
||||
Copy-Item -LiteralPath $builtInstaller -Destination $canonicalInstaller -Force
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not copy to RynthBundle-Setup.exe (file may be in use). Primary artifact: $builtInstaller"
|
||||
}
|
||||
}
|
||||
|
||||
# Record the version that produced the bundle (enables archive on next bump).
|
||||
$builtInstaller = "$ScriptDir\Output\$outputName.exe"
|
||||
if ($Version) {
|
||||
New-Item -ItemType Directory -Path $previousReleaseDir -Force | Out-Null
|
||||
[System.IO.File]::WriteAllText($lastVersionFile, $Version.Trim())
|
||||
# Canonical name for the launcher updater / docs; best effort if the file is locked.
|
||||
try { Copy-Item $builtInstaller "$ScriptDir\Output\RynthCore-Setup.exe" -Force }
|
||||
catch { Write-Warning "Could not refresh Output\RynthCore-Setup.exe (in use?). Primary artifact: $builtInstaller" }
|
||||
[IO.File]::WriteAllText($lastVersionFile, $Version)
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "SUCCESS" -ForegroundColor Green
|
||||
Write-Host "Installer: $builtInstaller"
|
||||
|
||||
|
|
|
|||
103
installer/New-UpdateSigningKey.ps1
Normal file
103
installer/New-UpdateSigningKey.ps1
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
#Requires -Version 7
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Creates the RynthCore update-signing keys. Run it once, yourself.
|
||||
|
||||
.DESCRIPTION
|
||||
Launchers install an update only if its feed is signed by a key they trust. This makes
|
||||
two ECDSA P-256 keys:
|
||||
|
||||
primary Signs every release. Saved to <KeyDir>\primary.key, encrypted with Windows
|
||||
DPAPI for your user account: Publish-Update.ps1 signs without a prompt, and the
|
||||
file is useless on any other account or PC.
|
||||
backup Replaces the primary if it is ever lost (new PC, reinstall). Saved to
|
||||
<KeyDir>\backup.key.p8, encrypted with a password you choose here. Move it
|
||||
OFFLINE (a USB stick in a drawer) and delete the copy on this PC.
|
||||
|
||||
Both public halves are written into src\RynthCore.App.Avalonia\UpdateTrust.cs, so
|
||||
launchers built afterwards trust either key. Commit that file, then build and release.
|
||||
|
||||
The private keys never leave this PC. Never copy them to the server: the point of signing
|
||||
is that a compromised server still can't push code to players.
|
||||
|
||||
.PARAMETER Force
|
||||
Replace existing keys. Launchers that only trust the old keys will refuse every release
|
||||
signed with the new ones, so this strands them until they reinstall by hand.
|
||||
#>
|
||||
param(
|
||||
[string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"),
|
||||
[string]$TrustFile = (Join-Path $PSScriptRoot "..\src\RynthCore.App.Avalonia\UpdateTrust.cs"),
|
||||
# For scripted tests only; normally you are prompted.
|
||||
[SecureString]$BackupPassword,
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Add-Type -AssemblyName System.Security
|
||||
$crypto = [System.Security.Cryptography.ProtectedData].Assembly # DPAPI present (fails loudly if not)
|
||||
|
||||
$primaryPath = Join-Path $KeyDir "primary.key"
|
||||
$backupPath = Join-Path $KeyDir "backup.key.p8"
|
||||
if ((Test-Path $primaryPath) -and -not $Force) {
|
||||
throw "Keys already exist in $KeyDir. Replacing them strands launchers that trust only the old ones; pass -Force only if you mean it."
|
||||
}
|
||||
if (-not (Test-Path $TrustFile)) { throw "UpdateTrust.cs not found at $TrustFile" }
|
||||
|
||||
if (-not $BackupPassword) {
|
||||
$BackupPassword = Read-Host "Password for the BACKUP key (needed only if the primary is ever lost)" -AsSecureString
|
||||
$again = Read-Host "Repeat it" -AsSecureString
|
||||
if ((ConvertFrom-SecureString $BackupPassword -AsPlainText) -ne (ConvertFrom-SecureString $again -AsPlainText)) {
|
||||
throw "The passwords don't match."
|
||||
}
|
||||
}
|
||||
$plain = ConvertFrom-SecureString $BackupPassword -AsPlainText
|
||||
if ($plain.Length -lt 12) { throw "Use at least 12 characters for the backup key password." }
|
||||
|
||||
New-Item -ItemType Directory -Force $KeyDir | Out-Null
|
||||
$curve = [System.Security.Cryptography.ECCurve+NamedCurves]::nistP256
|
||||
$primary = [System.Security.Cryptography.ECDsa]::Create($curve)
|
||||
$backup = [System.Security.Cryptography.ECDsa]::Create($curve)
|
||||
|
||||
# Primary: DPAPI (CurrentUser), with fixed entropy so a stray DPAPI blob can't pose as it.
|
||||
$entropy = [Text.Encoding]::UTF8.GetBytes("RynthCore update signing v1")
|
||||
$pkcs8 = $primary.ExportPkcs8PrivateKey()
|
||||
try {
|
||||
$blob = [System.Security.Cryptography.ProtectedData]::Protect($pkcs8, $entropy, 'CurrentUser')
|
||||
[IO.File]::WriteAllBytes($primaryPath, $blob)
|
||||
} finally { [Array]::Clear($pkcs8) }
|
||||
|
||||
# Backup: password-encrypted PKCS#8 (AES-256, 600k PBKDF2 rounds).
|
||||
$pbe = [System.Security.Cryptography.PbeParameters]::new(
|
||||
[System.Security.Cryptography.PbeEncryptionAlgorithm]::Aes256Cbc,
|
||||
[System.Security.Cryptography.HashAlgorithmName]::SHA256, 600000)
|
||||
[IO.File]::WriteAllBytes($backupPath, $backup.ExportEncryptedPkcs8PrivateKey($plain, $pbe))
|
||||
$plain = $null
|
||||
|
||||
function KeyId([byte[]]$spki) {
|
||||
$h = [System.Security.Cryptography.SHA256]::HashData($spki)
|
||||
return ([Convert]::ToHexString($h, 0, 8)).ToLowerInvariant()
|
||||
}
|
||||
$keys = foreach ($k in @(@{ Name = "primary"; Key = $primary }, @{ Name = "backup"; Key = $backup })) {
|
||||
$spki = $k.Key.ExportSubjectPublicKeyInfo()
|
||||
[pscustomobject]@{ Name = $k.Name; Id = KeyId $spki; Base64 = [Convert]::ToBase64String($spki) }
|
||||
}
|
||||
|
||||
# Write the public keys between the markers in UpdateTrust.cs.
|
||||
$src = Get-Content $TrustFile -Raw
|
||||
$begin = "// BEGIN KEYS (New-UpdateSigningKey.ps1)"
|
||||
$end = "// END KEYS"
|
||||
$i = $src.IndexOf($begin); $j = $src.IndexOf($end)
|
||||
if ($i -lt 0 -or $j -lt $i) { throw "Key markers not found in $TrustFile" }
|
||||
$indent = " "
|
||||
$lines = $keys | ForEach-Object { "$indent`"$($_.Base64)`", // $($_.Name) $($_.Id)" }
|
||||
$new = $src.Substring(0, $i + $begin.Length) + "`r`n" + ($lines -join "`r`n") + "`r`n$indent" + $src.Substring($j)
|
||||
Set-Content -Path $TrustFile -Value $new -NoNewline -Encoding utf8
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Keys created in $KeyDir" -ForegroundColor Green
|
||||
$keys | ForEach-Object { Write-Host (" {0,-8} {1}" -f $_.Name, $_.Id) }
|
||||
Write-Host ""
|
||||
Write-Host "Public keys written to $TrustFile" -ForegroundColor Green
|
||||
Write-Host "Next:"
|
||||
Write-Host " 1. Move $backupPath OFFLINE (USB stick), then delete it here. Keep its password somewhere safe."
|
||||
Write-Host " 2. Commit UpdateTrust.cs, then publish with installer\Publish-Update.ps1 -Version <yyyy.m.d.n>."
|
||||
256
installer/Publish-Update.ps1
Normal file
256
installer/Publish-Update.ps1
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
#Requires -Version 7
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Builds, signs and publishes a RynthCore + RynthSuite release to the launchers' update feed.
|
||||
|
||||
.DESCRIPTION
|
||||
One command per release:
|
||||
1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped,
|
||||
if either repo has uncommitted changes, or if -Version isn't newer than the live feed.
|
||||
2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into
|
||||
installer\Releases\<release>\ — never into the live C:\Games folders.
|
||||
3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key
|
||||
(Sign-Update.ps1, no prompt) and checks the signature the way the launcher will.
|
||||
4. Uploads the release files, checks their hashes on the server, replaces the website's
|
||||
RynthCore-Setup.exe and RynthSuite-Plugins.zip (old ones kept in ~/backups/rynth),
|
||||
and swaps in update.json last, atomically.
|
||||
5. Fetches the live feed back and compares it byte for byte.
|
||||
|
||||
Launchers pick it up at their next check (start-up, every 6 hours, or the button). Plugins
|
||||
swap in place without touching running bots; the core installer waits until every
|
||||
RynthCore client is closed.
|
||||
|
||||
.EXAMPLE
|
||||
.\Publish-Update.ps1 -Version 2026.9.28.1 -Changes "Arrow crafting covers every head type.", "The Tell button works on players too."
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Version,
|
||||
# Release notes for players, one line per change: they become this release's entry in
|
||||
# downloads/rynth/releases.json, which the "What's new" list on aelrynth.com/rynth.html shows.
|
||||
[string[]]$Changes = @(),
|
||||
# Short text the launcher shows next to an available update; defaults to the changes.
|
||||
[string]$Notes = "",
|
||||
[switch]$DryRun, # build + sign + verify, upload nothing
|
||||
[switch]$AllowDirty, # publish with uncommitted changes (don't)
|
||||
[string]$SshHost = "aelrynth-vps",
|
||||
[string]$RemoteDir = "/var/www/site/downloads/rynth",
|
||||
[string]$BaseUrl = "https://aelrynth.com/downloads/rynth",
|
||||
[string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"),
|
||||
[string]$RynthSuiteRoot = "",
|
||||
[string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ScriptDir = $PSScriptRoot
|
||||
$RepoRoot = Split-Path $ScriptDir -Parent
|
||||
if (-not $RynthSuiteRoot) { $RynthSuiteRoot = Join-Path (Split-Path $RepoRoot -Parent) "RynthSuite" }
|
||||
if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalonia\UpdateTrust.cs" }
|
||||
|
||||
function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan }
|
||||
function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() }
|
||||
|
||||
# Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes.
|
||||
function Test-Envelope([string]$path, [string[]]$keys) {
|
||||
$envelope = Get-Content $path -Raw | ConvertFrom-Json
|
||||
$payload = [Convert]::FromBase64String($envelope.payload)
|
||||
foreach ($k in $keys) {
|
||||
$spki = [Convert]::FromBase64String($k)
|
||||
$id = ([Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData($spki), 0, 8)).ToLowerInvariant()
|
||||
$ec = [System.Security.Cryptography.ECDsa]::Create()
|
||||
$read = 0; $ec.ImportSubjectPublicKeyInfo($spki, [ref]$read)
|
||||
foreach ($s in $envelope.signatures) {
|
||||
if ($s.key -ne $id) { continue }
|
||||
if ($ec.VerifyData($payload, [Convert]::FromBase64String($s.sig),
|
||||
[System.Security.Cryptography.HashAlgorithmName]::SHA256,
|
||||
[System.Security.Cryptography.DSASignatureFormat]::IeeeP1363FixedFieldConcatenation)) { return $true }
|
||||
}
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# ── 1. Preconditions ─────────────────────────────────────────────────────────
|
||||
Step "Checking preconditions"
|
||||
$p = $Version.Split('.')
|
||||
if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' })) { throw "-Version must be yyyy.m.d.n, got '$Version'" }
|
||||
$release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3]
|
||||
if ($Changes.Count -eq 0 -and $Notes) { $Changes = @($Notes -split ';\s*' | Where-Object { $_ }) }
|
||||
if ($Changes.Count -eq 0) { throw "Give -Changes: the release notes players see on aelrynth.com/rynth.html (one string per change)." }
|
||||
if (-not $Notes) { $Notes = $Changes -join " " }
|
||||
|
||||
$trusted = [regex]::Matches((Get-Content $TrustFile -Raw), '"([A-Za-z0-9+/=]{80,})"') | ForEach-Object { $_.Groups[1].Value }
|
||||
if ($trusted.Count -lt 2) {
|
||||
throw "UpdateTrust.cs has $($trusted.Count) key(s); it needs the primary and the backup. Run New-UpdateSigningKey.ps1 and commit UpdateTrust.cs."
|
||||
}
|
||||
$probe = New-TemporaryFile
|
||||
try {
|
||||
Set-Content $probe "probe $release" -NoNewline
|
||||
& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath $probe -OutPath "$probe.sig" -KeyDir $KeyDir | Out-Null
|
||||
if (-not (Test-Envelope "$probe.sig" $trusted)) {
|
||||
throw "The signing key in $KeyDir is not one UpdateTrust.cs trusts: launchers would refuse this release."
|
||||
}
|
||||
} finally { Remove-Item $probe, "$probe.sig" -ErrorAction SilentlyContinue }
|
||||
Write-Host " signing key is trusted by the launcher ($($trusted.Count) keys)"
|
||||
|
||||
if (-not $AllowDirty) {
|
||||
foreach ($repo in $RepoRoot, $RynthSuiteRoot) {
|
||||
$dirty = git -C $repo status --porcelain --untracked-files=no
|
||||
if ($dirty) { throw "$repo has uncommitted changes — release from committed code (or pass -AllowDirty):`n$dirty" }
|
||||
}
|
||||
Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)"
|
||||
}
|
||||
|
||||
try {
|
||||
$live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20
|
||||
$liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release
|
||||
if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." }
|
||||
Write-Host " live feed is at $liveRelease; publishing $release"
|
||||
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
|
||||
Write-Host " no live feed yet — this is the first release"
|
||||
}
|
||||
|
||||
# ── 2. Build ─────────────────────────────────────────────────────────────────
|
||||
$rel = Join-Path $ScriptDir "Releases\$release"
|
||||
if (Test-Path $rel) { Remove-Item $rel -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null
|
||||
|
||||
Step "Building the installer ($Version)"
|
||||
& (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot
|
||||
if (-not $?) { throw "Build-Installer.ps1 failed" }
|
||||
Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe"
|
||||
Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\"
|
||||
|
||||
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision"
|
||||
foreach ($name in $suitePlugins) {
|
||||
Step "Building $name"
|
||||
$proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
|
||||
# PublishDir overrides the projects' own (RynthNav/RynthVision publish into the live C:\Games folders).
|
||||
dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" -v q -nologo
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" }
|
||||
Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\"
|
||||
}
|
||||
|
||||
Step "Packing RynthSuite-Plugins.zip"
|
||||
$zipRoot = "$rel\build\zip"
|
||||
foreach ($name in $suitePlugins) {
|
||||
New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null
|
||||
Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\"
|
||||
}
|
||||
$navSrc = "C:\Games\RynthCore\NavData"
|
||||
New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null
|
||||
Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } |
|
||||
Copy-Item -Destination "$zipRoot\RynthCore\NavData\"
|
||||
@"
|
||||
RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version
|
||||
|
||||
Extract this zip into C:\Games - it creates:
|
||||
C:\Games\RynthSuite\RynthChat\ RynthChat plugin
|
||||
C:\Games\RynthSuite\RynthNav\ RynthNav plugin
|
||||
C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin
|
||||
C:\Games\RynthSuite\RynthVision\ RynthVision plugin
|
||||
C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles
|
||||
|
||||
Then, in the RynthCore launcher's Plugins tab, add the full path of each
|
||||
plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which
|
||||
also installs RynthAi and the Loot Editor. After that the launcher keeps
|
||||
the plugins up to date by itself.
|
||||
|
||||
MIT licensed. https://aelrynth.com/projects.html
|
||||
"@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline
|
||||
Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal
|
||||
|
||||
# ── 3. Manifest + signature ──────────────────────────────────────────────────
|
||||
Step "Writing and signing the manifest"
|
||||
$setup = Get-Item "$rel\RynthCore-Setup.exe"
|
||||
$plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) {
|
||||
[ordered]@{
|
||||
name = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
|
||||
file = $dll.Name
|
||||
url = "$BaseUrl/releases/$release/plugins/$($dll.Name)"
|
||||
size = $dll.Length
|
||||
sha256 = Sha256 $dll.FullName
|
||||
}
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
schema = 1
|
||||
release = $release
|
||||
version = $Version
|
||||
published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
notes = $Notes
|
||||
core = [ordered]@{
|
||||
release = $release
|
||||
version = $Version
|
||||
url = "$BaseUrl/releases/$release/RynthCore-Setup.exe"
|
||||
size = $setup.Length
|
||||
sha256 = Sha256 $setup.FullName
|
||||
}
|
||||
plugins = @($plugins)
|
||||
}
|
||||
Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
|
||||
& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir
|
||||
if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" }
|
||||
Write-Host " verified against the launcher's trusted keys"
|
||||
|
||||
# Release notes: this release on top of the live list (a re-run replaces its own entry).
|
||||
$history = @()
|
||||
try { $history = @((Invoke-RestMethod "$BaseUrl/releases.json" -TimeoutSec 20).releases) }
|
||||
catch [Microsoft.PowerShell.Commands.HttpResponseException] { Write-Host " no releases.json yet — starting one" }
|
||||
$entry = [ordered]@{ version = $Version; date = (Get-Date -Format "yyyy-MM-dd"); changes = @($Changes) }
|
||||
$releaseNotes = [ordered]@{ releases = @($entry) + @($history | Where-Object { $_ -and $_.version -ne $Version }) }
|
||||
Set-Content "$rel\releases.json" ($releaseNotes | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
|
||||
Write-Host " releases.json: $($releaseNotes.releases.Count) release(s), $($Changes.Count) change(s) in this one"
|
||||
|
||||
if ($DryRun) {
|
||||
Write-Host ""; Write-Host "Dry run: release built and signed in $rel; nothing uploaded." -ForegroundColor Yellow
|
||||
return
|
||||
}
|
||||
|
||||
# ── 4. Upload ────────────────────────────────────────────────────────────────
|
||||
Step "Uploading release $release"
|
||||
$remoteRel = "$RemoteDir/releases/$release"
|
||||
ssh $SshHost "mkdir -p '$remoteRel/plugins'"
|
||||
if ($LASTEXITCODE -ne 0) { throw "ssh mkdir failed" }
|
||||
scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" }
|
||||
scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" }
|
||||
|
||||
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll"
|
||||
$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 }
|
||||
foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 }
|
||||
foreach ($line in $remoteSums) {
|
||||
$sum, $name = $line -split '\s+', 2
|
||||
if ($expect[$name.TrimStart('*')] -ne $sum) { throw "Hash mismatch on the server for $name — feed NOT published" }
|
||||
}
|
||||
Write-Host " $($expect.Count) files uploaded and hash-checked"
|
||||
|
||||
Step "Replacing the website downloads"
|
||||
scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$RemoteDir/.RynthCore-Setup.exe.new"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the website installer failed" }
|
||||
scp -q "$rel\RynthSuite-Plugins.zip" "${SshHost}:$RemoteDir/.RynthSuite-Plugins.zip.new"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of the plugins zip failed" }
|
||||
ssh $SshHost "set -e; mkdir -p ~/backups/rynth; cd '$RemoteDir'; for f in RynthCore-Setup.exe RynthSuite-Plugins.zip; do [ -f `$f ] && cp -p `$f ~/backups/rynth/`$f.before-$release || true; mv -f .`$f.new `$f; done"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Replacing the website downloads failed" }
|
||||
|
||||
Step "Publishing the feed"
|
||||
scp -q "$rel\update.json" "${SshHost}:$RemoteDir/.update.json.new"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of update.json failed" }
|
||||
ssh $SshHost "mv -f '$RemoteDir/.update.json.new' '$RemoteDir/update.json'"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Publishing update.json failed" }
|
||||
# The release notes follow the feed, so the page never lists a release launchers can't get yet.
|
||||
scp -q "$rel\releases.json" "${SshHost}:$RemoteDir/.releases.json.new"
|
||||
if ($LASTEXITCODE -ne 0) { throw "scp of releases.json failed" }
|
||||
ssh $SshHost "mv -f '$RemoteDir/.releases.json.new' '$RemoteDir/releases.json'"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Publishing releases.json failed" }
|
||||
|
||||
# ── 5. Verify ────────────────────────────────────────────────────────────────
|
||||
Step "Verifying the live feed"
|
||||
$tmp = New-TemporaryFile
|
||||
try {
|
||||
Invoke-WebRequest "$BaseUrl/update.json" -OutFile $tmp -UseBasicParsing -Headers @{ "Cache-Control" = "no-cache" }
|
||||
if ((Sha256 $tmp) -ne (Sha256 "$rel\update.json")) { throw "The live update.json differs from the one just signed!" }
|
||||
if (-not (Test-Envelope $tmp $trusted)) { throw "The live update.json does not verify!" }
|
||||
} finally { Remove-Item $tmp -ErrorAction SilentlyContinue }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Published RynthCore $Version (release $release)." -ForegroundColor Green
|
||||
Write-Host "Launchers pick it up at their next check, and aelrynth.com/rynth.html lists it. Still by hand: the public source snapshots."
|
||||
|
|
@ -1,7 +1,18 @@
|
|||
; RynthCore + RynthSuite Installer
|
||||
; Build with: Build-Installer.ps1 (requires Inno Setup 6)
|
||||
; RynthCore + RynthSuite full installer
|
||||
; Build with: Build-Installer.ps1 (requires Inno Setup 6) — it builds every component from source
|
||||
; (launcher, engine, loader, RynthAi plugin, Loot Editor, Monster Editor) and stages them under
|
||||
; installer\staging\core and installer\staging\suite before invoking ISCC on this file.
|
||||
; Source: https://jrsoftware.org/isdl.php
|
||||
;
|
||||
; Install locations are user-defined:
|
||||
; * RynthCore folder ({app}) — the standard "Select Destination Location" page
|
||||
; * RynthSuite folder ({code:GetSuiteDir}) — a second folder page right after it
|
||||
; Both are recorded under HKA\Software\Rynth (CoreDir / SuiteDir); the engine, launcher and plugins
|
||||
; resolve every path from there (RynthInstallPaths.cs), so neither folder has to be under C:\Games.
|
||||
; Silent installs: /DIR="<core folder>" /SUITEDIR="<suite folder>".
|
||||
; Prerequisite: when the .NET 10 Desktop Runtime (x86) is missing, the "installdotnet" task (on by default)
|
||||
; downloads it from Microsoft and installs it before the files are copied. A failure is reported, never fatal.
|
||||
;
|
||||
; NOTE: No ISPP (#define / {#...}) macros are used in this file.
|
||||
; Build-Installer.ps1 replaces the AppVersion placeholder via text substitution
|
||||
; before invoking ISCC, so the preprocessor has nothing to expand.
|
||||
|
|
@ -9,13 +20,17 @@
|
|||
; APPVERSION_PLACEHOLDER=0.0.0
|
||||
|
||||
[Setup]
|
||||
; Same AppId as every earlier RynthCore / RynthBundle installer, so this upgrades them in place.
|
||||
AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678}
|
||||
AppName=RynthCore
|
||||
AppVerName=RynthCore + RynthSuite 0.0.0
|
||||
AppVersion=0.0.0
|
||||
AppPublisher=RynthCore
|
||||
AppPublisherURL=https://github.com/tombohar/RynthCore
|
||||
AppPublisherURL=https://aelrynth.com/rynth.html
|
||||
UninstallDisplayName=RynthCore + RynthSuite
|
||||
DefaultDirName=C:\Games\RynthCore
|
||||
DisableDirPage=no
|
||||
UsePreviousAppDir=yes
|
||||
DefaultGroupName=RynthCore
|
||||
DisableProgramGroupPage=yes
|
||||
OutputDir=Output
|
||||
|
|
@ -28,265 +43,440 @@ WizardStyle=modern
|
|||
; the chosen install folder requires it (e.g. C:\Games\).
|
||||
PrivilegesRequired=lowest
|
||||
PrivilegesRequiredOverridesAllowed=dialog
|
||||
; 32-bit app; works on 32/64-bit Windows
|
||||
ArchitecturesAllowed=x86 x64 arm64
|
||||
; Close a running launcher / editors before replacing their files.
|
||||
CloseApplications=yes
|
||||
; 32-bit app; works on 32/64-bit Windows (HKA registry writes land in the 32-bit view,
|
||||
; which is exactly where RynthInstallPaths reads HKLM from).
|
||||
ArchitecturesAllowed=x86compatible
|
||||
ArchitecturesInstallIn64BitMode=
|
||||
|
||||
[Languages]
|
||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
[Types]
|
||||
Name: "full"; Description: "Full install (RynthCore + RynthSuite)"
|
||||
Name: "core"; Description: "RynthCore only"
|
||||
Name: "custom"; Description: "Custom"; Flags: iscustom
|
||||
|
||||
[Components]
|
||||
Name: "core"; Description: "RynthCore launcher, engine and Loot Editor"; Types: full core custom; Flags: fixed
|
||||
Name: "rynthai"; Description: "RynthSuite: RynthAi plugin (installed and registered with the launcher)"; Types: full
|
||||
Name: "monstereditor"; Description: "RynthSuite: Monster Editor"; Types: full
|
||||
; Experimental plugins: unchecked by default in every install type (ticking one switches to Custom).
|
||||
Name: "experimental"; Description: "RynthSuite: Experimental plugins (work in progress)"
|
||||
Name: "experimental\rynthchat"; Description: "RynthChat - replacement chat window (classifies and owns game chat)"
|
||||
Name: "experimental\rynthjuice"; Description: "RynthJuice - floating damage/heal numbers and kill bursts"
|
||||
Name: "experimental\rynthnav"; Description: "RynthNav - navmesh pathing and portal routing (needs baked NavData tiles)"
|
||||
Name: "experimental\rynthtracker"; Description: "RynthTracker - per-session kill tracker"
|
||||
Name: "experimental\rynthvision"; Description: "RynthVision - unclimbable slope, water and radar-range overlays"
|
||||
|
||||
[Tasks]
|
||||
Name: desktopicon; Description: "Create a &desktop shortcut"; GroupDescription: "Additional icons:"
|
||||
; Only offered when the runtime is missing. RynthCore and its tools are self-contained / NativeAOT and run
|
||||
; without it; it is installed for framework-dependent add-ons and tools. Skip silently with /MERGETASKS="!installdotnet".
|
||||
Name: installdotnet; Description: "Download and install the Microsoft .NET 10 Desktop Runtime (x86, about 55 MB; may ask for administrator approval)"; GroupDescription: "Prerequisites:"; Check: DotNet10DesktopMissing
|
||||
|
||||
; Files left by older layouts (the 0.4.x RynthBundle put a framework-dependent launcher, the engine
|
||||
; and plugins straight into {app}). Mixing those with a newer launcher is what broke 2026-10-04's
|
||||
; reinstall (RynthCore.App.Avalonia.dll from 0.4.7 + a newer deps.json → missing DesktopLog).
|
||||
; Only loose top-level binaries/metadata are removed; every file the new build needs is copied back
|
||||
; by [Files] right after. User data (Logs, AcClient, NavData, DecalBridge, ...) is never touched.
|
||||
[InstallDelete]
|
||||
Type: files; Name: "{app}\*.dll"
|
||||
Type: files; Name: "{app}\*.json"
|
||||
Type: files; Name: "{app}\*.pdb"
|
||||
Type: files; Name: "{app}\*.exp"
|
||||
Type: files; Name: "{app}\*.lib"
|
||||
Type: files; Name: "{app}\*.previous"
|
||||
Type: files; Name: "{app}\RynthCore.App.Avalonia.exe"
|
||||
Type: files; Name: "{app}\RynthCore-Prerequisites.txt"
|
||||
Type: files; Name: "{app}\Runtime\*.dll"
|
||||
Type: files; Name: "{app}\Runtime\*.json"
|
||||
Type: files; Name: "{app}\Runtime\*.pdb"
|
||||
Type: files; Name: "{app}\Runtime\RynthCore.Injector.exe"
|
||||
Type: filesandordirs; Name: "{app}\Runtime\Plugins"
|
||||
|
||||
; Program files
|
||||
[Files]
|
||||
; Installs the entire staging layout (launcher, Runtime\, Tools\, etc.)
|
||||
Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
; RynthCore: launcher, Runtime\ (engine, loader, native deps), Tools\LootEditor, release.txt
|
||||
Source: "staging\core\*"; DestDir: "{app}"; Components: core; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
|
||||
; Data directories (created once; never removed on uninstall)
|
||||
; RynthSuite: the RynthAi plugin lives next to its data folders in the chosen Suite folder.
|
||||
Source: "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Flags: ignoreversion
|
||||
; Monster Editor: RynthAi's dashboard launches it from <RynthAi>\MonsterEditor\.
|
||||
Source: "staging\suite\RynthAi\MonsterEditor\*"; DestDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
|
||||
; Experimental plugins: each in its own <RynthSuite>\<Name>\ folder (the layout the launcher already uses).
|
||||
Source: "staging\suite\RynthChat\RynthCore.Plugin.RynthChat.dll"; DestDir: "{code:GetSuiteDir}\RynthChat"; Components: experimental\rynthchat; Flags: ignoreversion
|
||||
Source: "staging\suite\RynthJuice\RynthCore.Plugin.RynthJuice.dll"; DestDir: "{code:GetSuiteDir}\RynthJuice"; Components: experimental\rynthjuice; Flags: ignoreversion
|
||||
Source: "staging\suite\RynthNav\RynthCore.Plugin.RynthNav.dll"; DestDir: "{code:GetSuiteDir}\RynthNav"; Components: experimental\rynthnav; Flags: ignoreversion
|
||||
Source: "staging\suite\RynthTracker\RynthCore.Plugin.RynthTracker.dll"; DestDir: "{code:GetSuiteDir}\RynthTracker"; Components: experimental\rynthtracker; Flags: ignoreversion
|
||||
Source: "staging\suite\RynthVision\RynthCore.Plugin.RynthVision.dll"; DestDir: "{code:GetSuiteDir}\RynthVision"; Components: experimental\rynthvision; Flags: ignoreversion
|
||||
; RynthNav reads <RynthCore>\NavData. Starter portal list only; a newer one from RynthNav.PortalGraph is kept.
|
||||
Source: "staging\navdata\portals.tsv"; DestDir: "{app}\NavData"; Components: experimental\rynthnav; Flags: onlyifdoesntexist uninsneveruninstall
|
||||
|
||||
; RynthAi data directories (created once; never removed on uninstall — they hold user profiles)
|
||||
[Dirs]
|
||||
Name: "C:\Games\RynthSuite\RynthAi"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\NavProfiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\LootProfiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\MetaFiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\MetaProfiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles\ACEmulator"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\MonsterProfiles"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\LuaScripts"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\Logs"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\pvars"; Flags: uninsneveruninstall
|
||||
Name: "C:\Games\RynthSuite\RynthAi\ItemGiver"; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\NavProfiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\LootProfiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\MetaFiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\MetaProfiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles\ACEmulator"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\MonsterProfiles"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\LuaScripts"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\Logs"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\pvars"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\ItemGiver"; Components: rynthai; Flags: uninsneveruninstall
|
||||
Name: "{code:GetSuiteDir}\RynthAi\AutoVendor"; Components: rynthai; Flags: uninsneveruninstall
|
||||
; RynthNav tiles baked by RynthNav.Baker (default --out) go here; kept on uninstall.
|
||||
Name: "{app}\NavData"; Components: experimental\rynthnav; Flags: uninsneveruninstall
|
||||
|
||||
; Install locations for the engine / launcher / plugins (see RynthInstallPaths.cs), plus a one-shot
|
||||
; hand-off the launcher consumes on next start to add the plugin to its Plugins list.
|
||||
; HKA = HKCU for a per-user install, HKLM for an all-users (elevated) install.
|
||||
[Registry]
|
||||
Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "CoreDir"; ValueData: "{app}"; Flags: uninsdeletevalue uninsdeletekeyifempty
|
||||
Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "SuiteDir"; ValueData: "{code:GetSuiteDir}"; Flags: uninsdeletevalue uninsdeletekeyifempty
|
||||
Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "PendingPluginRegistration"; ValueData: "{code:GetPendingPlugins}"; Check: HasPendingPlugins; Flags: uninsdeletevalue
|
||||
|
||||
; Shortcuts
|
||||
[Icons]
|
||||
; Start Menu
|
||||
Name: "{group}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Comment: "Launch RynthCore and inject into Asheron's Call"
|
||||
Name: "{group}\RynthCore Injector (CLI)"; Filename: "{app}\Runtime\RynthCore.Injector.exe"; WorkingDir: "{app}\Runtime"; Check: FileExists(ExpandConstant('{app}\Runtime\RynthCore.Injector.exe'))
|
||||
Name: "{group}\RynthCore Loot Editor"; Filename: "{app}\Tools\LootEditor\RynthCore.LootEditor.exe"; WorkingDir: "{app}\Tools\LootEditor"; Check: FileExists(ExpandConstant('{app}\Tools\LootEditor\RynthCore.LootEditor.exe'))
|
||||
Name: "{group}\RynthCore Monster Editor"; Filename: "{app}\Tools\MonsterEditor\RynthCore.MonsterEditor.exe"; WorkingDir: "{app}\Tools\MonsterEditor"; Check: FileExists(ExpandConstant('{app}\Tools\MonsterEditor\RynthCore.MonsterEditor.exe'))
|
||||
; RynthCore.exe / Injector bundle .NET 10 (x86) — no Start Menu link nudging users to install a
|
||||
; global runtime. See RynthCore-Prerequisites.txt for the optional x64 runtime (Loot/Monster tools).
|
||||
Name: "{group}\Loot Editor"; Filename: "{app}\Tools\LootEditor\RynthCore.LootEditor.exe"; WorkingDir: "{app}\Tools\LootEditor"; Comment: "Edit VTank-style loot profiles"
|
||||
Name: "{group}\Monster Editor"; Filename: "{code:GetSuiteDir}\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe"; WorkingDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Comment: "Edit RynthAi monster profiles"
|
||||
Name: "{group}\RynthSuite Folder"; Filename: "{code:GetSuiteDir}"; Components: rynthai
|
||||
Name: "{group}\Uninstall RynthCore"; Filename: "{uninstallexe}"
|
||||
|
||||
; Optional Desktop shortcut (created only when the desktopicon task is checked)
|
||||
Name: "{autodesktop}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
|
||||
; ── Advisory: .NET 10+ Desktop Runtime (x64) for Suite tools (Loot/Monster) ──────────────
|
||||
; RynthCore.exe and the injector are self-contained. Loot/Monster are x64 FDD and need a
|
||||
; machine runtime; this page informs only — Next is never disabled (Rynth client policy; not UB-ILT).
|
||||
; Registry rules below must match src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs (C#) — change both together.
|
||||
[Run]
|
||||
; Interactive install: offer to start the launcher on the last page.
|
||||
Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch RynthCore"; Flags: nowait postinstall skipifsilent
|
||||
; The launcher's updater runs this installer with /SILENT /RELAUNCH after closing itself;
|
||||
; bring it back when the upgrade is done.
|
||||
Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH')
|
||||
|
||||
[Code]
|
||||
const
|
||||
{ Official landing page: user picks the x64 Desktop Runtime download. }
|
||||
DotNet10DesktopDownloadUrl = 'https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime';
|
||||
DefaultSuiteDir = 'C:\Games\RynthSuite';
|
||||
{ Microsoft's permalink to the latest .NET 10 Desktop Runtime (x86 to match RynthCore's x86 binaries). }
|
||||
DotNetDesktopUrl = 'https://aka.ms/dotnet/10.0/windowsdesktop-runtime-win-x86.exe';
|
||||
DotNetDesktopFile = 'windowsdesktop-runtime-10-win-x86.exe';
|
||||
DotNetManualUrl = 'https://dotnet.microsoft.com/download/dotnet/10.0';
|
||||
|
||||
var
|
||||
PrereqPage: TWizardPage;
|
||||
PrereqStatus: TNewStaticText;
|
||||
PrereqButtonDownload: TNewButton;
|
||||
PrereqButtonRecheck: TNewButton;
|
||||
SuiteDirPage: TInputDirWizardPage;
|
||||
DotNetDownloadPage: TDownloadWizardPage;
|
||||
{ Set once the .NET step ran (interactive: on leaving the Ready page; silent: in PrepareToInstall). }
|
||||
DotNetHandled: Boolean;
|
||||
{ True once the user (or /SUITEDIR / a previous install) chose the Suite folder explicitly;
|
||||
until then it follows the RynthCore folder as a sibling "RynthSuite" folder. }
|
||||
SuiteDirPinned: Boolean;
|
||||
|
||||
{ Path A: shared Windows Desktop pack (FDD for WinForms/WPF) — e.g. Microsoft.WindowsDesktop.App\10.0.0 }
|
||||
function IsWindowsDesktopSharedFramework10Plus: Boolean;
|
||||
function CmdLineParamExists(const Value: string): Boolean;
|
||||
var
|
||||
Names: TArrayOfString;
|
||||
I, Major, DotPos: Integer;
|
||||
S: String;
|
||||
begin
|
||||
Result := False;
|
||||
if not RegGetSubkeyNames(HKLM64, 'SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App', Names) then
|
||||
Exit;
|
||||
for I := 0 to GetArrayLength(Names) - 1 do
|
||||
begin
|
||||
S := Names[I];
|
||||
DotPos := Pos('.', S);
|
||||
if DotPos > 0 then
|
||||
begin
|
||||
Major := StrToIntDef(Copy(S, 1, DotPos - 1), 0);
|
||||
if Major >= 10 then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Path B: .NET host registration (see learn.microsoft.com runtime discovery) — sharedhost Version 10+.
|
||||
Uses HKLM64\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost\Version
|
||||
and the parallel Microsoft\dotnet\Setup key when present. }
|
||||
function IsSharedHostVersion10PlusX64: Boolean;
|
||||
var
|
||||
V: String;
|
||||
DotPos: Integer;
|
||||
Major: Integer;
|
||||
begin
|
||||
Result := False;
|
||||
if RegQueryStringValue(HKLM64, 'SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost', 'Version', V) then
|
||||
begin
|
||||
DotPos := Pos('.', V);
|
||||
if DotPos > 0 then
|
||||
begin
|
||||
Major := StrToIntDef(Copy(V, 1, DotPos - 1), 0);
|
||||
if Major >= 10 then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
if RegQueryStringValue(HKLM64, 'SOFTWARE\Microsoft\dotnet\Setup\InstalledVersions\x64\sharedhost', 'Version', V) then
|
||||
begin
|
||||
DotPos := Pos('.', V);
|
||||
if DotPos > 0 then
|
||||
begin
|
||||
Major := StrToIntDef(Copy(V, 1, DotPos - 1), 0);
|
||||
if Major >= 10 then
|
||||
Result := True;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Path C: SDK / workload bands under Microsoft\dotnet\InstalledManifests\x64
|
||||
(e.g. ...Manifest-10.0.100). }
|
||||
function IsDotNet10BandInInstalledManifestsX64: Boolean;
|
||||
var
|
||||
Names: TArrayOfString;
|
||||
I: Integer;
|
||||
S, L: String;
|
||||
begin
|
||||
Result := False;
|
||||
if not RegGetSubkeyNames(HKLM64, 'SOFTWARE\Microsoft\dotnet\InstalledManifests\x64', Names) then
|
||||
Exit;
|
||||
for I := 0 to GetArrayLength(Names) - 1 do
|
||||
begin
|
||||
S := Names[I];
|
||||
L := LowerCase(S);
|
||||
if Pos('manifest-10.', L) > 0 then
|
||||
for I := 1 to ParamCount do
|
||||
if CompareText(ParamStr(I), Value) = 0 then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Returns the value of a /NAME=value command-line switch, or '' when absent. }
|
||||
function CmdLineParamValue(const Name: string): string;
|
||||
var
|
||||
I: Integer;
|
||||
Prefix: string;
|
||||
begin
|
||||
Result := '';
|
||||
Prefix := '/' + Name + '=';
|
||||
for I := 1 to ParamCount do
|
||||
if CompareText(Copy(ParamStr(I), 1, Length(Prefix)), Prefix) = 0 then
|
||||
begin
|
||||
Result := RemoveQuotes(Copy(ParamStr(I), Length(Prefix) + 1, MaxInt));
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Suite folder recorded by an earlier install in the SAME install mode (HKA: HKCU per-user, HKLM all-users),
|
||||
or ''. Never adopt the other mode's folder: two installs sharing a Suite folder would delete each other's
|
||||
files on uninstall. }
|
||||
function RegisteredSuiteDir: string;
|
||||
begin
|
||||
Result := '';
|
||||
if not RegQueryStringValue(HKA, 'Software\Rynth', 'SuiteDir', Result) then
|
||||
Result := '';
|
||||
end;
|
||||
|
||||
{ Default Suite folder for a given RynthCore folder: its sibling "RynthSuite". }
|
||||
function SiblingSuiteDir(const CoreDir: string): string;
|
||||
begin
|
||||
Result := AddBackslash(ExtractFileDir(RemoveBackslashUnlessRoot(CoreDir))) + 'RynthSuite';
|
||||
end;
|
||||
|
||||
// {code:GetSuiteDir}: the chosen RynthSuite folder, without a trailing backslash.
|
||||
function GetSuiteDir(Param: string): string;
|
||||
begin
|
||||
if SuiteDirPage = nil then
|
||||
Result := DefaultSuiteDir
|
||||
else if WizardSilent and not SuiteDirPinned then
|
||||
{ Silent installs never run NextButtonClick: follow /DIR= with a sibling RynthSuite folder. }
|
||||
Result := SiblingSuiteDir(WizardDirValue)
|
||||
else
|
||||
Result := RemoveBackslashUnlessRoot(Trim(SuiteDirPage.Values[0]));
|
||||
end;
|
||||
|
||||
// Experimental plugin names; component "experimental\<lowercase name>" installs <Suite>\<Name>\RynthCore.Plugin.<Name>.dll.
|
||||
function ExperimentalPluginName(Index: Integer): string;
|
||||
begin
|
||||
case Index of
|
||||
0: Result := 'RynthChat';
|
||||
1: Result := 'RynthJuice';
|
||||
2: Result := 'RynthNav';
|
||||
3: Result := 'RynthTracker';
|
||||
4: Result := 'RynthVision';
|
||||
else
|
||||
Result := '';
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Satisfied if desktop pack 10+, InstalledManifests 10.x band, or x64 sharedhost Version 10+ (Path B). }
|
||||
function IsNetDesktop10PlusX64Present: Boolean;
|
||||
function ExperimentalSelected(Index: Integer): Boolean;
|
||||
begin
|
||||
Result := WizardIsComponentSelected('experimental\' + Lowercase(ExperimentalPluginName(Index)));
|
||||
end;
|
||||
|
||||
{ True when anything is going into the RynthSuite folder (controls the Suite folder page / memo line). }
|
||||
function AnySuiteComponentSelected: Boolean;
|
||||
var
|
||||
I: Integer;
|
||||
begin
|
||||
Result := WizardIsComponentSelected('rynthai') or WizardIsComponentSelected('monstereditor');
|
||||
for I := 0 to 4 do
|
||||
if ExperimentalSelected(I) then
|
||||
Result := True;
|
||||
end;
|
||||
|
||||
// {code:GetPendingPlugins}: ';'-separated plugin DLLs for the launcher to add to its Plugins list on next start.
|
||||
function GetPendingPlugins(Param: string): string;
|
||||
var
|
||||
I: Integer;
|
||||
Name: string;
|
||||
begin
|
||||
Result := '';
|
||||
if WizardIsComponentSelected('rynthai') then
|
||||
Result := GetSuiteDir('') + '\RynthAi\RynthCore.Plugin.RynthAi.dll';
|
||||
for I := 0 to 4 do
|
||||
if ExperimentalSelected(I) then
|
||||
begin
|
||||
Name := ExperimentalPluginName(I);
|
||||
if Result <> '' then
|
||||
Result := Result + ';';
|
||||
Result := Result + GetSuiteDir('') + '\' + Name + '\RynthCore.Plugin.' + Name + '.dll';
|
||||
end;
|
||||
end;
|
||||
|
||||
function HasPendingPlugins: Boolean;
|
||||
begin
|
||||
Result := GetPendingPlugins('') <> '';
|
||||
end;
|
||||
|
||||
{ ── .NET 10 Desktop Runtime (x86) ─────────────────────────────────────────── }
|
||||
|
||||
{ True when Root (a ...\shared\Microsoft.WindowsDesktop.App folder) holds a 10.x version folder. }
|
||||
function HasVersion10Folder(const Root: string): Boolean;
|
||||
var
|
||||
FindRec: TFindRec;
|
||||
begin
|
||||
Result := False;
|
||||
{ 32-bit Windows: no x64 Desktop host; treat as "not applicable" and let setup proceed. }
|
||||
if (not IsWin64) then
|
||||
begin
|
||||
Result := True;
|
||||
if FindFirst(AddBackslash(Root) + '10.*', FindRec) then
|
||||
try
|
||||
repeat
|
||||
if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY <> 0 then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
until not FindNext(FindRec);
|
||||
finally
|
||||
FindClose(FindRec);
|
||||
end;
|
||||
end;
|
||||
|
||||
{ Detects the x86 Desktop Runtime 10.x the way the .NET host does: the shared framework folder under
|
||||
Program Files (x86)\dotnet, or the installer's registration in the 32-bit registry view. }
|
||||
function IsDotNet10DesktopX86Installed: Boolean;
|
||||
var
|
||||
Names: TArrayOfString;
|
||||
I: Integer;
|
||||
begin
|
||||
Result := HasVersion10Folder(ExpandConstant('{commonpf32}\dotnet\shared\Microsoft.WindowsDesktop.App'));
|
||||
if Result then Exit;
|
||||
if RegGetValueNames(HKLM32, 'SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App', Names) then
|
||||
for I := 0 to GetArrayLength(Names) - 1 do
|
||||
if Copy(Names[I], 1, 3) = '10.' then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
|
||||
// Check function for the installdotnet task: offer it only when the runtime is missing.
|
||||
function DotNet10DesktopMissing: Boolean;
|
||||
begin
|
||||
Result := not IsDotNet10DesktopX86Installed;
|
||||
end;
|
||||
|
||||
function OnDotNetDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;
|
||||
begin
|
||||
Result := True; { never cancel from code; the download page has its own Abort button }
|
||||
end;
|
||||
|
||||
{ Downloads and runs the .NET 10 Desktop Runtime installer when the task is selected and the runtime is
|
||||
still missing. Returns '' on success / nothing to do, else a reason. Never blocks the RynthCore install. }
|
||||
function InstallDotNetRuntime(UsePage: Boolean): string;
|
||||
var
|
||||
SetupPath: string;
|
||||
ResultCode: Integer;
|
||||
begin
|
||||
Result := '';
|
||||
DotNetHandled := True;
|
||||
if not WizardIsTaskSelected('installdotnet') or IsDotNet10DesktopX86Installed then
|
||||
Exit;
|
||||
|
||||
Log('.NET 10 Desktop Runtime (x86) missing; downloading ' + DotNetDesktopUrl);
|
||||
try
|
||||
if UsePage then
|
||||
begin
|
||||
DotNetDownloadPage.Clear;
|
||||
DotNetDownloadPage.Add(DotNetDesktopUrl, DotNetDesktopFile, '');
|
||||
DotNetDownloadPage.Show;
|
||||
try
|
||||
DotNetDownloadPage.Download;
|
||||
finally
|
||||
DotNetDownloadPage.Hide;
|
||||
end;
|
||||
end
|
||||
else
|
||||
DownloadTemporaryFile(DotNetDesktopUrl, DotNetDesktopFile, '', @OnDotNetDownloadProgress);
|
||||
except
|
||||
Result := 'the download failed (' + GetExceptionMessage + ')';
|
||||
Exit;
|
||||
end;
|
||||
if IsWindowsDesktopSharedFramework10Plus or IsDotNet10BandInInstalledManifestsX64 or IsSharedHostVersion10PlusX64 then
|
||||
Result := True;
|
||||
end;
|
||||
|
||||
procedure PrereqUpdateStatus;
|
||||
var
|
||||
Ok: Boolean;
|
||||
begin
|
||||
Ok := IsNetDesktop10PlusX64Present;
|
||||
if Ok then
|
||||
PrereqStatus.Font.Color := $008000
|
||||
{ The runtime's own bundle asks for elevation (UAC) itself when this setup is not elevated. }
|
||||
SetupPath := ExpandConstant('{tmp}\' + DotNetDesktopFile);
|
||||
Log('Running ' + SetupPath + ' /install /quiet /norestart');
|
||||
if not ShellExec('', SetupPath, '/install /quiet /norestart', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
|
||||
Result := 'its installer could not be started (' + SysErrorMessage(ResultCode) + ')'
|
||||
{ 0 = installed, 3010/1641 = installed (restart pending/started), 1638 = a newer version is already installed }
|
||||
else if (ResultCode <> 0) and (ResultCode <> 3010) and (ResultCode <> 1641) and (ResultCode <> 1638) then
|
||||
Result := 'its installer exited with code ' + IntToStr(ResultCode) + ' (1602 = cancelled)'
|
||||
else
|
||||
PrereqStatus.Font.Color := $0000FF;
|
||||
if (not IsWin64) then
|
||||
begin
|
||||
PrereqStatus.Font.Color := $004040;
|
||||
PrereqStatus.Caption := '32-bit Windows: the bundled Loot/Monster tools need a 64-bit OS; ' +
|
||||
'RynthCore.exe will still be installed. You can skip the .NET x64 check.';
|
||||
end
|
||||
else if Ok then
|
||||
PrereqStatus.Caption := 'Microsoft .NET Desktop Runtime 10 or newer (x64) is already installed. You can continue.'
|
||||
else
|
||||
PrereqStatus.Caption := 'Not detected: Microsoft .NET 10+ Desktop Runtime (x64) for the Loot/Monster tools. ' +
|
||||
'You can still continue — RynthCore.exe does not need this. Install the x64 Desktop runtime when you use those tools ' +
|
||||
'(use "Open download page" / "Check again").' + #13#10#13#10 +
|
||||
'RynthCore ships with its own .NET for the launcher and injector.';
|
||||
PrereqButtonRecheck.Enabled := not Ok;
|
||||
{ Always allow Next: advisory-only page for the Rynth bundle installer. }
|
||||
WizardForm.NextButton.Enabled := True;
|
||||
Log('.NET 10 Desktop Runtime installer finished, exit code ' + IntToStr(ResultCode));
|
||||
end;
|
||||
|
||||
procedure PrereqOpenDownloadClick(Sender: TObject);
|
||||
{ Runs the .NET step and reports (but never fails on) a problem. }
|
||||
procedure HandleDotNetRuntime(UsePage: Boolean);
|
||||
var
|
||||
E: Integer;
|
||||
Problem: string;
|
||||
begin
|
||||
if not ShellExec('open', DotNet10DesktopDownloadUrl, '', '', SW_SHOWNORMAL, ewNoWait, E) then
|
||||
MsgBox('Could not open the web browser. Copy this address:'#13#10#13#10 + DotNet10DesktopDownloadUrl, mbError, MB_OK);
|
||||
end;
|
||||
|
||||
procedure PrereqRecheckClick(Sender: TObject);
|
||||
begin
|
||||
PrereqUpdateStatus;
|
||||
Problem := InstallDotNetRuntime(UsePage);
|
||||
if Problem = '' then Exit;
|
||||
Log('.NET 10 Desktop Runtime was not installed: ' + Problem);
|
||||
if not WizardSilent then
|
||||
MsgBox('The Microsoft .NET 10 Desktop Runtime could not be installed: ' + Problem + '.' + #13#10#13#10 +
|
||||
'RynthCore will still be installed and works without it (it is self-contained). ' +
|
||||
'You can install the runtime later from:' + #13#10 + DotNetManualUrl, mbInformation, MB_OK);
|
||||
end;
|
||||
|
||||
procedure InitializeWizard;
|
||||
var
|
||||
RowTop: Integer;
|
||||
Initial: string;
|
||||
begin
|
||||
PrereqPage := CreateCustomPage(
|
||||
wpWelcome,
|
||||
'Optional runtime (Suite tools)',
|
||||
'The Loot Editor and Monster Editor are x64 apps and need the Microsoft .NET 10+ Desktop Runtime (x64) on the PC to run. ' +
|
||||
'Setup does not require it to finish — RynthCore.exe and the injector bundle their own .NET.'
|
||||
);
|
||||
PrereqStatus := TNewStaticText.Create(PrereqPage);
|
||||
with PrereqStatus do
|
||||
begin
|
||||
Parent := PrereqPage.Surface;
|
||||
Top := 0;
|
||||
Left := 0;
|
||||
WordWrap := True;
|
||||
AutoSize := False;
|
||||
Height := 128;
|
||||
Width := PrereqPage.SurfaceWidth;
|
||||
end;
|
||||
RowTop := PrereqStatus.Top + PrereqStatus.Height + 16;
|
||||
PrereqButtonDownload := TNewButton.Create(PrereqPage);
|
||||
with PrereqButtonDownload do
|
||||
begin
|
||||
Parent := PrereqPage.Surface;
|
||||
Top := RowTop;
|
||||
Left := 0;
|
||||
Width := 200;
|
||||
Caption := 'Open download page';
|
||||
OnClick := @PrereqOpenDownloadClick;
|
||||
end;
|
||||
PrereqButtonRecheck := TNewButton.Create(PrereqPage);
|
||||
with PrereqButtonRecheck do
|
||||
begin
|
||||
Parent := PrereqPage.Surface;
|
||||
Top := RowTop;
|
||||
Left := PrereqButtonDownload.Left + PrereqButtonDownload.Width + 12;
|
||||
Width := 160;
|
||||
Caption := 'Check again';
|
||||
OnClick := @PrereqRecheckClick;
|
||||
end;
|
||||
PrereqUpdateStatus;
|
||||
{ After the Components page, so ShouldSkipPage knows whether any Suite component was picked. }
|
||||
SuiteDirPage := CreateInputDirPage(wpSelectComponents,
|
||||
'Select RynthSuite Location',
|
||||
'Where should the RynthSuite plugins and their data be installed?',
|
||||
'RynthAi, the Monster Editor and any experimental plugins you picked will be installed into the RynthSuite folder below, and your ' +
|
||||
'profiles (nav, loot, meta, settings) are kept there. To continue, click Next. ' +
|
||||
'If you would like to select a different folder, click Browse.',
|
||||
False, 'RynthSuite');
|
||||
SuiteDirPage.Add('');
|
||||
|
||||
{ Priority: /SUITEDIR= → previous install of this setup → registry → C:\Games\RynthSuite. }
|
||||
Initial := CmdLineParamValue('SUITEDIR');
|
||||
if Initial = '' then Initial := GetPreviousData('SuiteDir', '');
|
||||
if Initial = '' then Initial := RegisteredSuiteDir;
|
||||
SuiteDirPinned := Initial <> '';
|
||||
if Initial = '' then Initial := DefaultSuiteDir;
|
||||
SuiteDirPage.Values[0] := Initial;
|
||||
|
||||
{ Progress page for the optional .NET 10 Desktop Runtime download (shown only when that task runs). }
|
||||
DotNetDownloadPage := CreateDownloadPage('Downloading Prerequisites',
|
||||
'Downloading the Microsoft .NET 10 Desktop Runtime (x86)...', @OnDotNetDownloadProgress);
|
||||
end;
|
||||
|
||||
procedure CurPageChanged(CurPageID: Integer);
|
||||
procedure RegisterPreviousData(PreviousDataKey: Integer);
|
||||
begin
|
||||
if (PrereqPage <> nil) and (CurPageID = PrereqPage.ID) then
|
||||
PrereqUpdateStatus;
|
||||
SetPreviousData(PreviousDataKey, 'SuiteDir', GetSuiteDir(''));
|
||||
end;
|
||||
|
||||
function ShouldSkipPage(PageID: Integer): Boolean;
|
||||
begin
|
||||
{ Silent (or very silent) install: no GUI to open the download page. Admin must pre-install the x64 runtime. }
|
||||
if (PrereqPage <> nil) and (PageID = PrereqPage.ID) and WizardSilent then
|
||||
Result := True
|
||||
else
|
||||
Result := False;
|
||||
{ No Suite components selected → no Suite folder to choose. }
|
||||
Result := (SuiteDirPage <> nil) and (PageID = SuiteDirPage.ID) and not AnySuiteComponentSelected;
|
||||
end;
|
||||
|
||||
function NextButtonClick(CurPageID: Integer): Boolean;
|
||||
var
|
||||
Dir: string;
|
||||
begin
|
||||
{ Prereq page is advisory only — never block Next on .NET detection (Rynth client installer only). }
|
||||
Result := True;
|
||||
|
||||
{ Leaving the RynthCore folder page: keep an un-pinned Suite folder beside the chosen Core folder. }
|
||||
if (CurPageID = wpSelectDir) and not SuiteDirPinned then
|
||||
SuiteDirPage.Values[0] := SiblingSuiteDir(WizardDirValue);
|
||||
|
||||
if (SuiteDirPage <> nil) and (CurPageID = SuiteDirPage.ID) then
|
||||
begin
|
||||
Dir := GetSuiteDir('');
|
||||
{ Require an absolute local or UNC path (e.g. D:\Games\RynthSuite or \\server\share\RynthSuite). }
|
||||
if (Length(Dir) < 3) or not ((Copy(Dir, 2, 2) = ':\') or (Copy(Dir, 1, 2) = '\\')) then
|
||||
begin
|
||||
MsgBox('Please choose a full folder path for RynthSuite, for example D:\Games\RynthSuite.', mbError, MB_OK);
|
||||
Result := False;
|
||||
Exit;
|
||||
end;
|
||||
SuiteDirPinned := True;
|
||||
end;
|
||||
|
||||
{ Leaving the Ready page: fetch/install the .NET runtime first (with a progress page) if that task is on. }
|
||||
if CurPageID = wpReady then
|
||||
HandleDotNetRuntime(True);
|
||||
end;
|
||||
|
||||
// Silent installs skip the wizard pages, so the .NET step runs here instead (no progress page). Never blocks.
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
begin
|
||||
if not DotNetHandled then
|
||||
HandleDotNetRuntime(False);
|
||||
Result := '';
|
||||
end;
|
||||
|
||||
function UpdateReadyMemo(Space, NewLine, MemoUserInfoInfo, MemoDirInfo, MemoTypeInfo,
|
||||
MemoComponentsInfo, MemoGroupInfo, MemoTasksInfo: String): String;
|
||||
begin
|
||||
Result := MemoDirInfo + NewLine;
|
||||
if AnySuiteComponentSelected then
|
||||
Result := Result + 'RynthSuite location:' + NewLine + Space + GetSuiteDir('') + NewLine;
|
||||
Result := Result + NewLine + MemoComponentsInfo;
|
||||
if MemoTasksInfo <> '' then
|
||||
Result := Result + NewLine + MemoTasksInfo;
|
||||
end;
|
||||
|
|
|
|||
58
installer/Sign-Update.ps1
Normal file
58
installer/Sign-Update.ps1
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#Requires -Version 7
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Signs an update manifest into the envelope the launcher verifies (RynthUpdater.VerifyEnvelope).
|
||||
|
||||
.DESCRIPTION
|
||||
Output: {"payload": base64(manifest bytes), "signatures": [{"key": <id>, "sig": base64}]},
|
||||
ECDSA P-256 / SHA-256 over the exact payload bytes, IEEE P1363 format. Signs with the DPAPI
|
||||
primary key from New-UpdateSigningKey.ps1 — no prompt — or, with -UseBackupKey, the offline
|
||||
backup key (asks for its password).
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$PayloadPath,
|
||||
[Parameter(Mandatory)][string]$OutPath,
|
||||
[string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"),
|
||||
[switch]$UseBackupKey,
|
||||
[string]$BackupKeyPath,
|
||||
# For scripted tests only; normally you are prompted.
|
||||
[SecureString]$BackupPassword
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Add-Type -AssemblyName System.Security
|
||||
|
||||
$ec = [System.Security.Cryptography.ECDsa]::Create()
|
||||
if ($UseBackupKey) {
|
||||
if (-not $BackupKeyPath) { $BackupKeyPath = Join-Path $KeyDir "backup.key.p8" }
|
||||
if (-not (Test-Path $BackupKeyPath)) { throw "Backup key not found at $BackupKeyPath" }
|
||||
if (-not $BackupPassword) { $BackupPassword = Read-Host "Backup key password" -AsSecureString }
|
||||
$pw = ConvertFrom-SecureString $BackupPassword -AsPlainText
|
||||
$read = 0
|
||||
$ec.ImportEncryptedPkcs8PrivateKey($pw, [IO.File]::ReadAllBytes($BackupKeyPath), [ref]$read)
|
||||
$pw = $null
|
||||
} else {
|
||||
$primaryPath = Join-Path $KeyDir "primary.key"
|
||||
if (-not (Test-Path $primaryPath)) {
|
||||
throw "No signing key at $primaryPath. Run installer\New-UpdateSigningKey.ps1 first."
|
||||
}
|
||||
$entropy = [Text.Encoding]::UTF8.GetBytes("RynthCore update signing v1")
|
||||
$pkcs8 = [System.Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($primaryPath), $entropy, 'CurrentUser')
|
||||
try {
|
||||
$read = 0
|
||||
$ec.ImportPkcs8PrivateKey($pkcs8, [ref]$read)
|
||||
} finally { [Array]::Clear($pkcs8) }
|
||||
}
|
||||
|
||||
$payload = [IO.File]::ReadAllBytes($PayloadPath)
|
||||
$sig = $ec.SignData($payload, [System.Security.Cryptography.HashAlgorithmName]::SHA256,
|
||||
[System.Security.Cryptography.DSASignatureFormat]::IeeeP1363FixedFieldConcatenation)
|
||||
$spki = $ec.ExportSubjectPublicKeyInfo()
|
||||
$id = ([Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData($spki), 0, 8)).ToLowerInvariant()
|
||||
|
||||
$envelope = [ordered]@{
|
||||
payload = [Convert]::ToBase64String($payload)
|
||||
signatures = @([ordered]@{ key = $id; sig = [Convert]::ToBase64String($sig) })
|
||||
}
|
||||
Set-Content -Path $OutPath -Value ($envelope | ConvertTo-Json -Depth 4) -Encoding utf8NoBOM
|
||||
Write-Host "Signed $PayloadPath with key $id -> $OutPath"
|
||||
|
|
@ -1 +1 @@
|
|||
0.4.10
|
||||
2026.10.4.6
|
||||
|
|
|
|||
38
native/SehTrampoline/Build-SehTrampoline.ps1
Normal file
38
native/SehTrampoline/Build-SehTrampoline.ps1
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Build-SehTrampoline.ps1
|
||||
# Compiles RynthCore.SehTrampoline.dll (x86 MSVC) and copies to the runtime.
|
||||
# Run from anywhere; finds VS automatically via vswhere.
|
||||
|
||||
$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"
|
||||
New-Item -ItemType Directory -Path $out -Force | Out-Null
|
||||
|
||||
Write-Host "Compiling SehTrampoline.c (MSVC $vcVer, x86)..."
|
||||
Set-Location $out
|
||||
& $cl /nologo /O2 /MT /GS- /LD /W3 "$src\SehTrampoline.c" `
|
||||
/link /MACHINE:X86 /OUT:"$out\RynthCore.SehTrampoline.dll"
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
|
||||
|
||||
$size = (Get-Item "$out\RynthCore.SehTrampoline.dll").Length
|
||||
Write-Host "Built: RynthCore.SehTrampoline.dll ($size bytes)"
|
||||
|
||||
$runtimeDst = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll"
|
||||
Copy-Item "$out\RynthCore.SehTrampoline.dll" $runtimeDst -Force
|
||||
Write-Host "Deployed to $runtimeDst"
|
||||
439
native/SehTrampoline/SehTrampoline.c
Normal file
439
native/SehTrampoline/SehTrampoline.c
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
/*
|
||||
* RynthCore.SehTrampoline.dll — x86 native SEH wrapper for dangerous AC API calls.
|
||||
*
|
||||
* NativeAOT managed try/catch cannot intercept access violations (hardware
|
||||
* exceptions / corrupted-state exceptions). When the bot calls AC APIs on
|
||||
* objects that are being torn down by the client's object lifecycle, the AV
|
||||
* propagates up and kills acclient.exe.
|
||||
*
|
||||
* This DLL provides __try/__except wrappers that live entirely in native code.
|
||||
* Each export calls a supplied function pointer inside a structured exception
|
||||
* handler scoped only to that one call — it does not install any process-wide
|
||||
* handler (VEH/SUEF), so it cannot interfere with AC's or Avalonia's own
|
||||
* internal exception handling.
|
||||
*
|
||||
* Conventions:
|
||||
* - All exports are __cdecl so the caller controls stack cleanup.
|
||||
* - Return value: 1 = call completed normally; 0 = AV was caught.
|
||||
* - out_* parameters are always written (safe default on AV).
|
||||
* - __thiscall helpers are separate non-__try functions; MSVC does not allow
|
||||
* inline __asm and __try in the same function on x86.
|
||||
*
|
||||
* Build: cl /nologo /O2 /MD /LD SehTrampoline.c /link /MACHINE:X86
|
||||
* /OUT:RynthCore.SehTrampoline.dll /DEF:SehTrampoline.def
|
||||
*/
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved)
|
||||
{
|
||||
(void)hModule; (void)ul_reason; (void)lpReserved;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/* ── Cdecl helpers ─────────────────────────────────────────────────────── */
|
||||
|
||||
/* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */
|
||||
typedef void* (__cdecl *Fn_CdeclPtrUint)(unsigned int);
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result)
|
||||
{
|
||||
*out_result = NULL;
|
||||
__try {
|
||||
*out_result = fn(arg);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
*out_result = NULL;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* void* __cdecl fn() — e.g. GetCombatSystem */
|
||||
typedef void* (__cdecl *Fn_CdeclPtrVoid)(void);
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result)
|
||||
{
|
||||
*out_result = NULL;
|
||||
__try {
|
||||
*out_result = fn();
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
*out_result = NULL;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* void __cdecl fn(unsigned int, unsigned char) — e.g. CastSpell(spellId, targetIsSelected) */
|
||||
typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char);
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2)
|
||||
{
|
||||
__try {
|
||||
fn(arg1, arg2);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* void __thiscall fn(this, unsigned int spellId, unsigned int targetId)
|
||||
* e.g. ClientMagicSystem::FreeHandsAndCastSpell(this, spellId, targetId) @ 0x00567C90.
|
||||
* Modeled as __fastcall (this in ECX, a dummy EDX slot, spellId+targetId on the stack;
|
||||
* callee cleans the 8 stack bytes) — the exact, proven binding RynthSuite2 uses. The
|
||||
* target is an EXPLICIT argument, so this never reads AC's global selection and never
|
||||
* touches UI state (unlike CastSpell(spellId, targetIsSelected=1) @ 0x00568DE0, which
|
||||
* reads [magicSysSingleton+0xF4]). __fastcall is a real declarable convention, so this
|
||||
* needs no inline __asm and can host its own __try. */
|
||||
typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int spellId, unsigned int targetId);
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId)
|
||||
{
|
||||
__try {
|
||||
((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ── Thiscall helpers — inline __asm lives here, NOT in __try functions ── */
|
||||
|
||||
/*
|
||||
* MSVC x86: __thiscall puts 'this' in ECX. C has no __thiscall call-site
|
||||
* syntax, so we use inline __asm. These helpers must NOT contain __try;
|
||||
* the outer SEH wrappers call them so the SEH frame is established by the
|
||||
* caller's stack frame, not by the helper.
|
||||
*/
|
||||
|
||||
/* unsigned char __thiscall fn(unsigned int objectId) */
|
||||
static unsigned char __cdecl
|
||||
_helper_thiscall_byte_uint(void* fn_ptr, void* this_ptr, unsigned int arg)
|
||||
{
|
||||
unsigned char result = 0;
|
||||
__asm {
|
||||
mov ecx, this_ptr
|
||||
push arg
|
||||
call fn_ptr
|
||||
mov result, al
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* unsigned int __thiscall fn() — no stack args, this in ECX */
|
||||
static unsigned int __cdecl
|
||||
_helper_thiscall_uint_noarg(void* fn_ptr, void* this_ptr)
|
||||
{
|
||||
unsigned int result = 0;
|
||||
__asm {
|
||||
mov ecx, this_ptr
|
||||
call fn_ptr
|
||||
mov result, eax
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* ── Thiscall SEH wrappers ─────────────────────────────────────────────── */
|
||||
|
||||
/*
|
||||
* unsigned char __thiscall fn(unsigned int objectId)
|
||||
* e.g. ClientCombatSystem::ObjectIsAttackable(objectId)
|
||||
*/
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg,
|
||||
unsigned char* out_result)
|
||||
{
|
||||
*out_result = 0;
|
||||
__try {
|
||||
*out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
*out_result = 0;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* unsigned int __thiscall fn()
|
||||
* e.g. ACCWeenieObject::InqType()
|
||||
*/
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result)
|
||||
{
|
||||
*out_result = 0;
|
||||
__try {
|
||||
*out_result = _helper_thiscall_uint_noarg(fn, this_ptr);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
*out_result = 0;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* int __thiscall fn(unsigned int stype, void* outStruct)
|
||||
* e.g. CACQualities/CWeenieObject::InqAttribute2nd(stype, &SecondaryAttribute).
|
||||
* this in ECX; stype + outStruct on the stack (callee cleans, thiscall). Reads a
|
||||
* 2nd-level attribute (health/stam/mana) into the caller's struct. Used to pull a
|
||||
* MONSTER's real MaxHealth out of its (possibly partially-populated) qualities
|
||||
* table without crashing if a sub-table is null — the AV that forced the
|
||||
* AllowNonPlayerQualities gate. */
|
||||
static int __cdecl
|
||||
_helper_thiscall_int_uint_ptr(void* fn_ptr, void* this_ptr,
|
||||
unsigned int arg1, void* arg2)
|
||||
{
|
||||
int result = 0;
|
||||
__asm {
|
||||
mov ecx, this_ptr
|
||||
push arg2 /* outStruct (rightmost) */
|
||||
push arg1 /* stype */
|
||||
call fn_ptr /* thiscall callee cleans the 8 stack bytes */
|
||||
mov result, eax
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2,
|
||||
int* out_result)
|
||||
{
|
||||
*out_result = 0;
|
||||
__try {
|
||||
*out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2);
|
||||
}
|
||||
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
|
||||
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
|
||||
*out_result = 0;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ── Process-wide native crash logger (VEH) ───────────────────────────────
|
||||
* Logs the faulting 32-bit context + a module-resolved stack sweep to a
|
||||
* dedicated file BEFORE the process dies, for the fatal exceptions that bypass
|
||||
* NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and
|
||||
* 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled
|
||||
* managed exception or a stack-walk fail-fast in the plugin/engine).
|
||||
*
|
||||
* This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so
|
||||
* unlike the removed managed CrashLogger VEH it cannot itself re-trigger a
|
||||
* NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns
|
||||
* EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly
|
||||
* as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio /
|
||||
* user32) so the build link line stays unchanged. Hardened: stack sweep in
|
||||
* __try/__except, capped log count, dedicated file (no contention with the
|
||||
* managed log). x86 (32-bit) context fields only — matches the WOW64 target.
|
||||
*/
|
||||
static wchar_t g_crashLogPath[MAX_PATH];
|
||||
static volatile LONG g_crashCount = 0;
|
||||
static PVOID g_vehHandle = NULL;
|
||||
|
||||
static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; }
|
||||
|
||||
static char* cl_hex(char* p, unsigned int v)
|
||||
{
|
||||
const char* H = "0123456789ABCDEF";
|
||||
int i;
|
||||
*p++ = '0'; *p++ = 'x';
|
||||
for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; }
|
||||
return p;
|
||||
}
|
||||
|
||||
static char* cl_u(char* p, unsigned int v)
|
||||
{
|
||||
char tmp[12]; int n = 0;
|
||||
if (v == 0) { *p++ = '0'; return p; }
|
||||
while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; }
|
||||
while (n) { *p++ = tmp[--n]; }
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
|
||||
static char* cl_sym(char* p, unsigned int addr)
|
||||
{
|
||||
HMODULE hm = NULL;
|
||||
/* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */
|
||||
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) {
|
||||
wchar_t wpath[MAX_PATH];
|
||||
DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH);
|
||||
DWORD i, leaf = 0;
|
||||
for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; }
|
||||
for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; }
|
||||
p = cl_str(p, "+");
|
||||
p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm);
|
||||
} else {
|
||||
p = cl_hex(p, addr);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
|
||||
{
|
||||
DWORD code = ep->ExceptionRecord->ExceptionCode;
|
||||
if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (InterlockedIncrement(&g_crashCount) > 24) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
{
|
||||
HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; }
|
||||
SetFilePointer(h, 0, NULL, FILE_END);
|
||||
|
||||
{
|
||||
char buf[4096];
|
||||
char* p = buf;
|
||||
CONTEXT* c = ep->ContextRecord;
|
||||
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
|
||||
DWORD wr;
|
||||
|
||||
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code=");
|
||||
p = cl_hex(p, code);
|
||||
p = cl_str(p, " exAddr=");
|
||||
p = cl_sym(p, exAddr);
|
||||
p = cl_str(p, " tid=");
|
||||
p = cl_u(p, GetCurrentThreadId());
|
||||
{
|
||||
SYSTEMTIME st; GetLocalTime(&st);
|
||||
p = cl_str(p, " time=");
|
||||
p = cl_u(p, st.wHour); p = cl_str(p, ":");
|
||||
if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":");
|
||||
if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond);
|
||||
}
|
||||
if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) {
|
||||
unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0];
|
||||
unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1];
|
||||
p = cl_str(p, " access=");
|
||||
p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ"));
|
||||
p = cl_str(p, " dataAddr=");
|
||||
p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */
|
||||
}
|
||||
p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip);
|
||||
p = cl_str(p, " esp="); p = cl_hex(p, c->Esp);
|
||||
p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp);
|
||||
p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax);
|
||||
p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx);
|
||||
p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx);
|
||||
p = cl_str(p, " edx="); p = cl_hex(p, c->Edx);
|
||||
p = cl_str(p, " esi="); p = cl_hex(p, c->Esi);
|
||||
p = cl_str(p, " edi="); p = cl_hex(p, c->Edi);
|
||||
p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n");
|
||||
WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL);
|
||||
|
||||
__try {
|
||||
unsigned int* sp = (unsigned int*)c->Esp;
|
||||
int i, emitted = 0;
|
||||
for (i = 0; i < 4096 && emitted < 96; i++) {
|
||||
unsigned int v = sp[i];
|
||||
if (v > 0x00401000u && v < 0x7FFF0000u) {
|
||||
HMODULE hm = NULL;
|
||||
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) {
|
||||
char* q = buf;
|
||||
q = cl_str(q, " +");
|
||||
q = cl_hex(q, (unsigned int)(i * 4));
|
||||
q = cl_str(q, " ");
|
||||
q = cl_sym(q, v);
|
||||
q = cl_str(q, "\r\n");
|
||||
WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL);
|
||||
emitted++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
__except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
const char* m = " <stack sweep faulted>\r\n";
|
||||
WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL);
|
||||
}
|
||||
|
||||
{
|
||||
const char* e = "==== END NATIVE CRASH ====\r\n";
|
||||
WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL);
|
||||
}
|
||||
}
|
||||
CloseHandle(h);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
/* Install the VEH once. logPath = wide path to the dedicated crash log. */
|
||||
__declspec(dllexport) void __cdecl
|
||||
RC_InstallCrashLogger(const wchar_t* logPath)
|
||||
{
|
||||
if (g_vehHandle) { return; }
|
||||
if (logPath) {
|
||||
int i = 0;
|
||||
for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; }
|
||||
g_crashLogPath[i] = 0;
|
||||
}
|
||||
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
|
||||
}
|
||||
|
||||
/* ── Tagged-text parser guard (native MinHook detour body) ────────────────
|
||||
* Null-guards AC's tag-parser consumer FUN_0067D3C0 (live VA 0x0067D3C0)
|
||||
* against a null parser-context singleton. DAT_008F881C (AC's "current tag
|
||||
* parser context") is unsynchronized; when our off-thread pump triggers a
|
||||
* text-generation path while AC's main thread is mid-parse, it races to null
|
||||
* and the consumer does `MOV EDI,[EAX+0xC]` with EAX=0 at 0x0067D3DA -> AV
|
||||
* READ [null+0xC]. That is the recurring text-parser-race crash (captured
|
||||
* 2026-06-03 native-crash.log: code=0xC0000005 exAddr=acclient.exe+0x27D3DA).
|
||||
*
|
||||
* MUST be native: the consumer is called by AC's main thread for EVERY parsed
|
||||
* tag. A MANAGED MinHook detour here (reverse-P/Invoke per tag) reintroduced a
|
||||
* NativeAOT fail-fast and crashed in ~7s (2026-05-25, pid 20852). This detour
|
||||
* has NO managed transition. The engine installs the hook via MinHook and
|
||||
* hands us the trampoline (original) through RC_SetTagParserOriginal BEFORE it
|
||||
* enables the hook. If the parser context is null we drop ONE parse run
|
||||
* (return 0) instead of dereferencing it; the caller (FUN_0067E150) discards
|
||||
* the return value, so dropping it is safe.
|
||||
*
|
||||
* The hooked function is __cdecl: void* FUN_0067D3C0(void* parserContext).
|
||||
*/
|
||||
typedef void* (__cdecl *Fn_TagParserConsume)(void*);
|
||||
static Fn_TagParserConsume g_tagParserOriginal = NULL;
|
||||
static volatile LONG g_tagParserSkips = 0;
|
||||
|
||||
static void* __cdecl RC_TagParserGuard(void* parserContext)
|
||||
{
|
||||
if (parserContext == NULL) {
|
||||
InterlockedIncrement(&g_tagParserSkips);
|
||||
return NULL; /* drop this parse run — no null deref */
|
||||
}
|
||||
if (g_tagParserOriginal == NULL) {
|
||||
return NULL; /* not wired yet (pre-SetOriginal) — fail safe */
|
||||
}
|
||||
return g_tagParserOriginal(parserContext);
|
||||
}
|
||||
|
||||
/* Returns the address of the native detour for the engine to pass to MinHook. */
|
||||
__declspec(dllexport) void* __cdecl RC_GetTagParserGuardAddress(void)
|
||||
{
|
||||
return (void*)(UINT_PTR)&RC_TagParserGuard;
|
||||
}
|
||||
|
||||
/* Engine calls this with the MinHook trampoline (original) BEFORE enabling. */
|
||||
__declspec(dllexport) void __cdecl RC_SetTagParserOriginal(void* original)
|
||||
{
|
||||
g_tagParserOriginal = (Fn_TagParserConsume)original;
|
||||
}
|
||||
|
||||
/* Diagnostic: how many null-context parse runs we've dropped. */
|
||||
__declspec(dllexport) unsigned int __cdecl RC_TagParserSkipCount(void)
|
||||
{
|
||||
return (unsigned int)g_tagParserSkips;
|
||||
}
|
||||
|
|
@ -1,6 +1,21 @@
|
|||
param(
|
||||
[string]$Destination = "C:\Games\RynthCore",
|
||||
[switch]$SkipPublish
|
||||
[string]$PluginsDestination = "C:\Games\RynthSuite",
|
||||
[switch]$SkipPublish,
|
||||
# When set, skip both the launcher publish AND the launcher payload copy
|
||||
# to $Destination root. Use this for engine-only / plugin-only iteration
|
||||
# while the launcher (RynthCore.exe) is running — without it, the launcher's
|
||||
# held Avalonia.Base.dll causes a Copy-Item lock failure that wipes the
|
||||
# Runtime\ folder. Engine still publishes/deploys to Runtime\ and plugins
|
||||
# still deploy under $PluginsDestination.
|
||||
[switch]$SkipLauncher,
|
||||
# Pre-deploy pattern gate (tools\check-patterns.ps1): verify every acclient.exe
|
||||
# signature embedded in the engine source still resolves uniquely + correctly
|
||||
# against the live client BEFORE shipping. -SkipPatternCheck bypasses it;
|
||||
# -AcClient overrides the binary it checks (default: auto-detect the private
|
||||
# copy under $Destination\AcClient, else C:\Turbine\Asheron's Call).
|
||||
[switch]$SkipPatternCheck,
|
||||
[string]$AcClient = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
|
@ -9,24 +24,73 @@ Set-StrictMode -Version Latest
|
|||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$launcherProject = Join-Path $repoRoot "src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj"
|
||||
$engineProject = Join-Path $repoRoot "src\RynthCore.Engine\RynthCore.Engine.csproj"
|
||||
$loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.csproj"
|
||||
|
||||
# Plugins are deployed to per-plugin folders under $PluginsDestination
|
||||
# (e.g. C:\Games\RynthSuite\RynthAi\). Users register plugin DLLs through
|
||||
# the launcher's "Add Plugin DLL" UI; the engine no longer relies on a
|
||||
# default Runtime\Plugins\ scan being populated by deploy.
|
||||
#
|
||||
# RynthAi's live source lives in a separate repo at C:\Projects\RynthSuite -
|
||||
# the rynthcore\Plugins\RynthCore.Plugin.RynthAi tree is a stub (~1 MB
|
||||
# published) that lacks Combat / Loot / Meta / Raycasting / LegacyUi.
|
||||
# Always source from the RynthSuite tree so the real ~8 MB plugin ships.
|
||||
$rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi"
|
||||
$rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat"
|
||||
$rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision"
|
||||
$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice"
|
||||
$pluginProjects = @(
|
||||
@{
|
||||
Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\RynthCore.Plugin.HelloBox.csproj"
|
||||
Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\bin\Release\net9.0-windows\win-x86\publish"
|
||||
DllName = "RynthCore.Plugin.HelloBox.dll"
|
||||
Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj"
|
||||
Publish = Join-Path $rynthAiSourceRoot "bin\Release\net10.0-windows\win-x86\publish"
|
||||
DllName = "RynthCore.Plugin.RynthAi.dll"
|
||||
DestSubdir = "RynthAi"
|
||||
},
|
||||
@{
|
||||
Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj"
|
||||
Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\bin\Release\net9.0-windows\win-x86\publish"
|
||||
DllName = "RynthCore.Plugin.RynthAi.dll"
|
||||
Project = Join-Path $rynthChatSourceRoot "RynthCore.Plugin.RynthChat.csproj"
|
||||
Publish = Join-Path $rynthChatSourceRoot "bin\Release\net10.0-windows\win-x86\publish"
|
||||
DllName = "RynthCore.Plugin.RynthChat.dll"
|
||||
DestSubdir = "RynthChat"
|
||||
},
|
||||
# RynthVision sets <PublishDir> to its deploy home, so publish lands
|
||||
# directly in $PluginsDestination\RynthVision. The copy step below detects
|
||||
# source == dest and skips the redundant self-copy.
|
||||
@{
|
||||
Project = Join-Path $rynthVisionSourceRoot "RynthCore.Plugin.RynthVision.csproj"
|
||||
Publish = Join-Path $PluginsDestination "RynthVision"
|
||||
DllName = "RynthCore.Plugin.RynthVision.dll"
|
||||
DestSubdir = "RynthVision"
|
||||
},
|
||||
@{
|
||||
Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\RynthCore.Plugin.RynthTracker.csproj"
|
||||
Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\bin\Release\net10.0-windows\win-x86\publish"
|
||||
DllName = "RynthCore.Plugin.RynthTracker.dll"
|
||||
DestSubdir = "RynthTracker"
|
||||
},
|
||||
# RynthJuice sets <PublishDir> to its deploy home (like RynthVision), so
|
||||
# publish lands directly in $PluginsDestination\RynthJuice and the copy step
|
||||
# below detects source == dest and skips the redundant self-copy.
|
||||
@{
|
||||
Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj"
|
||||
Publish = Join-Path $PluginsDestination "RynthJuice"
|
||||
DllName = "RynthCore.Plugin.RynthJuice.dll"
|
||||
DestSubdir = "RynthJuice"
|
||||
},
|
||||
# RynthNav also publishes straight to its deploy home via <PublishDir>.
|
||||
# It was missing from this list entirely, so full deploys never refreshed it.
|
||||
@{
|
||||
Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthNav\RynthCore.Plugin.RynthNav.csproj"
|
||||
Publish = Join-Path $PluginsDestination "RynthNav"
|
||||
DllName = "RynthCore.Plugin.RynthNav.dll"
|
||||
DestSubdir = "RynthNav"
|
||||
}
|
||||
)
|
||||
|
||||
$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\win-x86\publish"
|
||||
$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net9.0-windows\win-x86\publish"
|
||||
$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net10.0-windows7.0\win-x86\publish"
|
||||
$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish"
|
||||
$loaderPublish = Join-Path $repoRoot "src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish"
|
||||
|
||||
$runtimeDir = Join-Path $Destination "Runtime"
|
||||
$runtimePluginsDir = Join-Path $runtimeDir "Plugins"
|
||||
|
||||
function Copy-FilteredChildren {
|
||||
param(
|
||||
|
|
@ -41,14 +105,71 @@ function Copy-FilteredChildren {
|
|||
} | Copy-Item -Destination $Target -Recurse -Force
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pre-deploy pattern gate: verify every acclient.exe signature embedded in the
|
||||
# engine source still resolves uniquely + correctly against the live client
|
||||
# binary BEFORE we publish/ship. A future AC patch / ACE rebuild that shifts
|
||||
# code or a data global fails HERE instead of silently shipping a hook that
|
||||
# falls back to a stale VA at runtime. (tools\pe_pattern.py CHECK, wrapped by
|
||||
# tools\check-patterns.ps1.) Bypass: -SkipPatternCheck. Target: -AcClient.
|
||||
# ---------------------------------------------------------------------------
|
||||
if (-not $SkipPatternCheck) {
|
||||
$checkScript = Join-Path $repoRoot "tools\check-patterns.ps1"
|
||||
$acClientPath = $AcClient
|
||||
if ([string]::IsNullOrWhiteSpace($acClientPath)) {
|
||||
foreach ($cand in @((Join-Path $Destination "AcClient\acclient.exe"), "C:\Turbine\Asheron's Call\acclient.exe")) {
|
||||
if (Test-Path -LiteralPath $cand) { $acClientPath = $cand; break }
|
||||
}
|
||||
}
|
||||
|
||||
# Fail CLOSED: a gate that silently downgrades to a warning when python /
|
||||
# the script / the binary is missing is no gate at all — the explicit
|
||||
# bypass is -SkipPatternCheck.
|
||||
if (-not (Get-Command python -ErrorAction SilentlyContinue)) {
|
||||
throw "Pattern gate cannot run: 'python' is not on PATH. Install Python, or pass -SkipPatternCheck to bypass deliberately."
|
||||
}
|
||||
elseif (-not (Test-Path -LiteralPath $checkScript)) {
|
||||
throw "Pattern gate cannot run: $checkScript not found. Pass -SkipPatternCheck to bypass deliberately."
|
||||
}
|
||||
elseif ([string]::IsNullOrWhiteSpace($acClientPath) -or -not (Test-Path -LiteralPath $acClientPath)) {
|
||||
throw "Pattern gate cannot run: no acclient.exe found (tried '$Destination\AcClient' and 'C:\Turbine\Asheron''s Call'). Pass -AcClient <path>, or -SkipPatternCheck to bypass deliberately."
|
||||
}
|
||||
else {
|
||||
Write-Host "Pattern gate: verifying engine signatures against $acClientPath ..."
|
||||
& $checkScript -AcClient $acClientPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Pattern gate FAILED (exit $LASTEXITCODE) - aborting deploy. A signature drifted or is wrong; re-cut it with tools\pe_pattern.py (GEN / ALL / DATA), fix the source, rebuild, and retry. Override with -SkipPatternCheck only if you understand the risk."
|
||||
}
|
||||
Write-Host "Pattern gate PASSED - all engine signatures unique & correct."
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-Publish {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$What,
|
||||
[Parameter(Mandatory = $true)][string[]]$Arguments
|
||||
)
|
||||
dotnet @Arguments
|
||||
# PS 5.1's $ErrorActionPreference=Stop does NOT throw on a native exe's
|
||||
# nonzero exit — without this check a failed publish silently deployed the
|
||||
# PREVIOUS publish output (the root staleness trap).
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "dotnet publish FAILED for $What (exit $LASTEXITCODE) - aborting deploy so stale output cannot ship."
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $SkipPublish) {
|
||||
$env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean"
|
||||
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
|
||||
|
||||
dotnet publish $launcherProject -c Release -r win-x86
|
||||
dotnet publish $engineProject -c Release
|
||||
if (-not $SkipLauncher) {
|
||||
# --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed".
|
||||
Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false')
|
||||
}
|
||||
Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release')
|
||||
Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release')
|
||||
foreach ($plugin in $pluginProjects) {
|
||||
dotnet publish $plugin.Project -c Release
|
||||
Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release')
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -77,32 +198,129 @@ $rootCleanup = @(
|
|||
"RynthCore.exe.pre-avalonia-redeploy-20260331.bak"
|
||||
)
|
||||
|
||||
foreach ($name in $rootCleanup) {
|
||||
$target = Join-Path $Destination $name
|
||||
if (Test-Path -LiteralPath $target) {
|
||||
Remove-Item -LiteralPath $target -Recurse -Force
|
||||
if (-not $SkipLauncher) {
|
||||
# Same pre-flight for the launcher payload: a running RynthCore.exe holds its
|
||||
# Avalonia DLLs, and the copy failing on one of them used to abort the deploy
|
||||
# AFTER Runtime\ below had been wiped (2026-09-26) — no engine until a redeploy.
|
||||
$launcherLocked = @()
|
||||
foreach ($f in Get-ChildItem -LiteralPath $launcherPublish -File) {
|
||||
$target = Join-Path $Destination $f.Name
|
||||
if ($f.Name -eq "RynthCore.App.Avalonia.exe") { $target = Join-Path $Destination "RynthCore.exe" }
|
||||
if (-not (Test-Path -LiteralPath $target)) { continue }
|
||||
try {
|
||||
$s = [System.IO.File]::Open($target, 'Open', 'ReadWrite', 'None')
|
||||
$s.Close()
|
||||
} catch {
|
||||
$launcherLocked += $target
|
||||
}
|
||||
}
|
||||
if ($launcherLocked.Count -gt 0) {
|
||||
throw ("Deploy aborted BEFORE touching anything - $($launcherLocked.Count) launcher file(s) are locked (close the RynthCore launcher, or pass -SkipLauncher):`n " + ($launcherLocked -join "`n "))
|
||||
}
|
||||
|
||||
foreach ($name in $rootCleanup) {
|
||||
$target = Join-Path $Destination $name
|
||||
if (Test-Path -LiteralPath $target) {
|
||||
Remove-Item -LiteralPath $target -Recurse -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $runtimeDir) {
|
||||
# Lock pre-flight BEFORE the destructive wipe. A running client holds
|
||||
# Runtime\RynthCore.Loader.dll (loaded UNshadowed into acclient.exe) and
|
||||
# its .engine_loads shadow DLLs; the old behavior wiped Runtime\ first and
|
||||
# then died on the locked file, leaving a half-destroyed deploy. Probe
|
||||
# every file for an exclusive open and abort cleanly while the old deploy
|
||||
# is still intact.
|
||||
$locked = @()
|
||||
foreach ($f in Get-ChildItem -LiteralPath $runtimeDir -Recurse -File) {
|
||||
try {
|
||||
$s = [System.IO.File]::Open($f.FullName, 'Open', 'ReadWrite', 'None')
|
||||
$s.Close()
|
||||
} catch {
|
||||
$locked += $f.FullName
|
||||
}
|
||||
}
|
||||
if ($locked.Count -gt 0) {
|
||||
throw ("Deploy aborted BEFORE wiping Runtime\ - $($locked.Count) file(s) are locked by running processes (close all AC clients and the launcher, then retry):`n " + ($locked -join "`n "))
|
||||
}
|
||||
Remove-Item -LiteralPath $runtimeDir -Recurse -Force
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $Destination -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $runtimeDir -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $runtimePluginsDir -Force | Out-Null
|
||||
|
||||
Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb")
|
||||
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeExtensions @(".pdb")
|
||||
foreach ($plugin in $pluginProjects) {
|
||||
Copy-FilteredChildren -Source $plugin.Publish -Target $runtimePluginsDir -ExcludeNames @("cimgui.dll") -ExcludeExtensions @(".pdb")
|
||||
if (-not $SkipLauncher) {
|
||||
# Launcher payload to root, except the bootstrapper exe (renamed below).
|
||||
Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb")
|
||||
}
|
||||
|
||||
Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force
|
||||
foreach ($plugin in $pluginProjects) {
|
||||
Copy-Item -LiteralPath (Join-Path $plugin.Publish $plugin.DllName) -Destination (Join-Path $runtimePluginsDir $plugin.DllName) -Force
|
||||
}
|
||||
Get-ChildItem -Path $Destination -Recurse -Filter *.pdb -File | Remove-Item -Force
|
||||
# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins
|
||||
# are deployed separately to $PluginsDestination so they have a single home.
|
||||
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb")
|
||||
|
||||
Write-Host "Launcher deployed to $Destination"
|
||||
# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the
|
||||
# Loader then maps RynthCore.Engine.dll and provides hot-reload support.
|
||||
Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force
|
||||
|
||||
# SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers
|
||||
# around dangerous AC API calls so object-teardown AVs are caught instead of
|
||||
# crashing acclient.exe. Built by native\SehTrampoline\Build-SehTrampoline.ps1.
|
||||
$sehTrampolineSrc = Join-Path $repoRoot "native\SehTrampoline\bin\RynthCore.SehTrampoline.dll"
|
||||
$sehTrampolineC = Join-Path $repoRoot "native\SehTrampoline\SehTrampoline.c"
|
||||
if (-not (Test-Path -LiteralPath $sehTrampolineSrc)) {
|
||||
# Fail closed: the trampoline is load-bearing (SEH-guarded AC reads) and a
|
||||
# missing DLL silently shipped an engine whose guarded calls all throw.
|
||||
throw "RynthCore.SehTrampoline.dll not found at $sehTrampolineSrc - build it with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy."
|
||||
}
|
||||
if (Test-Path -LiteralPath $sehTrampolineC) {
|
||||
# The trampoline is hand-built (cl.exe), not part of dotnet publish — a
|
||||
# newer .c than the built DLL means the binary about to ship is stale.
|
||||
$srcTime = (Get-Item -LiteralPath $sehTrampolineC).LastWriteTime
|
||||
$dllTime = (Get-Item -LiteralPath $sehTrampolineSrc).LastWriteTime
|
||||
if ($srcTime -gt $dllTime) {
|
||||
throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c edited $srcTime > DLL built $dllTime). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy."
|
||||
}
|
||||
}
|
||||
Copy-Item -LiteralPath $sehTrampolineSrc -Destination (Join-Path $runtimeDir "RynthCore.SehTrampoline.dll") -Force
|
||||
Write-Host "SEH trampoline deployed to $runtimeDir"
|
||||
|
||||
if (-not $SkipLauncher) {
|
||||
Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force
|
||||
}
|
||||
|
||||
foreach ($plugin in $pluginProjects) {
|
||||
$pluginSrc = Join-Path $plugin.Publish $plugin.DllName
|
||||
if (-not (Test-Path -LiteralPath $pluginSrc)) {
|
||||
Write-Warning "Plugin DLL not found at $pluginSrc - skipping copy."
|
||||
continue
|
||||
}
|
||||
|
||||
$pluginTargetDir = Join-Path $PluginsDestination $plugin.DestSubdir
|
||||
if (-not (Test-Path -LiteralPath $pluginTargetDir)) {
|
||||
New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null
|
||||
}
|
||||
|
||||
# Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.)
|
||||
# in place by not touching anything else under $pluginTargetDir.
|
||||
$pluginDest = Join-Path $pluginTargetDir $plugin.DllName
|
||||
if ([System.IO.Path]::GetFullPath($pluginSrc) -ieq [System.IO.Path]::GetFullPath($pluginDest)) {
|
||||
# Plugin published straight into its deploy home (see RynthVision) -
|
||||
# nothing to copy, the publish already put the DLL in place.
|
||||
Write-Host "Plugin $($plugin.DllName) already in place at $pluginTargetDir; skipping copy."
|
||||
} else {
|
||||
Copy-Item -LiteralPath $pluginSrc -Destination $pluginDest -Force
|
||||
Write-Host "Plugin $($plugin.DllName) deployed to $pluginTargetDir"
|
||||
}
|
||||
}
|
||||
|
||||
# Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked
|
||||
# the ~1.4 GB private AcClient copy on every deploy for nothing.
|
||||
Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force
|
||||
Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force
|
||||
|
||||
if (-not $SkipLauncher) {
|
||||
Write-Host "Launcher deployed to $Destination"
|
||||
}
|
||||
Write-Host "Engine runtime deployed to $runtimeDir"
|
||||
|
|
|
|||
344
scripts/Show-AcMemoryTrend.ps1
Normal file
344
scripts/Show-AcMemoryTrend.ps1
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
# ============================================================================
|
||||
# Show-AcMemoryTrend.ps1
|
||||
#
|
||||
# Live console-based memory monitor for acclient.exe. Complements the
|
||||
# persistent CSV logger (Watch-AcMemory.ps1) by giving an in-the-moment
|
||||
# trend view: current WorkingSet/Private/Virtual + handle/thread counts,
|
||||
# deltas vs. session start, and computed growth rates (MB/min, MB/hour)
|
||||
# with stable/growing/shrinking indicators.
|
||||
#
|
||||
# Two parallel rate windows are shown:
|
||||
# * all-time — from the first sample we took to now (good for long
|
||||
# averaged leak rates)
|
||||
# * recent — last ~15 samples (~75s at 5s tick), so a process that
|
||||
# leaked at startup then stabilised reads STABLE in this
|
||||
# column while the all-time column still shows growth
|
||||
#
|
||||
# Zero impact on the running engine — pure OS query, no injection.
|
||||
#
|
||||
# This is a live VIEWER only — no file output. Persistence is owned by
|
||||
# Watch-AcMemory.ps1 (5-min CSV samples to C:\Games\RynthCore\Logs\).
|
||||
# Both can run in parallel against the same PID.
|
||||
#
|
||||
# Usage:
|
||||
# .\Show-AcMemoryTrend.ps1 # auto-pick first acclient.exe, 5s refresh
|
||||
# .\Show-AcMemoryTrend.ps1 -TargetPid 35456 # explicit PID
|
||||
# .\Show-AcMemoryTrend.ps1 -IntervalSeconds 2 # tighter cadence
|
||||
# .\Show-AcMemoryTrend.ps1 -HistorySize 120 # deeper recent-trend window
|
||||
#
|
||||
# acclient.exe is x86 — 2 GB user address space ceiling. The viewer
|
||||
# surfaces a WARNING line at >1800 MB Virtual and a CRITICAL line at
|
||||
# >1900 MB Virtual.
|
||||
#
|
||||
# Exit: Ctrl-C (clean), or auto-exits with a final summary when the
|
||||
# watched process terminates.
|
||||
#
|
||||
# Accessibility: status indicators use text labels (STABLE / GROWING /
|
||||
# SHRINKING) and ASCII arrows (->, ^, v). Colour is used as a
|
||||
# supplement only and is never the sole signal.
|
||||
# ============================================================================
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Alias('Pid')]
|
||||
[int]$TargetPid = 0,
|
||||
|
||||
[int]$IntervalSeconds = 5,
|
||||
|
||||
# How many samples to keep in the rolling buffer. 60 @ 5s = 5 min.
|
||||
[int]$HistorySize = 60,
|
||||
|
||||
# How many of the most-recent samples define the "recent trend" slope.
|
||||
[int]$RecentSampleCount = 15,
|
||||
|
||||
# MB/min threshold below which a memory metric reads STABLE.
|
||||
[double]$StableThresholdMbPerMin = 0.5,
|
||||
|
||||
# Handles/hour threshold below which the handle metric reads STABLE.
|
||||
[double]$StableThresholdHandlesPerHour = 50.0
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resolve target PID — explicit param wins, else auto-pick the running client.
|
||||
# ---------------------------------------------------------------------------
|
||||
if ($TargetPid -eq 0) {
|
||||
$candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue)
|
||||
if ($candidates.Count -eq 0) {
|
||||
Write-Error 'No acclient.exe process found. Pass -TargetPid <id> or launch AC first.'
|
||||
exit 1
|
||||
}
|
||||
if ($candidates.Count -gt 1) {
|
||||
Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id)
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
$TargetPid = $candidates[0].Id
|
||||
}
|
||||
|
||||
$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
|
||||
if (-not $proc) {
|
||||
Write-Error "No process found with PID $TargetPid."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# StartTime can throw on protected processes; tolerate it.
|
||||
$startTime = $null
|
||||
try { $startTime = $proc.StartTime } catch { $startTime = (Get-Date) }
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sample state. Each sample is a PSCustomObject; we keep at most $HistorySize.
|
||||
# ---------------------------------------------------------------------------
|
||||
$history = New-Object System.Collections.Generic.List[object]
|
||||
$firstSample = $null
|
||||
$sessionStartWall = Get-Date
|
||||
|
||||
function New-Sample {
|
||||
param([System.Diagnostics.Process]$p)
|
||||
|
||||
[pscustomobject]@{
|
||||
Time = Get-Date
|
||||
WsMB = [double]($p.WorkingSet64 / 1MB)
|
||||
PrivMB = [double]($p.PrivateMemorySize64 / 1MB)
|
||||
VmMB = [double]($p.VirtualMemorySize64 / 1MB)
|
||||
Handles = [int]$p.HandleCount
|
||||
Threads = [int]$p.Threads.Count
|
||||
}
|
||||
}
|
||||
|
||||
# Compute MB-per-minute slope between two samples. Returns 0 if window is
|
||||
# too short to be meaningful.
|
||||
function Get-RatePerMinute {
|
||||
param($older, $newer, [string]$field)
|
||||
|
||||
if (-not $older -or -not $newer) { return 0.0 }
|
||||
$deltaMinutes = ($newer.Time - $older.Time).TotalMinutes
|
||||
if ($deltaMinutes -le 0.01) { return 0.0 }
|
||||
return ($newer.$field - $older.$field) / $deltaMinutes
|
||||
}
|
||||
|
||||
# Pick a text status label + an ASCII arrow given a slope and a stability
|
||||
# threshold. The arrow + label are the load-bearing signals (the user is
|
||||
# colorblind — colour, where used, is a supplement only).
|
||||
function Get-Status {
|
||||
param([double]$ratePerMinute, [double]$threshold)
|
||||
|
||||
$abs = [math]::Abs($ratePerMinute)
|
||||
if ($abs -lt $threshold) {
|
||||
return [pscustomobject]@{ Label = 'STABLE '; Arrow = '->'; Color = 'Gray' }
|
||||
}
|
||||
if ($ratePerMinute -gt 0) {
|
||||
return [pscustomobject]@{ Label = 'GROWING '; Arrow = '^^'; Color = 'Yellow' }
|
||||
}
|
||||
return [pscustomobject]@{ Label = 'SHRINKING'; Arrow = 'vv'; Color = 'Cyan' }
|
||||
}
|
||||
|
||||
# Format a delta with explicit sign so STABLE vs GROWING is visually obvious
|
||||
# even without colour. "+12.3" / "-4.5" / " 0.0".
|
||||
function Format-Delta {
|
||||
param([double]$v, [int]$width = 7, [int]$decimals = 1)
|
||||
|
||||
# Build the .NET composite-format string explicitly to dodge PS's
|
||||
# "variable:scope" lookahead after a colon. e.g. width=7, decimals=1 ->
|
||||
# "{0,7:+0.0;-0.0; 0.0}".
|
||||
$dec = ('0' * $decimals)
|
||||
$pos = if ($decimals -gt 0) { "+0.$dec" } else { '+0' }
|
||||
$neg = if ($decimals -gt 0) { "-0.$dec" } else { '-0' }
|
||||
$zero = if ($decimals -gt 0) { " 0.$dec" } else { ' 0' }
|
||||
$fmt = '{0,' + $width + ':' + $pos + ';' + $neg + ';' + $zero + '}'
|
||||
return ($fmt -f $v)
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Console plumbing. We try in-place redraw via SetCursorPosition; if the host
|
||||
# doesn't support it (ISE, some remote shells) we fall back to Clear-Host.
|
||||
# Either way, redraws must tolerate a resized terminal — no fixed widths
|
||||
# beyond the host's BufferWidth.
|
||||
# ---------------------------------------------------------------------------
|
||||
$supportsCursor = $true
|
||||
try {
|
||||
[void][Console]::CursorTop
|
||||
[void][Console]::CursorLeft
|
||||
} catch {
|
||||
$supportsCursor = $false
|
||||
}
|
||||
|
||||
function Clear-Frame {
|
||||
if ($supportsCursor) {
|
||||
try {
|
||||
[Console]::SetCursorPosition(0, 0)
|
||||
# Overwrite the previously-drawn region with blanks. We pad to the
|
||||
# current BufferWidth so the new frame doesn't leave stale chars
|
||||
# at the right edge after a resize.
|
||||
$w = [Console]::BufferWidth
|
||||
$h = [Math]::Min(40, [Console]::BufferHeight - 1)
|
||||
$blank = ' ' * ($w - 1)
|
||||
for ($i = 0; $i -lt $h; $i++) {
|
||||
[Console]::SetCursorPosition(0, $i)
|
||||
[Console]::Write($blank)
|
||||
}
|
||||
[Console]::SetCursorPosition(0, 0)
|
||||
} catch {
|
||||
# Resize or other transient failure — fall back to Clear-Host.
|
||||
Clear-Host
|
||||
}
|
||||
} else {
|
||||
Clear-Host
|
||||
}
|
||||
}
|
||||
|
||||
function Write-Line {
|
||||
param([string]$text, [ConsoleColor]$Color = [ConsoleColor]::White)
|
||||
|
||||
# Truncate to BufferWidth-1 so we never wrap mid-frame and corrupt
|
||||
# subsequent SetCursorPosition writes.
|
||||
try {
|
||||
$maxLen = [Console]::BufferWidth - 1
|
||||
if ($maxLen -gt 0 -and $text.Length -gt $maxLen) {
|
||||
$text = $text.Substring(0, $maxLen)
|
||||
}
|
||||
} catch { }
|
||||
|
||||
$prevFg = $null
|
||||
try { $prevFg = [Console]::ForegroundColor } catch { }
|
||||
try { [Console]::ForegroundColor = $Color } catch { }
|
||||
[Console]::WriteLine($text)
|
||||
if ($null -ne $prevFg) {
|
||||
try { [Console]::ForegroundColor = $prevFg } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
function Format-Uptime {
|
||||
param([TimeSpan]$ts)
|
||||
return ("{0:00}:{1:00}:{2:00}" -f [int]$ts.TotalHours, $ts.Minutes, $ts.Seconds)
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main loop. Sample, append to history, render frame, sleep.
|
||||
# Ctrl-C handling: PowerShell raises a PipelineStoppedException out of
|
||||
# Start-Sleep; the finally block prints a goodbye and restores cursor.
|
||||
# ---------------------------------------------------------------------------
|
||||
try {
|
||||
Clear-Frame
|
||||
Write-Line ("Starting Show-AcMemoryTrend for PID {0} (interval {1}s, history {2})..." -f $TargetPid, $IntervalSeconds, $HistorySize)
|
||||
Start-Sleep -Milliseconds 250
|
||||
|
||||
while ($true) {
|
||||
$p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
|
||||
if (-not $p) {
|
||||
Clear-Frame
|
||||
Write-Line ("PID {0} (acclient.exe) exited at {1}." -f $TargetPid, (Get-Date).ToString('HH:mm:ss')) Red
|
||||
if ($firstSample -and $history.Count -gt 0) {
|
||||
$last = $history[$history.Count - 1]
|
||||
$sessionMin = ($last.Time - $firstSample.Time).TotalMinutes
|
||||
if ($sessionMin -gt 0) {
|
||||
$wsRate = ($last.WsMB - $firstSample.WsMB) / $sessionMin
|
||||
$privRate = ($last.PrivMB - $firstSample.PrivMB) / $sessionMin
|
||||
$vmRate = ($last.VmMB - $firstSample.VmMB) / $sessionMin
|
||||
Write-Line ("Final summary : {0} samples over {1:0.0} min" -f $history.Count, $sessionMin)
|
||||
Write-Line (" WS : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.WsMB, (Format-Delta ($last.WsMB - $firstSample.WsMB)), $wsRate)
|
||||
Write-Line (" Priv: last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.PrivMB, (Format-Delta ($last.PrivMB - $firstSample.PrivMB)), $privRate)
|
||||
Write-Line (" VM : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.VmMB, (Format-Delta ($last.VmMB - $firstSample.VmMB)), $vmRate)
|
||||
}
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
$sample = New-Sample -p $p
|
||||
if (-not $firstSample) { $firstSample = $sample }
|
||||
$history.Add($sample)
|
||||
if ($history.Count -gt $HistorySize) {
|
||||
$history.RemoveAt(0)
|
||||
}
|
||||
|
||||
# ---- Compute deltas + rates ----
|
||||
$deltaWs = $sample.WsMB - $firstSample.WsMB
|
||||
$deltaPriv = $sample.PrivMB - $firstSample.PrivMB
|
||||
$deltaVm = $sample.VmMB - $firstSample.VmMB
|
||||
$deltaHnd = $sample.Handles - $firstSample.Handles
|
||||
$deltaThr = $sample.Threads - $firstSample.Threads
|
||||
|
||||
$allTimeWs = Get-RatePerMinute $firstSample $sample 'WsMB'
|
||||
$allTimePriv = Get-RatePerMinute $firstSample $sample 'PrivMB'
|
||||
$allTimeVm = Get-RatePerMinute $firstSample $sample 'VmMB'
|
||||
$allTimeHnd = Get-RatePerMinute $firstSample $sample 'Handles'
|
||||
|
||||
# Recent window: last N samples, oldest of those vs newest.
|
||||
$recentOlder = $null
|
||||
if ($history.Count -ge 2) {
|
||||
$idx = [Math]::Max(0, $history.Count - $RecentSampleCount)
|
||||
$recentOlder = $history[$idx]
|
||||
}
|
||||
$recentWs = Get-RatePerMinute $recentOlder $sample 'WsMB'
|
||||
$recentPriv = Get-RatePerMinute $recentOlder $sample 'PrivMB'
|
||||
$recentVm = Get-RatePerMinute $recentOlder $sample 'VmMB'
|
||||
$recentHnd = Get-RatePerMinute $recentOlder $sample 'Handles'
|
||||
|
||||
$statWs = Get-Status -ratePerMinute $recentWs -threshold $StableThresholdMbPerMin
|
||||
$statPriv = Get-Status -ratePerMinute $recentPriv -threshold $StableThresholdMbPerMin
|
||||
$statVm = Get-Status -ratePerMinute $recentVm -threshold $StableThresholdMbPerMin
|
||||
# Handle threshold is given per-hour; convert to per-minute for the
|
||||
# comparator so we share the same Get-Status helper.
|
||||
$statHnd = Get-Status -ratePerMinute $recentHnd -threshold ($StableThresholdHandlesPerHour / 60.0)
|
||||
|
||||
# ---- Render frame ----
|
||||
Clear-Frame
|
||||
|
||||
$procUptime = if ($startTime) { (Get-Date) - $startTime } else { [TimeSpan]::Zero }
|
||||
$sessionUptime = (Get-Date) - $sessionStartWall
|
||||
|
||||
Write-Line "============================================================================"
|
||||
Write-Line (" Show-AcMemoryTrend PID {0,-6} now {1}" -f $TargetPid, (Get-Date).ToString('HH:mm:ss'))
|
||||
Write-Line (" proc started {0} proc uptime {1} viewer uptime {2}" -f `
|
||||
($(if ($startTime) { $startTime.ToString('yyyy-MM-dd HH:mm:ss') } else { '?' })), `
|
||||
(Format-Uptime $procUptime), (Format-Uptime $sessionUptime))
|
||||
Write-Line (" samples {0}/{1} interval {2}s recent window = last {3} samples" -f `
|
||||
$history.Count, $HistorySize, $IntervalSeconds, [Math]::Min($RecentSampleCount, $history.Count))
|
||||
Write-Line "============================================================================"
|
||||
Write-Line ""
|
||||
Write-Line " METRIC CURRENT DELTA ALL-TIME RECENT (~75s)"
|
||||
Write-Line " --------- ----------- ----------- -------------- ------------------------"
|
||||
|
||||
# WorkingSet
|
||||
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
|
||||
'WS', $sample.WsMB, (Format-Delta $deltaWs), $allTimeWs, $recentWs, $statWs.Arrow, $statWs.Label)) $statWs.Color
|
||||
# Private
|
||||
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
|
||||
'Private', $sample.PrivMB, (Format-Delta $deltaPriv), $allTimePriv, $recentPriv, $statPriv.Arrow, $statPriv.Label)) $statPriv.Color
|
||||
# Virtual
|
||||
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
|
||||
'Virtual', $sample.VmMB, (Format-Delta $deltaVm), $allTimeVm, $recentVm, $statVm.Arrow, $statVm.Label)) $statVm.Color
|
||||
# Handles (count, not MB; rate column header still reads correctly)
|
||||
Write-Line ((" {0,-9} {1,7} {2} {3,7:+0.00;-0.00; 0.00} /min {4,7:+0.00;-0.00; 0.00} /min {5} {6}" -f `
|
||||
'Handles', $sample.Handles, (Format-Delta $deltaHnd 7 0), $allTimeHnd, $recentHnd, $statHnd.Arrow, $statHnd.Label)) $statHnd.Color
|
||||
# Threads (informational, no slope label — usually noisy by design)
|
||||
Write-Line (" {0,-9} {1,7} {2}" -f `
|
||||
'Threads', $sample.Threads, (Format-Delta $deltaThr 7 0))
|
||||
|
||||
Write-Line ""
|
||||
Write-Line (" Per-hour extrapolation (all-time): WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f `
|
||||
($allTimeWs * 60), ($allTimePriv * 60), ($allTimeVm * 60), ($allTimeHnd * 60))
|
||||
Write-Line (" Per-hour extrapolation (recent) : WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f `
|
||||
($recentWs * 60), ($recentPriv * 60), ($recentVm * 60), ($recentHnd * 60))
|
||||
|
||||
# ---- x86 2 GB ceiling warnings ----
|
||||
Write-Line ""
|
||||
if ($sample.VmMB -ge 1900) {
|
||||
Write-Line " !! CRITICAL: Virtual memory >= 1900 MB. acclient.exe x86 ceiling is ~2 GB. Crash imminent. !!" Red
|
||||
Write-Line " !! CRITICAL: Save state / disconnect now before the address space is exhausted. !!" Red
|
||||
} elseif ($sample.VmMB -ge 1800) {
|
||||
Write-Line " ** WARNING: Virtual memory >= 1800 MB. Approaching x86 ~2 GB address space ceiling. **" Yellow
|
||||
}
|
||||
|
||||
Write-Line ""
|
||||
Write-Line " Status legend: STABLE -> (within threshold) GROWING ^^ (rising) SHRINKING vv (falling)"
|
||||
Write-Line (" Thresholds : memory < {0} MB/min = STABLE; handles < {1} /hr = STABLE" -f $StableThresholdMbPerMin, $StableThresholdHandlesPerHour)
|
||||
Write-Line " Press Ctrl-C to exit. CSV persistence is handled separately by Watch-AcMemory.ps1."
|
||||
|
||||
Start-Sleep -Seconds $IntervalSeconds
|
||||
}
|
||||
} finally {
|
||||
# Make sure the cursor is left on a fresh line so the prompt isn't
|
||||
# overwritten on whatever row the last frame happened to end on.
|
||||
try { [Console]::ResetColor() } catch { }
|
||||
Write-Host ""
|
||||
Write-Host "Show-AcMemoryTrend exited."
|
||||
}
|
||||
338
scripts/Watch-AcFreeze.ps1
Normal file
338
scripts/Watch-AcFreeze.ps1
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
# ============================================================================
|
||||
# Watch-AcFreeze.ps1
|
||||
#
|
||||
# Out-of-process freeze/wedge watchdog for RynthCore-injected acclient.exe.
|
||||
# Tails the per-PID heartbeat log (C:\Games\RynthCore\Logs\RynthCore.<pid>.log)
|
||||
# and applies the SAME wedge heuristics the Avalonia launcher uses
|
||||
# (MaybeRestartWedgedClients), so it can run with the launcher closed:
|
||||
#
|
||||
# * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive)
|
||||
# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining)
|
||||
# * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock)
|
||||
# * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc)
|
||||
#
|
||||
# On a CONFIRMED wedge it captures a diagnostic bundle, then (by default) kills
|
||||
# and relaunches the same account so an unattended soak keeps running:
|
||||
#
|
||||
# 1. procdump -ma full dump -> Logs\freezes\freeze_<pid>_<stamp>.dmp
|
||||
# 2. cdb "~*k" all-thread stacks -> ..._cdb.txt
|
||||
# 3. symbolicate.py on the per-PID log -> ..._symbolicated.txt
|
||||
#
|
||||
# Zero impact on the running engine - pure OS query + log tail, no injection.
|
||||
#
|
||||
# Usage:
|
||||
# .\Watch-AcFreeze.ps1 # auto-pick the RynthCore client
|
||||
# .\Watch-AcFreeze.ps1 -TargetPid 12345
|
||||
# .\Watch-AcFreeze.ps1 -Account Buffi # account to use on relaunch
|
||||
# .\Watch-AcFreeze.ps1 -Relaunch:$false # capture only, leave frozen
|
||||
# .\Watch-AcFreeze.ps1 -Once # single evaluation pass (test)
|
||||
# ============================================================================
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Alias('Pid')]
|
||||
[int]$TargetPid = 0,
|
||||
|
||||
# Account name/id passed to the injector on relaunch. If empty, read from
|
||||
# the watched PID's launch_context_<pid>.json.
|
||||
[string]$Account = '',
|
||||
|
||||
[int]$IntervalSeconds = 5,
|
||||
|
||||
# Sustained dwell before an fps=0 / queue wedge is acted on. Matches the
|
||||
# launcher's WedgeRestartSeconds default.
|
||||
[int]$WedgeHoldSeconds = 90,
|
||||
|
||||
# Heartbeat file untouched this long while the process lives = engine dead.
|
||||
[int]$HbStaleSeconds = 120,
|
||||
|
||||
# Combat-mode "stuck Ns" threshold for the fps>0 item-action hard-lock.
|
||||
[int]$StanceStuckSeconds = 300,
|
||||
|
||||
# Main-thread queue depth that means AC stopped draining.
|
||||
[int]$QueueWedgeDepth = 2000,
|
||||
|
||||
[bool]$Relaunch = $true,
|
||||
|
||||
# Stop relaunching after this many wedges (kill/relaunch loop breaker).
|
||||
[int]$MaxRelaunch = 5,
|
||||
|
||||
[string]$InjectorPath = 'C:\Projects\RynthCore\src\RynthCore.Injector\bin\Release\net10.0-windows\RynthCore.Injector.exe',
|
||||
|
||||
[string]$LogDir = 'C:\Games\RynthCore\Logs',
|
||||
|
||||
[string]$ToolsDir = 'C:\Games\RynthCore\tools',
|
||||
|
||||
[string]$SymbolicatePs1 = 'C:\Projects\RynthCore\tools\symbolicate.ps1',
|
||||
|
||||
# Do one evaluation pass and exit (for testing the detection logic).
|
||||
[switch]$Once
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$DumpDir = Join-Path $LogDir 'freezes'
|
||||
$WatchLog = Join-Path $LogDir 'freeze-watch.log'
|
||||
$ProcDump = Join-Path $ToolsDir 'procdump.exe'
|
||||
$Cdb = Join-Path $ToolsDir 'dbg_x86\cdb.exe'
|
||||
New-Item -ItemType Directory -Path $DumpDir -Force | Out-Null
|
||||
|
||||
# Heartbeat parse. Groups: 1=fps, 2=plug pump rate, 3=login(in-world), 4=qd.
|
||||
# NOTE: fps is captured but NOT used as a wedge signal - see Test-Wedge.
|
||||
$HbRegex = [regex]'hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?'
|
||||
$StanceRegex = [regex]'ChangeCombatMode\([^)]*\) retry #\d+ \(stuck (\d+)s'
|
||||
# The engine's own MainThreadHangWatchdog confirms a permanent main-thread wedge.
|
||||
# It beats off the UseTime game tick (live even when EndScene/fps is not), so it
|
||||
# works in every overlay config - the strongest cross-config signal.
|
||||
$HangPermRegex = [regex]'still hung after'
|
||||
$RecoverRegex = [regex]'MAIN THREAD RECOVERED'
|
||||
|
||||
Add-Type -Namespace Native -Name Win -MemberDefinition @'
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")]
|
||||
public static extern bool IsIconic(System.IntPtr hWnd);
|
||||
'@
|
||||
|
||||
function Write-WatchLog {
|
||||
param([string]$Message, [string]$Level = 'INF')
|
||||
$line = "[{0}] [{1}] {2}" -f (Get-Date -Format 'HH:mm:ss'), $Level, $Message
|
||||
Write-Host $line
|
||||
try { Add-Content -Path $WatchLog -Value $line -Encoding UTF8 } catch { }
|
||||
}
|
||||
|
||||
function Get-RynthCorePids {
|
||||
# A RynthCore-injected acclient is the one with a recently-written
|
||||
# per-PID log; Decal/Thwargle clients have no RynthCore.<pid>.log.
|
||||
$live = @{}
|
||||
foreach ($p in @(Get-Process -Name acclient -ErrorAction SilentlyContinue)) { $live[$p.Id] = $true }
|
||||
$result = @()
|
||||
foreach ($f in Get-ChildItem (Join-Path $LogDir 'RynthCore.*.log') -ErrorAction SilentlyContinue) {
|
||||
if ($f.Name -match '^RynthCore\.(\d+)\.log$') {
|
||||
$candidatePid = [int]$Matches[1]
|
||||
if ($live.ContainsKey($candidatePid) -and ((Get-Date) - $f.LastWriteTime).TotalSeconds -lt 30) {
|
||||
$result += $candidatePid
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
function Resolve-TargetPid {
|
||||
if ($TargetPid -ne 0) { return $TargetPid }
|
||||
$found = @(Get-RynthCorePids)
|
||||
if ($found.Count -eq 0) { return 0 }
|
||||
if ($found.Count -gt 1) {
|
||||
Write-WatchLog ("Multiple RynthCore clients ({0}); picking {1}. Pass -TargetPid to override." -f ($found -join ', '), $found[0]) 'WRN'
|
||||
}
|
||||
return $found[0]
|
||||
}
|
||||
|
||||
function Get-AccountForPid {
|
||||
param([int]$ProcId)
|
||||
if ($Account) { return $Account }
|
||||
$ctx = Join-Path $env:APPDATA "RynthCore\launch_contexts\launch_context_$ProcId.json"
|
||||
if (Test-Path $ctx) {
|
||||
try { return (Get-Content $ctx -Raw | ConvertFrom-Json).AccountName } catch { }
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
# Returns $null if healthy, else a reason string. $state is a hashtable used to
|
||||
# track sustained-dwell start times across calls (per the launcher's logic).
|
||||
function Test-Wedge {
|
||||
param([int]$ProcId, [hashtable]$State)
|
||||
|
||||
$proc = Get-Process -Id $ProcId -ErrorAction SilentlyContinue
|
||||
if (-not $proc) { return $null } # gone, not wedged
|
||||
|
||||
# Minimized windows can read fps=0 on healthy clients - exempt them.
|
||||
try {
|
||||
$h = $proc.MainWindowHandle
|
||||
if ($h -ne [IntPtr]::Zero -and [Native.Win]::IsIconic($h)) {
|
||||
$State.Remove('zeroSince'); return $null
|
||||
}
|
||||
} catch { }
|
||||
|
||||
$logPath = Join-Path $LogDir "RynthCore.$ProcId.log"
|
||||
$fi = Get-Item $logPath -ErrorAction SilentlyContinue
|
||||
if (-not $fi) { $State.Remove('zeroSince'); return $null }
|
||||
|
||||
if (((Get-Date) - $fi.LastWriteTime).TotalSeconds -gt $HbStaleSeconds) {
|
||||
return ("engine heartbeat silent for >{0}s while process alive" -f $HbStaleSeconds)
|
||||
}
|
||||
|
||||
# Tail ~16KB (enough for the every-30s combat-stuck line).
|
||||
$tail = ''
|
||||
try {
|
||||
$fs = [System.IO.File]::Open($logPath, 'Open', 'Read', 'ReadWrite, Delete')
|
||||
try {
|
||||
$want = [Math]::Min(16384, $fs.Length)
|
||||
[void]$fs.Seek(-$want, 'End')
|
||||
$buf = New-Object byte[] $want
|
||||
$read = $fs.Read($buf, 0, $want)
|
||||
$tail = [System.Text.Encoding]::UTF8.GetString($buf, 0, $read)
|
||||
} finally { $fs.Close() }
|
||||
} catch { return $null }
|
||||
|
||||
# STRONGEST signal: the engine's own watchdog confirmed a permanent
|
||||
# main-thread wedge. Act only on the "still hung" confirmation, and only if
|
||||
# no later RECOVERED line (transient stalls self-recover).
|
||||
$hangIdx = $tail.LastIndexOf('MAIN THREAD HANG DETECTED')
|
||||
if ($hangIdx -ge 0) {
|
||||
$after = $tail.Substring($hangIdx)
|
||||
if ($HangPermRegex.IsMatch($after) -and -not $RecoverRegex.IsMatch($after)) {
|
||||
return "in-process MainThreadHangWatchdog confirmed a permanent main-thread wedge"
|
||||
}
|
||||
}
|
||||
|
||||
# Item-action hard-lock while the engine threads keep ticking.
|
||||
$stanceStuck = 0
|
||||
foreach ($m in $StanceRegex.Matches($tail)) {
|
||||
$s = [int]$m.Groups[1].Value
|
||||
if ($s -gt $stanceStuck) { $stanceStuck = $s }
|
||||
}
|
||||
if ($stanceStuck -ge $StanceStuckSeconds) {
|
||||
return ("combat-mode stuck {0}s with login=1 (item-action hard-lock, heartbeat alive)" -f $stanceStuck)
|
||||
}
|
||||
|
||||
$hb = $HbRegex.Matches($tail)
|
||||
if ($hb.Count -eq 0) { $State.Remove('zeroSince'); return $null }
|
||||
$last = $hb[$hb.Count - 1]
|
||||
$fps = [int]$last.Groups[1].Value
|
||||
$plug = [int]$last.Groups[2].Value
|
||||
$inWorld = $last.Groups[3].Value -eq '1'
|
||||
$qd = if ($last.Groups[4].Success) { [int]$last.Groups[4].Value } else { 0 }
|
||||
|
||||
# Minimized clients were already exempted above (they throttle fps on their
|
||||
# own), so fps=0 here = a VISIBLE in-world client that stopped rendering
|
||||
# (a healthy visible client renders tens of fps). plug=0 = plugin pump dead.
|
||||
if (-not $inWorld) { $State.Remove('zeroSince'); return $null }
|
||||
|
||||
$reason = $null
|
||||
if ($fps -eq 0) { $reason = "fps=0 with login=1 (render dead)" }
|
||||
elseif ($plug -eq 0) { $reason = "plugin pump dead (plug=0/s) with login=1" }
|
||||
elseif ($qd -gt $QueueWedgeDepth) { $reason = ("main-thread queue backing up (qd={0}, login=1)" -f $qd) }
|
||||
|
||||
if (-not $reason) { $State.Remove('zeroSince'); return $null }
|
||||
|
||||
if (-not $State.ContainsKey('zeroSince')) {
|
||||
$State['zeroSince'] = Get-Date
|
||||
Write-WatchLog ("Wedge candidate on PID {0} ({1}) - holding {2}s to confirm." -f $ProcId, $reason, $WedgeHoldSeconds) 'WRN'
|
||||
return $null
|
||||
}
|
||||
$held = ((Get-Date) - $State['zeroSince']).TotalSeconds
|
||||
if ($held -lt $WedgeHoldSeconds) { return $null }
|
||||
|
||||
return ("{0} for >{1}s (heartbeat alive - AC main thread/pump wedged)" -f $reason, $WedgeHoldSeconds)
|
||||
}
|
||||
|
||||
function Invoke-FreezeCapture {
|
||||
param([int]$ProcId, [string]$Reason)
|
||||
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
|
||||
$base = Join-Path $DumpDir ("freeze_{0}_{1}" -f $ProcId, $stamp)
|
||||
$dmp = "$base.dmp"
|
||||
$cdbOut = "${base}_cdb.txt"
|
||||
$symOut = "${base}_symbolicated.txt"
|
||||
|
||||
Write-WatchLog ("FREEZE CONFIRMED pid={0} - {1}" -f $ProcId, $Reason) 'ERR'
|
||||
Write-WatchLog ("Capturing bundle -> {0}.*" -f $base)
|
||||
|
||||
# 1. Full dump.
|
||||
if (Test-Path $ProcDump) {
|
||||
try {
|
||||
& $ProcDump -accepteula -ma $ProcId $dmp 2>&1 | Out-Null
|
||||
if (Test-Path $dmp) { Write-WatchLog (" dump: {0} ({1} MB)" -f $dmp, [int]((Get-Item $dmp).Length/1MB)) }
|
||||
else { Write-WatchLog " dump: procdump produced no file" 'WRN' }
|
||||
} catch { Write-WatchLog (" dump FAILED: {0}" -f $_.Exception.Message) 'WRN' }
|
||||
} else { Write-WatchLog (" procdump not found at {0}" -f $ProcDump) 'WRN' }
|
||||
|
||||
# 2. All-thread native stacks from the dump (catches fps>0 locks the
|
||||
# in-process watchdog never logged a stack for).
|
||||
if ((Test-Path $Cdb) -and (Test-Path $dmp)) {
|
||||
try {
|
||||
& $Cdb -z $dmp -c "~*k; q" 2>&1 | Out-File -FilePath $cdbOut -Encoding UTF8
|
||||
Write-WatchLog (" cdb stacks: {0}" -f $cdbOut)
|
||||
} catch { Write-WatchLog (" cdb FAILED: {0}" -f $_.Exception.Message) 'WRN' }
|
||||
}
|
||||
|
||||
# 3. Symbolicate the per-PID log (contains the in-process hang stack when
|
||||
# the EndScene/UseTime watchdog fired).
|
||||
$logPath = Join-Path $LogDir "RynthCore.$ProcId.log"
|
||||
if ((Test-Path $SymbolicatePs1) -and (Test-Path $logPath)) {
|
||||
try {
|
||||
& powershell -NoProfile -ExecutionPolicy Bypass -File $SymbolicatePs1 $logPath -o $symOut --only-crash 2>&1 | Out-Null
|
||||
if (Test-Path $symOut) { Write-WatchLog (" symbolicated: {0}" -f $symOut) }
|
||||
} catch { Write-WatchLog (" symbolicate FAILED: {0}" -f $_.Exception.Message) 'WRN' }
|
||||
}
|
||||
|
||||
return $base
|
||||
}
|
||||
|
||||
function Invoke-Relaunch {
|
||||
param([int]$DeadPid, [string]$Acct)
|
||||
if (-not (Test-Path $InjectorPath)) {
|
||||
Write-WatchLog ("Cannot relaunch - injector not found at {0}" -f $InjectorPath) 'ERR'
|
||||
return 0
|
||||
}
|
||||
if (-not $Acct) {
|
||||
Write-WatchLog "Cannot relaunch - no account resolved (pass -Account)." 'ERR'
|
||||
return 0
|
||||
}
|
||||
try { Stop-Process -Id $DeadPid -Force -ErrorAction SilentlyContinue } catch { }
|
||||
Write-WatchLog ("Relaunching account '{0}' via injector..." -f $Acct)
|
||||
$out = & $InjectorPath --launch --account $Acct 2>&1
|
||||
$out | ForEach-Object { Write-WatchLog (" injector> {0}" -f $_) }
|
||||
$m = ($out | Select-String -Pattern 'LAUNCHED_PID=(\d+)' | Select-Object -Last 1)
|
||||
if ($m) {
|
||||
$newPid = [int]$m.Matches[0].Groups[1].Value
|
||||
Write-WatchLog ("Relaunched as PID {0}." -f $newPid) 'INF'
|
||||
return $newPid
|
||||
}
|
||||
Write-WatchLog "Relaunch did not report a PID." 'WRN'
|
||||
return 0
|
||||
}
|
||||
|
||||
# -- Main ---------------------------------------------------------------------
|
||||
$activePid = Resolve-TargetPid
|
||||
if ($activePid -eq 0) {
|
||||
Write-WatchLog "No RynthCore-injected acclient found. Launch one first (RynthCore.Injector.exe --launch)." 'ERR'
|
||||
exit 1
|
||||
}
|
||||
$acct = Get-AccountForPid -ProcId $activePid
|
||||
Write-WatchLog ("Watching PID {0} (account='{1}', relaunch={2}, hold={3}s, interval={4}s)." -f $activePid, $acct, $Relaunch, $WedgeHoldSeconds, $IntervalSeconds)
|
||||
|
||||
$state = @{}
|
||||
$relaunchCount = 0
|
||||
|
||||
while ($true) {
|
||||
$proc = Get-Process -Id $activePid -ErrorAction SilentlyContinue
|
||||
if (-not $proc) {
|
||||
Write-WatchLog ("PID {0} is gone." -f $activePid) 'WRN'
|
||||
if ($Relaunch -and -not $Once -and $acct -and $relaunchCount -lt $MaxRelaunch) {
|
||||
$relaunchCount++
|
||||
$newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct
|
||||
if ($newPid -ne 0) { $activePid = $newPid; $state = @{}; Start-Sleep -Seconds 10; continue }
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
$reason = Test-Wedge -ProcId $activePid -State $state
|
||||
if ($reason) {
|
||||
[void](Invoke-FreezeCapture -ProcId $activePid -Reason $reason)
|
||||
$state = @{}
|
||||
if ($Relaunch -and -not $Once) {
|
||||
if ($relaunchCount -ge $MaxRelaunch) {
|
||||
Write-WatchLog ("Hit MaxRelaunch ({0}) - leaving client and stopping." -f $MaxRelaunch) 'ERR'
|
||||
break
|
||||
}
|
||||
$relaunchCount++
|
||||
$newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct
|
||||
if ($newPid -ne 0) { $activePid = $newPid; Start-Sleep -Seconds 10; continue }
|
||||
break
|
||||
} else {
|
||||
Write-WatchLog ("Relaunch disabled - leaving PID {0} frozen for inspection. Stopping." -f $activePid) 'INF'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($Once) { Write-WatchLog ("Single pass complete - PID {0} healthy." -f $activePid); break }
|
||||
Start-Sleep -Seconds $IntervalSeconds
|
||||
}
|
||||
100
scripts/Watch-AcMemory.ps1
Normal file
100
scripts/Watch-AcMemory.ps1
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
# ============================================================================
|
||||
# Watch-AcMemory.ps1
|
||||
#
|
||||
# Polls acclient.exe's memory + handle metrics on an interval and appends
|
||||
# them to a CSV under C:\Games\RynthCore\Logs\. Designed for long-running
|
||||
# 24/7 bot sessions where we want to know:
|
||||
#
|
||||
# * is RynthCore (or AC itself) leaking?
|
||||
# * if yes, how fast (MB/hour)?
|
||||
# * does growth correlate with subsystem activity (loot on/off, mage cast
|
||||
# cycles, travel into new cells)?
|
||||
#
|
||||
# Zero impact on the running engine — runs in a separate PowerShell host,
|
||||
# pure OS query, no injection.
|
||||
#
|
||||
# Usage:
|
||||
# .\Watch-AcMemory.ps1 # auto-pick first acclient.exe
|
||||
# .\Watch-AcMemory.ps1 -Pid 35456 # explicit PID
|
||||
# .\Watch-AcMemory.ps1 -IntervalSeconds 60 # tighter cadence
|
||||
# .\Watch-AcMemory.ps1 -OutFile foo.csv # custom output path
|
||||
#
|
||||
# Exits when the watched process exits (clean or crash) so it's safe to
|
||||
# start-and-forget; the CSV stays on disk for post-session analysis.
|
||||
# ============================================================================
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Alias('Pid')]
|
||||
[int]$TargetPid = 0,
|
||||
|
||||
[int]$IntervalSeconds = 300,
|
||||
|
||||
[string]$OutFile = $null
|
||||
)
|
||||
|
||||
# Resolve target PID — explicit param wins, else auto-pick the running acclient.
|
||||
if ($TargetPid -eq 0) {
|
||||
$candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue)
|
||||
if ($candidates.Count -eq 0) {
|
||||
Write-Error 'No acclient.exe process found. Pass -TargetPid <id> or launch AC first.'
|
||||
exit 1
|
||||
}
|
||||
if ($candidates.Count -gt 1) {
|
||||
Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id)
|
||||
}
|
||||
$TargetPid = $candidates[0].Id
|
||||
}
|
||||
|
||||
# Verify the PID is alive before we commit to a CSV path.
|
||||
$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
|
||||
if (-not $proc) {
|
||||
Write-Error "No process found with PID $TargetPid."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Default output: timestamped per session so successive runs never overwrite.
|
||||
if (-not $OutFile) {
|
||||
$logsDir = 'C:\Games\RynthCore\Logs'
|
||||
if (-not (Test-Path $logsDir)) { New-Item -ItemType Directory -Path $logsDir | Out-Null }
|
||||
$stamp = (Get-Date -Format 'yyyyMMdd-HHmmss')
|
||||
$OutFile = Join-Path $logsDir ("acclient-memory-pid{0}-{1}.csv" -f $TargetPid, $stamp)
|
||||
}
|
||||
|
||||
Write-Host "Watching acclient.exe PID $TargetPid"
|
||||
Write-Host "Interval : $IntervalSeconds seconds"
|
||||
Write-Host "Output : $OutFile"
|
||||
Write-Host "Process start: $($proc.StartTime)"
|
||||
Write-Host ''
|
||||
|
||||
# Header. Append-only after this so a Ctrl-C resume preserves prior samples.
|
||||
'Timestamp,PID,UptimeMinutes,WorkingSetMB,PrivateMB,VirtualMB,HandleCount,ThreadCount' |
|
||||
Out-File -FilePath $OutFile -Encoding UTF8
|
||||
|
||||
$startTime = $proc.StartTime
|
||||
|
||||
while ($true) {
|
||||
$p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
|
||||
if (-not $p) {
|
||||
Write-Host "PID $TargetPid exited. Final sample written. CSV: $OutFile"
|
||||
break
|
||||
}
|
||||
|
||||
$now = Get-Date
|
||||
$uptimeMin = [math]::Round(($now - $startTime).TotalMinutes, 2)
|
||||
$wsMB = [int]($p.WorkingSet64 / 1MB)
|
||||
$privMB = [int]($p.PrivateMemorySize64 / 1MB)
|
||||
$vmMB = [int]($p.VirtualMemorySize64 / 1MB)
|
||||
$handles = $p.HandleCount
|
||||
$threads = $p.Threads.Count
|
||||
|
||||
$row = "{0},{1},{2},{3},{4},{5},{6},{7}" -f `
|
||||
$now.ToString('s'), $TargetPid, $uptimeMin, $wsMB, $privMB, $vmMB, $handles, $threads
|
||||
$row | Out-File -FilePath $OutFile -Append -Encoding UTF8
|
||||
|
||||
# Echo to console too so a watching terminal shows live trend.
|
||||
Write-Host ("[{0}] up={1,7:0.00}min WS={2,5}MB Priv={3,5}MB Handles={4,5} Threads={5,3}" -f `
|
||||
$now.ToString('HH:mm:ss'), $uptimeMin, $wsMB, $privMB, $handles, $threads)
|
||||
|
||||
Start-Sleep -Seconds $IntervalSeconds
|
||||
}
|
||||
369
spikes/WglDxInterop/D3D9.cs
Normal file
369
spikes/WglDxInterop/D3D9.cs
Normal file
|
|
@ -0,0 +1,369 @@
|
|||
// Plain D3D9 device + render-target texture. Mimics AC's setup: Direct3DCreate9
|
||||
// (NOT Ex), SOFTWARE_VERTEXPROCESSING (matches what AC's actual device uses, per
|
||||
// the engine's MultiClient hooks). The interop chain we're testing in this spike
|
||||
// must work against a non-Ex device because that's what AC ships.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WglDxInterop;
|
||||
|
||||
internal sealed unsafe class D3D9Host : IDisposable
|
||||
{
|
||||
public const uint D3D_SDK_VERSION = 32;
|
||||
public const uint D3DDEVTYPE_HAL = 1;
|
||||
public const uint D3DCREATE_FPU_PRESERVE = 0x00000002;
|
||||
public const uint D3DCREATE_MULTITHREADED = 0x00000004;
|
||||
public const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
|
||||
public const uint D3DFMT_UNKNOWN = 0;
|
||||
public const uint D3DFMT_A8R8G8B8 = 21;
|
||||
public const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
public const uint D3DPOOL_DEFAULT = 0;
|
||||
public const uint D3DUSAGE_RENDERTARGET = 0x00000001;
|
||||
public const uint D3DFVF_XYZRHW = 0x004;
|
||||
public const uint D3DFVF_TEX1 = 0x100;
|
||||
public const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
|
||||
public const uint D3DRS_LIGHTING = 137;
|
||||
public const uint D3DRS_ZENABLE = 7;
|
||||
public const uint D3DRS_CULLMODE = 22;
|
||||
public const uint D3DCULL_NONE = 1;
|
||||
|
||||
public const uint D3DTSS_COLOROP = 1;
|
||||
public const uint D3DTSS_COLORARG1 = 2;
|
||||
public const uint D3DTSS_ALPHAOP = 4;
|
||||
public const uint D3DTSS_ALPHAARG1 = 5;
|
||||
public const uint D3DTOP_SELECTARG1 = 2;
|
||||
public const uint D3DTA_TEXTURE = 2;
|
||||
public const uint D3DSAMP_MINFILTER = 5;
|
||||
public const uint D3DSAMP_MAGFILTER = 6;
|
||||
public const uint D3DTEXF_LINEAR = 2;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat;
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType;
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect;
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed;
|
||||
public int EnableAutoDepthStencil;
|
||||
public uint AutoDepthStencilFormat;
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct D3DVIEWPORT9 { public uint X, Y, Width, Height; public float MinZ, MaxZ; }
|
||||
|
||||
[DllImport("d3d9.dll")]
|
||||
public static extern IntPtr Direct3DCreate9(uint sdkVersion);
|
||||
|
||||
[DllImport("d3d9.dll")]
|
||||
public static extern int Direct3DCreate9Ex(uint sdkVersion, out IntPtr pD3D9Ex);
|
||||
|
||||
public const int IDirect3D9Ex_CreateDeviceEx = 20;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int CreateDeviceExD(IntPtr pD3D9Ex, uint adapter, uint deviceType, IntPtr hFocusWindow,
|
||||
uint behaviorFlags, IntPtr pPresentationParameters, IntPtr pFullscreenDisplayMode,
|
||||
out IntPtr ppReturnedDeviceInterface);
|
||||
|
||||
// Vtable indexes for IDirect3D9 / IDirect3DDevice9 / IDirect3DTexture9.
|
||||
// Cross-checked against the engine's D3D9VTable.cs at investigation time.
|
||||
public const int IDirect3D9_CreateDevice = 16;
|
||||
public const int IDirect3D9_Release = 2;
|
||||
public const int IDirect3DDevice9_TestCooperativeLevel = 3;
|
||||
public const int IDirect3DDevice9_Reset = 16;
|
||||
public const int IDirect3DDevice9_Present = 17;
|
||||
public const int IDirect3DDevice9_BeginScene = 41;
|
||||
public const int IDirect3DDevice9_EndScene = 42;
|
||||
public const int IDirect3DDevice9_Clear = 43;
|
||||
public const int IDirect3DDevice9_SetRenderState = 57;
|
||||
public const int IDirect3DDevice9_SetTextureStageState = 60;
|
||||
public const int IDirect3DDevice9_SetSamplerState = 62;
|
||||
public const int IDirect3DDevice9_SetTexture = 65;
|
||||
public const int IDirect3DDevice9_SetFVF = 89;
|
||||
public const int IDirect3DDevice9_DrawPrimitiveUP = 83;
|
||||
public const int IDirect3DDevice9_CreateTexture = 23;
|
||||
public const int IDirect3DDevice9_Release = 2;
|
||||
public const int IDirect3DTexture9_Release = 2;
|
||||
public const int IDirect3DTexture9_GetSurfaceLevel = 18;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int CreateDeviceD(IntPtr pD3D9, uint adapter, uint deviceType, IntPtr hFocusWindow,
|
||||
uint behaviorFlags, IntPtr pPresentationParameters, out IntPtr ppReturnedDeviceInterface);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate uint ReleaseD(IntPtr pObj);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage,
|
||||
uint fmt, uint pool, out IntPtr ppTex, IntPtr pSharedHandle);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int PresentD(IntPtr dev, IntPtr pSourceRect, IntPtr pDestRect,
|
||||
IntPtr hDestWindowOverride, IntPtr pDirtyRegion);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int ClearD(IntPtr dev, uint count, IntPtr pRects, uint flags, uint color, float z, uint stencil);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int BeginSceneD(IntPtr dev);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int EndSceneD(IntPtr dev);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int SetSamplerStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int SetFVFD(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
|
||||
|
||||
public IntPtr Direct3D9 { get; private set; }
|
||||
public IntPtr Device { get; private set; }
|
||||
public uint AdapterIndex { get; private set; }
|
||||
public bool IsEx { get; private set; }
|
||||
|
||||
private CreateTextureD? _createTexture;
|
||||
private PresentD? _present;
|
||||
private ClearD? _clear;
|
||||
private BeginSceneD? _beginScene;
|
||||
private EndSceneD? _endScene;
|
||||
private SetRenderStateD? _setRenderState;
|
||||
private SetTextureStageStateD? _setTexStageState;
|
||||
private SetSamplerStateD? _setSamplerState;
|
||||
private SetTextureD? _setTexture;
|
||||
private SetFVFD? _setFvf;
|
||||
private DrawPrimitiveUPD? _drawPrimitiveUp;
|
||||
|
||||
public void Initialize(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: false);
|
||||
|
||||
/// <summary>D3D9Ex variant — required if WGL_NV_DX_interop needs shared-handle textures.</summary>
|
||||
public void InitializeEx(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: true);
|
||||
|
||||
private void InitializeInternal(IntPtr hwnd, int width, int height, bool useEx)
|
||||
{
|
||||
if (useEx)
|
||||
{
|
||||
int hrEx = Direct3DCreate9Ex(D3D_SDK_VERSION, out IntPtr pEx);
|
||||
if (hrEx < 0 || pEx == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"Direct3DCreate9Ex failed, HRESULT=0x{hrEx:X8}.");
|
||||
Direct3D9 = pEx;
|
||||
IsEx = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Direct3D9 = Direct3DCreate9(D3D_SDK_VERSION);
|
||||
if (Direct3D9 == IntPtr.Zero)
|
||||
throw new InvalidOperationException("Direct3DCreate9 returned null. Ensure d3d9.dll is present.");
|
||||
IsEx = false;
|
||||
}
|
||||
|
||||
var pp = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = (uint)width,
|
||||
BackBufferHeight = (uint)height,
|
||||
BackBufferFormat = D3DFMT_A8R8G8B8,
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = hwnd,
|
||||
Windowed = 1,
|
||||
EnableAutoDepthStencil = 0,
|
||||
AutoDepthStencilFormat = D3DFMT_UNKNOWN,
|
||||
PresentationInterval = 0
|
||||
};
|
||||
|
||||
IntPtr pPP = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
|
||||
try
|
||||
{
|
||||
Marshal.StructureToPtr(pp, pPP, false);
|
||||
|
||||
IntPtr d3dVtable = Marshal.ReadIntPtr(Direct3D9);
|
||||
|
||||
int hr;
|
||||
IntPtr device;
|
||||
if (useEx)
|
||||
{
|
||||
var createDeviceEx = Marshal.GetDelegateForFunctionPointer<CreateDeviceExD>(
|
||||
Marshal.ReadIntPtr(d3dVtable, IDirect3D9Ex_CreateDeviceEx * IntPtr.Size));
|
||||
hr = createDeviceEx(
|
||||
Direct3D9, 0, D3DDEVTYPE_HAL, hwnd,
|
||||
0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE,
|
||||
pPP, IntPtr.Zero, out device);
|
||||
}
|
||||
else
|
||||
{
|
||||
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceD>(
|
||||
Marshal.ReadIntPtr(d3dVtable, IDirect3D9_CreateDevice * IntPtr.Size));
|
||||
hr = createDevice(
|
||||
Direct3D9, 0, D3DDEVTYPE_HAL, hwnd,
|
||||
0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE,
|
||||
pPP, out device);
|
||||
}
|
||||
|
||||
if (hr < 0 || device == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"CreateDevice{(useEx ? "Ex" : "")} failed, HRESULT=0x{hr:X8}");
|
||||
|
||||
Device = device;
|
||||
AdapterIndex = 0;
|
||||
|
||||
CacheDeviceMethods();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(pPP);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D3D9Ex-only: create an RT texture with a non-null pSharedHandle slot so
|
||||
/// the driver allocates a kernel-mode shared handle for the texture. The
|
||||
/// returned shared handle can then be passed to wglDXSetResourceShareHandleNV.
|
||||
/// On a non-Ex device this returns a texture but the share handle stays null.
|
||||
/// </summary>
|
||||
public IntPtr CreateRenderTargetTextureWithSharedHandle(int width, int height, out IntPtr sharedHandle)
|
||||
{
|
||||
if (_createTexture == null) throw new InvalidOperationException("Device not initialized.");
|
||||
sharedHandle = IntPtr.Zero;
|
||||
|
||||
// CreateTexture's pSharedHandle is in/out: caller passes a pointer to
|
||||
// a HANDLE; on D3D9Ex devices the driver writes the kernel handle there.
|
||||
unsafe
|
||||
{
|
||||
IntPtr handle = IntPtr.Zero;
|
||||
int hr = _createTexture(Device, (uint)width, (uint)height, 1,
|
||||
D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
|
||||
out IntPtr tex, new IntPtr(&handle));
|
||||
if (hr < 0 || tex == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"CreateTexture(RT shared {width}x{height}) failed, HRESULT=0x{hr:X8}");
|
||||
sharedHandle = handle;
|
||||
return tex;
|
||||
}
|
||||
}
|
||||
|
||||
private void CacheDeviceMethods()
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(Device);
|
||||
_createTexture = GetMethod<CreateTextureD>(vtbl, IDirect3DDevice9_CreateTexture);
|
||||
_present = GetMethod<PresentD>(vtbl, IDirect3DDevice9_Present);
|
||||
_clear = GetMethod<ClearD>(vtbl, IDirect3DDevice9_Clear);
|
||||
_beginScene = GetMethod<BeginSceneD>(vtbl, IDirect3DDevice9_BeginScene);
|
||||
_endScene = GetMethod<EndSceneD>(vtbl, IDirect3DDevice9_EndScene);
|
||||
_setRenderState = GetMethod<SetRenderStateD>(vtbl, IDirect3DDevice9_SetRenderState);
|
||||
_setTexStageState = GetMethod<SetTextureStageStateD>(vtbl, IDirect3DDevice9_SetTextureStageState);
|
||||
_setSamplerState = GetMethod<SetSamplerStateD>(vtbl, IDirect3DDevice9_SetSamplerState);
|
||||
_setTexture = GetMethod<SetTextureD>(vtbl, IDirect3DDevice9_SetTexture);
|
||||
_setFvf = GetMethod<SetFVFD>(vtbl, IDirect3DDevice9_SetFVF);
|
||||
_drawPrimitiveUp = GetMethod<DrawPrimitiveUPD>(vtbl, IDirect3DDevice9_DrawPrimitiveUP);
|
||||
}
|
||||
|
||||
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
|
||||
=> Marshal.GetDelegateForFunctionPointer<T>(Marshal.ReadIntPtr(vtable, index * IntPtr.Size));
|
||||
|
||||
/// <summary>Creates an A8R8G8B8 texture in D3DPOOL_DEFAULT with RENDERTARGET usage.</summary>
|
||||
public IntPtr CreateRenderTargetTexture(int width, int height)
|
||||
{
|
||||
if (_createTexture == null) throw new InvalidOperationException("Device not initialized.");
|
||||
int hr = _createTexture(Device, (uint)width, (uint)height, 1,
|
||||
D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
|
||||
out IntPtr tex, IntPtr.Zero);
|
||||
if (hr < 0 || tex == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"CreateTexture(RT {width}x{height}) failed, HRESULT=0x{hr:X8}");
|
||||
return tex;
|
||||
}
|
||||
|
||||
/// <summary>Returns IDirect3DSurface9* for level 0 of the texture. Caller releases.</summary>
|
||||
public IntPtr GetTextureSurfaceLevel0(IntPtr texture)
|
||||
{
|
||||
if (texture == IntPtr.Zero) return IntPtr.Zero;
|
||||
IntPtr texVtbl = Marshal.ReadIntPtr(texture);
|
||||
var getSurfaceLevel = Marshal.GetDelegateForFunctionPointer<GetSurfaceLevelD>(
|
||||
Marshal.ReadIntPtr(texVtbl, IDirect3DTexture9_GetSurfaceLevel * IntPtr.Size));
|
||||
int hr = getSurfaceLevel(texture, 0, out IntPtr surface);
|
||||
if (hr < 0 || surface == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"GetSurfaceLevel(0) failed, HRESULT=0x{hr:X8}");
|
||||
return surface;
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetSurfaceLevelD(IntPtr tex, uint level, out IntPtr ppSurface);
|
||||
|
||||
public void ReleaseObject(IntPtr pObj)
|
||||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size));
|
||||
release(pObj);
|
||||
}
|
||||
|
||||
// ─── Frame helpers ────────────────────────────────────────────────────
|
||||
public int Clear(uint argbColor) => _clear!(Device, 0, IntPtr.Zero, 0x00000001 /*D3DCLEAR_TARGET*/, argbColor, 1.0f, 0);
|
||||
public int BeginScene() => _beginScene!(Device);
|
||||
public int EndScene() => _endScene!(Device);
|
||||
public int Present() => _present!(Device, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
|
||||
public void DrawTexturedQuad(IntPtr texture, float W, float H)
|
||||
{
|
||||
// Pre-transformed XYZRHW vertices; matches OverlayTextureRenderer.cs in the engine.
|
||||
// -0.5 offset is the D3D9 half-texel rule.
|
||||
Span<QuadVertex> verts = stackalloc QuadVertex[4];
|
||||
verts[0] = new QuadVertex { X = -0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 0, V = 0 };
|
||||
verts[1] = new QuadVertex { X = W - 0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 1, V = 0 };
|
||||
verts[2] = new QuadVertex { X = -0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 0, V = 1 };
|
||||
verts[3] = new QuadVertex { X = W - 0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 1, V = 1 };
|
||||
|
||||
_setRenderState!(Device, D3DRS_LIGHTING, 0);
|
||||
_setRenderState!(Device, D3DRS_ZENABLE, 0);
|
||||
_setRenderState!(Device, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
|
||||
_setTexStageState!(Device, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
|
||||
_setTexStageState!(Device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(Device, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
|
||||
_setTexStageState!(Device, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
_setSamplerState!(Device, 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
|
||||
_setSamplerState!(Device, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
|
||||
|
||||
_setFvf!(Device, D3DFVF_XYZRHW | D3DFVF_TEX1);
|
||||
_setTexture!(Device, 0, texture);
|
||||
|
||||
fixed (QuadVertex* p = verts)
|
||||
{
|
||||
_drawPrimitiveUp!(Device, D3DPT_TRIANGLESTRIP, 2, (IntPtr)p, (uint)sizeof(QuadVertex));
|
||||
}
|
||||
|
||||
_setTexture!(Device, 0, IntPtr.Zero);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Device != IntPtr.Zero)
|
||||
{
|
||||
ReleaseObject(Device);
|
||||
Device = IntPtr.Zero;
|
||||
}
|
||||
if (Direct3D9 != IntPtr.Zero)
|
||||
{
|
||||
ReleaseObject(Direct3D9);
|
||||
Direct3D9 = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct QuadVertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public float U, V;
|
||||
}
|
||||
}
|
||||
201
spikes/WglDxInterop/Gl.cs
Normal file
201
spikes/WglDxInterop/Gl.cs
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
// OpenGL + WGL bootstrap. We need a real GL context (not ANGLE) to access the
|
||||
// WGL_NV_DX_interop2 extension, which is the whole point of the spike.
|
||||
//
|
||||
// Sequence:
|
||||
// 1. Create a hidden Win32 window and DC.
|
||||
// 2. ChoosePixelFormat / SetPixelFormat with a basic 32-bit RGBA / no depth format.
|
||||
// 3. wglCreateContext → fallback GL 1.x context, just to bootstrap.
|
||||
// 4. wglMakeCurrent the fallback so we can call wglGetProcAddress for ARB extensions.
|
||||
// 5. (Optional) wglCreateContextAttribsARB to upgrade to 3.3 core. Skia GL needs this.
|
||||
// 6. Load WGL_NV_DX_interop2 entry points via wglGetProcAddress.
|
||||
// 7. Confirm the extension string contains "WGL_NV_DX_interop2".
|
||||
//
|
||||
// Spike question A7 (multi-adapter): on a laptop with dGPU+iGPU, the default GL
|
||||
// context may be on the wrong adapter. Confirming this requires hardware to test.
|
||||
// For now, the spike just uses whatever the default DC ends up on.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace WglDxInterop;
|
||||
|
||||
internal static unsafe class Gl
|
||||
{
|
||||
// ─── opengl32.dll core ────────────────────────────────────────────────
|
||||
[DllImport("opengl32.dll")] public static extern IntPtr wglCreateContext(IntPtr hdc);
|
||||
[DllImport("opengl32.dll")] public static extern bool wglMakeCurrent(IntPtr hdc, IntPtr hglrc);
|
||||
[DllImport("opengl32.dll")] public static extern bool wglDeleteContext(IntPtr hglrc);
|
||||
[DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentContext();
|
||||
[DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentDC();
|
||||
[DllImport("opengl32.dll", CharSet = CharSet.Ansi)] public static extern IntPtr wglGetProcAddress(string name);
|
||||
|
||||
// ─── core GL we need (resolved via wglGetProcAddress for >=GL 1.5 / ARB) ──
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearD(uint mask);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearColorD(float r, float g, float b, float a);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glViewportD(int x, int y, int w, int h);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFinishD();
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFlushD();
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate IntPtr glGetStringD(uint name);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenTexturesD(int n, uint* textures);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteTexturesD(int n, uint* textures);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindTextureD(uint target, uint texture);
|
||||
|
||||
// FBO entry points (GL 3.0 / ARB_framebuffer_object)
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenFramebuffersD(int n, uint* framebuffers);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteFramebuffersD(int n, uint* framebuffers);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindFramebufferD(uint target, uint framebuffer);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFramebufferTexture2DD(uint target, uint attachment, uint textarget, uint texture, int level);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate uint glCheckFramebufferStatusD(uint target);
|
||||
|
||||
// GL constants we need
|
||||
public const uint GL_VENDOR = 0x1F00;
|
||||
public const uint GL_RENDERER = 0x1F01;
|
||||
public const uint GL_VERSION = 0x1F02;
|
||||
public const uint GL_EXTENSIONS = 0x1F03;
|
||||
public const uint GL_TEXTURE_2D = 0x0DE1;
|
||||
public const uint GL_TEXTURE_RECTANGLE = 0x84F5;
|
||||
public const uint GL_FRAMEBUFFER = 0x8D40;
|
||||
public const uint GL_COLOR_ATTACHMENT0 = 0x8CE0;
|
||||
public const uint GL_FRAMEBUFFER_COMPLETE = 0x8CD5;
|
||||
public const uint GL_COLOR_BUFFER_BIT = 0x00004000;
|
||||
|
||||
// ─── WGL_ARB_extensions_string + WGL_ARB_create_context ────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate IntPtr wglGetExtensionsStringARBD(IntPtr hdc);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate IntPtr wglCreateContextAttribsARBD(IntPtr hdc, IntPtr hShareContext, int* attribList);
|
||||
|
||||
public const int WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
|
||||
public const int WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
|
||||
public const int WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
|
||||
public const int WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
|
||||
|
||||
// ─── WGL_NV_DX_interop2 ────────────────────────────────────────────────
|
||||
// Function signatures from the registered extension spec at
|
||||
// https://registry.khronos.org/OpenGL/extensions/NV/WGL_NV_DX_interop.txt
|
||||
// (DX_interop2 is the same surface; v2 just lifts the D3D11 restriction.)
|
||||
public const uint WGL_ACCESS_READ_ONLY_NV = 0x00000000;
|
||||
public const uint WGL_ACCESS_READ_WRITE_NV = 0x00000001;
|
||||
public const uint WGL_ACCESS_WRITE_DISCARD_NV = 0x00000002;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate IntPtr wglDXOpenDeviceNVD(IntPtr dxDevice);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate bool wglDXCloseDeviceNVD(IntPtr hDevice);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate IntPtr wglDXRegisterObjectNVD(IntPtr hDevice, IntPtr dxObject, uint name, uint type, uint access);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate bool wglDXUnregisterObjectNVD(IntPtr hDevice, IntPtr hObject);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate bool wglDXLockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate bool wglDXUnlockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
public delegate bool wglDXSetResourceShareHandleNVD(IntPtr dxObject, IntPtr shareHandle);
|
||||
|
||||
public sealed class Bindings
|
||||
{
|
||||
public glClearD glClear = null!;
|
||||
public glClearColorD glClearColor = null!;
|
||||
public glViewportD glViewport = null!;
|
||||
public glFinishD glFinish = null!;
|
||||
public glFlushD glFlush = null!;
|
||||
public glGetStringD glGetString = null!;
|
||||
public glGenTexturesD glGenTextures = null!;
|
||||
public glDeleteTexturesD glDeleteTextures = null!;
|
||||
public glBindTextureD glBindTexture = null!;
|
||||
|
||||
public glGenFramebuffersD glGenFramebuffers = null!;
|
||||
public glDeleteFramebuffersD glDeleteFramebuffers = null!;
|
||||
public glBindFramebufferD glBindFramebuffer = null!;
|
||||
public glFramebufferTexture2DD glFramebufferTexture2D = null!;
|
||||
public glCheckFramebufferStatusD glCheckFramebufferStatus = null!;
|
||||
|
||||
public wglDXOpenDeviceNVD wglDXOpenDeviceNV = null!;
|
||||
public wglDXCloseDeviceNVD wglDXCloseDeviceNV = null!;
|
||||
public wglDXRegisterObjectNVD wglDXRegisterObjectNV = null!;
|
||||
public wglDXUnregisterObjectNVD wglDXUnregisterObjectNV = null!;
|
||||
public wglDXLockObjectsNVD wglDXLockObjectsNV = null!;
|
||||
public wglDXUnlockObjectsNVD wglDXUnlockObjectsNV = null!;
|
||||
public wglDXSetResourceShareHandleNVD? wglDXSetResourceShareHandleNV; // optional; only needed for D3D9 shared HANDLE textures
|
||||
|
||||
public bool Loaded;
|
||||
}
|
||||
|
||||
public static T Resolve<T>(string name) where T : Delegate
|
||||
{
|
||||
IntPtr proc = wglGetProcAddress(name);
|
||||
if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1))
|
||||
{
|
||||
// wglGetProcAddress returns 1/2/3/-1 on some drivers when the name isn't a real ICD entry; fall through to opengl32 itself.
|
||||
IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll");
|
||||
proc = Win32.GetProcAddress(opengl32, name);
|
||||
}
|
||||
if (proc == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"GL proc not found: {name}");
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(proc);
|
||||
}
|
||||
|
||||
public static T? TryResolve<T>(string name) where T : Delegate
|
||||
{
|
||||
IntPtr proc = wglGetProcAddress(name);
|
||||
if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1))
|
||||
{
|
||||
IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll");
|
||||
proc = Win32.GetProcAddress(opengl32, name);
|
||||
}
|
||||
if (proc == IntPtr.Zero) return null;
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(proc);
|
||||
}
|
||||
|
||||
public static Bindings LoadAll()
|
||||
{
|
||||
var b = new Bindings
|
||||
{
|
||||
glClear = Resolve<glClearD>("glClear"),
|
||||
glClearColor = Resolve<glClearColorD>("glClearColor"),
|
||||
glViewport = Resolve<glViewportD>("glViewport"),
|
||||
glFinish = Resolve<glFinishD>("glFinish"),
|
||||
glFlush = Resolve<glFlushD>("glFlush"),
|
||||
glGetString = Resolve<glGetStringD>("glGetString"),
|
||||
glGenTextures = Resolve<glGenTexturesD>("glGenTextures"),
|
||||
glDeleteTextures = Resolve<glDeleteTexturesD>("glDeleteTextures"),
|
||||
glBindTexture = Resolve<glBindTextureD>("glBindTexture"),
|
||||
|
||||
glGenFramebuffers = Resolve<glGenFramebuffersD>("glGenFramebuffers"),
|
||||
glDeleteFramebuffers = Resolve<glDeleteFramebuffersD>("glDeleteFramebuffers"),
|
||||
glBindFramebuffer = Resolve<glBindFramebufferD>("glBindFramebuffer"),
|
||||
glFramebufferTexture2D = Resolve<glFramebufferTexture2DD>("glFramebufferTexture2D"),
|
||||
glCheckFramebufferStatus = Resolve<glCheckFramebufferStatusD>("glCheckFramebufferStatus"),
|
||||
|
||||
wglDXOpenDeviceNV = Resolve<wglDXOpenDeviceNVD>("wglDXOpenDeviceNV"),
|
||||
wglDXCloseDeviceNV = Resolve<wglDXCloseDeviceNVD>("wglDXCloseDeviceNV"),
|
||||
wglDXRegisterObjectNV = Resolve<wglDXRegisterObjectNVD>("wglDXRegisterObjectNV"),
|
||||
wglDXUnregisterObjectNV = Resolve<wglDXUnregisterObjectNVD>("wglDXUnregisterObjectNV"),
|
||||
wglDXLockObjectsNV = Resolve<wglDXLockObjectsNVD>("wglDXLockObjectsNV"),
|
||||
wglDXUnlockObjectsNV = Resolve<wglDXUnlockObjectsNVD>("wglDXUnlockObjectsNV"),
|
||||
|
||||
wglDXSetResourceShareHandleNV = TryResolve<wglDXSetResourceShareHandleNVD>("wglDXSetResourceShareHandleNV"),
|
||||
|
||||
Loaded = true,
|
||||
};
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
public static string GetGlString(Bindings b, uint name)
|
||||
{
|
||||
IntPtr p = b.glGetString(name);
|
||||
return p == IntPtr.Zero ? "<null>" : Marshal.PtrToStringAnsi(p) ?? "<null>";
|
||||
}
|
||||
|
||||
public static string GetWglExtensionsString(IntPtr hdc)
|
||||
{
|
||||
var fn = TryResolve<wglGetExtensionsStringARBD>("wglGetExtensionsStringARB");
|
||||
if (fn == null) return string.Empty;
|
||||
IntPtr p = fn(hdc);
|
||||
return p == IntPtr.Zero ? string.Empty : Marshal.PtrToStringAnsi(p) ?? string.Empty;
|
||||
}
|
||||
}
|
||||
165
spikes/WglDxInterop/InteropTexture.cs
Normal file
165
spikes/WglDxInterop/InteropTexture.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
// One unit of "shared" texture state:
|
||||
// - A D3D9 RT texture on AC's-emulated device (POOL_DEFAULT, USAGE_RENDERTARGET).
|
||||
// - A GL texture name + FBO bound to that texture via wglDXRegisterObjectNV.
|
||||
// - The interop handle returned by Register that we Lock/Unlock per frame.
|
||||
//
|
||||
// The Phase A spike doesn't render Skia yet — it just clears the FBO to a known
|
||||
// animated color so we can verify the chain visually. Skia integration is
|
||||
// straight after the chain is proven.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WglDxInterop;
|
||||
|
||||
internal sealed unsafe class InteropTexture : IDisposable
|
||||
{
|
||||
public IntPtr D3D9Texture { get; private set; }
|
||||
public IntPtr D3D9Surface { get; private set; }
|
||||
public uint GlTexture { get; private set; }
|
||||
public uint GlFramebuffer { get; private set; }
|
||||
public IntPtr WglObject { get; private set; }
|
||||
public int Width { get; }
|
||||
public int Height { get; }
|
||||
|
||||
private readonly Gl.Bindings _gl;
|
||||
private readonly D3D9Host _d3d;
|
||||
private readonly IntPtr _wglDevice;
|
||||
|
||||
public InteropTexture(Gl.Bindings gl, D3D9Host d3d, IntPtr wglDevice, int width, int height)
|
||||
{
|
||||
_gl = gl;
|
||||
_d3d = d3d;
|
||||
_wglDevice = wglDevice;
|
||||
Width = width;
|
||||
Height = height;
|
||||
|
||||
// Step 1 — D3D9 RT texture. If Ex, get a shared handle too.
|
||||
IntPtr sharedHandle = IntPtr.Zero;
|
||||
if (d3d.IsEx)
|
||||
{
|
||||
D3D9Texture = d3d.CreateRenderTargetTextureWithSharedHandle(width, height, out sharedHandle);
|
||||
Console.WriteLine($"[spike] D3D9Ex RT created with sharedHandle=0x{sharedHandle:X8}");
|
||||
}
|
||||
else
|
||||
{
|
||||
D3D9Texture = d3d.CreateRenderTargetTexture(width, height);
|
||||
}
|
||||
|
||||
// Step 1b — WGL_NV_DX_interop on D3D9 only supports SURFACES, not the
|
||||
// ID3DTexture wrapper. Get the level-0 IDirect3DSurface9 and register
|
||||
// that. The GL side still sees it as GL_TEXTURE_2D.
|
||||
D3D9Surface = d3d.GetTextureSurfaceLevel0(D3D9Texture);
|
||||
|
||||
// Step 1c — If we have a shared handle, register it BEFORE Register.
|
||||
// This is required by NVIDIA's implementation when the resource has
|
||||
// a shared handle, even when the GL context's interop device matches
|
||||
// the D3D device that created the resource.
|
||||
if (sharedHandle != IntPtr.Zero && gl.wglDXSetResourceShareHandleNV != null)
|
||||
{
|
||||
bool setOk = gl.wglDXSetResourceShareHandleNV(D3D9Surface, sharedHandle);
|
||||
Console.WriteLine($"[spike] wglDXSetResourceShareHandleNV(surface) → {setOk}");
|
||||
if (!setOk)
|
||||
throw new InvalidOperationException($"wglDXSetResourceShareHandleNV failed (LastError=0x{Marshal.GetLastWin32Error():X}).");
|
||||
}
|
||||
|
||||
// Step 2 — GL texture name to receive the binding.
|
||||
uint glTex = 0;
|
||||
gl.glGenTextures(1, &glTex);
|
||||
if (glTex == 0) throw new InvalidOperationException("glGenTextures returned 0.");
|
||||
GlTexture = glTex;
|
||||
|
||||
// Step 3 — Register the D3D9 surface as a GL texture under the GL context.
|
||||
// Try a sequence of (target, access) combinations and (texture vs surface) until one
|
||||
// succeeds. NVIDIA's WGL_NV_DX_interop driver has historically been picky about
|
||||
// which D3D9 source types it accepts.
|
||||
var attempts = new[] {
|
||||
(Label: "surface, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV),
|
||||
(Label: "surface, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
|
||||
(Label: "surface, GL_TEXTURE_RECTANGLE, RW", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_RECTANGLE, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
|
||||
(Label: "texture, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV),
|
||||
(Label: "texture, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV),
|
||||
};
|
||||
|
||||
IntPtr wglObj = IntPtr.Zero;
|
||||
string lastFail = "";
|
||||
foreach (var a in attempts)
|
||||
{
|
||||
wglObj = gl.wglDXRegisterObjectNV(_wglDevice, a.Obj, GlTexture, a.Type, a.Access);
|
||||
if (wglObj != IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine($"[spike] wglDXRegisterObjectNV SUCCESS via: {a.Label}");
|
||||
break;
|
||||
}
|
||||
lastFail = $"{a.Label} → LastError=0x{Marshal.GetLastWin32Error():X}";
|
||||
Console.WriteLine($"[spike] wglDXRegisterObjectNV FAIL via: {lastFail}");
|
||||
}
|
||||
|
||||
if (wglObj == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"wglDXRegisterObjectNV failed in all variants. Last: {lastFail}");
|
||||
|
||||
WglObject = wglObj;
|
||||
|
||||
// Step 4 — Build an FBO with the GL texture as color attachment 0.
|
||||
// FBO setup is done while the texture is NOT locked (legal per spec; the
|
||||
// attachment binding is a GL state operation that doesn't touch contents).
|
||||
// The first lock is the point at which GL can actually clear the texture.
|
||||
uint fbo = 0;
|
||||
gl.glGenFramebuffers(1, &fbo);
|
||||
GlFramebuffer = fbo;
|
||||
|
||||
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, fbo);
|
||||
gl.glFramebufferTexture2D(Gl.GL_FRAMEBUFFER, Gl.GL_COLOR_ATTACHMENT0, Gl.GL_TEXTURE_2D, GlTexture, 0);
|
||||
|
||||
uint status = gl.glCheckFramebufferStatus(Gl.GL_FRAMEBUFFER);
|
||||
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0);
|
||||
|
||||
if (status != Gl.GL_FRAMEBUFFER_COMPLETE)
|
||||
throw new InvalidOperationException($"FBO incomplete after attaching interop texture, status=0x{status:X}.");
|
||||
}
|
||||
|
||||
/// <summary>Lock the D3D9 texture so the GL context has exclusive write access.</summary>
|
||||
public bool Lock()
|
||||
{
|
||||
IntPtr h = WglObject;
|
||||
return _gl.wglDXLockObjectsNV(_wglDevice, 1, &h);
|
||||
}
|
||||
|
||||
/// <summary>Release the D3D9 texture back to D3D9. After this, AC's render thread can sample.</summary>
|
||||
public bool Unlock()
|
||||
{
|
||||
IntPtr h = WglObject;
|
||||
return _gl.wglDXUnlockObjectsNV(_wglDevice, 1, &h);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (WglObject != IntPtr.Zero)
|
||||
{
|
||||
_gl.wglDXUnregisterObjectNV(_wglDevice, WglObject);
|
||||
WglObject = IntPtr.Zero;
|
||||
}
|
||||
if (GlFramebuffer != 0)
|
||||
{
|
||||
uint fbo = GlFramebuffer;
|
||||
_gl.glDeleteFramebuffers(1, &fbo);
|
||||
GlFramebuffer = 0;
|
||||
}
|
||||
if (GlTexture != 0)
|
||||
{
|
||||
uint tex = GlTexture;
|
||||
_gl.glDeleteTextures(1, &tex);
|
||||
GlTexture = 0;
|
||||
}
|
||||
if (D3D9Surface != IntPtr.Zero)
|
||||
{
|
||||
_d3d.ReleaseObject(D3D9Surface);
|
||||
D3D9Surface = IntPtr.Zero;
|
||||
}
|
||||
if (D3D9Texture != IntPtr.Zero)
|
||||
{
|
||||
_d3d.ReleaseObject(D3D9Texture);
|
||||
D3D9Texture = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
337
spikes/WglDxInterop/Program.cs
Normal file
337
spikes/WglDxInterop/Program.cs
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
// Phase A spike — WGL_NV_DX_interop2 architectural test.
|
||||
//
|
||||
// What it does end-to-end:
|
||||
// 1. Open a normal Win32 window and create a plain D3D9 device on it.
|
||||
// (Direct3DCreate9, NOT Ex — exactly what AC ships.)
|
||||
// 2. Create a 'producer' window+DC and bring up a real OpenGL 3.3 core context.
|
||||
// 3. Confirm WGL_NV_DX_interop2 is in the WGL extensions string.
|
||||
// (Spike A8 — driver coverage. Hard-fail with a clear log if missing.)
|
||||
// 4. Open the D3D9 device for interop and register a D3DUSAGE_RENDERTARGET
|
||||
// texture under it as a GL texture.
|
||||
// 5. Per frame:
|
||||
// - Lock the texture for GL.
|
||||
// - Bind FBO, set viewport, clear to an animated color (proves the GL
|
||||
// path is actually writing into the D3D9 resource).
|
||||
// - Unlock.
|
||||
// - Use the D3D9 texture in a normal D3D9 fullscreen quad to the window.
|
||||
// 6. Log frame timing every second so spike A3 (lock/unlock cost) gets data.
|
||||
//
|
||||
// This is intentionally Skia-free for the first cut. Skia layers on top
|
||||
// trivially once the chain works (replace the glClearColor with a Skia render
|
||||
// into the same FBO). Proving the chain first means a Skia rendering bug is
|
||||
// disambiguated from an interop bug.
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WglDxInterop;
|
||||
|
||||
internal static unsafe class Program
|
||||
{
|
||||
private const int WindowWidth = 1280;
|
||||
private const int WindowHeight = 720;
|
||||
|
||||
private static IntPtr _hwnd;
|
||||
private static bool _quitRequested;
|
||||
|
||||
// Holding the WndProc delegate alive for the lifetime of the window —
|
||||
// RegisterClassExW stores a function pointer; if the delegate is GC'd
|
||||
// we get a callback into freed memory.
|
||||
private static Win32.WndProcDelegate? _wndProc;
|
||||
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("[spike] WGL_NV_DX_interop2 architectural test");
|
||||
|
||||
try
|
||||
{
|
||||
CreateMainWindow();
|
||||
|
||||
// Spike branch — `--ex` flag selects D3D9Ex+shared-handle path so we can
|
||||
// empirically test whether WGL_NV_DX_interop2 needs Ex's shared handles.
|
||||
// Default is plain D3D9 to mirror AC's reality.
|
||||
bool useEx = Array.IndexOf(args, "--ex") >= 0;
|
||||
|
||||
using var d3d = new D3D9Host();
|
||||
if (useEx) d3d.InitializeEx(_hwnd, WindowWidth, WindowHeight);
|
||||
else d3d.Initialize(_hwnd, WindowWidth, WindowHeight);
|
||||
Console.WriteLine($"[spike] D3D9{(d3d.IsEx ? "Ex" : "")} device created on adapter {d3d.AdapterIndex}.");
|
||||
|
||||
// GL context lives on the SAME thread as the message loop and D3D9.
|
||||
// For the engine integration, the GL context will live on Avalonia's
|
||||
// STA thread; here on the spike main thread is fine.
|
||||
//
|
||||
// Use a SEPARATE hidden window for the GL context so the GL default
|
||||
// framebuffer doesn't compete with the D3D9 swap chain on the visible
|
||||
// window. NVIDIA's WGL_NV_DX_interop layer is documented as needing
|
||||
// this isolation for D3D9 sources.
|
||||
IntPtr glHwnd = CreateHiddenGlWindow();
|
||||
IntPtr glContext = CreateGlContext(glHwnd, out IntPtr hdcUsed);
|
||||
if (glContext == IntPtr.Zero)
|
||||
return Fail("Could not create OpenGL context.");
|
||||
|
||||
string wglExt = Gl.GetWglExtensionsString(hdcUsed);
|
||||
Console.WriteLine($"[spike] WGL extensions: {wglExt.Length} chars.");
|
||||
bool hasInterop2 = wglExt.Contains("WGL_NV_DX_interop2");
|
||||
bool hasInterop1 = wglExt.Contains("WGL_NV_DX_interop");
|
||||
Console.WriteLine($"[spike] WGL_NV_DX_interop = {hasInterop1}, WGL_NV_DX_interop2 = {hasInterop2}");
|
||||
if (!hasInterop2 && !hasInterop1)
|
||||
return Fail("Driver does not advertise WGL_NV_DX_interop. Spike cannot run on this hardware.");
|
||||
|
||||
var gl = Gl.LoadAll();
|
||||
Console.WriteLine($"[spike] GL_VENDOR = {Gl.GetGlString(gl, Gl.GL_VENDOR)}");
|
||||
Console.WriteLine($"[spike] GL_RENDERER = {Gl.GetGlString(gl, Gl.GL_RENDERER)}");
|
||||
Console.WriteLine($"[spike] GL_VERSION = {Gl.GetGlString(gl, Gl.GL_VERSION)}");
|
||||
|
||||
IntPtr wglDevice = gl.wglDXOpenDeviceNV(d3d.Device);
|
||||
if (wglDevice == IntPtr.Zero)
|
||||
return Fail($"wglDXOpenDeviceNV failed (LastError=0x{Marshal.GetLastWin32Error():X}).");
|
||||
Console.WriteLine($"[spike] wglDXOpenDeviceNV → 0x{wglDevice:X}");
|
||||
|
||||
using var tex = new InteropTexture(gl, d3d, wglDevice, WindowWidth, WindowHeight);
|
||||
Console.WriteLine($"[spike] Registered D3D9 RT 0x{tex.D3D9Texture:X} as GL tex {tex.GlTexture}, FBO {tex.GlFramebuffer}, wglObj 0x{tex.WglObject:X}.");
|
||||
|
||||
RunRenderLoop(d3d, gl, tex);
|
||||
|
||||
// Teardown order matters — Unregister + CloseDeviceNV before D3D9 release.
|
||||
gl.wglDXCloseDeviceNV(wglDevice);
|
||||
Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero);
|
||||
Gl.wglDeleteContext(glContext);
|
||||
|
||||
Console.WriteLine("[spike] Clean exit.");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Fail($"Unhandled: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int Fail(string msg)
|
||||
{
|
||||
Console.Error.WriteLine($"[spike] FAILED: {msg}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ─── Window ───────────────────────────────────────────────────────────
|
||||
private static void CreateMainWindow()
|
||||
{
|
||||
_wndProc = StaticWndProc;
|
||||
IntPtr wndProcPtr = Marshal.GetFunctionPointerForDelegate(_wndProc);
|
||||
|
||||
var wc = new Win32.WNDCLASSEXW
|
||||
{
|
||||
cbSize = (uint)Marshal.SizeOf<Win32.WNDCLASSEXW>(),
|
||||
style = 0,
|
||||
lpfnWndProc = wndProcPtr,
|
||||
hInstance = Win32.GetModuleHandleW(null),
|
||||
hCursor = IntPtr.Zero,
|
||||
hbrBackground = IntPtr.Zero,
|
||||
lpszMenuName = IntPtr.Zero,
|
||||
lpszClassName = Marshal.StringToHGlobalUni("WglDxInteropSpike"),
|
||||
};
|
||||
|
||||
ushort atom = Win32.RegisterClassExW(ref wc);
|
||||
if (atom == 0)
|
||||
throw new InvalidOperationException($"RegisterClassExW failed: {Marshal.GetLastWin32Error()}");
|
||||
|
||||
_hwnd = Win32.CreateWindowExW(
|
||||
0, "WglDxInteropSpike", "WGL_NV_DX_interop2 spike",
|
||||
Win32.WS_OVERLAPPEDWINDOW | Win32.WS_VISIBLE,
|
||||
Win32.CW_USEDEFAULT, Win32.CW_USEDEFAULT, WindowWidth, WindowHeight,
|
||||
IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero);
|
||||
|
||||
if (_hwnd == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"CreateWindowExW failed: {Marshal.GetLastWin32Error()}");
|
||||
|
||||
Win32.ShowWindow(_hwnd, Win32.SW_SHOW);
|
||||
}
|
||||
|
||||
private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case Win32.WM_CLOSE:
|
||||
_quitRequested = true;
|
||||
Win32.PostQuitMessage(0);
|
||||
return IntPtr.Zero;
|
||||
case Win32.WM_DESTROY:
|
||||
Win32.PostQuitMessage(0);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
return Win32.DefWindowProcW(hwnd, msg, wParam, lParam);
|
||||
}
|
||||
|
||||
private static IntPtr CreateHiddenGlWindow()
|
||||
{
|
||||
IntPtr hwnd = Win32.CreateWindowExW(
|
||||
0, "WglDxInteropSpike", "GL helper",
|
||||
Win32.WS_POPUP,
|
||||
0, 0, 16, 16,
|
||||
IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero);
|
||||
if (hwnd == IntPtr.Zero)
|
||||
throw new InvalidOperationException($"GL helper CreateWindowExW failed: {Marshal.GetLastWin32Error()}");
|
||||
return hwnd;
|
||||
}
|
||||
|
||||
// ─── GL context bootstrap ─────────────────────────────────────────────
|
||||
private static IntPtr CreateGlContext(IntPtr hwnd, out IntPtr hdcOut)
|
||||
{
|
||||
IntPtr hdc = Win32.GetDC(hwnd);
|
||||
if (hdc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
|
||||
|
||||
var pfd = new Win32.PIXELFORMATDESCRIPTOR
|
||||
{
|
||||
nSize = (ushort)Marshal.SizeOf<Win32.PIXELFORMATDESCRIPTOR>(),
|
||||
nVersion = 1,
|
||||
dwFlags = (uint)(Win32.PFD_DRAW_TO_WINDOW | Win32.PFD_SUPPORT_OPENGL | Win32.PFD_DOUBLEBUFFER),
|
||||
iPixelType = Win32.PFD_TYPE_RGBA,
|
||||
cColorBits = 32,
|
||||
cAlphaBits = 8,
|
||||
cDepthBits = 0,
|
||||
cStencilBits = 0,
|
||||
iLayerType = Win32.PFD_MAIN_PLANE,
|
||||
};
|
||||
|
||||
int format = Win32.ChoosePixelFormat(hdc, ref pfd);
|
||||
if (format == 0) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
|
||||
if (!Win32.SetPixelFormat(hdc, format, ref pfd)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
|
||||
|
||||
IntPtr glrc = Gl.wglCreateContext(hdc);
|
||||
if (glrc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
|
||||
if (!Gl.wglMakeCurrent(hdc, glrc)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; }
|
||||
|
||||
// Try to upgrade to GL 3.3 core via wglCreateContextAttribsARB.
|
||||
// If unavailable (very old driver) the fallback 1.x context is used —
|
||||
// that may or may not have FBO support. Fail gracefully.
|
||||
var createAttribs = Gl.TryResolve<Gl.wglCreateContextAttribsARBD>("wglCreateContextAttribsARB");
|
||||
if (createAttribs != null)
|
||||
{
|
||||
int* attribs = stackalloc int[]
|
||||
{
|
||||
Gl.WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
|
||||
Gl.WGL_CONTEXT_MINOR_VERSION_ARB, 3,
|
||||
Gl.WGL_CONTEXT_PROFILE_MASK_ARB, Gl.WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
|
||||
0,
|
||||
};
|
||||
|
||||
IntPtr coreCtx = createAttribs(hdc, IntPtr.Zero, attribs);
|
||||
if (coreCtx != IntPtr.Zero)
|
||||
{
|
||||
Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero);
|
||||
Gl.wglDeleteContext(glrc);
|
||||
glrc = coreCtx;
|
||||
Gl.wglMakeCurrent(hdc, glrc);
|
||||
Console.WriteLine("[spike] Upgraded to GL 3.3 core context.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("[spike] wglCreateContextAttribsARB returned null — staying on legacy context.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("[spike] wglCreateContextAttribsARB not available — staying on legacy context.");
|
||||
}
|
||||
|
||||
hdcOut = hdc;
|
||||
return glrc;
|
||||
}
|
||||
|
||||
// ─── Render loop ──────────────────────────────────────────────────────
|
||||
private static void RunRenderLoop(D3D9Host d3d, Gl.Bindings gl, InteropTexture tex)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
long frameStartTicks;
|
||||
long lockTotalTicks = 0;
|
||||
long unlockTotalTicks = 0;
|
||||
long unlockMaxTicks = 0;
|
||||
int frame = 0;
|
||||
long secondAnchor = sw.ElapsedTicks;
|
||||
int framesThisSecond = 0;
|
||||
|
||||
while (!_quitRequested)
|
||||
{
|
||||
// Drain Win32 messages.
|
||||
while (Win32.PeekMessageW(out Win32.MSG msg, IntPtr.Zero, 0, 0, Win32.PM_REMOVE))
|
||||
{
|
||||
if (msg.message == Win32.WM_QUIT)
|
||||
{
|
||||
_quitRequested = true;
|
||||
break;
|
||||
}
|
||||
Win32.TranslateMessage(ref msg);
|
||||
Win32.DispatchMessageW(ref msg);
|
||||
}
|
||||
if (_quitRequested) break;
|
||||
|
||||
frameStartTicks = sw.ElapsedTicks;
|
||||
|
||||
// ── GL phase: lock → render to FBO → unlock ──
|
||||
long lockStart = sw.ElapsedTicks;
|
||||
if (!tex.Lock())
|
||||
{
|
||||
Console.Error.WriteLine($"[spike] wglDXLockObjectsNV failed at frame {frame}.");
|
||||
break;
|
||||
}
|
||||
long lockEnd = sw.ElapsedTicks;
|
||||
lockTotalTicks += (lockEnd - lockStart);
|
||||
|
||||
// Bind the interop FBO and clear to an animated color so it's visually
|
||||
// obvious the GL path is writing into the D3D9 texture. Swizzle is
|
||||
// intentional: we want to see whether glClearColor's RGBA is sampled
|
||||
// as RGBA or as BGRA when drawn through D3D9's quad shader path.
|
||||
// Spike question A2 — color format mapping.
|
||||
float t = (frame % 600) / 600.0f;
|
||||
float r = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI));
|
||||
float g = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 2.0));
|
||||
float b = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 4.0));
|
||||
|
||||
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, tex.GlFramebuffer);
|
||||
gl.glViewport(0, 0, tex.Width, tex.Height);
|
||||
gl.glClearColor(r, g, b, 1.0f);
|
||||
gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
|
||||
gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0);
|
||||
gl.glFlush();
|
||||
|
||||
long unlockStart = sw.ElapsedTicks;
|
||||
if (!tex.Unlock())
|
||||
{
|
||||
Console.Error.WriteLine($"[spike] wglDXUnlockObjectsNV failed at frame {frame}.");
|
||||
break;
|
||||
}
|
||||
long unlockEnd = sw.ElapsedTicks;
|
||||
long unlockTicks = unlockEnd - unlockStart;
|
||||
unlockTotalTicks += unlockTicks;
|
||||
if (unlockTicks > unlockMaxTicks) unlockMaxTicks = unlockTicks;
|
||||
|
||||
// ── D3D9 phase: render the texture as a fullscreen quad ──
|
||||
d3d.Clear(0xFF000000); // opaque black, so quad alpha is visible
|
||||
d3d.BeginScene();
|
||||
d3d.DrawTexturedQuad(tex.D3D9Texture, WindowWidth, WindowHeight);
|
||||
d3d.EndScene();
|
||||
d3d.Present();
|
||||
|
||||
frame++;
|
||||
framesThisSecond++;
|
||||
|
||||
// Per-second telemetry — feeds Spike question A3.
|
||||
long now = sw.ElapsedTicks;
|
||||
if ((now - secondAnchor) >= Stopwatch.Frequency)
|
||||
{
|
||||
double avgLockMs = (lockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1);
|
||||
double avgUnlockMs = (unlockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1);
|
||||
double maxUnlockMs = (unlockMaxTicks / (double)Stopwatch.Frequency) * 1000.0;
|
||||
Console.WriteLine($"[spike] frame={frame} fps={framesThisSecond} lock={avgLockMs:F3}ms avgUnlock={avgUnlockMs:F3}ms maxUnlock={maxUnlockMs:F3}ms");
|
||||
|
||||
lockTotalTicks = 0;
|
||||
unlockTotalTicks = 0;
|
||||
unlockMaxTicks = 0;
|
||||
framesThisSecond = 0;
|
||||
secondAnchor = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
24
spikes/WglDxInterop/WglDxInterop.csproj
Normal file
24
spikes/WglDxInterop/WglDxInterop.csproj
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<Platforms>x86</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>WglDxInterop</RootNamespace>
|
||||
<AssemblyName>WglDxInterop</AssemblyName>
|
||||
<UseWindowsForms>false</UseWindowsForms>
|
||||
<UseWPF>false</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--
|
||||
Stage 1 (this csproj): managed build only. Runs as a normal x86 .NET app to keep
|
||||
iteration tight while we prove the WGL_NV_DX_interop2 chain. Stage 2 turns on
|
||||
PublishAot=true and TrimMode=link to mirror the engine's build flags so spike
|
||||
question A6 (NativeAOT survival) can be answered before engine integration.
|
||||
-->
|
||||
|
||||
</Project>
|
||||
141
spikes/WglDxInterop/Win32.cs
Normal file
141
spikes/WglDxInterop/Win32.cs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
// Win32 P/Invoke surface for the spike. Kept narrow — we only need window
|
||||
// creation, a message loop, DC management, and pixel-format setup. All the
|
||||
// GL-side P/Invokes live in Gl.cs; D3D9 P/Invokes live in D3D9.cs.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WglDxInterop;
|
||||
|
||||
internal static unsafe class Win32
|
||||
{
|
||||
public const int WS_OVERLAPPEDWINDOW = 0x00CF0000;
|
||||
public const int WS_VISIBLE = 0x10000000;
|
||||
public const int WS_POPUP = unchecked((int)0x80000000);
|
||||
public const int CW_USEDEFAULT = unchecked((int)0x80000000);
|
||||
public const int SW_SHOW = 5;
|
||||
|
||||
public const uint WM_DESTROY = 0x0002;
|
||||
public const uint WM_QUIT = 0x0012;
|
||||
public const uint WM_SIZE = 0x0005;
|
||||
public const uint WM_CLOSE = 0x0010;
|
||||
public const uint WM_PAINT = 0x000F;
|
||||
|
||||
public const int PFD_DRAW_TO_WINDOW = 0x00000004;
|
||||
public const int PFD_SUPPORT_OPENGL = 0x00000020;
|
||||
public const int PFD_DOUBLEBUFFER = 0x00000001;
|
||||
public const int PFD_TYPE_RGBA = 0;
|
||||
public const byte PFD_MAIN_PLANE = 0;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct PIXELFORMATDESCRIPTOR
|
||||
{
|
||||
public ushort nSize;
|
||||
public ushort nVersion;
|
||||
public uint dwFlags;
|
||||
public byte iPixelType;
|
||||
public byte cColorBits;
|
||||
public byte cRedBits, cRedShift;
|
||||
public byte cGreenBits, cGreenShift;
|
||||
public byte cBlueBits, cBlueShift;
|
||||
public byte cAlphaBits, cAlphaShift;
|
||||
public byte cAccumBits, cAccumRedBits, cAccumGreenBits, cAccumBlueBits, cAccumAlphaBits;
|
||||
public byte cDepthBits, cStencilBits, cAuxBuffers;
|
||||
public byte iLayerType;
|
||||
public byte bReserved;
|
||||
public uint dwLayerMask, dwVisibleMask, dwDamageMask;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct MSG
|
||||
{
|
||||
public IntPtr hwnd;
|
||||
public uint message;
|
||||
public IntPtr wParam;
|
||||
public IntPtr lParam;
|
||||
public uint time;
|
||||
public int ptX;
|
||||
public int ptY;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct WNDCLASSEXW
|
||||
{
|
||||
public uint cbSize;
|
||||
public uint style;
|
||||
public IntPtr lpfnWndProc;
|
||||
public int cbClsExtra;
|
||||
public int cbWndExtra;
|
||||
public IntPtr hInstance;
|
||||
public IntPtr hIcon;
|
||||
public IntPtr hCursor;
|
||||
public IntPtr hbrBackground;
|
||||
public IntPtr lpszMenuName;
|
||||
public IntPtr lpszClassName;
|
||||
public IntPtr hIconSm;
|
||||
}
|
||||
|
||||
public delegate IntPtr WndProcDelegate(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern IntPtr CreateWindowExW(
|
||||
int dwExStyle, string lpClassName, string lpWindowName, int dwStyle,
|
||||
int x, int y, int nWidth, int nHeight,
|
||||
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr DefWindowProcW(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
public static extern bool DestroyWindow(IntPtr hwnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern IntPtr GetDC(IntPtr hwnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool PeekMessageW(out MSG msg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool TranslateMessage(ref MSG msg);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr DispatchMessageW(ref MSG msg);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern void PostQuitMessage(int nExitCode);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr GetModuleHandleW(string? lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
|
||||
public static extern IntPtr LoadLibraryA(string lpFileName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
|
||||
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
public static extern int ChoosePixelFormat(IntPtr hdc, ref PIXELFORMATDESCRIPTOR ppfd);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
public static extern bool SetPixelFormat(IntPtr hdc, int format, ref PIXELFORMATDESCRIPTOR ppfd);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
public static extern bool SwapBuffers(IntPtr hdc);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct RECT { public int Left, Top, Right, Bottom; }
|
||||
|
||||
public const uint PM_REMOVE = 0x0001;
|
||||
}
|
||||
76
spikes/WglDxInterop/findings.md
Normal file
76
spikes/WglDxInterop/findings.md
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
# Phase A spike findings — WGL_NV_DX_interop2 for D3D9 sources
|
||||
|
||||
**Verdict: NOT VIABLE on this hardware.**
|
||||
|
||||
The technique recommended in `wgl-interop-plan.md` does not work for D3D9 sources on the user's machine. This invalidates the plan as written. **Stop and pivot before any engine code changes.**
|
||||
|
||||
---
|
||||
|
||||
## What was tested
|
||||
|
||||
Hardware: NVIDIA GeForce GTX 1650 SUPER, driver 560.94 (current).
|
||||
|
||||
OS: Windows 10 Pro 19045.
|
||||
|
||||
GL: 3.3.0 NVIDIA 560.94, real ICD context (not Microsoft GDI fallback). 809 chars of WGL extension string, both `WGL_NV_DX_interop` and `WGL_NV_DX_interop2` advertised as supported.
|
||||
|
||||
Spike code: `C:\Projects\RynthCore\spikes\WglDxInterop\` — ~600 LOC, builds clean as managed x86.
|
||||
|
||||
## Results
|
||||
|
||||
`wglDXOpenDeviceNV(deviceHandle)`: **succeeds** for both plain D3D9 and D3D9Ex. Returns a non-null handle. Already informative — the D3D device is recognized as a valid interop source.
|
||||
|
||||
`wglDXSetResourceShareHandleNV(surface, sharedHandle)`: **succeeds** for D3D9Ex render-target textures created with a non-null `pSharedHandle` slot.
|
||||
|
||||
`wglDXRegisterObjectNV(...)`: **fails (returns NULL)** in 10 distinct configurations:
|
||||
|
||||
| Device | Source | Type | Access | Result |
|
||||
|---|---|---|---|---|
|
||||
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL (LastError 0xC007006E first call, 0x0 subsequent) |
|
||||
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
|
||||
| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL |
|
||||
| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
|
||||
| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
|
||||
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
|
||||
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
|
||||
| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL |
|
||||
| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL |
|
||||
| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL |
|
||||
|
||||
Other variables ruled out:
|
||||
- `D3DCREATE_MULTITHREADED` flag: tested both on and off. Same failure either way.
|
||||
- `D3DCREATE_HARDWARE_VERTEXPROCESSING` vs `_SOFTWARE_VERTEXPROCESSING`: tested both. Same failure.
|
||||
- Shared focus window vs isolated hidden window for the GL context: tested both. Same failure.
|
||||
- Texture format / dimensions: A8R8G8B8, 1280×720, D3DPOOL_DEFAULT, D3DUSAGE_RENDERTARGET — the canonical "supported" combination per spec.
|
||||
|
||||
The `0xC007006E = HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE)` on the very first call (subsequent calls leave LastError as 0, suggesting the driver doesn't reliably call `SetLastError`) is the only diagnostic NVIDIA's driver gives us. There is no way to query a more specific error.
|
||||
|
||||
## Interpretation
|
||||
|
||||
The published NV_DX_interop spec lists D3D9 surfaces as supported, but **NVIDIA's current driver implementation does not work for D3D9 sources** in the configurations a real-world overlay would need. This matches scattered third-party reports (Chromium's interop code carries D3D11 fallbacks and explicit notes about D3D9 quirkiness; various Steam/MSI Afterburner reverse-engineerings show they use D3D11 internally and composite differently). **WGL_NV_DX_interop2 is essentially a D3D11-and-newer interop in practice, even though the spec language is broader.**
|
||||
|
||||
Key implication: **the recommendation in `wgl-interop-plan.md` was wrong.** I led the user there based on the spec text and well-known overlay-in-D3D9-game examples — but those examples almost universally use D3D11 internally, not D3D9. The "render into AC's D3D9 texture via WGL interop" path is closed on this driver, and likely on every modern NVIDIA driver.
|
||||
|
||||
## What's left
|
||||
|
||||
The original GPU-rendering option space, re-evaluated against this finding:
|
||||
|
||||
1. **D3D11 producer via WGL_NV_DX_interop2 → AC's plain D3D9 consumer.** Not tested in the spike yet, but the *interop* part is the well-trodden one and almost certainly works. The hard part was always "→ AC's plain D3D9 consumer", which still requires either:
|
||||
- **(a) Hook `Direct3DCreate9` in acclient.exe at runtime to substitute `Direct3DCreate9Ex`.** Makes AC's device Ex. Ex devices CAN open shared HANDLEs from D3D11 (via DXGI sharing). MANAGED-pool wrapper required for AC's textures, lost-device semantics need shimming.
|
||||
- **(b) CPU readback of the D3D11 texture, then D3D9 LockRect+memcpy.** Same as today's software path with extra GPU latency. Nets nothing.
|
||||
|
||||
2. **Layered/child window approach.** No AC modification. Avalonia renders to its own ANGLE+D3D11 swap chain on a separate Win32 window, DWM composites it over AC. The mover bug (Phase 2a diagnostic — ~50 LOC fix) needs landing first. Then we'd extend layered windows to cover the bar + docked panels too, retiring the EndScene composite path.
|
||||
|
||||
3. **Fix software Skia.** Pursue the LFH AV at its actual source (Skia teardown allocations) rather than trying to GPU-accelerate a path that's blocked at the consumer side.
|
||||
|
||||
Path 1(a) is the same "hook Direct3DCreate9 → Ex" we discussed before the spike — runtime hook, no acclient.exe disk patch, no other-user impact. The spike's value here is that it confirms WGL interop is fine for D3D11 (assumed; would need a 30-minute test to verify), and the only structural blocker remaining is making AC's device Ex.
|
||||
|
||||
Path 2 has the largest scope but the smallest risk to AC stability. Coexistence-mode-friendly for free.
|
||||
|
||||
Path 3 is the smallest and probably the most-immediate-value option (the LFH AV is the actual blocker for daily use, not the lack of GPU rendering).
|
||||
|
||||
## Recommendation
|
||||
|
||||
Stop pursuing the WGL_NV_DX_interop2 → AC's D3D9 plan. Present the three remaining paths and let the user pick. None of them are a small follow-up on the current investigation — each is a meaningful pivot.
|
||||
|
||||
The spike was an unambiguous win: ~3 hours invested, conclusive data, prevented a multi-weekend integration on a foundation that wouldn't have worked.
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="RynthCore.App.Avalonia.AccountProfileDialog"
|
||||
Width="520"
|
||||
Height="360"
|
||||
Width="600"
|
||||
Height="620"
|
||||
CanResize="False"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Title="Account Profile"
|
||||
|
|
@ -24,10 +24,23 @@
|
|||
<TextBlock x:Name="PasswordHintText"
|
||||
Foreground="#9AA8B3"
|
||||
TextWrapping="Wrap" />
|
||||
<TextBlock Text="Character / Slot" Foreground="#EAF0F4" />
|
||||
<ComboBox x:Name="CharacterBox" HorizontalAlignment="Stretch" IsTextSearchEnabled="True" />
|
||||
<TextBlock Text="Alias" Foreground="#EAF0F4" />
|
||||
<TextBox x:Name="AliasBox" />
|
||||
|
||||
<TextBlock Text="Per-account UserPreferences.ini stash (optional)" Foreground="#EAF0F4" />
|
||||
<Grid ColumnDefinitions="*,Auto,Auto">
|
||||
<TextBox x:Name="UserPrefsPathBox"
|
||||
Grid.Column="0"
|
||||
Margin="0,0,6,0"
|
||||
Watermark="Leave blank to share the global UserPreferences.ini" />
|
||||
<Button x:Name="BrowseUserPrefsButton" Grid.Column="1" Margin="0,0,6,0" Content="Browse..." />
|
||||
<Button x:Name="SnapshotUserPrefsButton" Grid.Column="2" Content="Snapshot live →" />
|
||||
</Grid>
|
||||
<TextBlock x:Name="UserPrefsHintText"
|
||||
Foreground="#9AA8B3"
|
||||
TextWrapping="Wrap"
|
||||
Text="Leave blank for the default path under %APPDATA%\RynthCore\prefs. The launcher snapshots live UserPreferences.ini back to the stash automatically when this client exits, so per-account chat tabs / hotkeys / UI layout persist across sessions." />
|
||||
|
||||
<TextBlock x:Name="ValidationText" Foreground="#E2B348" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
|
@ -26,116 +26,82 @@ internal partial class AccountProfileDialog : Window
|
|||
|
||||
AccountBox.Text = profile.AccountName;
|
||||
AliasBox.Text = profile.Alias;
|
||||
UserPrefsPathBox.Text = profile.UserPrefsPath;
|
||||
PasswordHintText.Text = string.IsNullOrEmpty(profile.Password)
|
||||
? "No password is saved for this profile yet."
|
||||
: "A password is already saved for this profile. It stays hidden unless you replace or clear it.";
|
||||
|
||||
PopulateCharacterDropdown(profile.AccountName, GetSelectedServerName(), profile.CharacterName);
|
||||
|
||||
// Re-populate characters when account name or server changes
|
||||
AccountBox.TextChanged += (_, _) =>
|
||||
{
|
||||
string currentChar = GetSelectedCharacterName();
|
||||
PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), currentChar);
|
||||
};
|
||||
ServerComboBox.SelectionChanged += (_, _) =>
|
||||
{
|
||||
PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), GetSelectedCharacterName());
|
||||
};
|
||||
|
||||
SaveButton.Click += (_, _) => SaveAndClose();
|
||||
CancelButton.Click += (_, _) => Close(false);
|
||||
BrowseUserPrefsButton.Click += async (_, _) => await BrowseUserPrefsAsync();
|
||||
SnapshotUserPrefsButton.Click += (_, _) => SnapshotLiveUserPrefs();
|
||||
}
|
||||
|
||||
private string GetSelectedServerName() =>
|
||||
ServerComboBox.SelectedIndex >= 0 && ServerComboBox.SelectedIndex < _servers.Count
|
||||
? _servers[ServerComboBox.SelectedIndex].Name
|
||||
: string.Empty;
|
||||
|
||||
private void PopulateCharacterDropdown(string accountName, string serverName, string selectedCharacter)
|
||||
private async System.Threading.Tasks.Task BrowseUserPrefsAsync()
|
||||
{
|
||||
List<string> chars = LoadDetectedCharacters(accountName, serverName);
|
||||
if (string.IsNullOrWhiteSpace(selectedCharacter) && chars.Count == 1)
|
||||
selectedCharacter = chars[0];
|
||||
var topLevel = GetTopLevel(this);
|
||||
if (topLevel == null)
|
||||
return;
|
||||
|
||||
// Ensure the existing saved name appears even if the scan file is empty
|
||||
if (!string.IsNullOrEmpty(selectedCharacter) && !chars.Contains(selectedCharacter))
|
||||
chars.Insert(0, selectedCharacter);
|
||||
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Select a UserPreferences.ini stash",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter =
|
||||
[
|
||||
new FilePickerFileType("Asheron's Call prefs (*.ini)") { Patterns = ["*.ini"] },
|
||||
new FilePickerFileType("All Files") { Patterns = ["*"] }
|
||||
]
|
||||
});
|
||||
|
||||
CharacterBox.ItemsSource = chars;
|
||||
if (files.Count == 0)
|
||||
return;
|
||||
|
||||
if (!string.IsNullOrEmpty(selectedCharacter) && chars.Contains(selectedCharacter))
|
||||
CharacterBox.SelectedItem = selectedCharacter;
|
||||
UserPrefsPathBox.Text = Path.GetFullPath(files[0].Path.LocalPath);
|
||||
}
|
||||
|
||||
private string GetSelectedCharacterName() =>
|
||||
CharacterBox.SelectedItem as string ?? string.Empty;
|
||||
|
||||
private static List<string> LoadDetectedCharacters(string accountName, string serverName = "")
|
||||
private void SnapshotLiveUserPrefs()
|
||||
{
|
||||
try
|
||||
string stashPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(stashPath))
|
||||
{
|
||||
List<string> cachedCharacters = CharacterCacheStore.Read(accountName, serverName);
|
||||
if (cachedCharacters.Count > 0)
|
||||
return cachedCharacters;
|
||||
|
||||
// 3. ThwargLauncher character files
|
||||
return ReadThwargCharacters(accountName, serverName);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> ReadThwargCharacters(string accountName, string serverName = "")
|
||||
{
|
||||
try
|
||||
{
|
||||
string charDir = Path.Combine(
|
||||
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),
|
||||
"ThwargLauncher", "characters");
|
||||
|
||||
if (!Directory.Exists(charDir))
|
||||
return [];
|
||||
|
||||
var results = new List<string>();
|
||||
foreach (string file in Directory.GetFiles(charDir, "*.txt"))
|
||||
string accountName = AccountBox.Text?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(accountName))
|
||||
{
|
||||
try
|
||||
{
|
||||
string json = File.ReadAllText(file);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (var entry in doc.RootElement.EnumerateObject())
|
||||
{
|
||||
bool accountMatches = string.IsNullOrWhiteSpace(accountName) ||
|
||||
entry.Name.EndsWith("-" + accountName, System.StringComparison.OrdinalIgnoreCase);
|
||||
bool serverMatches = string.IsNullOrWhiteSpace(serverName) ||
|
||||
entry.Name.StartsWith(serverName + "-", System.StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!accountMatches || !serverMatches) continue;
|
||||
if (!entry.Value.TryGetProperty("CharacterList", out var list)) continue;
|
||||
|
||||
foreach (var charEl in list.EnumerateArray())
|
||||
{
|
||||
if (charEl.TryGetProperty("Name", out var nameEl))
|
||||
{
|
||||
string name = nameEl.GetString() ?? string.Empty;
|
||||
if (!string.IsNullOrEmpty(name) && !results.Contains(name))
|
||||
results.Add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
UserPrefsHintText.Text = "Snapshot needs an account name (so it can pick a default stash file).";
|
||||
return;
|
||||
}
|
||||
return results;
|
||||
|
||||
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||||
string safeName = string.Join("_", accountName.Split(Path.GetInvalidFileNameChars()));
|
||||
stashPath = Path.Combine(appdata, "RynthCore", "prefs", $"{safeName}.ini");
|
||||
}
|
||||
catch
|
||||
|
||||
string livePath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
|
||||
"Asheron's Call",
|
||||
"UserPreferences.ini");
|
||||
|
||||
if (!File.Exists(livePath))
|
||||
{
|
||||
return [];
|
||||
UserPrefsHintText.Text = $"Live UserPreferences.ini not found at {livePath}.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(stashPath);
|
||||
if (!string.IsNullOrWhiteSpace(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
File.Copy(livePath, stashPath, overwrite: true);
|
||||
UserPrefsHintText.Text = $"Snapshot saved to {stashPath}.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UserPrefsHintText.Text = $"Snapshot failed: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveAndClose()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(AccountBox.Text))
|
||||
|
|
@ -157,8 +123,8 @@ internal partial class AccountProfileDialog : Window
|
|||
_profile.Password = PasswordBox.Text;
|
||||
}
|
||||
|
||||
_profile.CharacterName = GetSelectedCharacterName();
|
||||
_profile.Alias = AliasBox.Text?.Trim() ?? string.Empty;
|
||||
_profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty;
|
||||
|
||||
Close(true);
|
||||
}
|
||||
|
|
|
|||
138
src/RynthCore.App.Avalonia/EngineJsonStore.cs
Normal file
138
src/RynthCore.App.Avalonia/EngineJsonStore.cs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Read-modify-write access to %APPDATA%\RynthCore\engine.json. The launcher
|
||||
/// owns a few engine-side flags (DComp overlay toggle, plugin paths, etc.)
|
||||
/// but the engine has its own flags that the launcher should never overwrite
|
||||
/// (EnableImGuiShell, EnableImGuiBackend, EngineHookCount, ...). This helper
|
||||
/// preserves every field it doesn't touch so those don't get clobbered when
|
||||
/// the launcher updates one setting.
|
||||
/// </summary>
|
||||
internal static class EngineJsonStore
|
||||
{
|
||||
public static string Path => System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"engine.json");
|
||||
|
||||
// Latched when an EXISTING engine.json failed to parse. While set, Write()
|
||||
// is refused: writing the (empty) read-back would silently destroy every
|
||||
// field the parse failure hid — EnableImGuiShell, PluginPaths, the lot —
|
||||
// the exact clobber this class's doc comment promises not to do.
|
||||
private static bool _refuseWrites;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the JSON document as a mutable dictionary. Missing file → empty
|
||||
/// dict. Parse error on an EXISTING file → empty dict for read-only use,
|
||||
/// but writes are disabled until the file is fixed or deleted.
|
||||
/// </summary>
|
||||
public static Dictionary<string, JsonElement> Read()
|
||||
{
|
||||
var result = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(Path)) return result;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(Path));
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return result;
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
result[p.Name] = p.Value.Clone();
|
||||
_refuseWrites = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!_refuseWrites)
|
||||
LauncherDiag.Info($"ENGINEJSON: {Path} failed to parse ({ex.GetType().Name}: {ex.Message}) — launcher writes to it are DISABLED until the file is fixed or deleted, so the engine's settings can't be clobbered.");
|
||||
_refuseWrites = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void Write(Dictionary<string, JsonElement> fields)
|
||||
{
|
||||
if (_refuseWrites)
|
||||
{
|
||||
LauncherDiag.Info($"ENGINEJSON: write refused — {Path} is corrupt (see earlier ENGINEJSON line). Fix or delete it, then retry.");
|
||||
return;
|
||||
}
|
||||
|
||||
string? dir = System.IO.Path.GetDirectoryName(Path);
|
||||
if (dir != null) Directory.CreateDirectory(dir);
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
foreach (KeyValuePair<string, JsonElement> kv in fields)
|
||||
{
|
||||
w.WritePropertyName(kv.Key);
|
||||
kv.Value.WriteTo(w);
|
||||
}
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
// Atomic swap (with .bak) — a crash mid-write otherwise truncates the
|
||||
// file, and the engine silently reverts ALL settings on a corrupt read.
|
||||
string tmp = Path + ".tmp";
|
||||
File.WriteAllBytes(tmp, ms.ToArray());
|
||||
if (File.Exists(Path))
|
||||
File.Replace(tmp, Path, Path + ".bak");
|
||||
else
|
||||
File.Move(tmp, Path);
|
||||
}
|
||||
|
||||
public static bool? GetBool(string field)
|
||||
{
|
||||
Dictionary<string, JsonElement> fields = Read();
|
||||
if (!fields.TryGetValue(field, out JsonElement el)) return null;
|
||||
return el.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
public static void SetBool(string field, bool value)
|
||||
{
|
||||
Dictionary<string, JsonElement> fields = Read();
|
||||
using var doc = JsonDocument.Parse(value ? "true" : "false");
|
||||
fields[field] = doc.RootElement.Clone();
|
||||
Write(fields);
|
||||
}
|
||||
|
||||
public static void SetStringArray(string field, IEnumerable<string> values)
|
||||
{
|
||||
Dictionary<string, JsonElement> fields = Read();
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms))
|
||||
{
|
||||
w.WriteStartArray();
|
||||
foreach (string v in values) w.WriteStringValue(v);
|
||||
w.WriteEndArray();
|
||||
}
|
||||
using var doc = JsonDocument.Parse(ms.ToArray());
|
||||
fields[field] = doc.RootElement.Clone();
|
||||
Write(fields);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a single string field (e.g. "LoggingLevel"), preserving every other field.
|
||||
/// </summary>
|
||||
public static void SetString(string field, string value)
|
||||
{
|
||||
Dictionary<string, JsonElement> fields = Read();
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms))
|
||||
w.WriteStringValue(value);
|
||||
using var doc = JsonDocument.Parse(ms.ToArray());
|
||||
fields[field] = doc.RootElement.Clone();
|
||||
Write(fields);
|
||||
}
|
||||
}
|
||||
65
src/RynthCore.App.Avalonia/LauncherDiag.cs
Normal file
65
src/RynthCore.App.Avalonia/LauncherDiag.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Tiny file-append logger for the launcher. Mirrors the pattern used by
|
||||
/// RynthCore.Loader and RynthCore.Engine so all three components write to
|
||||
/// the same unified log (C:\Games\RynthCore\Logs\RynthCore.log) and entries
|
||||
/// can be correlated across processes.
|
||||
///
|
||||
/// Used for diagnostic instrumentation that needs to survive a launcher
|
||||
/// restart — AppendActivity only feeds the in-memory UI panel and is lost
|
||||
/// when the launcher exits, which makes it useless for diagnosing exactly
|
||||
/// the kind of "restart fixes it" launcher-state bugs we're chasing.
|
||||
/// </summary>
|
||||
internal static class LauncherDiag
|
||||
{
|
||||
// Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore).
|
||||
private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir;
|
||||
private const string UnifiedLogFileName = "RynthCore.log";
|
||||
|
||||
private static readonly object LogLock = new();
|
||||
|
||||
public static void Info(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = $"[{DateTime.Now:HH:mm:ss.fff}] [pid:{Environment.ProcessId}] [launcher] {message}\r\n";
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(line);
|
||||
|
||||
lock (LogLock)
|
||||
{
|
||||
for (int attempt = 0; attempt < 4; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(UnifiedLogDirectory);
|
||||
using var fs = new FileStream(
|
||||
Path.Combine(UnifiedLogDirectory, UnifiedLogFileName),
|
||||
FileMode.Append,
|
||||
FileAccess.Write,
|
||||
FileShare.ReadWrite);
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
return;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
87
src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml
Normal file
87
src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="RynthCore.App.Avalonia.LoginCommandsDialog"
|
||||
Width="780"
|
||||
Height="540"
|
||||
CanResize="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Title="OnLogin Commands"
|
||||
Background="#132028">
|
||||
<Grid ColumnDefinitions="260,*" Margin="14">
|
||||
<Border Grid.Column="0" Background="#0F161D" CornerRadius="10" Padding="10" Margin="0,0,8,0">
|
||||
<Grid RowDefinitions="Auto,Auto,*,Auto,Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Text="Characters" FontSize="14" FontWeight="SemiBold" Foreground="#26C1A6" Margin="0,0,0,4" />
|
||||
<TextBlock Grid.Row="1"
|
||||
x:Name="ScopeText"
|
||||
Foreground="#9AA8B3"
|
||||
FontSize="11.5"
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,0,0,8" />
|
||||
<ListBox Grid.Row="2"
|
||||
x:Name="CharacterList"
|
||||
Background="Transparent"
|
||||
BorderBrush="#243742"
|
||||
Foreground="#EAF0F4"
|
||||
FontSize="12.5" />
|
||||
<TextBlock Grid.Row="3" Text="Add a character" Foreground="#EAF0F4" Margin="0,10,0,4" />
|
||||
<Grid Grid.Row="4" ColumnDefinitions="*,Auto">
|
||||
<TextBox Grid.Column="0" x:Name="NewCharacterBox" Watermark="Character name" />
|
||||
<Button Grid.Column="1" x:Name="AddCharacterButton" Content="Add" Margin="6,0,0,0" />
|
||||
</Grid>
|
||||
<StackPanel Grid.Row="5" Orientation="Horizontal" Spacing="6" Margin="0,8,0,0">
|
||||
<Button x:Name="RefreshCharactersButton"
|
||||
Content="Refresh from cache"
|
||||
ToolTip.Tip="Pulls the character roster captured at last char-select for this account+server. The engine writes this on every char-select visit." />
|
||||
<Button x:Name="RemoveCharacterButton" Content="Remove" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="1" Background="#0F161D" CornerRadius="10" Padding="14">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
|
||||
<TextBlock Grid.Row="0"
|
||||
x:Name="HeaderText"
|
||||
Text="Select a character on the left."
|
||||
FontSize="15"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="#EAF0F4"
|
||||
Margin="0,0,0,4" />
|
||||
<TextBlock Grid.Row="1"
|
||||
x:Name="SubHeaderText"
|
||||
Text=""
|
||||
Foreground="#9AA8B3"
|
||||
Margin="0,0,0,12" />
|
||||
|
||||
<Grid Grid.Row="2" ColumnDefinitions="Auto,Auto,*" Margin="0,0,0,10">
|
||||
<TextBlock Grid.Column="0" Text="Wait after login (ms):" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<NumericUpDown Grid.Column="1" x:Name="WaitMsBox" Minimum="0" Maximum="60000" Increment="500" Width="120" />
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="Per-account. Default 3000ms. Wait runs after the engine sees AC's login-complete signal."
|
||||
Foreground="#73828D"
|
||||
TextWrapping="Wrap"
|
||||
VerticalAlignment="Center"
|
||||
Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
|
||||
<Border Grid.Row="3" BorderBrush="#243742" BorderThickness="1" CornerRadius="6">
|
||||
<TextBox x:Name="CommandsBox"
|
||||
AcceptsReturn="True"
|
||||
AcceptsTab="False"
|
||||
TextWrapping="NoWrap"
|
||||
VerticalContentAlignment="Top"
|
||||
Watermark="One command per line. Examples: /fellow open /say ready /cm channel join allegiance"
|
||||
Background="#0B1116"
|
||||
Foreground="#EAF0F4"
|
||||
BorderThickness="0"
|
||||
Padding="8" />
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Row="4" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,12,0,0">
|
||||
<TextBlock x:Name="StatusText" Foreground="#9AA8B3" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<Button x:Name="SaveButton" Content="Save" />
|
||||
<Button x:Name="CloseButton" Content="Close" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
286
src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml.cs
Normal file
286
src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml.cs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Per-account dialog for editing OnLogin chat commands. Scoped to a single
|
||||
/// LaunchAccountProfile so we never accidentally show characters from other
|
||||
/// accounts. The character list is sourced strictly from:
|
||||
/// 1. The profile's currently-selected CharacterName
|
||||
/// 2. Characters that already have configured commands on this profile
|
||||
/// 3. Names the user adds manually via the "Add character" field
|
||||
///
|
||||
/// We pull from CharacterCacheStore.ReadStrict (server-scoped, no fallback).
|
||||
/// The engine writes the full slot roster from AC's 0xF658 server packet on
|
||||
/// every char-select visit, scoped per (account, server). The strict reader
|
||||
/// avoids the legacy account-only fallback file which can leak chars from
|
||||
/// other accounts/servers populated before per-server scoping existed.
|
||||
/// </summary>
|
||||
internal partial class LoginCommandsDialog : Window
|
||||
{
|
||||
private readonly LaunchAccountProfile _profile;
|
||||
private readonly LaunchServerProfile? _server;
|
||||
|
||||
private readonly ObservableCollection<string> _characters = new();
|
||||
private string? _current;
|
||||
private bool _suppressDirtyTracking;
|
||||
private bool _isDirty;
|
||||
|
||||
public bool ChangesSaved { get; private set; }
|
||||
|
||||
public LoginCommandsDialog(LaunchAccountProfile profile, LaunchServerProfile? server)
|
||||
{
|
||||
_profile = profile;
|
||||
_server = server;
|
||||
InitializeComponent();
|
||||
|
||||
ScopeText.Text = server == null
|
||||
? $"Account: {_profile.AccountName}"
|
||||
: $"{_profile.AccountName} @ {server.Name}";
|
||||
|
||||
SeedCharacterList();
|
||||
|
||||
CharacterList.ItemsSource = _characters;
|
||||
CharacterList.SelectionChanged += OnCharacterSelectionChanged;
|
||||
|
||||
WaitMsBox.ValueChanged += (_, _) => MarkDirty();
|
||||
CommandsBox.TextChanged += (_, _) => MarkDirty();
|
||||
|
||||
SaveButton.Click += (_, _) => SaveCurrent();
|
||||
CloseButton.Click += (_, _) => Close();
|
||||
AddCharacterButton.Click += (_, _) => AddCharacterFromBox();
|
||||
RemoveCharacterButton.Click += (_, _) => RemoveSelectedCharacter();
|
||||
RefreshCharactersButton.Click += (_, _) => RefreshFromCache();
|
||||
NewCharacterBox.KeyDown += (_, e) =>
|
||||
{
|
||||
if (e.Key == global::Avalonia.Input.Key.Enter)
|
||||
AddCharacterFromBox();
|
||||
};
|
||||
|
||||
if (_characters.Count == 0)
|
||||
{
|
||||
HeaderText.Text = "No characters yet.";
|
||||
SubHeaderText.Text = "Add a character on the left to start editing commands.";
|
||||
SetEditorEnabled(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
CharacterList.SelectedIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void SeedCharacterList()
|
||||
{
|
||||
var seen = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_profile.CharacterName)
|
||||
&& _profile.CharacterName != LaunchAccountProfile.NoneOption)
|
||||
{
|
||||
seen.Add(_profile.CharacterName);
|
||||
}
|
||||
|
||||
foreach (string configured in _profile.OnLoginCommandsByCharacter.Keys)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(configured))
|
||||
seen.Add(configured);
|
||||
}
|
||||
|
||||
// Strict (account, server) read — avoids the legacy account-only
|
||||
// fallback file that could leak characters from prior contexts.
|
||||
if (_server != null)
|
||||
{
|
||||
foreach (string cached in CharacterCacheStore.ReadStrict(_profile.AccountName, _server.Name))
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(cached))
|
||||
seen.Add(cached);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (string c in seen)
|
||||
_characters.Add(c);
|
||||
}
|
||||
|
||||
private void RefreshFromCache()
|
||||
{
|
||||
if (_server == null)
|
||||
{
|
||||
StatusText.Text = "No server set on this profile — nothing to refresh.";
|
||||
return;
|
||||
}
|
||||
|
||||
var fresh = CharacterCacheStore.ReadStrict(_profile.AccountName, _server.Name);
|
||||
if (fresh.Count == 0)
|
||||
{
|
||||
StatusText.Text = "Cache is empty for this account+server. Visit char-select once to populate.";
|
||||
return;
|
||||
}
|
||||
|
||||
// Preserve any user-added characters and any with configured commands;
|
||||
// merge the cache list on top.
|
||||
var merged = new SortedSet<string>(_characters, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string c in fresh)
|
||||
merged.Add(c);
|
||||
|
||||
// Re-seed the visible list from the merged set.
|
||||
string? previouslySelected = _current;
|
||||
_characters.Clear();
|
||||
foreach (string c in merged)
|
||||
_characters.Add(c);
|
||||
|
||||
if (previouslySelected != null)
|
||||
SelectCharacter(previouslySelected);
|
||||
|
||||
StatusText.Text = $"Loaded {fresh.Count} character(s) from cache.";
|
||||
}
|
||||
|
||||
private void OnCharacterSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (_isDirty && _current != null)
|
||||
{
|
||||
// Auto-save in-flight edits so a stray click doesn't lose work.
|
||||
SaveCurrent();
|
||||
}
|
||||
|
||||
_current = CharacterList.SelectedItem as string;
|
||||
LoadCurrent();
|
||||
}
|
||||
|
||||
private void LoadCurrent()
|
||||
{
|
||||
_suppressDirtyTracking = true;
|
||||
try
|
||||
{
|
||||
if (_current == null)
|
||||
{
|
||||
HeaderText.Text = _characters.Count == 0
|
||||
? "No characters yet."
|
||||
: "Select a character on the left.";
|
||||
SubHeaderText.Text = "";
|
||||
CommandsBox.Text = "";
|
||||
WaitMsBox.Value = _profile.OnLoginWaitMs;
|
||||
SetEditorEnabled(false);
|
||||
return;
|
||||
}
|
||||
|
||||
HeaderText.Text = _current;
|
||||
SubHeaderText.Text = _server == null
|
||||
? _profile.AccountName
|
||||
: $"{_profile.AccountName} @ {_server.Name}";
|
||||
|
||||
WaitMsBox.Value = _profile.OnLoginWaitMs;
|
||||
CommandsBox.Text = _profile.OnLoginCommandsByCharacter.TryGetValue(_current, out List<string>? cmds) && cmds != null
|
||||
? string.Join(Environment.NewLine, cmds)
|
||||
: string.Empty;
|
||||
|
||||
SetEditorEnabled(true);
|
||||
StatusText.Text = "";
|
||||
_isDirty = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressDirtyTracking = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkDirty()
|
||||
{
|
||||
if (_suppressDirtyTracking)
|
||||
return;
|
||||
_isDirty = true;
|
||||
StatusText.Text = "Unsaved changes";
|
||||
}
|
||||
|
||||
private void SaveCurrent()
|
||||
{
|
||||
if (_current == null)
|
||||
return;
|
||||
|
||||
var lines = (CommandsBox.Text ?? string.Empty)
|
||||
.Replace("\r\n", "\n", StringComparison.Ordinal)
|
||||
.Split('\n')
|
||||
.Select(l => l.TrimEnd())
|
||||
.Where(l => !string.IsNullOrWhiteSpace(l))
|
||||
.ToList();
|
||||
|
||||
if (lines.Count == 0)
|
||||
_profile.OnLoginCommandsByCharacter.Remove(_current);
|
||||
else
|
||||
_profile.OnLoginCommandsByCharacter[_current] = lines;
|
||||
|
||||
if (WaitMsBox.Value is decimal w)
|
||||
_profile.OnLoginWaitMs = (int)w;
|
||||
|
||||
ChangesSaved = true;
|
||||
_isDirty = false;
|
||||
StatusText.Text = $"Saved {lines.Count} command(s) for {_current}.";
|
||||
}
|
||||
|
||||
private void AddCharacterFromBox()
|
||||
{
|
||||
string name = (NewCharacterBox.Text ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(name))
|
||||
return;
|
||||
|
||||
if (!_characters.Any(c => string.Equals(c, name, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
_characters.Add(name);
|
||||
// Resort with case-insensitive ordinal compare for stable display.
|
||||
ResortCharacters();
|
||||
}
|
||||
|
||||
NewCharacterBox.Text = string.Empty;
|
||||
SelectCharacter(name);
|
||||
SetEditorEnabled(true);
|
||||
}
|
||||
|
||||
private void RemoveSelectedCharacter()
|
||||
{
|
||||
if (_current == null)
|
||||
return;
|
||||
|
||||
// Removing also clears any saved commands for that character so the
|
||||
// profile state matches the visible list.
|
||||
_profile.OnLoginCommandsByCharacter.Remove(_current);
|
||||
_characters.Remove(_current);
|
||||
ChangesSaved = true;
|
||||
_current = null;
|
||||
|
||||
if (_characters.Count > 0)
|
||||
CharacterList.SelectedIndex = 0;
|
||||
else
|
||||
LoadCurrent();
|
||||
}
|
||||
|
||||
private void SelectCharacter(string name)
|
||||
{
|
||||
for (int i = 0; i < _characters.Count; i++)
|
||||
{
|
||||
if (string.Equals(_characters[i], name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
CharacterList.SelectedIndex = i;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ResortCharacters()
|
||||
{
|
||||
var sorted = _characters.OrderBy(c => c, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
_characters.Clear();
|
||||
foreach (string c in sorted)
|
||||
_characters.Add(c);
|
||||
}
|
||||
|
||||
private void SetEditorEnabled(bool enabled)
|
||||
{
|
||||
CommandsBox.IsEnabled = enabled;
|
||||
WaitMsBox.IsEnabled = enabled;
|
||||
SaveButton.IsEnabled = enabled;
|
||||
RemoveCharacterButton.IsEnabled = enabled;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:RynthCore.App.Avalonia"
|
||||
x:Class="RynthCore.App.Avalonia.MainWindow"
|
||||
Width="1280"
|
||||
Height="860"
|
||||
|
|
@ -70,6 +71,13 @@
|
|||
FontSize="24"
|
||||
FontWeight="Bold"
|
||||
Foreground="#26C1A6" />
|
||||
<TextBlock x:Name="HeaderVersionText"
|
||||
FontSize="11"
|
||||
Foreground="#9AA8B3" />
|
||||
<TextBlock x:Name="HeaderUpdateText"
|
||||
IsVisible="False"
|
||||
FontSize="12"
|
||||
Foreground="#F2C14E" />
|
||||
</StackPanel>
|
||||
|
||||
<GridSplitter Grid.Column="2"
|
||||
|
|
@ -229,6 +237,23 @@
|
|||
<TabItem Header="Plugins">
|
||||
<ScrollViewer>
|
||||
<StackPanel Spacing="12" Margin="6">
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock x:Name="UpdateStatusText"
|
||||
Text="Not checked yet."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
<WrapPanel Orientation="Horizontal">
|
||||
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" />
|
||||
<Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" />
|
||||
<Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" />
|
||||
</WrapPanel>
|
||||
<CheckBox x:Name="AutoUpdatePluginsCheckBox"
|
||||
Content="Update plugins automatically (a running bot keeps its version until AC restarts)"
|
||||
Foreground="#EAF0F4" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
|
|
@ -284,7 +309,12 @@
|
|||
<CheckBox x:Name="SkipIntroVideosCheckBox" Content="Skip intro videos" />
|
||||
<CheckBox x:Name="SkipLoginLogosCheckBox" Content="Skip login logos" />
|
||||
<CheckBox x:Name="AutoInjectAfterLaunchCheckBox" Content="Auto inject after launch" />
|
||||
<CheckBox x:Name="WatchForAcStartCheckBox" Content="Watch for AC start" />
|
||||
<CheckBox x:Name="WatchForAcStartCheckBox"
|
||||
Content="Auto-inject into externally-launched AC"
|
||||
ToolTip.Tip="Watches for acclient.exe processes started by other launchers (Decal, UBLoader, ThwargLauncher). Once the client's graphics state is stable, RynthCore is injected automatically. Skips processes the launcher started itself or that already have RynthCore loaded." />
|
||||
<CheckBox x:Name="OverrideWindowTitleCheckBox"
|
||||
Content="Rewrite AC window titles per account"
|
||||
ToolTip.Tip="Replaces "Asheron's Call" with "Account / Character @ Server" on tracked clients so multi-box taskbars are readable. Untracked external clients are left alone." />
|
||||
<CheckBox x:Name="InjectAllRunningAcCheckBox" Content="Inject all running AC sessions" />
|
||||
<TextBlock Text="Logging level" Foreground="#EAF0F4" Margin="0,4,0,0" />
|
||||
<ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="0">
|
||||
|
|
@ -294,6 +324,26 @@
|
|||
<ComboBoxItem Content="Debug" />
|
||||
<ComboBoxItem Content="Trace" />
|
||||
</ComboBox>
|
||||
<Grid ColumnDefinitions="*,Auto" RowDefinitions="Auto,Auto,Auto" Margin="0,8,0,0">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="Inter-launch stagger (ms)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,6" />
|
||||
<NumericUpDown Grid.Row="0" Grid.Column="1" x:Name="LaunchStaggerMsBox" Minimum="0" Maximum="5000" Increment="50" Width="120" Margin="0,0,0,6" />
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Crash-relaunch limit per window" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,6" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="1" x:Name="CrashRelaunchLimitBox" Minimum="1" Maximum="20" Increment="1" Width="120" Margin="0,0,0,6" />
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="Crash-relaunch window (minutes)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<NumericUpDown Grid.Row="2" Grid.Column="1" x:Name="CrashRelaunchWindowBox" Minimum="1" Maximum="60" Increment="1" Width="120" />
|
||||
</Grid>
|
||||
|
||||
<CheckBox x:Name="KillStuckClientsCheckBox"
|
||||
Content="Kill stuck clients (pre- and post-login)"
|
||||
ToolTip.Tip="Kills RynthCore-mode acclient.exe processes we launched that are stuck in either: (1) never reached login within the timeout (patcher hangs, char-select sit, login errors), or (2) logged out / disconnected and sat there longer than the timeout (disconnect dialog, idle char-select). Decal-mode clients are skipped (no engine = no login signal)."
|
||||
Margin="0,8,0,4" />
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Grid.Column="0" Text="Stuck-client timeout (seconds)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<NumericUpDown Grid.Column="1" x:Name="StuckClientTimeoutBox" Minimum="15" Maximum="600" Increment="15" Width="120" />
|
||||
</Grid>
|
||||
|
||||
<Button x:Name="SaveBehaviorButton"
|
||||
Content="Save Launch Behavior"
|
||||
HorizontalAlignment="Left" />
|
||||
|
|
@ -301,6 +351,18 @@
|
|||
</Border>
|
||||
</Grid>
|
||||
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Engine Settings" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="These flags are read by RynthCore.Engine on each AC client launch. They write to %APPDATA%\RynthCore\engine.json — other engine flags in that file are preserved untouched."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
<CheckBox x:Name="EnableDcompOverlayCheckBox"
|
||||
Content="Use DComp overlay (experimental, GPU-rendered)"
|
||||
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
|
|
@ -310,8 +372,10 @@
|
|||
<WrapPanel Orientation="Horizontal" ItemWidth="176" ItemHeight="40">
|
||||
<Button x:Name="InjectRunningAcButton" Content="Inject Into Running AC" Margin="0,0,8,8" />
|
||||
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
|
||||
<Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8"
|
||||
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle."
|
||||
<TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="#9AA8B3" />
|
||||
</StackPanel>
|
||||
|
|
@ -340,6 +404,10 @@
|
|||
</ScrollViewer>
|
||||
</TabItem>
|
||||
|
||||
<TabItem Header="Memory">
|
||||
<local:MemoryTabView />
|
||||
</TabItem>
|
||||
|
||||
<TabItem Header="Notes">
|
||||
<ScrollViewer>
|
||||
<StackPanel Spacing="12" Margin="6">
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
330
src/RynthCore.App.Avalonia/MemorySparkline.cs
Normal file
330
src/RynthCore.App.Avalonia/MemorySparkline.cs
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight per-frame chart for the Memory tab. Custom-drawn in
|
||||
/// <see cref="OnRender"/> — no Canvas full of Lines (too many allocations
|
||||
/// per tick when the buffer hits 17k samples).
|
||||
///
|
||||
/// Series are passed in by the host on each <see cref="InvalidateAndRedraw"/>
|
||||
/// call; this control keeps no sample storage of its own. The Y axis is
|
||||
/// normalised per-series (each series has its own min/max) so we can overlay
|
||||
/// MB, handle counts, and thread counts on the same plot without one drowning
|
||||
/// out the others. The per-series stroke pattern is what the user reads.
|
||||
///
|
||||
/// Colorblind contract: line identity is carried by <see cref="MemorySeries.Dash"/>,
|
||||
/// not by colour. The colour on each series is decorative and the legend
|
||||
/// (rendered by the host as a separate StackPanel) reproduces the same dash
|
||||
/// pattern next to the metric name so a user who can't tell the colours apart
|
||||
/// can still match line to series.
|
||||
/// </summary>
|
||||
internal sealed class MemorySparkline : Control
|
||||
{
|
||||
private List<MemorySeries> _series = new();
|
||||
private DateTime _windowStartUtc;
|
||||
private DateTime _windowEndUtc;
|
||||
private double? _hoverFractionX;
|
||||
// Drawn rectangles per series in last render — used by hover crosshair to
|
||||
// report the nearest sample value at the mouse-X position.
|
||||
private readonly List<RenderedSeries> _renderedSeries = new();
|
||||
// x86 LAA 4 GB ceiling, in MB. acclient.exe is flagged
|
||||
// IMAGE_FILE_LARGE_ADDRESS_AWARE, so on 64-bit Windows the 32-bit
|
||||
// process gets the full 4 GB user VM space, not the legacy 2 GB.
|
||||
// Drawn as a labelled guide line over the Virtual series whenever
|
||||
// Virtual is among the visible series.
|
||||
public const double X86CeilingMb = 4096.0;
|
||||
private static readonly IBrush PlotBackground = Brush.Parse("#0B1116");
|
||||
|
||||
public MemorySparkline()
|
||||
{
|
||||
// Plain Control doesn't expose a Background property — we paint our
|
||||
// backdrop manually in Render. The host card already supplies padding;
|
||||
// we paint edge-to-edge inside our own bounds.
|
||||
Focusable = false;
|
||||
ClipToBounds = true;
|
||||
}
|
||||
|
||||
public void UpdateData(IReadOnlyList<MemorySeries> series, DateTime windowStartUtc, DateTime windowEndUtc)
|
||||
{
|
||||
_series = new List<MemorySeries>(series);
|
||||
_windowStartUtc = windowStartUtc;
|
||||
_windowEndUtc = windowEndUtc;
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
protected override void OnPointerMoved(PointerEventArgs e)
|
||||
{
|
||||
base.OnPointerMoved(e);
|
||||
Point p = e.GetPosition(this);
|
||||
double w = Bounds.Width;
|
||||
_hoverFractionX = (w > 0 && p.X >= 0 && p.X <= w) ? (p.X / w) : null;
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
protected override void OnPointerExited(PointerEventArgs e)
|
||||
{
|
||||
base.OnPointerExited(e);
|
||||
_hoverFractionX = null;
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
public override void Render(DrawingContext context)
|
||||
{
|
||||
Rect bounds = new Rect(Bounds.Size);
|
||||
// Backdrop.
|
||||
context.FillRectangle(PlotBackground, bounds);
|
||||
|
||||
// Axes inset — leave a band on the left for the Y label and a band on
|
||||
// the bottom for the time axis.
|
||||
double leftPad = 6;
|
||||
double rightPad = 8;
|
||||
double topPad = 8;
|
||||
double bottomPad = 22;
|
||||
double plotW = bounds.Width - leftPad - rightPad;
|
||||
double plotH = bounds.Height - topPad - bottomPad;
|
||||
if (plotW <= 8 || plotH <= 8)
|
||||
return;
|
||||
Rect plot = new Rect(leftPad, topPad, plotW, plotH);
|
||||
|
||||
// Grid lines (3 horizontal, 3 vertical). Very faint so they don't
|
||||
// compete with the data lines.
|
||||
var gridPen = new Pen(Brush.Parse("#1E2A33"), 1);
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
double y = plot.Y + plot.Height * (i / 4.0);
|
||||
context.DrawLine(gridPen, new Point(plot.X, y), new Point(plot.Right, y));
|
||||
double x = plot.X + plot.Width * (i / 4.0);
|
||||
context.DrawLine(gridPen, new Point(x, plot.Y), new Point(x, plot.Bottom));
|
||||
}
|
||||
|
||||
// Axis frame.
|
||||
var framePen = new Pen(Brush.Parse("#33444F"), 1);
|
||||
context.DrawLine(framePen, new Point(plot.X, plot.Y), new Point(plot.X, plot.Bottom));
|
||||
context.DrawLine(framePen, new Point(plot.X, plot.Bottom), new Point(plot.Right, plot.Bottom));
|
||||
|
||||
// X-axis labels: start time + end time.
|
||||
var labelFg = Brush.Parse("#73828D");
|
||||
var typeface = new Typeface(FontFamily.Default);
|
||||
var startLabel = new FormattedText(
|
||||
FormatAxisTime(_windowStartUtc),
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
FlowDirection.LeftToRight,
|
||||
typeface, 10, labelFg);
|
||||
var endLabel = new FormattedText(
|
||||
FormatAxisTime(_windowEndUtc),
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
FlowDirection.LeftToRight,
|
||||
typeface, 10, labelFg);
|
||||
context.DrawText(startLabel, new Point(plot.X, plot.Bottom + 4));
|
||||
context.DrawText(endLabel, new Point(plot.Right - endLabel.Width, plot.Bottom + 4));
|
||||
|
||||
if (_series.Count == 0)
|
||||
{
|
||||
var empty = new FormattedText(
|
||||
"No metrics visible — toggle Show on a metric row.",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
FlowDirection.LeftToRight, typeface, 12, labelFg);
|
||||
context.DrawText(empty, new Point(
|
||||
plot.X + (plot.Width - empty.Width) / 2,
|
||||
plot.Y + (plot.Height - empty.Height) / 2));
|
||||
return;
|
||||
}
|
||||
|
||||
double windowSpanTicks = (_windowEndUtc - _windowStartUtc).Ticks;
|
||||
if (windowSpanTicks <= 0)
|
||||
return;
|
||||
|
||||
_renderedSeries.Clear();
|
||||
|
||||
// Render each visible series. Each series is normalised independently
|
||||
// (per-metric Y axis), so overlaying MB and Handles works visually.
|
||||
foreach (MemorySeries s in _series)
|
||||
{
|
||||
if (s.Points.Count < 2)
|
||||
continue;
|
||||
|
||||
// Find min/max in window so the line uses the full vertical range.
|
||||
// Including the ceiling (for Virtual) keeps the line visually
|
||||
// anchored against it instead of stretching to fill the full pane.
|
||||
double min = double.MaxValue;
|
||||
double max = double.MinValue;
|
||||
foreach (MemoryPoint pt in s.Points)
|
||||
{
|
||||
if (pt.Time < _windowStartUtc || pt.Time > _windowEndUtc)
|
||||
continue;
|
||||
if (pt.Value < min) min = pt.Value;
|
||||
if (pt.Value > max) max = pt.Value;
|
||||
}
|
||||
if (s.IncludeCeiling && X86CeilingMb > max)
|
||||
max = X86CeilingMb;
|
||||
if (min == double.MaxValue)
|
||||
continue;
|
||||
|
||||
// Pad the range so a flat series isn't on the top/bottom edge.
|
||||
double range = max - min;
|
||||
if (range < 0.0001) { range = 1.0; min -= 0.5; }
|
||||
double pad = range * 0.08;
|
||||
min -= pad;
|
||||
max += pad;
|
||||
range = max - min;
|
||||
|
||||
IDashStyle dashStyle = MakeDashStyle(s.Dash);
|
||||
// Slightly thicker stroke so dotted/dashed patterns remain visible
|
||||
// against the dark background.
|
||||
var pen = new Pen(s.Stroke, 2.0)
|
||||
{
|
||||
DashStyle = dashStyle,
|
||||
LineJoin = PenLineJoin.Round,
|
||||
LineCap = PenLineCap.Round
|
||||
};
|
||||
|
||||
// 4 GB LAA ceiling line for Virtual.
|
||||
if (s.IncludeCeiling && X86CeilingMb >= min && X86CeilingMb <= max)
|
||||
{
|
||||
double yC = plot.Bottom - ((X86CeilingMb - min) / range) * plot.Height;
|
||||
var ceilingPen = new Pen(Brush.Parse("#C75450"), 1)
|
||||
{
|
||||
DashStyle = new DashStyle(new double[] { 4.0, 3.0 }, 0)
|
||||
};
|
||||
context.DrawLine(ceilingPen, new Point(plot.X, yC), new Point(plot.Right, yC));
|
||||
var ceilLabel = new FormattedText(
|
||||
"x86 LAA 4 GB ceiling",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
FlowDirection.LeftToRight, typeface, 9,
|
||||
Brush.Parse("#C75450"));
|
||||
context.DrawText(ceilLabel, new Point(plot.Right - ceilLabel.Width - 4, yC - ceilLabel.Height - 1));
|
||||
}
|
||||
|
||||
var geom = new StreamGeometry();
|
||||
bool first = true;
|
||||
using (StreamGeometryContext ctx = geom.Open())
|
||||
{
|
||||
foreach (MemoryPoint pt in s.Points)
|
||||
{
|
||||
if (pt.Time < _windowStartUtc || pt.Time > _windowEndUtc)
|
||||
continue;
|
||||
double fx = (pt.Time - _windowStartUtc).Ticks / windowSpanTicks;
|
||||
double x = plot.X + fx * plot.Width;
|
||||
double y = plot.Bottom - ((pt.Value - min) / range) * plot.Height;
|
||||
if (first)
|
||||
{
|
||||
ctx.BeginFigure(new Point(x, y), false);
|
||||
first = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.LineTo(new Point(x, y));
|
||||
}
|
||||
}
|
||||
ctx.EndFigure(false);
|
||||
}
|
||||
context.DrawGeometry(null, pen, geom);
|
||||
|
||||
_renderedSeries.Add(new RenderedSeries(s, min, range, plot));
|
||||
}
|
||||
|
||||
// Hover crosshair + value tooltip at the mouse-X.
|
||||
if (_hoverFractionX.HasValue)
|
||||
{
|
||||
double hx = plot.X + _hoverFractionX.Value * plot.Width;
|
||||
var crosshairPen = new Pen(Brush.Parse("#26C1A6"), 1)
|
||||
{
|
||||
DashStyle = new DashStyle(new double[] { 2.0, 2.0 }, 0)
|
||||
};
|
||||
context.DrawLine(crosshairPen, new Point(hx, plot.Y), new Point(hx, plot.Bottom));
|
||||
|
||||
// Snap hover to the nearest sample in the first rendered series.
|
||||
DateTime hoverTime = _windowStartUtc + TimeSpan.FromTicks(
|
||||
(long)(_hoverFractionX.Value * windowSpanTicks));
|
||||
|
||||
// Build a "Time | series1: value | series2: value" tooltip block.
|
||||
var lines = new List<string> { hoverTime.ToLocalTime().ToString("HH:mm:ss") };
|
||||
foreach (RenderedSeries rs in _renderedSeries)
|
||||
{
|
||||
MemoryPoint? nearest = NearestPoint(rs.Series.Points, hoverTime);
|
||||
if (nearest is MemoryPoint pt)
|
||||
lines.Add($"{rs.Series.Name}: {pt.Value:F1} {rs.Series.Unit}");
|
||||
}
|
||||
|
||||
string tipText = string.Join("\n", lines);
|
||||
var tipBrush = Brush.Parse("#EAF0F4");
|
||||
var tipBg = Brush.Parse("#1A2E38");
|
||||
var tipBorder = new Pen(Brush.Parse("#26C1A6"), 1);
|
||||
var ft = new FormattedText(tipText,
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
FlowDirection.LeftToRight, typeface, 11, tipBrush);
|
||||
|
||||
double boxW = ft.Width + 10;
|
||||
double boxH = ft.Height + 8;
|
||||
double boxX = hx + 8;
|
||||
if (boxX + boxW > plot.Right) boxX = hx - 8 - boxW;
|
||||
double boxY = plot.Y + 4;
|
||||
var box = new Rect(boxX, boxY, boxW, boxH);
|
||||
context.FillRectangle(tipBg, box, 4);
|
||||
context.DrawRectangle(null, tipBorder, box, 4, 4);
|
||||
context.DrawText(ft, new Point(boxX + 5, boxY + 4));
|
||||
}
|
||||
}
|
||||
|
||||
private static MemoryPoint? NearestPoint(IReadOnlyList<MemoryPoint> pts, DateTime t)
|
||||
{
|
||||
if (pts.Count == 0)
|
||||
return null;
|
||||
// Linear scan is fine — even 17k samples is sub-ms at 60 Hz.
|
||||
long bestDiff = long.MaxValue;
|
||||
MemoryPoint best = pts[0];
|
||||
foreach (MemoryPoint p in pts)
|
||||
{
|
||||
long d = Math.Abs((p.Time - t).Ticks);
|
||||
if (d < bestDiff) { bestDiff = d; best = p; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static string FormatAxisTime(DateTime utc)
|
||||
{
|
||||
DateTime local = utc.ToLocalTime();
|
||||
return local.ToString("HH:mm:ss");
|
||||
}
|
||||
|
||||
private static IDashStyle MakeDashStyle(DashPattern p) => p switch
|
||||
{
|
||||
DashPattern.Solid => new DashStyle(),
|
||||
DashPattern.Dash => DashStyle.Dash,
|
||||
DashPattern.Dot => DashStyle.Dot,
|
||||
DashPattern.DashDot => DashStyle.DashDot,
|
||||
DashPattern.LongDash => new DashStyle(new double[] { 6.0, 2.0 }, 0),
|
||||
_ => new DashStyle()
|
||||
};
|
||||
|
||||
private readonly record struct RenderedSeries(MemorySeries Series, double Min, double Range, Rect Plot);
|
||||
}
|
||||
|
||||
/// <summary>One series fed to the sparkline. <see cref="Dash"/> carries identity
|
||||
/// for colorblind users; <see cref="Stroke"/> is decorative.</summary>
|
||||
internal sealed class MemorySeries
|
||||
{
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public string Unit { get; init; } = string.Empty;
|
||||
public IBrush Stroke { get; init; } = Brushes.White;
|
||||
public DashPattern Dash { get; init; } = DashPattern.Solid;
|
||||
public bool IncludeCeiling { get; init; }
|
||||
public IReadOnlyList<MemoryPoint> Points { get; init; } = Array.Empty<MemoryPoint>();
|
||||
}
|
||||
|
||||
internal readonly record struct MemoryPoint(DateTime Time, double Value);
|
||||
|
||||
internal enum DashPattern
|
||||
{
|
||||
Solid,
|
||||
Dash,
|
||||
Dot,
|
||||
DashDot,
|
||||
LongDash
|
||||
}
|
||||
232
src/RynthCore.App.Avalonia/MemoryTabView.axaml
Normal file
232
src/RynthCore.App.Avalonia/MemoryTabView.axaml
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:RynthCore.App.Avalonia"
|
||||
x:Class="RynthCore.App.Avalonia.MemoryTabView">
|
||||
<UserControl.Styles>
|
||||
<Style Selector="TextBlock.metricCell">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="Foreground" Value="#EAF0F4" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.metricHeader">
|
||||
<Setter Property="FontSize" Value="11.5" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="#73828D" />
|
||||
<Setter Property="Margin" Value="0,0,8,4" />
|
||||
</Style>
|
||||
<Style Selector="Button.zoom">
|
||||
<Setter Property="Padding" Value="10,4" />
|
||||
<Setter Property="FontSize" Value="11.5" />
|
||||
<Setter Property="MinWidth" Value="62" />
|
||||
</Style>
|
||||
<Style Selector="Button.zoom.active">
|
||||
<Setter Property="Background" Value="#1A2E38" />
|
||||
<Setter Property="BorderBrush" Value="#26C1A6" />
|
||||
<Setter Property="Foreground" Value="#26C1A6" />
|
||||
</Style>
|
||||
</UserControl.Styles>
|
||||
<ScrollViewer>
|
||||
<StackPanel Spacing="12" Margin="6">
|
||||
<!-- Header controls: PID picker, refresh-rate, action buttons.
|
||||
Avalonia 11.2.3 Grid doesn't expose RowSpacing/ColumnSpacing, so
|
||||
each child carries its own margin. -->
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto" ColumnDefinitions="Auto,*,Auto,Auto,Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="acclient.exe PID"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#26C1A6"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,10,8" />
|
||||
<ComboBox Grid.Row="0" Grid.Column="1"
|
||||
x:Name="PidComboBox"
|
||||
PlaceholderText="(no process)"
|
||||
HorizontalAlignment="Stretch"
|
||||
MinWidth="220"
|
||||
Margin="0,0,10,8" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="2"
|
||||
Text="Refresh"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#9AA8B3"
|
||||
Margin="0,0,6,8" />
|
||||
<ComboBox Grid.Row="0" Grid.Column="3"
|
||||
x:Name="RefreshRateComboBox"
|
||||
MinWidth="80"
|
||||
Margin="0,0,10,8" />
|
||||
<ToggleButton Grid.Row="0" Grid.Column="4"
|
||||
x:Name="PauseToggleButton"
|
||||
Content="Pause"
|
||||
Padding="12,6"
|
||||
FontSize="12"
|
||||
Margin="0,0,10,8" />
|
||||
<Button Grid.Row="0" Grid.Column="5"
|
||||
x:Name="SnapshotNowButton"
|
||||
Content="Snapshot Now"
|
||||
Padding="12,6"
|
||||
FontSize="12"
|
||||
Margin="0,0,0,8" />
|
||||
|
||||
<!-- Row 2: process info -->
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="6"
|
||||
x:Name="ProcessInfoText"
|
||||
Text="No process selected."
|
||||
Foreground="#EAF0F4"
|
||||
FontSize="12.5"
|
||||
Margin="0,0,0,8" />
|
||||
|
||||
<!-- Row 3: export + status -->
|
||||
<StackPanel Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Button x:Name="ExportCsvButton" Content="Export CSV" Padding="12,6" FontSize="12" />
|
||||
<TextBlock x:Name="StatusBannerText"
|
||||
Text="Polling stopped."
|
||||
Foreground="#9AA8B3"
|
||||
VerticalAlignment="Center"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="2" Grid.Column="4" Grid.ColumnSpan="2"
|
||||
x:Name="SampleCountText"
|
||||
Text="0 samples"
|
||||
Foreground="#9AA8B3"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Right" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Warning banners: Virtual approaching x86 LAA 4 GB ceiling. -->
|
||||
<Border x:Name="WarningBanner"
|
||||
Background="#3A1F1F"
|
||||
BorderBrush="#C75450"
|
||||
BorderThickness="1"
|
||||
CornerRadius="10"
|
||||
Padding="12"
|
||||
IsVisible="False">
|
||||
<TextBlock x:Name="WarningBannerText"
|
||||
Text=""
|
||||
Foreground="#FFC9C5"
|
||||
FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" />
|
||||
</Border>
|
||||
|
||||
<!-- Process-exit banner. -->
|
||||
<Border x:Name="ExitBanner"
|
||||
Background="#2F2A1A"
|
||||
BorderBrush="#D4A24C"
|
||||
BorderThickness="1"
|
||||
CornerRadius="10"
|
||||
Padding="12"
|
||||
IsVisible="False">
|
||||
<TextBlock x:Name="ExitBannerText"
|
||||
Text=""
|
||||
Foreground="#F0DAB0"
|
||||
FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" />
|
||||
</Border>
|
||||
|
||||
<!-- Sparkline chart + zoom controls + legend. -->
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="10">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="Memory chart"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="#26C1A6"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="4" VerticalAlignment="Center">
|
||||
<TextBlock Text="Window:"
|
||||
Foreground="#9AA8B3"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,6,0" />
|
||||
<Button x:Name="Zoom5MinButton" Classes="zoom" Content="5 min" />
|
||||
<Button x:Name="Zoom30MinButton" Classes="zoom" Content="30 min" />
|
||||
<Button x:Name="Zoom1HrButton" Classes="zoom" Content="1 hr" />
|
||||
<Button x:Name="ZoomAllButton" Classes="zoom" Content="All" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<local:MemorySparkline x:Name="Sparkline" Height="260" />
|
||||
<StackPanel x:Name="LegendPanel"
|
||||
Orientation="Horizontal"
|
||||
Spacing="14" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Metric grid: per-metric current/delta/rates/status. -->
|
||||
<Border Background="#132028" CornerRadius="16" Padding="18">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Metrics"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="#26C1A6" />
|
||||
<!-- Header row (0) is declared here; BuildMetricRows() in code-behind
|
||||
appends one Auto row per metric so children placed at Grid.Row
|
||||
1..N have a valid row to land on. Without this header row, the
|
||||
code-side adds N rows (indices 0..N-1) but the Nth metric is
|
||||
assigned Grid.Row=N → collapses onto row N-1 → overlap bug. -->
|
||||
<Grid x:Name="MetricGrid"
|
||||
RowDefinitions="Auto"
|
||||
ColumnDefinitions="120,Auto,110,140,140,160,Auto,Auto">
|
||||
<!-- Header row -->
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Classes="metricHeader" Text="Metric" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Classes="metricHeader" Text="Current" MinWidth="100" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="2" Classes="metricHeader" Text="Delta" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="3" Classes="metricHeader" Text="Rate /min (all)" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="4" Classes="metricHeader" Text="Rate /hr (all)" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="5" Classes="metricHeader" Text="Recent /min (~75s)" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="6" Classes="metricHeader" Text="Status" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="7" Classes="metricHeader" Text="Show" />
|
||||
<!-- Metric rows are added in code. -->
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Thresholds (collapsed by default). -->
|
||||
<Expander Header="Configurable thresholds (status STABLE/GROWING boundary)"
|
||||
FontSize="13"
|
||||
IsExpanded="False"
|
||||
Background="#132028"
|
||||
Foreground="#26C1A6">
|
||||
<Border Background="#132028" CornerRadius="10" Padding="14" Margin="0,8,0,0">
|
||||
<Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="Memory STABLE boundary (MB/min)"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#EAF0F4"
|
||||
Margin="0,0,12,8" />
|
||||
<NumericUpDown Grid.Row="0" Grid.Column="1"
|
||||
x:Name="MemoryThresholdBox"
|
||||
Minimum="0.0"
|
||||
Maximum="100.0"
|
||||
Increment="0.1"
|
||||
FormatString="0.00"
|
||||
Width="120"
|
||||
Margin="0,0,12,8" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="2"
|
||||
Text="Default 0.5. Below this magnitude reads STABLE."
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#73828D"
|
||||
Margin="0,0,0,8" />
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0"
|
||||
Text="Handles STABLE boundary (count/hour)"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#EAF0F4"
|
||||
Margin="0,0,12,0" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="1"
|
||||
x:Name="HandlesThresholdBox"
|
||||
Minimum="0"
|
||||
Maximum="100000"
|
||||
Increment="1"
|
||||
FormatString="0"
|
||||
Width="120"
|
||||
Margin="0,0,12,0" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="2"
|
||||
Text="Default 1. Below this rate reads STABLE."
|
||||
VerticalAlignment="Center"
|
||||
Foreground="#73828D" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Expander>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
885
src/RynthCore.App.Avalonia/MemoryTabView.axaml.cs
Normal file
885
src/RynthCore.App.Avalonia/MemoryTabView.axaml.cs
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Controls.Shapes;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Live process-monitor for acclient.exe. Mirrors the columns and trend logic
|
||||
/// from <c>scripts\Watch-AcMemory.ps1</c> and <c>scripts\Show-AcMemoryTrend.ps1</c>:
|
||||
/// all-time slope, recent slope (~75 s), STABLE/GROWING/SHRINKING status with
|
||||
/// text+arrow (mandatory — user is colorblind).
|
||||
///
|
||||
/// Lifecycle:
|
||||
/// * <see cref="_processListTimer"/> polls the OS for acclient.exe PIDs every
|
||||
/// 2 s and refreshes the PID dropdown without disturbing the user's selection.
|
||||
/// * <see cref="_sampleTimer"/> takes a sample at the user-chosen interval and
|
||||
/// pushes it to <see cref="_history"/>. Pause stops sampling but keeps the
|
||||
/// timer ticking so resume is instant.
|
||||
/// * When the watched process disappears, <see cref="HandleProcessExit"/> freezes
|
||||
/// the chart and shows the exit banner. User picks a new PID to restart.
|
||||
///
|
||||
/// History buffer: full session in memory. 24h @ 5s = 17,280 samples ~= 700 KB.
|
||||
/// The zoom window selects what gets rendered, not what's stored.
|
||||
/// </summary>
|
||||
internal sealed partial class MemoryTabView : UserControl
|
||||
{
|
||||
// ---- Metric definitions ----
|
||||
// Order here drives both the metric grid row layout and the legend.
|
||||
// Stroke palette is teal / amber / violet / pale-blue / pale-green; each
|
||||
// has a distinct DashPattern so colorblind users can still match line to
|
||||
// metric via the dash key in the legend.
|
||||
private static readonly MetricDef WsDef = new("WorkingSet", "MB", Brushes.MediumTurquoise, DashPattern.Solid, IsHandleMetric: false, IsVirtualMetric: false);
|
||||
private static readonly MetricDef PrivateDef = new("Private", "MB", Brushes.Khaki, DashPattern.Dash, IsHandleMetric: false, IsVirtualMetric: false);
|
||||
private static readonly MetricDef VirtualDef = new("Virtual", "MB", Brushes.LightCoral, DashPattern.LongDash, IsHandleMetric: false, IsVirtualMetric: true);
|
||||
private static readonly MetricDef HandlesDef = new("Handles", "", Brushes.LightSkyBlue, DashPattern.Dot, IsHandleMetric: true, IsVirtualMetric: false);
|
||||
private static readonly MetricDef ThreadsDef = new("Threads", "", Brushes.LightGreen, DashPattern.DashDot, IsHandleMetric: false, IsVirtualMetric: false);
|
||||
|
||||
private static readonly MetricDef[] AllMetrics = new[] { WsDef, PrivateDef, VirtualDef, HandlesDef, ThreadsDef };
|
||||
|
||||
// ---- State ----
|
||||
// Full history for the watched PID. Cleared when the user picks a different
|
||||
// PID (the old samples belonged to a different process).
|
||||
private readonly List<MemorySample> _history = new();
|
||||
// Refresh-rate options shown in the dropdown. Default 5 s matches the
|
||||
// PowerShell viewer.
|
||||
private static readonly int[] RefreshSecondsOptions = { 1, 2, 5, 10, 30 };
|
||||
// Recent-trend slope window: last RecentTrendSeconds of samples.
|
||||
private const int RecentTrendSeconds = 75;
|
||||
|
||||
private readonly DispatcherTimer _processListTimer = new() { Interval = TimeSpan.FromSeconds(2) };
|
||||
private readonly DispatcherTimer _sampleTimer = new() { Interval = TimeSpan.FromSeconds(5) };
|
||||
|
||||
private int? _watchedPid;
|
||||
private DateTime? _watchedStartTimeLocal;
|
||||
private bool _isPaused;
|
||||
private bool _processHasExited;
|
||||
private DateTime? _processExitedAtLocal;
|
||||
private double _memoryThresholdMbPerMin = 0.5;
|
||||
private double _handlesThresholdPerHour = 1.0;
|
||||
private ZoomWindow _zoomWindow = ZoomWindow.FiveMin;
|
||||
// Per-metric "show in chart" checkbox state.
|
||||
private readonly Dictionary<string, bool> _showInChart = new(StringComparer.Ordinal);
|
||||
// Per-metric grid row controls so we can update text in place per tick.
|
||||
private readonly Dictionary<string, MetricRowControls> _metricRows = new(StringComparer.Ordinal);
|
||||
// Internal flag set when we mutate PidComboBox.SelectedItem ourselves so
|
||||
// the SelectionChanged handler doesn't treat it as a user pick.
|
||||
private bool _suppressPidSelectionEvent;
|
||||
// Last bottom-up screen of available PIDs. Lets us reconcile the dropdown
|
||||
// without flickering it on every poll when nothing changed.
|
||||
private List<int> _lastKnownPids = new();
|
||||
// List<int> of the four zoom buttons — keeps the active-style toggling
|
||||
// logic in one place.
|
||||
private List<Button> _zoomButtons = new();
|
||||
|
||||
public MemoryTabView()
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
foreach (MetricDef m in AllMetrics)
|
||||
_showInChart[m.Name] = true; // Default: all visible.
|
||||
|
||||
BuildRefreshRateOptions();
|
||||
BuildMetricRows();
|
||||
BuildLegend();
|
||||
WireEvents();
|
||||
|
||||
// Initial state: process-list poll runs immediately, sample timer is
|
||||
// armed but does nothing until a PID is chosen.
|
||||
RefreshProcessList();
|
||||
_processListTimer.Tick += (_, _) => RefreshProcessList();
|
||||
_processListTimer.Start();
|
||||
_sampleTimer.Tick += (_, _) => OnSampleTimerTick();
|
||||
_sampleTimer.Start();
|
||||
|
||||
SetZoomActive(_zoomWindow);
|
||||
UpdateMetricGrid();
|
||||
UpdateChart();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Construction helpers
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private void BuildRefreshRateOptions()
|
||||
{
|
||||
foreach (int s in RefreshSecondsOptions)
|
||||
RefreshRateComboBox.Items.Add(new ComboBoxItem { Content = $"{s} s", Tag = s });
|
||||
// Default to 5 s (index 2). Matches the PowerShell viewer default.
|
||||
RefreshRateComboBox.SelectedIndex = 2;
|
||||
|
||||
MemoryThresholdBox.Value = (decimal)_memoryThresholdMbPerMin;
|
||||
HandlesThresholdBox.Value = (decimal)_handlesThresholdPerHour;
|
||||
}
|
||||
|
||||
private void BuildMetricRows()
|
||||
{
|
||||
// Grid header is in AXAML at row 0. Append a row per metric here so we
|
||||
// can stash references to the per-cell TextBlocks for live updates.
|
||||
// Avalonia 11.2.3 Grid lacks ColumnSpacing — we put right/bottom
|
||||
// margins on each child to make rows readable.
|
||||
var cellMargin = new global::Avalonia.Thickness(0, 0, 8, 4);
|
||||
var rightAlignMargin = new global::Avalonia.Thickness(0, 0, 0, 4);
|
||||
|
||||
for (int i = 0; i < AllMetrics.Length; i++)
|
||||
{
|
||||
MetricDef def = AllMetrics[i];
|
||||
int row = i + 1;
|
||||
|
||||
MetricGrid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
||||
|
||||
var nameCell = new TextBlock { Text = def.Name, Classes = { "metricCell" }, FontWeight = FontWeight.SemiBold, Margin = cellMargin };
|
||||
var curCell = new TextBlock { Text = "—", Classes = { "metricCell" }, Margin = cellMargin };
|
||||
var delCell = new TextBlock { Text = "—", Classes = { "metricCell" }, Margin = cellMargin };
|
||||
var amCell = new TextBlock { Text = "—", Classes = { "metricCell" }, Margin = cellMargin };
|
||||
var ahCell = new TextBlock { Text = "—", Classes = { "metricCell" }, Margin = cellMargin };
|
||||
var recCell = new TextBlock { Text = "—", Classes = { "metricCell" }, Margin = cellMargin };
|
||||
var statCell = new TextBlock { Text = "—", Classes = { "metricCell" }, FontWeight = FontWeight.SemiBold, Margin = cellMargin };
|
||||
var showBox = new CheckBox { IsChecked = _showInChart[def.Name], MinWidth = 0, Margin = rightAlignMargin };
|
||||
showBox.IsCheckedChanged += (_, _) =>
|
||||
{
|
||||
_showInChart[def.Name] = showBox.IsChecked == true;
|
||||
UpdateChart();
|
||||
};
|
||||
|
||||
SetGrid(nameCell, row, 0);
|
||||
SetGrid(curCell, row, 1);
|
||||
SetGrid(delCell, row, 2);
|
||||
SetGrid(amCell, row, 3);
|
||||
SetGrid(ahCell, row, 4);
|
||||
SetGrid(recCell, row, 5);
|
||||
SetGrid(statCell, row, 6);
|
||||
SetGrid(showBox, row, 7);
|
||||
|
||||
MetricGrid.Children.Add(nameCell);
|
||||
MetricGrid.Children.Add(curCell);
|
||||
MetricGrid.Children.Add(delCell);
|
||||
MetricGrid.Children.Add(amCell);
|
||||
MetricGrid.Children.Add(ahCell);
|
||||
MetricGrid.Children.Add(recCell);
|
||||
MetricGrid.Children.Add(statCell);
|
||||
MetricGrid.Children.Add(showBox);
|
||||
|
||||
_metricRows[def.Name] = new MetricRowControls(curCell, delCell, amCell, ahCell, recCell, statCell, showBox);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetGrid(Control c, int row, int col)
|
||||
{
|
||||
Grid.SetRow(c, row);
|
||||
Grid.SetColumn(c, col);
|
||||
}
|
||||
|
||||
private void BuildLegend()
|
||||
{
|
||||
LegendPanel.Children.Clear();
|
||||
foreach (MetricDef def in AllMetrics)
|
||||
{
|
||||
// Each legend item: a short line drawn with the metric's actual
|
||||
// dash style + the metric name. Colorblind users key off the dash
|
||||
// pattern, sighted users get the colour too.
|
||||
var sample = new Line
|
||||
{
|
||||
StartPoint = new global::Avalonia.Point(0, 5),
|
||||
EndPoint = new global::Avalonia.Point(28, 5),
|
||||
Stroke = def.Stroke,
|
||||
StrokeThickness = 2,
|
||||
Width = 28,
|
||||
Height = 10,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
sample.StrokeDashArray = MakeDashArray(def.Dash);
|
||||
|
||||
var label = new TextBlock
|
||||
{
|
||||
Text = def.Name + (string.IsNullOrEmpty(def.Unit) ? "" : $" ({def.Unit})"),
|
||||
Foreground = Brush.Parse("#EAF0F4"),
|
||||
FontSize = 11.5,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new global::Avalonia.Thickness(6, 0, 0, 0)
|
||||
};
|
||||
|
||||
var row = new StackPanel { Orientation = Orientation.Horizontal };
|
||||
row.Children.Add(sample);
|
||||
row.Children.Add(label);
|
||||
LegendPanel.Children.Add(row);
|
||||
}
|
||||
}
|
||||
|
||||
private static global::Avalonia.Collections.AvaloniaList<double> MakeDashArray(DashPattern p) => p switch
|
||||
{
|
||||
DashPattern.Solid => new global::Avalonia.Collections.AvaloniaList<double>(),
|
||||
DashPattern.Dash => new global::Avalonia.Collections.AvaloniaList<double> { 2, 2 },
|
||||
DashPattern.Dot => new global::Avalonia.Collections.AvaloniaList<double> { 0.5, 1.5 },
|
||||
DashPattern.DashDot => new global::Avalonia.Collections.AvaloniaList<double> { 2, 2, 0.5, 2 },
|
||||
DashPattern.LongDash => new global::Avalonia.Collections.AvaloniaList<double> { 4, 2 },
|
||||
_ => new global::Avalonia.Collections.AvaloniaList<double>()
|
||||
};
|
||||
|
||||
private void WireEvents()
|
||||
{
|
||||
PidComboBox.SelectionChanged += (_, _) => OnPidSelectionChanged();
|
||||
RefreshRateComboBox.SelectionChanged += (_, _) => OnRefreshRateChanged();
|
||||
PauseToggleButton.IsCheckedChanged += (_, _) => OnPauseToggleChanged();
|
||||
SnapshotNowButton.Click += (_, _) => TakeSnapshot(force: true);
|
||||
ExportCsvButton.Click += async (_, _) => await ExportCsvAsync();
|
||||
|
||||
Zoom5MinButton.Click += (_, _) => SetZoomActive(ZoomWindow.FiveMin);
|
||||
Zoom30MinButton.Click += (_, _) => SetZoomActive(ZoomWindow.ThirtyMin);
|
||||
Zoom1HrButton.Click += (_, _) => SetZoomActive(ZoomWindow.OneHour);
|
||||
ZoomAllButton.Click += (_, _) => SetZoomActive(ZoomWindow.All);
|
||||
_zoomButtons = new List<Button> { Zoom5MinButton, Zoom30MinButton, Zoom1HrButton, ZoomAllButton };
|
||||
|
||||
MemoryThresholdBox.ValueChanged += (_, _) =>
|
||||
{
|
||||
if (MemoryThresholdBox.Value is decimal d) _memoryThresholdMbPerMin = (double)d;
|
||||
UpdateMetricGrid();
|
||||
};
|
||||
HandlesThresholdBox.ValueChanged += (_, _) =>
|
||||
{
|
||||
if (HandlesThresholdBox.Value is decimal d) _handlesThresholdPerHour = (double)d;
|
||||
UpdateMetricGrid();
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Process discovery
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private void RefreshProcessList()
|
||||
{
|
||||
List<int> pids = new();
|
||||
try
|
||||
{
|
||||
foreach (Process p in Process.GetProcessesByName("acclient"))
|
||||
{
|
||||
pids.Add(p.Id);
|
||||
p.Dispose();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Process enumeration occasionally throws on transient access
|
||||
// errors — skip this tick rather than poison the dropdown.
|
||||
return;
|
||||
}
|
||||
pids.Sort();
|
||||
|
||||
// Skip the rebuild if the live PID list hasn't changed; rebuilding
|
||||
// would flash the dropdown and reset the user's selection.
|
||||
if (pids.SequenceEqual(_lastKnownPids))
|
||||
return;
|
||||
_lastKnownPids = pids;
|
||||
|
||||
// Preserve the user's current selection if that PID is still live.
|
||||
int? prior = _watchedPid;
|
||||
_suppressPidSelectionEvent = true;
|
||||
try
|
||||
{
|
||||
PidComboBox.Items.Clear();
|
||||
foreach (int pid in pids)
|
||||
{
|
||||
string label = BuildPidLabel(pid);
|
||||
PidComboBox.Items.Add(new ComboBoxItem { Content = label, Tag = pid });
|
||||
}
|
||||
|
||||
if (pids.Count == 0)
|
||||
{
|
||||
PidComboBox.SelectedIndex = -1;
|
||||
// The watched PID may have just vanished — let the sample
|
||||
// timer's "process gone" path handle the exit banner.
|
||||
}
|
||||
else if (prior.HasValue && pids.Contains(prior.Value))
|
||||
{
|
||||
for (int i = 0; i < PidComboBox.Items.Count; i++)
|
||||
{
|
||||
if (PidComboBox.Items[i] is ComboBoxItem ci && ci.Tag is int p && p == prior.Value)
|
||||
{
|
||||
PidComboBox.SelectedIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Auto-pick the first PID when nothing is watched yet.
|
||||
PidComboBox.SelectedIndex = 0;
|
||||
StartWatching((int)((ComboBoxItem)PidComboBox.Items[0]!).Tag!);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressPidSelectionEvent = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildPidLabel(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process p = Process.GetProcessById(pid);
|
||||
DateTime st = p.StartTime;
|
||||
TimeSpan up = DateTime.Now - st;
|
||||
return $"PID {pid} (started {st:HH:mm:ss}, up {FormatHms(up)})";
|
||||
}
|
||||
catch
|
||||
{
|
||||
return $"PID {pid}";
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPidSelectionChanged()
|
||||
{
|
||||
if (_suppressPidSelectionEvent)
|
||||
return;
|
||||
if (PidComboBox.SelectedItem is not ComboBoxItem ci || ci.Tag is not int pid)
|
||||
return;
|
||||
if (_watchedPid == pid && !_processHasExited)
|
||||
return; // No-op — already watching this PID.
|
||||
|
||||
StartWatching(pid);
|
||||
}
|
||||
|
||||
private void StartWatching(int pid)
|
||||
{
|
||||
_watchedPid = pid;
|
||||
_history.Clear();
|
||||
_processHasExited = false;
|
||||
_processExitedAtLocal = null;
|
||||
ExitBanner.IsVisible = false;
|
||||
WarningBanner.IsVisible = false;
|
||||
|
||||
try
|
||||
{
|
||||
using Process p = Process.GetProcessById(pid);
|
||||
_watchedStartTimeLocal = p.StartTime;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_watchedStartTimeLocal = null;
|
||||
}
|
||||
|
||||
// Take an immediate first sample so the user gets data instantly.
|
||||
TakeSnapshot(force: true);
|
||||
UpdateProcessInfoText();
|
||||
UpdateStatusBanner();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Sampling
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private void OnRefreshRateChanged()
|
||||
{
|
||||
int seconds = 5;
|
||||
if (RefreshRateComboBox.SelectedItem is ComboBoxItem ci && ci.Tag is int s)
|
||||
seconds = s;
|
||||
_sampleTimer.Interval = TimeSpan.FromSeconds(seconds);
|
||||
UpdateStatusBanner();
|
||||
}
|
||||
|
||||
private void OnPauseToggleChanged()
|
||||
{
|
||||
_isPaused = PauseToggleButton.IsChecked == true;
|
||||
PauseToggleButton.Content = _isPaused ? "Resume" : "Pause";
|
||||
UpdateStatusBanner();
|
||||
}
|
||||
|
||||
private void OnSampleTimerTick()
|
||||
{
|
||||
if (_isPaused || _watchedPid == null || _processHasExited)
|
||||
return;
|
||||
TakeSnapshot(force: false);
|
||||
}
|
||||
|
||||
/// <summary>Samples the watched PID once. <paramref name="force"/> bypasses
|
||||
/// the pause/exit gates so the Snapshot Now button always grabs one.</summary>
|
||||
private void TakeSnapshot(bool force)
|
||||
{
|
||||
if (_watchedPid == null)
|
||||
return;
|
||||
if (!force && (_isPaused || _processHasExited))
|
||||
return;
|
||||
|
||||
int pid = _watchedPid.Value;
|
||||
try
|
||||
{
|
||||
using Process p = Process.GetProcessById(pid);
|
||||
// Refresh() forces a live read; without it cached values from the
|
||||
// Process construction are reused.
|
||||
p.Refresh();
|
||||
var sample = new MemorySample
|
||||
{
|
||||
TimeUtc = DateTime.UtcNow,
|
||||
WorkingSetMb = p.WorkingSet64 / 1024.0 / 1024.0,
|
||||
PrivateMb = p.PrivateMemorySize64 / 1024.0 / 1024.0,
|
||||
VirtualMb = p.VirtualMemorySize64 / 1024.0 / 1024.0,
|
||||
Handles = p.HandleCount,
|
||||
Threads = p.Threads.Count
|
||||
};
|
||||
_history.Add(sample);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
// PID gone or no longer accessible — treat as exit.
|
||||
HandleProcessExit();
|
||||
return;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Transient enumeration failure — skip this tick.
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateProcessInfoText();
|
||||
UpdateMetricGrid();
|
||||
UpdateChart();
|
||||
UpdateWarningBanner();
|
||||
UpdateStatusBanner();
|
||||
}
|
||||
|
||||
private void HandleProcessExit()
|
||||
{
|
||||
if (_processHasExited)
|
||||
return;
|
||||
_processHasExited = true;
|
||||
_processExitedAtLocal = DateTime.Now;
|
||||
|
||||
ExitBanner.IsVisible = true;
|
||||
StringBuilder sb = new();
|
||||
sb.Append("Process PID ").Append(_watchedPid).Append(" exited at ")
|
||||
.Append(_processExitedAtLocal?.ToString("HH:mm:ss") ?? "?");
|
||||
if (_history.Count > 0)
|
||||
{
|
||||
MemorySample first = _history[0];
|
||||
MemorySample last = _history[^1];
|
||||
double minutes = (last.TimeUtc - first.TimeUtc).TotalMinutes;
|
||||
sb.AppendLine();
|
||||
sb.Append("Final summary: ").Append(_history.Count).Append(" samples over ")
|
||||
.Append(minutes.ToString("F1", CultureInfo.InvariantCulture)).Append(" min. ")
|
||||
.Append("WS ").Append(last.WorkingSetMb.ToString("F1", CultureInfo.InvariantCulture)).Append(" MB (")
|
||||
.Append(SignedNumber(last.WorkingSetMb - first.WorkingSetMb, 1)).Append("), ")
|
||||
.Append("Private ").Append(last.PrivateMb.ToString("F1", CultureInfo.InvariantCulture)).Append(" MB (")
|
||||
.Append(SignedNumber(last.PrivateMb - first.PrivateMb, 1)).Append("), ")
|
||||
.Append("Virtual ").Append(last.VirtualMb.ToString("F1", CultureInfo.InvariantCulture)).Append(" MB (")
|
||||
.Append(SignedNumber(last.VirtualMb - first.VirtualMb, 1)).Append(").");
|
||||
}
|
||||
sb.AppendLine();
|
||||
sb.Append("Pick a different PID in the dropdown to resume monitoring.");
|
||||
ExitBannerText.Text = sb.ToString();
|
||||
UpdateStatusBanner();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// UI updates
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private void UpdateProcessInfoText()
|
||||
{
|
||||
if (_watchedPid == null)
|
||||
{
|
||||
ProcessInfoText.Text = "No process selected.";
|
||||
return;
|
||||
}
|
||||
StringBuilder sb = new();
|
||||
sb.Append("PID ").Append(_watchedPid);
|
||||
if (_watchedStartTimeLocal is DateTime st)
|
||||
{
|
||||
sb.Append(" started ").Append(st.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
TimeSpan up = (_processExitedAtLocal ?? DateTime.Now) - st;
|
||||
if (up.TotalSeconds > 0)
|
||||
sb.Append(" up ").Append(FormatHms(up));
|
||||
}
|
||||
if (_processHasExited && _processExitedAtLocal is DateTime ex)
|
||||
sb.Append(" EXITED ").Append(ex.ToString("HH:mm:ss"));
|
||||
SampleCountText.Text = $"{_history.Count} samples";
|
||||
ProcessInfoText.Text = sb.ToString();
|
||||
}
|
||||
|
||||
private void UpdateStatusBanner()
|
||||
{
|
||||
if (_watchedPid == null)
|
||||
{
|
||||
StatusBannerText.Text = "No process selected.";
|
||||
return;
|
||||
}
|
||||
if (_processHasExited)
|
||||
{
|
||||
StatusBannerText.Text = "Process exited — polling stopped. Pick a new PID to resume.";
|
||||
return;
|
||||
}
|
||||
int seconds = (int)_sampleTimer.Interval.TotalSeconds;
|
||||
StatusBannerText.Text = _isPaused
|
||||
? $"Paused. Polling resumes when you click Resume. Interval {seconds} s."
|
||||
: $"Live polling every {seconds} s.";
|
||||
}
|
||||
|
||||
private void UpdateMetricGrid()
|
||||
{
|
||||
if (_history.Count == 0)
|
||||
{
|
||||
foreach (MetricDef def in AllMetrics)
|
||||
{
|
||||
MetricRowControls r = _metricRows[def.Name];
|
||||
r.Current.Text = "—";
|
||||
r.Delta.Text = "—";
|
||||
r.AllMin.Text = "—";
|
||||
r.AllHour.Text = "—";
|
||||
r.Recent.Text = "—";
|
||||
r.Status.Text = "—";
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
MemorySample first = _history[0];
|
||||
MemorySample last = _history[^1];
|
||||
|
||||
foreach (MetricDef def in AllMetrics)
|
||||
{
|
||||
MetricRowControls r = _metricRows[def.Name];
|
||||
double current = GetMetricValue(last, def);
|
||||
double startVal = GetMetricValue(first, def);
|
||||
double delta = current - startVal;
|
||||
|
||||
(double allMin, double allHour) = ComputeAllTimeRates(def);
|
||||
double recentMin = ComputeRecentRatePerMinute(def);
|
||||
|
||||
r.Current.Text = FormatCurrent(def, current);
|
||||
r.Delta.Text = SignedNumber(delta, def.IsHandleMetric || def.Name == "Threads" ? 0 : 1)
|
||||
+ (string.IsNullOrEmpty(def.Unit) ? "" : " " + def.Unit);
|
||||
r.AllMin.Text = FormatRate(def, allMin, perHour: false);
|
||||
r.AllHour.Text = FormatRate(def, allHour, perHour: true);
|
||||
r.Recent.Text = FormatRate(def, recentMin, perHour: false);
|
||||
|
||||
// Status uses the per-metric threshold. Memory metrics use the
|
||||
// MB/min boundary; handles use a per-hour boundary (converted to
|
||||
// per-min for the comparator). Threads are informational — no
|
||||
// status, ratio noise dominates.
|
||||
if (def.Name == "Threads")
|
||||
{
|
||||
r.Status.Text = "(info)";
|
||||
}
|
||||
else
|
||||
{
|
||||
double threshold = def.IsHandleMetric
|
||||
? (_handlesThresholdPerHour / 60.0)
|
||||
: _memoryThresholdMbPerMin;
|
||||
(string label, string arrow) = ClassifyTrend(recentMin, threshold);
|
||||
r.Status.Text = $"{label} {arrow}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static double GetMetricValue(MemorySample s, MetricDef def) => def.Name switch
|
||||
{
|
||||
"WorkingSet" => s.WorkingSetMb,
|
||||
"Private" => s.PrivateMb,
|
||||
"Virtual" => s.VirtualMb,
|
||||
"Handles" => s.Handles,
|
||||
"Threads" => s.Threads,
|
||||
_ => 0.0
|
||||
};
|
||||
|
||||
private (double PerMin, double PerHour) ComputeAllTimeRates(MetricDef def)
|
||||
{
|
||||
if (_history.Count < 2) return (0.0, 0.0);
|
||||
MemorySample first = _history[0];
|
||||
MemorySample last = _history[^1];
|
||||
double minutes = (last.TimeUtc - first.TimeUtc).TotalMinutes;
|
||||
if (minutes <= 0.01) return (0.0, 0.0);
|
||||
double delta = GetMetricValue(last, def) - GetMetricValue(first, def);
|
||||
double perMin = delta / minutes;
|
||||
return (perMin, perMin * 60.0);
|
||||
}
|
||||
|
||||
private double ComputeRecentRatePerMinute(MetricDef def)
|
||||
{
|
||||
if (_history.Count < 2) return 0.0;
|
||||
MemorySample last = _history[^1];
|
||||
// Find the first sample within RecentTrendSeconds of "now". Scan
|
||||
// backwards from the end so we exit early as soon as we cross the
|
||||
// boundary.
|
||||
DateTime cutoff = last.TimeUtc.AddSeconds(-RecentTrendSeconds);
|
||||
MemorySample? olderRef = null;
|
||||
for (int i = _history.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_history[i].TimeUtc <= cutoff)
|
||||
{
|
||||
olderRef = _history[i];
|
||||
break;
|
||||
}
|
||||
olderRef = _history[i];
|
||||
}
|
||||
if (olderRef is not MemorySample older || older.TimeUtc >= last.TimeUtc)
|
||||
return 0.0;
|
||||
double minutes = (last.TimeUtc - older.TimeUtc).TotalMinutes;
|
||||
if (minutes <= 0.01) return 0.0;
|
||||
double delta = GetMetricValue(last, def) - GetMetricValue(older, def);
|
||||
return delta / minutes;
|
||||
}
|
||||
|
||||
private static (string Label, string Arrow) ClassifyTrend(double rate, double thresholdPerMin)
|
||||
{
|
||||
if (Math.Abs(rate) < thresholdPerMin) return ("STABLE", "->");
|
||||
return rate > 0 ? ("GROWING", "^") : ("SHRINKING", "v");
|
||||
}
|
||||
|
||||
private void UpdateChart()
|
||||
{
|
||||
if (_history.Count == 0)
|
||||
{
|
||||
Sparkline.UpdateData(Array.Empty<MemorySeries>(), DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow);
|
||||
return;
|
||||
}
|
||||
|
||||
DateTime endUtc = _history[^1].TimeUtc;
|
||||
DateTime startUtc = _zoomWindow switch
|
||||
{
|
||||
ZoomWindow.FiveMin => endUtc.AddMinutes(-5),
|
||||
ZoomWindow.ThirtyMin => endUtc.AddMinutes(-30),
|
||||
ZoomWindow.OneHour => endUtc.AddHours(-1),
|
||||
ZoomWindow.All => _history[0].TimeUtc,
|
||||
_ => endUtc.AddMinutes(-5)
|
||||
};
|
||||
if (startUtc > _history[0].TimeUtc && _zoomWindow != ZoomWindow.All)
|
||||
{
|
||||
// Keep startUtc inside the window even if history doesn't fill it
|
||||
// yet (so the chart's X-axis labels match what we render).
|
||||
}
|
||||
// Ensure we always show at least a small span so the chart isn't
|
||||
// collapsed on first sample.
|
||||
if ((endUtc - startUtc).TotalSeconds < 5)
|
||||
startUtc = endUtc.AddSeconds(-5);
|
||||
|
||||
var seriesList = new List<MemorySeries>();
|
||||
foreach (MetricDef def in AllMetrics)
|
||||
{
|
||||
if (!_showInChart.TryGetValue(def.Name, out bool show) || !show)
|
||||
continue;
|
||||
|
||||
// Build the visible-window point list. We slice the in-memory
|
||||
// history here; the chart control just renders.
|
||||
var pts = new List<MemoryPoint>(_history.Count);
|
||||
foreach (MemorySample s in _history)
|
||||
{
|
||||
if (s.TimeUtc < startUtc || s.TimeUtc > endUtc) continue;
|
||||
pts.Add(new MemoryPoint(s.TimeUtc, GetMetricValue(s, def)));
|
||||
}
|
||||
seriesList.Add(new MemorySeries
|
||||
{
|
||||
Name = def.Name,
|
||||
Unit = def.Unit,
|
||||
Stroke = def.Stroke,
|
||||
Dash = def.Dash,
|
||||
IncludeCeiling = def.IsVirtualMetric,
|
||||
Points = pts
|
||||
});
|
||||
}
|
||||
|
||||
Sparkline.UpdateData(seriesList, startUtc, endUtc);
|
||||
}
|
||||
|
||||
private void UpdateWarningBanner()
|
||||
{
|
||||
if (_history.Count == 0)
|
||||
{
|
||||
WarningBanner.IsVisible = false;
|
||||
return;
|
||||
}
|
||||
double vm = _history[^1].VirtualMb;
|
||||
double ceiling = MemorySparkline.X86CeilingMb;
|
||||
if (vm >= ceiling * 0.93)
|
||||
{
|
||||
WarningBanner.IsVisible = true;
|
||||
WarningBannerText.FontSize = 14;
|
||||
WarningBannerText.Text = $"!! CRITICAL: Virtual memory {vm:F0} MB — within {ceiling - vm:F0} MB of the x86 LAA 4 GB ceiling. Crash imminent. Save state / disconnect now.";
|
||||
}
|
||||
else if (vm >= ceiling * 0.88)
|
||||
{
|
||||
WarningBanner.IsVisible = true;
|
||||
WarningBannerText.FontSize = 12.5;
|
||||
WarningBannerText.Text = $"WARNING: Virtual memory {vm:F0} MB — approaching the x86 LAA 4 GB ceiling ({ceiling - vm:F0} MB headroom).";
|
||||
}
|
||||
else
|
||||
{
|
||||
WarningBanner.IsVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetZoomActive(ZoomWindow w)
|
||||
{
|
||||
_zoomWindow = w;
|
||||
// Refresh button visuals: only the active one wears the .active class.
|
||||
Button? active = w switch
|
||||
{
|
||||
ZoomWindow.FiveMin => Zoom5MinButton,
|
||||
ZoomWindow.ThirtyMin => Zoom30MinButton,
|
||||
ZoomWindow.OneHour => Zoom1HrButton,
|
||||
ZoomWindow.All => ZoomAllButton,
|
||||
_ => Zoom5MinButton
|
||||
};
|
||||
foreach (Button b in _zoomButtons)
|
||||
{
|
||||
if (b == active)
|
||||
{
|
||||
if (!b.Classes.Contains("active")) b.Classes.Add("active");
|
||||
}
|
||||
else
|
||||
{
|
||||
b.Classes.Remove("active");
|
||||
}
|
||||
}
|
||||
UpdateChart();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// CSV export
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private async Task ExportCsvAsync()
|
||||
{
|
||||
if (_history.Count == 0)
|
||||
return;
|
||||
|
||||
IStorageProvider? sp = TopLevel.GetTopLevel(this)?.StorageProvider;
|
||||
if (sp == null)
|
||||
return;
|
||||
|
||||
string defaultName = $"acclient-memory-pid{_watchedPid?.ToString(CultureInfo.InvariantCulture) ?? "unknown"}-{DateTime.Now:yyyyMMdd-HHmmss}.csv";
|
||||
|
||||
var opts = new FilePickerSaveOptions
|
||||
{
|
||||
Title = "Export memory history",
|
||||
SuggestedFileName = defaultName,
|
||||
DefaultExtension = "csv",
|
||||
FileTypeChoices = new[]
|
||||
{
|
||||
new FilePickerFileType("CSV") { Patterns = new[] { "*.csv" } }
|
||||
}
|
||||
};
|
||||
|
||||
IStorageFile? file = await sp.SaveFilePickerAsync(opts);
|
||||
if (file == null)
|
||||
return;
|
||||
|
||||
// Column header matches Watch-AcMemory.ps1 exactly so existing parsers
|
||||
// (Excel sheets, scripts) keep working.
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("Timestamp,PID,UptimeMinutes,WorkingSetMB,PrivateMB,VirtualMB,HandleCount,ThreadCount");
|
||||
|
||||
DateTime startUtc = _watchedStartTimeLocal?.ToUniversalTime() ?? _history[0].TimeUtc;
|
||||
int pid = _watchedPid ?? 0;
|
||||
|
||||
foreach (MemorySample s in _history)
|
||||
{
|
||||
double uptimeMin = Math.Round((s.TimeUtc - startUtc).TotalMinutes, 2);
|
||||
sb.Append(s.TimeUtc.ToLocalTime().ToString("s", CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(pid).Append(',')
|
||||
.Append(uptimeMin.ToString(CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(((int)s.WorkingSetMb).ToString(CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(((int)s.PrivateMb).ToString(CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(((int)s.VirtualMb).ToString(CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(s.Handles).Append(',')
|
||||
.Append(s.Threads)
|
||||
.AppendLine();
|
||||
}
|
||||
|
||||
await using Stream stream = await file.OpenWriteAsync();
|
||||
await using var writer = new StreamWriter(stream, Encoding.UTF8);
|
||||
await writer.WriteAsync(sb.ToString());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Formatting helpers
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private static string FormatCurrent(MetricDef def, double value)
|
||||
{
|
||||
if (def.IsHandleMetric || def.Name == "Threads")
|
||||
return ((int)value).ToString(CultureInfo.InvariantCulture);
|
||||
return value.ToString("F1", CultureInfo.InvariantCulture) + " " + def.Unit;
|
||||
}
|
||||
|
||||
private static string FormatRate(MetricDef def, double rate, bool perHour)
|
||||
{
|
||||
string unit;
|
||||
if (def.IsHandleMetric || def.Name == "Threads")
|
||||
unit = perHour ? "/hr" : "/min";
|
||||
else
|
||||
unit = perHour ? " " + def.Unit + "/hr" : " " + def.Unit + "/min";
|
||||
|
||||
int decimals = (def.IsHandleMetric || def.Name == "Threads")
|
||||
? (perHour ? 0 : 1)
|
||||
: 2;
|
||||
return SignedNumber(rate, decimals) + unit;
|
||||
}
|
||||
|
||||
/// <summary>Always emits an explicit sign (+/-/space) so STABLE/GROWING
|
||||
/// readout is visually obvious even without colour cues.</summary>
|
||||
private static string SignedNumber(double v, int decimals)
|
||||
{
|
||||
string mag = Math.Abs(v).ToString("F" + decimals, CultureInfo.InvariantCulture);
|
||||
if (v > 0) return "+" + mag;
|
||||
if (v < 0) return "-" + mag;
|
||||
return " " + mag;
|
||||
}
|
||||
|
||||
private static string FormatHms(TimeSpan ts)
|
||||
=> $"{(int)ts.TotalHours:D2}:{ts.Minutes:D2}:{ts.Seconds:D2}";
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Types
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private struct MemorySample
|
||||
{
|
||||
public DateTime TimeUtc;
|
||||
public double WorkingSetMb;
|
||||
public double PrivateMb;
|
||||
public double VirtualMb;
|
||||
public int Handles;
|
||||
public int Threads;
|
||||
}
|
||||
|
||||
/// <summary>Per-metric definition: name, unit, stroke, dash pattern, and a
|
||||
/// couple of role bits used for status thresholds + ceiling overlay.
|
||||
/// IsHandleMetric flips the status threshold to use the handles-per-hour
|
||||
/// boundary; IsVirtualMetric flips on the x86 LAA 4 GB ceiling overlay.</summary>
|
||||
private sealed record MetricDef(
|
||||
string Name,
|
||||
string Unit,
|
||||
IBrush Stroke,
|
||||
DashPattern Dash,
|
||||
bool IsHandleMetric,
|
||||
bool IsVirtualMetric);
|
||||
|
||||
private sealed record MetricRowControls(
|
||||
TextBlock Current,
|
||||
TextBlock Delta,
|
||||
TextBlock AllMin,
|
||||
TextBlock AllHour,
|
||||
TextBlock Recent,
|
||||
TextBlock Status,
|
||||
CheckBox Show);
|
||||
|
||||
private enum ZoomWindow
|
||||
{
|
||||
FiveMin,
|
||||
ThirtyMin,
|
||||
OneHour,
|
||||
All
|
||||
}
|
||||
}
|
||||
|
|
@ -43,12 +43,15 @@
|
|||
<ItemGroup>
|
||||
<Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" />
|
||||
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
|
||||
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
|
||||
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
|
||||
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\LaunchContextStore.cs" Link="Shared\LaunchContextStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
|
||||
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
|
||||
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
|
||||
|
|
@ -56,4 +59,9 @@
|
|||
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
|
||||
<Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
341
src/RynthCore.App.Avalonia/RynthUpdater.cs
Normal file
341
src/RynthCore.App.Avalonia/RynthUpdater.cs
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Signed updates for RynthCore and the RynthSuite plugins.
|
||||
///
|
||||
/// The feed is a signed envelope — {"payload": base64(manifest JSON), "signatures": [{"key": id,
|
||||
/// "sig": base64}]}, ECDSA P-256 / SHA-256 over the payload bytes (IEEE P1363). Nothing in it is
|
||||
/// used until a signature from one of <see cref="UpdateTrust.PublicKeys"/> verifies. The signing
|
||||
/// key lives on the publisher's PC, never on the server, so a compromised aelrynth.com cannot push
|
||||
/// code to players. Every download is then checked against the signed size and SHA-256.
|
||||
///
|
||||
/// Plugins update in place. The engine runs plugins from shadow copies, so swapping the DLL never
|
||||
/// touches a running bot: the new version loads the next time AC starts, or on RL if the player
|
||||
/// chooses — the updater never reloads anything. The core (engine, Loader, launcher) updates by
|
||||
/// running the release's installer, and only while no RynthCore client is running.
|
||||
/// </summary>
|
||||
internal sealed class RynthUpdater
|
||||
{
|
||||
public const string DefaultFeedUrl = "https://aelrynth.com/downloads/rynth/update.json";
|
||||
|
||||
private const long MaxFeedBytes = 256 * 1024;
|
||||
private const long MaxPluginBytes = 64L << 20;
|
||||
private const long MaxInstallerBytes = 256L << 20;
|
||||
|
||||
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256);
|
||||
public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256);
|
||||
public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes,
|
||||
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins);
|
||||
|
||||
/// <summary>One installed copy of a plugin the feed knows.</summary>
|
||||
public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State);
|
||||
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild }
|
||||
|
||||
public sealed record CheckResult(Manifest Manifest, int InstalledCoreRelease, IReadOnlyList<PluginStatus> Plugins)
|
||||
{
|
||||
public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease;
|
||||
public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
|
||||
}
|
||||
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private readonly string _feedUrl;
|
||||
private readonly string _allowedPrefix;
|
||||
private readonly IReadOnlyList<string> _trustedKeys;
|
||||
private readonly string _stateDir;
|
||||
private readonly string _appDir;
|
||||
|
||||
public RynthUpdater(string feedUrl = DefaultFeedUrl, IReadOnlyList<string>? trustedKeys = null,
|
||||
string? stateDir = null, string? appDir = null)
|
||||
{
|
||||
_feedUrl = feedUrl;
|
||||
// Downloads must come from the feed's own folder — the signature already covers the URLs,
|
||||
// this just refuses to follow a signed manifest anywhere else.
|
||||
_allowedPrefix = feedUrl[..(feedUrl.LastIndexOf('/') + 1)];
|
||||
_trustedKeys = trustedKeys ?? UpdateTrust.PublicKeys;
|
||||
_stateDir = stateDir ?? Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
|
||||
_appDir = appDir ?? AppContext.BaseDirectory;
|
||||
}
|
||||
|
||||
/// <summary>False until the signing keys exist: with no trusted key nothing can verify.</summary>
|
||||
public bool IsConfigured => _trustedKeys.Count > 0;
|
||||
|
||||
/// <summary>The core release this install came from (release.txt, written by the installer); 0 when unknown.</summary>
|
||||
public int InstalledCoreRelease
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(_appDir, "release.txt");
|
||||
if (!File.Exists(path)) return 0;
|
||||
string first = File.ReadLines(path).FirstOrDefault() ?? "";
|
||||
return int.TryParse(first.Trim(), out int r) ? r : 0;
|
||||
}
|
||||
catch { return 0; }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Check ─────────────────────────────────────────────────────────────────
|
||||
|
||||
public async Task<CheckResult> CheckAsync(IEnumerable<string> pluginPaths, CancellationToken ct = default)
|
||||
{
|
||||
if (!IsConfigured)
|
||||
throw new InvalidOperationException("updates are not set up in this build (no signing key)");
|
||||
|
||||
byte[] envelope = await DownloadBytesAsync(_feedUrl, MaxFeedBytes, ct);
|
||||
byte[] payload = VerifyEnvelope(envelope, _trustedKeys);
|
||||
Manifest manifest = ParseManifest(payload);
|
||||
|
||||
// Replay guard: a signed but older feed (an attacker re-serving last month's) is refused.
|
||||
int floor = Math.Max(ReadHighestRelease(), InstalledCoreRelease);
|
||||
if (manifest.Release < floor)
|
||||
throw new InvalidDataException($"the feed is older ({manifest.Release}) than one already seen ({floor})");
|
||||
if (manifest.Release > ReadHighestRelease())
|
||||
WriteHighestRelease(manifest.Release);
|
||||
|
||||
var statuses = new List<PluginStatus>();
|
||||
var byFile = manifest.Plugins.ToDictionary(p => p.File, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string path in pluginPaths.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!byFile.TryGetValue(Path.GetFileName(path), out PluginEntry? entry) || !File.Exists(path))
|
||||
continue; // not a plugin this feed ships (a private or third-party one): never touched
|
||||
|
||||
PluginState state;
|
||||
if (string.Equals(Sha256File(path), entry.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
state = PluginState.UpToDate;
|
||||
else if (File.GetLastWriteTimeUtc(path) > manifest.PublishedUtc.AddMinutes(1))
|
||||
state = PluginState.LocalBuild; // newer than the release: someone's own build, leave it
|
||||
else
|
||||
state = PluginState.NeedsUpdate;
|
||||
statuses.Add(new PluginStatus(entry, path, state));
|
||||
}
|
||||
|
||||
return new CheckResult(manifest, InstalledCoreRelease, statuses);
|
||||
}
|
||||
|
||||
// ── Plugins ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Swaps each outdated plugin DLL for the verified release build. The previous file is kept
|
||||
/// beside it as .previous. Running clients keep the version they started with.
|
||||
/// </summary>
|
||||
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, CancellationToken ct = default)
|
||||
{
|
||||
var done = new List<string>();
|
||||
foreach (var group in check.PluginsToUpdate.GroupBy(p => p.Entry))
|
||||
{
|
||||
PluginEntry e = group.Key;
|
||||
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
|
||||
try
|
||||
{
|
||||
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct);
|
||||
foreach (PluginStatus p in group)
|
||||
{
|
||||
string staged = p.Path + ".new";
|
||||
File.Copy(temp, staged, overwrite: true);
|
||||
// Stamp the release time so a later check never mistakes it for a local build.
|
||||
File.SetLastWriteTimeUtc(staged, check.Manifest.PublishedUtc);
|
||||
File.Copy(p.Path, p.Path + ".previous", overwrite: true);
|
||||
File.Move(staged, p.Path, overwrite: true);
|
||||
done.Add($"{e.Name} → {check.Manifest.Version}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(temp); } catch { }
|
||||
}
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
// ── Core ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
|
||||
public async Task<string> DownloadInstallerAsync(CheckResult check, CancellationToken ct = default)
|
||||
{
|
||||
InstallerEntry core = check.Manifest.Core;
|
||||
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"RynthCore", "updates", core.Release.ToString());
|
||||
Directory.CreateDirectory(dir);
|
||||
string path = Path.Combine(dir, "RynthCore-Setup.exe");
|
||||
if (File.Exists(path) && new FileInfo(path).Length == core.Size &&
|
||||
string.Equals(Sha256File(path), core.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
return path;
|
||||
|
||||
string temp = path + ".part";
|
||||
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct);
|
||||
File.Move(temp, path, overwrite: true);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>Runs the installer silently; it closes the launcher, upgrades in place and relaunches it.</summary>
|
||||
public static void RunInstaller(string installerPath)
|
||||
{
|
||||
// DownloadInstallerAsync verified it moments ago, into a per-user folder.
|
||||
Process.Start(new ProcessStartInfo(installerPath,
|
||||
"/SILENT /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS /RELAUNCH") { UseShellExecute = true });
|
||||
}
|
||||
|
||||
// ── Envelope + manifest ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Returns the payload bytes if any trusted key signed them; throws otherwise.</summary>
|
||||
public static byte[] VerifyEnvelope(byte[] envelope, IReadOnlyList<string> trustedKeys)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(envelope);
|
||||
byte[] payload = Convert.FromBase64String(doc.RootElement.GetProperty("payload").GetString() ?? "");
|
||||
var sigs = doc.RootElement.GetProperty("signatures");
|
||||
|
||||
foreach (string key in trustedKeys)
|
||||
{
|
||||
byte[] spki = Convert.FromBase64String(key);
|
||||
string id = KeyId(spki);
|
||||
using var ec = ECDsa.Create();
|
||||
ec.ImportSubjectPublicKeyInfo(spki, out _);
|
||||
foreach (JsonElement s in sigs.EnumerateArray())
|
||||
{
|
||||
if (!string.Equals(s.GetProperty("key").GetString(), id, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
byte[] sig = Convert.FromBase64String(s.GetProperty("sig").GetString() ?? "");
|
||||
if (ec.VerifyData(payload, sig, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation))
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
throw new InvalidDataException("the update feed's signature is not valid");
|
||||
}
|
||||
|
||||
/// <summary>First 8 bytes of SHA-256 over the public key (SubjectPublicKeyInfo), as hex.</summary>
|
||||
public static string KeyId(byte[] spki) => Convert.ToHexString(SHA256.HashData(spki).AsSpan(0, 8)).ToLowerInvariant();
|
||||
|
||||
private Manifest ParseManifest(byte[] payload)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.GetProperty("schema").GetInt32() != 1)
|
||||
throw new InvalidDataException("unknown update feed format — update RynthCore by hand");
|
||||
|
||||
JsonElement c = r.GetProperty("core");
|
||||
var core = new InstallerEntry(c.GetProperty("release").GetInt32(), c.GetProperty("version").GetString() ?? "",
|
||||
CheckUrl(c.GetProperty("url").GetString()), c.GetProperty("size").GetInt64(), c.GetProperty("sha256").GetString() ?? "");
|
||||
|
||||
var plugins = new List<PluginEntry>();
|
||||
foreach (JsonElement p in r.GetProperty("plugins").EnumerateArray())
|
||||
{
|
||||
string file = p.GetProperty("file").GetString() ?? "";
|
||||
if (file.Length == 0 || file != Path.GetFileName(file) || !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidDataException($"bad plugin file name '{file}'");
|
||||
plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file,
|
||||
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? ""));
|
||||
}
|
||||
|
||||
return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "",
|
||||
r.GetProperty("published").GetDateTime().ToUniversalTime(),
|
||||
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins);
|
||||
}
|
||||
|
||||
private string CheckUrl(string? url)
|
||||
{
|
||||
if (url == null || !url.StartsWith(_allowedPrefix, StringComparison.Ordinal) || url.Contains(".."))
|
||||
throw new InvalidDataException($"download outside the update folder: '{url}'");
|
||||
return url;
|
||||
}
|
||||
|
||||
// ── Downloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static async Task<byte[]> DownloadBytesAsync(string url, long max, CancellationToken ct)
|
||||
{
|
||||
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
await using var s = await resp.Content.ReadAsStreamAsync(ct);
|
||||
using var ms = new MemoryStream();
|
||||
byte[] buf = new byte[16384];
|
||||
int n;
|
||||
while ((n = await s.ReadAsync(buf, ct)) > 0)
|
||||
{
|
||||
if (ms.Length + n > max) throw new InvalidDataException($"{url} is larger than expected");
|
||||
ms.Write(buf, 0, n);
|
||||
}
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct)
|
||||
{
|
||||
if (size <= 0 || size > max) throw new InvalidDataException($"{url}: size {size} out of range");
|
||||
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
long total = 0;
|
||||
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
|
||||
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
byte[] buf = new byte[81920];
|
||||
int n;
|
||||
while ((n = await s.ReadAsync(buf, ct)) > 0)
|
||||
{
|
||||
total += n;
|
||||
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
|
||||
hash.AppendData(buf, 0, n);
|
||||
await f.WriteAsync(buf.AsMemory(0, n), ct);
|
||||
}
|
||||
}
|
||||
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
|
||||
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try { File.Delete(dest); } catch { }
|
||||
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
|
||||
}
|
||||
}
|
||||
|
||||
public static string Sha256File(string path)
|
||||
{
|
||||
using var f = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(f)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var http = new HttpClient { Timeout = TimeSpan.FromMinutes(15) };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher");
|
||||
return http;
|
||||
}
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private string StatePath => Path.Combine(_stateDir, "update-state.json");
|
||||
|
||||
private int ReadHighestRelease()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(StatePath)) return 0;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
|
||||
return doc.RootElement.TryGetProperty("highestRelease", out JsonElement v) ? v.GetInt32() : 0;
|
||||
}
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
private void WriteHighestRelease(int release)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_stateDir);
|
||||
string tmp = StatePath + ".tmp";
|
||||
File.WriteAllText(tmp, $"{{\"highestRelease\": {release}}}", Encoding.UTF8);
|
||||
File.Move(tmp, StatePath, overwrite: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
19
src/RynthCore.App.Avalonia/UpdateTrust.cs
Normal file
19
src/RynthCore.App.Avalonia/UpdateTrust.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>
|
||||
/// Public halves of the update-signing keys: the primary one that signs releases and the
|
||||
/// offline backup that replaces it if it is ever lost. SubjectPublicKeyInfo, base64.
|
||||
///
|
||||
/// Written by installer\New-UpdateSigningKey.ps1 — run it, then rebuild. Empty means updates
|
||||
/// are switched off: with no trusted key no feed can verify, so nothing is ever installed.
|
||||
/// </summary>
|
||||
internal static class UpdateTrust
|
||||
{
|
||||
public static readonly string[] PublicKeys =
|
||||
{
|
||||
// BEGIN KEYS (New-UpdateSigningKey.ps1)
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYVKNob7tzli73BPSjVgJjWWYUCoJjA6wwHUy6c+mMfy32V3I5cuheI+jMSMFk54ywcRgNBypfUqibrtKFcG7qQ==", // primary f0bc55ee71c184dd
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESJ7xQmQgVy90BJE93YSGOpZN11nB9jSbBAVbji8weZbhKlI/5aKnJfTMAWHHsl08HmCAPLXU4nfriuODegc8vw==", // backup 2c2ed4a9042ac855
|
||||
// END KEYS
|
||||
};
|
||||
}
|
||||
|
|
@ -23,6 +23,45 @@ internal sealed class AcClientLaunchSettingsService
|
|||
UpdateIntroVideoState(gameDirectory, skipIntroVideos, log);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a per-account UserPreferences.ini stash over the live file in
|
||||
/// My Documents\Asheron's Call, then re-applies the ComputeUniquePort flag.
|
||||
/// If <paramref name="stashPath"/> is empty or missing, no swap is performed
|
||||
/// and the live file is left as-is.
|
||||
/// </summary>
|
||||
public bool SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(stashPath))
|
||||
return false;
|
||||
|
||||
if (!File.Exists(stashPath))
|
||||
{
|
||||
log?.Invoke($"User prefs swap skipped: stash file not found at {stashPath}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
|
||||
string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call");
|
||||
string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName);
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(prefsDirectory);
|
||||
File.Copy(stashPath, prefsPath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log?.Invoke($"User prefs swap failed copying {stashPath}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Re-apply the ComputeUniquePort flag — the stash may have it set to
|
||||
// the wrong value (e.g. user set it up before enabling multi-client).
|
||||
UpdateUserPreferences(allowMultipleClients, log: null);
|
||||
log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log)
|
||||
{
|
||||
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
|
||||
|
|
|
|||
|
|
@ -19,8 +19,52 @@ internal sealed class AppSettings
|
|||
public bool WatchForAcStart { get; set; } = true;
|
||||
public bool InjectAllRunningClients { get; set; } = true;
|
||||
public string LoggingLevel { get; set; } = "Info";
|
||||
public int LaunchStaggerMs { get; set; } = 250;
|
||||
public int CrashRelaunchLimitInWindow { get; set; } = 3;
|
||||
public int CrashRelaunchWindowMinutes { get; set; } = 5;
|
||||
public bool OverrideWindowTitle { get; set; } = true;
|
||||
|
||||
/// When true (default), the launcher installs RynthSuite plugin updates as soon as a
|
||||
/// check finds them. Safe mid-session: running clients keep the version they started
|
||||
/// with; the new one loads on the next AC start. Core updates always ask first.
|
||||
public bool AutoUpdatePlugins { get; set; } = true;
|
||||
|
||||
/// When true, the launcher kills any RynthCore-mode acclient.exe it
|
||||
/// launched that hasn't reached IsLoggedIn within
|
||||
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,
|
||||
/// patcher hangs, and "you have been disconnected" failure screens at
|
||||
/// the front of the launch flow. Off by default — destructive.
|
||||
/// Decal-mode clients are skipped (no engine = no IsLoggedIn signal).
|
||||
public bool KillStuckClients { get; set; }
|
||||
public int StuckClientTimeoutSeconds { get; set; } = 60;
|
||||
|
||||
/// When true (default), the launcher kills+relaunches a RynthCore-mode
|
||||
/// client whose per-PID heartbeat shows the WEDGE signature: login=1 and
|
||||
/// fps=0 sustained for <see cref="WedgeRestartSeconds"/> while the engine
|
||||
/// heartbeat keeps flowing (AC main thread dead, process alive — the AV
|
||||
/// class). Containment for the residual corruption AVs: an overnight soak
|
||||
/// loses ~2 minutes to a wedge instead of the rest of the night.
|
||||
/// Minimized windows are exempt (some drivers stop presenting). Relaunch
|
||||
/// rides the existing crash-relaunch machinery (counts toward the
|
||||
/// circuit breaker) and needs AutoLaunch for the relaunch half.
|
||||
public bool AutoRestartWedgedClients { get; set; } = true;
|
||||
public int WedgeRestartSeconds { get; set; } = 90;
|
||||
public List<string> EnabledPluginIds { get; set; } = [];
|
||||
public List<string> PluginDllPaths { get; set; } = [];
|
||||
|
||||
/// User-added plugin DLL paths whose checkboxes are currently unchecked.
|
||||
/// The path stays in <see cref="PluginDllPaths"/> (so the row remains in
|
||||
/// the UI), but is filtered out when syncing PluginPaths into engine.json.
|
||||
/// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase.
|
||||
public List<string> DisabledPluginDllPaths { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Last installer plugin hand-off (registry <c>Software\Rynth\PendingPluginRegistration</c>)
|
||||
/// the launcher applied. Lets an all-users install, whose HKLM value the launcher cannot
|
||||
/// delete, register its plugins once without re-adding a plugin the user later removed.
|
||||
/// </summary>
|
||||
public string? AppliedInstallerPluginRegistration { get; set; }
|
||||
|
||||
public List<LaunchServerProfile> ServerProfiles { get; set; } = [];
|
||||
public List<LaunchAccountProfile> AccountProfiles { get; set; } = [];
|
||||
|
||||
|
|
|
|||
|
|
@ -20,16 +20,52 @@ internal static class AppSettingsStore
|
|||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
|
||||
|
||||
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
|
||||
private static string BackupPath => SettingsPath + ".bak";
|
||||
|
||||
/// <summary>
|
||||
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
|
||||
/// possibly recovered from the .bak). Null when the load was clean. The
|
||||
/// launcher surfaces this after startup — this store is shared source and
|
||||
/// must not depend on launcher-only logging.
|
||||
/// </summary>
|
||||
public static string? LastLoadDiagnostic { get; private set; }
|
||||
|
||||
public static AppSettings Load()
|
||||
{
|
||||
LastLoadDiagnostic = null;
|
||||
|
||||
if (!File.Exists(SettingsPath))
|
||||
return new AppSettings();
|
||||
|
||||
if (TryLoadFrom(SettingsPath, out AppSettings? settings))
|
||||
return settings!;
|
||||
|
||||
// The primary file is corrupt (truncated write, disk issue). This file
|
||||
// holds every server/account profile — NEVER silently reset to defaults.
|
||||
// Quarantine the bad file for post-mortem, then try the backup the
|
||||
// atomic Save() keeps.
|
||||
string quarantine = SettingsPath + ".corrupt-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
|
||||
try { File.Move(SettingsPath, quarantine); }
|
||||
catch { quarantine = "(quarantine move failed)"; }
|
||||
|
||||
if (File.Exists(BackupPath) && TryLoadFrom(BackupPath, out AppSettings? backup))
|
||||
{
|
||||
try { File.Copy(BackupPath, SettingsPath, overwrite: true); } catch { }
|
||||
LastLoadDiagnostic = $"appsettings.json was corrupt — recovered from .bak (bad file kept at {quarantine}).";
|
||||
return backup!;
|
||||
}
|
||||
|
||||
LastLoadDiagnostic = $"appsettings.json was corrupt and no usable .bak exists — starting with defaults (bad file kept at {quarantine}).";
|
||||
return new AppSettings();
|
||||
}
|
||||
|
||||
private static bool TryLoadFrom(string path, out AppSettings? settings)
|
||||
{
|
||||
settings = null;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(SettingsPath))
|
||||
return new AppSettings();
|
||||
|
||||
string json = File.ReadAllText(SettingsPath);
|
||||
AppSettings settings = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
|
||||
string json = File.ReadAllText(path);
|
||||
AppSettings loaded = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
|
||||
|
||||
using JsonDocument document = JsonDocument.Parse(json);
|
||||
JsonElement root = document.RootElement;
|
||||
|
|
@ -37,20 +73,30 @@ internal static class AppSettingsStore
|
|||
root.TryGetProperty("AutoRelaunch", out JsonElement legacyAutoRelaunch) &&
|
||||
legacyAutoRelaunch.ValueKind is JsonValueKind.True or JsonValueKind.False)
|
||||
{
|
||||
settings.AutoLaunch = legacyAutoRelaunch.GetBoolean();
|
||||
loaded.AutoLaunch = legacyAutoRelaunch.GetBoolean();
|
||||
}
|
||||
|
||||
return settings;
|
||||
settings = loaded;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new AppSettings();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Save(AppSettings settings)
|
||||
{
|
||||
// Atomic write: serialize to a temp file, then swap it in. A crash or
|
||||
// power cut mid-write can no longer truncate the live file (which holds
|
||||
// every server/account profile and is rewritten constantly); the swap
|
||||
// also maintains a .bak Load() can recover from.
|
||||
Directory.CreateDirectory(SettingsDirectory);
|
||||
File.WriteAllText(SettingsPath, JsonSerializer.Serialize(settings, JsonOptions));
|
||||
string tmp = SettingsPath + ".tmp";
|
||||
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
|
||||
if (File.Exists(SettingsPath))
|
||||
File.Replace(tmp, SettingsPath, BackupPath);
|
||||
else
|
||||
File.Move(tmp, SettingsPath);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
46
src/RynthCore.App/BuildVersion.cs
Normal file
46
src/RynthCore.App/BuildVersion.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
/// <summary>
|
||||
/// Human-readable build versions, for the launcher and the in-game UI.
|
||||
///
|
||||
/// Release builds are stamped with the release number (Build-Installer.ps1 and
|
||||
/// Publish-Update.ps1 pass -p:Version=yyyy.m.d.n), and the .NET SDK appends the git
|
||||
/// commit to the product version: "2026.9.26.3+8ca322f…". Anything built without a
|
||||
/// version (Deploy-RynthCore.ps1, an IDE build) reads "1.0.0+8ca322f…" — a dev build.
|
||||
/// NativeAOT DLLs carry the same Windows version resource, so plugins need no code.
|
||||
/// </summary>
|
||||
internal static class BuildVersion
|
||||
{
|
||||
/// <summary>"2026.9.26.3 (8ca322f)" for a release, "dev (8ca322f)" otherwise.</summary>
|
||||
public static string Format(string? productVersion)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(productVersion)) return "unknown";
|
||||
string version = productVersion.Trim();
|
||||
string commit = "";
|
||||
int plus = version.IndexOf('+');
|
||||
if (plus >= 0)
|
||||
{
|
||||
commit = version[(plus + 1)..];
|
||||
version = version[..plus];
|
||||
}
|
||||
if (commit.Length > 7) commit = commit[..7];
|
||||
if (version is "1.0.0" or "1.0.0.0") version = "dev";
|
||||
return commit.Length > 0 ? $"{version} ({commit})" : version;
|
||||
}
|
||||
|
||||
/// <summary>A DLL's or EXE's version resource, formatted; "" if it has none or can't be read.</summary>
|
||||
public static string OfFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(path) ? Format(FileVersionInfo.GetVersionInfo(path).ProductVersion) : "";
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,28 @@ namespace RynthCore.App;
|
|||
|
||||
internal static class CharacterCacheStore
|
||||
{
|
||||
/// Strict reader — only returns characters from the server-scoped file
|
||||
/// for this (account, server) pair. Will NOT fall through to the
|
||||
/// account-only file. Use this when correctness across accounts/servers
|
||||
/// matters more than tolerance for missing data (e.g. UI dropdowns where
|
||||
/// stale legacy files would leak the wrong account's characters).
|
||||
public static List<string> ReadStrict(string accountName, string serverName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(serverName))
|
||||
return [];
|
||||
|
||||
string safeAccount = SanitizeFileName(accountName);
|
||||
string safeServer = SanitizeFileName(serverName);
|
||||
return ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public static List<string> Read(string accountName, string serverName = "")
|
||||
{
|
||||
try
|
||||
|
|
@ -63,12 +85,17 @@ internal static class CharacterCacheStore
|
|||
return;
|
||||
|
||||
List<string> characters = Read(accountName, serverName);
|
||||
if (!characters.Contains(characterName, StringComparer.OrdinalIgnoreCase))
|
||||
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
|
||||
characters.Add(characterName);
|
||||
|
||||
Write(accountName, serverName, characters);
|
||||
}
|
||||
|
||||
// The client shows admin names with a leading '+' ('+Buffi'); a launch-context
|
||||
// name may lack it. Treat both as one character so the list holds no duplicate.
|
||||
private static bool IsSameCharacter(string a, string b) =>
|
||||
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public static void DeleteForAccount(string accountName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(accountName))
|
||||
|
|
|
|||
73
src/RynthCore.App/DecalLocator.cs
Normal file
73
src/RynthCore.App/DecalLocator.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
/// <summary>
|
||||
/// Locates a local Decal install via the same registry probe ThwargLauncher
|
||||
/// uses. Decal records its agent directory at HKLM\SOFTWARE\Decal\Agent (the
|
||||
/// launcher is x86, so we transparently see the Wow6432Node redirect on 64-bit
|
||||
/// Windows). Inject.dll lives directly in that directory and exports
|
||||
/// DecalStartup, which is the entry point the suspended-launch injector calls.
|
||||
/// </summary>
|
||||
internal static class DecalLocator
|
||||
{
|
||||
private const string AgentSubKey = @"SOFTWARE\Decal\Agent";
|
||||
private const string AgentPathValue = "AgentPath";
|
||||
private const string PortalPathValue = "PortalPath";
|
||||
private const string InjectDllName = "Inject.dll";
|
||||
private const string AcClientName = "acclient.exe";
|
||||
|
||||
/// <summary>Returns the absolute path to Decal's Inject.dll, or null if
|
||||
/// Decal is not registered or the file cannot be found beside its agent
|
||||
/// directory.</summary>
|
||||
public static string? TryGetInjectDllPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
|
||||
if (key == null)
|
||||
return null;
|
||||
|
||||
string? agentPath = key.GetValue(AgentPathValue) as string;
|
||||
if (string.IsNullOrWhiteSpace(agentPath))
|
||||
return null;
|
||||
|
||||
string injectPath = Path.Combine(agentPath, InjectDllName);
|
||||
return File.Exists(injectPath) ? injectPath : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the AC client install Decal expects, derived from its
|
||||
/// PortalPath registry value (e.g. C:\Turbine\Asheron's Call). Used when an
|
||||
/// account is set to Decal mode and the launcher's global AcClientPath
|
||||
/// points elsewhere (e.g. the RynthCore-private duplicate). Returns null if
|
||||
/// not registered or the file is missing.</summary>
|
||||
public static string? TryGetDecalAcClientPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
|
||||
if (key == null)
|
||||
return null;
|
||||
|
||||
string? portalPath = key.GetValue(PortalPathValue) as string;
|
||||
if (string.IsNullOrWhiteSpace(portalPath))
|
||||
return null;
|
||||
|
||||
string acPath = Path.Combine(portalPath, AcClientName);
|
||||
return File.Exists(acPath) ? acPath : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsInstalled() => TryGetInjectDllPath() != null;
|
||||
}
|
||||
17
src/RynthCore.App/InjectionMode.cs
Normal file
17
src/RynthCore.App/InjectionMode.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
namespace RynthCore.App;
|
||||
|
||||
/// <summary>
|
||||
/// Per-account choice of which modding stack to inject when launching the AC
|
||||
/// client. Selected from the launcher's per-row Injection Method dropdown.
|
||||
/// </summary>
|
||||
internal enum InjectionMode
|
||||
{
|
||||
/// <summary>RynthCore.Loader.dll → RynthCore.Engine.dll injected via the
|
||||
/// in-process injector. The native RynthCore stack.</summary>
|
||||
RynthCore = 0,
|
||||
|
||||
/// <summary>Decal's Inject.dll injected with its DecalStartup export. The
|
||||
/// account runs against Decal + UBService + VTank or whatever Decal plugins
|
||||
/// the user has registered.</summary>
|
||||
Decal = 1,
|
||||
}
|
||||
|
|
@ -1,9 +1,15 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
internal sealed class LaunchAccountProfile
|
||||
{
|
||||
/// Sentinel stored in CharacterName when the user has explicitly opted out of auto-login.
|
||||
/// At launch time, ResolveTargetCharacterForLaunch translates this to an empty string so
|
||||
/// the engine's CharacterCapture sees a blank TargetCharacter and skips auto-login entirely.
|
||||
public const string NoneOption = "(None — no auto-login)";
|
||||
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||
public string AccountName { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
|
|
@ -11,11 +17,39 @@ internal sealed class LaunchAccountProfile
|
|||
public string Alias { get; set; } = string.Empty;
|
||||
public string ServerId { get; set; } = string.Empty;
|
||||
|
||||
// Saved AC client window placement, restored on next launch and updated
|
||||
// when the user moves/resizes the window. Null until first save.
|
||||
public int? WindowX { get; set; }
|
||||
public int? WindowY { get; set; }
|
||||
public int? WindowWidth { get; set; }
|
||||
public int? WindowHeight { get; set; }
|
||||
|
||||
/// Optional path to a per-account stash of UserPreferences.ini. If set, the
|
||||
/// launcher copies this file over My Documents\Asheron's Call\UserPreferences.ini
|
||||
/// before launching this account. Empty/missing path = no swap, AC reads
|
||||
/// whatever happens to be in place.
|
||||
public string UserPrefsPath { get; set; } = string.Empty;
|
||||
|
||||
/// Which modding stack to inject when this account is launched. Defaults to
|
||||
/// RynthCore. Decal mode launches AC with Decal's Inject.dll instead and
|
||||
/// does not load the RynthCore engine into the process.
|
||||
public InjectionMode InjectionMode { get; set; } = InjectionMode.RynthCore;
|
||||
|
||||
/// Per-character chat commands to dispatch after login completes. Key is
|
||||
/// the character name (case-insensitive on lookup). Each list entry is one
|
||||
/// command line — "/say hi", "/fellow create xyz", etc. — sent in order
|
||||
/// with a small gap between commands. Empty/missing key = no commands.
|
||||
public Dictionary<string, List<string>> OnLoginCommandsByCharacter { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// Milliseconds to wait after the engine observes login-complete before
|
||||
/// dispatching the first OnLogin command. Matches Thwargle's default.
|
||||
public int OnLoginWaitMs { get; set; } = 3000;
|
||||
|
||||
public string DisplayName
|
||||
{
|
||||
get
|
||||
{
|
||||
string launchLabel = !string.IsNullOrWhiteSpace(CharacterName)
|
||||
string launchLabel = !string.IsNullOrWhiteSpace(CharacterName) && CharacterName != NoneOption
|
||||
? CharacterName
|
||||
: Alias;
|
||||
|
||||
|
|
@ -34,7 +68,15 @@ internal sealed class LaunchAccountProfile
|
|||
Password = Password,
|
||||
CharacterName = CharacterName,
|
||||
Alias = Alias,
|
||||
ServerId = ServerId
|
||||
ServerId = ServerId,
|
||||
WindowX = WindowX,
|
||||
WindowY = WindowY,
|
||||
WindowWidth = WindowWidth,
|
||||
WindowHeight = WindowHeight,
|
||||
UserPrefsPath = UserPrefsPath,
|
||||
InjectionMode = InjectionMode,
|
||||
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase),
|
||||
OnLoginWaitMs = OnLoginWaitMs,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -46,6 +88,14 @@ internal sealed class LaunchAccountProfile
|
|||
CharacterName = source.CharacterName;
|
||||
Alias = source.Alias;
|
||||
ServerId = source.ServerId;
|
||||
WindowX = source.WindowX;
|
||||
WindowY = source.WindowY;
|
||||
WindowWidth = source.WindowWidth;
|
||||
WindowHeight = source.WindowHeight;
|
||||
UserPrefsPath = source.UserPrefsPath;
|
||||
InjectionMode = source.InjectionMode;
|
||||
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(source.OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase);
|
||||
OnLoginWaitMs = source.OnLoginWaitMs;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
|
|
|
|||
|
|
@ -14,6 +14,16 @@ internal sealed class LaunchContextRecord
|
|||
public string TargetCharacter { get; set; } = string.Empty;
|
||||
public bool SkipLoginLogos { get; set; }
|
||||
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
|
||||
|
||||
/// Chat commands the engine should dispatch after login-complete fires
|
||||
/// for this PID. Resolved by the launcher from
|
||||
/// LaunchAccountProfile.OnLoginCommandsByCharacter at launch time. Null /
|
||||
/// empty = nothing to dispatch.
|
||||
public List<string>? OnLoginCommands { get; set; }
|
||||
|
||||
/// Milliseconds to wait after login-complete before sending the first
|
||||
/// command. 0 (or omitted) = use the engine's default.
|
||||
public int OnLoginWaitMs { get; set; }
|
||||
}
|
||||
|
||||
internal static class LaunchContextStore
|
||||
|
|
@ -25,7 +35,9 @@ internal static class LaunchContextStore
|
|||
string accountName,
|
||||
string serverName,
|
||||
string targetCharacter,
|
||||
bool skipLoginLogos)
|
||||
bool skipLoginLogos,
|
||||
List<string>? onLoginCommands = null,
|
||||
int onLoginWaitMs = 0)
|
||||
{
|
||||
return new LaunchContextRecord
|
||||
{
|
||||
|
|
@ -33,7 +45,9 @@ internal static class LaunchContextStore
|
|||
ServerName = serverName ?? string.Empty,
|
||||
TargetCharacter = targetCharacter ?? string.Empty,
|
||||
SkipLoginLogos = skipLoginLogos,
|
||||
CreatedAtUtc = DateTime.UtcNow
|
||||
CreatedAtUtc = DateTime.UtcNow,
|
||||
OnLoginCommands = onLoginCommands,
|
||||
OnLoginWaitMs = onLoginWaitMs
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -56,7 +70,9 @@ internal static class LaunchContextStore
|
|||
ServerName = context.ServerName,
|
||||
TargetCharacter = context.TargetCharacter,
|
||||
SkipLoginLogos = context.SkipLoginLogos,
|
||||
CreatedAtUtc = DateTime.UtcNow
|
||||
CreatedAtUtc = DateTime.UtcNow,
|
||||
OnLoginCommands = context.OnLoginCommands,
|
||||
OnLoginWaitMs = context.OnLoginWaitMs
|
||||
};
|
||||
|
||||
File.WriteAllText(GetProcessPath(processId), JsonSerializer.Serialize(processContext));
|
||||
|
|
|
|||
128
src/RynthCore.App/RynthInstallPaths.cs
Normal file
128
src/RynthCore.App/RynthInstallPaths.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Install;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick
|
||||
/// both folders and records them under <c>Software\Rynth</c> (HKCU for a per-user install,
|
||||
/// HKLM for an all-users install), so nothing may assume <c>C:\Games\...</c> any more.
|
||||
/// <para>
|
||||
/// Resolution order per folder: environment override (<c>RYNTHCORE_DIR</c> /
|
||||
/// <c>RYNTHSUITE_DIR</c>, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit
|
||||
/// installer writes) → the historical default under <c>C:\Games</c>. Results are cached
|
||||
/// for the life of the process.
|
||||
/// </para>
|
||||
/// Linked into every RynthCore project (Engine, Loader, Injector, launcher, StatusAgent);
|
||||
/// RynthSuite keeps an identical copy in <c>Shared/RynthInstallPaths.cs</c> — change both together.
|
||||
/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming
|
||||
/// without pulling in Microsoft.Win32.Registry.
|
||||
/// </summary>
|
||||
internal static class RynthInstallPaths
|
||||
{
|
||||
/// <summary>Default RynthCore folder (pre-2026.10.4.2 installs always used this).</summary>
|
||||
public const string DefaultCoreDir = @"C:\Games\RynthCore";
|
||||
|
||||
/// <summary>Default RynthSuite folder (pre-2026.10.4.2 installs always used this).</summary>
|
||||
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
|
||||
|
||||
/// <summary>Registry key (under HKCU or HKLM) written by the installer.</summary>
|
||||
public const string RegistryKey = @"Software\Rynth";
|
||||
|
||||
private static string? _coreDir;
|
||||
private static string? _suiteDir;
|
||||
|
||||
/// <summary>RynthCore install folder (launcher, <c>Runtime\</c>, <c>Logs\</c>, <c>Tools\</c>).</summary>
|
||||
public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir);
|
||||
|
||||
/// <summary>RynthSuite folder (plugins and their data, e.g. <c>RynthAi\</c>).</summary>
|
||||
public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir);
|
||||
|
||||
/// <summary>Unified RynthCore log folder (<c><CoreDir>\Logs</c>).</summary>
|
||||
public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
|
||||
|
||||
/// <summary>RynthAi plugin home and data root (<c><SuiteDir>\RynthAi</c>).</summary>
|
||||
public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
|
||||
|
||||
/// <summary>Reads a string value from <c>Software\Rynth</c> (HKCU first, then HKLM 32-bit view); null when absent.</summary>
|
||||
public static string? ReadSetting(string valueName)
|
||||
=> ReadRegistryString(HKEY_CURRENT_USER, valueName, 0)
|
||||
?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
|
||||
|
||||
/// <summary>Deletes a value from HKCU <c>Software\Rynth</c> (used for one-shot installer hand-offs). Best effort.</summary>
|
||||
public static void DeleteUserSetting(string valueName)
|
||||
{
|
||||
try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { }
|
||||
}
|
||||
|
||||
private static string Resolve(string envVar, string valueName, string fallback)
|
||||
{
|
||||
string? fromEnv = null;
|
||||
try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { }
|
||||
|
||||
foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) })
|
||||
{
|
||||
string? normalized = Normalize(candidate);
|
||||
if (normalized != null) return normalized;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// <summary>Accepts only absolute paths; trims whitespace, quotes and trailing separators.</summary>
|
||||
private static string? Normalize(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return null;
|
||||
string p = path.Trim().Trim('"').TrimEnd('\\', '/');
|
||||
if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\"
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(p)) return null;
|
||||
string full = Path.GetFullPath(p);
|
||||
return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Win32 registry (advapi32) ───────────────────────────────────────────
|
||||
|
||||
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
|
||||
private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));
|
||||
private const uint RRF_RT_REG_SZ = 0x00000002;
|
||||
private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004;
|
||||
private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000;
|
||||
private const int ERROR_SUCCESS = 0;
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
|
||||
private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags,
|
||||
IntPtr pdwType, char[]? pvData, ref uint pcbData);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
|
||||
private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
|
||||
|
||||
private static string? ReadRegistryString(IntPtr root, string valueName, uint viewFlags)
|
||||
{
|
||||
try
|
||||
{
|
||||
uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags;
|
||||
uint bytes = 0;
|
||||
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2)
|
||||
return null;
|
||||
|
||||
var buffer = new char[(bytes + 1) / 2];
|
||||
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS)
|
||||
return null;
|
||||
|
||||
int len = Array.IndexOf(buffer, '\0');
|
||||
return new string(buffer, 0, len >= 0 ? len : buffer.Length);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Missing advapi32 entry point or access denied — fall back to the defaults.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,10 @@ internal sealed class SessionStateRecord
|
|||
public DateTime? LoginCompletedAtUtc { get; set; }
|
||||
public DateTime LastUpdatedAtUtc { get; set; } = DateTime.UtcNow;
|
||||
public bool IsLoggedIn { get; set; }
|
||||
/// Set by the engine when LogoutLifecycleHooks observes a logout (clean
|
||||
/// or server-driven disconnect). Stays set across the post-login reaper
|
||||
/// window so the launcher can detect "stuck on disconnect/char-select".
|
||||
public DateTime? LogoutAtUtc { get; set; }
|
||||
}
|
||||
|
||||
internal static class SessionStateStore
|
||||
|
|
@ -32,7 +36,9 @@ internal static class SessionStateStore
|
|||
|
||||
record.ProcessId = processId;
|
||||
record.LastUpdatedAtUtc = DateTime.UtcNow;
|
||||
File.WriteAllText(GetProcessPath(processId), BuildSessionJson(record), Encoding.UTF8);
|
||||
// Explicit no-BOM UTF-8 — Encoding.UTF8 emits a BOM under NativeAOT which
|
||||
// breaks JsonDocument.Parse on the launcher side.
|
||||
File.WriteAllText(GetProcessPath(processId), BuildSessionJson(record), new System.Text.UTF8Encoding(false));
|
||||
}
|
||||
|
||||
public static SessionStateRecord? TryReadForProcess(int processId)
|
||||
|
|
@ -43,7 +49,15 @@ internal static class SessionStateStore
|
|||
|
||||
try
|
||||
{
|
||||
using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
// Strip UTF-8 BOM if present — the engine writes with Encoding.UTF8
|
||||
// which emits a BOM (EF BB BF) under NativeAOT, and JsonDocument.Parse
|
||||
// on a byte span rejects the BOM as an invalid JSON start character.
|
||||
ReadOnlyMemory<byte> content = bytes;
|
||||
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
|
||||
content = new ReadOnlyMemory<byte>(bytes, 3, bytes.Length - 3);
|
||||
|
||||
using JsonDocument document = JsonDocument.Parse(content);
|
||||
JsonElement root = document.RootElement;
|
||||
|
||||
var record = new SessionStateRecord
|
||||
|
|
@ -56,7 +70,8 @@ internal static class SessionStateStore
|
|||
LaunchStartedAtUtc = GetDateTime(root, "LaunchStartedAtUtc") ?? DateTime.UtcNow,
|
||||
LoginCompletedAtUtc = GetDateTime(root, "LoginCompletedAtUtc"),
|
||||
LastUpdatedAtUtc = GetDateTime(root, "LastUpdatedAtUtc") ?? DateTime.UtcNow,
|
||||
IsLoggedIn = GetBoolean(root, "IsLoggedIn")
|
||||
IsLoggedIn = GetBoolean(root, "IsLoggedIn"),
|
||||
LogoutAtUtc = GetDateTime(root, "LogoutAtUtc")
|
||||
};
|
||||
|
||||
if (record.ProcessId == 0)
|
||||
|
|
@ -138,6 +153,10 @@ internal static class SessionStateStore
|
|||
writer.WriteNull("LoginCompletedAtUtc");
|
||||
writer.WriteString("LastUpdatedAtUtc", record.LastUpdatedAtUtc.ToString("O", CultureInfo.InvariantCulture));
|
||||
writer.WriteBoolean("IsLoggedIn", record.IsLoggedIn);
|
||||
if (record.LogoutAtUtc.HasValue)
|
||||
writer.WriteString("LogoutAtUtc", record.LogoutAtUtc.Value.ToString("O", CultureInfo.InvariantCulture));
|
||||
else
|
||||
writer.WriteNull("LogoutAtUtc");
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
|
|
|
|||
79
src/RynthCore.Engine/Compatibility/AcActionTrace.cs
Normal file
79
src/RynthCore.Engine/Compatibility/AcActionTrace.cs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
// ============================================================================
|
||||
// AcActionTrace.cs — Temporary diagnostic for Class B AVs (AC UIElement::
|
||||
// GetAttribute_* AVs that fire with NO RynthCore frame on the faulting stack).
|
||||
//
|
||||
// Lock-free 256-entry ring buffer that records every RynthCore-issued AC-
|
||||
// mutating call (SelectItem / UseObject / ChangeCombatMode / Cast / attacks)
|
||||
// with a timestamp. Dumped to the log by ProcessExitHooks.LogTermination on
|
||||
// any process-exit path so post-crash analysis shows the literal sequence of
|
||||
// switches RynthCore made in the milliseconds before death — tests the
|
||||
// "too many switches" hypothesis without behavioural change.
|
||||
//
|
||||
// Zero per-call allocation: struct array preallocated at startup, lock-free
|
||||
// via Interlocked.Increment. Concurrent overwrites of the same slot are
|
||||
// tolerated (rare at depth 256; we only need the rough recent sequence).
|
||||
//
|
||||
// REMOVE once Class B is diagnosed and fixed.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class AcActionTrace
|
||||
{
|
||||
private struct Entry
|
||||
{
|
||||
public long Ticks; // DateTime.UtcNow.Ticks
|
||||
public string Name; // string literal at call site → no per-call alloc
|
||||
public uint A; // primary arg (typically objectId)
|
||||
public uint B; // secondary arg (e.g. spellId, mode, attackHeight)
|
||||
}
|
||||
|
||||
private const int Capacity = 256; // power of 2 for cheap mask
|
||||
private const int Mask = Capacity - 1;
|
||||
private static readonly Entry[] _slots = new Entry[Capacity];
|
||||
private static int _next; // Interlocked-incremented counter
|
||||
|
||||
/// <summary>
|
||||
/// Record an AC-mutating action at the engine callback entry. Safe from
|
||||
/// any thread; per call cost = one Interlocked.Increment + 4 struct field
|
||||
/// writes. Name MUST be a string literal (no per-call allocation).
|
||||
/// </summary>
|
||||
public static void Record(string name, uint a = 0, uint b = 0)
|
||||
{
|
||||
int slot = (Interlocked.Increment(ref _next) - 1) & Mask;
|
||||
_slots[slot].Ticks = DateTime.UtcNow.Ticks;
|
||||
_slots[slot].Name = name;
|
||||
_slots[slot].A = a;
|
||||
_slots[slot].B = b;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dump the buffer to the log. Called by ProcessExitHooks.LogTermination
|
||||
/// on every termination path so the action history is preserved across
|
||||
/// AV / fail-fast / clean exit.
|
||||
/// </summary>
|
||||
public static void DumpToLog()
|
||||
{
|
||||
try
|
||||
{
|
||||
int total = Volatile.Read(ref _next);
|
||||
int count = Math.Min(total, Capacity);
|
||||
int start = total - count;
|
||||
RynthLog.Info($"[AcActionTrace] dumping last {count} actions (total counter={total}):");
|
||||
for (int i = start; i < total; i++)
|
||||
{
|
||||
Entry e = _slots[i & Mask];
|
||||
if (e.Name == null) continue;
|
||||
DateTime dt = new DateTime(e.Ticks, DateTimeKind.Utc).ToLocalTime();
|
||||
RynthLog.Info($"[AcActionTrace] {dt:HH:mm:ss.fff} {e.Name}(0x{e.A:X8}, 0x{e.B:X8})");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"[AcActionTrace] dump exception: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
620
src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs
Normal file
620
src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs
Normal file
|
|
@ -0,0 +1,620 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
// Marshals off-thread bot ACTIONS onto AC's main (game) thread.
|
||||
//
|
||||
// AC is single-threaded and non-reentrant. The plugin pump (and chat-command /
|
||||
// UI threads) run OFF AC's main thread; when they invoke AC state-mutating
|
||||
// functions directly — combat-mode flips, melee/missile attacks, movement,
|
||||
// object use — they race AC's own per-tick bookkeeping and corrupt its
|
||||
// object / range lists. AC then access-violates LATER on its own thread during
|
||||
// routine teardown / range recompute: the dump-verified object-teardown class
|
||||
// 0x0055FA24 (List<ObjectRangeInfo>::remove via CPlayerSystem::CalculateObjectRangeChecks)
|
||||
// and 0x00416C86 (DBOCache::DestroyObj). The per-callsite SEH trampoline only
|
||||
// CONTAINS an AV that fires inside OUR call — it cannot stop AC tripping over
|
||||
// corruption we left behind. The only real fix is to not mutate off-thread:
|
||||
// enqueue here, execute on the main thread.
|
||||
//
|
||||
// Drained from the always-on EngineFrameController.OnEndScene tick (AC's main
|
||||
// thread; ~22-33 Hz; fires regardless of EnableImGuiBackend / idle / combat).
|
||||
//
|
||||
// Multi-producer-safe: Enqueue takes a short lock (it runs on engine-owned
|
||||
// threads, never inside an AC detour, so a lock is fine). Drain is the single
|
||||
// consumer (the main thread) and is lock-free + zero-alloc, so it never blocks
|
||||
// inside the reverse-P/Invoke detour and never reintroduces the GC-in-detour
|
||||
// fail-fast class.
|
||||
//
|
||||
// The drain re-invokes the EXISTING public action methods. Each of those
|
||||
// methods self-gates on MainThreadGuard.IsOnMainThread(): off-thread it
|
||||
// enqueues here; on the main thread (i.e. when called from Drain, or from any
|
||||
// legitimately main-thread caller) it executes the AC call directly. So there
|
||||
// is no separate "Direct" body to keep in sync, and no risk of an enqueue loop.
|
||||
//
|
||||
// CASTS: routed via the separate cast slot below (EnqueueCast / DrainCasts),
|
||||
// drained from AC's GAME-LOGIC tick (Client::UseTime, via GameTickHooks) — NOT
|
||||
// EndScene. EndScene is the render phase and does not drive AC's cast state machine
|
||||
// to completion (proven dead-end, reverted 2026-05-19); UseTime is where AC processes
|
||||
// player actions, so the cast completes there. SelectItem is paired inside
|
||||
// CombatActionHooks.CastSpell's main-thread path, so it stays ordered with the cast.
|
||||
internal static class AcMainThreadQueue
|
||||
{
|
||||
internal enum ActionKind : byte
|
||||
{
|
||||
ChangeCombatMode,
|
||||
MeleeAttack,
|
||||
MissileAttack,
|
||||
DoMovement,
|
||||
StopMovement,
|
||||
Jump,
|
||||
UseObject,
|
||||
// Item mutators marshalled 2026-06-05 (off-thread UseObjectOn/MoveItem/stack ops
|
||||
// raced AC's per-tick object graph -> null-deref AVs in Client::UseTime, e.g.
|
||||
// acclient+0xF24E0; same off-thread class as the P1 UseObject fix).
|
||||
UseObjectOn,
|
||||
UseEquippedItem,
|
||||
MoveItemExternal,
|
||||
MoveItemInternal,
|
||||
SplitStackInternal,
|
||||
MergeStackInternal,
|
||||
GiveObjectTo,
|
||||
// CommandInterpreter movement marshalled 2026-06-12: SetAutoRun /
|
||||
// TurnToHeading / StopCompletely were the last direct off-thread AC
|
||||
// mutators (dump-proven: a SetAutoRun executed 15s after a main thread
|
||||
// had wedged) — they rewrite the locomotion channels of the SAME
|
||||
// CommandInterpreter/motion graph the CSequence-AV class corrupts.
|
||||
SetAutoRun,
|
||||
TurnToHeading,
|
||||
StopCompletely,
|
||||
SetMotion,
|
||||
// SetSelectedObject marshalled 2026-06-13: the host-API SelectItem /
|
||||
// SetSelectedObjectId (looting/targeting) was the LAST AC-mutating helper
|
||||
// still calling AC directly off the pump thread. AC's SetSelectedObject
|
||||
// (0x0058D110) updates the selection/targeting UIElement subtree; run off
|
||||
// the main thread it raced AC's own UI walk -> deterministic corruption AV
|
||||
// at acclient+0x60D1D (UIElement smart-ptr refcount writeback into
|
||||
// read-only .text, 5 captures in native-crash.log, two threads at once).
|
||||
SetSelectedObject,
|
||||
// NativeAttack marshalled 2026-09-01 (deep-audit finding #15): the
|
||||
// ClientCombatSystem StartAttackRequest/EndAttackRequest pair (plus the
|
||||
// height-change notify) had no MainThreadGuard gate, unlike the sibling
|
||||
// MeleeAttack/MissileAttack/ChangeCombatMode. UseNativeAttack defaults
|
||||
// true, so CombatManager.FireAttack ran this un-marshalled every fight
|
||||
// right after a correctly-marshalled SelectItem on the same pump thread.
|
||||
// Carried as one entry (not split) so the whole ordered sequence executes
|
||||
// atomically after the paired selection, per the audit's fix note.
|
||||
NativeAttack,
|
||||
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): CommenceJump/
|
||||
// DoJump/TapJump call native CommandInterpreter members through
|
||||
// _boundCmdInterp with zero MainThreadGuard gate — unlike every sibling
|
||||
// (SetAutoRun/SetMotion/StopCompletely/TurnToHeading), which all marshal
|
||||
// via this queue. Live-exercised off-thread today via Jumper.cs's
|
||||
// Decal-coexistence pump-thread tick. CommenceJump and the later
|
||||
// DoJump/LaunchJumpWithMotion release land in separate queue entries
|
||||
// (separate ticks, ~msToHoldDown apart) — that's fine, the ordering
|
||||
// just needs to stay FIFO within this single-consumer queue, which it does.
|
||||
CommenceJump,
|
||||
TapJump,
|
||||
DoJumpAutonomous,
|
||||
// LaunchJumpWithMotion (PlayerPhysicsHooks.cs) is the more dangerous of
|
||||
// the two release paths: it Marshal.WriteInt32's directly into
|
||||
// CMotionInterp's forward/strafe/turn fields with NO thread gate at
|
||||
// all (not even the thiscall-through-delegate try/catch the
|
||||
// CommandInterpreter trio has) before calling DoJump. A torn write here
|
||||
// racing AC's own motion-graph tick is exactly the CSequence corruption
|
||||
// class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W,
|
||||
// bit2=X, bit3=Z, bit4=C).
|
||||
LaunchJumpWithMotion,
|
||||
}
|
||||
|
||||
// Four payload slots cover every routed action (the 4th was added for
|
||||
// MoveItemInternal/SplitStackInternal: id, container, slot, amount). Floats are
|
||||
// carried as their IEEE bit pattern in a uint slot (BitConverter round-trip).
|
||||
private readonly struct Entry(AcMainThreadQueue.ActionKind kind, uint a, uint b, uint c, uint d)
|
||||
{
|
||||
public readonly ActionKind Kind = kind;
|
||||
public readonly uint A = a;
|
||||
public readonly uint B = b;
|
||||
public readonly uint C = c;
|
||||
public readonly uint D = d;
|
||||
}
|
||||
|
||||
private const int Capacity = 256; // power of two
|
||||
private const int Mask = Capacity - 1;
|
||||
private static readonly Entry[] _slots = new Entry[Capacity];
|
||||
private static readonly object _producerLock = new();
|
||||
|
||||
// Monotonic counters. Producers advance _tail under _producerLock; the sole
|
||||
// consumer (main thread) advances _head.
|
||||
private static int _head;
|
||||
private static int _tail;
|
||||
private static long _dropped;
|
||||
|
||||
public static long DroppedCount => Interlocked.Read(ref _dropped);
|
||||
|
||||
private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0)
|
||||
{
|
||||
lock (_producerLock)
|
||||
{
|
||||
int tail = _tail;
|
||||
int head = Volatile.Read(ref _head);
|
||||
if (tail - head >= Capacity)
|
||||
{
|
||||
// Full. Drop rather than block or fall back to an off-thread AC
|
||||
// mutation — a dropped movement/attack tick self-corrects on the
|
||||
// next bot tick; an off-thread mutation can crash the client.
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
|
||||
_slots[tail & Mask] = new Entry(kind, a, b, c, d);
|
||||
Volatile.Write(ref _tail, tail + 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Typed enqueue helpers (called by the public action methods when they
|
||||
// detect they're running off AC's main thread) ───────────────────────
|
||||
public static bool EnqueueChangeCombatMode(int mode) =>
|
||||
Enqueue(ActionKind.ChangeCombatMode, unchecked((uint)mode), 0, 0);
|
||||
|
||||
public static bool EnqueueMeleeAttack(uint targetId, int attackHeight, float powerLevel) =>
|
||||
Enqueue(ActionKind.MeleeAttack, targetId, unchecked((uint)attackHeight),
|
||||
BitConverter.SingleToUInt32Bits(powerLevel));
|
||||
|
||||
public static bool EnqueueMissileAttack(uint targetId, int attackHeight, float accuracyLevel) =>
|
||||
Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight),
|
||||
BitConverter.SingleToUInt32Bits(accuracyLevel));
|
||||
|
||||
public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) =>
|
||||
Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey),
|
||||
BitConverter.SingleToUInt32Bits(speed));
|
||||
|
||||
public static bool EnqueueStopMovement(uint motion, int holdKey) =>
|
||||
Enqueue(ActionKind.StopMovement, motion, unchecked((uint)holdKey), 0);
|
||||
|
||||
public static bool EnqueueSetAutoRun(bool enabled) =>
|
||||
Enqueue(ActionKind.SetAutoRun, enabled ? 1u : 0u, 0, 0);
|
||||
|
||||
public static bool EnqueueTurnToHeading(float headingDegrees) =>
|
||||
Enqueue(ActionKind.TurnToHeading, BitConverter.SingleToUInt32Bits(headingDegrees), 0, 0);
|
||||
|
||||
public static bool EnqueueStopCompletely() =>
|
||||
Enqueue(ActionKind.StopCompletely, 0, 0, 0);
|
||||
|
||||
public static bool EnqueueSetMotion(uint motion, bool enabled) =>
|
||||
Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0);
|
||||
|
||||
public static bool EnqueueJump(float extent) =>
|
||||
Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0);
|
||||
|
||||
public static bool EnqueueUseObject(uint objectId) =>
|
||||
Enqueue(ActionKind.UseObject, objectId, 0, 0);
|
||||
|
||||
public static bool EnqueueUseObjectOn(uint sourceObjectId, uint targetObjectId) =>
|
||||
Enqueue(ActionKind.UseObjectOn, sourceObjectId, targetObjectId, 0);
|
||||
|
||||
public static bool EnqueueUseEquippedItem(uint sourceObjectId, uint targetObjectId) =>
|
||||
Enqueue(ActionKind.UseEquippedItem, sourceObjectId, targetObjectId, 0);
|
||||
|
||||
public static bool EnqueueMoveItemExternal(uint objectId, uint targetContainerId, int amount) =>
|
||||
Enqueue(ActionKind.MoveItemExternal, objectId, targetContainerId, unchecked((uint)amount));
|
||||
|
||||
public static bool EnqueueMoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
|
||||
Enqueue(ActionKind.MoveItemInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
|
||||
|
||||
public static bool EnqueueSplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
|
||||
Enqueue(ActionKind.SplitStackInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
|
||||
|
||||
public static bool EnqueueMergeStackInternal(uint sourceObjectId, uint targetObjectId) =>
|
||||
Enqueue(ActionKind.MergeStackInternal, sourceObjectId, targetObjectId, 0);
|
||||
|
||||
public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) =>
|
||||
Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount));
|
||||
|
||||
public static bool EnqueueSetSelectedObject(uint objectId) =>
|
||||
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
|
||||
|
||||
public static bool EnqueueNativeAttack(int attackHeight, float power) =>
|
||||
Enqueue(ActionKind.NativeAttack, unchecked((uint)attackHeight),
|
||||
BitConverter.SingleToUInt32Bits(power), 0);
|
||||
|
||||
public static bool EnqueueCommenceJump() => Enqueue(ActionKind.CommenceJump, 0, 0, 0);
|
||||
public static bool EnqueueTapJump() => Enqueue(ActionKind.TapJump, 0, 0, 0);
|
||||
public static bool EnqueueDoJumpAutonomous(bool autonomous) =>
|
||||
Enqueue(ActionKind.DoJumpAutonomous, autonomous ? 1u : 0u, 0, 0);
|
||||
|
||||
public static bool EnqueueLaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
|
||||
{
|
||||
uint flags = (shift ? 1u : 0u) | (holdW ? 2u : 0u) | (holdX ? 4u : 0u) | (holdZ ? 8u : 0u) | (holdC ? 16u : 0u);
|
||||
return Enqueue(ActionKind.LaunchJumpWithMotion, flags, 0, 0);
|
||||
}
|
||||
|
||||
// Latched by EngineLifecycle.Shutdown: once teardown begins, queued plugin
|
||||
// actions must NOT keep executing on AC's main thread — the detours stay
|
||||
// live until MH_DisableHook(ALL), so without this latch a marshalled
|
||||
// mutation (SetAutoRun etc.) can run mid-teardown against state that
|
||||
// plugin Shutdowns are concurrently freeing (observed live at
|
||||
// 2026-06-11 07:44:03: "Move: SetAutoRun(False)" fired between plugin
|
||||
// shutdown steps). Abandoned entries are benign.
|
||||
private static volatile bool _disarmed;
|
||||
|
||||
/// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary>
|
||||
public static void Disarm() => _disarmed = true;
|
||||
|
||||
// Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene).
|
||||
// Re-invokes the public action methods; on the main thread they execute the
|
||||
// real AC call directly (their IsOnMainThread gate is satisfied here).
|
||||
// Gesture-phase defer state for the action ring (mirrors the cast slot's
|
||||
// 56e6946 guard; see DrainDeferTickCap note below for why we PROCEED
|
||||
// rather than drop after the cap).
|
||||
private static int _drainDeferTicks;
|
||||
private const int DrainDeferTickCap = 250;
|
||||
|
||||
public static void Drain()
|
||||
{
|
||||
if (_disarmed) return;
|
||||
|
||||
// Deep-audit finding #22 (2026-06-18): these three queues are
|
||||
// documented as deliberately separate from the gesture-gated action
|
||||
// ring below specifically so appraisals/chat "can never get
|
||||
// gesture-deferred" — but the gesture-defer early-return further
|
||||
// down used to run BEFORE these calls, so a non-empty action ring
|
||||
// sitting behind an in-flight gesture silently stalled chat output
|
||||
// and 0xC8 appraisal sends too, contradicting that invariant. Each
|
||||
// drains only while ITS OWN queue is non-empty, so moving them here
|
||||
// costs nothing when they're empty (the common case).
|
||||
DrainChat();
|
||||
DrainChatCommands();
|
||||
DrainRequestIds();
|
||||
// Vendor buy/sell: a packet send through the client's own SendShopEvent, not a
|
||||
// motion, so it sits with the non-gesture queues above. Also polls whether the
|
||||
// vendor window is still open. Idle fast path when no vendor is open.
|
||||
try { VendorTrade.MainThreadTick(); } catch { }
|
||||
|
||||
int head = _head; // only the main thread writes _head
|
||||
int tail = Volatile.Read(ref _tail);
|
||||
|
||||
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
|
||||
// to the whole ring) ─────────────────────────────────────────────────
|
||||
// Every ring action perturbs AC's action/motion state to some degree:
|
||||
// UseObject starts a reach gesture, ChangeCombatMode rebuilds the
|
||||
// motion graph, movement rewrites locomotion channels. Retail AC
|
||||
// serializes these against the IN-FLIGHT gesture via its action queue;
|
||||
// we previously serialized thread + tick-phase but not gesture-phase.
|
||||
// Defer the drain while the pending-motion list [CMI+0x80] is
|
||||
// non-empty — bounded, then PROCEED (unlike the cast slot we never
|
||||
// drop: dropping arbitrary item/movement actions desyncs the bot far
|
||||
// worse than a late injection, and the pre-2026-06-12 behavior was
|
||||
// "always inject" anyway, so proceeding past the cap is never worse).
|
||||
if (head != tail)
|
||||
{
|
||||
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight
|
||||
&& ++_drainDeferTicks <= DrainDeferTickCap)
|
||||
return;
|
||||
_drainDeferTicks = 0;
|
||||
}
|
||||
while (head != tail)
|
||||
{
|
||||
Entry e = _slots[head & Mask];
|
||||
Volatile.Write(ref _head, ++head);
|
||||
|
||||
try
|
||||
{
|
||||
switch (e.Kind)
|
||||
{
|
||||
case ActionKind.ChangeCombatMode:
|
||||
CombatActionHooks.ChangeCombatMode(unchecked((int)e.A));
|
||||
break;
|
||||
case ActionKind.MeleeAttack:
|
||||
CombatActionHooks.MeleeAttack(e.A, unchecked((int)e.B),
|
||||
BitConverter.UInt32BitsToSingle(e.C));
|
||||
break;
|
||||
case ActionKind.MissileAttack:
|
||||
CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B),
|
||||
BitConverter.UInt32BitsToSingle(e.C));
|
||||
break;
|
||||
case ActionKind.DoMovement:
|
||||
MovementActionHooks.DoMovement(e.A,
|
||||
BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B));
|
||||
break;
|
||||
case ActionKind.StopMovement:
|
||||
MovementActionHooks.StopMovement(e.A, unchecked((int)e.B));
|
||||
break;
|
||||
case ActionKind.Jump:
|
||||
MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A));
|
||||
break;
|
||||
case ActionKind.UseObject:
|
||||
ClientHelperHooks.UseObject(e.A);
|
||||
break;
|
||||
case ActionKind.UseObjectOn:
|
||||
ClientHelperHooks.UseObjectOn(e.A, e.B);
|
||||
break;
|
||||
case ActionKind.UseEquippedItem:
|
||||
ClientHelperHooks.UseEquippedItem(e.A, e.B);
|
||||
break;
|
||||
case ActionKind.MoveItemExternal:
|
||||
ClientHelperHooks.MoveItemExternal(e.A, e.B, unchecked((int)e.C));
|
||||
break;
|
||||
case ActionKind.MoveItemInternal:
|
||||
ClientHelperHooks.MoveItemInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
|
||||
break;
|
||||
case ActionKind.SplitStackInternal:
|
||||
ClientHelperHooks.SplitStackInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
|
||||
break;
|
||||
case ActionKind.MergeStackInternal:
|
||||
ClientHelperHooks.MergeStackInternal(e.A, e.B);
|
||||
break;
|
||||
case ActionKind.GiveObjectTo:
|
||||
ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C));
|
||||
break;
|
||||
case ActionKind.SetSelectedObject:
|
||||
// On the main thread now -> SetSelectedObjectId's gate is
|
||||
// satisfied and it calls AC's SetSelectedObject directly.
|
||||
ClientHelperHooks.SetSelectedObjectId(e.A);
|
||||
break;
|
||||
case ActionKind.NativeAttack:
|
||||
// On the main thread now -> NativeAttack's gate is
|
||||
// satisfied and it fires the real StartAttackRequest/
|
||||
// EndAttackRequest pair directly.
|
||||
ClientCombatHooks.NativeAttack(unchecked((int)e.A),
|
||||
BitConverter.UInt32BitsToSingle(e.B));
|
||||
break;
|
||||
case ActionKind.CommenceJump:
|
||||
CommandInterpreterHooks.CommenceJump();
|
||||
break;
|
||||
case ActionKind.TapJump:
|
||||
CommandInterpreterHooks.TapJump();
|
||||
break;
|
||||
case ActionKind.DoJumpAutonomous:
|
||||
CommandInterpreterHooks.DoJump(e.A != 0);
|
||||
break;
|
||||
case ActionKind.LaunchJumpWithMotion:
|
||||
PlayerPhysicsHooks.LaunchJumpWithMotion(
|
||||
(e.A & 1u) != 0, (e.A & 2u) != 0, (e.A & 4u) != 0,
|
||||
(e.A & 8u) != 0, (e.A & 16u) != 0);
|
||||
break;
|
||||
case ActionKind.SetAutoRun:
|
||||
CommandInterpreterHooks.SetAutoRun(e.A != 0);
|
||||
break;
|
||||
case ActionKind.TurnToHeading:
|
||||
CommandInterpreterHooks.TurnToHeading(BitConverter.UInt32BitsToSingle(e.A));
|
||||
break;
|
||||
case ActionKind.StopCompletely:
|
||||
CommandInterpreterHooks.StopCompletely();
|
||||
break;
|
||||
case ActionKind.SetMotion:
|
||||
CommandInterpreterHooks.SetMotion(e.A, e.B != 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// One action must never break the drain loop. (AC-side AVs are
|
||||
// not managed exceptions and won't be caught here — but these
|
||||
// now run on the correct thread, which is the whole point.)
|
||||
}
|
||||
|
||||
tail = Volatile.Read(ref _tail);
|
||||
}
|
||||
}
|
||||
|
||||
// ── RequestId slot (0xC8 appraisal sends from AutoIdService) ──────────────────
|
||||
// AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap
|
||||
// allocation + a non-atomic shared UI-counter increment off AC's main thread (the
|
||||
// off-thread-send class flagged for RequestId). Marshal onto the main thread here.
|
||||
// Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog
|
||||
// of appraisals can never crowd out combat/movement actions or get gesture-deferred:
|
||||
// an appraisal is just a packet send and doesn't perturb AC's motion/UI state.
|
||||
private static readonly System.Collections.Generic.Queue<uint> _requestIdQueue = new();
|
||||
private static readonly object _requestIdLock = new();
|
||||
private const int MaxRequestIdQueue = 256;
|
||||
|
||||
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full.
|
||||
public static bool EnqueueRequestId(uint objectId)
|
||||
{
|
||||
if (objectId == 0) return false;
|
||||
lock (_requestIdLock)
|
||||
{
|
||||
if (_requestIdQueue.Count >= MaxRequestIdQueue)
|
||||
{
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
_requestIdQueue.Enqueue(objectId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Single-consumer drain on AC's main thread (from Drain()). On the main thread
|
||||
// CombatActionHooks.RequestId sends the 0xC8 directly.
|
||||
private static void DrainRequestIds()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
uint id;
|
||||
lock (_requestIdLock)
|
||||
{
|
||||
if (_requestIdQueue.Count == 0) return;
|
||||
id = _requestIdQueue.Dequeue();
|
||||
}
|
||||
try { CombatActionHooks.RequestId(id); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Chat slot (WriteToChat strings) ──────────────────────────────────────────
|
||||
// WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread
|
||||
// AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring
|
||||
// 0x00460D1D write-AV that killed a 5h+ session 2026-06-05). Chat writes marshal
|
||||
// here and drain on the main thread from Drain(), alongside the item/movement
|
||||
// actions. WriteToChat's 100 ms rate-limit runs BEFORE the enqueue, so a bot retry
|
||||
// burst is dropped on the pump thread and this queue never fills with spam.
|
||||
private static readonly System.Collections.Generic.Queue<(string Text, int ChatType)> _chatQueue = new();
|
||||
private static readonly object _chatLock = new();
|
||||
private const int MaxChatQueue = 64;
|
||||
|
||||
// Pump-thread enqueue. Drops (returns false) if the queue is full.
|
||||
public static bool EnqueueWriteToChat(string text, int chatType)
|
||||
{
|
||||
lock (_chatLock)
|
||||
{
|
||||
if (_chatQueue.Count >= MaxChatQueue)
|
||||
{
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
_chatQueue.Enqueue((text, chatType));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Single-consumer drain on AC's main thread. Re-invokes WriteToChat, whose
|
||||
// IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly.
|
||||
private static void DrainChat()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
(string Text, int ChatType) item;
|
||||
lock (_chatLock)
|
||||
{
|
||||
if (_chatQueue.Count == 0) return;
|
||||
item = _chatQueue.Dequeue();
|
||||
}
|
||||
try { ClientHelperHooks.WriteToChat(item.Text, item.ChatType); }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Chat COMMAND slot (full ChatCommandDispatcher.Dispatch lines) ────────────
|
||||
// Deep-audit finding #4 (2026-06-18): ChatCommandDispatcher.Dispatch is not
|
||||
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
|
||||
// constructs/destructs AC's native PStringBase<char> (alloc/free in AC's
|
||||
// heap), and calls Event_Talk/Event_Emote/etc. directly against AC's live
|
||||
// chat-manager, all of which assumed (incorrectly) "safe from any thread".
|
||||
// Off-thread callers exist today: OnLoginCommandRunner (ThreadPool via
|
||||
// Task.Run), ChatFileDispatcher (FileSystemWatcher thread), and
|
||||
// Host.InvokeChatParser (plugin export, any thread). Gating inside
|
||||
// Dispatch() itself (rather than at each caller) covers all three at once.
|
||||
// A full command line can't ride the uint Entry ring, so it gets its own
|
||||
// string queue, same shape as the WriteToChat slot above.
|
||||
private static readonly System.Collections.Generic.Queue<string> _chatCommandQueue = new();
|
||||
private static readonly object _chatCommandLock = new();
|
||||
private const int MaxChatCommandQueue = 64;
|
||||
|
||||
// Off-thread enqueue. Drops (returns false) if the queue is full.
|
||||
public static bool EnqueueChatCommand(string text)
|
||||
{
|
||||
lock (_chatCommandLock)
|
||||
{
|
||||
if (_chatCommandQueue.Count >= MaxChatCommandQueue)
|
||||
{
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
_chatCommandQueue.Enqueue(text);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Single-consumer drain on AC's main thread. Re-invokes Dispatch, whose
|
||||
// IsOnMainThread gate is satisfied here so it runs the full body directly
|
||||
// instead of re-enqueuing.
|
||||
private static void DrainChatCommands()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
string text;
|
||||
lock (_chatCommandLock)
|
||||
{
|
||||
if (_chatCommandQueue.Count == 0) return;
|
||||
text = _chatCommandQueue.Dequeue();
|
||||
}
|
||||
try { ChatCommandDispatcher.Dispatch(text); }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cast slot (SelectItem + CastSpell pair) ─────────────────────────────────
|
||||
// Drained at AC's GAME-LOGIC tick (Client::UseTime via GameTickHooks), NOT the
|
||||
// EndScene render tick. Single-outstanding: EnqueueCast returns false while a cast
|
||||
// is pending so the off-thread caller (BuffManager / CombatManager) retries next
|
||||
// tick — they already handle a false return without wedging. At ~frame-rate drain
|
||||
// the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be
|
||||
// marshalled, closing the off-thread object-graph corruption class at its source.
|
||||
private static int _castPending;
|
||||
private static uint _castTargetId;
|
||||
private static uint _castSpellId;
|
||||
private static readonly object _castLock = new();
|
||||
|
||||
// Ticks DrainCasts has deferred the pending cast because a motion gesture was
|
||||
// still in flight. Bounded so a stuck gesture (the documented wand-wield wedge
|
||||
// variant) can't park a cast forever: past the cap the cast is DROPPED — the
|
||||
// plugin's no-chat-resolve machinery already retries casts that produce no
|
||||
// chat, so a drop degrades to one retry cycle, never a wedge.
|
||||
private static int _castDeferTicks;
|
||||
private static long _castDeferDrops;
|
||||
private const int CastDeferTickCap = 250; // ~4-8 s at the 30-63 Hz UseTime rate
|
||||
|
||||
/// <summary>Casts dropped after deferring CastDeferTickCap ticks (stuck gesture).</summary>
|
||||
public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops);
|
||||
|
||||
// Pump-thread enqueue. Returns false (caller retries next tick) if a cast is
|
||||
// already pending.
|
||||
public static bool EnqueueCast(uint targetId, uint spellId)
|
||||
{
|
||||
lock (_castLock)
|
||||
{
|
||||
if (_castPending != 0) return false;
|
||||
_castTargetId = targetId;
|
||||
_castSpellId = spellId;
|
||||
_castPending = 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
|
||||
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
|
||||
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
|
||||
public static void DrainCasts()
|
||||
{
|
||||
if (_disarmed) return; // engine teardown in progress
|
||||
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path
|
||||
|
||||
// ── Anim-walk race guard (dump-proven 2026-06-12) ────────────────────
|
||||
// DrainCasts runs PRE-tick (selection timing), but a cast initiates a
|
||||
// wind-up gesture that REPLACES the player's pending CSequence motions —
|
||||
// and the SAME UseTime call then walks that sequence. If a gesture is
|
||||
// already mid-flight when we inject, the walker can hit a freed/null
|
||||
// node: AV at acclient 0x00526840 AnimSequenceNode::get_part_frame
|
||||
// [null+0xC], full stack in CrashDumps\acclient_anim_av_4716.dmp
|
||||
// (7.6 h overnight soak, crash INSIDE _originalUseTime, our detour on
|
||||
// the stack below it). Same mechanism the post-tick reorder fixed for
|
||||
// UseObject/movement — casts were exempted and carried the residue.
|
||||
// Defer while the pending-motion list is non-empty (the exact structure
|
||||
// the tick walks); main-thread read, alloc-free, fail-open: if the read
|
||||
// itself fails we cast (pre-fix behavior) rather than park.
|
||||
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
|
||||
{
|
||||
if (++_castDeferTicks <= CastDeferTickCap)
|
||||
return; // retry next tick
|
||||
// Gesture stuck past the cap — drop the cast instead of injecting
|
||||
// into a wedged motion graph; the plugin retries via no-chat-resolve.
|
||||
lock (_castLock) { _castPending = 0; }
|
||||
_castDeferTicks = 0;
|
||||
Interlocked.Increment(ref _castDeferDrops);
|
||||
return;
|
||||
}
|
||||
_castDeferTicks = 0;
|
||||
|
||||
uint target, spell;
|
||||
lock (_castLock)
|
||||
{
|
||||
if (_castPending == 0) return;
|
||||
target = _castTargetId;
|
||||
spell = _castSpellId;
|
||||
_castPending = 0;
|
||||
}
|
||||
CombatActionHooks.CastSpell(target, unchecked((int)spell));
|
||||
}
|
||||
}
|
||||
|
|
@ -27,10 +27,20 @@ internal static class AccountHooks
|
|||
{
|
||||
private const int ReferenceClientGetInstance = 0x004114C0;
|
||||
private const int ReferenceClientGetAccountName = 0x00401D90;
|
||||
private const int SendNoticeWorldNameVa = 0x00693A60;
|
||||
private const int SendNoticeWorldNameFallbackVa = 0x00693A60;
|
||||
private const int PStringBufferLenOffset = 8;
|
||||
private const int PStringBufferDataOffset = 20;
|
||||
|
||||
// ECM_Login::SendNotice_WorldName(AC1Legacy::PStringBase<char> const&) — bool (cdecl)
|
||||
// Distinctive: vftable-call via push 0x186A2 (UI message ID for world-name notice).
|
||||
private static readonly byte?[] SendNoticeWorldNamePattern =
|
||||
[
|
||||
0xE8, null, null, null, null, // call rel32
|
||||
0x8B, 0x10, 0x68, 0xA2, 0x86, 0x01, 0x00, // mov edx,[eax]; push 0x186A2
|
||||
0x8B, 0xC8, 0xFF, 0x52, 0x10, // mov ecx,eax; call [edx+0x10]
|
||||
0x85, 0xC0, 0x74, 0x22, 0x56, 0x8B, 0x70, 0x04
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr ClientGetInstanceDelegate();
|
||||
|
||||
|
|
@ -94,43 +104,34 @@ internal static class AccountHooks
|
|||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
RynthLog.Compat("Compat: world-name hook skipped - acclient.exe not available.");
|
||||
RynthLog.Compat("AccountHooks: world-name hook skipped - acclient.exe not available.");
|
||||
return;
|
||||
}
|
||||
|
||||
int funcOff = SendNoticeWorldNameVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: world-name hook failed - VA 0x{SendNoticeWorldNameVa:X8} out of text section range.");
|
||||
var resolved = HookResolver.Resolve(textSection, "AccountHooks.SendNotice_WorldName",
|
||||
SendNoticeWorldNamePattern, SendNoticeWorldNameFallbackVa);
|
||||
if (!resolved.Success)
|
||||
return;
|
||||
}
|
||||
|
||||
byte firstByte = textSection.Bytes[funcOff];
|
||||
if (firstByte is 0x00 or 0xCC or 0xC3)
|
||||
{
|
||||
RynthLog.Compat($"Compat: world-name hook failed - invalid opcode 0x{firstByte:X2} @ 0x{SendNoticeWorldNameVa:X8}.");
|
||||
return;
|
||||
}
|
||||
|
||||
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_sendNoticeWorldNameDetour = SendNoticeWorldNameDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendNoticeWorldNameDetour);
|
||||
_originalSendNoticeWorldName = Marshal.GetDelegateForFunctionPointer<SendNoticeWorldNameDelegate>(
|
||||
MinHook.HookCreate(targetAddress, detourPtr));
|
||||
MinHook.HookCreate(resolved.Address, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(targetAddress);
|
||||
MinHook.Enable(resolved.Address);
|
||||
|
||||
WorldHookInstalled = true;
|
||||
RynthLog.Verbose($"Compat: world-name hook ready - ECM_Login::SendNotice_WorldName @ 0x{targetAddress.ToInt32():X8}.");
|
||||
RynthLog.Compat($"AccountHooks: world-name hook ready @ 0x{resolved.Address.ToInt32():X8}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: world-name hook failed - {ex.Message}");
|
||||
RynthLog.Compat($"AccountHooks: world-name hook install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static byte SendNoticeWorldNameDetour(IntPtr pstringPtr)
|
||||
{
|
||||
RecursionGuard.Tick("AccountHooks.SendNoticeWorldName");
|
||||
byte result = 0;
|
||||
try { result = _originalSendNoticeWorldName!(pstringPtr); } catch { }
|
||||
|
||||
|
|
@ -143,7 +144,10 @@ internal static class AccountHooks
|
|||
if (bufferPtr != IntPtr.Zero && IsReadable(bufferPtr + PStringBufferDataOffset))
|
||||
{
|
||||
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
|
||||
if (len > 1)
|
||||
// Clamp + length-aware check (finding #29): len comes from
|
||||
// AC's own heap, only floor-checked before — a corrupt/torn
|
||||
// value could otherwise drive a copy past the committed page.
|
||||
if (len > 1 && len <= 256 && IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
|
||||
{
|
||||
string? name = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
|
|
@ -192,7 +196,9 @@ internal static class AccountHooks
|
|||
return false;
|
||||
|
||||
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
|
||||
if (len <= 1)
|
||||
// Clamp + length-aware check (finding #29): same rationale as
|
||||
// SendNoticeWorldNameDetour above.
|
||||
if (len <= 1 || len > 256 || !IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
|
||||
return false;
|
||||
|
||||
string? str = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
|
||||
|
|
@ -268,4 +274,23 @@ internal static class AccountHooks
|
|||
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deep-audit finding #29 (2026-06-18): the single-arg IsReadable above
|
||||
// only validates the START page. All three PtrToStringAnsi call sites in
|
||||
// this file then do a len-driven copy (len from AC's own heap, only
|
||||
// floor-checked at >1) that can cross into an uncommitted page if len is
|
||||
// corrupt or torn — a length-aware check (mirroring CrashLogger's
|
||||
// IsReadable(addr, bytes), which isn't accessible from here) is needed
|
||||
// for the actual byte span being copied, not just its first byte.
|
||||
private static bool IsReadable(IntPtr ptr, int bytes)
|
||||
{
|
||||
if (ptr == IntPtr.Zero || bytes <= 0) return false;
|
||||
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return false;
|
||||
if (mbi.State != MEM_COMMIT) return false;
|
||||
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
|
||||
|
||||
long endRequested = ptr.ToInt64() + bytes;
|
||||
long endRegion = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
|
||||
return endRequested <= endRegion;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,6 +79,32 @@ internal static class AppraisalHooks
|
|||
return _appraisedGuids.Contains(guid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deep-audit finding #33 (2026-06-18): these seven session-scoped
|
||||
/// collections were populated per appraised guid and never cleared or
|
||||
/// bounded — no ClearSession() existed, and this class was conspicuously
|
||||
/// absent from DispatchPendingLogout's reset pipeline (contrast the peer
|
||||
/// ObjectQualityCache, which has both MaxEntries and a logout
|
||||
/// ClearSession()). Guids don't survive a session, so a daily
|
||||
/// multi-boxer accumulates entries indefinitely across relogs — worth
|
||||
/// closing given this stack's documented 32-bit VA-exhaustion
|
||||
/// sensitivity even though growth itself is slow. Call from
|
||||
/// DispatchPendingLogout alongside the other ResetSession() calls.
|
||||
/// </summary>
|
||||
public static void ClearSession()
|
||||
{
|
||||
lock (_cacheLock)
|
||||
{
|
||||
_appraisedGuids.Clear();
|
||||
_lastIdTime.Clear();
|
||||
_intCache.Clear();
|
||||
_boolCache.Clear();
|
||||
_stringCache.Clear();
|
||||
_spellIdCache.Clear();
|
||||
_failedRollLogged.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never.
|
||||
/// </summary>
|
||||
|
|
@ -228,37 +254,61 @@ internal static class AppraisalHooks
|
|||
try { RynthLog.Compat($"Compat: appraisal spell cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
CacheCreatureVitals(guid, profilePtr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void CacheIntProps(uint guid, IntPtr profilePtr)
|
||||
{
|
||||
if (profilePtr == IntPtr.Zero)
|
||||
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
|
||||
return;
|
||||
|
||||
// AppraisalProfile._intStatsTable* is at offset +0x18
|
||||
IntPtr intTablePtr = Marshal.ReadIntPtr(profilePtr + 0x18);
|
||||
if (intTablePtr == IntPtr.Zero)
|
||||
IntPtr intTableFieldAddr = profilePtr + 0x18;
|
||||
if (!ClientObjectHooks.IsReadablePointer(intTableFieldAddr))
|
||||
return;
|
||||
IntPtr intTablePtr = Marshal.ReadIntPtr(intTableFieldAddr);
|
||||
if (intTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(intTablePtr))
|
||||
return;
|
||||
|
||||
// PackableHashTable<uint,int>: bucket_array at +0x8, bucket_count at +0xC
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(intTablePtr + 0x08);
|
||||
int bucketCount = Marshal.ReadInt32(intTablePtr + 0x0C);
|
||||
IntPtr bucketArrayFieldAddr = intTablePtr + 0x08;
|
||||
IntPtr bucketCountFieldAddr = intTablePtr + 0x0C;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
|
||||
return;
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
|
||||
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
|
||||
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
|
||||
return;
|
||||
|
||||
var props = new Dictionary<uint, int>(8);
|
||||
|
||||
int totalGuard = 0;
|
||||
for (int i = 0; i < bucketCount; i++)
|
||||
{
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
|
||||
while (node != IntPtr.Zero)
|
||||
IntPtr bucketSlotAddr = bucketArray + i * 4;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
|
||||
|
||||
int chainGuard = 0;
|
||||
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
|
||||
{
|
||||
if (!ClientObjectHooks.IsReadablePointer(node)) break;
|
||||
uint key = (uint)Marshal.ReadInt32(node);
|
||||
int val = Marshal.ReadInt32(node + 4);
|
||||
props[key] = val;
|
||||
node = Marshal.ReadIntPtr(node + 8);
|
||||
IntPtr nextAddr = node + 8;
|
||||
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
|
||||
node = Marshal.ReadIntPtr(nextAddr);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -275,32 +325,47 @@ internal static class AppraisalHooks
|
|||
|
||||
private static void CacheBoolProps(uint guid, IntPtr profilePtr)
|
||||
{
|
||||
if (profilePtr == IntPtr.Zero)
|
||||
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
|
||||
return;
|
||||
|
||||
// AppraisalProfile._boolStatsTable* is at offset +0x20
|
||||
IntPtr boolTablePtr = Marshal.ReadIntPtr(profilePtr + 0x20);
|
||||
if (boolTablePtr == IntPtr.Zero)
|
||||
IntPtr boolTableFieldAddr = profilePtr + 0x20;
|
||||
if (!ClientObjectHooks.IsReadablePointer(boolTableFieldAddr))
|
||||
return;
|
||||
IntPtr boolTablePtr = Marshal.ReadIntPtr(boolTableFieldAddr);
|
||||
if (boolTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(boolTablePtr))
|
||||
return;
|
||||
|
||||
// PackableHashTable: bucket_array at +0x8, bucket_count at +0xC
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(boolTablePtr + 0x08);
|
||||
int bucketCount = Marshal.ReadInt32(boolTablePtr + 0x0C);
|
||||
IntPtr bucketArrayFieldAddr = boolTablePtr + 0x08;
|
||||
IntPtr bucketCountFieldAddr = boolTablePtr + 0x0C;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
|
||||
return;
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
|
||||
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
|
||||
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
|
||||
return;
|
||||
|
||||
var props = new Dictionary<uint, bool>(4);
|
||||
|
||||
int totalGuard = 0;
|
||||
for (int i = 0; i < bucketCount; i++)
|
||||
{
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
|
||||
while (node != IntPtr.Zero)
|
||||
IntPtr bucketSlotAddr = bucketArray + i * 4;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
|
||||
|
||||
int chainGuard = 0;
|
||||
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
|
||||
{
|
||||
if (!ClientObjectHooks.IsReadablePointer(node)) break;
|
||||
uint key = (uint)Marshal.ReadInt32(node);
|
||||
int val = Marshal.ReadInt32(node + 4);
|
||||
props[key] = val != 0;
|
||||
node = Marshal.ReadIntPtr(node + 8);
|
||||
IntPtr nextAddr = node + 8;
|
||||
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
|
||||
node = Marshal.ReadIntPtr(nextAddr);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -317,45 +382,65 @@ internal static class AppraisalHooks
|
|||
|
||||
private static void CacheStringProps(uint guid, IntPtr profilePtr)
|
||||
{
|
||||
if (profilePtr == IntPtr.Zero)
|
||||
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
|
||||
return;
|
||||
|
||||
// AppraisalProfile._strStatsTable* is at offset +0x28
|
||||
IntPtr strTablePtr = Marshal.ReadIntPtr(profilePtr + 0x28);
|
||||
if (strTablePtr == IntPtr.Zero)
|
||||
IntPtr strTableFieldAddr = profilePtr + 0x28;
|
||||
if (!ClientObjectHooks.IsReadablePointer(strTableFieldAddr))
|
||||
return;
|
||||
IntPtr strTablePtr = Marshal.ReadIntPtr(strTableFieldAddr);
|
||||
if (strTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(strTablePtr))
|
||||
return;
|
||||
|
||||
// PackableHashTable<uint, PStringBase<char>>: bucket_array at +0x8, bucket_count at +0xC
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(strTablePtr + 0x08);
|
||||
int bucketCount = Marshal.ReadInt32(strTablePtr + 0x0C);
|
||||
IntPtr bucketArrayFieldAddr = strTablePtr + 0x08;
|
||||
IntPtr bucketCountFieldAddr = strTablePtr + 0x0C;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
|
||||
return;
|
||||
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
|
||||
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
|
||||
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
|
||||
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
|
||||
return;
|
||||
|
||||
var props = new Dictionary<uint, string>(4);
|
||||
|
||||
int totalGuard = 0;
|
||||
for (int i = 0; i < bucketCount; i++)
|
||||
{
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
|
||||
while (node != IntPtr.Zero)
|
||||
IntPtr bucketSlotAddr = bucketArray + i * 4;
|
||||
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
|
||||
|
||||
int chainGuard = 0;
|
||||
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
|
||||
{
|
||||
if (!ClientObjectHooks.IsReadablePointer(node)) break;
|
||||
uint key = (uint)Marshal.ReadInt32(node);
|
||||
|
||||
// Node value at +4: PStringBase<char>.m_buffer (PSRefBuffer<char>*)
|
||||
// PSRefBuffer<char> layout: vtable(4) + m_cRef(4) + m_len(4) + m_size(4) + m_hash(4) + m_data[]
|
||||
IntPtr bufferPtr = Marshal.ReadIntPtr(node + 4);
|
||||
if (bufferPtr != IntPtr.Zero)
|
||||
if (bufferPtr != IntPtr.Zero && ClientObjectHooks.IsReadablePointer(bufferPtr))
|
||||
{
|
||||
int len = Marshal.ReadInt32(bufferPtr + 8);
|
||||
if (len > 1)
|
||||
IntPtr lenFieldAddr = bufferPtr + 8;
|
||||
if (ClientObjectHooks.IsReadablePointer(lenFieldAddr))
|
||||
{
|
||||
string? str = Marshal.PtrToStringAnsi(bufferPtr + 20, len - 1);
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
props[key] = str;
|
||||
int len = Marshal.ReadInt32(lenFieldAddr);
|
||||
IntPtr strDataAddr = bufferPtr + 20;
|
||||
if (len > 1 && len < 4096 && ClientObjectHooks.IsReadablePointer(strDataAddr))
|
||||
{
|
||||
string? str = Marshal.PtrToStringAnsi(strDataAddr, len - 1);
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
props[key] = str;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node = Marshal.ReadIntPtr(node + 8);
|
||||
IntPtr nextAddr = node + 8;
|
||||
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
|
||||
node = Marshal.ReadIntPtr(nextAddr);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -405,6 +490,86 @@ internal static class AppraisalHooks
|
|||
RynthLog.Verbose($"Compat: cached {mNum} spell ID(s) for guid=0x{guid:X8}");
|
||||
}
|
||||
|
||||
// Rate-limit counter for the creature-vitals diagnostic log line.
|
||||
private static int _creatureVitalsLogCount;
|
||||
// Guids already logged with a [FAILED-ROLL] line (dedupe; guarded by _cacheLock).
|
||||
private static readonly HashSet<uint> _failedRollLogged = new();
|
||||
|
||||
/// <summary>
|
||||
/// Reads the creature sub-profile (AppraisalProfile+0x08 → CreatureAppraisalProfile) for
|
||||
/// absolute Health/MaxHealth/Stamina/Mana and publishes them to ObjectQualityCache (polled
|
||||
/// via RynthCoreHost.TryGetTargetVitals) and to plugins (OnUpdateHealth push, e.g. RynthAi's
|
||||
/// CreatureProfileStore / RynthJuice numbers).
|
||||
///
|
||||
/// This is the ONLY opcode that carries a monster's *absolute* max HP — the 0xC9 appraisal
|
||||
/// CreatureProfile. The 0x01C0 combat stream is ratio-only (ACE divides Current/MaxValue
|
||||
/// server-side). This hook (CM_Examine::SendNotice_SetAppraiseInfo @ 0x006B05B0) is the live
|
||||
/// appraisal seam on ACE; the older wire-parse in CombatActionHooks.TryParseIdentifyResponse
|
||||
/// is dead (its InnerDispatcher caller is disabled and the SmartBox caller was removed).
|
||||
///
|
||||
/// Offsets verified from CreatureAppraisalProfile::InqAttribute2nd (decompile 0x005B6ED0):
|
||||
/// MaxHealth=+0x28 Health=+0x1C MaxStamina=+0x2C Stamina=+0x20 MaxMana=+0x30 Mana=+0x24.
|
||||
/// The +0x08 pointer is non-null only when the appraisal carried a CreatureProfile (creatures
|
||||
/// that are not NPCLooksLikeObject); items/hooks leave it 0 (AppraisalProfile::Clear layout).
|
||||
/// It is the engine's own live struct for this dispatch frame, so the read is safe under the
|
||||
/// same try/catch the sibling Cache* helpers use — no native call, no AC mutation.
|
||||
///
|
||||
/// Crucially this captures max even on a FAILED assess roll: ACE assigns Health/HealthMax
|
||||
/// before the success gate (CreatureProfile.cs), so no AssessCreature skill is required.
|
||||
/// </summary>
|
||||
private static void CacheCreatureVitals(uint guid, IntPtr profilePtr)
|
||||
{
|
||||
if (profilePtr == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
// AppraisalProfile._creatureProfile* is at offset +0x08.
|
||||
IntPtr creaturePtr = Marshal.ReadIntPtr(profilePtr + 0x08);
|
||||
if (creaturePtr == IntPtr.Zero)
|
||||
return; // non-creature appraisal (item / hook) — no vitals present
|
||||
|
||||
uint maxHealth = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x28));
|
||||
if (maxHealth == 0 || maxHealth >= 1_000_000)
|
||||
return; // unset / implausible — don't poison the cache
|
||||
|
||||
uint health = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x1C));
|
||||
uint stamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x20));
|
||||
uint maxStamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x2C));
|
||||
uint mana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x24));
|
||||
uint maxMana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x30));
|
||||
|
||||
if (health > maxHealth)
|
||||
health = maxHealth; // clamp a transient over-read
|
||||
|
||||
ObjectQualityCache.SetCreatureVitals(guid,
|
||||
new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana));
|
||||
|
||||
float ratio = (float)health / maxHealth;
|
||||
Plugins.PluginManager.QueueUpdateHealth(guid, ratio, health, maxHealth);
|
||||
|
||||
// ShowAttributes (wire flag 0x8) is CLEAR on a FAILED assess roll; CreatureAppraisalProfile::UnPack
|
||||
// (decompile 0x005B7240, lines 31-42) then EXPLICITLY zeroes stamina/mana/attributes — so
|
||||
// (maxStamina==0 && maxMana==0) is a reliable failed-roll signal, while Health/MaxHealth are written
|
||||
// unconditionally. A failed-roll line therefore PROVES the un-gated capture (max obtained with no
|
||||
// attributes). Failed rolls are rare (most mobs have Deception==0 → success forced) and are the whole
|
||||
// point of this hook, so log them ALWAYS (greppable [FAILED-ROLL] tag); rate-limit the common success case.
|
||||
if (maxStamina == 0 && maxMana == 0)
|
||||
{
|
||||
// Failed roll. Dedupe per guid — the combat target gets re-appraised ~1/0.75s, which would
|
||||
// otherwise spam the log (and bloat it over a grind). Log the first capture per mob only.
|
||||
bool firstForGuid;
|
||||
lock (_cacheLock)
|
||||
firstForGuid = _failedRollLogged.Add(guid);
|
||||
if (firstForGuid)
|
||||
RynthLog.Compat($"Compat: appraisal creature vitals [FAILED-ROLL] guid=0x{guid:X8} hp={health}/{maxHealth} (stam/mana withheld — max captured anyway)");
|
||||
}
|
||||
else
|
||||
{
|
||||
int log = Interlocked.Increment(ref _creatureVitalsLogCount);
|
||||
if (log <= 50)
|
||||
RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills <paramref name="output"/> with spell IDs from the last appraisal spell book.
|
||||
/// Returns the total number of spell IDs (may exceed <paramref name="maxCount"/>), or -1 if no data.
|
||||
|
|
|
|||
|
|
@ -41,6 +41,20 @@ internal static class AutoIdService
|
|||
RynthLog.Verbose("Compat: AutoIdService started.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose the drain timer at engine shutdown so it doesn't keep firing in
|
||||
/// the old generation's (intentionally still-mapped) module across hot-reloads.
|
||||
/// </summary>
|
||||
public static void Stop()
|
||||
{
|
||||
if (!_started)
|
||||
return;
|
||||
_started = false;
|
||||
_drainTimer?.Dispose();
|
||||
_drainTimer = null;
|
||||
RynthLog.Verbose("Compat: AutoIdService stopped.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour.
|
||||
/// </summary>
|
||||
|
|
@ -69,6 +83,9 @@ internal static class AutoIdService
|
|||
_sent.TryRemove(objectId, out _);
|
||||
}
|
||||
|
||||
// Last target we issued a priority appraisal for (fires once per target change).
|
||||
private static uint _lastPriorityTarget;
|
||||
|
||||
private static void DrainTick(object? state)
|
||||
{
|
||||
try
|
||||
|
|
@ -77,13 +94,30 @@ internal static class AutoIdService
|
|||
return;
|
||||
|
||||
int sent = 0;
|
||||
|
||||
// Combat-target priority: when the selected target CHANGES, appraise it
|
||||
// immediately — enqueued ahead of the create-order backlog so a fast kill
|
||||
// still gets its max-HP appraisal out first instead of waiting behind the
|
||||
// whole spawn. Fires once per change (guarded), so no per-tick re-appraisal.
|
||||
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
|
||||
if (target != 0 && target != _lastPriorityTarget)
|
||||
{
|
||||
_lastPriorityTarget = target;
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target))
|
||||
sent++;
|
||||
}
|
||||
|
||||
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
|
||||
{
|
||||
// Object may have been destroyed between enqueue and drain
|
||||
if (objectId == 0)
|
||||
continue;
|
||||
|
||||
ClientActionHooks.RequestId(objectId);
|
||||
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
|
||||
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic
|
||||
// UI-counter increment). EnqueueRequestId is the marshalled path.
|
||||
AcMainThreadQueue.EnqueueRequestId(objectId);
|
||||
sent++;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,15 +8,44 @@ namespace RynthCore.Engine.Compatibility;
|
|||
|
||||
internal static class BusyCountHooks
|
||||
{
|
||||
private const int IncrementBusyCountVa = 0x00565610;
|
||||
private const int DecrementBusyCountVa = 0x00565630;
|
||||
|
||||
// ClientUISystem::UpdateCursorState — per-frame cursor evaluation
|
||||
private const int UpdateCursorStateVa = 0x005653D0;
|
||||
// Fallback VAs (4,841,472-byte client). Pattern-scan is now the source of truth.
|
||||
private const int IncrementBusyCountFallbackVa = 0x00565610;
|
||||
private const int DecrementBusyCountFallbackVa = 0x00565630;
|
||||
private const int UpdateCursorStateFallbackVa = 0x005653D0;
|
||||
|
||||
// ClientUISystem struct field offset for m_cBusy (confirmed via runtime dump)
|
||||
private const int OffsetMCBusy = 0x14;
|
||||
|
||||
// ClientUISystem::IncrementBusyCount — entire function is short:
|
||||
// mov edx,[ecx+14]; inc edx; mov eax,edx; cmp eax,1; mov [ecx+14],edx;
|
||||
// jne +5; jmp UpdateCursorState; ret
|
||||
private static readonly byte?[] IncrementBusyCountPattern =
|
||||
[
|
||||
0x8B, 0x51, 0x14, 0x42, 0x8B, 0xC2, 0x83, 0xF8,
|
||||
0x01, 0x89, 0x51, 0x14, 0x75, 0x05,
|
||||
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
|
||||
0xC3
|
||||
];
|
||||
|
||||
// ClientUISystem::DecrementBusyCount — also short:
|
||||
// dec [ecx+14]; jne +5; jmp UpdateCursorState; ret
|
||||
private static readonly byte?[] DecrementBusyCountPattern =
|
||||
[
|
||||
0xFF, 0x49, 0x14, 0x75, 0x05,
|
||||
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
|
||||
0xC3
|
||||
];
|
||||
|
||||
// ClientUISystem::UpdateCursorState — large prologue with cmp/setcc pair.
|
||||
private static readonly byte?[] UpdateCursorStatePattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x55, 0x56, 0x57, 0x89,
|
||||
0x4C, 0x24, 0x10,
|
||||
0xE8, null, null, null, null, // call rel32
|
||||
0x85, 0xC0, 0x0F, 0x95, 0xC3, 0x33, 0xC0, 0x84,
|
||||
0xDB
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void BusyCountDelegate(IntPtr thisPtr);
|
||||
|
||||
|
|
@ -29,6 +58,7 @@ internal static class BusyCountHooks
|
|||
private static BusyCountDelegate? _decrementBusyCountDetour;
|
||||
private static IntPtr _incrementTargetAddress;
|
||||
private static IntPtr _decrementTargetAddress;
|
||||
private static IntPtr _updateCursorStateAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _incrementDispatchCount;
|
||||
private static int _decrementDispatchCount;
|
||||
|
|
@ -41,18 +71,67 @@ internal static class BusyCountHooks
|
|||
/// <summary>Returns 0 if the character is idle, positive if a UI action is in progress.</summary>
|
||||
public static int GetBusyState() => Math.Max(0, _netBusyCount);
|
||||
|
||||
/// <summary>Force-reset the client's busy count to zero and re-evaluate the cursor.
|
||||
/// Directly writes m_cBusy=0 then calls UpdateCursorState so the game
|
||||
/// switches from hourglass back to the default arrow.</summary>
|
||||
public static void ForceResetBusyCount()
|
||||
/// <summary>
|
||||
/// Force-reset the client's busy count to zero and re-evaluate the cursor.
|
||||
/// <paramref name="clearMotion"/> additionally flushes the command
|
||||
/// interpreter (ClearAllCommands/TakeControlFromServer/PlayerTeleported) —
|
||||
/// ⚠ DANGEROUS and OFF by default: AC only runs that triplet inside full
|
||||
/// teleport flows that also reset the physics sequence. Fired standalone
|
||||
/// around a live gesture it can leave the player's CSequence with a null
|
||||
/// current anim node → AC's next animation tick AVs at acclient 0x5264A9
|
||||
/// reading null+0xC (CSequence::update_internal). Diagnosed live
|
||||
/// 2026-06-11: the loot busy-watchdog called this every ~2s for an hour
|
||||
/// (every corpse open leaks +1 m_cBusy) and one clear landed in the
|
||||
/// gesture window. The busy UNSTICK itself only needs the decrement loop +
|
||||
/// cursor refresh below. Even when requested, the motion flush is skipped
|
||||
/// while a cast/action gesture is animating.
|
||||
/// </summary>
|
||||
// Session counters surfaced in the heartbeat so a soak shows the busy-fix
|
||||
// machinery working: fcl = force-clears performed, rec = cast/item-action
|
||||
// reconciles performed. A healthy post-fix soak should see rec climb during
|
||||
// combat/looting and fcl stay near-flat (force-clear is now just a backstop).
|
||||
private static long _forceClearCount;
|
||||
private static long _reconcileCount;
|
||||
public static long ForceClearCount => Interlocked.Read(ref _forceClearCount);
|
||||
public static long ReconcileCount => Interlocked.Read(ref _reconcileCount);
|
||||
|
||||
// Off-thread force-reset requests latch here and are consumed by
|
||||
// CheckWatchdog on the main thread (post-tick). ≤1 tick latency —
|
||||
// irrelevant for a 2-5s watchdog; coalesces bursts for free.
|
||||
private static int _forceResetRequested;
|
||||
|
||||
public static void ForceResetBusyCount(bool clearMotion = false)
|
||||
{
|
||||
// ⚠ MAIN THREAD ONLY (2026-06-12 cross-incident forensics, top-ranked
|
||||
// corruption writer): the plugin host API called this raw from the
|
||||
// pump thread 284-471×/session — up to 20 native DecrementBusyCount
|
||||
// calls (each falling through into UpdateCursorState's UI/object-graph
|
||||
// walk) plus a raw m_cBusy write, concurrent with AC's main thread.
|
||||
// Leading suspect for the LFH heap detonation (ntdll+0x87D99, free()
|
||||
// during object teardown, last off-thread clear ≤1s before the AV).
|
||||
// Off-thread callers latch a request consumed post-tick instead.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
Interlocked.Exchange(ref _forceResetRequested, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsInstalled || _lastThisPtr == IntPtr.Zero)
|
||||
return;
|
||||
Interlocked.Increment(ref _forceClearCount);
|
||||
|
||||
// Never mutate through a stale pointer: after logout/close AC frees the
|
||||
// ClientUISystem singleton, and the decrement/cursor calls below would
|
||||
// run native code against freed memory (uncatchable under NativeAOT).
|
||||
if (!ClientObjectHooks.IsReadablePointer(_lastThisPtr + OffsetMCBusy))
|
||||
{
|
||||
RynthLog.Compat("BusyCountHooks: ForceResetBusyCount skipped — cached ClientUISystem pointer is no longer readable.");
|
||||
_lastThisPtr = IntPtr.Zero;
|
||||
return;
|
||||
}
|
||||
|
||||
int was = _netBusyCount;
|
||||
|
||||
// Call the original decrement a few times to let the client run
|
||||
// its own cleanup path (cursor reset, etc) for any non-zero count.
|
||||
if (_originalDecrementBusyCount != null)
|
||||
{
|
||||
int calls = Math.Max(was, 3);
|
||||
|
|
@ -62,24 +141,35 @@ internal static class BusyCountHooks
|
|||
|
||||
Interlocked.Exchange(ref _netBusyCount, 0);
|
||||
|
||||
// Directly zero m_cBusy — DecrementBusyCount guards with if(m_cBusy>0)
|
||||
// so it's a no-op when our tracked count drifts from the real value.
|
||||
try { Marshal.WriteInt32(_lastThisPtr + OffsetMCBusy, 0); }
|
||||
catch { /* non-fatal */ }
|
||||
|
||||
// Clear pending commands and restore client control
|
||||
CommandInterpreterHooks.ClearAllCommands();
|
||||
CommandInterpreterHooks.TakeControlFromServer();
|
||||
CommandInterpreterHooks.PlayerTeleported();
|
||||
|
||||
// Force the game's own cursor evaluation with the cleared state
|
||||
try
|
||||
if (clearMotion)
|
||||
{
|
||||
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(
|
||||
new IntPtr(UpdateCursorStateVa));
|
||||
updateCursor(_lastThisPtr);
|
||||
bool gesture = false;
|
||||
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
|
||||
catch { gesture = false; }
|
||||
if (gesture)
|
||||
{
|
||||
RynthLog.Compat("BusyCountHooks: motion flush SKIPPED — a gesture is animating (the CSequence-corruption window).");
|
||||
}
|
||||
else
|
||||
{
|
||||
CommandInterpreterHooks.ClearAllCommands();
|
||||
CommandInterpreterHooks.TakeControlFromServer();
|
||||
CommandInterpreterHooks.PlayerTeleported();
|
||||
}
|
||||
}
|
||||
|
||||
if (_updateCursorStateAddress != IntPtr.Zero)
|
||||
{
|
||||
try
|
||||
{
|
||||
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress);
|
||||
updateCursor(_lastThisPtr);
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
|
||||
RynthLog.Verbose($"Compat: force-reset busy count (was {was})");
|
||||
}
|
||||
|
|
@ -95,75 +185,318 @@ internal static class BusyCountHooks
|
|||
return;
|
||||
}
|
||||
|
||||
int incrementOff = IncrementBusyCountVa - textSection.TextBaseVa;
|
||||
int decrementOff = DecrementBusyCountVa - textSection.TextBaseVa;
|
||||
if (!LooksHookable(textSection.Bytes, incrementOff, out byte incrementByte))
|
||||
{
|
||||
_statusMessage = $"ClientUISystem::IncrementBusyCount looks invalid @ 0x{IncrementBusyCountVa:X8}.";
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
var inc = HookResolver.Resolve(textSection, "BusyCountHooks.IncrementBusyCount",
|
||||
IncrementBusyCountPattern, IncrementBusyCountFallbackVa);
|
||||
var dec = HookResolver.Resolve(textSection, "BusyCountHooks.DecrementBusyCount",
|
||||
DecrementBusyCountPattern, DecrementBusyCountFallbackVa);
|
||||
var cursor = HookResolver.Resolve(textSection, "BusyCountHooks.UpdateCursorState",
|
||||
UpdateCursorStatePattern, UpdateCursorStateFallbackVa);
|
||||
|
||||
if (!LooksHookable(textSection.Bytes, decrementOff, out byte decrementByte))
|
||||
if (cursor.Success) _updateCursorStateAddress = cursor.Address;
|
||||
|
||||
if (!inc.Success || !dec.Success)
|
||||
{
|
||||
_statusMessage = $"ClientUISystem::DecrementBusyCount looks invalid @ 0x{DecrementBusyCountVa:X8}.";
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
|
||||
_statusMessage = $"Resolve failed — increment={inc.Detail}, decrement={dec.Detail}.";
|
||||
RynthLog.Compat($"BusyCountHooks: {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_incrementTargetAddress = new IntPtr(textSection.TextBaseVa + incrementOff);
|
||||
_incrementTargetAddress = inc.Address;
|
||||
_incrementBusyCountDetour = IncrementBusyCountDetour;
|
||||
IntPtr incrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_incrementBusyCountDetour);
|
||||
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
|
||||
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
|
||||
MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
|
||||
|
||||
_decrementTargetAddress = new IntPtr(textSection.TextBaseVa + decrementOff);
|
||||
_decrementTargetAddress = dec.Address;
|
||||
_decrementBusyCountDetour = DecrementBusyCountDetour;
|
||||
IntPtr decrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_decrementBusyCountDetour);
|
||||
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
|
||||
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
|
||||
MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
|
||||
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_incrementTargetAddress);
|
||||
MinHook.Enable(_decrementTargetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked busy-count seams @ 0x{_incrementTargetAddress.ToInt32():X8}/0x{_decrementTargetAddress.ToInt32():X8}.";
|
||||
RynthLog.Verbose($"Compat: busy-count hooks installed");
|
||||
_statusMessage = $"Hooked busy-count seams (inc=0x{_incrementTargetAddress.ToInt32():X8}, dec=0x{_decrementTargetAddress.ToInt32():X8}).";
|
||||
RynthLog.Compat($"BusyCountHooks: hooks installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: busy-count hook failed - {ex.Message}");
|
||||
RynthLog.Compat($"BusyCountHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int _incFires, _decFires;
|
||||
|
||||
// ── Auto-watchdog: force-clear busy if it stays >0 too long ──────────
|
||||
// Engine-side safety net so the bot self-heals when its busy tracking
|
||||
// desyncs from AC's m_cBusy (e.g., a hook miss, RDP-eaten chat input
|
||||
// preventing the user from running /ra clearbusy manually, or AC's
|
||||
// own busy state going stuck after a server-rejected action).
|
||||
//
|
||||
// Trigger: any of our main-thread detours can call CheckWatchdog().
|
||||
// SmartBoxHooks.DispatchGameEventDetour wires this in — it fires
|
||||
// frequently on AC's main thread while in-world, so the watchdog
|
||||
// gets a tick at least every server event.
|
||||
//
|
||||
// Heuristic: if busy has been positive for > BusyWatchdogTimeoutMs
|
||||
// with no transitions back to zero, fire ForceResetBusyCount. We
|
||||
// do this regardless of why it got stuck — combat-urgent or not —
|
||||
// because the alternative is an inert bot.
|
||||
private static long _busyBecamePositiveTickMs;
|
||||
private static long _lastWatchdogFireTickMs;
|
||||
private const long BusyWatchdogTimeoutMs = 5_000;
|
||||
private const long BusyWatchdogCooldownMs = 2_000;
|
||||
|
||||
// Real-field watchdog. The shadow counter (_netBusyCount) DESYNCS from AC's
|
||||
// real m_cBusy whenever AC mutates the field through a path we don't hook (or
|
||||
// a detour is missed): the counter drifts to ~0 while the real field stays
|
||||
// pinned > 0. A pinned real m_cBusy makes AC LOCALLY refuse combat-mode
|
||||
// changes (its SetCombatMode never even fires) and casts ("You're too
|
||||
// busy!") — wedging the bot in NonCombat (can't re-enter Magic to buff/fight)
|
||||
// with NEITHER counter-based watchdog firing, because the counter says idle.
|
||||
// So the watchdog must also trust the REAL field, read straight from
|
||||
// [ClientUISystem + OffsetMCBusy]. (Diagnosed 2026-06-09: SetCombatMode
|
||||
// stopped firing for 30+ min while ChangeCombatMode was re-sent and 191
|
||||
// "too busy" refusals piled up, yet zero force-clears — classic desync.)
|
||||
private static long _realBusyPositiveTickMs;
|
||||
private const long RealBusyWatchdogTimeoutMs = 4_000;
|
||||
|
||||
private static int ReadRealBusy()
|
||||
{
|
||||
IntPtr p = _lastThisPtr;
|
||||
if (p == IntPtr.Zero) return -1;
|
||||
// The try/catch below cannot catch a non-null-page AV under NativeAOT
|
||||
// (only null-page faults map to NullReferenceException). If AC freed
|
||||
// the ClientUISystem singleton (logout/close teardown) a stale pointer
|
||||
// read is fail-fast — probe the page first. TOCTOU-narrow but this is
|
||||
// a watchdog: skipping one beat is free.
|
||||
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return -1;
|
||||
try { return Marshal.ReadInt32(p + OffsetMCBusy); }
|
||||
catch { return -1; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drop the cached ClientUISystem pointer at logout / client-close so the
|
||||
/// watchdog and ForceResetBusyCount can't touch a freed singleton (the
|
||||
/// 0x0056547B close-AV class). The increment/decrement detours re-capture
|
||||
/// it on the next legit AC call.
|
||||
/// </summary>
|
||||
public static void ResetSession()
|
||||
{
|
||||
_lastThisPtr = IntPtr.Zero;
|
||||
Volatile.Write(ref _realBusyPositiveTickMs, 0);
|
||||
_pendingCastBusyDelta = 0;
|
||||
_pendingCastGestureSeen = false;
|
||||
}
|
||||
|
||||
// ── Direct-action busy reconciliation (source fix for the per-action leak) ──
|
||||
// The engine's direct AC calls — casts (FreeHandsAndCastSpell / CastSpell)
|
||||
// AND item actions (UseObject corpse-open / equip / item-use, UseObjectOn) —
|
||||
// make AC increment m_cBusy synchronously, but they never register the queued
|
||||
// action whose completion handler performs the matching decrements (that
|
||||
// lives in the player-initiated flow we bypass). Result: EVERY such call
|
||||
// leaked busy, caught only downstream by watchdogs (casts: 4322 plugin-side
|
||||
// clears in one 10h soak; corpse opens: a force-clear every ~2s during loot
|
||||
// grinds). Source fix: measure the real m_cBusy delta synchronously around
|
||||
// the call (both run on AC's main thread, nothing interleaves, so the delta
|
||||
// is exactly ours), then once the action GESTURE has completed
|
||||
// ([CMI+0x80] empties — a use-reach is a sequenced motion just like a cast
|
||||
// wind-up) — or after a timeout if it never starts (server refusal) — invoke
|
||||
// the REAL DecrementBusyCount exactly delta times through the HOOKED entry,
|
||||
// so the shadow counter and plugin busy events stay in sync. Deterministic,
|
||||
// no ClearAllCommands side effects, never touches counts owned by others.
|
||||
// A single accumulator serves both casts and item actions (all are
|
||||
// engine-issued busy that should clear at the next gesture-end).
|
||||
private static int _pendingCastBusyDelta;
|
||||
private static long _pendingCastIssuedAtMs;
|
||||
private static bool _pendingCastGestureSeen;
|
||||
private static int _reconcileLogCount;
|
||||
private const long CastBusyReconcileTimeoutMs = 4_000;
|
||||
|
||||
/// <summary>Snapshot the real m_cBusy immediately before a direct cast/item-action call (-1 = unreadable).</summary>
|
||||
public static int CaptureRealBusyForCast() => ReadRealBusy();
|
||||
|
||||
/// <summary>
|
||||
/// Arm reconciliation right after a direct cast/item-action call, given the
|
||||
/// pre-call snapshot. Main thread only (these calls already run there).
|
||||
/// </summary>
|
||||
public static void NoteDirectCastIssued(int busyBefore)
|
||||
{
|
||||
if (busyBefore < 0) return;
|
||||
int after = ReadRealBusy();
|
||||
if (after < 0) return;
|
||||
int delta = after - busyBefore;
|
||||
if (delta <= 0) return;
|
||||
_pendingCastBusyDelta += delta;
|
||||
_pendingCastIssuedAtMs = Environment.TickCount64;
|
||||
_pendingCastGestureSeen = false;
|
||||
}
|
||||
|
||||
private static void ReconcileCastBusy(long now)
|
||||
{
|
||||
int pending = _pendingCastBusyDelta;
|
||||
if (pending <= 0) return;
|
||||
|
||||
bool gesture = false;
|
||||
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
|
||||
catch { gesture = false; }
|
||||
|
||||
if (gesture)
|
||||
{
|
||||
// Cast animation running — completion is the decrement point.
|
||||
_pendingCastGestureSeen = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Decrement once the observed gesture has ENDED, or after the timeout
|
||||
// when no gesture was ever seen (refused cast / instant failure). The
|
||||
// timeout matches the real-field watchdog window, so worst case this
|
||||
// path is no slower than the old crutch.
|
||||
if (!_pendingCastGestureSeen && now - _pendingCastIssuedAtMs <= CastBusyReconcileTimeoutMs)
|
||||
return;
|
||||
|
||||
_pendingCastBusyDelta = 0;
|
||||
_pendingCastGestureSeen = false;
|
||||
|
||||
IntPtr p = _lastThisPtr;
|
||||
if (p == IntPtr.Zero || _decrementTargetAddress == IntPtr.Zero) return;
|
||||
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return;
|
||||
|
||||
// Clamp to the live field — if AC (or a watchdog) already cleared part
|
||||
// of it, never push m_cBusy negative.
|
||||
int real = ReadRealBusy();
|
||||
int n = Math.Min(pending, real);
|
||||
if (n <= 0) return;
|
||||
|
||||
try
|
||||
{
|
||||
// Call the HOOKED decrement entry (not the trampoline): our detour
|
||||
// fires, so _netBusyCount and the plugin busy-decremented events
|
||||
// stay consistent for free.
|
||||
var dec = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(_decrementTargetAddress);
|
||||
for (int i = 0; i < n; i++) dec(p);
|
||||
Interlocked.Increment(ref _reconcileCount);
|
||||
if (_reconcileLogCount < 50 || _reconcileLogCount % 100 == 0)
|
||||
RynthLog.Compat($"BusyCountHooks: direct-action busy reconciled — decremented {n} (real now {ReadRealBusy()}, total reconciles {_reconcileLogCount + 1}).");
|
||||
_reconcileLogCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Auto-clear busy state if it has been positive for too long.
|
||||
/// Safe to call from any thread; only performs work on AC's main
|
||||
/// thread (via MainThreadGuard) since ForceResetBusyCount writes
|
||||
/// AC memory and calls AC functions that aren't thread-safe.
|
||||
/// </summary>
|
||||
public static void CheckWatchdog()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
|
||||
// ── Real-field watchdog (catches counter desync) ─────────────────────
|
||||
// Trust AC's REAL m_cBusy over our shadow counter: when they diverge a
|
||||
// pinned real field is what actually wedges the client (mode-change /
|
||||
// cast refusal) while _netBusyCount reads ~0 and the counter watchdog
|
||||
// below never fires. A legit action returns the field to 0 within ~2-3s
|
||||
// (resetting the timer); only a genuinely stuck field reaches the 4s
|
||||
// timeout. Field read is harmless off-thread, but ForceResetBusyCount
|
||||
// mutates AC, so only clear on the main thread.
|
||||
if (MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
// Reconcile our own cast increments FIRST — a clean deterministic
|
||||
// decrement here means the stuck-field watchdog below (and the
|
||||
// plugin-side clears) have nothing left to catch.
|
||||
ReconcileCastBusy(now);
|
||||
|
||||
// Consume any off-thread force-reset request (plugin watchdogs):
|
||||
// the actual clear runs HERE, on the main thread.
|
||||
if (Interlocked.Exchange(ref _forceResetRequested, 0) == 1)
|
||||
ForceResetBusyCount();
|
||||
|
||||
int realBusy = ReadRealBusy();
|
||||
if (realBusy > 0)
|
||||
{
|
||||
long sinceR = Volatile.Read(ref _realBusyPositiveTickMs);
|
||||
if (sinceR == 0)
|
||||
{
|
||||
Volatile.Write(ref _realBusyPositiveTickMs, now);
|
||||
}
|
||||
else if (now - sinceR > RealBusyWatchdogTimeoutMs
|
||||
&& now - Volatile.Read(ref _lastWatchdogFireTickMs) > BusyWatchdogCooldownMs)
|
||||
{
|
||||
Volatile.Write(ref _lastWatchdogFireTickMs, now);
|
||||
RynthLog.Compat($"BusyCountHooks: REAL m_cBusy stuck at {realBusy} for {now - sinceR}ms (counter={_netBusyCount}) — force-clearing desync.");
|
||||
ForceResetBusyCount();
|
||||
Volatile.Write(ref _realBusyPositiveTickMs, 0);
|
||||
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 0 = idle; -1 = unreadable (no pointer / freed page). Either
|
||||
// way disarm the timer — leaving it armed across an unreadable
|
||||
// stretch caused an instant force-clear when reads resumed
|
||||
// (e.g. first beat after the next login).
|
||||
Volatile.Write(ref _realBusyPositiveTickMs, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Counter-based watchdog (original) ────────────────────────────────
|
||||
long stuckSince = Volatile.Read(ref _busyBecamePositiveTickMs);
|
||||
if (stuckSince == 0)
|
||||
return;
|
||||
|
||||
long elapsed = now - stuckSince;
|
||||
if (elapsed < BusyWatchdogTimeoutMs)
|
||||
return;
|
||||
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return;
|
||||
|
||||
long lastFire = Volatile.Read(ref _lastWatchdogFireTickMs);
|
||||
if (now - lastFire < BusyWatchdogCooldownMs)
|
||||
return;
|
||||
|
||||
Volatile.Write(ref _lastWatchdogFireTickMs, now);
|
||||
RynthLog.Compat($"BusyCountHooks: watchdog auto-resetting — busy stuck at {_netBusyCount} for {elapsed}ms.");
|
||||
ForceResetBusyCount();
|
||||
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
|
||||
}
|
||||
|
||||
private static void IncrementBusyCountDetour(IntPtr thisPtr)
|
||||
{
|
||||
RecursionGuard.Tick("BusyCountHooks.Increment");
|
||||
_lastThisPtr = thisPtr;
|
||||
_originalIncrementBusyCount!(thisPtr);
|
||||
if (++_incFires <= 3)
|
||||
RynthLog.Compat($"BusyCountHooks: Increment fired #{_incFires} this=0x{thisPtr.ToInt32():X8}");
|
||||
try { _originalIncrementBusyCount!(thisPtr); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Increment original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
|
||||
Interlocked.Increment(ref _incrementDispatchCount);
|
||||
Interlocked.Increment(ref _netBusyCount);
|
||||
int after = Interlocked.Increment(ref _netBusyCount);
|
||||
if (after == 1)
|
||||
Volatile.Write(ref _busyBecamePositiveTickMs, Environment.TickCount64);
|
||||
PluginManager.QueueBusyCountIncremented();
|
||||
}
|
||||
|
||||
private static void DecrementBusyCountDetour(IntPtr thisPtr)
|
||||
{
|
||||
RecursionGuard.Tick("BusyCountHooks.Decrement");
|
||||
if (_lastThisPtr == IntPtr.Zero)
|
||||
_lastThisPtr = thisPtr;
|
||||
_originalDecrementBusyCount!(thisPtr);
|
||||
if (++_decFires <= 3)
|
||||
RynthLog.Compat($"BusyCountHooks: Decrement fired #{_decFires} this=0x{thisPtr.ToInt32():X8}");
|
||||
try { _originalDecrementBusyCount!(thisPtr); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Decrement original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
|
||||
Interlocked.Increment(ref _decrementDispatchCount);
|
||||
Interlocked.Decrement(ref _netBusyCount);
|
||||
int after = Interlocked.Decrement(ref _netBusyCount);
|
||||
if (after <= 0)
|
||||
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
|
||||
PluginManager.QueueBusyCountDecremented();
|
||||
}
|
||||
|
||||
private static bool LooksHookable(byte[] textBytes, int offset, out byte firstByte)
|
||||
{
|
||||
firstByte = 0;
|
||||
if (offset < 0 || offset >= textBytes.Length)
|
||||
return false;
|
||||
|
||||
firstByte = textBytes[offset];
|
||||
return firstByte is not (0x00 or 0xCC or 0xC3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
220
src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs
Normal file
220
src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Enumerates AC's authoritative world-object table via CObjectMaint.
|
||||
///
|
||||
/// Primary use: seed PluginManager._liveObjects on hot-reload, since the new
|
||||
/// engine module's static state starts empty after a reload. Walking the
|
||||
/// maintainer gives an immediate snapshot of every weenie the client knows
|
||||
/// about so we can replay create-object events to a freshly loaded plugin
|
||||
/// without waiting for new spawn/visibility events.
|
||||
///
|
||||
/// Secondary use: reconciliation / drift detection — even on cold start, if
|
||||
/// any CreateObject hook fires miss the live-object set the maintainer is
|
||||
/// authoritative and catches the omission.
|
||||
///
|
||||
/// Singleton: CObjectMaint::s_pcInstance @ 0x00842ADC (CObjectMaint**)
|
||||
///
|
||||
/// CObjectMaint layout (from Chorizite acclient.map + struct defs):
|
||||
/// +0x00 Interface a0 (vtable*, 4)
|
||||
/// +0x04 NoticeHandler a1 (vtable*, 4)
|
||||
/// +0x08 Turbine_RefCount (vtable + m_cRef, 8)
|
||||
/// +0x10 is_active (Int32, 4)
|
||||
/// +0x14 lost_cell_table (IntrusiveHashTable, 112)
|
||||
/// +0x84 object_table (LongHash<CPhysicsObj>, 24)
|
||||
/// +0x9C null_object_table (LongHash<CPhysicsObj>, 24)
|
||||
/// +0xB4 weenie_object_table (LongHash<CWeenieObject>, 24)
|
||||
///
|
||||
/// HashBase<UInt32> layout (LongHash wraps this):
|
||||
/// +0 vfptr
|
||||
/// +4 table_mask
|
||||
/// +8 key_shift
|
||||
/// +12 buckets (HashBaseData<UInt32>**)
|
||||
/// +16 table_size
|
||||
/// +20 fPlacementNew_
|
||||
///
|
||||
/// HashBaseData<UInt32> layout:
|
||||
/// +0 vfptr
|
||||
/// +4 hash_next
|
||||
/// +8 id (UInt32)
|
||||
/// </summary>
|
||||
internal static class CObjectMaintHooks
|
||||
{
|
||||
private const int S_PC_INSTANCE_VA = 0x00842ADC;
|
||||
private const int WEENIE_OBJECT_TABLE_OFFSET = 0xB4;
|
||||
// DIAGNOSTIC (temporary): the CPhysicsObj table — superset of physics
|
||||
// objects, including ones whose weenie isn't registered in
|
||||
// weenie_object_table yet (the suspected missing-monster set).
|
||||
private const int OBJECT_TABLE_OFFSET = 0x84;
|
||||
private const int HASHBASE_BUCKETS_OFFSET = 12;
|
||||
private const int HASHBASE_TABLE_SIZE_OFFSET = 16;
|
||||
private const int HASHBASEDATA_HASH_NEXT_OFFSET = 4;
|
||||
private const int HASHBASEDATA_ID_OFFSET = 8;
|
||||
|
||||
// Sanity bounds — table_size larger than this almost certainly means
|
||||
// we're reading garbage (real AC tables are typically 1k-8k buckets).
|
||||
private const int MaxBuckets = 65536;
|
||||
private const int MaxChainPerBucket = 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Walks CObjectMaint::weenie_object_table and invokes <paramref name="visit"/> for each
|
||||
/// known object id. Returns the number of ids visited, or -1 if the maintainer or
|
||||
/// table layout couldn't be read safely.
|
||||
/// </summary>
|
||||
public static int EnumerateLiveWeenieObjectIds(Action<uint> visit)
|
||||
{
|
||||
if (visit == null) return -1;
|
||||
|
||||
IntPtr maintainer = ReadMaintainer();
|
||||
if (maintainer == IntPtr.Zero)
|
||||
return -1;
|
||||
|
||||
IntPtr tablePtr = maintainer + WEENIE_OBJECT_TABLE_OFFSET;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
|
||||
return -1;
|
||||
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
|
||||
if (buckets == IntPtr.Zero)
|
||||
return -1;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
|
||||
return -1;
|
||||
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
|
||||
if (tableSize == 0 || tableSize > MaxBuckets)
|
||||
return -1;
|
||||
|
||||
int count = 0;
|
||||
try
|
||||
{
|
||||
for (uint i = 0; i < tableSize; i++)
|
||||
{
|
||||
IntPtr bucketSlot = buckets + (int)(i * 4);
|
||||
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
|
||||
break;
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
|
||||
|
||||
int chainGuard = 0;
|
||||
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
|
||||
{
|
||||
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
|
||||
break;
|
||||
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
|
||||
if (id != 0)
|
||||
{
|
||||
visit(id);
|
||||
count++;
|
||||
}
|
||||
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
|
||||
break;
|
||||
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CObjectMaint enumerate threw {ex.GetType().Name}: {ex.Message}");
|
||||
return count > 0 ? count : -1;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
// DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over
|
||||
// an arbitrary CObjectMaint table (object_table +0x84 / null_object_table
|
||||
// +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the
|
||||
// tested enumerator. Remove with the diagnostic.
|
||||
public static int EnumerateTableIds(int tableOffset, Action<uint> visit)
|
||||
{
|
||||
if (visit == null) return -1;
|
||||
|
||||
IntPtr maintainer = ReadMaintainer();
|
||||
if (maintainer == IntPtr.Zero)
|
||||
return -1;
|
||||
|
||||
IntPtr tablePtr = maintainer + tableOffset;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
|
||||
return -1;
|
||||
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
|
||||
if (buckets == IntPtr.Zero)
|
||||
return -1;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
|
||||
return -1;
|
||||
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
|
||||
if (tableSize == 0 || tableSize > MaxBuckets)
|
||||
return -1;
|
||||
|
||||
int count = 0;
|
||||
try
|
||||
{
|
||||
for (uint i = 0; i < tableSize; i++)
|
||||
{
|
||||
IntPtr bucketSlot = buckets + (int)(i * 4);
|
||||
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
|
||||
break;
|
||||
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
|
||||
|
||||
int chainGuard = 0;
|
||||
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
|
||||
{
|
||||
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
|
||||
break;
|
||||
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
|
||||
if (id != 0)
|
||||
{
|
||||
visit(id);
|
||||
count++;
|
||||
}
|
||||
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
|
||||
break;
|
||||
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CObjectMaint object-table enumerate threw {ex.GetType().Name}: {ex.Message}");
|
||||
return count > 0 ? count : -1;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
// Phase B: resolve s_pcInstance's address by code-xref ("mov ecx,[s_pcInstance]" =
|
||||
// 8B 0D <addr>), operand at offset 2; the VA stays as fallback. Resolved lazily once.
|
||||
private static readonly byte?[] PatXrefInstancePP = [ 0x8B, 0x0D, null, null, null, null, 0x55, 0xE8 ];
|
||||
private static int _instancePPAddr;
|
||||
|
||||
private static int InstancePPAddr()
|
||||
{
|
||||
if (_instancePPAddr == 0)
|
||||
{
|
||||
_instancePPAddr = S_PC_INSTANCE_VA;
|
||||
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
_instancePPAddr = HookResolver.ResolveData(text, "CObjectMaint.s_pcInstance", PatXrefInstancePP, 2, S_PC_INSTANCE_VA).Address.ToInt32();
|
||||
}
|
||||
return _instancePPAddr;
|
||||
}
|
||||
|
||||
private static IntPtr ReadMaintainer()
|
||||
{
|
||||
IntPtr instancePP = new IntPtr(InstancePPAddr());
|
||||
if (!SmartBoxLocator.IsMemoryReadable(instancePP, 4))
|
||||
return IntPtr.Zero;
|
||||
IntPtr maintainer = Marshal.ReadIntPtr(instancePP);
|
||||
if (maintainer == IntPtr.Zero)
|
||||
return IntPtr.Zero;
|
||||
|
||||
if (!SmartBoxLocator.IsMemoryReadable(maintainer, 4))
|
||||
return IntPtr.Zero;
|
||||
IntPtr vtable = Marshal.ReadIntPtr(maintainer);
|
||||
if (!SmartBoxLocator.IsPointerInModule(vtable))
|
||||
return IntPtr.Zero;
|
||||
|
||||
return maintainer;
|
||||
}
|
||||
}
|
||||
89
src/RynthCore.Engine/Compatibility/CastGate.cs
Normal file
89
src/RynthCore.Engine/Compatibility/CastGate.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// The real spell-cast gate for RynthAi buff/combat recasts.
|
||||
///
|
||||
/// Problem: AC refuses a cast issued while the player is mid cast-gesture
|
||||
/// animation with a server-driven "You're too busy!" text notice. A tight
|
||||
/// clear-and-recast retry loop on that refusal re-enters AC's AddTextToScroll
|
||||
/// and produces the visible 0x00460D1D write-AV after long uptime.
|
||||
///
|
||||
/// AC's ClientUISystem busy-count (<see cref="BusyCountHooks"/>) is the
|
||||
/// hourglass/cursor state, NOT the cast gate — it reads 0 while AC still says
|
||||
/// "too busy". The true LOCAL gate is the cast GESTURE: CMotionInterp's
|
||||
/// sequenced/one-shot motion queue is non-empty while the wind-up/release
|
||||
/// animates and empties when it completes (offline RE of acclient.exe; see
|
||||
/// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>).
|
||||
///
|
||||
/// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/>
|
||||
/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll)
|
||||
/// and reads a single CMotionInterp scalar through the already-proven
|
||||
/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
|
||||
/// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at
|
||||
/// the same tick rate, so the busy→idle edge is observed without any new
|
||||
/// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class).
|
||||
/// </summary>
|
||||
internal static class CastGate
|
||||
{
|
||||
private static int _castBusy; // 0 = clear to cast, 1 = gesture in progress
|
||||
private static int _reachable; // 1 once CMotionInterp has ever been read
|
||||
private static long _gestureCount;
|
||||
private static string _statusMessage = "Not sampled yet.";
|
||||
|
||||
public static bool IsInitialized => Volatile.Read(ref _reachable) == 1;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
/// <summary>Number of cast/action gestures observed completing this session.</summary>
|
||||
public static long GestureCount => Interlocked.Read(ref _gestureCount);
|
||||
|
||||
/// <summary>
|
||||
/// 0 = clear to cast, 1 = a cast/action gesture is in progress. Mirrors
|
||||
/// <see cref="BusyCountHooks.GetBusyState"/> for the host-API pull path.
|
||||
/// </summary>
|
||||
public static int GetCastBusyState() => Volatile.Read(ref _castBusy);
|
||||
|
||||
/// <summary>
|
||||
/// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully
|
||||
/// guarded, never throws. If CMotionInterp isn't reachable (pre-login /
|
||||
/// between worlds) the gate reports "clear to cast" so the consumer falls
|
||||
/// back to its own throttle/park, which is the hard anti-spam guarantee.
|
||||
/// </summary>
|
||||
public static void Sample()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool inProgress))
|
||||
{
|
||||
Volatile.Write(ref _castBusy, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _reachable, 1);
|
||||
|
||||
int was = Volatile.Read(ref _castBusy);
|
||||
int now = inProgress ? 1 : 0;
|
||||
if (now == was)
|
||||
return;
|
||||
|
||||
Volatile.Write(ref _castBusy, now);
|
||||
if (now == 1)
|
||||
{
|
||||
_statusMessage = "Cast gesture in progress.";
|
||||
}
|
||||
else
|
||||
{
|
||||
Interlocked.Increment(ref _gestureCount);
|
||||
_statusMessage = "Ready (gate open).";
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The gate must never destabilise the pump. Default to clear-to-cast;
|
||||
// the consumer's throttle still bounds retries.
|
||||
Volatile.Write(ref _castBusy, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,14 +28,46 @@ internal static class CharacterCaptureHooks
|
|||
private const int XCharList = 121;
|
||||
private const int YTopOfBox = 209;
|
||||
private const int YBottomOfBox = 532;
|
||||
private const int AutoLoginDelayMs = 800;
|
||||
private const int AutoLoginDelayMs = 2000;
|
||||
private const int AutoLoginWindowWaitMs = 10000;
|
||||
private const int AutoLoginWindowPollMs = 250;
|
||||
private const int AutoLoginAttempts = 3;
|
||||
private const int AutoLoginAttempts = 15;
|
||||
private const int AutoLoginAttemptDelayMs = 600;
|
||||
private const int AutoLoginDoubleClickGapMs = 100;
|
||||
private const int DirectAutoLoginAttempts = 40;
|
||||
private const int DirectAutoLoginAttemptDelayMs = 250;
|
||||
private const int CharacterManagementUIMode = 0x1000000A;
|
||||
private const int GamePlayUIMode = 0x10000008;
|
||||
|
||||
// Poll-driven auto-login. The packet-driven path (ScheduleAutoLoginIfRequested,
|
||||
// fed by InnerDispatcherDetour) is dead on this client: InnerDispatcherHook was
|
||||
// disabled 2026-05-14 because its pattern walk-back stalls ACE in "Entering
|
||||
// World", and SmartBox does not carry the pre-login 0xF658 char-list packet.
|
||||
// Result: zero CharacterCapture activity, auto-login never fired. This poll
|
||||
// drives login off the native CharacterSet directly (CharacterManagementHooks),
|
||||
// which needs no packet — it just watches the UIFlow mode and retries until
|
||||
// login completes. Replaces the dead trigger; the packet path is left intact
|
||||
// (harmless, never invoked) in case InnerDispatcher is ever re-enabled.
|
||||
private const int AutoLoginPollIntervalMs = 600;
|
||||
private const int AutoLoginPollHardTimeoutMs = 120_000;
|
||||
private const int AutoLoginDirectFailsBeforeClick = 4;
|
||||
private static int _autoLoginPollStarted;
|
||||
|
||||
// Native character-list capture. The 0xF658 packet path is dead (see above),
|
||||
// so ParseAndSaveCharacterList never runs and the launcher's cache
|
||||
// (characters_<server>_<account>.json) was only written by SessionStateRegistry's
|
||||
// login upsert, which records just the launch context's TargetCharacter. An
|
||||
// account launched with no character picked therefore never got a cache file
|
||||
// and its launcher dropdown stayed empty. This poll reads the list straight
|
||||
// from AC's native CharacterSet while char-select is up, whether or not
|
||||
// auto-login is armed. In the world it only checks a managed flag; the native
|
||||
// set is read only in CharacterManagementUI. Logout back to char-select
|
||||
// (LoginLifecycleHooks.ResetObservation) re-arms it, so a new or deleted
|
||||
// character is picked up too. The file is rewritten only when the list changes.
|
||||
private const int CharacterListCapturePollIntervalMs = 500;
|
||||
private static int _characterListCapturePollStarted;
|
||||
private static readonly object CharacterListCaptureLock = new();
|
||||
private static string _lastCharacterListCaptureKey = string.Empty;
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
|
|
@ -61,6 +93,266 @@ internal static class CharacterCaptureHooks
|
|||
|
||||
private static int _autoLoginScheduled;
|
||||
|
||||
// Latches once auto-login has fired in this process. The character-list packet
|
||||
// (0xF658) arrives every time the client sees char-select — including the
|
||||
// logout-to-char-select transition — and without this latch we'd re-trigger
|
||||
// auto-login the moment the user manually logs out. One-shot per process: if
|
||||
// the user wants to swap characters, they can pick from char-select manually,
|
||||
// or relaunch.
|
||||
private static int _autoLoginEverFired;
|
||||
|
||||
/// <summary>
|
||||
/// Starts the character-list capture poll (always) and the poll-driven
|
||||
/// auto-login worker. Call once from InitWorker. Auto-login no-ops if no
|
||||
/// TargetCharacter is configured in the launch context, or if the worker is
|
||||
/// already running. Safe to call before the client window or char-select UI
|
||||
/// exists — both workers wait for them.
|
||||
/// </summary>
|
||||
public static void Initialize()
|
||||
{
|
||||
StartCharacterListCapturePoll();
|
||||
|
||||
(_, _, string targetCharacter) = ReadLaunchContext();
|
||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
{
|
||||
RynthLog.Verbose("CharacterCapture: Initialize - no TargetCharacter in launch context; auto-login disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0)
|
||||
return;
|
||||
|
||||
var thread = new Thread(AutoLoginPollLoop)
|
||||
{
|
||||
Name = "RynthCore.AutoLoginPoll",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches the native UIFlow mode and drives LogOnCharacter directly off
|
||||
/// AC's native CharacterSet. Retries every tick while char-select is up,
|
||||
/// so a too-early attempt or a missed click just gets re-tried — until
|
||||
/// login completes, the client enters the world, or the hard timeout hits.
|
||||
/// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed:
|
||||
/// poking LogOn pointers while in-game has been correlated with AC self-
|
||||
/// exiting (see ScheduleAutoLoginIfRequested's notes).
|
||||
/// </summary>
|
||||
private static void AutoLoginPollLoop()
|
||||
{
|
||||
(_, _, string targetCharacter) = ReadLaunchContext();
|
||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
return;
|
||||
|
||||
long charSelectFirstSeenTick = 0;
|
||||
int directFailCount = 0;
|
||||
bool issuedDirect = false;
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Thread.Sleep(AutoLoginPollIntervalMs);
|
||||
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' (LoginComplete observed).");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
// One-shot: if the (currently dead) packet path ever fires and
|
||||
// latches, stand down so we don't double-drive.
|
||||
if (Volatile.Read(ref _autoLoginEverFired) != 0)
|
||||
{
|
||||
RynthLog.Verbose($"CharacterCapture: Poll standing down for '{targetCharacter}' - auto-login already fired elsewhere.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode))
|
||||
continue; // UIFlow not ready yet — keep waiting.
|
||||
|
||||
if (mode == GamePlayUIMode)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Poll stopping for '{targetCharacter}' - client already in GamePlayUI.");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode != CharacterManagementUIMode)
|
||||
{
|
||||
// Still in connect/logo/transition — don't start the timeout
|
||||
// clock until char-select has actually appeared.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (charSelectFirstSeenTick == 0)
|
||||
{
|
||||
charSelectFirstSeenTick = Environment.TickCount64;
|
||||
RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'.");
|
||||
}
|
||||
|
||||
// Save the account's character list before logging on, so the
|
||||
// launcher cache is written even when auto-login is quick.
|
||||
TryCaptureNativeCharacterList();
|
||||
|
||||
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
|
||||
// No packet required. Retries every tick if it didn't take.
|
||||
if (CharacterManagementHooks.TryLogOnCharacter(
|
||||
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out string status))
|
||||
{
|
||||
if (!issuedDirect)
|
||||
{
|
||||
issuedDirect = true;
|
||||
RynthLog.Info($"CharacterCapture: Issued LogOnCharacter for '{matched}' (target '{targetCharacter}', avatar 0x{avatarId:X8}). Awaiting world entry.");
|
||||
}
|
||||
directFailCount = 0;
|
||||
// Keep looping — watch for LoginComplete/GamePlayUI. If the
|
||||
// issue didn't take, next ticks will re-issue.
|
||||
}
|
||||
else
|
||||
{
|
||||
directFailCount++;
|
||||
RynthLog.Verbose($"CharacterCapture: Direct auto-login attempt {directFailCount} for '{targetCharacter}' - {status}");
|
||||
|
||||
// Direct keeps failing (native set not readable / name not
|
||||
// matched yet). Fall back to a char-list double-click, but
|
||||
// only when we know the slot — slotIndex is set when the
|
||||
// name matched in the native set; otherwise use the packet-
|
||||
// cached index is unavailable here so skip until known.
|
||||
if (directFailCount >= AutoLoginDirectFailsBeforeClick && slotIndex >= 0)
|
||||
{
|
||||
int slotCount = CharacterManagementHooks.GetNativeCharacterSetSlotCount();
|
||||
if (slotCount > 0)
|
||||
TryClickCharacterSlot(targetCharacter, slotIndex, slotCount);
|
||||
directFailCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (charSelectFirstSeenTick != 0 &&
|
||||
Environment.TickCount64 - charSelectFirstSeenTick > AutoLoginPollHardTimeoutMs)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' gave up after {AutoLoginPollHardTimeoutMs / 1000}s at char-select. Last status: {status}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login poll loop crashed - {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _autoLoginPollStarted, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void StartCharacterListCapturePoll()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
|
||||
return;
|
||||
|
||||
var thread = new Thread(CharacterListCapturePollLoop)
|
||||
{
|
||||
Name = "RynthCore.CharacterListCapture",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private static void CharacterListCapturePollLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!EngineLifecycle.IsShuttingDown)
|
||||
{
|
||||
Thread.Sleep(CharacterListCapturePollIntervalMs);
|
||||
|
||||
// In the world: no native reads at all.
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
continue;
|
||||
|
||||
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode) || mode != CharacterManagementUIMode)
|
||||
continue;
|
||||
|
||||
TryCaptureNativeCharacterList();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Character-list capture poll crashed - {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _characterListCapturePollStarted, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the character list from AC's native CharacterSet (char-select only)
|
||||
/// and saves it to the launcher's character cache for this client's
|
||||
/// account/server. Writes only when the list differs from the last one seen
|
||||
/// in this process. Safe to call from any poll thread.
|
||||
/// </summary>
|
||||
private static void TryCaptureNativeCharacterList()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!CharacterManagementHooks.TryReadCharacterNames(out List<string> characters))
|
||||
return;
|
||||
|
||||
lock (CharacterListCaptureLock)
|
||||
{
|
||||
string key = string.Join("\n", characters);
|
||||
if (string.Equals(key, _lastCharacterListCaptureKey, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
_lastCharacterListCaptureKey = key;
|
||||
RynthLog.Info($"CharacterCapture: Native character set has {characters.Count} chars: {string.Join(", ", characters)}");
|
||||
|
||||
(string accountName, string serverName, _) = ReadLaunchContext();
|
||||
SaveCharacterList(characters, accountName, serverName);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Native character-list capture failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Single char-list double-click at the slot for <paramref name="slotIndex"/>.
|
||||
/// Fallback for when the direct native LogOnCharacter path isn't taking.
|
||||
/// </summary>
|
||||
private static void TryClickCharacterSlot(string targetCharacter, int slotIndex, int slotCount)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int m) && m == GamePlayUIMode)
|
||||
return;
|
||||
|
||||
IntPtr hwnd = WaitForGameWindow();
|
||||
if (hwnd == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
SetForegroundWindow(hwnd);
|
||||
|
||||
float nameSize = (YBottomOfBox - YTopOfBox) / (float)slotCount;
|
||||
int yOffset = (int)(YTopOfBox + (nameSize / 2.0f) + (nameSize * slotIndex));
|
||||
|
||||
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' at slot {slotIndex}/{slotCount} ({XCharList},{yOffset}).");
|
||||
PostMouseClick(hwnd, XCharList, yOffset);
|
||||
Thread.Sleep(AutoLoginDoubleClickGapMs);
|
||||
PostMouseClick(hwnd, XCharList, yOffset);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Click fallback threw - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false)
|
||||
{
|
||||
if (blob == IntPtr.Zero)
|
||||
|
|
@ -151,14 +443,26 @@ internal static class CharacterCaptureHooks
|
|||
}
|
||||
|
||||
characters = new List<string>(characterCount);
|
||||
// Deep-audit finding #28 (2026-06-18): this loop advanced offset
|
||||
// (GUID, nameLen, name bytes, padding, timeout) and never compared
|
||||
// it against blobSize — only nameLen itself was range-checked
|
||||
// (1..127). A short/malformed blob (this server's own login
|
||||
// response, so not adversarial, but still worth bounding) would
|
||||
// walk past the buffer into whatever heap memory follows it.
|
||||
// Bound every read against blobSize; break (not continue) on any
|
||||
// overrun since offset is no longer trustworthy past that point.
|
||||
for (int i = 0; i < characterCount; i++)
|
||||
{
|
||||
if (offset + 4 > blobSize) break; // GUID
|
||||
offset += 4; // Skip Character GUID
|
||||
|
||||
if (offset + 2 > blobSize) break; // nameLen
|
||||
short nameLen = Marshal.ReadInt16(IntPtr.Add(payloadPtr, offset));
|
||||
offset += 2;
|
||||
|
||||
if (nameLen > 0 && nameLen < 128)
|
||||
{
|
||||
if (offset + nameLen > blobSize) break; // name bytes
|
||||
byte[] nameBytes = new byte[nameLen];
|
||||
Marshal.Copy(IntPtr.Add(payloadPtr, offset), nameBytes, 0, nameLen);
|
||||
string name = Encoding.Default.GetString(nameBytes);
|
||||
|
|
@ -169,6 +473,12 @@ internal static class CharacterCaptureHooks
|
|||
if (offset % 4 != 0)
|
||||
offset += 4 - (offset % 4);
|
||||
offset += 4; // Skip Delete Timeout
|
||||
|
||||
if (offset > blobSize)
|
||||
{
|
||||
offset = (int)blobSize; // cap so the slotCount read below can't overrun either
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
characters.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
|
|
@ -177,7 +487,7 @@ internal static class CharacterCaptureHooks
|
|||
? Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset))
|
||||
: characters.Count;
|
||||
|
||||
RynthLog.Verbose($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
|
||||
RynthLog.Info($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
|
||||
|
||||
if (characters.Count > 0)
|
||||
{
|
||||
|
|
@ -247,7 +557,7 @@ internal static class CharacterCaptureHooks
|
|||
if (!string.IsNullOrWhiteSpace(accountName))
|
||||
{
|
||||
CharacterCacheStore.Write(accountName, serverName, characters);
|
||||
RynthLog.Verbose(
|
||||
RynthLog.Info(
|
||||
!string.IsNullOrWhiteSpace(serverName)
|
||||
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
|
||||
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
|
||||
|
|
@ -269,6 +579,35 @@ internal static class CharacterCaptureHooks
|
|||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
return;
|
||||
|
||||
// If the client is already past character-select, do NOT schedule any
|
||||
// auto-login work. The 0xF658 character-list packet can arrive in
|
||||
// transitional states (logout-to-char-select, hot-reload replay, etc.),
|
||||
// and starting a 10-second polling loop that pokes at native LogOn
|
||||
// pointers while the player is in-game has been correlated with AC
|
||||
// self-exiting via MSVCR70 a few seconds later.
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Verbose($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - login already complete.");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int currentMode) && currentMode == 0x10000008 /* GamePlayUI */)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - client is already in GamePlayUI.");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
// One-shot per process: if auto-login already fired (and the user has
|
||||
// since logged back out), don't re-trigger. This keeps a manual logout
|
||||
// from instantly re-logging the same character.
|
||||
if (Interlocked.CompareExchange(ref _autoLoginEverFired, 1, 0) != 0)
|
||||
{
|
||||
RynthLog.Verbose($"CharacterCapture: Auto-login already fired this session — skipping for '{targetCharacter}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _autoLoginScheduled, 1) != 0)
|
||||
return;
|
||||
|
||||
|
|
@ -276,7 +615,7 @@ internal static class CharacterCaptureHooks
|
|||
? new List<string>(characters)
|
||||
: [];
|
||||
int finalSlots = slotCount > 0 ? slotCount : fallbackCharacters.Count;
|
||||
int fallbackIndex = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
|
||||
int fallbackIndex = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
|
||||
int logoDelayMs = LogoBypassHooks.GetRecommendedAutoLoginDelayMs();
|
||||
int scheduledDelayMs = Math.Max(AutoLoginDelayMs, logoDelayMs);
|
||||
|
||||
|
|
@ -315,6 +654,17 @@ internal static class CharacterCaptureHooks
|
|||
return;
|
||||
}
|
||||
|
||||
// Hard early-out: if the client has already entered GamePlayUI, the player
|
||||
// is in the world. Continuing to poll TryLogOnCharacter (which keeps
|
||||
// dereferencing UIFlow + PlayerSystem pointers) has been correlated with
|
||||
// AC self-exiting via MSVCR70 ~20s later. Treat this as "done", not a
|
||||
// failure to be retried.
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int gpMode) && gpMode == 0x10000008 /* GamePlayUI */)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - client is already in GamePlayUI. Last direct status: {lastDirectStatus}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (CharacterManagementHooks.TryLogOnCharacter(targetCharacter, out string matchedCharacter, out uint avatarId, out string directStatus))
|
||||
{
|
||||
RynthLog.Verbose(
|
||||
|
|
@ -323,19 +673,39 @@ internal static class CharacterCaptureHooks
|
|||
}
|
||||
|
||||
lastDirectStatus = directStatus;
|
||||
|
||||
// Belt-and-braces: TryLogOnCharacter itself reports "Client is already in
|
||||
// GamePlayUI" when mode==GamePlayUI. If we somehow raced past the
|
||||
// pre-call mode check above, still bail on the status.
|
||||
if (directStatus.IndexOf("already in GamePlayUI", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - {directStatus}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt < DirectAutoLoginAttempts)
|
||||
Thread.Sleep(DirectAutoLoginAttemptDelayMs);
|
||||
}
|
||||
|
||||
RynthLog.Compat($"CharacterCapture: Direct auto-login did not succeed for '{targetCharacter}' - {lastDirectStatus}");
|
||||
|
||||
int index = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
|
||||
int index = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
|
||||
if (index < 0 || slotCount <= 0)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: No click fallback is available for '{targetCharacter}' after direct login failure.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Final guard: the click fallback drives a foreground window via PostMessage.
|
||||
// If, by the time we reach the fallback, the client is in GamePlayUI (eg the
|
||||
// user clicked through during the retry window), do NOT spam clicks at the
|
||||
// game viewport.
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int fbMode) && fbMode == 0x10000008 /* GamePlayUI */)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Skipping click fallback for '{targetCharacter}' - client is already in GamePlayUI.");
|
||||
return;
|
||||
}
|
||||
|
||||
IntPtr hwnd = WaitForGameWindow();
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
|
|
@ -350,6 +720,30 @@ internal static class CharacterCaptureHooks
|
|||
|
||||
for (int attempt = 1; attempt <= AutoLoginAttempts; attempt++)
|
||||
{
|
||||
// Login made it through (either by our earlier click or by the user) — stop clicking.
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - login complete.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int clickMode) && clickMode == GamePlayUIMode)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - client is already in GamePlayUI.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Only click while char-select is actually visible. The 0xF658 packet can arrive
|
||||
// before the UI has transitioned (logos still dismissing, etc.) — wasting clicks
|
||||
// outside char-select is what made earlier runs "give up too soon."
|
||||
bool charSelectReady = CharacterManagementHooks.TryGetCurrentMode(out int curMode) && curMode == CharacterManagementUIMode;
|
||||
if (!charSelectReady)
|
||||
{
|
||||
RynthLog.Verbose($"CharacterCapture: Click fallback waiting for char-select UI on attempt {attempt}/{AutoLoginAttempts} (mode=0x{curMode:X8}).");
|
||||
Thread.Sleep(AutoLoginAttemptDelayMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
RynthLog.Verbose($"CharacterCapture: Auto-login attempt {attempt}/{AutoLoginAttempts} for '{targetCharacter}' at ({XCharList}, {yOffset}).");
|
||||
|
||||
PostMouseClick(hwnd, XCharList, yOffset);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,12 @@ internal static class CharacterManagementHooks
|
|||
{
|
||||
private const int UIFlowInstanceVa = 0x0083E72C;
|
||||
private const int PlayerSystemVa = 0x0087119C;
|
||||
|
||||
// Phase B: resolve the two data globals by code-xref (operand at offset 2); VAs stay fallback.
|
||||
private static readonly byte?[] PatXrefUIFlow = [ 0x51, 0xA1, null, null, null, null, 0x8B, 0x4C ];
|
||||
private static readonly byte?[] PatXrefCPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
|
||||
private static int _uiFlowAddr = UIFlowInstanceVa;
|
||||
private static int _playerSystemAddr = PlayerSystemVa;
|
||||
private const int UIFlowCurModeOffset = 0x8C;
|
||||
private const int UIFlowDataOffset = 0x98;
|
||||
private const int UIPersistantDataCharacterSetOffset = 0x04;
|
||||
|
|
@ -51,6 +57,24 @@ internal static class CharacterManagementHooks
|
|||
private static CharacterSetGetNameDelegate? _characterSetGetName;
|
||||
private static CharacterSetGetGidDelegate? _characterSetGetGid;
|
||||
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
|
||||
// The *Va consts above are FALLBACKs; these signatures (verified unique + landing exactly
|
||||
// at the VA offline via tools/pe_pattern.py) are the source of truth, surviving AC-patch /
|
||||
// ACE-rebuild drift. GetName/GetGid are sibling accessors differing only in a trailing
|
||||
// field offset (0x08 vs 0x04) — pinned literally to stay unique.
|
||||
private static readonly byte?[] PatUIFlowGetPersistantData = [ 0x8B, 0x81, 0x98, 0x00, 0x00, 0x00, 0xC3, 0x90 ];
|
||||
private static readonly byte?[] PatGetPlayerSystem = [ 0xA1, 0x9C, 0x11, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
|
||||
private static readonly byte?[] PatLogOnCharacter = [ 0x56, 0x8B, 0xF1, 0x8A, 0x86, 0x10, 0x02, 0x00 ];
|
||||
private static readonly byte?[] PatCharacterSetGetIdentity = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x0F ];
|
||||
private static readonly byte?[] PatCharacterSetGetName = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x08 ];
|
||||
private static readonly byte?[] PatCharacterSetGetGid = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x04 ];
|
||||
|
||||
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
|
||||
}
|
||||
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool TryGetCurrentMode(out int mode)
|
||||
|
|
@ -65,9 +89,19 @@ internal static class CharacterManagementHooks
|
|||
}
|
||||
|
||||
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out string status)
|
||||
=> TryLogOnCharacter(targetCharacter, out matchedCharacter, out avatarId, out _, out status);
|
||||
|
||||
/// <summary>
|
||||
/// Same as the 4-arg overload, but also reports the matched character's
|
||||
/// slot index in AC's native CharacterSet (-1 when no match was found).
|
||||
/// The slot index is what the click fallback in CharacterCaptureHooks
|
||||
/// needs to compute the y-offset for the character-list double-click.
|
||||
/// </summary>
|
||||
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
|
||||
{
|
||||
matchedCharacter = string.Empty;
|
||||
avatarId = 0;
|
||||
slotIndex = -1;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||
{
|
||||
|
|
@ -113,9 +147,15 @@ internal static class CharacterManagementHooks
|
|||
continue;
|
||||
|
||||
availableCharacters.Add(candidateName);
|
||||
if (!string.Equals(candidateName, targetCharacter, StringComparison.OrdinalIgnoreCase))
|
||||
// Admin/staff character names render with a leading '+' in the AC
|
||||
// client UI but the cached/launcher-side name often lacks it (or the
|
||||
// server packet does). Match prefix-tolerantly so 'Buffi' matches
|
||||
// '+Buffi' and vice versa.
|
||||
if (!CharacterNamesMatch(candidateName, targetCharacter))
|
||||
continue;
|
||||
|
||||
slotIndex = index;
|
||||
|
||||
IntPtr playerSystemPtr = GetPlayerSystemPointer();
|
||||
if (playerSystemPtr == IntPtr.Zero)
|
||||
{
|
||||
|
|
@ -144,6 +184,84 @@ internal static class CharacterManagementHooks
|
|||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the character names in AC's native CharacterSet, in slot order
|
||||
/// (the order char-select lists them). Read-only: never calls
|
||||
/// LogOnCharacter. Only reads while CharacterManagementUI is the current
|
||||
/// mode, so the native set is never touched in the world. Returns false
|
||||
/// (empty list) when unbound, not at char-select, or the set isn't filled yet.
|
||||
/// </summary>
|
||||
public static bool TryReadCharacterNames(out List<string> names)
|
||||
{
|
||||
names = new List<string>();
|
||||
|
||||
if (!EnsureBound())
|
||||
return false;
|
||||
|
||||
if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI)
|
||||
return false;
|
||||
|
||||
IntPtr charSetPtr = GetCharacterSetPointer();
|
||||
if (charSetPtr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
for (int index = 0; index < MaxCharacterSlots; index++)
|
||||
{
|
||||
IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index);
|
||||
if (identityPtr == IntPtr.Zero)
|
||||
continue;
|
||||
|
||||
string? name = ReadAnsiString(_characterSetGetName!(charSetPtr, index));
|
||||
uint avatarId = _characterSetGetGid!(charSetPtr, index);
|
||||
if (string.IsNullOrWhiteSpace(name) || avatarId == 0)
|
||||
continue;
|
||||
|
||||
names.Add(name.Trim());
|
||||
}
|
||||
|
||||
return names.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of populated character slots in AC's native
|
||||
/// CharacterSet (slots where GetIdentity returns non-null). Used by the
|
||||
/// click fallback in CharacterCaptureHooks when the 0xF658 packet parser
|
||||
/// produced an empty list — typical on ACE where the packet shape differs
|
||||
/// from retail.
|
||||
/// </summary>
|
||||
public static int GetNativeCharacterSetSlotCount()
|
||||
{
|
||||
if (!EnsureBound())
|
||||
return 0;
|
||||
|
||||
IntPtr charSetPtr = GetCharacterSetPointer();
|
||||
if (charSetPtr == IntPtr.Zero)
|
||||
return 0;
|
||||
|
||||
int count = 0;
|
||||
for (int index = 0; index < MaxCharacterSlots; index++)
|
||||
{
|
||||
IntPtr identityPtr;
|
||||
try { identityPtr = _characterSetGetIdentity!(charSetPtr, index); }
|
||||
catch { return count; }
|
||||
|
||||
if (identityPtr != IntPtr.Zero)
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares two AC character names tolerantly of the leading '+' that the
|
||||
/// client adds to admin/staff names. e.g. 'Buffi' matches '+Buffi'.
|
||||
/// </summary>
|
||||
internal static bool CharacterNamesMatch(string? a, string? b)
|
||||
{
|
||||
string lhs = (a ?? string.Empty).Trim().TrimStart('+');
|
||||
string rhs = (b ?? string.Empty).Trim().TrimStart('+');
|
||||
return lhs.Length > 0 && string.Equals(lhs, rhs, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool EnsureBound()
|
||||
{
|
||||
lock (BindLock)
|
||||
|
|
@ -154,15 +272,30 @@ internal static class CharacterManagementHooks
|
|||
_bindAttempted = true;
|
||||
try
|
||||
{
|
||||
_uiFlowGetPersistantData = Marshal.GetDelegateForFunctionPointer<UIFlowGetPersistantDataDelegate>(new IntPtr(UIFlowGetPersistantDataVa));
|
||||
_getPlayerSystem = Marshal.GetDelegateForFunctionPointer<GetPlayerSystemDelegate>(new IntPtr(GetPlayerSystemVa));
|
||||
_logOnCharacter = Marshal.GetDelegateForFunctionPointer<LogOnCharacterDelegate>(new IntPtr(LogOnCharacterVa));
|
||||
_characterSetGetIdentity = Marshal.GetDelegateForFunctionPointer<CharacterSetGetIdentityDelegate>(new IntPtr(CharacterSetGetIdentityVa));
|
||||
_characterSetGetName = Marshal.GetDelegateForFunctionPointer<CharacterSetGetNameDelegate>(new IntPtr(CharacterSetGetNameVa));
|
||||
_characterSetGetGid = Marshal.GetDelegateForFunctionPointer<CharacterSetGetGidDelegate>(new IntPtr(CharacterSetGetGidVa));
|
||||
_bound = true;
|
||||
_statusMessage = "Bound.";
|
||||
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
_bound = false;
|
||||
_statusMessage = "acclient .text not readable for pattern resolve.";
|
||||
RynthLog.Compat($"CharacterManagement: bind failed - {_statusMessage}");
|
||||
return _bound;
|
||||
}
|
||||
|
||||
_uiFlowGetPersistantData = Bind<UIFlowGetPersistantDataDelegate>(text, "CharMgmt.UIFlowGetPersistantData", PatUIFlowGetPersistantData, UIFlowGetPersistantDataVa);
|
||||
_getPlayerSystem = Bind<GetPlayerSystemDelegate>(text, "CharMgmt.GetPlayerSystem", PatGetPlayerSystem, GetPlayerSystemVa);
|
||||
_logOnCharacter = Bind<LogOnCharacterDelegate>(text, "CharMgmt.LogOnCharacter", PatLogOnCharacter, LogOnCharacterVa);
|
||||
_characterSetGetIdentity = Bind<CharacterSetGetIdentityDelegate>(text, "CharMgmt.CharacterSetGetIdentity", PatCharacterSetGetIdentity, CharacterSetGetIdentityVa);
|
||||
_characterSetGetName = Bind<CharacterSetGetNameDelegate>(text, "CharMgmt.CharacterSetGetName", PatCharacterSetGetName, CharacterSetGetNameVa);
|
||||
_characterSetGetGid = Bind<CharacterSetGetGidDelegate>(text, "CharMgmt.CharacterSetGetGid", PatCharacterSetGetGid, CharacterSetGetGidVa);
|
||||
_uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32();
|
||||
_playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
|
||||
|
||||
_bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
|
||||
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null;
|
||||
_statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve.";
|
||||
if (_bound)
|
||||
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
|
||||
else
|
||||
RynthLog.Compat($"CharacterManagement: bind incomplete - {_statusMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -179,7 +312,7 @@ internal static class CharacterManagementHooks
|
|||
{
|
||||
try
|
||||
{
|
||||
return Marshal.ReadIntPtr(new IntPtr(UIFlowInstanceVa));
|
||||
return Marshal.ReadIntPtr(new IntPtr(_uiFlowAddr));
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
|
@ -235,7 +368,7 @@ internal static class CharacterManagementHooks
|
|||
|
||||
try
|
||||
{
|
||||
return Marshal.ReadIntPtr(new IntPtr(PlayerSystemVa));
|
||||
return Marshal.ReadIntPtr(new IntPtr(_playerSystemAddr));
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
|
|
|||
|
|
@ -25,20 +25,17 @@ internal static class ChatCallbackHooks
|
|||
private const bool EnableOutgoingHook = true;
|
||||
private static IncomingChatMode CurrentIncomingMode => IncomingChatMode.AddTextToScrollHostEat;
|
||||
|
||||
private static readonly byte[] IncomingChatAddTextToScrollSignature =
|
||||
// Verified unique + lands at 0x005649F0 offline (tools/pe_pattern.py).
|
||||
private static readonly byte?[] IncomingChatAddTextToScrollPattern =
|
||||
[
|
||||
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84,
|
||||
0x24, 0x54, 0x09, 0x00, 0x00, 0x53, 0x55, 0x56,
|
||||
0x33, 0xF6, 0x84, 0xC0, 0x57, 0x8B, 0xBC, 0x24,
|
||||
0x5C, 0x09, 0x00, 0x00, 0x89, 0x4C, 0x24, 0x24
|
||||
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84
|
||||
];
|
||||
|
||||
private static readonly byte[] IncomingChatWrapperSignature =
|
||||
// Verified unique + lands at 0x0058A000 offline (tools/pe_pattern.py).
|
||||
private static readonly byte?[] IncomingChatWrapperPattern =
|
||||
[
|
||||
0xA1, 0xE4, 0x0B, 0x87, 0x00, 0x85, 0xC0, 0x75,
|
||||
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56,
|
||||
0x8B, 0x74, 0x24, 0x10, 0x83, 0xFE, 0x01, 0x74,
|
||||
0x0F
|
||||
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56
|
||||
];
|
||||
|
||||
private static readonly byte?[] OutgoingChatPattern =
|
||||
|
|
@ -73,6 +70,15 @@ internal static class ChatCallbackHooks
|
|||
private static int _incomingChatSuppressionEnabled;
|
||||
private static int _incomingCallCount;
|
||||
|
||||
// Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing
|
||||
// chat function DIRECTLY (deterministic) instead of simulating keystrokes into
|
||||
// the native chat bar. Keystroke simulation depends on the bar's open/closed
|
||||
// state, which the first simulated send corrupts — so the second send silently
|
||||
// fails to submit ("works once, then stops"). Calling the function directly has
|
||||
// no chat-bar state and is fully repeatable.
|
||||
private static IntPtr _lastOutgoingThis;
|
||||
private static uint _lastOutgoingSource = 8;
|
||||
|
||||
public static bool IncomingInstalled { get; private set; }
|
||||
public static bool OutgoingInstalled { get; private set; }
|
||||
public static bool IsInstalled => (!EnableIncomingHook || IncomingInstalled) && (!EnableOutgoingHook || OutgoingInstalled);
|
||||
|
|
@ -189,17 +195,17 @@ internal static class ChatCallbackHooks
|
|||
|
||||
private static bool TryInstallIncomingWrapperHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
int incomingOff = IncomingChatWrapperVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatWrapperSignature))
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatWrapper", IncomingChatWrapperPattern, IncomingChatWrapperVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
incomingStatus = $"signature mismatch @ 0x{IncomingChatWrapperVa:X8}";
|
||||
incomingStatus = $"unresolved (VA 0x{IncomingChatWrapperVa:X8})";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
|
||||
_incomingAddress = resolved.Address;
|
||||
_incomingChatWrapperDetour = IncomingChatWrapperDetour;
|
||||
IntPtr incomingPtr = Marshal.GetFunctionPointerForDelegate(_incomingChatWrapperDetour);
|
||||
_originalIncomingChatWrapper = Marshal.GetDelegateForFunctionPointer<IncomingChatWrapperDelegate>(MinHook.HookCreate(_incomingAddress, incomingPtr));
|
||||
|
|
@ -218,10 +224,10 @@ internal static class ChatCallbackHooks
|
|||
|
||||
private static bool TryInstallIncomingAddTextHook(AcClientTextSection textSection, out string incomingStatus)
|
||||
{
|
||||
int incomingOff = IncomingChatAddTextToScrollVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatAddTextToScrollSignature))
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatAddTextToScroll", IncomingChatAddTextToScrollPattern, IncomingChatAddTextToScrollVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
incomingStatus = $"signature mismatch @ 0x{IncomingChatAddTextToScrollVa:X8}";
|
||||
incomingStatus = $"unresolved (VA 0x{IncomingChatAddTextToScrollVa:X8})";
|
||||
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
|
||||
return false;
|
||||
}
|
||||
|
|
@ -230,7 +236,7 @@ internal static class ChatCallbackHooks
|
|||
{
|
||||
unsafe
|
||||
{
|
||||
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
|
||||
_incomingAddress = resolved.Address;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
|
||||
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
|
||||
}
|
||||
|
|
@ -247,6 +253,7 @@ internal static class ChatCallbackHooks
|
|||
|
||||
private static int IncomingChatWrapperDetour(int flags, IntPtr text, int chatChannel)
|
||||
{
|
||||
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatWrapper");
|
||||
try
|
||||
{
|
||||
return CurrentIncomingMode switch
|
||||
|
|
@ -269,6 +276,7 @@ internal static class ChatCallbackHooks
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
|
||||
{
|
||||
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText");
|
||||
// 1. Read string BEFORE original — buffer may be freed after
|
||||
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
|
||||
|
||||
|
|
@ -326,9 +334,25 @@ internal static class ChatCallbackHooks
|
|||
|
||||
private static int OutgoingChatDetour(IntPtr thisPtr, IntPtr text, uint commandSource)
|
||||
{
|
||||
RecursionGuard.Tick("ChatCallbackHooks.OutgoingChat");
|
||||
try
|
||||
{
|
||||
string? line = ReadWidePString(text);
|
||||
LogoffOriginProbe.RecordChat($"AC OutgoingChat src={commandSource}", line);
|
||||
|
||||
// Capture the chat-manager 'this' + command source from the live submit
|
||||
// so ChatCommandDispatcher can re-invoke this function directly later.
|
||||
if (thisPtr != IntPtr.Zero)
|
||||
{
|
||||
_lastOutgoingThis = thisPtr;
|
||||
_lastOutgoingSource = commandSource;
|
||||
}
|
||||
|
||||
// RynthCore engine commands (/rc ...) — consume before plugins or
|
||||
// AC see the line so the user never broadcasts "/rc resetbar" and
|
||||
// a hidden overlay bar stays recoverable.
|
||||
if (RynthCoreChatCommands.TryHandle(line))
|
||||
return 1;
|
||||
|
||||
if (PluginManager.DispatchChatBarEnter(line))
|
||||
return 1;
|
||||
|
|
@ -514,4 +538,114 @@ internal static class ChatCallbackHooks
|
|||
{
|
||||
return opcode is 0xE9 or 0xE8 or 0xEB or 0x68 or 0xFF;
|
||||
}
|
||||
|
||||
/// <summary>True once a chat-manager 'this' has been captured from a live submit.</summary>
|
||||
public static bool CanDispatchDirect =>
|
||||
OutgoingInstalled && _originalOutgoingChat != null && _lastOutgoingThis != IntPtr.Zero;
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches a chat line by calling AC's outgoing-chat function directly — the
|
||||
/// same path AC takes when you press Enter on the native chat bar, but with no
|
||||
/// keystroke simulation and no chat-bar state, so it is repeatable. Uses the
|
||||
/// 'this' + command source captured by <see cref="OutgoingChatDetour"/> from a
|
||||
/// prior real submit. Returns false if the hook isn't installed or no 'this' has
|
||||
/// been captured yet — the caller then falls back to keystroke simulation, whose
|
||||
/// first successful send seeds the capture for all subsequent calls.
|
||||
/// Plugin pre-dispatch / engine-command handling is the caller's responsibility
|
||||
/// (already done in ChatCommandDispatcher.Dispatch), so this goes straight to AC.
|
||||
/// </summary>
|
||||
public static unsafe bool TryDispatchDirect(string? text)
|
||||
{
|
||||
if (!OutgoingInstalled || _originalOutgoingChat == null)
|
||||
return false;
|
||||
|
||||
IntPtr self = _lastOutgoingThis;
|
||||
if (self == IntPtr.Zero || string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
string line = text!.TrimEnd('\r', '\n');
|
||||
if (line.Length == 0)
|
||||
return false;
|
||||
foreach (char c in line)
|
||||
if (c < 0x20 && c != '\t')
|
||||
return false; // never feed AC control chars
|
||||
LogoffOriginProbe.RecordChat("OutgoingChat direct", line);
|
||||
|
||||
try
|
||||
{
|
||||
ushort[] chars = new ushort[line.Length + 1]; // +1 null terminator (wcslen)
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
chars[i] = line[i];
|
||||
|
||||
var wide = OutgoingWidePString.Create(chars);
|
||||
try
|
||||
{
|
||||
// 'wide' is a stack local (unmanaged struct) — its address is stable
|
||||
// for the synchronous call, so no 'fixed' pin is needed (or allowed).
|
||||
_originalOutgoingChat(self, (IntPtr)(&wide), _lastOutgoingSource);
|
||||
return true;
|
||||
}
|
||||
finally { wide.Dispose(); }
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"OutgoingChat direct failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the cached chat-manager 'this'. Called on logout: AC frees the object
|
||||
/// during the world→charselect transition, so the stale pointer must not be
|
||||
/// reused. It is re-captured from the next real submit after the next login.
|
||||
/// </summary>
|
||||
public static void ResetOutgoingTarget()
|
||||
{
|
||||
_lastOutgoingThis = IntPtr.Zero;
|
||||
}
|
||||
|
||||
// Minimal duplicate of ClientHelperHooks.WidePString (AC1Legacy::PStringBase<wchar_t>).
|
||||
// Duplicated deliberately so the actively-used WriteToChat path stays untouched.
|
||||
// Phase B / 1a-dup: resolve the PStringBase<wchar_t> ctor/dtor (fn VAs) by pattern and the
|
||||
// s_NullBuffer (data VA) by code-xref. These were duplicate raw VAs left by 1a's per-file pass.
|
||||
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
|
||||
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];
|
||||
private static readonly byte?[] PatXrefWideNullBuffer = [ 0x3B, 0x05, null, null, null, null, 0x74, 0xE7 ];
|
||||
private static unsafe void* ResolveFnVa(string name, byte?[] pattern, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return (void*)fallbackVa;
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
|
||||
}
|
||||
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return new IntPtr(fallbackVa);
|
||||
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct OutgoingWidePString
|
||||
{
|
||||
private static readonly IntPtr NullWideBufferVa = ResolveDataVa("ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
|
||||
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void> Ctor =
|
||||
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void>)ResolveFnVa("ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730);
|
||||
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, void> Dtor =
|
||||
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, void>)ResolveFnVa("ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0);
|
||||
|
||||
public IntPtr CharBuffer;
|
||||
|
||||
public static OutgoingWidePString Create(ushort[] chars)
|
||||
{
|
||||
var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) };
|
||||
fixed (ushort* pChars = chars)
|
||||
Ctor(&value, pChars);
|
||||
return value;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
fixed (OutgoingWidePString* ptr = &this)
|
||||
Dtor(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
|
|
@ -10,17 +12,46 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// </summary>
|
||||
internal static unsafe class ChatCommandDispatcher
|
||||
{
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
|
||||
// The Event_*/PStringBase VAs below are now FALLBACKs; these signatures (verified unique
|
||||
// + landing exactly at the VA offline via tools/pe_pattern.py) are the source of truth.
|
||||
// Declared BEFORE the fn-ptr fields so the static field initializers see them. The Event_*
|
||||
// senders are near-identical templates, so the patterns run long to reach the distinct tail.
|
||||
private static readonly byte?[] PatEventTalk = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0x15 ];
|
||||
private static readonly byte?[] PatEventEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xDF ];
|
||||
private static readonly byte?[] PatEventSoulEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xE1 ];
|
||||
private static readonly byte?[] PatEventTalkDirectByName = [ 0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x18, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x1C, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0x6C, 0x24, 0x24, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x14, 0x51, 0x8B, 0xCD, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x54, 0x24, 0x14, 0x52, 0x8D, 0x4C, 0x24, 0x1C, 0x03, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x89, 0x44, 0x24, 0x10, 0x8B, 0xF8, 0x56, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8D, 0x4C, 0x24, 0x1C, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x10, 0xC7, 0x01, 0x5D ];
|
||||
private static readonly byte?[] PatEventChannelBroadcast = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x00, 0x47 ];
|
||||
private static readonly byte?[] PatPStringBaseCtor = [ 0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x57, 0x8B, 0xF9, 0x74, 0x35, 0x80, 0x3E, 0x00, 0x74, 0x30, 0x8B, 0xC6, 0x8D, 0x50, 0x01, 0x8A, 0x08, 0x40, 0x84, 0xC9, 0x75, 0xF9, 0x2B, 0xC2, 0x50, 0x8B, 0xCF, 0xE8, null, null, null, null, 0x8B, 0x07 ];
|
||||
private static readonly byte?[] PatPStringBaseClear = [ 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x56, 0x57, 0x8B, 0xF9, 0x8B, 0x37, 0x3B, 0xF0, 0x74, 0x2D, 0x8D, 0x46, 0x04, 0x50, 0xFF, 0x15, 0xF8, 0x31, 0x79, 0x00, 0x85, 0xC0, 0x75, 0x0C, 0x85, 0xF6, 0x74, 0x08, 0x8B, 0x16, 0x6A, 0x01, 0x8B, 0xCE, 0xFF, 0x12, 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x8B, 0xC8, 0x83, 0xC1, 0x04, 0x51, 0x89, 0x07, 0xFF, 0x15, 0xFC, 0x31, 0x79, 0x00, 0x5F ];
|
||||
|
||||
private static void* ResolveVa(string name, byte?[] pattern, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
return (void*)fallbackVa;
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
|
||||
}
|
||||
|
||||
// Phase B: PStringBase<char>::s_NullBuffer (0x008EF11C) via code-xref (3B 3D <addr>), offset 2.
|
||||
private static readonly byte?[] PatXrefPStringNullBuffer = [ 0x3B, 0x3D, null, null, null, null, 0x74, 0xF1 ];
|
||||
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
return new IntPtr(fallbackVa);
|
||||
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
|
||||
}
|
||||
// CM_Communication::Event_* — all cdecl, all using AC1Legacy::PStringBase<char>
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventTalk =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A53E0;
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Talk", PatEventTalk, 0x006A53E0);
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventEmote =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A4F40;
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Emote", PatEventEmote, 0x006A4F40);
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventSoulEmote =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A5320;
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_SoulEmote", PatEventSoulEmote, 0x006A5320);
|
||||
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte> FnEventTalkDirectByName =
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)0x006A55A0;
|
||||
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_TalkDirectByName", PatEventTalkDirectByName, 0x006A55A0);
|
||||
private static readonly delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte> FnEventChannelBroadcast =
|
||||
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)0x006A4E50;
|
||||
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_ChannelBroadcast", PatEventChannelBroadcast, 0x006A4E50);
|
||||
|
||||
private const uint WM_KEYDOWN = 0x0100;
|
||||
private const uint WM_KEYUP = 0x0101;
|
||||
|
|
@ -33,6 +64,16 @@ internal static unsafe class ChatCommandDispatcher
|
|||
/// </summary>
|
||||
public static bool UseDirectChatInput { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Recursion guard for the plugin pre-dispatch step. A plugin's
|
||||
/// OnChatBarEnter handler may chain by calling Host.InvokeChatParser →
|
||||
/// PluginManager.InvokeChatParser → ClientHelperHooks.InvokeParser →
|
||||
/// ChatCommandDispatcher.Dispatch. Without this guard the plugin would
|
||||
/// re-enter its own OnChatBarEnter on the chained line and could loop.
|
||||
/// </summary>
|
||||
[ThreadStatic]
|
||||
private static bool _inPluginPreDispatch;
|
||||
|
||||
/// <summary>
|
||||
/// AC1Legacy::PStringBase<char> for Event_* functions.
|
||||
/// </summary>
|
||||
|
|
@ -41,11 +82,11 @@ internal static unsafe class ChatCommandDispatcher
|
|||
{
|
||||
public IntPtr Buffer;
|
||||
|
||||
private static readonly IntPtr NullBufferVa = new(0x008EF11C);
|
||||
private static readonly IntPtr NullBufferVa = ResolveDataVa("ChatCmd.PStringChar_NullBuffer", PatXrefPStringNullBuffer, 2, 0x008EF11C);
|
||||
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void> Ctor =
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)0x0048C3E0;
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)ResolveVa("ChatCmd.PStringBaseC_ctor", PatPStringBaseCtor, 0x0048C3E0);
|
||||
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, void> ClearFn =
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)0x004AB990;
|
||||
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)ResolveVa("ChatCmd.PStringBaseC_Clear", PatPStringBaseClear, 0x004AB990);
|
||||
|
||||
public static LegacyPString Create(string text)
|
||||
{
|
||||
|
|
@ -70,14 +111,64 @@ internal static unsafe class ChatCommandDispatcher
|
|||
if (string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
// Deep-audit finding #4 (2026-06-18): this whole function is not
|
||||
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
|
||||
// constructs/destructs AC's native PStringBase<char> in AC's heap,
|
||||
// and calls Event_Talk/Event_Emote/etc. directly against AC's live
|
||||
// chat-manager. The old inline comment claiming this was "thread-safe"
|
||||
// was an inherited Decal/VTank assumption that contradicts the
|
||||
// engine's own AcMainThreadQueue design (see the documented
|
||||
// 0x00460D1D chat-buffer write-AV class). Gating here (rather than at
|
||||
// each call site) covers every off-thread caller at once:
|
||||
// OnLoginCommandRunner (ThreadPool), ChatFileDispatcher
|
||||
// (FileSystemWatcher thread), and Host.InvokeChatParser (plugin
|
||||
// export, any thread). The queued call re-invokes this same method
|
||||
// from the drain, where IsOnMainThread is satisfied and the body
|
||||
// below runs directly — so there's only one code path to keep in sync.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueChatCommand(text);
|
||||
|
||||
try
|
||||
{
|
||||
string trimmed = text.Trim();
|
||||
if (trimmed.Length == 0) return false;
|
||||
LogoffOriginProbe.RecordChat("ChatCommandDispatcher", trimmed);
|
||||
|
||||
// RynthCore engine commands (/rc ...) are handled before plugin
|
||||
// pre-dispatch and before any AC chat routing so they work even
|
||||
// when the overlay is hidden and no plugin can eat the line.
|
||||
if (RynthCoreChatCommands.TryHandle(trimmed))
|
||||
return true;
|
||||
|
||||
// Expand shorthand: /s → /say, /t → /tell, /e → /emote
|
||||
trimmed = ExpandShorthand(trimmed);
|
||||
|
||||
// Plugin pre-dispatch: matches AC's natural OutgoingChatDetour
|
||||
// behavior — when a user types in the chat bar, plugins
|
||||
// (RynthAi /ra, VTank /vt, UBService /ub, MagTools /mt, etc.) get
|
||||
// first dibs via OnChatBarEnter and can eat the line. We mirror
|
||||
// that here so callers like OnLoginCommandRunner and
|
||||
// Host.InvokeChatParser produce identical-to-typed semantics.
|
||||
//
|
||||
// Skipped when:
|
||||
// - Already inside a plugin pre-dispatch on this thread
|
||||
// (avoids infinite loops on chained Host.InvokeChatParser calls)
|
||||
// - UseDirectChatInput is on (raw simulate mode bypasses this)
|
||||
if (!UseDirectChatInput && !_inPluginPreDispatch)
|
||||
{
|
||||
_inPluginPreDispatch = true;
|
||||
try
|
||||
{
|
||||
if (PluginManager.DispatchChatBarEnter(trimmed))
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ChatDispatch: plugin pre-dispatch threw on '{trimmed}' - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally { _inPluginPreDispatch = false; }
|
||||
}
|
||||
|
||||
// Direct Chat Input mode — everything goes through keyboard sim
|
||||
if (UseDirectChatInput)
|
||||
return SimulateChatInput(trimmed);
|
||||
|
|
@ -102,16 +193,16 @@ internal static unsafe class ChatCommandDispatcher
|
|||
if (StartsWithCmd(trimmed, "/a "))
|
||||
return DispatchChannelBroadcast(1, trimmed.Substring(3));
|
||||
|
||||
// /f message (fellowship — use keyboard sim, no direct Event_*)
|
||||
// /f message (fellowship — no direct Event_*; use the raw chat path)
|
||||
if (StartsWithCmd(trimmed, "/f "))
|
||||
return SimulateChatInput(trimmed);
|
||||
return DispatchRaw(trimmed);
|
||||
|
||||
// Bare text → say
|
||||
if (!trimmed.StartsWith("/", StringComparison.Ordinal))
|
||||
return DispatchSay(trimmed);
|
||||
|
||||
// Everything else → keyboard simulation fallback
|
||||
return SimulateChatInput(trimmed);
|
||||
// Everything else (arbitrary slash commands like /smite) → raw chat path
|
||||
return DispatchRaw(trimmed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -169,7 +260,7 @@ internal static unsafe class ChatCommandDispatcher
|
|||
int commaIdx = args.IndexOf(',');
|
||||
if (commaIdx < 1)
|
||||
{
|
||||
return SimulateChatInput("/tell " + args);
|
||||
return DispatchRaw("/tell " + args);
|
||||
}
|
||||
|
||||
string targetName = args.Substring(0, commaIdx).Trim();
|
||||
|
|
@ -210,29 +301,59 @@ internal static unsafe class ChatCommandDispatcher
|
|||
finally { ps.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches an arbitrary chat line. Prefers calling AC's outgoing-chat
|
||||
/// function directly (deterministic and repeatable — no native chat-bar state to
|
||||
/// corrupt); falls back to keystroke simulation only until the chat 'this' has
|
||||
/// been captured (typically the very first send of a session, whose successful
|
||||
/// submit seeds the capture for every send after it).
|
||||
/// </summary>
|
||||
private static bool DispatchRaw(string command)
|
||||
{
|
||||
if (ChatCallbackHooks.TryDispatchDirect(command))
|
||||
return true;
|
||||
return SimulateChatInput(command);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simulates keyboard input to type and submit a chat command.
|
||||
/// Used as fallback for commands without a direct Event_* function.
|
||||
/// </summary>
|
||||
private static bool SimulateChatInput(string command)
|
||||
{
|
||||
// Enter → opens chat input
|
||||
IntPtr enterDown = MakeKeyLParam(0x1C, false);
|
||||
IntPtr enterUp = MakeKeyLParam(0x1C, true);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
LogoffOriginProbe.RecordChat("SimulateChatInput", command);
|
||||
// Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives
|
||||
// CallWindowProcA directly into AC's WndProc — calling that off the
|
||||
// window-owning thread is a cross-thread WndProc re-entry. Dispatch()
|
||||
// gating (finding #4) already closes the two known off-thread paths
|
||||
// into this method, but wrap here too per the fix note ("protect
|
||||
// future callers"): RunOnGameThread inlines with zero overhead when
|
||||
// already on the game thread (the common case, post-#4) and marshals
|
||||
// synchronously otherwise.
|
||||
return ImGuiBackend.Win32Backend.RunOnGameThread(() =>
|
||||
{
|
||||
// Enter → opens chat input. The WM_CHAR '\r' is required here to complete
|
||||
// AC's chat-bar open transition.
|
||||
IntPtr enterDown = MakeKeyLParam(0x1C, false);
|
||||
IntPtr enterUp = MakeKeyLParam(0x1C, true);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
|
||||
// Type each character
|
||||
foreach (char c in command)
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
|
||||
// Type each character
|
||||
foreach (char c in command)
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
|
||||
|
||||
// Enter → submit
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
// Enter → submit. NO trailing WM_CHAR '\r' here: the WM_KEYDOWN submits and
|
||||
// closes the bar; a '\r' arriving on the now-closed bar re-opens it (the
|
||||
// "lone '\r'" behavior the chat-capture path also guards against), leaving the
|
||||
// bar open so the NEXT command's open-Enter submits an empty bar instead and
|
||||
// the command is lost — the "works once then stops" symptom.
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
|
||||
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
|
||||
|
||||
return true;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private static IntPtr MakeKeyLParam(byte scanCode, bool keyUp)
|
||||
|
|
|
|||
188
src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs
Normal file
188
src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// File-driven chat command dispatcher.
|
||||
///
|
||||
/// Watches <c>%APPDATA%\RynthCore\dispatch.txt</c>. Any change to that file
|
||||
/// is interpreted as a slash command for AC's chat — the file's content
|
||||
/// (last non-blank line) is sent through <see cref="ChatCommandDispatcher.Dispatch"/>,
|
||||
/// which routes through any RynthCore-style plugins (RynthAi, VTank, etc.)
|
||||
/// just like a user-typed command would.
|
||||
///
|
||||
/// Use cases:
|
||||
/// - User is on Remote Desktop and AC's chat input is unresponsive after a
|
||||
/// hot reload or focus event. Open the dispatch.txt file in Notepad,
|
||||
/// change the contents, save — command fires.
|
||||
/// - Scripted automation outside the AC client.
|
||||
/// - Backup chat path when ImGui/Avalonia keyboard capture is eating input.
|
||||
///
|
||||
/// Format: the file is plain text. The dispatcher reads the LAST non-blank
|
||||
/// non-comment line (lines starting with '#' are ignored). Saving the file
|
||||
/// triggers a debounced dispatch (~200ms after the last save event, so
|
||||
/// half-completed edits don't fire).
|
||||
///
|
||||
/// Safety:
|
||||
/// - Empty file or only comments → no dispatch.
|
||||
/// - Dispatcher does not delete the file. Repeated saves of the same
|
||||
/// content re-fire the command — by design, so the user can save again
|
||||
/// to retry. If you want fire-once, write a sentinel line.
|
||||
/// </summary>
|
||||
internal static class ChatFileDispatcher
|
||||
{
|
||||
private static FileSystemWatcher? _watcher;
|
||||
private static readonly object SyncRoot = new();
|
||||
private static long _pendingFireTickMs;
|
||||
private static Timer? _debounceTimer;
|
||||
private static string _lastDispatchedContent = string.Empty;
|
||||
|
||||
private const int DebounceMs = 200;
|
||||
|
||||
public static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"dispatch.txt");
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (_watcher != null) return;
|
||||
|
||||
try
|
||||
{
|
||||
string dir = Path.GetDirectoryName(FilePath) ?? "";
|
||||
string name = Path.GetFileName(FilePath);
|
||||
if (string.IsNullOrEmpty(dir) || string.IsNullOrEmpty(name))
|
||||
{
|
||||
RynthLog.Compat($"ChatFileDispatcher: invalid FilePath '{FilePath}', not starting.");
|
||||
return;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
File.WriteAllText(FilePath,
|
||||
"# RynthCore chat-command dispatch file.\n" +
|
||||
"# Save this file with a slash command on the last line to dispatch it.\n" +
|
||||
"# Example: /ra clearbusy\n" +
|
||||
"# Comments (lines starting with #) and blank lines are ignored.\n" +
|
||||
"# Plugin pre-dispatch (RynthAi /ra, etc.) is honored.\n");
|
||||
}
|
||||
|
||||
_watcher = new FileSystemWatcher(dir, name)
|
||||
{
|
||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.CreationTime,
|
||||
EnableRaisingEvents = true,
|
||||
};
|
||||
_watcher.Changed += OnChanged;
|
||||
_watcher.Created += OnChanged;
|
||||
_watcher.Renamed += OnRenamed;
|
||||
|
||||
_debounceTimer = new Timer(DispatchOnce, null, Timeout.Infinite, Timeout.Infinite);
|
||||
|
||||
RynthLog.Compat($"ChatFileDispatcher: watching '{FilePath}'.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ChatFileDispatcher: start failed — {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Stop()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_watcher != null)
|
||||
{
|
||||
_watcher.EnableRaisingEvents = false;
|
||||
_watcher.Dispose();
|
||||
_watcher = null;
|
||||
}
|
||||
_debounceTimer?.Dispose();
|
||||
_debounceTimer = null;
|
||||
}
|
||||
catch { /* shutdown — non-fatal */ }
|
||||
}
|
||||
|
||||
private static void OnChanged(object _, FileSystemEventArgs e) => ScheduleDispatch();
|
||||
private static void OnRenamed(object _, RenamedEventArgs e) => ScheduleDispatch();
|
||||
|
||||
private static void ScheduleDispatch()
|
||||
{
|
||||
lock (SyncRoot)
|
||||
{
|
||||
_pendingFireTickMs = Environment.TickCount64 + DebounceMs;
|
||||
try { _debounceTimer?.Change(DebounceMs, Timeout.Infinite); }
|
||||
catch { /* timer disposed during shutdown */ }
|
||||
}
|
||||
}
|
||||
|
||||
private static void DispatchOnce(object? _)
|
||||
{
|
||||
string? line = null;
|
||||
try
|
||||
{
|
||||
// ReadAllText with a brief retry: the editor may still hold the
|
||||
// file briefly after save, FileSystemWatcher fires before the
|
||||
// handle is released. Try a few times.
|
||||
string? text = null;
|
||||
for (int attempt = 0; attempt < 5; attempt++)
|
||||
{
|
||||
try { text = File.ReadAllText(FilePath); break; }
|
||||
catch (IOException) { Thread.Sleep(40); }
|
||||
}
|
||||
if (text == null) return;
|
||||
|
||||
// Find the LAST non-blank non-comment line.
|
||||
string[] rawLines = text.Replace("\r\n", "\n").Split('\n');
|
||||
for (int i = rawLines.Length - 1; i >= 0; i--)
|
||||
{
|
||||
string trimmed = rawLines[i].Trim();
|
||||
if (trimmed.Length == 0) continue;
|
||||
if (trimmed.StartsWith('#')) continue;
|
||||
line = trimmed;
|
||||
break;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
return;
|
||||
|
||||
// Dedup adjacent identical content silently. Saving the file
|
||||
// re-fires only if content actually differs from last dispatch
|
||||
// OR the line is prefixed with "force:" (force-fire even if
|
||||
// same content). User can also clear+resave to fire again.
|
||||
bool force = line.StartsWith("force:", StringComparison.OrdinalIgnoreCase);
|
||||
if (force) line = line.Substring("force:".Length).TrimStart();
|
||||
|
||||
if (!force && line == _lastDispatchedContent)
|
||||
{
|
||||
RynthLog.Verbose($"ChatFileDispatcher: skipped re-dispatch of unchanged line '{line}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
_lastDispatchedContent = line;
|
||||
|
||||
// Strip leading slash if present — Dispatch handles both forms.
|
||||
string toDispatch = line.StartsWith('/') ? line.Substring(1) : line;
|
||||
string forDispatch = '/' + toDispatch;
|
||||
|
||||
RynthLog.Compat($"ChatFileDispatcher: dispatching '{forDispatch}'.");
|
||||
try
|
||||
{
|
||||
bool ok = ChatCommandDispatcher.Dispatch(forDispatch);
|
||||
RynthLog.Compat($"ChatFileDispatcher: dispatched ok={ok}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ChatFileDispatcher: Dispatch threw — {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ChatFileDispatcher: read/parse failed — {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
176
src/RynthCore.Engine/Compatibility/ChatHooks.cs
Normal file
176
src/RynthCore.Engine/Compatibility/ChatHooks.cs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/ChatHooks.cs
|
||||
//
|
||||
// Hooks gmMainChatUI::ListenToElementMessage purely to capture the widget's
|
||||
// 'this' pointer on first UI dispatch. Per-frame visibility assertion is
|
||||
// driven from EndSceneHook (ChatHooks.TickHide) and calls UIElement::SetVisible
|
||||
// directly on the captured singleton.
|
||||
//
|
||||
// Both addresses (the listen hook and the SetVisible call target) are now
|
||||
// resolved via HookResolver — pattern-scan first, fallback VA second.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class ChatHooks
|
||||
{
|
||||
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
|
||||
private const int GmMainChatUIListenMsgFallbackVa = 0x004CE6F0;
|
||||
private const int UIElementSetVisibleFallbackVa = 0x00462390;
|
||||
|
||||
// gmMainChatUI::ListenToElementMessage(UIElementMessageInfo const&)
|
||||
// Reads the message kind from [esi+8], decrements, switches on it (0x3C, 0x3E, ...).
|
||||
private static readonly byte?[] ListenToElementMessagePattern =
|
||||
[
|
||||
0x56, 0x8B, 0x74, 0x24, 0x08, 0x8B, 0x46, 0x08,
|
||||
0x48, 0x57, 0x8B, 0xF9, 0x74, 0x72, 0x83, 0xE8,
|
||||
0x06, 0x75, 0x7D, 0x8B, 0x4E, 0x04, 0x8B, 0x01,
|
||||
0x6A, 0x06, 0xFF, 0x90, 0x94, 0x00, 0x00, 0x00
|
||||
];
|
||||
|
||||
// UIElement::SetVisible(bool) — duplicated against RadarHooks deliberately;
|
||||
// each consumer resolves independently so a partial failure isolates per-file.
|
||||
private static readonly byte?[] UIElementSetVisiblePattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x57,
|
||||
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
|
||||
0x8B, 0xF1,
|
||||
0xE8, null, null, null, null, // call rel32
|
||||
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
|
||||
0x88, 0x44, 0x24, 0x0F
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void ListenToElementMessageDelegate(IntPtr thisPtr, IntPtr msgInfo);
|
||||
|
||||
private static ListenToElementMessageDelegate? _originalListen;
|
||||
private static ListenToElementMessageDelegate? _listenDetour;
|
||||
|
||||
private static IntPtr _gmMainChatInstance;
|
||||
private static IntPtr _uiElementSetVisibleAddress;
|
||||
private static bool _hookInstalled;
|
||||
private static string _statusMessage = "Not initialized.";
|
||||
|
||||
public static bool IsInstalled => _hookInstalled;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static bool SuppressOriginalChat; // the user's "Hide retail chat" option
|
||||
|
||||
/// <summary>RynthChat's panel is on screen (set by RynthChatPanel).</summary>
|
||||
public static volatile bool ChatPanelShown;
|
||||
|
||||
/// <summary>
|
||||
/// RynthChat is standing in for the retail chat: in the world, its panel is open AND
|
||||
/// "Hide retail chat" is on. Only then is the retail chatbox hidden and Enter routed to
|
||||
/// RynthChat — whichever chat is visible gets Enter. Outside the world Enter is AC's:
|
||||
/// at character select it enters the game.
|
||||
/// </summary>
|
||||
public static bool RynthChatOwnsChat =>
|
||||
SuppressOriginalChat && ChatPanelShown && LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
|
||||
public static IntPtr GmMainChatInstance => _gmMainChatInstance;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_hookInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
var setVisible = HookResolver.Resolve(textSection, "ChatHooks.UIElement::SetVisible",
|
||||
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
|
||||
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
|
||||
|
||||
var listen = HookResolver.Resolve(textSection, "ChatHooks.ListenToElementMessage",
|
||||
ListenToElementMessagePattern, GmMainChatUIListenMsgFallbackVa);
|
||||
if (!listen.Success)
|
||||
{
|
||||
_statusMessage = $"ListenToElementMessage resolve failed ({listen.Detail}).";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_listenDetour = ListenDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_listenDetour);
|
||||
_originalListen = Marshal.GetDelegateForFunctionPointer<ListenToElementMessageDelegate>(
|
||||
MinHook.HookCreate(listen.Address, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(listen.Address);
|
||||
|
||||
_hookInstalled = true;
|
||||
_statusMessage = $"Hooked gmMainChatUI::ListenToElementMessage @ 0x{listen.Address.ToInt32():X8}.";
|
||||
RynthLog.Compat($"ChatHooks: install ok.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"ChatHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int _listenFires;
|
||||
|
||||
private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo)
|
||||
{
|
||||
RecursionGuard.Tick("ChatHooks.Listen");
|
||||
if (thisPtr != IntPtr.Zero)
|
||||
_gmMainChatInstance = thisPtr;
|
||||
if (++_listenFires <= 3)
|
||||
RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}");
|
||||
try { _originalListen!(thisPtr, msgInfo); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"ChatHooks: Listen original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
|
||||
}
|
||||
|
||||
// Starts true so the first tick asserts the setting either way: after an engine reload
|
||||
// the previous generation may have left the chatbox hidden, and a fresh "false" here
|
||||
// would never show it again even with "Hide retail chat" off. SetVisible(true) on a
|
||||
// visible chatbox is a no-op.
|
||||
private static bool _isHiddenAsserted = true;
|
||||
|
||||
public static unsafe void TickHide()
|
||||
{
|
||||
if (!LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
return;
|
||||
|
||||
IntPtr inst = _gmMainChatInstance;
|
||||
if (inst == IntPtr.Zero) return;
|
||||
if (_uiElementSetVisibleAddress == IntPtr.Zero) return;
|
||||
|
||||
if (RynthChatOwnsChat)
|
||||
{
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 0);
|
||||
}
|
||||
catch { /* best-effort */ }
|
||||
_isHiddenAsserted = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_isHiddenAsserted)
|
||||
{
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 1);
|
||||
}
|
||||
catch { /* best-effort */ }
|
||||
_isHiddenAsserted = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void ResetCachedInstance()
|
||||
{
|
||||
_gmMainChatInstance = IntPtr.Zero;
|
||||
_isHiddenAsserted = true; // re-assert on the next instance, as at start-up
|
||||
}
|
||||
}
|
||||
|
|
@ -136,6 +136,21 @@ internal static class ClientActionHooks
|
|||
return CommandInterpreterHooks.TapJump();
|
||||
}
|
||||
|
||||
public static bool CommenceJump()
|
||||
{
|
||||
return CommandInterpreterHooks.CommenceJump();
|
||||
}
|
||||
|
||||
public static bool DoJump(bool autonomous)
|
||||
{
|
||||
return CommandInterpreterHooks.DoJump(autonomous);
|
||||
}
|
||||
|
||||
public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
|
||||
{
|
||||
return PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
|
||||
}
|
||||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
return CommandInterpreterHooks.SetMotion(motion, enabled);
|
||||
|
|
|
|||
|
|
@ -62,6 +62,30 @@ internal static class ClientCombatHooks
|
|||
private static AutoTargetDelegate? _autoTarget;
|
||||
private static SendAttackHeightChangedDelegate? _sendAttackHeightChanged;
|
||||
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
|
||||
// The *Va consts above are now FALLBACKs. These signatures (verified unique + landing
|
||||
// exactly at the VA offline against this client via tools/pe_pattern.py) are the source
|
||||
// of truth, so binding survives AC-patch / ACE-rebuild drift. null = wildcard (rel32).
|
||||
private static readonly byte?[] PatGetCombatSystem = [ 0xA1, 0x6C, 0x16, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
|
||||
private static readonly byte?[] PatSetRequestedAttackHeight = [ 0x8B, 0x51, 0x24, 0x8B, 0x44, 0x24, 0x04, 0x3B ];
|
||||
private static readonly byte?[] PatStartAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0x8A ];
|
||||
private static readonly byte?[] PatEndAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0x8A, 0x46, 0x3E, 0x84, 0xC0, 0x0F ];
|
||||
private static readonly byte?[] PatPlayerInReadyPosition = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x83, 0xEC, 0x18 ];
|
||||
private static readonly byte?[] PatAutoTarget = [ 0x83, 0xEC, 0x18, 0x53, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
|
||||
private static readonly byte?[] PatSendAttackHeightChanged = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xFC ];
|
||||
|
||||
// Phase B (1a-data): s_pCombatSystem global (0x0087166C) resolved by code-xref — the unique
|
||||
// "mov [s_pCombatSystem],esi" site (89 35 <addr>); read the address from the operand at
|
||||
// offset 2. The VA stays as the logged fallback.
|
||||
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
|
||||
private static IntPtr _combatSystemPtrAddr = new(CombatSystemPtrVa);
|
||||
|
||||
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
|
||||
}
|
||||
|
||||
private static bool _initialized;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
|
|
@ -75,17 +99,26 @@ internal static class ClientCombatHooks
|
|||
{
|
||||
try
|
||||
{
|
||||
_getCombatSystem = Marshal.GetDelegateForFunctionPointer<GetCombatSystemDelegate>(new IntPtr(GetCombatSystemVa));
|
||||
_setAttackHeight = Marshal.GetDelegateForFunctionPointer<SetRequestedAttackHeightDelegate>(new IntPtr(SetRequestedAttackHeightVa));
|
||||
_startAttackRequest = Marshal.GetDelegateForFunctionPointer<StartAttackRequestDelegate>(new IntPtr(StartAttackRequestVa));
|
||||
_endAttackRequest = Marshal.GetDelegateForFunctionPointer<EndAttackRequestDelegate>(new IntPtr(EndAttackRequestVa));
|
||||
_playerInReadyPosition = Marshal.GetDelegateForFunctionPointer<PlayerInReadyPositionDelegate>(new IntPtr(PlayerInReadyPositionVa));
|
||||
_autoTarget = Marshal.GetDelegateForFunctionPointer<AutoTargetDelegate>(new IntPtr(AutoTargetVa));
|
||||
_sendAttackHeightChanged = Marshal.GetDelegateForFunctionPointer<SendAttackHeightChangedDelegate>(new IntPtr(SendAttackHeightChangedVa));
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
_statusMessage = "acclient .text not readable for pattern resolve.";
|
||||
RynthLog.Compat($"Compat: ClientCombat probe failed - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_combatSystemPtrAddr = HookResolver.ResolveData(text, "ClientCombat.s_pCombatSystem", PatXrefCombatSystemPtr, 2, CombatSystemPtrVa).Address;
|
||||
|
||||
_getCombatSystem = Bind<GetCombatSystemDelegate>(text, "ClientCombat.GetCombatSystem", PatGetCombatSystem, GetCombatSystemVa);
|
||||
_setAttackHeight = Bind<SetRequestedAttackHeightDelegate>(text, "ClientCombat.SetRequestedAttackHeight", PatSetRequestedAttackHeight, SetRequestedAttackHeightVa);
|
||||
_startAttackRequest = Bind<StartAttackRequestDelegate>(text, "ClientCombat.StartAttackRequest", PatStartAttackRequest, StartAttackRequestVa);
|
||||
_endAttackRequest = Bind<EndAttackRequestDelegate>(text, "ClientCombat.EndAttackRequest", PatEndAttackRequest, EndAttackRequestVa);
|
||||
_playerInReadyPosition = Bind<PlayerInReadyPositionDelegate>(text, "ClientCombat.PlayerInReadyPosition", PatPlayerInReadyPosition, PlayerInReadyPositionVa);
|
||||
_autoTarget = Bind<AutoTargetDelegate>(text, "ClientCombat.AutoTarget", PatAutoTarget, AutoTargetVa);
|
||||
_sendAttackHeightChanged = Bind<SendAttackHeightChangedDelegate>(text, "ClientCombat.SendAttackHeightChanged", PatSendAttackHeightChanged, SendAttackHeightChangedVa);
|
||||
|
||||
// Verify the combat system singleton is accessible
|
||||
IntPtr cs = _getCombatSystem();
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
|
||||
IntPtr cs = _getCombatSystem?.Invoke() ?? IntPtr.Zero;
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
|
||||
RynthLog.Verbose($"Compat: ClientCombat GetCombatSystem()=0x{cs:X8}, global=0x{globalPtr:X8}");
|
||||
if (cs == IntPtr.Zero && globalPtr == IntPtr.Zero)
|
||||
{
|
||||
|
|
@ -135,15 +168,27 @@ internal static class ClientCombatHooks
|
|||
return false;
|
||||
}
|
||||
|
||||
// Deep-audit finding #15 (2026-06-18): this fires 4 AC combat-state
|
||||
// mutators (height notify, SetRequestedAttackHeight, StartAttackRequest,
|
||||
// EndAttackRequest) that must land in the SAME order as the paired
|
||||
// SelectItem that precedes it. Reachable off-thread via the host API,
|
||||
// and UseNativeAttack defaults true — so unlike this file's sibling
|
||||
// MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal
|
||||
// as ONE queue entry (not split into four) so the sequence stays atomic
|
||||
// relative to the drain loop's other actions.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr cs = _getCombatSystem();
|
||||
if (cs == IntPtr.Zero)
|
||||
{
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
|
||||
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
|
||||
if (globalPtr == IntPtr.Zero) return false;
|
||||
cs = globalPtr;
|
||||
}
|
||||
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
|
||||
|
||||
// Notify client of height change via CM_Combat (same path as keyboard Del/End/PgDn)
|
||||
_sendAttackHeightChanged?.Invoke(attackHeight);
|
||||
|
|
@ -184,10 +229,18 @@ internal static class ClientCombatHooks
|
|||
if (_autoTarget == null || _getCombatSystem == null)
|
||||
return false;
|
||||
|
||||
// Same mutator class as NativeAttack (audit finding #15). Not currently
|
||||
// exposed through the plugin SDK, so there's no live off-thread caller
|
||||
// today — fail closed rather than queue, since queuing an unreachable
|
||||
// path is dead-weight; revisit with an ActionKind if this is exposed.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr cs = _getCombatSystem();
|
||||
if (cs == IntPtr.Zero) return false;
|
||||
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
|
||||
_autoTarget(cs);
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,6 +62,15 @@ internal static class ClientHelperHooks
|
|||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte EventStackableMergeDelegate(uint mergeFromId, uint mergeToId, int amount);
|
||||
|
||||
// CM_Inventory::Event_GiveObjectRequest — the public give-item-to-NPC API.
|
||||
// Byte-identical sibling of Event_StackableMerge (differs only in the action
|
||||
// opcode immediate: give writes 0xCD, merge 0x54). Cdecl, returns bool.
|
||||
// Chorizite map: 002ACA60 -> live VA 0x006ACA60. Sends the F7B1 give
|
||||
// GameAction. amount = stack count to give (0 = whole object).
|
||||
// Args (live-disasm + call-site UIAttemptGive confirmed): item, targetNpc, amount.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte EventGiveObjectRequestDelegate(uint objectId, uint targetId, int amount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId);
|
||||
|
||||
|
|
@ -94,6 +103,8 @@ internal static class ClientHelperHooks
|
|||
private const int TotalStackVa = 0x0081D7F0; // total_stack
|
||||
// CM_Inventory::Event_StackableMerge — public merge-stack API (from Chorizite map).
|
||||
private const int EventStackableMergeVa = 0x006ACDD0;
|
||||
// CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned).
|
||||
private const int EventGiveObjectRequestVa = 0x006ACA60;
|
||||
private const int UseObjectVa = 0x00565750;
|
||||
private const int PlayerSystemVa = 0x0087119C;
|
||||
private const int InqPlayerCoordsVa = 0x00560E00;
|
||||
|
|
@ -114,6 +125,7 @@ internal static class ClientHelperHooks
|
|||
private static MoveItemExternalDelegate? _moveItemExternal;
|
||||
private static MoveItemInternalDelegate? _moveItemInternal;
|
||||
private static EventStackableMergeDelegate? _eventStackableMerge;
|
||||
private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest;
|
||||
private static InqPlayerCoordsDelegate? _inqPlayerCoords;
|
||||
private static GetPlayerIdDelegate? _getPlayerId;
|
||||
private static AddTextToScrollDelegate? _addTextToScroll;
|
||||
|
|
@ -138,6 +150,7 @@ internal static class ClientHelperHooks
|
|||
public static bool HasMoveItemInternal => _moveItemInternal != null;
|
||||
public static bool HasSplitStackInternal => _moveItemInternal != null;
|
||||
public static bool HasMergeStackInternal => _eventStackableMerge != null;
|
||||
public static bool HasGiveObjectTo => _eventGiveObjectRequest != null;
|
||||
public static bool HasGetCurCoords => _inqPlayerCoords != null;
|
||||
public static bool HasGetPlayerId => _getPlayerId != null;
|
||||
public static bool HasGetGroundContainerId => true;
|
||||
|
|
@ -146,25 +159,99 @@ internal static class ClientHelperHooks
|
|||
public static bool HasSalvagePanel => _sendNoticeOpenSalvagePanel != null && _gmSalvageUIAddNewItem != null && _gmSalvageUISalvage != null;
|
||||
private static int _currentGroundContainerId;
|
||||
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
|
||||
// The *Va consts above are FALLBACKs; these signatures (verified unique + landing exactly
|
||||
// at the VA offline via tools/pe_pattern.py) are the source of truth, surviving AC-patch /
|
||||
// ACE-rebuild drift. UseObjectOn/UseEquippedItem are sibling templates differing only in a
|
||||
// trailing immediate (0x00 vs 0x01) — both run long to stay unique. null = wildcard (rel32).
|
||||
private static readonly byte?[] PatSetSelectedObject = [ 0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54 ];
|
||||
private static readonly byte?[] PatUseObject = [ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x56, 0x8B, 0xF1, 0x74, 0x11 ];
|
||||
private static readonly byte?[] PatGetAcPlugin = [ 0xA1, 0x54, 0x10, 0x87, 0x00, 0x85, 0xC0, 0x74, 0x03 ];
|
||||
private static readonly byte?[] PatUseObjectOn = [ 0x51, 0x56, 0x8B, 0x74, 0x24, 0x0C, 0x8B, 0x06, 0x8D, 0x4C, 0x24, 0x04, 0x51, 0x56, 0xC7, 0x44, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x20, 0x8B, 0x44, 0x24, 0x14, 0x8B, 0x16, 0x50, 0x56, 0xFF, 0x52, 0x18, 0x8B, 0x4C, 0x24, 0x10, 0x6A, 0x00 ];
|
||||
private static readonly byte?[] PatUseEquippedItem = [ 0x51, 0x56, 0x8B, 0x74, 0x24, 0x0C, 0x8B, 0x06, 0x8D, 0x4C, 0x24, 0x04, 0x51, 0x56, 0xC7, 0x44, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x20, 0x8B, 0x44, 0x24, 0x14, 0x8B, 0x16, 0x50, 0x56, 0xFF, 0x52, 0x18, 0x8B, 0x4C, 0x24, 0x10, 0x6A, 0x01 ];
|
||||
private static readonly byte?[] PatMoveItemExternal = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x4C, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x51, 0x52, 0xE8 ];
|
||||
private static readonly byte?[] PatMoveItemInternal = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x4C, 0x24, 0x14, 0x8B, 0x54, 0x24, 0x0C ];
|
||||
private static readonly byte?[] PatEventStackableMerge = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x54 ];
|
||||
// CM_Inventory::Event_GiveObjectRequest @0x006ACA60. Identical to the merge
|
||||
// pattern except the trailing action-opcode write (give 0xCD vs merge 0x54) —
|
||||
// that last byte is the uniqueness discriminator vs the merge/usewith siblings,
|
||||
// so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via
|
||||
// pe_pattern.py GEN against both acclient copies.
|
||||
private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ];
|
||||
private static readonly byte?[] PatInqPlayerCoords = [ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
|
||||
private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ];
|
||||
private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ];
|
||||
private static readonly byte?[] PatUseWithTargetEvent = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x35 ];
|
||||
private static readonly byte?[] PatSendNoticeOpenSalvagePanel = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0x22 ];
|
||||
private static readonly byte?[] PatGmSalvageUIAddNewItem = [ 0x8B, 0x44, 0x24, 0x04, 0x56, 0x57, 0x50, 0x8B, 0xF9 ];
|
||||
private static readonly byte?[] PatGmSalvageUISalvage = [ 0x83, 0xEC, 0x14, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x8E ];
|
||||
|
||||
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
|
||||
}
|
||||
|
||||
// Phase B: data globals resolved by code-xref (operand at offset 2); the VA consts above
|
||||
// stay as fallbacks. The 7 read/write globals resolve in Probe (cached int); the WidePString
|
||||
// null-buffer resolves at struct static-init via ResolveDataVa.
|
||||
private static readonly byte?[] PatXrefSelectedId = [ 0xC3, 0xA1, null, null, null, null, 0x89, 0x87 ];
|
||||
private static readonly byte?[] PatXrefPrevSelectedId = [ 0x89, 0x3D, null, null, null, null, 0x74, 0x06 ];
|
||||
private static readonly byte?[] PatXrefUiSystem = [ 0x8B, 0x0D, null, null, null, null, 0x53, 0x6A ];
|
||||
private static readonly byte?[] PatXrefSplitAmount = [ 0x00, 0xA1, null, null, null, null, 0x57, 0x50 ];
|
||||
private static readonly byte?[] PatXrefTotalStack = [ 0x10, 0xA1, null, null, null, null, 0x3B, 0xD8 ];
|
||||
private static readonly byte?[] PatXrefPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
|
||||
private static readonly byte?[] PatXrefCommunicationSystem = [ 0x08, 0xA1, null, null, null, null, 0x56, 0xBE ];
|
||||
private static readonly byte?[] PatXrefWideNullBuffer = [ 0x3B, 0x05, null, null, null, null, 0x74, 0xE7 ];
|
||||
private static int _selectedIdAddr = SelectedIdVa;
|
||||
private static int _prevSelectedIdAddr = PreviousSelectedIdVa;
|
||||
private static int _uiSystemAddr = UiSystemVa;
|
||||
private static int _splitAmountAddr = SplitAmountVa;
|
||||
private static int _totalStackAddr = TotalStackVa;
|
||||
private static int _playerSystemAddr = PlayerSystemVa;
|
||||
private static int _commSystemAddr = CommunicationSystemVa;
|
||||
|
||||
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
return new IntPtr(fallbackVa);
|
||||
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
|
||||
}
|
||||
|
||||
public static bool Probe()
|
||||
{
|
||||
try
|
||||
{
|
||||
_setSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(new IntPtr(SetSelectedObjectVa));
|
||||
_useObject = Marshal.GetDelegateForFunctionPointer<UseObjectDelegate>(new IntPtr(UseObjectVa));
|
||||
_getAcPlugin = Marshal.GetDelegateForFunctionPointer<GetAcPluginDelegate>(new IntPtr(GetAcPluginVa));
|
||||
_useObjectOn = Marshal.GetDelegateForFunctionPointer<UseObjectOnDelegate>(new IntPtr(UseObjectOnVa));
|
||||
_useEquippedItem = Marshal.GetDelegateForFunctionPointer<UseEquippedItemDelegate>(new IntPtr(UseEquippedItemVa));
|
||||
_moveItemExternal = Marshal.GetDelegateForFunctionPointer<MoveItemExternalDelegate>(new IntPtr(MoveItemExternalVa));
|
||||
_moveItemInternal = Marshal.GetDelegateForFunctionPointer<MoveItemInternalDelegate>(new IntPtr(MoveItemInternalVa));
|
||||
_eventStackableMerge = Marshal.GetDelegateForFunctionPointer<EventStackableMergeDelegate>(new IntPtr(EventStackableMergeVa));
|
||||
_inqPlayerCoords = Marshal.GetDelegateForFunctionPointer<InqPlayerCoordsDelegate>(new IntPtr(InqPlayerCoordsVa));
|
||||
_getPlayerId = Marshal.GetDelegateForFunctionPointer<GetPlayerIdDelegate>(new IntPtr(GetPlayerIdVa));
|
||||
_addTextToScroll = Marshal.GetDelegateForFunctionPointer<AddTextToScrollDelegate>(new IntPtr(AddTextToScrollVa));
|
||||
_useWithTargetEvent = Marshal.GetDelegateForFunctionPointer<UseWithTargetEventDelegate>(new IntPtr(UseWithTargetEventVa));
|
||||
_sendNoticeOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer<SendNoticeOpenSalvagePanelDelegate>(new IntPtr(SendNoticeOpenSalvagePanelVa));
|
||||
_gmSalvageUIAddNewItem = Marshal.GetDelegateForFunctionPointer<GmSalvageUIAddNewItemDelegate>(new IntPtr(GmSalvageUIAddNewItemVa));
|
||||
_gmSalvageUISalvage = Marshal.GetDelegateForFunctionPointer<GmSalvageUISalvageDelegate>(new IntPtr(GmSalvageUISalvageVa));
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
_statusMessage = "acclient .text not readable for pattern resolve.";
|
||||
RynthLog.Compat($"Compat: helper hooks failed - {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_setSelectedObject = Bind<SetSelectedObjectDelegate>(text, "ClientHelper.SetSelectedObject", PatSetSelectedObject, SetSelectedObjectVa);
|
||||
_useObject = Bind<UseObjectDelegate>(text, "ClientHelper.UseObject", PatUseObject, UseObjectVa);
|
||||
_getAcPlugin = Bind<GetAcPluginDelegate>(text, "ClientHelper.GetAcPlugin", PatGetAcPlugin, GetAcPluginVa);
|
||||
_useObjectOn = Bind<UseObjectOnDelegate>(text, "ClientHelper.UseObjectOn", PatUseObjectOn, UseObjectOnVa);
|
||||
_useEquippedItem = Bind<UseEquippedItemDelegate>(text, "ClientHelper.UseEquippedItem", PatUseEquippedItem, UseEquippedItemVa);
|
||||
_moveItemExternal = Bind<MoveItemExternalDelegate>(text, "ClientHelper.MoveItemExternal", PatMoveItemExternal, MoveItemExternalVa);
|
||||
_moveItemInternal = Bind<MoveItemInternalDelegate>(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa);
|
||||
_eventStackableMerge = Bind<EventStackableMergeDelegate>(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa);
|
||||
_eventGiveObjectRequest = Bind<EventGiveObjectRequestDelegate>(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa);
|
||||
_inqPlayerCoords = Bind<InqPlayerCoordsDelegate>(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa);
|
||||
_getPlayerId = Bind<GetPlayerIdDelegate>(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa);
|
||||
_addTextToScroll = Bind<AddTextToScrollDelegate>(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa);
|
||||
_useWithTargetEvent = Bind<UseWithTargetEventDelegate>(text, "ClientHelper.UseWithTargetEvent", PatUseWithTargetEvent, UseWithTargetEventVa);
|
||||
_sendNoticeOpenSalvagePanel = Bind<SendNoticeOpenSalvagePanelDelegate>(text, "ClientHelper.SendNotice_OpenSalvagePanel", PatSendNoticeOpenSalvagePanel, SendNoticeOpenSalvagePanelVa);
|
||||
_gmSalvageUIAddNewItem = Bind<GmSalvageUIAddNewItemDelegate>(text, "ClientHelper.gmSalvageUI_AddNewItem", PatGmSalvageUIAddNewItem, GmSalvageUIAddNewItemVa);
|
||||
_gmSalvageUISalvage = Bind<GmSalvageUISalvageDelegate>(text, "ClientHelper.gmSalvageUI_Salvage", PatGmSalvageUISalvage, GmSalvageUISalvageVa);
|
||||
_selectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_selected_id", PatXrefSelectedId, 2, SelectedIdVa).Address.ToInt32();
|
||||
_prevSelectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_previous_selected_id", PatXrefPrevSelectedId, 2, PreviousSelectedIdVa).Address.ToInt32();
|
||||
_uiSystemAddr = HookResolver.ResolveData(text, "ClientHelper.ClientUISystem", PatXrefUiSystem, 2, UiSystemVa).Address.ToInt32();
|
||||
_splitAmountAddr = HookResolver.ResolveData(text, "ClientHelper.split_amount", PatXrefSplitAmount, 2, SplitAmountVa).Address.ToInt32();
|
||||
_totalStackAddr = HookResolver.ResolveData(text, "ClientHelper.total_stack", PatXrefTotalStack, 2, TotalStackVa).Address.ToInt32();
|
||||
_playerSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
|
||||
_commSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CommunicationSystem", PatXrefCommunicationSystem, 2, CommunicationSystemVa).Address.ToInt32();
|
||||
_initialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers.");
|
||||
|
|
@ -186,6 +273,19 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool SetSelectedObjectId(uint objectId)
|
||||
{
|
||||
// Marshal onto AC's main thread. AC's SetSelectedObject (0x0058D110)
|
||||
// rewrites the selection/targeting UIElement subtree; off the pump thread
|
||||
// it raced AC's own main-thread UI walk and corrupted a UIElement ->
|
||||
// the deterministic write-AV at acclient+0x60D1D (UIElement smart-ptr
|
||||
// refcount writeback into read-only .text; native-crash.log captured it
|
||||
// on TWO threads at once during corpse-loot target selection, 2026-06-13).
|
||||
// This was the last AC-mutating helper still calling AC directly off-thread
|
||||
// (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes
|
||||
// this on the main thread, where the gate is satisfied and it runs directly.
|
||||
// SelectItem() funnels through here, so this one gate covers both.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueSetSelectedObject(objectId);
|
||||
|
||||
if (_setSelectedObject == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -202,26 +302,40 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static uint GetSelectedItemId()
|
||||
{
|
||||
return ReadUInt32(SelectedIdVa);
|
||||
return ReadUInt32(_selectedIdAddr);
|
||||
}
|
||||
|
||||
public static uint GetPreviousSelectedItemId()
|
||||
{
|
||||
return ReadUInt32(PreviousSelectedIdVa);
|
||||
return ReadUInt32(_prevSelectedIdAddr);
|
||||
}
|
||||
|
||||
public static bool UseObject(uint objectId)
|
||||
{
|
||||
// P1 marshalling: looting's open-corpse / pick-up use-action runs on AC's
|
||||
// main thread (via the OnEndScene drain), not off the pump thread. Off-thread
|
||||
// UseObject mutated AC's animation sequence (CSequence) and corrupted it ->
|
||||
// the CSequence::update_internal AV captured after looting was enabled.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueUseObject(objectId);
|
||||
|
||||
if (_useObject == null || !IsValidObjectId(objectId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr uiSystem = ReadPointer(UiSystemVa);
|
||||
IntPtr uiSystem = ReadPointer(_uiSystemAddr);
|
||||
if (uiSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
// Reconcile the busy this open/use leaks (same source-fix as casts):
|
||||
// UseObject bumps m_cBusy but no retail completion handler runs to
|
||||
// decrement it, so corpse-open grinds left the plugin force-clearing
|
||||
// every ~2s. Snapshot the delta; BusyCountHooks decrements it once
|
||||
// the use-reach gesture completes. Both run on AC's main thread here.
|
||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||
_useObject(uiSystem, objectId);
|
||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
|
|
@ -232,12 +346,23 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool UseObjectOn(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
// Marshal onto AC's main thread (off-thread use-on-target mutates AC's
|
||||
// object/animation graph and corrupts it — see UseObject). Drain re-invokes
|
||||
// this on the main thread, where the gate is satisfied and it runs directly.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId);
|
||||
|
||||
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Reconcile leaked busy (same source-fix as casts / UseObject) — a
|
||||
// use-on-target (e.g. PetManager essence refill) bumps m_cBusy with
|
||||
// no retail completion decrement.
|
||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||
_useWithTargetEvent(sourceObjectId, targetObjectId);
|
||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||
LogInteraction($"UseObjectOn invoked via Event_UseWithTargetEvent source=0x{sourceObjectId:X8} target=0x{targetObjectId:X8}");
|
||||
return true;
|
||||
}
|
||||
|
|
@ -250,6 +375,9 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId);
|
||||
|
||||
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
return false;
|
||||
|
||||
|
|
@ -270,9 +398,23 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool MoveItemExternal(uint objectId, uint targetContainerId, int amount)
|
||||
{
|
||||
// Marshal onto AC's main thread — off-thread item moves race AC's per-tick
|
||||
// object/container bookkeeping (the looting null-deref AV class).
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount);
|
||||
|
||||
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
|
||||
return false;
|
||||
|
||||
// P0 (2026-06-24): if the target is one of THIS player's OWN containers and it
|
||||
// is full, the native PutItemInContainer slot-table walk (FUN_00588f70) AVs
|
||||
// instead of failing. Fail CLOSED here. Non-owned targets (trade/give to
|
||||
// another player, NPCs, world containers) are NOT gated — they pass through.
|
||||
// Runs on the main thread (marshalled above) so the ownership/capacity/count
|
||||
// reads are authoritative. See AutoCram crash deep-dive.
|
||||
if (IsFullOwnedContainer(targetContainerId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
|
||||
|
|
@ -288,14 +430,32 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount);
|
||||
|
||||
if (_moveItemInternal == null) return false;
|
||||
if (!IsValidObjectId(objectId)) return false;
|
||||
if (!IsValidContainerId(targetContainerId)) return false;
|
||||
if (slot < 0) return false;
|
||||
if (amount <= 0) return false;
|
||||
|
||||
// P0 (2026-06-24): fail CLOSED if the target is one of THIS player's OWN
|
||||
// containers and it is full — the native slot-table walk (FUN_00588f70) AVs
|
||||
// on a full owned pack rather than failing. Non-owned targets pass through.
|
||||
if (IsFullOwnedContainer(targetContainerId))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// P0 (2026-06-24): defensively restore the whole-move split globals to
|
||||
// their default 1/1 state before the send, so a leaked split state from a
|
||||
// prior SplitStackInternal can never force the 0x55 specific-slot path
|
||||
// (which honors `slot` and can target a populated slot). 1/1 == opcode 0x19
|
||||
// (PutItemInContainer, first-empty-slot), which is what MoveItemInternal
|
||||
// callers expect.
|
||||
Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1);
|
||||
Marshal.WriteInt32(new IntPtr(_totalStackAddr), 1);
|
||||
|
||||
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
|
||||
// uninitialized Decal plugin pointer at DAT_00871054.
|
||||
//
|
||||
|
|
@ -327,6 +487,9 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount);
|
||||
|
||||
if (_moveItemInternal == null) return false;
|
||||
if (!IsValidObjectId(objectId)) return false;
|
||||
if (!IsValidContainerId(targetContainerId)) return false;
|
||||
|
|
@ -338,8 +501,8 @@ internal static class ClientHelperHooks
|
|||
// Force split_amount < total_stack so FUN_00588f70 takes the split
|
||||
// path. The actual values aren't sent on the wire — FUN_00588f70
|
||||
// only uses them to pick which sub-function to dispatch to.
|
||||
Marshal.WriteInt32(new IntPtr(SplitAmountVa), amount);
|
||||
Marshal.WriteInt32(new IntPtr(TotalStackVa), amount + 1);
|
||||
Marshal.WriteInt32(new IntPtr(_splitAmountAddr), amount);
|
||||
Marshal.WriteInt32(new IntPtr(_totalStackAddr), amount + 1);
|
||||
|
||||
_moveItemInternal(IntPtr.Zero, objectId, targetContainerId, slot, amount);
|
||||
return true;
|
||||
|
|
@ -348,6 +511,17 @@ internal static class ClientHelperHooks
|
|||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// P0 (2026-06-24): restore the split globals to their default whole-move
|
||||
// state (1/1). They were previously written above and never restored,
|
||||
// leaving a leaked state that could push a later plain MoveItemInternal
|
||||
// onto the 0x55 specific-slot path. DORMANT today (AutoStack uses
|
||||
// MergeStackInternal) but fixed defensively. Writes are individually
|
||||
// try/caught so a failed restore can't escape the finally.
|
||||
try { Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1); } catch { }
|
||||
try { Marshal.WriteInt32(new IntPtr(_totalStackAddr), 1); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -365,6 +539,9 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
|
||||
|
||||
if (_eventStackableMerge == null) return false;
|
||||
if (!IsValidObjectId(sourceObjectId)) return false;
|
||||
if (!IsValidObjectId(targetObjectId)) return false;
|
||||
|
|
@ -411,6 +588,39 @@ internal static class ClientHelperHooks
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Give an item to an NPC (or another player) via the canonical public API
|
||||
/// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give
|
||||
/// GameAction, the same path the drag-onto-NPC UI uses. This is the CORRECT
|
||||
/// give-to-NPC primitive; MoveItemExternal is move-to-container and does not
|
||||
/// give. amount=0 gives the whole object; positive = partial stack.
|
||||
/// </summary>
|
||||
public static bool GiveObjectTo(uint objectId, uint targetId, int amount = 0)
|
||||
{
|
||||
// Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's
|
||||
// per-tick object/container bookkeeping (the looting null-deref AV class),
|
||||
// exactly like MoveItemExternal / MergeStackInternal.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount);
|
||||
|
||||
if (_eventGiveObjectRequest == null) return false;
|
||||
if (!IsValidObjectId(objectId)) return false;
|
||||
if (!IsValidObjectId(targetId)) return false;
|
||||
if (amount < 0) return false;
|
||||
|
||||
try
|
||||
{
|
||||
byte rv = _eventGiveObjectRequest(objectId, targetId, amount);
|
||||
RynthLog.Verbose($"Compat: Event_GiveObjectRequest item=0x{objectId:X8} -> target=0x{targetId:X8} amount={amount} rv={rv}");
|
||||
return rv != 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_GiveObjectRequest threw - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetCurCoords(out double northSouth, out double eastWest)
|
||||
{
|
||||
northSouth = 0;
|
||||
|
|
@ -421,7 +631,7 @@ internal static class ClientHelperHooks
|
|||
|
||||
try
|
||||
{
|
||||
IntPtr playerSystem = ReadPointer(PlayerSystemVa);
|
||||
IntPtr playerSystem = ReadPointer(_playerSystemAddr);
|
||||
if (playerSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
|
|
@ -491,14 +701,106 @@ internal static class ClientHelperHooks
|
|||
return containerId != 0;
|
||||
}
|
||||
|
||||
// P0 (2026-06-24): shared owned-container full-check used by MoveItemInternal AND
|
||||
// MoveItemExternal. Returns true ONLY when `target` is a container owned by the
|
||||
// local player (the main pack, or a sub-pack/foci that roots at the player) AND it
|
||||
// is full / its capacity-or-count can't be resolved (fail CLOSED).
|
||||
//
|
||||
// For ANY non-owned target — another player (trade/give), an NPC, a corpse, a
|
||||
// world/landscape container, or an un-resolvable object — this returns FALSE so the
|
||||
// caller passes the move through UNCHANGED. Trade/give is therefore never blocked.
|
||||
// The crash this guards (native PutItemInContainer slot-table walk FUN_00588f70
|
||||
// AVing on a full pack) only ever happens on the player's OWN pack.
|
||||
//
|
||||
// MUST be called only after the caller has marshalled onto AC's main thread (both
|
||||
// MoveItemInternal/External early-return-enqueue off-thread), so the PWD ownership
|
||||
// read, ITEMS_CAPACITY read, and GetNumContainedItems walk are all authoritative
|
||||
// and the off-thread read-AV class does not apply.
|
||||
private static bool IsFullOwnedContainer(uint target)
|
||||
{
|
||||
uint player = GetPlayerId();
|
||||
if (player == 0)
|
||||
return false; // can't resolve self -> treat as NOT owned -> pass through (never block trade)
|
||||
|
||||
bool isMainPack = target == player;
|
||||
bool owned = isMainPack;
|
||||
if (!owned)
|
||||
{
|
||||
// One-hop ownership: AC inventory is two levels deep — the player holds
|
||||
// loose items and sub-packs directly, so an owned sub-pack/foci has
|
||||
// _containerID == player (or _wielderID == player for a wielded
|
||||
// container). Read straight from the target's PublicWeenieDesc on the main
|
||||
// thread (page-probed + try/caught: returns false, never AVs).
|
||||
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(target, out uint containerID, out uint wielderID, out _))
|
||||
return false; // can't resolve target ownership -> NOT provably owned -> pass through
|
||||
owned = containerID == player || wielderID == player;
|
||||
}
|
||||
|
||||
if (!owned)
|
||||
return false; // non-owned target (trade/give/NPC/world) -> NEVER gate
|
||||
|
||||
// Owned target: compute free = capacity - count, all on the main thread.
|
||||
if (!ClientObjectHooks.TryGetObjectIntProperty(target, 6 /* ITEMS_CAPACITY */, out int capacity))
|
||||
capacity = 0;
|
||||
if (isMainPack && capacity <= 0)
|
||||
capacity = 102; // main-pack PWD capacity may not reflect the 102 item-slot
|
||||
// cap; mirror the proven plugin constant so a cold/unresolved
|
||||
// read does NOT fail-close every main-pack move.
|
||||
if (capacity <= 0)
|
||||
return true; // sub-pack capacity unresolved -> fail CLOSED (don't risk the walk)
|
||||
|
||||
int count = ClientObjectHooks.GetNumContainedItems(target); // AC's own walk; -1 if unavailable
|
||||
if (count < 0)
|
||||
return true; // count unresolved -> fail CLOSED
|
||||
|
||||
// GetNumContainedItems can only ever OVER-count (if it includes nested packs)
|
||||
// -> free UNDER-stated -> conservative/safe. It never under-counts its own
|
||||
// container, so a genuinely full owned pack can never slip through.
|
||||
return (capacity - count) < 1;
|
||||
}
|
||||
|
||||
// Rate-limit + reentry guard for WriteToChat. AC's AddTextToScroll
|
||||
// (0x005649F0) consistently AVs at 0x00460D1D after sustained re-entry
|
||||
// from inside its own chat-add path (observed when RynthAi's buff retry
|
||||
// loop spammed the same "Casting: X" message dozens of times). Plus we
|
||||
// also hook the same function in ChatCallbackHooks.IncomingChatAddTextDetour,
|
||||
// which fires when AC processes our own WriteToChat output — guard
|
||||
// against unbounded recursion into ourselves.
|
||||
private const int WriteToChatMinIntervalMs = 100;
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void EnsureChatRateLimiterReady() { /* triggers static init */ }
|
||||
private static long _lastWriteToChatTick;
|
||||
[ThreadStatic] private static int _writeToChatDepth;
|
||||
|
||||
public static bool WriteToChat(string? text, int chatType)
|
||||
{
|
||||
if (_addTextToScroll == null || string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
// Off AC's main thread: rate-limit the spam, then marshal. Running
|
||||
// AddTextToScroll off-thread races AC's chat-scroll buffer and corrupts it ->
|
||||
// the recurring 0x00460D1D write-AV (killed a 5h+ session 2026-06-05). The
|
||||
// rate-limit lives HERE (not on the drain path) so bot retry bursts are
|
||||
// dropped before they queue, and drained messages are never re-dropped.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
long last = System.Threading.Interlocked.Read(ref _lastWriteToChatTick);
|
||||
if (last != 0 && now - last < WriteToChatMinIntervalMs)
|
||||
return false;
|
||||
System.Threading.Interlocked.Exchange(ref _lastWriteToChatTick, now);
|
||||
return AcMainThreadQueue.EnqueueWriteToChat(text!, chatType);
|
||||
}
|
||||
|
||||
// On AC's main thread (drain, or a legit main-thread caller): execute directly.
|
||||
// Re-entry guard: AC's AddTextToScroll calls back into our hook chain, which
|
||||
// may re-enter WriteToChat. One level is fine; deeper risks the crash pattern.
|
||||
if (_writeToChatDepth > 0)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr communicationSystem = ReadPointer(CommunicationSystemVa);
|
||||
IntPtr communicationSystem = ReadPointer(_commSystemAddr);
|
||||
if (communicationSystem == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
|
|
@ -506,11 +808,21 @@ internal static class ClientHelperHooks
|
|||
if (line.Length == 0)
|
||||
return false;
|
||||
|
||||
// Strip any control chars that might confuse AC's chat tokenizer.
|
||||
// The previous WriteToChat crashes correlated with bursts of
|
||||
// bot retries that may have left malformed text in flight.
|
||||
foreach (char c in line)
|
||||
{
|
||||
if (c < 0x20 && c != '\t')
|
||||
return false; // bail rather than feed AC bad input.
|
||||
}
|
||||
|
||||
ushort[] chars = new ushort[line.Length + 1]; // +1 for null terminator (wcslen requirement)
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
chars[i] = line[i];
|
||||
|
||||
var wide = WidePString.Create(chars);
|
||||
_writeToChatDepth++;
|
||||
try
|
||||
{
|
||||
return _addTextToScroll(
|
||||
|
|
@ -522,6 +834,7 @@ internal static class ClientHelperHooks
|
|||
}
|
||||
finally
|
||||
{
|
||||
_writeToChatDepth--;
|
||||
wide.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -623,6 +936,7 @@ internal static class ClientHelperHooks
|
|||
return false;
|
||||
|
||||
RynthLog.Verbose($"Compat: InvokeParser text='{line}'");
|
||||
LogoffOriginProbe.RecordChat("InvokeChatParser", line);
|
||||
return ChatCommandDispatcher.Dispatch(line);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -642,6 +956,7 @@ internal static class ClientHelperHooks
|
|||
_moveItemExternal = null;
|
||||
_moveItemInternal = null;
|
||||
_eventStackableMerge = null;
|
||||
_eventGiveObjectRequest = null;
|
||||
_inqPlayerCoords = null;
|
||||
_getPlayerId = null;
|
||||
_addTextToScroll = null;
|
||||
|
|
@ -686,12 +1001,26 @@ internal static class ClientHelperHooks
|
|||
return Marshal.ReadIntPtr(new IntPtr(address));
|
||||
}
|
||||
|
||||
// WidePString (AC1Legacy::PStringBase<ushort>) helper fns — pattern-resolved (1a, 2026-06-05).
|
||||
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
|
||||
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];
|
||||
|
||||
// Resolve a fn-ptr for static-init field use; returns the fallback VA (never null) on a
|
||||
// total miss so the WidePString call sites keep their non-null assumption (old behavior).
|
||||
private static unsafe void* ResolveFnPtr(string name, byte?[] pattern, int fallbackVa)
|
||||
{
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
return (void*)fallbackVa;
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
|
||||
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct WidePString
|
||||
{
|
||||
private static readonly IntPtr NullWideBufferVa = new(0x00818340);
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, ushort*, void> Ctor = (delegate* unmanaged[Thiscall]<WidePString*, ushort*, void>)0x00402730;
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, void> Dtor = (delegate* unmanaged[Thiscall]<WidePString*, void>)0x004011B0;
|
||||
private static readonly IntPtr NullWideBufferVa = ResolveDataVa("ClientHelper.PStringWide_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, ushort*, void> Ctor = (delegate* unmanaged[Thiscall]<WidePString*, ushort*, void>)ResolveFnPtr("ClientHelper.PStringBaseW_ctor", PatWidePStringCtor, 0x00402730);
|
||||
private static readonly delegate* unmanaged[Thiscall]<WidePString*, void> Dtor = (delegate* unmanaged[Thiscall]<WidePString*, void>)ResolveFnPtr("ClientHelper.PStringBaseW_dtor", PatWidePStringDtor, 0x004011B0);
|
||||
|
||||
public IntPtr CharBuffer;
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -11,6 +11,17 @@ internal static class CombatActionHooks
|
|||
{
|
||||
private const int QueryHealthResponseVa = 0x006AA900;
|
||||
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-06) ─────────────
|
||||
// The cast/tick VAs were previously bound by raw VA + in-module/warn-only-prologue checks.
|
||||
// These signatures (verified unique + landing exactly at the VA offline via
|
||||
// tools/pe_pattern.py) are now the source of truth; the VA stays as logged fallback.
|
||||
// GetMagicSystem/FreeHandsAndCastSpell are invoked via the SEH trampoline on AC's main
|
||||
// thread — resolving by pattern changes only how the address is found, not the call path.
|
||||
private static readonly byte?[] QueryHealthResponsePattern = [ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x74, 0x18, 0x8B, 0x48, 0x50 ];
|
||||
private static readonly byte?[] CastSpellClientPattern = [ 0x81, 0xEC, 0x48, 0x01, 0x00, 0x00, 0x53, 0x56 ];
|
||||
private static readonly byte?[] GetMagicSystemPattern = [ 0xA1, 0x4C, 0x14, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
|
||||
private static readonly byte?[] FreeHandsAndCastSpellPattern = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x8B, 0x88, 0xB8, 0x00, 0x00, 0x00, 0x8B, 0x11, 0xFF, 0x92, 0xC0, 0x00, 0x00, 0x00, 0x8B, 0x44 ];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool TargetedMeleeAttackDelegate(uint targetId, int attackHeight, float powerLevel);
|
||||
|
||||
|
|
@ -61,6 +72,18 @@ internal static class CombatActionHooks
|
|||
private static RequestIdDelegate? _requestId;
|
||||
private static CastSpellDelegate? _castSpell;
|
||||
private static CastSpellClientDelegate? _castSpellClient;
|
||||
private static IntPtr _castSpellClientPtr;
|
||||
|
||||
// RC2-proven explicit-target cast (no SelectItem / global selection). VAs verified
|
||||
// against acclient.map. GetMagicSystem returns the ClientMagicSystem singleton ('this');
|
||||
// FreeHandsAndCastSpell(this, spellId, targetId) takes the target as an EXPLICIT arg, so
|
||||
// it never reads AC's selected-object global ([singleton+0xF4]) the way CastSpell(...,1)
|
||||
// @ 0x00568DE0 does — which is why it survives being marshalled onto AC's game tick.
|
||||
private const int GetMagicSystemVa = 0x00567C00; // void* __cdecl GetMagicSystem()
|
||||
private const int FreeHandsAndCastSpellVa = 0x00567C90; // void __thiscall FreeHandsAndCastSpell(this, uint spellId, uint targetId)
|
||||
private static IntPtr _getMagicSystemPtr;
|
||||
private static IntPtr _freeHandsCastPtr;
|
||||
private static int _sehAvLogCount;
|
||||
private static QueryHealthResponseDelegate? _queryHealthResponseDetour;
|
||||
private static QueryHealthResponseDelegate? _originalQueryHealthResponse;
|
||||
private static QueryHealthResponseDelegate? _identifyObjectDetour;
|
||||
|
|
@ -206,7 +229,7 @@ internal static class CombatActionHooks
|
|||
{
|
||||
int requestIdVa = textSection.TextBaseVa + requestIdFuncOff;
|
||||
_requestId = Marshal.GetDelegateForFunctionPointer<RequestIdDelegate>(new IntPtr(requestIdVa));
|
||||
RynthLog.Verbose($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
|
||||
RynthLog.Compat($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -217,34 +240,84 @@ internal static class CombatActionHooks
|
|||
{
|
||||
int castSpellVa = textSection.TextBaseVa + castSpellFuncOff;
|
||||
_castSpell = Marshal.GetDelegateForFunctionPointer<CastSpellDelegate>(new IntPtr(castSpellVa));
|
||||
RynthLog.Verbose($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
|
||||
RynthLog.Compat($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: CastSpell (0x4A) not found — magic combat unavailable.");
|
||||
}
|
||||
|
||||
// ClientMagicSystem::CastSpell — direct VA from Chorizite.
|
||||
// Static Cdecl: void CastSpell(uint spellId, byte targetIsSelected)
|
||||
// ClientMagicSystem::CastSpell — static Cdecl:
|
||||
// void CastSpell(uint spellId, byte targetIsSelected)
|
||||
// Uses the currently selected target (from SelectItem).
|
||||
if (SmartBoxLocator.IsPointerInModule(new IntPtr(ClientMagicSystemCastSpellVa)))
|
||||
//
|
||||
// The in-module check uses `textSection` (already read above), NOT
|
||||
// SmartBoxLocator.IsPointerInModule. SmartBoxLocator's bounds are
|
||||
// populated only by its own Probe(), which runs lazily at the first
|
||||
// TryGetSmartBox (around login) — long AFTER this early init step
|
||||
// (ClientActionHooks.Initialize). IsPointerInModule therefore always
|
||||
// saw _moduleBase==0 here and fail-closed for EVERY pointer, so this
|
||||
// correct VA was rejected on essentially every launch and casting
|
||||
// was forced onto the mis-bound _castSpell pattern fallback — the
|
||||
// root cause of the AC-side near-null write AV (0x00568DE0 logged
|
||||
// "outside module"; AC crashed at 0x00416C86 [null+0x28] /
|
||||
// 0x0055FA24 [null+0x40]). acclient.exe is byte-identical to retail
|
||||
// (only PE-header metadata differs) so this retail VA is valid here;
|
||||
// it is validated live below per the no-blind-decompile-RVA rule.
|
||||
HookResolver.ResolveResult csRes = HookResolver.Resolve(textSection, "CombatAction.CastSpellClient", CastSpellClientPattern, ClientMagicSystemCastSpellVa);
|
||||
if (csRes.Success)
|
||||
{
|
||||
_castSpellClient = Marshal.GetDelegateForFunctionPointer<CastSpellClientDelegate>(
|
||||
new IntPtr(ClientMagicSystemCastSpellVa));
|
||||
RynthLog.Verbose($"Compat: ClientMagicSystem::CastSpell bound at 0x{ClientMagicSystemCastSpellVa:X8}");
|
||||
_castSpellClient = Marshal.GetDelegateForFunctionPointer<CastSpellClientDelegate>(csRes.Address);
|
||||
_castSpellClientPtr = csRes.Address;
|
||||
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell bound at 0x{csRes.Address.ToInt32():X8} ({csRes.Detail})");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: ClientMagicSystem::CastSpell VA outside module — unavailable.");
|
||||
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell VA 0x{ClientMagicSystemCastSpellVa:X8} unresolved — unavailable.");
|
||||
}
|
||||
|
||||
// Explicit-target cast pair (RC2-proven): GetMagicSystem + FreeHandsAndCastSpell,
|
||||
// invoked via the SEH trampoline on AC's main thread. Replaces the SelectItem +
|
||||
// CastSpell(targetIsSelected=1) two-step for TARGETED casts (the global-selection
|
||||
// read that didn't survive being marshalled onto the tick).
|
||||
HookResolver.ResolveResult gmsRes = HookResolver.Resolve(textSection, "CombatAction.GetMagicSystem", GetMagicSystemPattern, GetMagicSystemVa);
|
||||
HookResolver.ResolveResult fhcRes = HookResolver.Resolve(textSection, "CombatAction.FreeHandsAndCastSpell", FreeHandsAndCastSpellPattern, FreeHandsAndCastSpellVa);
|
||||
if (gmsRes.Success && fhcRes.Success)
|
||||
{
|
||||
_getMagicSystemPtr = gmsRes.Address;
|
||||
_freeHandsCastPtr = fhcRes.Address;
|
||||
RynthLog.Compat(
|
||||
$"Compat: explicit-target cast bound — GetMagicSystem=0x{gmsRes.Address.ToInt32():X8} ({gmsRes.Detail}), " +
|
||||
$"FreeHandsAndCastSpell=0x{fhcRes.Address.ToInt32():X8} ({fhcRes.Detail}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat(
|
||||
$"Compat: explicit-target cast VAs unresolved (gms={gmsRes.Success}, fhc={fhcRes.Success}) — " +
|
||||
"targeted casts fail closed.");
|
||||
}
|
||||
|
||||
InstallQueryHealthResponseHook();
|
||||
InstallInnerDispatcherHook();
|
||||
// InstallInnerDispatcherHook intentionally disabled 2026-05-14.
|
||||
// Its anchor-then-scan-backward heuristic (find CALL to
|
||||
// QueryHealthResponseVa, then walk back ≤0x1000 bytes looking for
|
||||
// `SUB ESP, 0x1C0`) lands on a function that — on this ACE
|
||||
// build at least — AC traverses during world-entry, and the
|
||||
// MinHook trampoline at that entry point hangs the load (player
|
||||
// stuck on "Entering World", no SendLoginCompleteNotification).
|
||||
// The 0xF658 character-list and 0xC9 IdentifyObject packets we
|
||||
// were collecting here are redundantly captured by SmartBoxHooks'
|
||||
// DispatchSmartBoxEvent / DispatchGameEvent hooks (see
|
||||
// SmartBoxHooks.DispatchSmartBoxEventDetour → ProcessPotentialCharacterMessage
|
||||
// at line ~117). Re-enabling requires a tighter pattern that
|
||||
// *uniquely* identifies the intended inner dispatcher, plus a
|
||||
// verification that AC's world-load path is unaffected.
|
||||
// InstallInnerDispatcherHook();
|
||||
|
||||
IsInitialized = true;
|
||||
_statusMessage = "Ready.";
|
||||
|
||||
RynthLog.Verbose($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
|
||||
RynthLog.Compat($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -258,6 +331,9 @@ internal static class CombatActionHooks
|
|||
|
||||
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
|
||||
|
||||
if (_meleeAttack == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -273,6 +349,9 @@ internal static class CombatActionHooks
|
|||
|
||||
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
|
||||
|
||||
if (_missileAttack == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -288,6 +367,28 @@ internal static class CombatActionHooks
|
|||
|
||||
public static bool ChangeCombatMode(int combatMode)
|
||||
{
|
||||
// P1 marshalling: off-thread mutators run on AC's main thread (via the
|
||||
// OnEndScene drain) so AC mutates its single-threaded object/animation
|
||||
// (CSequence) state on the thread that updates it — eliminating the
|
||||
// off-thread-mutation corruption class (e.g. the CSequence::update_internal
|
||||
// AV). On the main thread (incl. the drain) this executes directly.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
|
||||
|
||||
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
|
||||
// scanning for the function that writes network opcode 0x53
|
||||
// (CM_Combat::Event_ChangeCombatMode) — that is the packet sender and
|
||||
// nothing more. It tells the server and leaves the client's own UI
|
||||
// untouched, so the stance widgets never learn and the toolbar icon sits
|
||||
// on Peace while the character is in Magic and casting.
|
||||
//
|
||||
// ClientCombatSystem::SetCombatMode is the layer above: it sets the mode
|
||||
// field, sends the same 0x53, AND notifies the UI. Calling it is what a
|
||||
// toolbar click does. Falls through to the raw sender when the hook isn't
|
||||
// installed, so behaviour is unchanged if the pattern ever fails to resolve.
|
||||
if (CombatModeHooks.RequestCombatMode(combatMode))
|
||||
return true;
|
||||
|
||||
if (_changeCombatMode == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -349,36 +450,146 @@ internal static class CombatActionHooks
|
|||
public static bool CastSpell(uint targetId, int spellId)
|
||||
{
|
||||
if (spellId <= 0) return false;
|
||||
if (_castSpellClient == null) return false;
|
||||
|
||||
// Prefer ClientMagicSystem::CastSpell — initiates the full client-side
|
||||
// cast sequence (animation, state, network). The target must already be
|
||||
// selected via SelectItem before calling this.
|
||||
// P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2).
|
||||
// Off the main thread, enqueue the cast; GameTickHooks drains it on AC's
|
||||
// game-logic tick (Client::UseTime) BEFORE _originalUseTime runs, so AC's SAME
|
||||
// tick processes the freshly-set selection + cast (mimics AC's natural
|
||||
// input -> UseTime flow). Attempt 1 (drain AFTER the tick) landed self-buffs but
|
||||
// NOT targeted casts: SelectItem + cast initiated at the END of tick N weren't
|
||||
// processed until tick N+1, by which point the selection was clobbered (target
|
||||
// held hp=50/50, zero damage).
|
||||
//
|
||||
// Off-thread casting is NOT a safe fallback: it races AC's cast/UI state and
|
||||
// AVs UNCAUGHT (0xC0000005 WRITE in UIElement::GetAttribute_Bool, off the main
|
||||
// thread, tid != main) — it killed a 37-min P1 soak. So the cast MUST run on the
|
||||
// main thread; the only open question is landing a targeted cast from the tick,
|
||||
// which the drain-before order is intended to fix. On the main thread (the
|
||||
// UseTime drain, or any main-thread caller) this falls through to the direct
|
||||
// cast below.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId);
|
||||
|
||||
// Call ClientMagicSystem::CastSpell directly off the plugin pump thread.
|
||||
// This is the proven-working casting path (buffs + combat resolve in
|
||||
// chat). The earlier EndScene-marshalled variant (AcMainThreadQueue,
|
||||
// drained from OnEndScene) was REVERTED 2026-05-19: EndScene fires AC's
|
||||
// IncrementBusyCount but is not the context that drives the cast state
|
||||
// machine to completion, so combat casts never produced a projectile /
|
||||
// damage / "You cast" chat — busy leaked, AC's single cast slot jammed
|
||||
// "Casting <spell>" client-wide, and even manual casting died. Do NOT
|
||||
// re-introduce queue/EndScene marshalling for casts.
|
||||
// The documented object-teardown AV (0x0055FA24 [null+0x40] /
|
||||
// 0x00416C86 [null+0x28]) is contained per-callsite by the SEH
|
||||
// trampoline below (__try/__except in RynthCore.SehTrampoline.dll),
|
||||
// which is the correct fix for that AV. AC's CastSpell reads its
|
||||
// "currently selected target" when targetIsSelected=1; SelectItem
|
||||
// first so AC's selection matches the caller's intent.
|
||||
if (_castSpellClient != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte targetIsSelected = targetId != 0 ? (byte)1 : (byte)0;
|
||||
_castSpellClient((uint)spellId, targetIsSelected);
|
||||
// TARGETED cast (targetId != 0): explicit-target path — RC2-proven, NO
|
||||
// SelectItem. GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spellId, targetId).
|
||||
// The old SelectItem + CastSpell(targetIsSelected=1) two-step relied on AC's
|
||||
// global selection ([magicSysSingleton+0xF4], read inside 0x00568DE0) surviving
|
||||
// the marshal onto AC's tick — it didn't (targets held hp=50/50, zero damage).
|
||||
// FreeHandsAndCastSpell takes the target as an explicit arg and auto-readies the
|
||||
// wand, so there is nothing to clobber.
|
||||
if (targetId != 0)
|
||||
{
|
||||
if (SehTrampoline.IsAvailable && _freeHandsCastPtr != IntPtr.Zero && _getMagicSystemPtr != IntPtr.Zero)
|
||||
{
|
||||
IntPtr mgr = SehTrampoline.CdeclPtrVoid(_getMagicSystemPtr, out bool avMgr);
|
||||
if (avMgr || mgr == IntPtr.Zero)
|
||||
{
|
||||
if (System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||
RynthLog.Compat($"[SEH] GetMagicSystem null/AV — targeted cast skipped spell={spellId} target=0x{targetId:X8}");
|
||||
return false;
|
||||
}
|
||||
// Measure the real m_cBusy delta around the call: the direct cast
|
||||
// increments it (wand-ready + cast, often +2) but never registers
|
||||
// the queued action whose completion would decrement — the per-cast
|
||||
// busy leak. BusyCountHooks reconciles the delta once the cast
|
||||
// gesture completes.
|
||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||
bool okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId);
|
||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
|
||||
return okCast;
|
||||
}
|
||||
return false; // trampoline / VAs unavailable — fail closed (never the off-thread SelectItem two-step)
|
||||
}
|
||||
|
||||
// SELF cast (targetId == 0): the proven CastSpell(spellId, targetIsSelected=0)
|
||||
// path — no selection dependency; lands buffs reliably.
|
||||
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
|
||||
{
|
||||
// Same per-cast busy-leak reconciliation as the targeted path —
|
||||
// buff self-casts were the dominant leak source (4322 plugin
|
||||
// clears / 10h soak, nearly all on buffs).
|
||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0);
|
||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");
|
||||
return ok;
|
||||
}
|
||||
|
||||
{
|
||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||
_castSpellClient((uint)spellId, 0);
|
||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Fall through to game action method
|
||||
// Fall through to "refuse" rather than the pattern-scanned
|
||||
// _castSpell — see the comment block on that fallback.
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: direct game action 0x4A (network message only)
|
||||
if (_castSpell == null || targetId == 0)
|
||||
return false;
|
||||
// No safe fallback — fail closed. The pattern-scanned game-action-0x4A
|
||||
// wrapper (_castSpell) resolves to the WRONG function on this
|
||||
// acclient.exe: CombatPrologue (83 EC 0C 53 56 57 E8) is shared by many
|
||||
// AC functions and FindPrologueBefore takes the FIRST match, which is
|
||||
// not the cast wrapper, so calling it would crash AC. The 2026-05-14
|
||||
// "binaries are byte-identical so the pattern is fine" reasoning was
|
||||
// wrong: identity makes the pattern consistently wrong on BOTH retail
|
||||
// and ACE, not correct.
|
||||
// ⚠ 2026-05-18, DUMP-VERIFIED: the AVs at 0x00416C86 [null+0x28] and
|
||||
// 0x0055FA24 [null+0x40] that older notes/comments blamed on this
|
||||
// fallback are NOT cast-related. Resolved via acclient.map they are
|
||||
// DBOCache::DestroyObj and CPlayerSystem::CalculateObjectRangeChecks →
|
||||
// List<ObjectRangeInfo>::remove — AC OBJECT-TEARDOWN code tripping over
|
||||
// a corrupted object/range list (async lifecycle corruption class, not
|
||||
// spellcasting). Do NOT chase CastSpell for these. See
|
||||
// rynthcore_castspell_fallback_pitfall.md / rynthcore_crash_investigation.md.
|
||||
// _castSpellClient (the verified ClientMagicSystem::CastSpell VA bound
|
||||
// in Probe) is the only safe path; if it is unavailable we refuse the
|
||||
// cast. BuffManager.CastSpellInner and CombatManager both handle a
|
||||
// false / no-op return without wedging (skip the spell, retry next
|
||||
// cycle), so refusing is strictly safer than crashing the client.
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
// Called by AcMainThreadQueue.Drain on AC's main thread (EndScene path).
|
||||
// The preceding queued SelectItem entry already set AC's selection, so
|
||||
// cast with targetIsSelected=1. Defensive: never throw into the drain loop.
|
||||
internal static void ExecuteQueuedCast(uint spellId)
|
||||
{
|
||||
if (_castSpellClient == null) return;
|
||||
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
|
||||
{
|
||||
return _castSpell(targetId, spellId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, spellId, 1);
|
||||
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||
RynthLog.Compat($"[SEH] AV in CastSpell spell={spellId} — caught, cast skipped");
|
||||
return;
|
||||
}
|
||||
try { _castSpellClient.Invoke(spellId, 1); } catch { }
|
||||
}
|
||||
|
||||
public static int MapAttackHeight(int uiHeight)
|
||||
|
|
@ -401,6 +612,9 @@ internal static class CombatActionHooks
|
|||
_requestId = null;
|
||||
_castSpell = null;
|
||||
_castSpellClient = null;
|
||||
_castSpellClientPtr = IntPtr.Zero;
|
||||
_getMagicSystemPtr = IntPtr.Zero;
|
||||
_freeHandsCastPtr = IntPtr.Zero;
|
||||
_queryHealthResponseDetour = null;
|
||||
_originalQueryHealthResponse = null;
|
||||
_identifyObjectDetour = null;
|
||||
|
|
@ -505,21 +719,37 @@ internal static class CombatActionHooks
|
|||
return pOriginal(thisPtr, buffer, size);
|
||||
}
|
||||
|
||||
private static int _identifyWireLogCount;
|
||||
private static int _mobHpReadLogCount;
|
||||
|
||||
/// <summary>
|
||||
/// Parses the IdentifyObject response (game event 0xC9) to extract health/maxHealth
|
||||
/// from the CreatureProfile section.
|
||||
/// Layout: [eventType(4)][objectId(4)][flags(4)][success(4)][sections based on flags...]
|
||||
/// Wire serialization order (matches ACE, NOT flag-bit order):
|
||||
/// 0x0001 IntStatsTable, 0x1000 Int64StatsTable, 0x0002 BoolStatsTable,
|
||||
/// 0x0004 FloatStatsTable, 0x0008 StringStatsTable, 0x0010 SpellBook,
|
||||
/// 0x0020 ArmorProfile, 0x0040 CreatureProfile, 0x0080 WeaponProfile,
|
||||
/// 0x0100 HookProfile, ...
|
||||
/// Parses the IdentifyObject response (game event 0xC9) to extract
|
||||
/// health/maxHealth from the CreatureProfile section. Wire format is
|
||||
/// authoritative per ACE AppraiseInfoExtensions.Write / CreatureProfile:
|
||||
///
|
||||
/// header: [_(4)][objectId(4)][Flags(4)][Success(4)] (parser base+0..+15)
|
||||
/// then sections, in ACE *write* order (NOT flag-bit order):
|
||||
/// 0x0001 IntStatsTable hashtbl, entry 8 (u32 key + i32)
|
||||
/// 0x2000 Int64StatsTable hashtbl, entry 12 (u32 key + i64)
|
||||
/// 0x0002 BoolStatsTable hashtbl, entry 8 (u32 key + u32)
|
||||
/// 0x0004 FloatStatsTable hashtbl, entry 12 (u32 key + f64)
|
||||
/// 0x0008 StringStatsTable hashtbl, string entries (u32 key + str16L)
|
||||
/// 0x1000 DidStatsTable hashtbl, entry 8 (u32 key + u32)
|
||||
/// 0x0010 SpellBook list: i32 count + count*u32
|
||||
/// 0x0080 ArmorProfile fixed 32 bytes (8 floats)
|
||||
/// 0x0100 CreatureProfile <-- target
|
||||
/// hashtbl header = ushort count + ushort numBuckets (4 bytes).
|
||||
///
|
||||
/// CreatureProfile: cpFlags(4), Health(4), HealthMax(4),
|
||||
/// if cpFlags&0x8: Str,End,Quick,Coord,Focus,Self,
|
||||
/// Stamina,Mana,StaminaMax,ManaMax (10*4),
|
||||
/// if cpFlags&0x1: AttrHighlights(2)+AttrColors(2).
|
||||
/// </summary>
|
||||
private static void TryParseIdentifyResponse(IntPtr buffer, uint size)
|
||||
internal static void TryParseIdentifyResponse(IntPtr buffer, uint size)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Header: eventType(4) + objectId(4) + flags(4) + success(4) = 16 bytes
|
||||
// Header: _(4) + objectId(4) + flags(4) + success(4) = 16 bytes
|
||||
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
|
||||
uint flags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 8)));
|
||||
uint success = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 12)));
|
||||
|
|
@ -527,71 +757,66 @@ internal static class CombatActionHooks
|
|||
if (success == 0 || objectId == 0)
|
||||
return;
|
||||
|
||||
// CreatureProfile = flag 0x1000 in the retail client
|
||||
if ((flags & 0x1000) == 0)
|
||||
const uint CreatureProfile = 0x0100;
|
||||
if ((flags & CreatureProfile) == 0)
|
||||
return;
|
||||
|
||||
int offset = 16; // Past the header
|
||||
int iSize = (int)size;
|
||||
|
||||
// Skip sections in wire order before CreatureProfile (0x1000):
|
||||
// 0x0001 - IntStatsTable: PHashTable<uint,int> = header(4) + count*8
|
||||
// Skip sections written before CreatureProfile, in ACE write order.
|
||||
if ((flags & 0x0001) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0002 - BoolStatsTable: PHashTable<uint,int> = header(4) + count*8
|
||||
return; // IntStatsTable
|
||||
if ((flags & 0x2000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
|
||||
return; // Int64StatsTable
|
||||
if ((flags & 0x0002) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0004 - FloatStatsTable: PHashTable<uint,double> = header(4) + count*12
|
||||
return; // BoolStatsTable
|
||||
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
|
||||
return;
|
||||
// 0x0008 - StringStatsTable: PHashTable<uint,string> — variable
|
||||
return; // FloatStatsTable
|
||||
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
|
||||
return;
|
||||
// 0x0010 - SpellBook: header(4) + count*4
|
||||
if ((flags & 0x0010) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 4))
|
||||
return;
|
||||
// 0x0020, 0x0040, 0x0080 — unknown fixed sections; bail if present
|
||||
if ((flags & 0x00E0) != 0)
|
||||
return;
|
||||
// 0x0100 - Int64StatsTable: PHashTable<uint,int32> = header(4) + count*8
|
||||
// (retail client serialises "Int64" properties as 32-bit values)
|
||||
if ((flags & 0x0100) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return;
|
||||
// 0x0200, 0x0400, 0x0800 — unknown sections; bail if present
|
||||
if ((flags & 0x0E00) != 0)
|
||||
return; // StringStatsTable
|
||||
if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
|
||||
return; // DidStatsTable
|
||||
if ((flags & 0x0010) != 0 && !SkipPackableListUInt(buffer, iSize, ref offset))
|
||||
return; // SpellBook
|
||||
if ((flags & 0x0080) != 0)
|
||||
{
|
||||
offset += 32; // ArmorProfile = 8 floats, fixed
|
||||
if (offset > iSize)
|
||||
return;
|
||||
}
|
||||
|
||||
// CreatureProfile: cpFlags(4), Health(4), HealthMax(4), ...
|
||||
if (offset + 12 > iSize)
|
||||
return;
|
||||
|
||||
// 0x1000 - CreatureProfile layout:
|
||||
// flags(4), health(4), maxHealth(4),
|
||||
// strength(4), endurance(4), quickness(4), coordination(4), focus(4), self(4),
|
||||
// stamina(4), maxStamina(4), mana(4), maxMana(4)
|
||||
// Total: 4 + 12*4 = 52 bytes
|
||||
if (offset + 52 > iSize)
|
||||
return;
|
||||
uint cpFlags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
|
||||
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
|
||||
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 8)));
|
||||
|
||||
// Skip the 4-byte CreatureProfile header/flags
|
||||
offset += 4;
|
||||
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
|
||||
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
|
||||
// Skip 6 primary attributes (str, end, quick, coord, focus, self) = 24 bytes
|
||||
// Layout: stamina(4), mana(4), maxStamina(4), maxMana(4)
|
||||
uint stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 32)));
|
||||
uint mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
|
||||
uint maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
|
||||
uint maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
|
||||
uint stamina = 0, maxStamina = 0, mana = 0, maxMana = 0;
|
||||
if ((cpFlags & 0x8) != 0 && offset + 52 <= iSize)
|
||||
{
|
||||
// Str(+12) End(+16) Quick(+20) Coord(+24) Focus(+28) Self(+32)
|
||||
// Stamina(+36) Mana(+40) StaminaMax(+44) ManaMax(+48)
|
||||
stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
|
||||
mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
|
||||
maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
|
||||
maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 48)));
|
||||
}
|
||||
|
||||
if (maxHealth > 0 && maxHealth < 1_000_000 && objectId != 0)
|
||||
int log = Interlocked.Increment(ref _identifyWireLogCount);
|
||||
if (log <= 20)
|
||||
RynthLog.Compat($"Compat: identify-wire obj=0x{objectId:X8} flags=0x{flags:X4} cp=0x{cpFlags:X} hp={health}/{maxHealth}");
|
||||
|
||||
if (maxHealth > 0 && maxHealth < 1_000_000)
|
||||
{
|
||||
var vitals = new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana);
|
||||
ObjectQualityCache.SetCreatureVitals(objectId, vitals);
|
||||
|
||||
if (ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr pWeenie) && pWeenie != IntPtr.Zero)
|
||||
ObjectQualityCache.SetMaxHealth(pWeenie, maxHealth);
|
||||
|
||||
float ratio = maxHealth > 0 ? (float)health / maxHealth : 0f;
|
||||
float ratio = (float)health / maxHealth;
|
||||
PluginManager.QueueUpdateHealth(objectId, ratio, health, maxHealth);
|
||||
|
||||
// If this is the player, seed exact max vitals
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId != 0 && objectId == playerId)
|
||||
PlayerVitalsHooks.SeedMaxVitalsFromIdentify(maxHealth, maxStamina, maxMana);
|
||||
|
|
@ -635,6 +860,17 @@ internal static class CombatActionHooks
|
|||
return offset <= size;
|
||||
}
|
||||
|
||||
/// <summary>Skips a PackableList<uint>: int32 count + count*uint32.</summary>
|
||||
private static bool SkipPackableListUInt(IntPtr buffer, int size, ref int offset)
|
||||
{
|
||||
if (offset + 4 > size) return false;
|
||||
int count = Marshal.ReadInt32(IntPtr.Add(buffer, offset));
|
||||
offset += 4;
|
||||
if (count < 0 || count > 100_000) return false;
|
||||
offset += count * 4;
|
||||
return offset <= size;
|
||||
}
|
||||
|
||||
private static void InstallQueryHealthResponseHook()
|
||||
{
|
||||
if (_originalQueryHealthResponse != null)
|
||||
|
|
@ -643,15 +879,13 @@ internal static class CombatActionHooks
|
|||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
return;
|
||||
|
||||
IntPtr responsePtr = new(QueryHealthResponseVa);
|
||||
int textStart = textSection.TextBaseVa;
|
||||
int textEnd = textStart + textSection.Bytes.Length;
|
||||
int responseVa = responsePtr.ToInt32();
|
||||
if (responseVa < textStart || responseVa >= textEnd)
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CombatAction.QueryHealthResponse", QueryHealthResponsePattern, QueryHealthResponseVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
RynthLog.Compat($"Compat: query-health-response hook skipped - invalid address 0x{QueryHealthResponseVa:X8}");
|
||||
RynthLog.Compat($"Compat: query-health-response hook skipped - unresolved 0x{QueryHealthResponseVa:X8}");
|
||||
return;
|
||||
}
|
||||
IntPtr responsePtr = resolved.Address;
|
||||
|
||||
_queryHealthResponseDetour = QueryHealthResponseDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_queryHealthResponseDetour);
|
||||
|
|
@ -678,25 +912,44 @@ internal static class CombatActionHooks
|
|||
// thread so the direct read is safe.
|
||||
uint maxHealth = 0;
|
||||
uint currentHealth = 0;
|
||||
if (ClientObjectHooks.TryGetWeenieObjectPtr(targetId, out IntPtr pWeenie))
|
||||
{
|
||||
if (ObjectQualityCache.TryGetMaxHealth(pWeenie, out uint cached))
|
||||
{
|
||||
maxHealth = cached;
|
||||
}
|
||||
else if (PlayerVitalsHooks.TryReadObjectMaxHealth(pWeenie, out uint queried) && queried > 0)
|
||||
{
|
||||
maxHealth = queried;
|
||||
ObjectQualityCache.SetMaxHealth(pWeenie, queried);
|
||||
}
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
|
||||
if (maxHealth > 0)
|
||||
// Appraisal-only (see SmartBoxHooks.TryQueueHealthUpdate):
|
||||
// emit absolute ONLY from a real appraisal's wire-parsed
|
||||
// CreatureProfile; otherwise max=0 → UI shows %. ACE creature
|
||||
// Inq / pointer-cache maxes are unreliable.
|
||||
if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
|
||||
{
|
||||
maxHealth = exact.MaxHealth;
|
||||
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
|
||||
}
|
||||
else if (targetId != 0 && targetId != playerId)
|
||||
{
|
||||
// No appraisal yet: read the mob's real MaxHealth straight from its
|
||||
// CACQualities (InqAttribute2nd on the qualities sub-object, SEH-
|
||||
// guarded). This is what fills in true HP (e.g. Olthoi Swarm
|
||||
// Harvester = 175) BEFORE the player's appraise skill is high enough
|
||||
// to produce a CreatureProfile. The earlier bug passed the weenie
|
||||
// ptr as `this`; InqAttribute2nd derefs this+0x60 for the attribute
|
||||
// cache, so it MUST get the CACQualities sub-object (resolved inside
|
||||
// TryReadCreatureMaxHealth). Gated to the main thread inside
|
||||
// TryGetQualitiesPtr — this detour runs on AC's game thread.
|
||||
if (ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint mobMax)
|
||||
&& mobMax > 0 && mobMax < 1_000_000)
|
||||
{
|
||||
maxHealth = mobMax;
|
||||
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
|
||||
ObjectQualityCache.SetCreatureVitals(targetId,
|
||||
new CreatureVitals(currentHealth, maxHealth, 0, 0, 0, 0));
|
||||
|
||||
int hlog = Interlocked.Increment(ref _mobHpReadLogCount);
|
||||
if (hlog <= 20)
|
||||
RynthLog.Compat($"Compat: mob-hp qualities-read id=0x{targetId:X8} maxHp={maxHealth} ratio={healthRatio:F3}");
|
||||
}
|
||||
}
|
||||
|
||||
// If this response is for the player, derive true MaxHealth from the ratio.
|
||||
// e.g. health=92541, ratio=0.925 → trueMax ≈ 99999
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f)
|
||||
PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio);
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,18 @@ namespace RynthCore.Engine.Compatibility;
|
|||
|
||||
internal static class CombatModeHooks
|
||||
{
|
||||
private const int SetCombatModeVa = 0x0056CB80;
|
||||
private const int SetCombatModeFallbackVa = 0x0056CB80;
|
||||
|
||||
// ClientCombatSystem::SetCombatMode(int newMode, int playerRequested)
|
||||
// Loads current mode from [esi+0x1C], compares with new arg from [esp+0x14],
|
||||
// jumps if equal. Distinctive 0x0F 0x84 EA 01 00 00 (je rel32 +0x1EA).
|
||||
private static readonly byte?[] SetCombatModePattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x1C,
|
||||
0x57, 0x8B, 0x7C, 0x24, 0x14, 0x3B, 0xF8, 0x8B,
|
||||
0xD8, 0x0F, 0x84, 0xEA, 0x01, 0x00, 0x00, 0x8A,
|
||||
0x44, 0x24, 0x18, 0x84, 0xC0
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void SetCombatModeDelegate(IntPtr thisPtr, int newCombatMode, int playerRequested);
|
||||
|
|
@ -17,38 +28,185 @@ internal static class CombatModeHooks
|
|||
private static SetCombatModeDelegate? _setCombatModeDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _lastObservedCombatMode;
|
||||
// Defaults to NonCombat (not 0) so an off-thread reader that arrives before
|
||||
// the first SetCombatMode detour fire still gets a sane value instead of an
|
||||
// unnormalized 0.
|
||||
private static int _lastObservedCombatMode = CombatActionHooks.CombatModeNonCombat;
|
||||
|
||||
// ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data
|
||||
// ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data.
|
||||
// This is a DATA address (not code), so it can't be pattern-scanned in .text;
|
||||
// it's left as a fallback constant. If the binary's .data layout shifted, the
|
||||
// first dereference would AV and CrashLogger would log it as
|
||||
// ACCESS_VIOLATION inside the engine's thiscall thunk.
|
||||
private const uint CombatSystemPtrVa = 0x0087166C;
|
||||
// Offset of combatMode (COMBAT_MODE) within ClientCombatSystem:
|
||||
// ClientSystem(8) + IInputActionCallback(4) + QualityChangeHandler(4)
|
||||
// + Turbine_RefCount(8) + jump_pending(1) + m_bTrackingTarget(1) + pad(2) = 28
|
||||
private const int CombatModeOffset = 28;
|
||||
|
||||
// Phase B: resolve s_pCombatSystem's address by code-xref ("mov [s_pCombatSystem],esi" =
|
||||
// 89 35 <addr>), operand at offset 2; the VA stays as fallback. Resolved in Initialize.
|
||||
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
|
||||
private static uint _combatSystemPtrAddr = CombatSystemPtrVa;
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current combat mode directly from ClientCombatSystem::combatMode.
|
||||
/// Returns NonCombat if the pointer is null or unreadable.
|
||||
/// </summary>
|
||||
// Deep-audit finding #4 (2026-06-18): this used to raw-dereference the
|
||||
// ClientCombatSystem singleton unconditionally, including off AC's main
|
||||
// thread — a teardown-window read (relog/portal, singleton being torn
|
||||
// down) can land on a freed/mid-reassignment pointer, an uncatchable AV
|
||||
// under NativeAOT. SetCombatModeDetour already runs ON the main thread
|
||||
// (it's the inbound-echo hook) and maintains _lastObservedCombatMode as a
|
||||
// main-thread-verified cache — off-thread callers get that instead of
|
||||
// touching AC memory at all.
|
||||
public static unsafe int ReadCurrentCombatMode()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return Volatile.Read(ref _lastObservedCombatMode);
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr combatSystem = *(IntPtr*)CombatSystemPtrVa;
|
||||
if (combatSystem == IntPtr.Zero)
|
||||
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
|
||||
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
|
||||
return Volatile.Read(ref _lastObservedCombatMode);
|
||||
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
|
||||
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
|
||||
return CombatActionHooks.CombatModeNonCombat;
|
||||
int raw = *(int*)(combatSystem + CombatModeOffset);
|
||||
return NormalizeCombatMode(raw);
|
||||
int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset));
|
||||
|
||||
// Heal the off-thread cache from this live main-thread read.
|
||||
//
|
||||
// _lastObservedCombatMode is only advanced by the detour, which fires
|
||||
// on a mode CHANGE. After a hot reload or a fresh client it starts at
|
||||
// its NonCombat default, so if the character is already in Magic and
|
||||
// stays there, no change ever occurs, the detour never fires, and the
|
||||
// cache stays wrong forever. Off-thread callers then read NonCombat
|
||||
// and request Magic in a loop that cannot succeed — nothing needs
|
||||
// changing — until EnsureMagicMode's deadlock recovery re-equips the
|
||||
// wand and forces a real transition. That is the 8s stance stall seen
|
||||
// at 01:49 (after a client restart) and 10:36 (after a reload) on
|
||||
// 2026-09-03, both visible as an unnecessary unwield/re-wield.
|
||||
//
|
||||
// Safe for the change-detection above: the detour compares against
|
||||
// this value, so healing it to the truth only suppresses events that
|
||||
// would have reported a change that did not happen.
|
||||
Volatile.Write(ref _lastObservedCombatMode, raw);
|
||||
return raw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return CombatActionHooks.CombatModeNonCombat;
|
||||
return Volatile.Read(ref _lastObservedCombatMode);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request a combat-mode change the way the CLIENT does it, by calling
|
||||
/// ClientCombatSystem::SetCombatMode(newMode, playerRequested: 1).
|
||||
///
|
||||
/// Why this exists: CombatActionHooks.ChangeCombatMode binds the function that
|
||||
/// writes network opcode 0x53 (CM_Combat::Event_ChangeCombatMode) and calls it
|
||||
/// directly. That is the bottom of the stack — it tells the SERVER, and nothing
|
||||
/// else. SetCombatMode is the layer above it, and it does three things:
|
||||
/// * sets the client's own mode field,
|
||||
/// * calls CM_Combat::Event_ChangeCombatMode → sends 0x53 to the server,
|
||||
/// * calls CM_Combat::SendNotice_SetCombatMode → notifies the UI widgets
|
||||
/// (gmCombatUI / gmToolbarUI / gmSpellcastingUI each have a
|
||||
/// RecvNotice_SetCombatMode handler).
|
||||
/// Going in below it meant the stance widgets were never told, so the toolbar
|
||||
/// icon kept showing Peace while the character was genuinely in Magic and
|
||||
/// casting — reported from live play 2026-09-02.
|
||||
///
|
||||
/// playerRequested: 1 marks this as player-initiated, which is the path the
|
||||
/// toolbar button itself takes. The inbound server echo arrives as 0, and the
|
||||
/// UI-refresh branch is skipped there because a real click has already updated
|
||||
/// the widget optimistically — which is exactly why the echo alone never fixed
|
||||
/// the icon for us.
|
||||
///
|
||||
/// Calls the trampoline, so our own detour does not re-enter. _lastObservedCombatMode
|
||||
/// is deliberately NOT updated here: it must keep meaning "what the server
|
||||
/// decided", or a server that refuses the stance (the documented wand-stance
|
||||
/// wedge) would look like it had accepted it. The echo updates it.
|
||||
///
|
||||
/// Main thread only — the caller marshals. Returns false if the hook isn't
|
||||
/// installed or the singleton isn't readable, so the caller can fall back.
|
||||
/// </summary>
|
||||
public static unsafe bool RequestCombatMode(int combatMode)
|
||||
{
|
||||
if (!IsInstalled || _originalSetCombatMode == null)
|
||||
{ LogRequestPath(combatMode, -1, "FALLBACK: hook not installed"); return false; }
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
{ LogRequestPath(combatMode, -1, "FALLBACK: off main thread"); return false; }
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
|
||||
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
|
||||
{ LogRequestPath(combatMode, -1, "FALLBACK: s_pCombatSystem address unreadable"); return false; }
|
||||
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
|
||||
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
|
||||
{ LogRequestPath(combatMode, -1, "FALLBACK: combat system singleton unreadable"); return false; }
|
||||
|
||||
// Read the field SetCombatMode itself compares against ([esi+0x1C]).
|
||||
// Its prologue jumps past the whole body when the request equals the
|
||||
// current mode — so if these are equal, the call sends NO packet and
|
||||
// notifies nothing, and the stance silently will not change. That is
|
||||
// the leading suspect for the 8s stance stall seen on force rebuff
|
||||
// (2026-09-03 01:49), so record it explicitly rather than guess.
|
||||
int cur = *(int*)(combatSystem + CombatModeOffset);
|
||||
|
||||
// Same healing as ReadCurrentCombatMode: this is a live main-thread
|
||||
// read, so it is strictly better than a stale cached default.
|
||||
Volatile.Write(ref _lastObservedCombatMode, NormalizeCombatMode(cur));
|
||||
|
||||
// The client already believes it is in this mode, so SetCombatMode
|
||||
// would jump straight past its body: no 0x53 to the server and no UI
|
||||
// notice. But the SERVER can disagree with the client's field — that
|
||||
// is exactly the case worth sending — so decline here and let the
|
||||
// caller fall through to the raw opcode-0x53 sender, which is what
|
||||
// this code did unconditionally before the client-level path existed.
|
||||
// Confirmed live 2026-09-03 01:57: req=8 against clientField=8
|
||||
// swallowed every retry for ~8s until EnsureMagicMode's deadlock
|
||||
// recovery re-equipped the wand and forced a real transition.
|
||||
//
|
||||
// Nothing is lost on the UI side by taking the raw path here: the
|
||||
// widgets read the same field, and it already holds the requested
|
||||
// mode, so there is no stale icon to correct.
|
||||
if (cur == combatMode)
|
||||
{
|
||||
LogRequestPath(combatMode, cur, "declining — client field already equals request (SetCombatMode would no-op); using raw 0x53 sender so the server is still told");
|
||||
return false;
|
||||
}
|
||||
|
||||
_originalSetCombatMode(combatSystem, combatMode, 1);
|
||||
|
||||
LogRequestPath(combatMode, cur, "sent via ClientCombatSystem::SetCombatMode(playerRequested=1)");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"CombatModeHooks: RequestCombatMode({combatMode}) threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string _lastRequestLog = "";
|
||||
private static long _lastRequestLogTicks;
|
||||
|
||||
/// <summary>One line per combat-mode request telling us which path ran.
|
||||
/// Stance flips are rare, but a retry loop would repeat, so identical
|
||||
/// messages are throttled to 1/s.</summary>
|
||||
private static void LogRequestPath(int requested, int current, string outcome)
|
||||
{
|
||||
try
|
||||
{
|
||||
string msg = $"CombatModeHooks: RequestCombatMode(req={requested}, clientField={current}) — {outcome}";
|
||||
long now = Environment.TickCount64;
|
||||
if (msg == _lastRequestLog && (now - _lastRequestLogTicks) < 1000) return;
|
||||
_lastRequestLog = msg;
|
||||
_lastRequestLogTicks = now;
|
||||
RynthLog.Compat(msg);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
|
|
@ -60,51 +218,71 @@ internal static class CombatModeHooks
|
|||
return;
|
||||
}
|
||||
|
||||
int funcOff = SetCombatModeVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
|
||||
var resolved = HookResolver.Resolve(textSection, "CombatModeHooks.SetCombatMode",
|
||||
SetCombatModePattern, SetCombatModeFallbackVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
_statusMessage = $"ClientCombatSystem::SetCombatMode VA out of range @ 0x{SetCombatModeVa:X8}.";
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
|
||||
_statusMessage = $"Resolve failed ({resolved.Detail}).";
|
||||
return;
|
||||
}
|
||||
|
||||
byte firstByte = textSection.Bytes[funcOff];
|
||||
if (firstByte is 0x00 or 0xCC or 0xC3)
|
||||
{
|
||||
_statusMessage = $"ClientCombatSystem::SetCombatMode looks invalid @ 0x{SetCombatModeVa:X8} (opcode 0x{firstByte:X2}).";
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
_combatSystemPtrAddr = (uint)HookResolver.ResolveData(textSection, "CombatMode.s_pCombatSystem", PatXrefCombatSystemPtr, 2, (int)CombatSystemPtrVa).Address.ToInt32();
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_targetAddress = resolved.Address;
|
||||
_setCombatModeDetour = SetCombatModeDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setCombatModeDetour);
|
||||
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked ClientCombatSystem::SetCombatMode @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Verbose($"Compat: combat-mode hook ready - SetCombatMode=0x{_targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
|
||||
RynthLog.Compat($"CombatModeHooks: install ok.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: combat-mode hook failed - {ex.Message}");
|
||||
RynthLog.Compat($"CombatModeHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int _fires;
|
||||
private static int _lastLoggedMode = int.MinValue;
|
||||
private static long _lastLogTicks;
|
||||
|
||||
private static void SetCombatModeDetour(IntPtr thisPtr, int newCombatMode, int playerRequested)
|
||||
{
|
||||
// First detour to fire latches AC's main thread ID so background
|
||||
// threads (DecalCoexistence plugin-tick, panel snapshot, etc.) can
|
||||
// refuse to call into AC's non-thread-safe internals.
|
||||
MainThreadGuard.RecordIfFirst();
|
||||
|
||||
RecursionGuard.Tick("CombatModeHooks.SetCombatMode");
|
||||
// This detour fires on the INBOUND server echo (RecvNotice_SetCombatMode ->
|
||||
// ClientCombatSystem::SetCombatMode), so it reflects what the SERVER decided,
|
||||
// not what the plugin requested. The old `_fires <= 3` lifetime cap went dark
|
||||
// hours before any wedge, hiding the diagnosis. Log every distinct mode plus
|
||||
// repeats throttled to 1/s, so a wand-stance wedge (server re-echoing
|
||||
// NonCombat=1 against repeated Magic requests) is visible instead of silent.
|
||||
// See rynthai_combat_busy_wedge ADDENDUM 5.
|
||||
long nowTicks = Environment.TickCount64;
|
||||
if (++_fires <= 3 || newCombatMode != _lastLoggedMode || (nowTicks - _lastLogTicks) >= 1000)
|
||||
{
|
||||
_lastLoggedMode = newCombatMode;
|
||||
_lastLogTicks = nowTicks;
|
||||
RynthLog.Compat($"CombatModeHooks: SetCombatMode fired #{_fires} mode={newCombatMode} requested={playerRequested} (main TID = {MainThreadGuard.MainThreadId})");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_originalSetCombatMode!(thisPtr, newCombatMode, playerRequested);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: combat-mode detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
try { RynthLog.Compat($"CombatModeHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
throw;
|
||||
}
|
||||
|
||||
|
|
@ -127,16 +305,4 @@ internal static class CombatModeHooks
|
|||
_ => combatMode
|
||||
};
|
||||
}
|
||||
|
||||
private static string FormatCombatMode(int combatMode)
|
||||
{
|
||||
return combatMode switch
|
||||
{
|
||||
CombatActionHooks.CombatModeNonCombat => "noncombat(1)",
|
||||
CombatActionHooks.CombatModeMelee => "melee(2)",
|
||||
CombatActionHooks.CombatModeMissile => "missile(4)",
|
||||
CombatActionHooks.CombatModeMagic => "magic(8)",
|
||||
_ => combatMode.ToString()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,15 @@ internal static class CommandInterpreterHooks
|
|||
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
|
||||
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
|
||||
|
||||
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
|
||||
// Primary resolution; the *Offset deltas below remain as fallback only.
|
||||
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
|
||||
private static readonly byte?[] StopCompletelyPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x04, 0x85, 0xC0, 0x74, 0x32 ];
|
||||
private static readonly byte?[] TurnToHeadingPattern = [ 0x83, 0xEC, 0x2C, 0x56, 0x8B, 0xF1, 0x8B, 0x06 ];
|
||||
private static readonly byte?[] PlayerTeleportedPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x06, 0x6A, 0x01, 0x6A ];
|
||||
private static readonly byte?[] TakeControlFromServerPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x34, 0x85, 0xC0, 0x74 ];
|
||||
private static readonly byte?[] ClearAllCommandsPattern = [ 0x56, 0x8B, 0xF1, 0x8D, 0x4E, 0x0C, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x18, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x24, 0x5E ];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void CommenceJumpDelegate(IntPtr thisPtr);
|
||||
|
||||
|
|
@ -54,6 +63,8 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
private static IntPtr _smartboxStaticAddr;
|
||||
private static IntPtr _boundCmdInterp;
|
||||
private static bool _absResolved;
|
||||
private static IntPtr _setMotionAbs, _stopCompletelyAbs, _turnToHeadingAbs, _playerTeleportedAbs, _takeControlAbs, _clearAllCommandsAbs;
|
||||
private static CommenceJumpDelegate? _commenceJump;
|
||||
private static DoJumpDelegate? _doJump;
|
||||
private static SetAutoRunDelegate? _setAutoRun;
|
||||
|
|
@ -113,24 +124,51 @@ internal static class CommandInterpreterHooks
|
|||
}
|
||||
}
|
||||
|
||||
// Rate-limited diag counters — see why patrol "creates a route but stands
|
||||
// still" by surfacing the actual movement API calls in RynthCore.log.
|
||||
private static int _setAutoRunCalls;
|
||||
private static int _turnToHeadingCalls;
|
||||
private static int _setMotionCalls;
|
||||
private static bool ShouldLogMove(int n) => n <= 3 || (n & 0x7) == 0;
|
||||
|
||||
public static bool SetAutoRun(bool enabled)
|
||||
{
|
||||
// ⚠ Main thread only (2026-06-12 cross-incident forensics): these
|
||||
// CommandInterpreter calls were the last direct off-thread AC mutators
|
||||
// — dump-proven executing 15s after a main thread had wedged. They
|
||||
// rewrite the locomotion channels of the same CommandInterpreter /
|
||||
// motion graph the CSequence-AV corruption class kills. Off-thread
|
||||
// callers marshal through the action ring (drained post-tick,
|
||||
// gesture-gated) like every other mutator.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
|
||||
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
|
||||
if (!TryBindDelegates())
|
||||
{
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} — TryBindDelegates failed: {_statusMessage}");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8})");
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
|
||||
if (!TryBindDelegates() || _setMotion == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -147,6 +185,8 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool StopCompletely()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
|
||||
if (!TryBindDelegates() || _stopCompletely == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -163,22 +203,41 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool TurnToHeading(float headingDegrees)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
|
||||
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
|
||||
if (!TryBindDelegates() || _turnToHeading == null)
|
||||
{
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} — bind={(_turnToHeading != null)} status='{_statusMessage}'");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_turnToHeading(_boundCmdInterp, headingDegrees);
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} -> ok");
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ShouldLogMove(n))
|
||||
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery triplet: unguarded like the jump trio, but only latent today
|
||||
// (reached solely from the main-thread-gated ForceResetBusyCount) — public
|
||||
// API surface though, so gate defensively rather than add queue plumbing
|
||||
// for a currently-unreached off-thread path (revisit with an ActionKind if
|
||||
// one of these is ever exposed to off-thread callers).
|
||||
|
||||
public static bool PlayerTeleported()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
if (!TryBindDelegates() || _playerTeleported == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -195,6 +254,8 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool TakeControlFromServer()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
if (!TryBindDelegates() || _takeControlFromServer == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -211,6 +272,8 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool ClearAllCommands()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
if (!TryBindDelegates() || _clearAllCommands == null)
|
||||
return false;
|
||||
|
||||
|
|
@ -225,8 +288,16 @@ internal static class CommandInterpreterHooks
|
|||
}
|
||||
}
|
||||
|
||||
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): these called the
|
||||
// native CommandInterpreter through _boundCmdInterp with zero
|
||||
// MainThreadGuard gate, unlike every sibling (SetAutoRun/SetMotion/
|
||||
// StopCompletely/TurnToHeading above), live-exercised off-thread via
|
||||
// Jumper.cs's Decal-coexistence pump-thread tick.
|
||||
|
||||
public static bool TapJump()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueTapJump();
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
||||
|
|
@ -244,6 +315,65 @@ internal static class CommandInterpreterHooks
|
|||
}
|
||||
}
|
||||
|
||||
public static bool CommenceJump()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueCommenceJump();
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_commenceJump!(_boundCmdInterp);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool DoJump(bool autonomous)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
_doJump!(_boundCmdInterp, autonomous ? 1 : 0);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the six non-vtable-slot member functions by unique .text signature (primary),
|
||||
// once and cached — they are static code addresses. On a miss they stay Zero and
|
||||
// TryBindDelegates falls back to the live-anchor + hardcoded-delta computation (old behavior).
|
||||
private static void EnsureAbsoluteResolved()
|
||||
{
|
||||
if (_absResolved) return;
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return; // retry next call
|
||||
HookResolver.ResolveResult r;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.SetMotion", SetMotionPattern, ReferenceAccCmdInterpSetMotion);
|
||||
_setMotionAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.StopCompletely", StopCompletelyPattern, ReferenceCommandInterpreterStopCompletely);
|
||||
_stopCompletelyAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.TurnToHeading", TurnToHeadingPattern, ReferenceCommandInterpreterTurnToHeading);
|
||||
_turnToHeadingAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.PlayerTeleported", PlayerTeleportedPattern, ReferenceCommandInterpreterPlayerTeleported);
|
||||
_playerTeleportedAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.TakeControlFromServer", TakeControlFromServerPattern, ReferenceCommandInterpreterTakeControlFromServer);
|
||||
_takeControlAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
r = HookResolver.Resolve(text, "CmdInterp.ClearAllCommands", ClearAllCommandsPattern, ReferenceCommandInterpreterClearAllCommands);
|
||||
_clearAllCommandsAbs = r.Success ? r.Address : IntPtr.Zero;
|
||||
_absResolved = true;
|
||||
}
|
||||
|
||||
private static bool TryBindDelegates()
|
||||
{
|
||||
IntPtr selectedStaticAddr = IntPtr.Zero;
|
||||
|
|
@ -299,12 +429,13 @@ internal static class CommandInterpreterHooks
|
|||
IntPtr commenceJumpPtr = Marshal.ReadIntPtr(vtable, VtblCommenceJumpIndex * IntPtr.Size);
|
||||
IntPtr doJumpPtr = Marshal.ReadIntPtr(vtable, VtblDoJumpIndex * IntPtr.Size);
|
||||
IntPtr setAutoRunPtr = Marshal.ReadIntPtr(vtable, VtblSetAutoRunIndex * IntPtr.Size);
|
||||
IntPtr setMotionPtr = ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
|
||||
IntPtr stopCompletelyPtr = AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
|
||||
IntPtr turnToHeadingPtr = AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
|
||||
IntPtr playerTeleportedPtr = AddOffset(setAutoRunPtr, PlayerTeleportedOffsetFromSetAutoRun);
|
||||
IntPtr takeControlPtr = AddOffset(setAutoRunPtr, TakeControlOffsetFromSetAutoRun);
|
||||
IntPtr clearAllCommandsPtr = AddOffset(setAutoRunPtr, ClearAllCommandsOffsetFromSetAutoRun);
|
||||
EnsureAbsoluteResolved();
|
||||
IntPtr setMotionPtr = _setMotionAbs != IntPtr.Zero ? _setMotionAbs : ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
|
||||
IntPtr stopCompletelyPtr = _stopCompletelyAbs != IntPtr.Zero ? _stopCompletelyAbs : AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
|
||||
IntPtr turnToHeadingPtr = _turnToHeadingAbs != IntPtr.Zero ? _turnToHeadingAbs : AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
|
||||
IntPtr playerTeleportedPtr = _playerTeleportedAbs != IntPtr.Zero ? _playerTeleportedAbs : AddOffset(setAutoRunPtr, PlayerTeleportedOffsetFromSetAutoRun);
|
||||
IntPtr takeControlPtr = _takeControlAbs != IntPtr.Zero ? _takeControlAbs : AddOffset(setAutoRunPtr, TakeControlOffsetFromSetAutoRun);
|
||||
IntPtr clearAllCommandsPtr = _clearAllCommandsAbs != IntPtr.Zero ? _clearAllCommandsAbs : AddOffset(setAutoRunPtr, ClearAllCommandsOffsetFromSetAutoRun);
|
||||
|
||||
if (!SmartBoxLocator.IsPointerInModule(commenceJumpPtr) ||
|
||||
!SmartBoxLocator.IsPointerInModule(doJumpPtr) ||
|
||||
|
|
@ -354,6 +485,8 @@ internal static class CommandInterpreterHooks
|
|||
{
|
||||
_smartboxStaticAddr = IntPtr.Zero;
|
||||
_boundCmdInterp = IntPtr.Zero;
|
||||
_absResolved = false;
|
||||
_setMotionAbs = _stopCompletelyAbs = _turnToHeadingAbs = _playerTeleportedAbs = _takeControlAbs = _clearAllCommandsAbs = IntPtr.Zero;
|
||||
_commenceJump = null;
|
||||
_doJump = null;
|
||||
_setAutoRun = null;
|
||||
|
|
|
|||
|
|
@ -9,12 +9,10 @@ namespace RynthCore.Engine.Compatibility;
|
|||
internal static class CreateObjectHooks
|
||||
{
|
||||
private const int CreateObjectVa = 0x005594B0;
|
||||
private static readonly byte[] CreateObjectSignature =
|
||||
// Verified unique + lands at 0x005594B0 offline (tools/pe_pattern.py).
|
||||
private static readonly byte?[] CreateObjectPattern =
|
||||
[
|
||||
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1,
|
||||
0x8B, 0x8E, 0x8C, 0x00, 0x00, 0x00, 0x8B, 0x96,
|
||||
0x88, 0x00, 0x00, 0x00, 0x8B, 0xC5, 0xD3, 0xE8,
|
||||
0x8B, 0x8E, 0x90, 0x00, 0x00, 0x00, 0x33, 0xC5
|
||||
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1, 0x8B, 0x8E
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
|
|
@ -28,6 +26,7 @@ internal static class CreateObjectHooks
|
|||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
public static int DispatchCount => _dispatchCount;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
|
|
@ -40,17 +39,17 @@ internal static class CreateObjectHooks
|
|||
return;
|
||||
}
|
||||
|
||||
int funcOff = CreateObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, CreateObjectSignature))
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CreateObject.CreateObject", CreateObjectPattern, CreateObjectVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::CreateObject signature mismatch @ 0x{CreateObjectVa:X8}.";
|
||||
_statusMessage = $"ACCObjectMaint::CreateObject unresolved (VA 0x{CreateObjectVa:X8}).";
|
||||
RynthLog.Compat($"Compat: create-object hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_targetAddress = resolved.Address;
|
||||
_createObjectDetour = CreateObjectDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createObjectDetour);
|
||||
_originalCreateObject = Marshal.GetDelegateForFunctionPointer<CreateObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
|
|
@ -70,6 +69,7 @@ internal static class CreateObjectHooks
|
|||
|
||||
private static IntPtr CreateObjectDetour(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc)
|
||||
{
|
||||
RecursionGuard.Tick("CreateObjectHooks.CreateObject");
|
||||
if (objectId != 0 && visualDesc != IntPtr.Zero)
|
||||
PaletteCache.ReadFromObjDesc(objectId, visualDesc);
|
||||
|
||||
|
|
|
|||
495
src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs
Normal file
495
src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// IAT-hooks acclient.exe's <c>kernel32!CreateFileW</c> and <c>CreateFileA</c>
|
||||
/// imports to force maximally-permissive share semantics on AC's data files.
|
||||
///
|
||||
/// Why this exists:
|
||||
/// <see cref="MultiClientHooks"/> patches AC's <c>OpenDataFile</c> high-level
|
||||
/// <c>openFlags</c> bit 0x2, which selects AC's "shared" branch — but that
|
||||
/// branch still translates to a CreateFile call whose <c>dwShareMode</c> may
|
||||
/// not be wide enough to coexist with handles already held by Decal-injected
|
||||
/// clients launched by other launchers (Thwargle etc.). Windows file-sharing
|
||||
/// compatibility is decided by the kernel at CreateFile time, not by AC's
|
||||
/// internal flag.
|
||||
///
|
||||
/// This hook intercepts CreateFile right before the kernel sees it, and for
|
||||
/// the known DAT paths rewrites:
|
||||
/// dwDesiredAccess = GENERIC_READ (drop WRITE — DATs are read-only after patch)
|
||||
/// dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
|
||||
/// Other paths pass through untouched.
|
||||
///
|
||||
/// Why IAT-hook instead of MinHook on the kernel32 export:
|
||||
/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile
|
||||
/// (that's how Decal-injected Thwargle clients can multibox without a
|
||||
/// second AC install). IAT-hooking acclient.exe's import slot intercepts only
|
||||
/// acclient.exe's own calls; our detour's call into the saved IAT pointer
|
||||
/// still routes through any Decal MinHook trampoline on the kernel32 export.
|
||||
/// No collision; both hooks fire in order.
|
||||
/// </summary>
|
||||
internal static class DatFileShareHooks
|
||||
{
|
||||
// We force-share by file *extension* (.dat) rather than an explicit name
|
||||
// list. Stock retail AC ships portal.dat / cell.dat / client_*.dat, but
|
||||
// private servers commonly add split client-cell DATs (client_cell_1.dat,
|
||||
// client_cell_2.dat, ...) and other variants we can't enumerate up front.
|
||||
// Filtering on extension catches them all without per-server tuning.
|
||||
// AC only opens .dat files via CreateFile for game data; non-DAT writes
|
||||
// (logs, prefs, screenshots) pass through unmodified.
|
||||
private const string DatExtension = ".dat";
|
||||
|
||||
private const uint GENERIC_READ = 0x80000000;
|
||||
private const uint FILE_SHARE_READ = 0x00000001;
|
||||
private const uint FILE_SHARE_WRITE = 0x00000002;
|
||||
private const uint FILE_SHARE_DELETE = 0x00000004;
|
||||
private const uint FILE_SHARE_ALL = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
|
||||
|
||||
private const uint PAGE_READWRITE = 0x04;
|
||||
private const uint PAGE_EXECUTE_READWRITE = 0x40;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private delegate IntPtr CreateFileWDelegate(
|
||||
IntPtr lpFileName,
|
||||
uint dwDesiredAccess,
|
||||
uint dwShareMode,
|
||||
IntPtr lpSecurityAttributes,
|
||||
uint dwCreationDisposition,
|
||||
uint dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private delegate IntPtr CreateFileADelegate(
|
||||
IntPtr lpFileName,
|
||||
uint dwDesiredAccess,
|
||||
uint dwShareMode,
|
||||
IntPtr lpSecurityAttributes,
|
||||
uint dwCreationDisposition,
|
||||
uint dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
|
||||
|
||||
// Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a
|
||||
// weak handle, so the delegate must be reachable for the process lifetime.
|
||||
private static CreateFileWDelegate? _wDetour;
|
||||
private static CreateFileADelegate? _aDetour;
|
||||
|
||||
// The IAT slot pointer (the address inside the IAT array, NOT the original
|
||||
// function address) — needed for the unhook path.
|
||||
private static IntPtr _wIatSlot;
|
||||
private static IntPtr _aIatSlot;
|
||||
|
||||
// What was in the IAT slot when we patched it. Could be the real
|
||||
// kernel32!CreateFile, or another hooker's detour if they got there first.
|
||||
private static IntPtr _wOriginalPtr;
|
||||
private static IntPtr _aOriginalPtr;
|
||||
|
||||
private static CreateFileWDelegate? _wOriginal;
|
||||
private static CreateFileADelegate? _aOriginal;
|
||||
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsEnabled { get; private set; }
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
// Diagnostic kill-switch. Set "EnableDatShareHook": false in
|
||||
// %APPDATA%\RynthCore\engine.json to skip detouring CreateFileA/W
|
||||
// entirely. Used to isolate this hook as a crash suspect.
|
||||
if (!Plugins.EngineSettings.EnableDatShareHook)
|
||||
{
|
||||
_statusMessage = "DAT share hook disabled via engine.json (EnableDatShareHook=false).";
|
||||
RynthLog.Info($"Compat: {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Gate behind AllowMultipleClients. If the user has multi-client off,
|
||||
// they're not multiboxing, so we have no reason to widen DAT sharing.
|
||||
if (!LauncherSettings.AllowMultipleClientsEnabled)
|
||||
{
|
||||
_statusMessage = "Multi-client disabled — DAT share hook skipped.";
|
||||
RynthLog.Verbose($"Compat: {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
IsEnabled = true;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr moduleBase = AcClientGetModuleBase();
|
||||
if (moduleBase == IntPtr.Zero)
|
||||
{
|
||||
_statusMessage = "acclient.exe module base not found.";
|
||||
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Hook the kernel32 exports directly with MinHook so we catch ALL
|
||||
// callers in the process — acclient.exe itself, the CRT layer
|
||||
// (msvcrt.dll, which is how AC's fopen-style DAT loads route), and
|
||||
// any plugin or runtime DLL. IAT-hooking acclient.exe alone misses
|
||||
// CRT-mediated calls because they go through msvcrt's own IAT slot.
|
||||
IntPtr hKernel32 = GetModuleHandleW("kernel32.dll");
|
||||
if (hKernel32 == IntPtr.Zero)
|
||||
{
|
||||
_statusMessage = "kernel32.dll module handle not found.";
|
||||
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Two-phase install. Phase 1: create both hooks (inactive),
|
||||
// assign typed trampolines into _aOriginal/_wOriginal. Phase 2:
|
||||
// memory barrier then Enable. Critical ordering: the detour can
|
||||
// fire from ANY caller in the process the moment Enable returns,
|
||||
// and the detour calls _aOriginal/_wOriginal — those fields MUST
|
||||
// be set first or the first invocation null-derefs and kills the
|
||||
// engine init thread.
|
||||
IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA");
|
||||
IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW");
|
||||
|
||||
int patched = 0;
|
||||
if (aTarget != IntPtr.Zero)
|
||||
{
|
||||
_aDetour = CreateFileADetour;
|
||||
IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour);
|
||||
_aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr);
|
||||
_aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr);
|
||||
patched++;
|
||||
}
|
||||
|
||||
if (wTarget != IntPtr.Zero)
|
||||
{
|
||||
_wDetour = CreateFileWDetour;
|
||||
IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour);
|
||||
_wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr);
|
||||
_wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr);
|
||||
patched++;
|
||||
}
|
||||
|
||||
// Publish trampolines to other cores before enabling.
|
||||
Thread.MemoryBarrier();
|
||||
|
||||
if (aTarget != IntPtr.Zero)
|
||||
{
|
||||
MinHook.Enable(aTarget);
|
||||
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found.");
|
||||
}
|
||||
|
||||
if (wTarget != IntPtr.Zero)
|
||||
{
|
||||
MinHook.Enable(wTarget);
|
||||
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found.");
|
||||
}
|
||||
|
||||
if (patched == 0)
|
||||
{
|
||||
_statusMessage = "MinHook on kernel32 CreateFile exports failed.";
|
||||
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
IsInstalled = true;
|
||||
_statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured).";
|
||||
RynthLog.Info($"Compat: {_statusMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = $"DAT share hook exception: {ex.Message}";
|
||||
RynthLog.Compat($"Compat: DAT share hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
/// <summary>
|
||||
/// Diagnostic — log every kernel32 import name we find that looks file- or
|
||||
/// memory-mapping-related. Useful when the standard CreateFileW/A hook
|
||||
/// doesn't catch DAT opens, because it tells us what API AC actually uses.
|
||||
/// </summary>
|
||||
private static unsafe void EnumerateKernel32FileImports(IntPtr moduleBase)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte* basePtr = (byte*)moduleBase;
|
||||
int peOffset = *(int*)(basePtr + 0x3C);
|
||||
byte* optHeader = basePtr + peOffset + 24;
|
||||
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1);
|
||||
if (importDirRva == 0)
|
||||
return;
|
||||
|
||||
byte* descriptor = basePtr + importDirRva;
|
||||
for (; ; descriptor += 20)
|
||||
{
|
||||
uint nameRva = *(uint*)(descriptor + 12);
|
||||
uint firstThunk = *(uint*)(descriptor + 16);
|
||||
if (nameRva == 0 && firstThunk == 0) break;
|
||||
|
||||
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
|
||||
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
|
||||
uint origFirstThunk = *(uint*)(descriptor + 0);
|
||||
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
|
||||
uint* names = (uint*)(basePtr + nameTableRva);
|
||||
int i = 0;
|
||||
var hits = new System.Text.StringBuilder("Compat: DAT share - kernel32 file/mmap imports in acclient.exe IAT:");
|
||||
int hitCount = 0;
|
||||
while (names[i] != 0)
|
||||
{
|
||||
uint thunk = names[i];
|
||||
if ((thunk & 0x80000000u) == 0)
|
||||
{
|
||||
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
|
||||
if (candidate != null &&
|
||||
(candidate.Contains("File", StringComparison.Ordinal) ||
|
||||
candidate.Contains("Mapping", StringComparison.Ordinal) ||
|
||||
candidate.Contains("MapView", StringComparison.Ordinal) ||
|
||||
candidate.StartsWith("_l", StringComparison.Ordinal) ||
|
||||
candidate.StartsWith("_open", StringComparison.Ordinal)))
|
||||
{
|
||||
hits.Append(' ').Append(candidate);
|
||||
hitCount++;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
RynthLog.Info(hitCount > 0 ? hits.ToString() : "Compat: DAT share - no file-related kernel32 imports found in acclient.exe IAT.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.Info("Compat: DAT share - kernel32.dll import descriptor not found in acclient.exe.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: DAT share - import enumeration failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr AcClientGetModuleBase()
|
||||
{
|
||||
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
|
||||
if (moduleBase == IntPtr.Zero)
|
||||
moduleBase = GetModuleHandleW(null);
|
||||
return moduleBase;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walks the import directory of <paramref name="moduleBase"/> looking for
|
||||
/// kernel32.dll's import descriptor, then locates the named import
|
||||
/// <paramref name="importName"/>'s IAT slot. Returns the slot's absolute
|
||||
/// address (not the function pointer it contains) plus the current
|
||||
/// pointer value.
|
||||
/// </summary>
|
||||
private static unsafe bool TryPatchIatSlot(IntPtr moduleBase, string importName, out IntPtr iatSlot, out IntPtr currentPtr)
|
||||
{
|
||||
iatSlot = IntPtr.Zero;
|
||||
currentPtr = IntPtr.Zero;
|
||||
|
||||
byte* basePtr = (byte*)moduleBase;
|
||||
int peOffset = *(int*)(basePtr + 0x3C);
|
||||
if (peOffset <= 0 || *(uint*)(basePtr + peOffset) != 0x00004550) // "PE\0\0"
|
||||
return false;
|
||||
|
||||
// OPTIONAL_HEADER starts at peOffset + 24 (4-byte sig + 20-byte FILE_HEADER).
|
||||
// PE32 magic is 0x010B; DataDirectory starts at OptionalHeader+96.
|
||||
byte* optHeader = basePtr + peOffset + 24;
|
||||
if (*(ushort*)optHeader != 0x010B)
|
||||
return false;
|
||||
|
||||
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1); // DataDirectory[1] = IMPORT
|
||||
if (importDirRva == 0)
|
||||
return false;
|
||||
|
||||
byte* descriptor = basePtr + importDirRva;
|
||||
// Each IMAGE_IMPORT_DESCRIPTOR is 20 bytes; terminated by all zeros.
|
||||
for (; ; descriptor += 20)
|
||||
{
|
||||
uint nameRva = *(uint*)(descriptor + 12);
|
||||
uint firstThunk = *(uint*)(descriptor + 16);
|
||||
if (nameRva == 0 && firstThunk == 0)
|
||||
break; // End of descriptor list.
|
||||
|
||||
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
|
||||
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(dllName, "KERNEL32.dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
uint origFirstThunk = *(uint*)(descriptor + 0);
|
||||
// INT (Import Name Table) — prefer OriginalFirstThunk if present;
|
||||
// some bound imports may have it zeroed, in which case the IAT
|
||||
// itself is still a valid name table pre-binding. Both arrays are
|
||||
// parallel, 4-byte entries on PE32.
|
||||
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
|
||||
uint* names = (uint*)(basePtr + nameTableRva);
|
||||
int i = 0;
|
||||
while (names[i] != 0)
|
||||
{
|
||||
uint thunk = names[i];
|
||||
// High bit set = import by ordinal — no name to match.
|
||||
if ((thunk & 0x80000000u) == 0)
|
||||
{
|
||||
// IMAGE_IMPORT_BY_NAME = { WORD Hint; CHAR Name[]; }
|
||||
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
|
||||
if (string.Equals(candidate, importName, StringComparison.Ordinal))
|
||||
{
|
||||
iatSlot = (IntPtr)(basePtr + firstThunk + 4 * i);
|
||||
currentPtr = Marshal.ReadIntPtr(iatSlot);
|
||||
return currentPtr != IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool WriteIatPointer(IntPtr iatSlot, IntPtr newValue)
|
||||
{
|
||||
// IAT lives in .rdata which is read-only after the loader binds it.
|
||||
// Flip protection, write, restore. Use the original-protection value
|
||||
// from VirtualProtect so we put the page back exactly the way we
|
||||
// found it (some loaders mark IAT pages as PAGE_READWRITE post-binding,
|
||||
// some PAGE_READONLY).
|
||||
if (!VirtualProtect(iatSlot, sizeof(int), PAGE_READWRITE, out uint oldProtect))
|
||||
{
|
||||
RynthLog.Compat($"Compat: DAT share - VirtualProtect(RW) on IAT slot 0x{iatSlot.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Marshal.WriteIntPtr(iatSlot, newValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
VirtualProtect(iatSlot, sizeof(int), oldProtect, out _);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsDatPath(string? path)
|
||||
{
|
||||
return !string.IsNullOrEmpty(path)
|
||||
&& path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern uint GetLastError();
|
||||
|
||||
private static IntPtr CreateFileWDetour(
|
||||
IntPtr lpFileName,
|
||||
uint dwDesiredAccess,
|
||||
uint dwShareMode,
|
||||
IntPtr lpSecurityAttributes,
|
||||
uint dwCreationDisposition,
|
||||
uint dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile)
|
||||
{
|
||||
string? path = null;
|
||||
bool isDat = false;
|
||||
bool isAnyDatExt = false;
|
||||
uint origAccess = dwDesiredAccess;
|
||||
uint origShare = dwShareMode;
|
||||
|
||||
try
|
||||
{
|
||||
path = Marshal.PtrToStringUni(lpFileName);
|
||||
isDat = IsDatPath(path);
|
||||
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
|
||||
if (isDat)
|
||||
{
|
||||
dwDesiredAccess = GENERIC_READ;
|
||||
dwShareMode = FILE_SHARE_ALL;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
|
||||
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
|
||||
|
||||
if (isAnyDatExt)
|
||||
{
|
||||
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
|
||||
string fname = Path.GetFileName(path!);
|
||||
string note = isDat ? "filtered" : "passthrough";
|
||||
RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static IntPtr CreateFileADetour(
|
||||
IntPtr lpFileName,
|
||||
uint dwDesiredAccess,
|
||||
uint dwShareMode,
|
||||
IntPtr lpSecurityAttributes,
|
||||
uint dwCreationDisposition,
|
||||
uint dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile)
|
||||
{
|
||||
string? path = null;
|
||||
bool isDat = false;
|
||||
bool isAnyDatExt = false;
|
||||
uint origAccess = dwDesiredAccess;
|
||||
uint origShare = dwShareMode;
|
||||
|
||||
try
|
||||
{
|
||||
path = Marshal.PtrToStringAnsi(lpFileName);
|
||||
isDat = IsDatPath(path);
|
||||
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
|
||||
if (isDat)
|
||||
{
|
||||
dwDesiredAccess = GENERIC_READ;
|
||||
dwShareMode = FILE_SHARE_ALL;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
|
||||
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
|
||||
|
||||
if (isAnyDatExt)
|
||||
{
|
||||
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
|
||||
string fname = Path.GetFileName(path!);
|
||||
string note = isDat ? "filtered" : "passthrough";
|
||||
RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
131
src/RynthCore.Engine/Compatibility/DbCacheTeardownHooks.cs
Normal file
131
src/RynthCore.Engine/Compatibility/DbCacheTeardownHooks.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks AC's DAT object-cache teardown <c>DBCache::DestroyObjectCaches</c>
|
||||
/// (acclient.map 0x00014040 + 0x401000 = 0x00415040; ImageBase 0x00400000, ASLR off)
|
||||
/// to QUIESCE off-thread enchantment-registry reads WHILE AC frees its DB objects.
|
||||
///
|
||||
/// Crash this addresses: the recurring <c>0x00416C86</c> (DBOCache::DestroyObj + 0x06,
|
||||
/// read [null+0x28]) AV. Root cause (MainThreadGuard.cs 2026-05-14 note): the
|
||||
/// off-thread plugin pump walks AC's CACQualities -> CEnchantmentRegistry linked lists
|
||||
/// (EnchantmentHooks.ReadEnchantmentsFromQualities / WalkEnchantList) while AC frees
|
||||
/// those nodes during a cache teardown; the pump reads a half-freed node and AC AVs in
|
||||
/// DestroyObj. Decal never hits this because it drives AC only on AC's own thread.
|
||||
///
|
||||
/// ⚠ CRITICAL (verified 2026-06-02 from the live log): DestroyObjectCaches is NOT
|
||||
/// close-only — AC calls it during world-load / zone-entry too (it fired ~5s after
|
||||
/// login). So this is a SCOPED guard: raise a depth latch on entry, lower it when the
|
||||
/// call returns. It must NOT stop the plugin pump or shut down the engine — an earlier
|
||||
/// destructive version (RequestTickPumpStop + EngineLifecycle.Shutdown in this detour)
|
||||
/// tore the engine down ~5-30s after EVERY login ("most things don't work"). The
|
||||
/// engine's real teardown stays on the ExitProcess / WM_CLOSE path. While the latch is
|
||||
/// set, EnchantmentHooks bails its registry walk, so the off-thread read never races
|
||||
/// AC's free — at world-load, zone change, logout, AND final close alike.
|
||||
///
|
||||
/// Ported (and corrected for v1's in-process threading) from RynthCore2's
|
||||
/// DestroyObjectCaches guard (RynthSuite2 f8a291e).
|
||||
/// </summary>
|
||||
internal static class DbCacheTeardownHooks
|
||||
{
|
||||
// DBCache::DestroyObjectCaches. Fallback VA; pattern-scan is the source of truth.
|
||||
private const int DestroyObjectCachesFallbackVa = 0x00415040;
|
||||
|
||||
// 8B 01 / 83 EC 0C / 53 56 57 / 6A 01 / FF 50 38 / 8D 4C 24 .. — unique in .text,
|
||||
// lands exactly at 0x00415040 (byte-verified against this client).
|
||||
private static readonly byte?[] DestroyObjectCachesPattern =
|
||||
[
|
||||
0x8B, 0x01, 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57,
|
||||
0x6A, 0x01, 0xFF, 0x50, 0x38, 0x8D, 0x4C, 0x24,
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
|
||||
|
||||
private static ThisCallVoidDelegate? _originalDestroyObjectCaches;
|
||||
private static ThisCallVoidDelegate? _destroyObjectCachesDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
|
||||
private static int _teardownDepth;
|
||||
private static int _installed;
|
||||
private static int _enterLogCount;
|
||||
|
||||
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// True only WHILE AC is inside DBCache::DestroyObjectCaches (freeing/rebuilding its
|
||||
/// DB object caches — world-load, zone change, logout, or final close). Off-thread
|
||||
/// AC object/registry walkers (the plugin-pump enchantment reader) must bail while
|
||||
/// this is set so they never deref a node AC is concurrently freeing. SCOPED —
|
||||
/// cleared when the call returns; NOT a one-way latch.
|
||||
/// </summary>
|
||||
public static bool TeardownActive => Volatile.Read(ref _teardownDepth) > 0;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
RynthLog.Compat("DbCacheTeardownHooks: acclient.exe not available.");
|
||||
return;
|
||||
}
|
||||
|
||||
var resolved = HookResolver.Resolve(
|
||||
textSection, "DbCacheTeardown.DestroyObjectCaches",
|
||||
DestroyObjectCachesPattern, DestroyObjectCachesFallbackVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = resolved.Address;
|
||||
_destroyObjectCachesDetour = DestroyObjectCachesDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_destroyObjectCachesDetour);
|
||||
_originalDestroyObjectCaches = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
RynthLog.Compat($"DbCacheTeardownHooks: ready (DestroyObjectCaches=0x{_targetAddress.ToInt32():X8}).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
RynthLog.Compat($"DbCacheTeardownHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DestroyObjectCachesDetour(IntPtr thisPtr)
|
||||
{
|
||||
// SCOPED read-quiesce. Raise the latch BEFORE AC frees anything; lower it when
|
||||
// AC's teardown loop returns. While raised, EnchantmentHooks (the off-thread
|
||||
// registry walker) bails, so the pump can't read a node AC is concurrently
|
||||
// freeing -> kills the 0x00416C86 (DBOCache::DestroyObj) AV. NO pump-stop / NO
|
||||
// engine shutdown here: DestroyObjectCaches ALSO fires at world-load/zone, and
|
||||
// destructive work tore the engine down mid-play (2026-06-02).
|
||||
Interlocked.Increment(ref _teardownDepth);
|
||||
try
|
||||
{
|
||||
if (Interlocked.Increment(ref _enterLogCount) <= 3)
|
||||
RynthLog.Compat("DbCacheTeardownHooks: DestroyObjectCaches entry — off-thread registry reads quiesced for this teardown.");
|
||||
_originalDestroyObjectCaches!(thisPtr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"DbCacheTeardownHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref _teardownDepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
71
src/RynthCore.Engine/Compatibility/DecalDetection.cs
Normal file
71
src/RynthCore.Engine/Compatibility/DecalDetection.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Detects whether a Decal-style coexistence stack is loaded inside this
|
||||
/// acclient.exe process. When true, the engine skips its D3D9 hooks and
|
||||
/// in-game overlays so Decal's own EndScene rendering isn't disrupted —
|
||||
/// only Avalonia floating panels (LayeredWindow / GDI) remain available.
|
||||
///
|
||||
/// Result is cached on first call: a Decal stack appearing later in the
|
||||
/// session would still take effect on a hot-reload, but during a single
|
||||
/// run the snapshot at engine init is what gates the D3D9 path.
|
||||
/// </summary>
|
||||
internal static class DecalDetection
|
||||
{
|
||||
private static readonly string[] DecalModuleNames =
|
||||
{
|
||||
"decal.dll",
|
||||
"UBLoader.dll",
|
||||
"Decal.Adapter.dll",
|
||||
"phatacd.dll",
|
||||
};
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static bool _evaluated;
|
||||
private static string? _detectedModule;
|
||||
|
||||
public static bool IsDecalLoaded => DetectedModule != null;
|
||||
|
||||
public static string? DetectedModule
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (_evaluated)
|
||||
return _detectedModule;
|
||||
|
||||
_evaluated = true;
|
||||
_detectedModule = ProbeOnce();
|
||||
return _detectedModule;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ProbeOnce()
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process self = Process.GetCurrentProcess();
|
||||
foreach (ProcessModule module in self.Modules)
|
||||
{
|
||||
string name = module.ModuleName;
|
||||
for (int i = 0; i < DecalModuleNames.Length; i++)
|
||||
{
|
||||
if (string.Equals(name, DecalModuleNames[i], StringComparison.OrdinalIgnoreCase))
|
||||
return DecalModuleNames[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Failed to enumerate modules — treat as no Decal so we don't
|
||||
// disable our own rendering on a transient probe error.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -9,12 +9,10 @@ namespace RynthCore.Engine.Compatibility;
|
|||
internal static class DeleteObjectHooks
|
||||
{
|
||||
private const int DeleteObjectVa = 0x00558330;
|
||||
private static readonly byte[] DeleteObjectSignature =
|
||||
// Verified unique + lands at 0x00558330 offline (tools/pe_pattern.py).
|
||||
private static readonly byte?[] DeleteObjectPattern =
|
||||
[
|
||||
0x56, 0x57, 0x8B, 0xF9, 0xE8, 0x67, 0x2D, 0x00,
|
||||
0x00, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C, 0x74,
|
||||
0x0C, 0xE8, 0xFA, 0x23, 0x00, 0x00, 0x8B, 0x08,
|
||||
0x56, 0x50, 0xFF, 0x51, 0x24, 0x56, 0xE8
|
||||
0x56, 0x57, 0x8B, 0xF9, 0xE8, null, null, null, null, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
|
|
@ -39,17 +37,17 @@ internal static class DeleteObjectHooks
|
|||
return;
|
||||
}
|
||||
|
||||
int funcOff = DeleteObjectVa - textSection.TextBaseVa;
|
||||
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DeleteObjectSignature))
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "DeleteObject.DeleteObject", DeleteObjectPattern, DeleteObjectVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
_statusMessage = $"ACCObjectMaint::DeleteObject signature mismatch @ 0x{DeleteObjectVa:X8}.";
|
||||
_statusMessage = $"ACCObjectMaint::DeleteObject unresolved (VA 0x{DeleteObjectVa:X8}).";
|
||||
RynthLog.Compat($"Compat: delete-object hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_targetAddress = resolved.Address;
|
||||
_deleteObjectDetour = DeleteObjectDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_deleteObjectDetour);
|
||||
_originalDeleteObject = Marshal.GetDelegateForFunctionPointer<DeleteObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
|
|
@ -69,6 +67,7 @@ internal static class DeleteObjectHooks
|
|||
|
||||
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
|
||||
{
|
||||
RecursionGuard.Tick("DeleteObjectHooks.DeleteObject");
|
||||
if (objectId != 0)
|
||||
{
|
||||
PaletteCache.Remove(objectId);
|
||||
|
|
|
|||
|
|
@ -5,9 +5,6 @@
|
|||
// Used by wobjectgetisdooropen[] to detect runtime door open/close state,
|
||||
// since STypeBool.OPEN in CBaseQualities reflects the default/creation state
|
||||
// and is NOT updated when a door is animated open or closed at runtime.
|
||||
//
|
||||
// VA derivation (map_offset + 0x00401000 = live VA):
|
||||
// 0010FAF0 CPhysicsObj::DoMotion → 0x00510AF0
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -20,31 +17,34 @@ namespace RynthCore.Engine.Compatibility;
|
|||
|
||||
internal static class DoMotionHooks
|
||||
{
|
||||
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent) — thiscall
|
||||
// Map: 0010FAF0 → live VA: 0x00510AF0
|
||||
private const int DoMotionVa = 0x00510AF0;
|
||||
private const int DoMotionFallbackVa = 0x00510AF0;
|
||||
|
||||
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent)
|
||||
// Distinctive 0x83 0xEC 0x64 (sub esp, 0x64) and the +0xC4 / +0xCC field
|
||||
// accesses; the 'mov dword ptr [esi+0xCC],1' is unique to this function's prologue.
|
||||
private static readonly byte?[] DoMotionPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x64, 0x56, 0x8B, 0xF1, 0x8B, 0x8E,
|
||||
0xC4, 0x00, 0x00, 0x00, 0x33, 0xC0, 0x3B, 0xC8,
|
||||
0xC7, 0x86, 0xCC, 0x00, 0x00, 0x00, 0x01, 0x00,
|
||||
0x00, 0x00, 0x75, 0x0C
|
||||
];
|
||||
|
||||
// Door motion commands (AC1Legacy Command enum)
|
||||
private const uint MotionOn = 0x4000000B; // door opens
|
||||
private const uint MotionOff = 0x4000000C; // door closes
|
||||
private const uint MotionOn = 0x4000000B;
|
||||
private const uint MotionOff = 0x4000000C;
|
||||
|
||||
// CPhysicsObj::weenie_obj pointer at +0x128
|
||||
// Calculated from CPhysicsObj struct layout (confirmed against PhysicsPositionOffset = 0x48).
|
||||
private const int WeenieObjOffset = 0x128;
|
||||
|
||||
// Object ID inside ACCWeenieObject (HashBaseData<UInt32>): vfptr(4) + hash_next*(4) + id(4) = offset 8
|
||||
private const int WeenieIdOffset = 8;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate uint DoMotionDelegate(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent);
|
||||
|
||||
private static DoMotionDelegate? _originalDoMotion;
|
||||
private static DoMotionDelegate? _doMotionDetour; // held alive to prevent GC
|
||||
private static DoMotionDelegate? _doMotionDetour;
|
||||
private static bool _hookInstalled;
|
||||
private static string _statusMessage = "Not initialized.";
|
||||
|
||||
// Per-object motion state: true = On (open/activated), false = Off (closed/deactivated).
|
||||
// Only populated for objects that have had an On or Off motion applied since injection.
|
||||
private static readonly ConcurrentDictionary<uint, bool> _objectOnState = new();
|
||||
|
||||
public static bool IsInstalled => _hookInstalled;
|
||||
|
|
@ -61,54 +61,47 @@ internal static class DoMotionHooks
|
|||
return;
|
||||
}
|
||||
|
||||
int funcOff = DoMotionVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
|
||||
var resolved = HookResolver.Resolve(textSection, "DoMotionHooks.DoMotion",
|
||||
DoMotionPattern, DoMotionFallbackVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
_statusMessage = $"CPhysicsObj::DoMotion VA out of range @ 0x{DoMotionVa:X8}.";
|
||||
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
byte firstByte = textSection.Bytes[funcOff];
|
||||
if (firstByte is 0x00 or 0xCC or 0xC3)
|
||||
{
|
||||
_statusMessage = $"CPhysicsObj::DoMotion looks invalid @ 0x{DoMotionVa:X8} (opcode 0x{firstByte:X2}).";
|
||||
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
|
||||
_statusMessage = $"Resolve failed ({resolved.Detail}).";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
|
||||
_doMotionDetour = DoMotionDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_doMotionDetour);
|
||||
_originalDoMotion = Marshal.GetDelegateForFunctionPointer<DoMotionDelegate>(
|
||||
MinHook.HookCreate(targetAddress, detourPtr));
|
||||
MinHook.HookCreate(resolved.Address, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(targetAddress);
|
||||
MinHook.Enable(resolved.Address);
|
||||
|
||||
_hookInstalled = true;
|
||||
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{targetAddress.ToInt32():X8}.";
|
||||
RynthLog.Verbose($"Compat: do-motion hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
|
||||
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{resolved.Address.ToInt32():X8}.";
|
||||
RynthLog.Compat($"DoMotionHooks: install ok.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: do-motion hook failed - {ex.Message}");
|
||||
RynthLog.Compat($"DoMotionHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last observed On/Off motion state for the given object ID.
|
||||
/// Returns false (not found) if this object has never had an On or Off motion since injection.
|
||||
/// </summary>
|
||||
public static bool TryGetObjectMotionOn(uint objectId, out bool isOn)
|
||||
{
|
||||
return _objectOnState.TryGetValue(objectId, out isOn);
|
||||
}
|
||||
|
||||
private static int _fires;
|
||||
|
||||
private static uint DoMotionDetour(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent)
|
||||
{
|
||||
RecursionGuard.Tick("DoMotionHooks.DoMotion");
|
||||
if (Interlocked.Increment(ref _fires) <= 3)
|
||||
RynthLog.Compat($"DoMotionHooks: fired #{_fires} this=0x{thisPtr.ToInt32():X8} motion=0x{motion:X8}");
|
||||
|
||||
try
|
||||
{
|
||||
if (thisPtr != IntPtr.Zero && (motion == MotionOn || motion == MotionOff))
|
||||
|
|
@ -120,7 +113,8 @@ internal static class DoMotionHooks
|
|||
}
|
||||
catch { }
|
||||
|
||||
return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent);
|
||||
try { return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"DoMotionHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
|
||||
}
|
||||
|
||||
private static uint ReadWeenieId(IntPtr physObjPtr)
|
||||
|
|
|
|||
|
|
@ -82,14 +82,15 @@ internal static class EnchantmentHooks
|
|||
|
||||
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
|
||||
|
||||
if (!_loggedFirstRead && count > 0)
|
||||
if (_enchReadLogCount < 8)
|
||||
{
|
||||
_loggedFirstRead = true;
|
||||
RynthLog.Verbose($"[EnchRead] first player read: {count} enchantments");
|
||||
System.Threading.Interlocked.Increment(ref _enchReadLogCount);
|
||||
RynthLog.Info($"[EnchRead] player read #{_enchReadLogCount}: {count} enchantments (qualPtr=0x{qualPtr.ToInt64():X8})");
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
private static int _enchReadLogCount;
|
||||
|
||||
/// <summary>
|
||||
/// Reads active enchantments from any game object's CEnchantmentRegistry.
|
||||
|
|
@ -142,6 +143,29 @@ internal static class EnchantmentHooks
|
|||
/// </summary>
|
||||
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
|
||||
{
|
||||
// While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this
|
||||
// on AC's main thread for the duration of DestroyObjectCaches — which fires at
|
||||
// world-load, zone change, logout, AND final close), refuse to walk the
|
||||
// CEnchantmentRegistry linked lists: AC is concurrently freeing those nodes, and
|
||||
// an off-thread (plugin-pump) walk over a half-freed node is the recurring
|
||||
// 0x00416C86 (DBOCache::DestroyObj, [null+0x28]) AV.
|
||||
if (DbCacheTeardownHooks.TeardownActive)
|
||||
return -1;
|
||||
|
||||
// Deep-audit finding #23 (2026-06-18): ReadObjectEnchantments (the
|
||||
// other caller of this method) validates the qualities pointer's own
|
||||
// vtable-in-module before ever reaching here; the player path used to
|
||||
// skip straight to walking the registry off a cached pointer with no
|
||||
// such check. KnownPlayerQualitiesPtr is zeroed on logout and
|
||||
// TeardownActive covers the dominant relog race, but a
|
||||
// committed-but-stale pointer surviving both (mainly a
|
||||
// Decal-coexistence exposure) would otherwise be walked as if it
|
||||
// were still a real CACQualities object — a use-after-free read.
|
||||
// Reuses the same canonical-vtable check the skill-read path already
|
||||
// relies on instead of a fresh page-probe-only check.
|
||||
if (!SmartBoxLocator.IsMemoryReadable(qualPtr, 4) || !ClientObjectHooks.IsCacQualitiesObject(qualPtr))
|
||||
return -1;
|
||||
|
||||
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
|
||||
return -1;
|
||||
|
|
@ -149,6 +173,42 @@ internal static class EnchantmentHooks
|
|||
|
||||
if (registryPtr == IntPtr.Zero) return 0;
|
||||
|
||||
// Validate the registry's own vtable too, mirroring ReadObjectEnchantments.
|
||||
if (!SmartBoxLocator.IsMemoryReadable(registryPtr, 4))
|
||||
return -1;
|
||||
IntPtr registryVtable = Marshal.ReadIntPtr(registryPtr);
|
||||
if (!SmartBoxLocator.IsPointerInModule(registryVtable))
|
||||
return -1;
|
||||
|
||||
// Stability check (2026-09-02 "infinite buffing loop" bug): AC's own
|
||||
// main thread mutates these linked lists as buffs land/expire, and in
|
||||
// Decal-coexistence mode this reader runs off-thread on the 30Hz
|
||||
// plugin pump (no EndScene-driven main-thread tick exists there) — a
|
||||
// walk here can race that mutation. A torn/truncated walk silently
|
||||
// under-reports the active buff set; BuffManager.RefreshFromLiveMemory
|
||||
// treats a short read as "buffs expired" and clears its timers,
|
||||
// making a just-completed rebuff pass look like nothing landed and
|
||||
// instantly restarting it. Walk twice and only trust an exact match;
|
||||
// on a mismatch, skip this tick (return -1, already a safe no-op for
|
||||
// every caller) rather than report a truncated set.
|
||||
int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount);
|
||||
|
||||
uint* idsB = stackalloc uint[maxCount];
|
||||
double* expB = stackalloc double[maxCount];
|
||||
int countB = WalkAllLists(registryPtr, idsB, expB, maxCount);
|
||||
|
||||
if (countA != countB)
|
||||
return -1;
|
||||
for (int i = 0; i < countA; i++)
|
||||
{
|
||||
if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i])
|
||||
return -1;
|
||||
}
|
||||
return countA;
|
||||
}
|
||||
|
||||
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount)
|
||||
{
|
||||
int count = 0;
|
||||
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
|
||||
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);
|
||||
|
|
|
|||
161
src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs
Normal file
161
src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - EngineStatusMetrics.cs
|
||||
//
|
||||
// A benign, generic "here are my own metrics" accessor. Each heartbeat tick
|
||||
// caches the engine's live metrics (UpdateMetrics); BuildEngineStatusJson
|
||||
// composes them — plus the main-thread-cached player stats and session
|
||||
// identity — into a small JSON object that a plugin can pull via the
|
||||
// GetEngineStatusJson host bridge. The engine NEVER writes a file, opens a
|
||||
// socket, or networks; it only hands a plugin its own numbers on request.
|
||||
//
|
||||
// (The per-client status file and phone command drain now live entirely in the
|
||||
// private RynthCore.Plugin.RynthRemote plugin, so the public engine carries no
|
||||
// remote or networking code — just this benign metrics accessor.)
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class EngineStatusMetrics
|
||||
{
|
||||
// Latest heartbeat metrics, cached so the parameterless BuildEngineStatusJson
|
||||
// accessor (backing the GetEngineStatusJson host bridge) can compose without
|
||||
// the heartbeat thread's locals. Updated every heartbeat tick; ~1s staleness
|
||||
// is fine for a status pull.
|
||||
private static long _mUptimeSec, _mWorkingSetMb, _mQueueDropped, _mReconciles, _mForceClears;
|
||||
private static int _mFps, _mPluginTicksPerSec;
|
||||
private static bool _mInWorld;
|
||||
|
||||
/// <summary>
|
||||
/// Cache this tick's engine metrics. Called once/second from the heartbeat
|
||||
/// thread with values it already computed — a few field writes, no I/O.
|
||||
/// </summary>
|
||||
internal static void UpdateMetrics(
|
||||
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
|
||||
bool inWorld, long queueDropped, long reconciles, long forceClears)
|
||||
{
|
||||
_mUptimeSec = uptimeSeconds; _mFps = fps; _mPluginTicksPerSec = pluginTicksPerSec;
|
||||
_mWorkingSetMb = workingSetMb; _mInWorld = inWorld; _mQueueDropped = queueDropped;
|
||||
_mReconciles = reconciles; _mForceClears = forceClears;
|
||||
}
|
||||
|
||||
// Per-process session baselines for the per-hour rates. Each client is its own
|
||||
// process, so these naturally reset per launch; we also reset on an XP drop
|
||||
// (relog / char swap).
|
||||
private static long _xpBaseline = -1;
|
||||
private static long _lumBaseline = -1;
|
||||
private static int _deathsBaseline = -1;
|
||||
private static DateTime _statsSessionStartUtc = DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Compose the engine-side status fields as a JSON object string, from the
|
||||
/// latest cached heartbeat metrics. Backs the GetEngineStatusJson host bridge.
|
||||
/// Never throws; returns "{}" on failure. Safe off the main thread — player
|
||||
/// stats come from a main-thread-cached source.
|
||||
/// </summary>
|
||||
internal static string BuildEngineStatusJson()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ms = new MemoryStream(1024);
|
||||
using (var w = new Utf8JsonWriter(ms))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
WriteEngineFields(w, _mUptimeSec, _mFps, _mPluginTicksPerSec, _mWorkingSetMb,
|
||||
_mInWorld, _mQueueDropped, _mReconciles, _mForceClears);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
|
||||
// Writes the engine status fields into an already-open JSON object. The per-hour
|
||||
// baselines below have a single writer (the GetEngineStatusJson accessor path).
|
||||
private static void WriteEngineFields(
|
||||
Utf8JsonWriter w,
|
||||
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
|
||||
bool inWorld, long queueDropped, long reconciles, long forceClears)
|
||||
{
|
||||
w.WriteString("schema", "rynthcore.client-status/1");
|
||||
w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));
|
||||
w.WriteString("host", SafeMachineName());
|
||||
w.WriteNumber("pid", Environment.ProcessId);
|
||||
|
||||
w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty);
|
||||
w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty);
|
||||
w.WriteString("server", SessionStateRegistry.LastServerName ?? string.Empty);
|
||||
|
||||
w.WriteNumber("uptimeSec", uptimeSeconds);
|
||||
w.WriteNumber("fps", fps);
|
||||
w.WriteNumber("pluginTicksPerSec", pluginTicksPerSec);
|
||||
w.WriteNumber("workingSetMB", workingSetMb);
|
||||
w.WriteBoolean("inWorld", inWorld);
|
||||
w.WriteNumber("queueDropped", queueDropped);
|
||||
w.WriteNumber("reconciles", reconciles);
|
||||
w.WriteNumber("forceClears", forceClears);
|
||||
|
||||
// Player stats, read on the main thread by PrefetchPlayerStats and served here off-thread
|
||||
// (the plugin pump can't read these live). deaths all-time; rates/session = whole-session.
|
||||
ClientObjectHooks.TryGetPlayerStats(out long xp, out long lum, out int deaths, out float vitae,
|
||||
out int encVal, out int encCap, out uint landcell,
|
||||
out float px, out float py, out float pz);
|
||||
double vitaePct = Math.Clamp((1.0 - vitae) * 100.0, 0.0, 100.0);
|
||||
// Lazy baselines; reset on an XP drop (relog / char change).
|
||||
if (xp > 0 && (_xpBaseline < 0 || xp < _xpBaseline))
|
||||
{
|
||||
_xpBaseline = xp; _deathsBaseline = deaths; _statsSessionStartUtc = DateTime.UtcNow;
|
||||
}
|
||||
if (_deathsBaseline < 0 && xp > 0) _deathsBaseline = deaths;
|
||||
if (lum > 0 && (_lumBaseline < 0 || lum < _lumBaseline)) _lumBaseline = lum;
|
||||
double hours = (DateTime.UtcNow - _statsSessionStartUtc).TotalHours;
|
||||
double xpPerHour = (hours > 1.0 / 3600.0 && _xpBaseline >= 0 && xp >= _xpBaseline) ? (xp - _xpBaseline) / hours : 0;
|
||||
double lumPerHour = (hours > 1.0 / 3600.0 && _lumBaseline >= 0 && lum >= _lumBaseline) ? (lum - _lumBaseline) / hours : 0;
|
||||
long xpSession = (_xpBaseline >= 0 && xp >= _xpBaseline) ? xp - _xpBaseline : 0;
|
||||
int deathsSession = (_deathsBaseline >= 0 && deaths >= _deathsBaseline) ? deaths - _deathsBaseline : 0;
|
||||
double burdenPct = encCap > 0 ? Math.Round((double)encVal / encCap * 100.0) : 0;
|
||||
w.WriteNumber("deaths", deaths);
|
||||
w.WriteNumber("deathsSession", deathsSession);
|
||||
w.WriteNumber("vitaePct", Math.Round(vitaePct, 1));
|
||||
w.WriteNumber("xpPerHour", Math.Round(xpPerHour));
|
||||
w.WriteNumber("luminancePerHour", Math.Round(lumPerHour));
|
||||
w.WriteNumber("xpSession", xpSession);
|
||||
w.WriteNumber("burdenPct", burdenPct);
|
||||
w.WriteString("area", landcell != 0 ? (landcell >> 16).ToString("X4") : "");
|
||||
// [status-export] live map-dot position. wx/wy are ABSOLUTE world coords (cell-local origin + the
|
||||
// landblock grid offset) because the baked dungeon map's bounds are absolute (DungeonLOS adds the
|
||||
// same gx/gy per vertex). The app maps these straight to map pixels.
|
||||
uint lb = landcell != 0 ? (landcell >> 16) : 0u;
|
||||
bool indoor = lb != 0 && (landcell & 0xFFFF) >= 0x0100; // indoor EnvCells are 0x0100+; outdoor = 0
|
||||
w.WriteString("landblock", lb != 0 ? lb.ToString("X8") : ""); // matches the .bin filename {lb:X8}
|
||||
w.WriteBoolean("indoor", indoor);
|
||||
if (indoor)
|
||||
{
|
||||
double wx = px + ((lb >> 8) & 0xFF) * 192.0;
|
||||
double wy = py + (lb & 0xFF) * 192.0;
|
||||
w.WriteNumber("wx", Math.Round(wx, 2));
|
||||
w.WriteNumber("wy", Math.Round(wy, 2));
|
||||
w.WriteNumber("pz", Math.Round(pz, 2)); // raw local Z — floor-label / fallback hint
|
||||
}
|
||||
// Last engine warning/error (truncated) + age, for remote diagnosis of a stuck box.
|
||||
string? li = RynthLog.LastIssue;
|
||||
if (!string.IsNullOrEmpty(li))
|
||||
{
|
||||
w.WriteString("lastIssue", li.Length > 140 ? li.Substring(0, 140) : li);
|
||||
w.WriteNumber("lastIssueAgeSec", (long)Math.Max(0, (DateTime.UtcNow - RynthLog.LastIssueUtc).TotalSeconds));
|
||||
}
|
||||
else { w.WriteNull("lastIssue"); w.WriteNumber("lastIssueAgeSec", -1); }
|
||||
}
|
||||
|
||||
private static string SafeMachineName()
|
||||
{
|
||||
try { return Environment.MachineName; }
|
||||
catch { return string.Empty; }
|
||||
}
|
||||
}
|
||||
186
src/RynthCore.Engine/Compatibility/GameTickHooks.cs
Normal file
186
src/RynthCore.Engine/Compatibility/GameTickHooks.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks AC's top-level per-frame game-logic tick, <c>Client::UseTime</c>
|
||||
/// (acclient.map 0x00010FA0 + 0x401000 = 0x00411FA0; ImageBase 0x00400000, ASLR
|
||||
/// off), to drain the marshalled CAST queue on AC's MAIN thread IN THE GAME-LOGIC
|
||||
/// PHASE.
|
||||
///
|
||||
/// Why this tick (not EndScene): a cast must run where AC processes player actions
|
||||
/// and advances its cast state machine. EndScene is the RENDER phase — marshalling
|
||||
/// the cast there fired IncrementBusyCount but never completed the cast (proven
|
||||
/// dead-end, reverted 2026-05-19: no projectile/damage, busy leaked, cast slot
|
||||
/// jammed). Client::UseTime IS the game-logic phase, so the cast completes there.
|
||||
///
|
||||
/// Why marshal casts at all: CastSpell is the LAST off-thread AC mutator. Run off
|
||||
/// the pump thread it mutates AC's single-threaded object/animation/enchant graph
|
||||
/// and corrupts it; AC then AVs LATER in its own per-tick code — CSequence::
|
||||
/// update_internal (animation, captured 2026-06-03), 0x67E779 (classify), 0x0055FA24
|
||||
/// (range-list). Running the cast here, on AC's own game thread, removes that race
|
||||
/// at the source — the root fix for the off-thread object-graph corruption class.
|
||||
///
|
||||
/// Thiscall detour, same proven pattern as DbCacheTeardownHooks / LogoutLifecycleHooks.
|
||||
/// DrainCasts early-returns when no cast is pending, so the detour is alloc-free in
|
||||
/// the common per-frame case — the same safe profile as the existing EndScene detour.
|
||||
/// </summary>
|
||||
internal static class GameTickHooks
|
||||
{
|
||||
private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL
|
||||
|
||||
// Client::UseTime returns a bool (AL): AC's main loop drives it as
|
||||
// do { } while ( UseTime() != 0 );
|
||||
// so the return value MUST be propagated. A void delegate discards AC's AL
|
||||
// and the loop then reads whatever the managed epilogue left in EAX — when
|
||||
// that is nonzero the loop never exits and the client hard-freezes (main
|
||||
// thread spins in UseTime pumping messages but never rendering; bot threads
|
||||
// keep running). Dump-confirmed root cause, 2026-06-05.
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate int ThisCallBoolDelegate(IntPtr thisPtr);
|
||||
|
||||
private static ThisCallBoolDelegate? _originalUseTime;
|
||||
private static ThisCallBoolDelegate? _useTimeDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static int _installed;
|
||||
private static int _exitLatch;
|
||||
|
||||
// Verified unique + lands exactly at UseTimeVa offline (tools/pe_pattern.py).
|
||||
// Replaces the prior warn-only prologue check; null = wildcard (rel32 call operand).
|
||||
private static readonly byte?[] UseTimePattern = [ 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0xE8, null, null, null, null, 0x84, 0xC0, 0x74 ];
|
||||
|
||||
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
RynthLog.Compat("GameTickHooks: acclient.exe not available.");
|
||||
return;
|
||||
}
|
||||
|
||||
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "GameTick.UseTime", UseTimePattern, UseTimeVa);
|
||||
if (!resolved.Success)
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime unresolved (VA 0x{UseTimeVa:X8}) — cast marshalling NOT installed.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_targetAddress = resolved.Address;
|
||||
_useTimeDetour = UseTimeDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
|
||||
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
Volatile.Write(ref _installed, 1);
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Volatile.Write(ref _installed, 0);
|
||||
RynthLog.Compat($"GameTickHooks: install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int UseTimeDetour(IntPtr thisPtr)
|
||||
{
|
||||
// Hang-watchdog beat from the game-logic tick (no frame count): the
|
||||
// EndScene beat alone left the watchdog blind to a main thread that
|
||||
// wedges before the new generation's EndScene hook installs.
|
||||
try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); }
|
||||
catch { }
|
||||
// Diag (diag/logoff-origin): 1 Hz sample of the client's own input-idle clock.
|
||||
try { LogoffOriginProbe.SampleIdleOnGameThread(); }
|
||||
catch { }
|
||||
// Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's
|
||||
// selection and the cast initiates, then THIS SAME UseTime call processes it to
|
||||
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
|
||||
// tick landed self-buffs but not targeted casts: the selection set at the end of
|
||||
// tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is
|
||||
// pending. Must never throw into AC's native frame.
|
||||
try { AcMainThreadQueue.DrainCasts(); }
|
||||
catch { }
|
||||
|
||||
// Refresh TeleportStateHooks' main-thread cache every real game tick. This
|
||||
// detour (unlike EndScene) fires on AC's true main thread in EVERY mode
|
||||
// including Decal-coexistence (no D3D9 hook there) — without this,
|
||||
// off-thread callers of IsPortaling in coexistence mode would see a
|
||||
// perpetually stale cache since nothing else ever reads it on-thread.
|
||||
// The getter itself does the guarded read + cache write; discard the value.
|
||||
try { _ = TeleportStateHooks.IsPortaling; }
|
||||
catch { }
|
||||
|
||||
// Run AC's own game-logic + physics + animation pass.
|
||||
int result;
|
||||
try { result = _originalUseTime!(thisPtr); }
|
||||
catch { result = 0; }
|
||||
|
||||
// ── Game loop is exiting — quiesce BEFORE AC's teardown ──────────────
|
||||
// AC's main loop is `do { } while (UseTime() != 0)`; a 0 return means
|
||||
// this was the LAST tick and AC tears its world down next (DBCache::
|
||||
// DestroyObjectCaches frees every DBObj). This is the only close signal
|
||||
// that covers ALL exit paths: the in-game exit / logout-quit flow never
|
||||
// delivers WM_CLOSE, so the Win32Backend/AvaloniaOverlay WM_CLOSE
|
||||
// quiesce never ran and the ~63 Hz pump kept firing Move/SetAutoRun/
|
||||
// object reads into freed objects -> the on-close AV at acclient
|
||||
// 0x00416C86 (DBOCache::DestroyObj reading [null+0x28]). We are still
|
||||
// INSIDE the final UseTime call here — AC objects are all valid — so
|
||||
// the pump's in-flight frame finishes safely during the bounded join.
|
||||
if (result == 0 && Interlocked.Exchange(ref _exitLatch, 1) == 0)
|
||||
{
|
||||
try { RynthLog.Compat("GameTickHooks: Client::UseTime returned 0 — game loop exiting; quiescing plugin pump + late input before AC teardown."); }
|
||||
catch { }
|
||||
// Drop the busy watchdog's cached ClientUISystem ptr (freed next).
|
||||
try { BusyCountHooks.ResetSession(); }
|
||||
catch { }
|
||||
// Arm the late mouse/cursor swallow in BOTH game-window subclasses
|
||||
// (the 0x0056547B UpdateCursorState close-AV trigger) — WM_CLOSE
|
||||
// never fired on this path, so neither latch is set yet.
|
||||
try { ImGuiBackend.Win32Backend.MarkCloseInFlight(); }
|
||||
catch { }
|
||||
try { UI.RynthOverlayWindow.MarkCloseInFlight(); }
|
||||
catch { }
|
||||
try { EntryPoint.StopTickPumpAndJoin(); }
|
||||
catch { }
|
||||
// Skip the post-tick drains/watchdog below — no engine-issued
|
||||
// mutation may run once the loop has decided to exit.
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Drain the marshalled-action ring AFTER AC's tick, NOT before.
|
||||
// ⚠ Issuing a UseObject (corpse open) / movement / stance change starts
|
||||
// or REPLACES the player's CSequence motion — and AC's animation update
|
||||
// (CPhysicsObj::update_object -> CSequence::update_internal ->
|
||||
// AnimSequenceNode::get_high_frame) runs inside _originalUseTime above.
|
||||
// Draining BEFORE that call meant the SAME tick walked the sequence we
|
||||
// had just perturbed, hitting a freed/null anim node -> hard AV at
|
||||
// acclient 0x5263xx/0x5264xx (null+0xC). Live-diagnosed 2026-06-11
|
||||
// during a rapid corpse-open grind (AC-only crash stack, no engine
|
||||
// frames). Draining after lets AC install the new gesture's node and
|
||||
// walk it cleanly on its NEXT tick. The EndScene drain (the other call
|
||||
// site) is already post-physics in the frame, so it was never the
|
||||
// trigger. (Casts stay PRE-tick above — their selection-timing
|
||||
// requirement, and they go through the separate cast slot.)
|
||||
try { AcMainThreadQueue.Drain(); }
|
||||
catch { }
|
||||
// Busy watchdog: also post-tick now. Its decrement / cursor-refresh
|
||||
// touch m_cBusy, not the motion sequence, so order is immaterial here;
|
||||
// keeping all engine-issued mutations after AC's pass is the invariant.
|
||||
try { BusyCountHooks.CheckWatchdog(); }
|
||||
catch { }
|
||||
|
||||
// MUST return Client::UseTime's own bool — AC loops do/while on it.
|
||||
return result;
|
||||
}
|
||||
}
|
||||
143
src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs
Normal file
143
src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Writes one short "hb #N" line to the unified log every second from a
|
||||
/// background thread. Purpose: when AC dies and no termination hook fires,
|
||||
/// the heartbeat gives a hard upper-bound timestamp for when the process
|
||||
/// went silent — so external traces (Procmon, Application Event Log,
|
||||
/// network captures) can be correlated to the second.
|
||||
///
|
||||
/// Cheap (one log line / second). Background thread, won't keep the
|
||||
/// process alive on its own. One-shot start; safe to call from
|
||||
/// pre-resume early-init.
|
||||
/// </summary>
|
||||
internal static class HeartbeatLogger
|
||||
{
|
||||
private const int IntervalMs = 1000;
|
||||
private static int _started;
|
||||
private static int _stopRequested;
|
||||
private static int _exited;
|
||||
private static Thread? _thread;
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
_thread = new Thread(Run)
|
||||
{
|
||||
Name = "RynthCore.Heartbeat",
|
||||
IsBackground = true,
|
||||
Priority = ThreadPriority.BelowNormal
|
||||
};
|
||||
_thread.Start();
|
||||
RynthLog.Info("HeartbeatLogger: started (1s cadence).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals the heartbeat thread to exit and waits up to <paramref name="timeoutMs"/>
|
||||
/// for it to do so. Called from EngineLifecycle.Shutdown — without this, the
|
||||
/// thread keeps running past loader FreeLibrary of the engine, executing code
|
||||
/// pages that have been unmapped → CLR exception / FAIL_FAST during hot reload.
|
||||
/// </summary>
|
||||
public static bool StopAndJoin(int timeoutMs = 1500)
|
||||
{
|
||||
if (_thread == null) return true;
|
||||
Interlocked.Exchange(ref _stopRequested, 1);
|
||||
|
||||
long deadline = Environment.TickCount64 + timeoutMs;
|
||||
while (Volatile.Read(ref _exited) == 0 && Environment.TickCount64 < deadline)
|
||||
Thread.Sleep(10);
|
||||
|
||||
bool exited = Volatile.Read(ref _exited) != 0;
|
||||
if (!exited)
|
||||
RynthLog.Info($"HeartbeatLogger: did NOT exit within {timeoutMs}ms.");
|
||||
return exited;
|
||||
}
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
long tick = 0;
|
||||
int lastFrames = 0;
|
||||
int lastPlugTicks = 0;
|
||||
long lastMs = Environment.TickCount64;
|
||||
long startMs = lastMs;
|
||||
try
|
||||
{
|
||||
while (Volatile.Read(ref _stopRequested) == 0)
|
||||
{
|
||||
tick++;
|
||||
// Rich beat: a silent-death log tail now shows WHAT the client
|
||||
// was doing — render rate (0 fps = render dead, process alive),
|
||||
// plugin pump rate (0 = wedged pump), memory trend, and in-world
|
||||
// state — not just "alive at T". All cheap, engine-side reads.
|
||||
try
|
||||
{
|
||||
long nowMs = Environment.TickCount64;
|
||||
long dtMs = nowMs - lastMs; if (dtMs <= 0) dtMs = 1;
|
||||
int frames = MainThreadHangWatchdog.FrameCount;
|
||||
int plug = Plugins.PluginManager.TickCount;
|
||||
int fps = (int)((frames - lastFrames) * 1000L / dtMs);
|
||||
int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs);
|
||||
lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs;
|
||||
|
||||
long wsMb = 0;
|
||||
try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { }
|
||||
int login = 0;
|
||||
try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { }
|
||||
|
||||
// qd = marshalled actions silently dropped (ring full). A
|
||||
// climbing qd with healthy fps means the consumer phase is
|
||||
// dead — exactly the silent blackhole class the review found.
|
||||
long dropped = 0;
|
||||
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
|
||||
// rec = busy reconciles (cast/item-action), fcl = force-clears.
|
||||
// Soak health: rec climbs during combat/loot; fcl stays flat.
|
||||
long rec = 0, fcl = 0;
|
||||
try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { }
|
||||
// idle = the client's own input-idle clock (diag/logoff-origin); the retail
|
||||
// client logs itself off past InactiveTimeBeforeLogout. Omitted when unknown.
|
||||
int idle = -1;
|
||||
try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { }
|
||||
string idleField = idle >= 0 ? $" idle={idle}s" : "";
|
||||
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}");
|
||||
|
||||
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
|
||||
// them to a plugin (the RynthRemote status export). No file write, no networking.
|
||||
EngineStatusMetrics.UpdateMetrics((nowMs - startMs) / 1000, fps, pps, wsMb,
|
||||
login == 1, dropped, rec, fcl);
|
||||
}
|
||||
catch { /* never let the heartbeat itself bring anything down */ }
|
||||
// Self-healing: clear a stuck floating-panel click-through
|
||||
// (DockedPanelPointerCaptureActive whose disarm was lost ->
|
||||
// every floating panel left WS_EX_TRANSPARENT). Runs here on
|
||||
// purpose: independent of the input path that strands it.
|
||||
try { RynthCore.Engine.UI.AvaloniaOverlay.WatchdogClearStuckClickThrough(); }
|
||||
catch { /* never let the heartbeat itself bring anything down */ }
|
||||
// Mid-session log rotation (~once/minute): without it a long
|
||||
// soak grows RynthCore.<pid>.log without bound (startup-only
|
||||
// rotation never fires mid-session and is skipped on reload).
|
||||
if (tick % 60 == 0)
|
||||
{
|
||||
try { LogPaths.RotateIfOversized(); }
|
||||
catch { /* never let the heartbeat itself bring anything down */ }
|
||||
}
|
||||
// Sleep in short slices so a stop signal is observed within <100ms,
|
||||
// not up to a full IntervalMs after request.
|
||||
int slept = 0;
|
||||
while (slept < IntervalMs && Volatile.Read(ref _stopRequested) == 0)
|
||||
{
|
||||
try { Thread.Sleep(50); } catch { return; }
|
||||
slept += 50;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _exited, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
190
src/RynthCore.Engine/Compatibility/HookResolver.cs
Normal file
190
src/RynthCore.Engine/Compatibility/HookResolver.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/HookResolver.cs
|
||||
//
|
||||
// Shared helper that resolves an acclient.exe function address by:
|
||||
// 1. Pattern scanning the .text section for a unique byte signature.
|
||||
// 2. Falling back to a hardcoded VA only if the pattern misses, with loud
|
||||
// logging so we know the next time the binary diverges.
|
||||
// 3. Reporting failure with full diagnostics so the failing hook can be
|
||||
// identified from the log alone.
|
||||
//
|
||||
// Every site that previously hardcoded `int funcOff = TargetVa - text.TextBaseVa`
|
||||
// should funnel through Resolve() so the install log line tells us exactly
|
||||
// how the address was found — pattern (good), fallback (suspect), or
|
||||
// unavailable (definitely the wrong build).
|
||||
// ============================================================================
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class HookResolver
|
||||
{
|
||||
public enum ResolveSource { Failed, PatternScan, FallbackVa }
|
||||
|
||||
public readonly struct ResolveResult
|
||||
{
|
||||
public ResolveResult(IntPtr address, ResolveSource source, string detail)
|
||||
{
|
||||
Address = address;
|
||||
Source = source;
|
||||
Detail = detail;
|
||||
}
|
||||
|
||||
public IntPtr Address { get; }
|
||||
public ResolveSource Source { get; }
|
||||
public string Detail { get; }
|
||||
public bool Success => Source != ResolveSource.Failed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locate <paramref name="functionName"/> in the loaded acclient.exe text
|
||||
/// section. Pattern is the source of truth; <paramref name="fallbackVa"/>
|
||||
/// is a last-resort safety net if pattern matching fails (e.g. a tiny
|
||||
/// build delta we haven't anticipated).
|
||||
///
|
||||
/// Logs at every outcome so the install-time log line names which hook
|
||||
/// resolved how — when a crash happens, the *previous* successful resolve
|
||||
/// log entry tells you which hook was the most recent thing patched.
|
||||
/// </summary>
|
||||
public static ResolveResult Resolve(
|
||||
AcClientTextSection text,
|
||||
string functionName,
|
||||
byte?[] pattern,
|
||||
int fallbackVa)
|
||||
{
|
||||
try
|
||||
{
|
||||
int firstMatch = PatternScanner.FindPattern(text.Bytes, pattern);
|
||||
if (firstMatch >= 0)
|
||||
{
|
||||
// Deep-audit finding #30 (2026-06-18): this used to find only
|
||||
// the first and the immediately-next match, so a 3rd+
|
||||
// occurrence was never considered and the multimatch log
|
||||
// claimed to have examined only 2 of N. Not reachable on the
|
||||
// current shipped binary (all patterns verified unique) —
|
||||
// this is a defensive fallback for future binary drift, but
|
||||
// "examined 2 of N and picked wrong" is exactly the failure
|
||||
// mode a defensive fallback shouldn't have. Enumerate every
|
||||
// match and keep the global-nearest to the fallback VA.
|
||||
int fallbackOff = fallbackVa - text.TextBaseVa;
|
||||
int chosen = firstMatch;
|
||||
int bestDist = Math.Abs(firstMatch - fallbackOff);
|
||||
int matchCount = 1;
|
||||
string detail;
|
||||
|
||||
if (bestDist != 0) // exact-VA short-circuit — no other match can beat this
|
||||
{
|
||||
int searchFrom = firstMatch + 1;
|
||||
while (true)
|
||||
{
|
||||
int next = PatternScanner.FindPatternInRegion(text.Bytes, pattern, searchFrom, text.Bytes.Length);
|
||||
if (next < 0) break;
|
||||
matchCount++;
|
||||
int dist = Math.Abs(next - fallbackOff);
|
||||
if (dist < bestDist) { bestDist = dist; chosen = next; }
|
||||
if (bestDist == 0) break;
|
||||
searchFrom = next + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (matchCount == 1)
|
||||
{
|
||||
detail = "pattern-unique";
|
||||
}
|
||||
else
|
||||
{
|
||||
detail = $"pattern-multimatch(near-fallback {chosen:X}, {matchCount} matches)";
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{functionName}]: pattern matched {matchCount} locations — " +
|
||||
$"chose 0x{text.TextBaseVa + chosen:X8} as nearest to fallback 0x{fallbackVa:X8}.");
|
||||
}
|
||||
|
||||
IntPtr addr = new IntPtr(text.TextBaseVa + chosen);
|
||||
RynthLog.Info(
|
||||
$"HookResolver[{functionName}]: RESOLVED via {detail} @ 0x{addr.ToInt32():X8} " +
|
||||
$"(fallbackVa=0x{fallbackVa:X8}, delta={(addr.ToInt32() - fallbackVa):+#;-#;0}).");
|
||||
return new ResolveResult(addr, ResolveSource.PatternScan, detail);
|
||||
}
|
||||
|
||||
// Pattern miss — try the hardcoded VA, but only if the bytes there
|
||||
// look plausible (not padding / interrupt fill / a bare ret).
|
||||
int vaOff = fallbackVa - text.TextBaseVa;
|
||||
if (vaOff >= 0 && vaOff < text.Bytes.Length)
|
||||
{
|
||||
byte firstByte = text.Bytes[vaOff];
|
||||
bool prologueLooksValid = firstByte is not (0x00 or 0xCC or 0xC3);
|
||||
|
||||
if (prologueLooksValid)
|
||||
{
|
||||
IntPtr addr = new IntPtr(fallbackVa);
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{functionName}]: PATTERN MISS — falling back to hardcoded VA 0x{fallbackVa:X8} " +
|
||||
$"(prologue byte=0x{firstByte:X2}). The binary may have shifted; install proceeds but is RISKY.");
|
||||
return new ResolveResult(addr, ResolveSource.FallbackVa, $"fallback-va(prologue=0x{firstByte:X2})");
|
||||
}
|
||||
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
|
||||
$"prologue is invalid (byte=0x{firstByte:X2}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
|
||||
$"is outside the readable .text window.");
|
||||
}
|
||||
|
||||
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, "unavailable");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"HookResolver[{functionName}]: UNAVAILABLE — exception during resolve: {ex.GetType().Name}: {ex.Message}");
|
||||
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, $"exception:{ex.GetType().Name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolve a DATA/global address (.data/.rdata — singleton ptr, selection id, string
|
||||
/// null-buffer, fn-ptr slot, …) by CODE-XREF: pattern-scan .text for a unique instruction
|
||||
/// that references the address as an absolute operand (the 4 operand bytes wildcarded in
|
||||
/// <paramref name="codePattern"/>), then read the address back from that operand at
|
||||
/// <paramref name="operandOffset"/>. Robust if the global relocates across builds.
|
||||
///
|
||||
/// Unlike function resolution this does NOT fail closed: the data VA is read/written by the
|
||||
/// caller, which assumes it always has one, so a miss falls back to the hardcoded VA (== old
|
||||
/// behavior) with a loud log rather than returning Zero.
|
||||
/// </summary>
|
||||
public static ResolveResult ResolveData(
|
||||
AcClientTextSection text, string name, byte?[] codePattern, int operandOffset, int fallbackVa)
|
||||
{
|
||||
try
|
||||
{
|
||||
int first = PatternScanner.FindPattern(text.Bytes, codePattern);
|
||||
if (first >= 0 && first + operandOffset + 4 <= text.Bytes.Length)
|
||||
{
|
||||
int next = PatternScanner.FindPatternInRegion(text.Bytes, codePattern, first + 1, text.Bytes.Length);
|
||||
if (next < 0)
|
||||
{
|
||||
int operand = BitConverter.ToInt32(text.Bytes, first + operandOffset);
|
||||
RynthLog.Info(
|
||||
$"HookResolver[{name}]: RESOLVED via data-xref @ 0x{operand:X8} " +
|
||||
$"(fallbackVa=0x{fallbackVa:X8}, delta={(operand - fallbackVa):+#;-#;0}).");
|
||||
return new ResolveResult(new IntPtr(operand), ResolveSource.PatternScan, "data-xref");
|
||||
}
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{name}]: data-xref matched MULTIPLE .text sites — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat(
|
||||
$"HookResolver[{name}]: data-xref pattern not found — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
|
||||
}
|
||||
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"HookResolver[{name}]: data-xref exception {ex.GetType().Name}: {ex.Message} — fallback VA 0x{fallbackVa:X8}.");
|
||||
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback-exc");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -82,8 +82,8 @@ internal static class LoginLifecycleHooks
|
|||
IsInstalled = true;
|
||||
_statusMessage = $"Hooked SendLoginCompleteNotification @ 0x{_targetAddress.ToInt32():X8}.";
|
||||
_nextStatusLogTick = Environment.TickCount64 + 3000;
|
||||
RynthLog.Verbose(
|
||||
$"Compat: login lifecycle hook ready - SendLoginCompleteNotification=0x{_targetAddress.ToInt32():X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}");
|
||||
RynthLog.Info(
|
||||
$"LoginLifecycleHooks: target=0x{_targetAddress.ToInt32():X8} (funcOff=0x{funcOff:X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}, prologueDistance={(textSection.TextBaseVa + callSiteOff) - _targetAddress.ToInt32()} bytes).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -92,6 +92,18 @@ internal static class LoginLifecycleHooks
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the one-shot observation flag so the next <c>SendLoginCompleteNotification</c>
|
||||
/// raises <see cref="LoginComplete"/> again. Called by the logout pipeline so the
|
||||
/// following login (e.g. swapping characters) re-runs login-gated startup.
|
||||
/// </summary>
|
||||
public static void ResetObservation()
|
||||
{
|
||||
HasObservedLoginComplete = false;
|
||||
_statusMessage = "Awaiting next SendLoginCompleteNotification.";
|
||||
_waitingLogged = false;
|
||||
}
|
||||
|
||||
public static void Poll()
|
||||
{
|
||||
if (HasObservedLoginComplete || !IsInstalled)
|
||||
|
|
@ -111,6 +123,7 @@ internal static class LoginLifecycleHooks
|
|||
|
||||
private static void SendLoginCompleteNotificationDetour(IntPtr thisPtr)
|
||||
{
|
||||
RecursionGuard.Tick("LoginLifecycleHooks.SendLoginCompleteNotification");
|
||||
_originalSendLoginCompleteNotification!(thisPtr);
|
||||
SignalLoginComplete("CPlayerSystem::SendLoginCompleteNotification");
|
||||
}
|
||||
|
|
@ -125,4 +138,17 @@ internal static class LoginLifecycleHooks
|
|||
RynthLog.Verbose($"Compat: login complete observed via {source}.");
|
||||
LoginComplete?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mark login as already complete and fire the <see cref="LoginComplete"/>
|
||||
/// event without waiting for the AC client's
|
||||
/// <c>SendLoginCompleteNotification</c>. Used by the hot-reload path: the
|
||||
/// new engine instance starts after the game is already in-world, so the
|
||||
/// notification will never fire again — we synthesize it so subscribers
|
||||
/// (PluginManager, D3D9 bootstrapper) reach their post-login state.
|
||||
/// </summary>
|
||||
public static void MarkAlreadyComplete(string source)
|
||||
{
|
||||
SignalLoginComplete(source);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,16 @@ internal static class LogoBypassHooks
|
|||
private const int DismissClickX = 350;
|
||||
private const int DismissClickY = 100;
|
||||
|
||||
// Early-burst dismiss: covers the pre-connect splash/EULA/Turbine logo
|
||||
// screens. Those screens appear before AC contacts the server, so the
|
||||
// packet-driven NotifyPostConnect / NotifyCharacterList triggers can never
|
||||
// catch them. As soon as we find a window of our PID, fire a series of
|
||||
// clicks at the splash hotspot to dismiss whatever shows up. Decal sidesteps
|
||||
// this by directly patching AC's splash code; we don't have that path, so
|
||||
// we brute-force it with PostMessage spam.
|
||||
private const int EarlyBurstClicks = 12;
|
||||
private const int EarlyBurstIntervalMs = 400;
|
||||
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
|
|
@ -68,7 +78,7 @@ internal static class LogoBypassHooks
|
|||
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
{
|
||||
RynthLog.Verbose("LogoBypass: Login already complete at start - skipping.");
|
||||
RynthLog.Compat("LogoBypass: Login already complete at start - skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -87,7 +97,7 @@ internal static class LogoBypassHooks
|
|||
};
|
||||
thread.Start();
|
||||
|
||||
RynthLog.Verbose("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
|
||||
RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
|
||||
}
|
||||
|
||||
public static void NotifyCharacterListObserved()
|
||||
|
|
@ -121,10 +131,30 @@ internal static class LogoBypassHooks
|
|||
return;
|
||||
}
|
||||
|
||||
RynthLog.Verbose($"LogoBypass: Found game HWND 0x{hwnd:X8} - awaiting post-connect or character-list signal.");
|
||||
RynthLog.Compat($"LogoBypass: Found game HWND 0x{hwnd:X8} - firing {EarlyBurstClicks} early dismiss clicks before awaiting packet signals.");
|
||||
EarlyBurstDismiss(hwnd);
|
||||
BypassLoop(hwnd);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fires a burst of dismiss clicks immediately, covering the pre-connect
|
||||
/// splash/EULA screens that the packet-driven triggers can't catch.
|
||||
/// Stops early if the client transitions out of the pre-login state
|
||||
/// (LoginComplete or auto-login-already-fired). Cheap to call into a
|
||||
/// post-splash window: the clicks just become spurious viewport clicks
|
||||
/// that AC's pre-connect UI ignores.
|
||||
/// </summary>
|
||||
private static void EarlyBurstDismiss(IntPtr hwnd)
|
||||
{
|
||||
for (int i = 0; i < EarlyBurstClicks; i++)
|
||||
{
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
return;
|
||||
SendDismissInput(hwnd);
|
||||
Thread.Sleep(EarlyBurstIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ScheduleDismissClicks(string triggerName, int startDelayMs)
|
||||
{
|
||||
if (!_started)
|
||||
|
|
@ -147,7 +177,7 @@ internal static class LogoBypassHooks
|
|||
|
||||
if (scheduled)
|
||||
{
|
||||
RynthLog.Verbose(
|
||||
RynthLog.Compat(
|
||||
$"LogoBypass: {triggerName} observed - scheduling {ScheduledDismissClicks} dismiss click(s) at ({DismissClickX}, {DismissClickY}) with {startDelayMs}ms start delay.");
|
||||
}
|
||||
}
|
||||
|
|
@ -225,7 +255,7 @@ internal static class LogoBypassHooks
|
|||
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
|
||||
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
|
||||
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
|
||||
RynthLog.Verbose($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}).");
|
||||
RynthLog.Compat($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}) to hwnd=0x{hwnd.ToInt64():X8}.");
|
||||
}
|
||||
|
||||
private static IntPtr MakeLParam(int x, int y) =>
|
||||
|
|
@ -233,31 +263,58 @@ internal static class LogoBypassHooks
|
|||
|
||||
private static bool ReadSkipLogosFromContext()
|
||||
{
|
||||
string rootDir = "(unresolved)";
|
||||
try
|
||||
{
|
||||
string rootDir = Path.Combine(
|
||||
rootDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore");
|
||||
|
||||
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
|
||||
bool? processValue = ReadSkipLogosFromFile(processPath);
|
||||
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext processId={Environment.ProcessId} processPath='{processPath}'");
|
||||
bool? processValue = ReadSkipLogosFromFile(processPath, "process");
|
||||
if (processValue.HasValue)
|
||||
{
|
||||
RynthLog.Compat($"LogoBypass: process-scoped context resolved SkipLoginLogos={processValue.Value}.");
|
||||
return processValue.Value;
|
||||
}
|
||||
|
||||
return ReadSkipLogosFromFile(Path.Combine(rootDir, "launch_context.json")) ?? false;
|
||||
string rootPath = Path.Combine(rootDir, "launch_context.json");
|
||||
RynthLog.Compat($"LogoBypass: process file did not yield value, falling back to rootPath='{rootPath}'");
|
||||
bool? rootValue = ReadSkipLogosFromFile(rootPath, "root");
|
||||
bool resolved = rootValue ?? false;
|
||||
RynthLog.Compat($"LogoBypass: root context resolved SkipLoginLogos={(rootValue.HasValue ? rootValue.Value.ToString() : "MISSING")} (effective={resolved}).");
|
||||
return resolved;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext threw {ex.GetType().Name}: {ex.Message} (rootDir='{rootDir}'). Treating as SkipLoginLogos=false.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? ReadSkipLogosFromFile(string path)
|
||||
private static bool? ReadSkipLogosFromFile(string path, string label)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
RynthLog.Compat($"LogoBypass: {label} context file missing at '{path}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
return doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el) ? el.GetBoolean() : null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
if (!doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el))
|
||||
{
|
||||
RynthLog.Compat($"LogoBypass: {label} context at '{path}' has no SkipLoginLogos property.");
|
||||
return null;
|
||||
}
|
||||
return el.GetBoolean();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"LogoBypass: {label} context at '{path}' read/parse failed: {ex.GetType().Name}: {ex.Message}.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
802
src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs
Normal file
802
src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs
Normal file
|
|
@ -0,0 +1,802 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// DIAGNOSTIC (branch diag/logoff-origin, 2026-09-27): pins down which client code path
|
||||
/// asks the server to log the character off. Lucy logged off by herself mid-fight at
|
||||
/// 14:28:20, 15:36:52 and 16:43:30; the ExecuteLogOff caller was the server's
|
||||
/// CharacterLogOff (0xF653) handler, and ACE only sends that in reply to a logoff the
|
||||
/// client requested. This probe watches the request side. It changes no behaviour.
|
||||
///
|
||||
/// Hooks (all log caller frames via <see cref="LogoutLifecycleHooks.LogCaller"/>):
|
||||
/// - CPlayerSystem::LogOffCharacter(bool immediate) every client logoff entry point
|
||||
/// - CPlayerSystem::RequestLogOff() prints "Logging off...", sends
|
||||
/// - Proto_UI::LogOffCharacter(uint gid) builds + sends the 0xF653 request
|
||||
/// - CPlayerSystem::SetLogOffStarted() ~3 s after the request (timeline)
|
||||
/// - ClientNet::LogOffServer() transport-level disconnect
|
||||
///
|
||||
/// Context, dumped once when a logoff is requested (or when one completes with no request):
|
||||
/// - client input idle time vs InactiveTimeBeforeLogout (the retail client logs itself
|
||||
/// off from ClientUISystem::UseTime when Timer::cur_time minus CInputManager's
|
||||
/// last-input time exceeds it; 1200 s on the reference client)
|
||||
/// - game-window foreground/focus state and when it last changed
|
||||
/// - ring buffers: the last window messages the WndProc subclass saw (keys, clicks,
|
||||
/// focus, close, syscommand) and the last chat lines through the engine's chat paths
|
||||
/// - an acclient-only stack sweep (return addresses above the detour; may be stale)
|
||||
///
|
||||
/// Idle milestones are also logged as the idle time climbs toward the threshold, and the
|
||||
/// heartbeat line carries idle=Ns.
|
||||
///
|
||||
/// CommandInterpreter::HandleLogOff (0x006B4270) is NOT hooked: it is a two-instruction
|
||||
/// thunk to CommandInterpreter::Disable (vtable +0x84) that runs as a consequence of a
|
||||
/// logoff, not a requester.
|
||||
/// </summary>
|
||||
internal static unsafe class LogoffOriginProbe
|
||||
{
|
||||
// Fallback VAs on the reference retail client (4,841,472 bytes, SizeOfImage 0x56D000).
|
||||
// The patterns below are the source of truth (cut + verified with tools/pe_pattern.py).
|
||||
private const int ProbeLogOffCharacterVa = 0x005642C0; // CPlayerSystem::LogOffCharacter(bool)
|
||||
private const int ProbeRequestLogOffVa = 0x00563B70; // CPlayerSystem::RequestLogOff()
|
||||
private const int ProbeProtoLogOffVa = 0x005475E0; // Proto_UI::LogOffCharacter(uint gid), cdecl
|
||||
private const int ProbeSetLogOffStartedVa = 0x0055E4F0; // CPlayerSystem::SetLogOffStarted()
|
||||
private const int ProbeLogOffServerVa = 0x00544AB0; // ClientNet::LogOffServer()
|
||||
private const int ProbeTimerCurTimeVa = 0x008379A8; // Timer::cur_time (double, seconds)
|
||||
private const int ProbeInputManagerVa = 0x00837FF4; // ICIDM::s_cidm (CInputManager*)
|
||||
private const int ProbeIdleLimitVa = 0x007CEB70; // InactiveTimeBeforeLogout (double, 1200.0)
|
||||
|
||||
private const int ReferenceImageSize = 0x0056D000;
|
||||
|
||||
// push esi; mov esi,ecx; push 0; lea ecx,[esi+0x30]; call; mov al,[esp+8]; test al,al
|
||||
private static readonly byte?[] LogOffCharacterPattern = [ 0x56, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4E, 0x30, 0xE8, null, null, null, null, 0x8A, 0x44, 0x24, 0x08, 0x84, 0xC0 ];
|
||||
// push ecx; push esi; push edi; push "Logging off...\n"; mov esi,ecx; push 0; lea ecx,[esp+0x10]; call
|
||||
private static readonly byte?[] RequestLogOffPattern = [ 0x51, 0x56, 0x57, 0x68, null, null, null, null, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0xE8 ];
|
||||
// push 8; call alloc; mov ecx,[esp+8]; push 8; mov dword ptr [eax],0xF653
|
||||
private static readonly byte?[] ProtoLogOffPattern = [ 0x6A, 0x08, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x08, 0x6A, 0x08, 0xC7, 0x00, 0x53, 0xF6, 0x00, 0x00 ];
|
||||
// mov byte ptr [ecx+0x221],0; ret
|
||||
private static readonly byte?[] SetLogOffStartedPattern = [ 0xC6, 0x81, 0x21, 0x02, 0x00, 0x00, 0x00, 0xC3 ];
|
||||
// push ebp; push esi; push edi; mov ebp,ecx; mov esi,[ebp+0x8820]; push 0x1C; call
|
||||
private static readonly byte?[] LogOffServerPattern = [ 0x55, 0x56, 0x57, 0x8B, 0xE9, 0x8B, 0xB5, 0x20, 0x88, 0x00, 0x00, 0x6A, 0x1C, 0xE8 ];
|
||||
|
||||
// Data globals by code-xref (operand at offset 2).
|
||||
private static readonly byte?[] CurTimeXrefPattern = [ 0xDD, 0x05, null, null, null, null, 0x56, 0xDD ];
|
||||
// ClientUISystem::UseTime: mov ebp,[ICIDM::s_cidm]; push esi; push edi; lea eax,[esp+0x10]
|
||||
private static readonly byte?[] InputManagerXrefPattern = [ 0x8B, 0x2D, null, null, null, null, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
|
||||
// ClientUISystem::UseTime: fcomp qword ptr [InactiveTimeBeforeLogout]; fnstsw ax; test ah,0x41; jne; cmp
|
||||
private static readonly byte?[] IdleLimitXrefPattern = [ 0xDC, 0x1D, null, null, null, null, 0xDF, 0xE0, 0xF6, 0xC4, 0x41, 0x75, 0x22, 0x3B ];
|
||||
|
||||
private static IntPtr _origLogOffCharacter;
|
||||
private static IntPtr _origRequestLogOff;
|
||||
private static IntPtr _origProtoLogOff;
|
||||
private static IntPtr _origSetLogOffStarted;
|
||||
private static IntPtr _origLogOffServer;
|
||||
|
||||
private static IntPtr _curTimeVa;
|
||||
private static IntPtr _inputMgrSlotVa;
|
||||
private static IntPtr _idleLimitVa;
|
||||
private static int _lastInputOffset = -1;
|
||||
private static bool _inputOffsetProbed;
|
||||
|
||||
private static long _acBase;
|
||||
private static long _acImageSize;
|
||||
private static long _acTextLo;
|
||||
private static long _acTextHi;
|
||||
private static bool _labelsValid;
|
||||
private static bool _initialized;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_initialized)
|
||||
return;
|
||||
_initialized = true;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
RynthLog.Compat("LogoffProbe: acclient.exe not available - probe not installed.");
|
||||
return;
|
||||
}
|
||||
|
||||
_acBase = text.ModuleBase.ToInt64();
|
||||
_acImageSize = text.ImageSize;
|
||||
_acTextLo = text.TextBaseVa;
|
||||
_acTextHi = text.TextBaseVa + (long)text.Bytes.Length;
|
||||
_labelsValid = text.ImageSize == ReferenceImageSize;
|
||||
|
||||
_curTimeVa = HookResolver.ResolveData(text, "LogoffProbe.Timer_cur_time", CurTimeXrefPattern, 2, ProbeTimerCurTimeVa).Address;
|
||||
_inputMgrSlotVa = HookResolver.ResolveData(text, "LogoffProbe.ICIDM_s_cidm", InputManagerXrefPattern, 2, ProbeInputManagerVa).Address;
|
||||
_idleLimitVa = HookResolver.ResolveData(text, "LogoffProbe.InactiveTimeBeforeLogout", IdleLimitXrefPattern, 2, ProbeIdleLimitVa).Address;
|
||||
|
||||
try
|
||||
{
|
||||
double limit = _idleLimitVa != IntPtr.Zero ? *(double*)_idleLimitVa : double.NaN;
|
||||
RynthLog.Compat($"LogoffProbe: client idle auto-logoff threshold (InactiveTimeBeforeLogout @ 0x{_idleLimitVa.ToInt32():X8}) = {limit:0.#} s. ClientUISystem::UseTime calls LogOffCharacter(0) once Timer::cur_time - last input exceeds it.");
|
||||
}
|
||||
catch { }
|
||||
|
||||
int hooked = 0;
|
||||
HookResolver.ResolveResult r;
|
||||
|
||||
r = HookResolver.Resolve(text, "LogoffProbe.LogOffCharacter", LogOffCharacterPattern, ProbeLogOffCharacterVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, byte, void> dLogOffCharacter = &LogOffCharacterDetour;
|
||||
if (TryHook(r, "CPlayerSystem::LogOffCharacter", (IntPtr)dLogOffCharacter, out _origLogOffCharacter)) hooked++;
|
||||
|
||||
r = HookResolver.Resolve(text, "LogoffProbe.RequestLogOff", RequestLogOffPattern, ProbeRequestLogOffVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> dRequestLogOff = &RequestLogOffDetour;
|
||||
if (TryHook(r, "CPlayerSystem::RequestLogOff", (IntPtr)dRequestLogOff, out _origRequestLogOff)) hooked++;
|
||||
|
||||
r = HookResolver.Resolve(text, "LogoffProbe.Proto_UI_LogOffCharacter", ProtoLogOffPattern, ProbeProtoLogOffVa);
|
||||
delegate* unmanaged[Cdecl]<uint, int> dProtoLogOff = &ProtoLogOffDetour;
|
||||
if (TryHook(r, "Proto_UI::LogOffCharacter", (IntPtr)dProtoLogOff, out _origProtoLogOff)) hooked++;
|
||||
|
||||
r = HookResolver.Resolve(text, "LogoffProbe.SetLogOffStarted", SetLogOffStartedPattern, ProbeSetLogOffStartedVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> dSetLogOffStarted = &SetLogOffStartedDetour;
|
||||
if (TryHook(r, "CPlayerSystem::SetLogOffStarted", (IntPtr)dSetLogOffStarted, out _origSetLogOffStarted)) hooked++;
|
||||
|
||||
r = HookResolver.Resolve(text, "LogoffProbe.ClientNet_LogOffServer", LogOffServerPattern, ProbeLogOffServerVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> dLogOffServer = &LogOffServerDetour;
|
||||
if (TryHook(r, "ClientNet::LogOffServer", (IntPtr)dLogOffServer, out _origLogOffServer)) hooked++;
|
||||
|
||||
RynthLog.Compat($"LogoffProbe: {hooked}/5 logoff-origin hooks installed (labels {(_labelsValid ? "on" : "off - not the reference client")}).");
|
||||
}
|
||||
|
||||
private static bool TryHook(HookResolver.ResolveResult r, string name, IntPtr detour, out IntPtr original)
|
||||
{
|
||||
original = IntPtr.Zero;
|
||||
if (!r.Success)
|
||||
{
|
||||
RynthLog.Compat($"LogoffProbe: {name} unresolved - not hooked.");
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
MinHook.Hook(r.Address, detour, out original);
|
||||
RynthLog.Compat($"LogoffProbe: {name} hooked @ 0x{r.Address.ToInt32():X8} ({r.Detail}).");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
original = IntPtr.Zero;
|
||||
RynthLog.Compat($"LogoffProbe: {name} hook failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Detours (game thread; must never throw into AC) ──────────────────────
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static void LogOffCharacterDetour(IntPtr thisPtr, byte immediate)
|
||||
{
|
||||
try { OnRequest("CPlayerSystem::LogOffCharacter", $"immediate={immediate}"); }
|
||||
catch { }
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, byte, void>)_origLogOffCharacter)(thisPtr, immediate);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static void RequestLogOffDetour(IntPtr thisPtr)
|
||||
{
|
||||
try { OnRequest("CPlayerSystem::RequestLogOff", ""); }
|
||||
catch { }
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origRequestLogOff)(thisPtr);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int ProtoLogOffDetour(uint gid)
|
||||
{
|
||||
try
|
||||
{
|
||||
Volatile.Write(ref _lastProtoSendMs, Environment.TickCount64);
|
||||
OnRequest("Proto_UI::LogOffCharacter", $"gid=0x{gid:X8} (sends 0xF653 to the server)");
|
||||
}
|
||||
catch { }
|
||||
return ((delegate* unmanaged[Cdecl]<uint, int>)_origProtoLogOff)(gid);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static void SetLogOffStartedDetour(IntPtr thisPtr)
|
||||
{
|
||||
try
|
||||
{
|
||||
string since = _lastRequestMs != 0 ? $" {(Environment.TickCount64 - _lastRequestMs) / 1000.0:0.00}s after the request" : " (no request seen)";
|
||||
RynthLog.Info($"LogoffProbe: CPlayerSystem::SetLogOffStarted{since}.");
|
||||
LogoutLifecycleHooks.LogCaller("SetLogOffStarted", "LogoffProbe");
|
||||
}
|
||||
catch { }
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origSetLogOffStarted)(thisPtr);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||
private static void LogOffServerDetour(IntPtr thisPtr)
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthLog.Info("LogoffProbe: ClientNet::LogOffServer (transport disconnect) entered.");
|
||||
LogoutLifecycleHooks.LogCaller("ClientNet::LogOffServer", "LogoffProbe");
|
||||
}
|
||||
catch { }
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origLogOffServer)(thisPtr);
|
||||
}
|
||||
|
||||
// ── Request / completion tracking ────────────────────────────────────────
|
||||
|
||||
private static long _lastRequestMs;
|
||||
private static string? _lastRequestDesc;
|
||||
private static long _lastProtoSendMs;
|
||||
private static long _lastDumpMs;
|
||||
|
||||
private static void OnRequest(string fn, string args)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe");
|
||||
string callerText = DescribeAcclientAddress(caller);
|
||||
|
||||
string idleText = "idle=?";
|
||||
bool idleOver = false;
|
||||
if (TryReadIdle(out double idle, out double limit, out _, out _))
|
||||
{
|
||||
idleOver = idle > limit;
|
||||
idleText = $"idle={idle:0.0}s/{limit:0.#}s{(idleOver ? " (OVER threshold: matches the client idle auto-logoff)" : "")}";
|
||||
}
|
||||
|
||||
string argText = args.Length > 0 ? $"({args})" : "()";
|
||||
RynthLog.Warn($"LogoffProbe: logoff requested - {fn}{argText} caller={callerText} {idleText} {DescribeFocus()}");
|
||||
|
||||
// The first request of a cycle names the path; later ones (RequestLogOff, the send)
|
||||
// are the same logoff continuing, so keep the original description.
|
||||
if (_lastRequestMs == 0 || now - _lastRequestMs > 30_000)
|
||||
{
|
||||
_lastRequestMs = now;
|
||||
_lastRequestDesc = $"{fn}{argText} from {callerText}";
|
||||
}
|
||||
|
||||
if (now - _lastDumpMs > 30_000)
|
||||
{
|
||||
_lastDumpMs = now;
|
||||
DumpContext($"request via {fn}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once per logout cycle from the ExecuteLogOff / RecvNotice_Logoff detours.
|
||||
/// Says whether the client asked for this logoff, and if not, dumps the context.
|
||||
/// </summary>
|
||||
internal static void OnLogoffCompleted(string via)
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
long req = _lastRequestMs;
|
||||
if (req != 0 && now - req < 120_000)
|
||||
{
|
||||
long send = Volatile.Read(ref _lastProtoSendMs);
|
||||
string sendText = send != 0 && now - send < 120_000 ? $"{(now - send) / 1000.0:0.00}s after the 0xF653 send" : "no 0xF653 send seen";
|
||||
RynthLog.Info($"LogoffProbe: logoff completed via {via} {(now - req) / 1000.0:0.00}s after the client request ({sendText}). Request: {_lastRequestDesc}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Warn($"LogoffProbe: logoff completed via {via} with NO client logoff request in the last 120 s - server-initiated, or a path this probe does not hook.");
|
||||
if (now - _lastDumpMs > 30_000)
|
||||
{
|
||||
_lastDumpMs = now;
|
||||
DumpContext($"completion via {via} without a request");
|
||||
}
|
||||
}
|
||||
_lastRequestMs = 0;
|
||||
_lastRequestDesc = null;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ── Idle time (client's own idle-logoff clock) ───────────────────────────
|
||||
|
||||
private static long _lastIdleSampleMs;
|
||||
private static int _idleSecondsForHb = -1;
|
||||
private static double _prevIdle;
|
||||
private static int _idleMilestoneIdx;
|
||||
private static bool _idleOverLogged;
|
||||
private static bool _idleDisabledLogged;
|
||||
// Seconds before the threshold at which a milestone line is logged.
|
||||
private static readonly int[] IdleMilestonesBefore = [900, 600, 300, 120, 60, 30, 10];
|
||||
|
||||
/// <summary>Client input idle seconds for the heartbeat line, or -1 when unknown.</summary>
|
||||
internal static int IdleSecondsForHeartbeat => Volatile.Read(ref _idleSecondsForHb);
|
||||
|
||||
/// <summary>
|
||||
/// Called from the Client::UseTime detour (AC's game thread). Samples once a second.
|
||||
/// </summary>
|
||||
internal static void SampleIdleOnGameThread()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _lastIdleSampleMs < 1000)
|
||||
return;
|
||||
_lastIdleSampleMs = now;
|
||||
|
||||
try
|
||||
{
|
||||
if (!TryReadIdle(out double idle, out double limit, out _, out _))
|
||||
{
|
||||
Volatile.Write(ref _idleSecondsForHb, -1);
|
||||
return;
|
||||
}
|
||||
Volatile.Write(ref _idleSecondsForHb, idle < 0 ? 0 : (int)Math.Min(idle, int.MaxValue));
|
||||
|
||||
// Input arrived since the last sample: the client reset its idle clock.
|
||||
if (idle + 1.5 < _prevIdle)
|
||||
{
|
||||
if (_idleMilestoneIdx > 0 || _idleOverLogged)
|
||||
RynthLog.Info($"LogoffProbe: client input idle clock reset after {_prevIdle:0}s (input received). {DescribeFocus()}");
|
||||
_idleMilestoneIdx = 0;
|
||||
_idleOverLogged = false;
|
||||
}
|
||||
_prevIdle = idle;
|
||||
|
||||
// ClientUISystem::UseTime only logs off an in-world player; skip the
|
||||
// milestone lines at character select.
|
||||
bool inWorld = false;
|
||||
try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { }
|
||||
if (!inWorld)
|
||||
return;
|
||||
|
||||
if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60)
|
||||
{
|
||||
if (!_idleDisabledLogged)
|
||||
{
|
||||
_idleDisabledLogged = true;
|
||||
RynthLog.Info($"LogoffProbe: idle auto-logoff threshold is {limit} - milestones off.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// The client counts only real keyboard/mouse input, so a character a bot is
|
||||
// playing idles out after InactiveTimeBeforeLogout (1200 s) and logs itself off
|
||||
// mid-fight - Lucy, three times on 2026-09-27, each 1206 s after the window lost
|
||||
// focus. Keep the idle clock fresh while in the world (PreventIdleLogoff).
|
||||
if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput())
|
||||
{
|
||||
long nowMs = Environment.TickCount64;
|
||||
if (nowMs - _lastIdleRefreshLogMs > 600_000)
|
||||
{
|
||||
_lastIdleRefreshLogMs = nowMs;
|
||||
RynthLog.Info($"LogoffProbe: reset the client's idle clock at {idle:0}s idle so the {limit:0.#}s idle auto-logoff can't fire (PreventIdleLogoff; logged at most every 10 min). {DescribeFocus()}");
|
||||
}
|
||||
_prevIdle = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
while (_idleMilestoneIdx < IdleMilestonesBefore.Length && idle >= limit - IdleMilestonesBefore[_idleMilestoneIdx])
|
||||
{
|
||||
RynthLog.Info($"LogoffProbe: client input idle {idle:0}s - the client auto-logs-off at {limit:0.#}s ({limit - idle:0}s left). {DescribeFocus()}");
|
||||
_idleMilestoneIdx++;
|
||||
}
|
||||
|
||||
if (!_idleOverLogged && idle > limit)
|
||||
{
|
||||
_idleOverLogged = true;
|
||||
RynthLog.Warn($"LogoffProbe: client input idle {idle:0.0}s is over the {limit:0.#}s threshold - ClientUISystem::UseTime should call LogOffCharacter(0) now. {DescribeFocus()}");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private const double IdleRefreshAfterSec = 120;
|
||||
private static long _lastIdleRefreshLogMs = -600_000;
|
||||
|
||||
/// <summary>Sets the input manager's last-input time to Timer::cur_time, as real input
|
||||
/// would. Game thread only (called from SampleIdleOnGameThread).</summary>
|
||||
private static bool TryRefreshLastInput()
|
||||
{
|
||||
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
|
||||
return false;
|
||||
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
|
||||
if (mgr == IntPtr.Zero)
|
||||
return false;
|
||||
int off = ResolveLastInputOffset(mgr);
|
||||
if (off < 0)
|
||||
return false;
|
||||
*(double*)((byte*)mgr + off) = *(double*)_curTimeVa;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Reads the same values ClientUISystem::UseTime compares. Game thread only.</summary>
|
||||
private static bool TryReadIdle(out double idle, out double limit, out double curTime, out double lastInput)
|
||||
{
|
||||
idle = 0; limit = double.NaN; curTime = 0; lastInput = 0;
|
||||
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
|
||||
if (mgr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
int off = ResolveLastInputOffset(mgr);
|
||||
if (off < 0)
|
||||
return false;
|
||||
|
||||
curTime = *(double*)_curTimeVa;
|
||||
lastInput = *(double*)((byte*)mgr + off);
|
||||
if (_idleLimitVa != IntPtr.Zero)
|
||||
limit = *(double*)_idleLimitVa;
|
||||
idle = curTime - lastInput;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ClientUISystem::UseTime gets the last-input time from vtable slot 5 of the input
|
||||
/// manager, CInputManager::GetLastInputTimestamp, which is "fld qword [ecx+off]; ret".
|
||||
/// Read the field offset out of that body so the probe never guesses a layout.
|
||||
/// </summary>
|
||||
private static int ResolveLastInputOffset(IntPtr mgr)
|
||||
{
|
||||
if (_inputOffsetProbed)
|
||||
return _lastInputOffset;
|
||||
_inputOffsetProbed = true;
|
||||
|
||||
long vtbl = (*(IntPtr*)mgr).ToInt64();
|
||||
if (vtbl < _acBase || vtbl + 0x18 > _acBase + _acImageSize)
|
||||
{
|
||||
RynthLog.Compat($"LogoffProbe: input manager vtable 0x{vtbl:X8} is outside acclient - idle probe off.");
|
||||
return -1;
|
||||
}
|
||||
long fn = (*(IntPtr*)(vtbl + 0x14)).ToInt64();
|
||||
if (fn < _acTextLo || fn + 4 > _acTextHi)
|
||||
{
|
||||
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp 0x{fn:X8} is outside acclient .text - idle probe off.");
|
||||
return -1;
|
||||
}
|
||||
byte* p = (byte*)fn;
|
||||
if (p[0] == 0xDD && p[1] == 0x41 && p[3] == 0xC3)
|
||||
{
|
||||
_lastInputOffset = p[2];
|
||||
RynthLog.Compat($"LogoffProbe: CInputManager last-input time at +0x{_lastInputOffset:X2} (GetLastInputTimestamp @ 0x{fn:X8}).");
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp @ 0x{fn:X8} has unexpected bytes {p[0]:X2} {p[1]:X2} {p[2]:X2} {p[3]:X2} - idle probe off.");
|
||||
}
|
||||
return _lastInputOffset;
|
||||
}
|
||||
|
||||
// ── Ring buffers ─────────────────────────────────────────────────────────
|
||||
|
||||
private const uint WM_DESTROY = 0x0002;
|
||||
private const uint WM_ACTIVATE = 0x0006;
|
||||
private const uint WM_SETFOCUS = 0x0007;
|
||||
private const uint WM_KILLFOCUS = 0x0008;
|
||||
private const uint WM_CLOSE = 0x0010;
|
||||
private const uint WM_QUERYENDSESSION = 0x0011;
|
||||
private const uint WM_ENDSESSION = 0x0016;
|
||||
private const uint WM_ACTIVATEAPP = 0x001C;
|
||||
private const uint WM_KEYDOWN = 0x0100;
|
||||
private const uint WM_KEYUP = 0x0101;
|
||||
private const uint WM_SYSKEYDOWN = 0x0104;
|
||||
private const uint WM_SYSKEYUP = 0x0105;
|
||||
private const uint WM_SYSCOMMAND = 0x0112;
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_RBUTTONDOWN = 0x0204;
|
||||
private const uint WM_MBUTTONDOWN = 0x0207;
|
||||
private const uint WM_XBUTTONDOWN = 0x020B;
|
||||
|
||||
private struct MsgEntry
|
||||
{
|
||||
public long Ms;
|
||||
public uint Msg;
|
||||
public int WParam;
|
||||
public int LParam;
|
||||
public bool Synthetic;
|
||||
}
|
||||
|
||||
private struct ChatEntry
|
||||
{
|
||||
public long Ms;
|
||||
public string Source;
|
||||
public string Text;
|
||||
}
|
||||
|
||||
private const int MsgRingSize = 24;
|
||||
private const int ChatRingSize = 16;
|
||||
private static readonly MsgEntry[] _msgRing = new MsgEntry[MsgRingSize];
|
||||
private static readonly ChatEntry[] _chatRing = new ChatEntry[ChatRingSize];
|
||||
private static int _msgCount;
|
||||
private static int _chatCount;
|
||||
private static readonly object _ringLock = new();
|
||||
|
||||
private static long _lastMouseMoveMs;
|
||||
private static long _lastRealKeyMs;
|
||||
private static long _lastRealClickMs;
|
||||
private static long _lastKillFocusMs;
|
||||
private static long _lastSetFocusMs;
|
||||
|
||||
/// <summary>
|
||||
/// Records an input/focus/close message seen by the game WndProc subclass
|
||||
/// (<paramref name="synthetic"/> = false) or sent by the engine through
|
||||
/// Win32Backend.SendToGameWndProc (true). Cheap filter first; never throws.
|
||||
/// </summary>
|
||||
internal static void RecordWndMsg(uint msg, IntPtr wParam, IntPtr lParam, bool synthetic)
|
||||
{
|
||||
try
|
||||
{
|
||||
long now;
|
||||
switch (msg)
|
||||
{
|
||||
case WM_MOUSEMOVE:
|
||||
if (!synthetic) Volatile.Write(ref _lastMouseMoveMs, Environment.TickCount64);
|
||||
return;
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
// Skip auto-repeat (bit 30 = key was already down) so a held key can't flood the ring.
|
||||
if (((long)lParam & 0x40000000) != 0) return;
|
||||
now = Environment.TickCount64;
|
||||
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
|
||||
break;
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
now = Environment.TickCount64;
|
||||
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
|
||||
break;
|
||||
case WM_LBUTTONDOWN:
|
||||
case WM_RBUTTONDOWN:
|
||||
case WM_MBUTTONDOWN:
|
||||
case WM_XBUTTONDOWN:
|
||||
now = Environment.TickCount64;
|
||||
if (!synthetic) Volatile.Write(ref _lastRealClickMs, now);
|
||||
break;
|
||||
case WM_SETFOCUS:
|
||||
now = Environment.TickCount64;
|
||||
Volatile.Write(ref _lastSetFocusMs, now);
|
||||
break;
|
||||
case WM_KILLFOCUS:
|
||||
now = Environment.TickCount64;
|
||||
Volatile.Write(ref _lastKillFocusMs, now);
|
||||
break;
|
||||
case WM_DESTROY:
|
||||
case WM_ACTIVATE:
|
||||
case WM_CLOSE:
|
||||
case WM_QUERYENDSESSION:
|
||||
case WM_ENDSESSION:
|
||||
case WM_ACTIVATEAPP:
|
||||
case WM_SYSCOMMAND:
|
||||
now = Environment.TickCount64;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_ringLock)
|
||||
{
|
||||
ref MsgEntry e = ref _msgRing[_msgCount % MsgRingSize];
|
||||
e.Ms = now;
|
||||
e.Msg = msg;
|
||||
e.WParam = (int)(long)wParam;
|
||||
e.LParam = (int)(long)lParam;
|
||||
e.Synthetic = synthetic;
|
||||
_msgCount++;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>Records a chat line passing through one of the engine's chat paths.</summary>
|
||||
internal static void RecordChat(string source, string? text)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (text == null) return;
|
||||
string t = text.Length > 120 ? text.Substring(0, 120) + "..." : text;
|
||||
lock (_ringLock)
|
||||
{
|
||||
ref ChatEntry e = ref _chatRing[_chatCount % ChatRingSize];
|
||||
e.Ms = Environment.TickCount64;
|
||||
e.Source = source;
|
||||
e.Text = t;
|
||||
_chatCount++;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ── Context dump ─────────────────────────────────────────────────────────
|
||||
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetFocus();
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetActiveWindow();
|
||||
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
|
||||
[DllImport("kernel32.dll")] private static extern void GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
|
||||
|
||||
private static string Ago(long ms, long now)
|
||||
=> ms == 0 ? "never" : $"{(now - ms) / 1000.0:0.0}s ago";
|
||||
|
||||
private static string DescribeFocus()
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
|
||||
long now = Environment.TickCount64;
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
int fgGame = game != IntPtr.Zero && fg == game ? 1 : 0;
|
||||
int focusGame = game != IntPtr.Zero && GetFocus() == game ? 1 : 0;
|
||||
int iconic = game != IntPtr.Zero && IsIconic(game) ? 1 : 0;
|
||||
return $"fg={fgGame} focus={focusGame} min={iconic} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}";
|
||||
}
|
||||
catch { return "fg=?"; }
|
||||
}
|
||||
|
||||
private static void DumpContext(string trigger)
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
DateTime wallNow = DateTime.Now;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"LogoffProbe: ---- context dump ({trigger}) ----");
|
||||
|
||||
if (TryReadIdle(out double idle, out double limit, out double cur, out double last))
|
||||
sb.Append($"\n idle: Timer::cur_time={cur:0.000} lastInput={last:0.000} idle={idle:0.0}s threshold={limit:0.#}s");
|
||||
else
|
||||
sb.Append("\n idle: unavailable");
|
||||
|
||||
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
sb.Append($"\n window: game=0x{game.ToInt64():X} foreground=0x{fg.ToInt64():X} active=0x{GetActiveWindow().ToInt64():X} focus=0x{GetFocus().ToInt64():X} minimized={(game != IntPtr.Zero && IsIconic(game) ? 1 : 0)}");
|
||||
sb.Append($"\n engine-seen input: key={Ago(Volatile.Read(ref _lastRealKeyMs), now)} click={Ago(Volatile.Read(ref _lastRealClickMs), now)} mousemove={Ago(Volatile.Read(ref _lastMouseMoveMs), now)} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}");
|
||||
|
||||
sb.Append("\n acclient stack sweep (may include stale frames):");
|
||||
AppendStackSweep(sb);
|
||||
|
||||
MsgEntry[] msgs;
|
||||
ChatEntry[] chats;
|
||||
int msgCount, chatCount;
|
||||
lock (_ringLock)
|
||||
{
|
||||
msgs = (MsgEntry[])_msgRing.Clone();
|
||||
chats = (ChatEntry[])_chatRing.Clone();
|
||||
msgCount = _msgCount;
|
||||
chatCount = _chatCount;
|
||||
}
|
||||
|
||||
int mn = Math.Min(msgCount, MsgRingSize);
|
||||
sb.Append($"\n last {mn} window messages (of {msgCount}):");
|
||||
for (int i = msgCount - mn; i < msgCount; i++)
|
||||
{
|
||||
MsgEntry e = msgs[i % MsgRingSize];
|
||||
sb.Append($"\n {Clock(wallNow, now, e.Ms)} {(e.Synthetic ? "synth " : "")}{DescribeMsg(e)}");
|
||||
}
|
||||
|
||||
int cn = Math.Min(chatCount, ChatRingSize);
|
||||
sb.Append($"\n last {cn} engine chat lines (of {chatCount}):");
|
||||
for (int i = chatCount - cn; i < chatCount; i++)
|
||||
{
|
||||
ChatEntry e = chats[i % ChatRingSize];
|
||||
sb.Append($"\n {Clock(wallNow, now, e.Ms)} [{e.Source}] '{e.Text}'");
|
||||
}
|
||||
|
||||
sb.Append("\nLogoffProbe: ---- end context dump ----");
|
||||
RynthLog.Info(sb.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Info($"LogoffProbe: context dump failed: {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static string Clock(DateTime wallNow, long now, long ms)
|
||||
=> $"{wallNow.AddMilliseconds(-(now - ms)):HH:mm:ss.fff} ({(ms - now) / 1000.0:0.0}s)";
|
||||
|
||||
private static string DescribeMsg(MsgEntry e)
|
||||
{
|
||||
switch (e.Msg)
|
||||
{
|
||||
case WM_KEYDOWN: return $"WM_KEYDOWN vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
|
||||
case WM_KEYUP: return $"WM_KEYUP vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
|
||||
case WM_SYSKEYDOWN: return $"WM_SYSKEYDOWN vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
|
||||
case WM_SYSKEYUP: return $"WM_SYSKEYUP vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
|
||||
case WM_LBUTTONDOWN: return $"WM_LBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
|
||||
case WM_RBUTTONDOWN: return $"WM_RBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
|
||||
case WM_MBUTTONDOWN: return "WM_MBUTTONDOWN";
|
||||
case WM_XBUTTONDOWN: return "WM_XBUTTONDOWN";
|
||||
case WM_SETFOCUS: return $"WM_SETFOCUS from=0x{e.WParam:X}";
|
||||
case WM_KILLFOCUS: return $"WM_KILLFOCUS to=0x{e.WParam:X}";
|
||||
case WM_ACTIVATE: return $"WM_ACTIVATE state={e.WParam & 0xFFFF} other=0x{e.LParam:X}";
|
||||
case WM_ACTIVATEAPP: return $"WM_ACTIVATEAPP active={e.WParam} tid={e.LParam}";
|
||||
case WM_CLOSE: return "WM_CLOSE";
|
||||
case WM_DESTROY: return "WM_DESTROY";
|
||||
case WM_QUERYENDSESSION: return "WM_QUERYENDSESSION";
|
||||
case WM_ENDSESSION: return $"WM_ENDSESSION ending={e.WParam}";
|
||||
case WM_SYSCOMMAND: return $"WM_SYSCOMMAND cmd=0x{e.WParam & 0xFFF0:X4}{((e.WParam & 0xFFF0) == 0xF060 ? " (SC_CLOSE)" : "")}";
|
||||
default: return $"msg=0x{e.Msg:X4} w=0x{e.WParam:X} l=0x{e.LParam:X}";
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsExtended(int lParam) => ((lParam >> 24) & 1) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Scans this thread's stack above the current frame for values that are return
|
||||
/// addresses into acclient .text (preceded by a call instruction). AC is built with
|
||||
/// frame-pointer omission, so the EBP walk in LogCaller stops at the first AC frame;
|
||||
/// this recovers the AC callers above it. Stale values from earlier calls can appear.
|
||||
/// </summary>
|
||||
private static void AppendStackSweep(StringBuilder sb)
|
||||
{
|
||||
int local = 0;
|
||||
long start = (long)(nint)(&local);
|
||||
GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
|
||||
long high = highLimit.ToInt64();
|
||||
if (start < lowLimit.ToInt64() || start >= high)
|
||||
{
|
||||
sb.Append(" <stack limits unavailable>");
|
||||
return;
|
||||
}
|
||||
long end = Math.Min(high, start + 0x3000);
|
||||
int hits = 0;
|
||||
for (long a = (start + 3) & ~3L; a + 4 <= end && hits < 16; a += 4)
|
||||
{
|
||||
long v = *(uint*)a;
|
||||
if (v < _acTextLo + 8 || v >= _acTextHi)
|
||||
continue;
|
||||
if (!LooksLikeReturnAddress((byte*)v))
|
||||
continue;
|
||||
hits++;
|
||||
sb.Append($" {DescribeAcclientAddress((IntPtr)v)}");
|
||||
}
|
||||
if (hits == 0)
|
||||
sb.Append(" <none>");
|
||||
}
|
||||
|
||||
private static bool LooksLikeReturnAddress(byte* ret)
|
||||
{
|
||||
if (ret[-5] == 0xE8) return true; // call rel32
|
||||
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 3) return true; // call reg
|
||||
if (ret[-3] == 0xFF && ((ret[-2] >> 3) & 7) == 2 && (ret[-2] >> 6) == 1) return true; // call [reg+disp8]
|
||||
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 0) return true; // call [reg]
|
||||
if (ret[-6] == 0xFF && ((ret[-5] >> 3) & 7) == 2 && ((ret[-5] >> 6) == 2 || (ret[-5] & 0xC7) == 0x05)) return true; // call [reg+disp32] / [abs]
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string DescribeAcclientAddress(IntPtr addr)
|
||||
{
|
||||
if (addr == IntPtr.Zero)
|
||||
return "<no acclient frame>";
|
||||
int rva = (int)(addr.ToInt64() - _acBase);
|
||||
string label = LabelForAcclientRva(rva);
|
||||
return label.Length > 0 ? $"acclient.exe+0x{rva:X}{{{label}}}" : $"acclient.exe+0x{rva:X}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Names the known logoff-related call sites by return-address RVA. Reference client
|
||||
/// only (labels are off on any other build); the raw module+RVA is always logged.
|
||||
/// </summary>
|
||||
internal static string LabelForAcclientRva(int rva)
|
||||
{
|
||||
if (!_labelsValid)
|
||||
return "";
|
||||
return rva switch
|
||||
{
|
||||
// callers of CPlayerSystem::LogOffCharacter
|
||||
0x166056 => "ClientUISystem::UseTime: idle auto-logoff",
|
||||
0x0EB0E9 => "gmGamePlayUI::UseTime: logout confirmed in the UI",
|
||||
0x0EAEC8 => "gmGamePlayUI::EndSession",
|
||||
0x0EA80F => "gmEpilogueUI ctor",
|
||||
0x15AD39 => "APIManager::EndCharacterSession: plugin API",
|
||||
// callers of CPlayerSystem::RequestLogOff
|
||||
0x1642EE => "CPlayerSystem::LogOffCharacter",
|
||||
0x163FC6 => "CPlayerSystem::UseTime: deferred request",
|
||||
// caller of Proto_UI::LogOffCharacter
|
||||
0x163BC4 => "CPlayerSystem::RequestLogOff",
|
||||
// callers of CPlayerSystem::ExecuteLogOff
|
||||
0x15D676 => "server CharacterLogOff 0xF653 handler",
|
||||
0x1642DC => "CPlayerSystem::LogOffCharacter(immediate)",
|
||||
// caller of CPlayerSystem::SetLogOffStarted
|
||||
0x0D7AF8 => "gmSmartBoxUI::UseTime",
|
||||
// callers of ClientNet::LogOffServer
|
||||
0x01160C => "Client::Disconnect",
|
||||
0x012077 => "Client::CleanupNet",
|
||||
0x145E79 => "ClientNet::ProcessOptionalHeader: server disconnect",
|
||||
0x145FEC => "ClientNet::RemoveConnection",
|
||||
_ => "",
|
||||
};
|
||||
}
|
||||
}
|
||||
222
src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs
Normal file
222
src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks the moments when the AC client commits to ending the in-world session.
|
||||
///
|
||||
/// - <c>CPlayerSystem::ExecuteLogOff(void)</c> — fires when the player has confirmed
|
||||
/// the logoff prompt and the actual logoff begins.
|
||||
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff notice.
|
||||
///
|
||||
/// Either one raises <see cref="LogoutComplete"/> once per logout cycle.
|
||||
///
|
||||
/// Both addresses are now resolved via HookResolver — pattern-scan first,
|
||||
/// fallback VA second, UNAVAILABLE if neither works.
|
||||
/// </summary>
|
||||
internal static class LogoutLifecycleHooks
|
||||
{
|
||||
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
|
||||
private const int ExecuteLogOffFallbackVa = 0x0055E4A0;
|
||||
private const int RecvNoticeLogoffFallbackVa = 0x004ECBA0;
|
||||
|
||||
// CPlayerSystem::ExecuteLogOff(void)
|
||||
// Two consecutive 'mov byte ptr [esi+0x213],bl' / 'mov byte ptr [esi+0x221],bl'
|
||||
// — those CPlayerSystem flags clears are unique anchor.
|
||||
private static readonly byte?[] ExecuteLogOffPattern =
|
||||
[
|
||||
0x53, 0x56, 0x8B, 0xF1, 0x33, 0xDB, 0x88, 0x9E,
|
||||
0x13, 0x02, 0x00, 0x00, 0x88, 0x9E, 0x21, 0x02,
|
||||
0x00, 0x00,
|
||||
0x8B, 0x0D, null, null, null, null, // mov ecx, ds:[imm32]
|
||||
0xA1, null, null, null, null, // mov eax, ds:[imm32]
|
||||
0x89, 0x86, 0x00, 0x02, 0x00, 0x00
|
||||
];
|
||||
|
||||
// gmGamePlayUI::RecvNotice_Logoff(void)
|
||||
// 0x90 stack frame, sets two booleans at +0x2D / +0x2E, then E8 to a helper.
|
||||
private static readonly byte?[] RecvNoticeLogoffPattern =
|
||||
[
|
||||
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B,
|
||||
0xF1, 0xB0, 0x01, 0x8D, 0x4C, 0x24, 0x04, 0x88,
|
||||
0x46, 0x2D, 0x88, 0x46, 0x2E,
|
||||
0xE8, null, null, null, null, // call rel32
|
||||
0xA1, null, null, null, null, // mov eax, ds:[imm32]
|
||||
0x68, 0x01, 0x00, 0x00, 0x10
|
||||
];
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
|
||||
|
||||
private static ThisCallVoidDelegate? _originalExecuteLogOff;
|
||||
private static ThisCallVoidDelegate? _executeLogOffDetour;
|
||||
private static IntPtr _executeLogOffAddress;
|
||||
|
||||
private static ThisCallVoidDelegate? _originalRecvNoticeLogoff;
|
||||
private static ThisCallVoidDelegate? _recvNoticeLogoffDetour;
|
||||
private static IntPtr _logoffAddress;
|
||||
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static bool HasObservedLogout { get; private set; }
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static event Action? LogoutComplete;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
|
||||
{
|
||||
_statusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
bool anyHooked = false;
|
||||
anyHooked |= TryInstall(textSection, "LogoutLifecycle.ExecuteLogOff",
|
||||
ExecuteLogOffPattern, ExecuteLogOffFallbackVa, ExecuteLogOffDetour,
|
||||
out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff);
|
||||
anyHooked |= TryInstall(textSection, "LogoutLifecycle.RecvNotice_Logoff",
|
||||
RecvNoticeLogoffPattern, RecvNoticeLogoffFallbackVa, RecvNoticeLogoffDetour,
|
||||
out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff);
|
||||
|
||||
if (anyHooked)
|
||||
{
|
||||
IsInstalled = true;
|
||||
RynthLog.Compat($"LogoutLifecycleHooks: ready (ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8}, RecvNotice_Logoff=0x{_logoffAddress.ToInt32():X8}).");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryInstall(
|
||||
AcClientTextSection textSection, string name,
|
||||
byte?[] pattern, int fallbackVa, ThisCallVoidDelegate detour,
|
||||
out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original)
|
||||
{
|
||||
address = IntPtr.Zero;
|
||||
detourField = detour;
|
||||
original = null;
|
||||
|
||||
var resolved = HookResolver.Resolve(textSection, name, pattern, fallbackVa);
|
||||
if (!resolved.Success)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
address = resolved.Address;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField);
|
||||
original = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
|
||||
MinHook.HookCreate(address, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(address);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_statusMessage = ex.Message;
|
||||
RynthLog.Compat($"LogoutLifecycleHooks: {name} install threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void ResetObservation()
|
||||
{
|
||||
HasObservedLogout = false;
|
||||
}
|
||||
|
||||
private static void ExecuteLogOffDetour(IntPtr thisPtr)
|
||||
{
|
||||
RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff");
|
||||
if (!HasObservedLogout)
|
||||
{
|
||||
RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered.");
|
||||
LogCaller("ExecuteLogOff");
|
||||
LogoffOriginProbe.OnLogoffCompleted("CPlayerSystem::ExecuteLogOff");
|
||||
}
|
||||
|
||||
try { _originalExecuteLogOff!(thisPtr); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
||||
|
||||
RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff");
|
||||
}
|
||||
|
||||
private static void RecvNoticeLogoffDetour(IntPtr thisPtr)
|
||||
{
|
||||
RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff");
|
||||
if (!HasObservedLogout)
|
||||
{
|
||||
RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered.");
|
||||
LogCaller("RecvNotice_Logoff");
|
||||
LogoffOriginProbe.OnLogoffCompleted("gmGamePlayUI::RecvNotice_Logoff");
|
||||
}
|
||||
|
||||
try { _originalRecvNoticeLogoff!(thisPtr); }
|
||||
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
||||
|
||||
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern ushort RtlCaptureStackBackTrace(
|
||||
uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash);
|
||||
|
||||
/// <summary>
|
||||
/// Logs who in the client called the logoff, as module+RVA frames. Characters were
|
||||
/// logging off by themselves (2026-09-27, Lucy, twice mid-route) with no meta, no
|
||||
/// command and nothing from the server, so the next one needs to say which client
|
||||
/// code path confirmed it (UI button, chat /logout, something else). x86 EBP walk:
|
||||
/// deep frames can be unreliable, the first acclient frames are the useful ones.
|
||||
/// Known logoff call sites get a {label} (LogoffOriginProbe). Returns the first
|
||||
/// acclient.exe frame (the immediate AC caller), or Zero if none was captured.
|
||||
/// </summary>
|
||||
internal static IntPtr LogCaller(string hook, string prefix = "LogoutLifecycleHooks")
|
||||
{
|
||||
IntPtr firstAcclient = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
var frames = new IntPtr[24];
|
||||
ushort captured = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _);
|
||||
var sb = new System.Text.StringBuilder($"{prefix}: {hook} caller frames:");
|
||||
for (int i = 0; i < captured && frames[i] != IntPtr.Zero; i++)
|
||||
{
|
||||
string module = ProcessExitHooks.ResolveModule(frames[i], out int rva);
|
||||
sb.Append($" [{i}] {module}+0x{rva:X}");
|
||||
if (string.Equals(module, "acclient.exe", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (firstAcclient == IntPtr.Zero)
|
||||
firstAcclient = frames[i];
|
||||
string label = LogoffOriginProbe.LabelForAcclientRva(rva);
|
||||
if (label.Length > 0)
|
||||
sb.Append($"{{{label}}}");
|
||||
}
|
||||
}
|
||||
RynthLog.Compat(sb.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"{prefix}: {hook} caller capture failed: {ex.GetType().Name}"); } catch { }
|
||||
}
|
||||
return firstAcclient;
|
||||
}
|
||||
|
||||
private static void RaiseLogoutCompleteOnce(string source)
|
||||
{
|
||||
if (HasObservedLogout)
|
||||
return;
|
||||
|
||||
HasObservedLogout = true;
|
||||
_statusMessage = $"Logout observed via {source}.";
|
||||
RynthLog.Compat($"LogoutLifecycleHooks: logout observed via {source} — raising LogoutComplete.");
|
||||
|
||||
try { LogoutComplete?.Invoke(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"LogoutLifecycleHooks: handler threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
62
src/RynthCore.Engine/Compatibility/MainThreadGuard.cs
Normal file
62
src/RynthCore.Engine/Compatibility/MainThreadGuard.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks which OS thread is AC's main thread, so RynthCore code that's about
|
||||
/// to call into AC's internals (CACQualities accessors, etc.) can refuse the
|
||||
/// call from any other thread.
|
||||
///
|
||||
/// AC's client is not thread-safe: its internal data structures (qualities
|
||||
/// hash tables, enchantment lists, object tables) are mutated by the main
|
||||
/// thread without locking. Reading them from another thread can observe a
|
||||
/// sub-pointer in the middle of being reassigned, which appears as null and
|
||||
/// AVs three frames deep inside AC (consistent crash at 0x00416C86 reading
|
||||
/// [null+0x28] from the DecalCoexistence plugin-tick thread, 2026-05-14).
|
||||
///
|
||||
/// Capture: any of our [UnmanagedCallersOnly] detours runs on the thread that
|
||||
/// called the detoured function. AC's main thread is what invokes
|
||||
/// SetCombatMode, BusyCount updates, SmartBox/GameEvent dispatch, etc. The
|
||||
/// first detour to fire after install latches that thread ID; everything
|
||||
/// after compares against it.
|
||||
/// </summary>
|
||||
internal static class MainThreadGuard
|
||||
{
|
||||
private static uint _acMainNativeTid;
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentThreadId();
|
||||
|
||||
/// <summary>
|
||||
/// Latch the current native thread ID as AC's main thread. Idempotent;
|
||||
/// only the first caller wins. Safe to call from any [UnmanagedCallersOnly]
|
||||
/// detour body — those run on whichever thread invoked the detoured AC
|
||||
/// function, which is AC's main thread for the detours we install.
|
||||
/// </summary>
|
||||
public static void RecordIfFirst()
|
||||
{
|
||||
if (_acMainNativeTid != 0) return;
|
||||
uint tid = GetCurrentThreadId();
|
||||
Interlocked.CompareExchange(ref _acMainNativeTid, tid, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True if AC's main thread has been observed AND the calling thread is
|
||||
/// that thread. Returns false before the main thread is known, so any
|
||||
/// cross-thread caller fails closed (refuses to enter AC) during early
|
||||
/// init too.
|
||||
/// </summary>
|
||||
public static bool IsOnMainThread()
|
||||
{
|
||||
uint mainTid = _acMainNativeTid;
|
||||
if (mainTid == 0) return false;
|
||||
return GetCurrentThreadId() == mainTid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Diagnostic accessor — for logging the captured thread ID at startup
|
||||
/// or in crash reports. Zero if not yet captured.
|
||||
/// </summary>
|
||||
public static uint MainThreadId => _acMainNativeTid;
|
||||
}
|
||||
|
|
@ -139,38 +139,77 @@ internal static class MovementActionHooks
|
|||
}
|
||||
}
|
||||
|
||||
// Light counters so we can see in the log that the bot's movement
|
||||
// commands are actually reaching AC and what AC says about each call.
|
||||
// Logged at Compat every 8th call after the first 3, so a busy patrol
|
||||
// loop doesn't flood the log but a one-shot test still shows up.
|
||||
private static int _doMovementCalls;
|
||||
private static int _stopMovementCalls;
|
||||
private static int _jumpCalls;
|
||||
private static int _autonomyCalls;
|
||||
private static bool ShouldLog(int n) => n <= 3 || (n & 0x7) == 0;
|
||||
|
||||
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
|
||||
|
||||
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
|
||||
if (_doMovement == null)
|
||||
{
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} — delegate null (probe failed).");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return _doMovement(motion, speed, holdKey);
|
||||
bool ok = _doMovement(motion, speed, holdKey);
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} -> {ok}");
|
||||
return ok;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
|
||||
|
||||
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
|
||||
if (_stopMovement == null)
|
||||
{
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} — delegate null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return _stopMovement(motion, holdKey);
|
||||
bool ok = _stopMovement(motion, holdKey);
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} -> {ok}");
|
||||
return ok;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ShouldLog(n))
|
||||
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool JumpNonAutonomous(float extent)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueJump(extent);
|
||||
|
||||
if (_jumpNonAutonomous == null)
|
||||
return false;
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,15 @@ namespace RynthCore.Engine.Compatibility;
|
|||
internal static class MultiClientHooks
|
||||
{
|
||||
private const int ExpectedImageSize = 0x56D000;
|
||||
private const int IsAlreadyRunningVa = 0x004122A0;
|
||||
private const int OpenDataFileVa = 0x00675920;
|
||||
private const uint OpenDataFileSharedAccessFlag = 0x4;
|
||||
private const int IsAlreadyRunningFallbackVa = 0x004122A0;
|
||||
private const int OpenDataFileFallbackVa = 0x00675920;
|
||||
// OpenDataFile's prologue tests bit 1 (value 0x2) of openFlags:
|
||||
// and cl, 2
|
||||
// cmp cl, 2
|
||||
// That's the bit AC's code dispatches on for "shared access" — the prior
|
||||
// value 0x4 was a misread of the byte sequence. Decal's coexisting clients
|
||||
// open with bit 1 set; matching that lets us share with their handles.
|
||||
private const uint OpenDataFileSharedAccessFlag = 0x2;
|
||||
|
||||
private static readonly byte?[] IsAlreadyRunningSignature =
|
||||
[
|
||||
|
|
@ -79,25 +85,6 @@ internal static class MultiClientHooks
|
|||
if (textSection.ImageSize != ExpectedImageSize)
|
||||
RynthLog.Verbose($"Compat: multi-client hook using unverified acclient image size 0x{textSection.ImageSize:X} (expected 0x{ExpectedImageSize:X}).");
|
||||
|
||||
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
_statusMessage = $"Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
|
||||
{
|
||||
byte? expected = IsAlreadyRunningSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
_statusMessage = $"Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.";
|
||||
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
TryInstallIsAlreadyRunningHook(textSection);
|
||||
TryInstallOpenDataFileHook(textSection);
|
||||
|
||||
|
|
@ -109,7 +96,7 @@ internal static class MultiClientHooks
|
|||
}
|
||||
|
||||
if (IsInstalled)
|
||||
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{IsAlreadyRunningVa:X8} and CLBlockAllocator::OpenDataFile @ 0x{OpenDataFileVa:X8}.";
|
||||
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{_targetAddress.ToInt32():X8} and CLBlockAllocator::OpenDataFile @ 0x{_openDataFileAddress.ToInt32():X8} (share flag 0x2).";
|
||||
else
|
||||
_statusMessage = $"Partial install. alreadyRunning={IsAlreadyRunningInstalled}, dataFile={OpenDataFileInstalled}.";
|
||||
}
|
||||
|
|
@ -122,66 +109,60 @@ internal static class MultiClientHooks
|
|||
|
||||
private static void TryInstallIsAlreadyRunningHook(AcClientTextSection textSection)
|
||||
{
|
||||
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.");
|
||||
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.Client::IsAlreadyRunning",
|
||||
IsAlreadyRunningSignature, IsAlreadyRunningFallbackVa);
|
||||
if (!resolved.Success)
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
|
||||
try
|
||||
{
|
||||
byte? expected = IsAlreadyRunningSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.");
|
||||
return;
|
||||
}
|
||||
_targetAddress = resolved.Address;
|
||||
_detour = IsAlreadyRunningDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
|
||||
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
IsAlreadyRunningInstalled = true;
|
||||
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning hook ready @ 0x{_targetAddress.ToInt32():X8}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
|
||||
_targetAddress = new IntPtr(IsAlreadyRunningVa);
|
||||
_detour = IsAlreadyRunningDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
|
||||
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
|
||||
IsAlreadyRunningInstalled = true;
|
||||
RynthLog.Verbose($"Compat: multi-client hook ready - IsAlreadyRunning=0x{IsAlreadyRunningVa:X8}");
|
||||
}
|
||||
|
||||
private static void TryInstallOpenDataFileHook(AcClientTextSection textSection)
|
||||
{
|
||||
int funcOff = OpenDataFileVa - textSection.TextBaseVa;
|
||||
if (funcOff < 0 || funcOff + OpenDataFileSignature.Length > textSection.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile VA 0x{OpenDataFileVa:X8} is outside the readable text window.");
|
||||
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.CLBlockAllocator::OpenDataFile",
|
||||
OpenDataFileSignature, OpenDataFileFallbackVa);
|
||||
if (!resolved.Success)
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < OpenDataFileSignature.Length; i++)
|
||||
try
|
||||
{
|
||||
byte? expected = OpenDataFileSignature[i];
|
||||
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
|
||||
{
|
||||
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile signature mismatch at 0x{OpenDataFileVa + i:X8}.");
|
||||
return;
|
||||
}
|
||||
_openDataFileAddress = resolved.Address;
|
||||
_openDataFileDetour = OpenDataFileDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
|
||||
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(
|
||||
MinHook.HookCreate(_openDataFileAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_openDataFileAddress);
|
||||
OpenDataFileInstalled = true;
|
||||
RynthLog.Compat($"MultiClientHooks: OpenDataFile hook ready @ 0x{_openDataFileAddress.ToInt32():X8}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"MultiClientHooks: OpenDataFile install threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
|
||||
_openDataFileAddress = new IntPtr(OpenDataFileVa);
|
||||
_openDataFileDetour = OpenDataFileDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
|
||||
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(MinHook.HookCreate(_openDataFileAddress, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_openDataFileAddress);
|
||||
|
||||
OpenDataFileInstalled = true;
|
||||
RynthLog.Verbose($"Compat: multi-client data-file hook ready - CLBlockAllocator::OpenDataFile=0x{OpenDataFileVa:X8}");
|
||||
}
|
||||
|
||||
private static byte IsAlreadyRunningDetour(IntPtr thisPtr)
|
||||
{
|
||||
// Skip the original entirely: it has a side-effect MessageBox path
|
||||
// that surfaces the "client is already running on this machine" dialog
|
||||
// even when we'd later override its return value, so calling it makes
|
||||
// things worse. Returning 0 unconditionally was the original design.
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,35 +16,35 @@ internal readonly record struct CreatureVitals(
|
|||
/// </summary>
|
||||
internal static class ObjectQualityCache
|
||||
{
|
||||
private static readonly Dictionary<IntPtr, uint> _maxHealthByPtr = new();
|
||||
// NOTE: a former _maxHealthByPtr (keyed by reusable CWeenieObject heap
|
||||
// pointers, populated per stat-update from an UnmanagedCallersOnly detour)
|
||||
// was removed 2026-06-11: it was write-only — zero readers — pure
|
||||
// allocation churn in a detour plus an unbounded pointer-keyed dictionary.
|
||||
private static readonly Dictionary<uint, CreatureVitals> _vitalsByObjectId = new();
|
||||
private static readonly object _lock = new();
|
||||
|
||||
public static void SetMaxHealth(IntPtr objectPtr, uint maxHealth)
|
||||
{
|
||||
if (objectPtr == IntPtr.Zero)
|
||||
return;
|
||||
lock (_lock)
|
||||
_maxHealthByPtr[objectPtr] = maxHealth;
|
||||
}
|
||||
|
||||
public static bool TryGetMaxHealth(IntPtr objectPtr, out uint maxHealth)
|
||||
{
|
||||
if (objectPtr == IntPtr.Zero)
|
||||
{
|
||||
maxHealth = 0;
|
||||
return false;
|
||||
}
|
||||
lock (_lock)
|
||||
return _maxHealthByPtr.TryGetValue(objectPtr, out maxHealth);
|
||||
}
|
||||
// Bound the cache: ids accumulate for the whole session otherwise. The
|
||||
// cache is advisory (resolvers fall back to ratio-only); a rare wholesale
|
||||
// clear is cheaper and safer than LRU bookkeeping inside detour paths.
|
||||
private const int MaxEntries = 4096;
|
||||
|
||||
public static void SetCreatureVitals(uint objectId, CreatureVitals vitals)
|
||||
{
|
||||
if (objectId == 0)
|
||||
return;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_vitalsByObjectId.Count >= MaxEntries && !_vitalsByObjectId.ContainsKey(objectId))
|
||||
_vitalsByObjectId.Clear();
|
||||
_vitalsByObjectId[objectId] = vitals;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drop all cached vitals at logout — object ids don't survive the session.</summary>
|
||||
public static void ClearSession()
|
||||
{
|
||||
lock (_lock)
|
||||
_vitalsByObjectId.Clear();
|
||||
}
|
||||
|
||||
public static bool TryGetCreatureVitals(uint objectId, out CreatureVitals vitals)
|
||||
|
|
|
|||
154
src/RynthCore.Engine/Compatibility/OnLoginCommandRunner.cs
Normal file
154
src/RynthCore.Engine/Compatibility/OnLoginCommandRunner.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Reads per-character OnLogin chat commands from the launcher's
|
||||
/// LaunchContextRecord (written per-PID under
|
||||
/// %APPDATA%\RynthCore\launch_contexts\) and dispatches them via
|
||||
/// <see cref="ChatCommandDispatcher"/> after AC's
|
||||
/// <c>SendLoginCompleteNotification</c> fires.
|
||||
///
|
||||
/// Timing model mirrors Thwargle's:
|
||||
/// 1. Wait for the engine's LoginComplete signal.
|
||||
/// 2. Sleep <c>OnLoginWaitMs</c> (default 3000 ms — the Thwargle default).
|
||||
/// 3. Dispatch each command in order with a small inter-command gap so AC's
|
||||
/// chat parser has time to finish processing before the next arrives.
|
||||
///
|
||||
/// Single-shot per process: subscribes once, fires once. Logout/relogin within
|
||||
/// the same client process is not handled here yet (would require
|
||||
/// re-subscribing after LoginLifecycleHooks.ResetObservation).
|
||||
/// </summary>
|
||||
internal static class OnLoginCommandRunner
|
||||
{
|
||||
/// <summary>Inter-command delay. AC's chat parser is synchronous on the
|
||||
/// main thread but the underlying network handlers benefit from breathing
|
||||
/// room; 250 ms keeps things human-paced and avoids any chance of the
|
||||
/// parser dropping a command queued behind a still-processing one.</summary>
|
||||
private const int InterCommandGapMs = 250;
|
||||
|
||||
/// <summary>Fallback wait if the launcher provides 0 / unset value.</summary>
|
||||
private const int DefaultWaitMs = 3000;
|
||||
|
||||
private static int _scheduled;
|
||||
private static string _statusMessage = "Not initialized.";
|
||||
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
// One-shot subscription. If LoginLifecycleHooks.ResetObservation gets
|
||||
// called (logout pipeline), the next LoginComplete will still fire
|
||||
// through this handler and we'll re-arm via Interlocked.Exchange.
|
||||
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
|
||||
_statusMessage = "OnLogin command runner armed.";
|
||||
RynthLog.Verbose($"Compat: {_statusMessage}");
|
||||
}
|
||||
|
||||
private static void OnLoginComplete()
|
||||
{
|
||||
// Guard: only schedule once per LoginComplete edge. If we ever support
|
||||
// mid-session relogin, ResetForRelogin should clear this flag.
|
||||
if (Interlocked.Exchange(ref _scheduled, 1) != 0)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
(List<string> commands, int waitMs) = ReadLaunchCommands();
|
||||
if (commands.Count == 0)
|
||||
{
|
||||
RynthLog.Verbose("OnLogin: no commands queued for this PID — skipping dispatch.");
|
||||
return;
|
||||
}
|
||||
|
||||
int effectiveWait = waitMs > 0 ? waitMs : DefaultWaitMs;
|
||||
RynthLog.Info($"OnLogin: {commands.Count} command(s) scheduled, first dispatch in {effectiveWait}ms.");
|
||||
|
||||
// Fire-and-forget background task. ChatCommandDispatcher.Dispatch
|
||||
// is safe to call from this ThreadPool thread — NOT because AC's
|
||||
// chat layer tolerates off-thread calls (it doesn't; that was the
|
||||
// deep-audit finding #4 bug this comment used to claim), but
|
||||
// because Dispatch() now self-marshals: an off-thread call
|
||||
// enqueues onto AcMainThreadQueue and the real native dispatch
|
||||
// runs on AC's main thread from the EndScene drain.
|
||||
_ = Task.Run(async () => await DispatchAsync(commands, effectiveWait));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"OnLogin: scheduling failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DispatchAsync(List<string> commands, int waitMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(waitMs);
|
||||
|
||||
for (int i = 0; i < commands.Count; i++)
|
||||
{
|
||||
string line = commands[i];
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
continue;
|
||||
|
||||
// Plugin-first dispatch lives inside ChatCommandDispatcher
|
||||
// itself — see its plugin pre-dispatch step. So we just call
|
||||
// the unified entry point here.
|
||||
bool ok = ChatCommandDispatcher.Dispatch(line);
|
||||
RynthLog.Info($"OnLogin: [{i + 1}/{commands.Count}] '{line}' dispatched={ok}.");
|
||||
|
||||
if (i + 1 < commands.Count)
|
||||
await Task.Delay(InterCommandGapMs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"OnLogin: dispatch loop failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static (List<string> commands, int waitMs) ReadLaunchCommands()
|
||||
{
|
||||
string path = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"launch_contexts",
|
||||
$"launch_context_{Environment.ProcessId}.json");
|
||||
|
||||
if (!File.Exists(path))
|
||||
return (new List<string>(), 0);
|
||||
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
JsonElement root = doc.RootElement;
|
||||
|
||||
int waitMs = 0;
|
||||
if (root.TryGetProperty("OnLoginWaitMs", out JsonElement wEl) && wEl.ValueKind == JsonValueKind.Number)
|
||||
waitMs = wEl.GetInt32();
|
||||
|
||||
var commands = new List<string>();
|
||||
if (root.TryGetProperty("OnLoginCommands", out JsonElement cmdEl) && cmdEl.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement entry in cmdEl.EnumerateArray())
|
||||
{
|
||||
string? line = entry.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(line))
|
||||
commands.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
return (commands, waitMs);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"OnLogin: launch context parse failed - {ex.Message}");
|
||||
return (new List<string>(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue