Snapshot for release 2026.10.13.1 (internal 90a2f4a)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:48 -04:00
commit 1d86acdf27
218 changed files with 24019 additions and 1517 deletions

View file

@ -0,0 +1,45 @@
# Char and Mini Remote menus: Character on top, server plugin windows below
## What changed
- **New server-section registry** (`UI/ServerMenus.cs`).
- Each server is defined once, with how to detect it and the command that forces it.
- Each installed plugin with windows for that server adds its items.
- A section shows only while its server is detected or forced, and only when it has at least
one item. So it appears exactly when you're on that server with one of its plugins
installed.
- Infinite Leaftide is registered in `EntryPoint.RegisterServerMenus`:
- detection: `IltInfo.IsIlt`;
- force: `/rc ilt on`;
- with RynthAi installed: the Mini Remote's Character, Quests, Pets, Banking, Gear and Games
tabs, Guardian, and Progression;
- with RynthILT installed: Bounties.
- Items are `/rc` commands, so the engine and RynthAi run the same thing.
- The engine pushes the sections to RynthAi as the `"servermenu"` remote command. It sends them
whenever they change (checked once a second from the bar's draw) and again every 30 s.
- **RynthAi dashboard, Char right-click menu:**
- Top, **Character**: Mini Remote, Spells, Skills, Inventory and Item Count.
- Bottom: the active server sections (`ServerMenus.DrawImGuiMenu`).
- When server plugins are installed but none matches the world, the bottom half shows a note
and "Treat this world as <server>".
- The menu's fixed list of ILT tabs, Guardian and Progression is replaced by the registry.
- **New and extended `/rc` commands:**
- `/rc spells [show|hide|toggle]`: RynthAi's Spells window.
- `/rc skills [show|hide|toggle]`: the Skills panel.
- `/rc progression`: the Skills panel on its Progression tab.
- `/rc miniremote tab <tab>`: opens the Mini Remote window on one of RynthAi's tabs.
## Files
- `src/RynthCore.Engine/UI/ServerMenus.cs`: new.
- `src/RynthCore.Engine/EntryPoint.cs`: `RegisterServerMenus`.
- `src/RynthCore.Engine/ImGui/ImGuiBar.cs`: calls `ServerMenus.Tick()` each frame.
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`: the Char menu (`CharMenu`,
`PanelMenuItem`) and the launcher tooltip.
- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs`: `/rc spells`, `/rc skills`,
`/rc progression` and `/rc miniremote tab`.
## Testing
- The engine builds in Release, and ItemHudTests pass.
- In-game checks are listed in the matching RynthSuite changelog.

View file

@ -0,0 +1,46 @@
# Game-tick crash guard (chatclient.dll null read)
RynthCore.SehTrampoline.dll native version 4 (previous: 3).
## The crash
On 2026-10-11 two idle clients died in the same second. Both CoreCLR dumps show the same fault on
AC's main thread:
- AC's `Client::UseTime` called into `chatclient.dll` (Turbine's chat client in the AC folder).
Three calls in, a `rep movsd` copy of about 2 MB read from address 0
(`chatclient.dll+0x1050`, read of 0x00000000).
- Both clients at once, both idle: most likely a bad or oversized message from the chat server.
- The fault unwound into the engine's managed `UseTime` detour. CoreCLR treats a native access
violation there as an unhandled exception and ends the process, so AC's own handlers never ran.
Windows reported the follow-on fault in `coreclr.dll+0x2c27ae`, which is the runtime's fail-fast
path, not the cause.
- `native-crash.log` had no record: a null read is held back until the process exits normally,
and the fail-fast skipped that.
## The fix
- `native/SehTrampoline/SehTrampoline.c`: new export `SEH_GameTickThiscall` calls
`int __thiscall fn(this)` under `__try`. On an access violation it returns 0 with the faulting
address (module-relative), the data address and the module name, and writes a full record
(registers and stack sweep) to `native-crash.log`, at most 16 per process.
- `Compatibility/GameTickHooks.cs`: AC's original `UseTime` goes through that wrapper when the
loaded trampoline is version 4 or later. A caught fault drops that one tick, logs an `[ERR]`
line, and returns 1 so AC's game loop keeps running (0 would make AC shut down). After 5 faults
within 30 seconds the guard turns itself off for the session, so a client whose state is
really broken still ends instead of spinning.
- `Compatibility/SehTrampoline.cs`: the P/Invoke, and `NativeVersion` (cached). A running client
keeps the trampoline DLL it started with, so a hot-reloaded engine meeting a v3 DLL logs
"native AV guard OFF" and calls `UseTime` directly, as before.
- `native/SehTrampoline/Build-SehTrampoline.ps1`: `-NoDeploy` builds into `bin\` without
copying to the runtime folder.
- `scripts/Publish-EngineCoreClr.ps1`: a trampoline DLL held by a running client is now moved
aside (`.old-<time>`) like the loader and shim, so new launches get the new one. Before, it
was skipped with a warning and every launch stayed on the old version until all clients closed.
## Tests
- The engine builds in Release (CoreCLR host).
- An x86 harness against the new DLL: a clean call returns its value, a null read is caught and
attributed to the right module, and a call after the caught fault works. Version reports 4.
- Not yet seen in game: the chat-server fault can't be reproduced on demand.

View file

@ -0,0 +1,72 @@
# Inventory: filter by item attributes; Charms moved to the ILT Mini Remote
## Inventory attribute filter
- **New button in the tools row:** a list-check icon between the search box and the sort picker.
- In the Modern look it is always visible.
- In the Classic look, open the tools row first (the funnel in the title bar).
- **The popup editor:**
- Filter on/off;
- "Keep items matching all rules / any rule";
- up to 12 rules, each made of an attribute, an operator and a value;
- Add rule, Clear rules, Close.
- **Attributes known without an identify:** Name, Value, Burden, Workmanship, Stack size, Material,
Fits slot (Head ... Aetheria), Equipped, Casts a spell.
- **Attributes that need an identify (marked \*):**
- Armor level, Max damage, Speed;
- Attack bonus %, Melee / Missile / Magic defense %, Elemental damage %, Mana conversion %;
- Damage, Damage resist, Crit, Crit resist, Crit damage, Crit damage resist, Healing boost and
Vitality ratings;
- Level to wield, Arcane lore, Spellcraft, Max mana, Times tinkered, Max item level;
- Armor set (name text), Spells (any spell's name contains the text);
- Imbued, Bonded, Attuned, Retained.
- **Operators:**
- numbers: >=, <=, =, !=;
- yes / no flags: yes, no;
- text: contains, doesn't contain (case-insensitive);
- slot: is, is not.
- **Missing values:** an attribute the item doesn't have counts as 0, no, or empty text. For
example, "Level to wield <= 150" keeps items with no level requirement.
- **Items the server hasn't identified yet:** a rule that needs an identify can't judge them, so
they are hidden and counted.
- The count appears in the header ("N not ID'd"), the button's tooltip and the popup.
- "Identify N" in the popup asks the server about them, 4 a second while the panel is open.
"Stop" empties the queue.
- Items already identified, or asked about in the last minute, are skipped.
- While such a rule is on, the list refreshes once a second so new answers show up.
- **Saving and Clear:**
- The rules are saved in `%LOCALAPPDATA%\RynthCore\inventory_settings.txt`, on the
`attrfilter=` line, when the popup closes.
- Clear (closing the Classic tools row) turns the filter off but keeps its rules.
- In Classic, the filter only applies while the tools row is open, so nothing is ever hidden
without a visible control.
- **Behaves like the search and category filters:**
- Classic lists matches from all packs;
- grid cells stop acting as slots, and drops refuse to reorder;
- "Nothing matches." shows when no item matches.
## Charms
- Settings > Charms Tracking is removed. It is now the Charms tab in RynthAi's Mini Remote
(the matching RynthSuite change). Its poller (`UI/Data/CharmsData.cs`) and its `UiSources` registration are
removed.
- The ILT server menu (right-click the Mini Remote) gains Charms after Gear. It opens with
`/rc miniremote tab charms`.
## Files
- `Compatibility/InventoryAttributeFilter.cs` (new): the attributes, operators, matching (Match /
NoMatch / Unknown), material and set names, and the saved line. It has no dependencies, so the
RynthSuite host tests link it.
- `Compatibility/InventoryFilterFacts.cs` (new): an item's values from the panel's item and the
appraisal cache (render thread, no AC reads).
- `Compatibility/InventoryModel.cs`: the identify queue (`QueueIdentify`, `IdentifyQueueCount`,
`ClearIdentifyQueue`), sent on AC's main thread and cleared on a character change.
- `ImGui/Panels/InventoryFace.AttrFilter.cs` (new): the button, the popup and the per-item check.
- `ImGui/Panels/InventoryFace.cs`, `InventoryFace.Classic.cs`: wiring, `FiltersOn`, and the
`attrfilter` setting.
- `ImGui/Panels/SettingsFace.cs`, `UI/Data/UiSources.cs`, `UI/Data/CharmsData.cs` (deleted),
`EntryPoint.cs`: the Charms move.
The engine builds in Release. The filter has 5 new host tests in RynthSuite
(`InventoryAttributeFilterTests`), and all of them pass. Not yet tested in game.

View file

@ -0,0 +1,84 @@
# Inventory: pick several items, then Drop, Give or Move them
**Date:** 2026-10-11
**Area:** Engine (`RynthCore.Engine`), Inventory panel (both looks: Modern and Classic) and
`InventoryModel`.
## What's new
The Inventory window can select several items and act on all of them at once.
- **Picking items** (in both looks):
- **Click:** selects one item, as before.
- **Ctrl+click:** adds an item to the selection, or removes it if it is already selected.
- **Shift+click:** selects every item from the last clicked item to this one, in the order the
grid shows them. **Ctrl+Shift+click** adds that run to the current selection.
- **Right-click > Select all shown:** selects every item the grid shows, meaning the open pack or
the search's matches. The menu item shows the count.
- **Right-click > Select only this item** returns to a single item.
- **Acting on the selection** when more than one item is selected:
- The zones read **Drop N** and **Give N: <target>**. Clicking a zone, or dragging any selected
item onto it, acts on the whole selection.
- Dragging a selected item onto a pack (the pack column, or a pack in the grid) moves the whole
selection there. The drag ghost shows the count.
- The right-click menu on a selected item shows *N items selected*, then **Drop N items**,
**Give N items to <target>** and **Move N items to >** (with a list of your packs).
- The status row shows the size of the selection and how to use it.
- **Confirmation:** Drop and Give of several items open a confirmation that lists the items by name
(for example "Pyreal x3", up to 10 lines). Give adds "Given items can't be taken back." Move
starts straight away.
- **Progress and Stop:** while the items are sent, the status row shows progress such as
*Giving 3 of 12 to Bob*, with a **Stop** button. When the run ends, the status row and the log
show a summary such as *Gave 10 of 12 items to Bob; 2 failed (first: …).* or *Stopped: dropped
3 of 12 items; 9 not sent.*
## Behaviour
- AC still gets one item action at a time. The batch passes each item to the same request path a
single click uses, so every item is checked, sent and watched exactly as before, including the
wait for AC's action gate. The next item goes only after the previous one has ended (done,
refused, gone or timed out), with a short gap of 0.25 s.
- The batch keeps running with the Inventory window closed and ends by itself.
- Some items are left out of a run, and the confirmation or the status row says how many and why:
- Worn and wielded items.
- Packs and foci sent to a side pack (they only fit in the main pack).
- Items that have already left the inventory.
- Items already in the target pack are skipped quietly, as a single item's drop on its own pack
is. A group dropped back onto its own pack does nothing.
- A Give stops early, and counts the remaining items as failed, if the target disappears or you
leave the world.
- At most 400 items per run.
- While a run is going, single item actions (Use, Split, Equip and so on) are refused with
"Several items are being sent; wait, or press Stop." A run can't start while a single action is
still waiting.
- Items that leave the inventory (given, dropped or merged) drop out of the selection
automatically.
- A plain click on one item of a selection keeps the selection if you drag, and narrows it to that
item if you release without dragging, as in Windows Explorer.
- No keyboard shortcuts were added (such as Ctrl+A or Delete). Keys may belong to AC, so selection
uses mouse modifiers only.
## Files
- `src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs` (new): the selection itself (ids, picked
order, anchor, ranges, select all, prune). It has no engine state, so it is unit-tested.
- `src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs` (new): clicks, group actions,
the confirmation, labels, the group menu, the status row's progress and Stop button, and the
drag badge.
- `src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs` (new): `RequestBatch`,
`CancelBatch`, `Batch` and `BatchRunning`, plus the main-thread runner that feeds items one at a
time.
- `src/RynthCore.Engine/Compatibility/InventoryModel.cs`: the model is now a partial class. Single
requests are refused during a run, and the tick drives the runner even with the panel closed.
- `src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs` and `InventoryFace.Classic.cs`: grid clicks,
selection highlight, zone labels, drag release, context menu and status row now use the
selection.
- `tools/InventorySelectionTests` (new): 42 checks covering click, Ctrl+click, Shift and Ctrl+Shift
runs in both directions, a missing anchor, select all, prune and id 0.
Run with `dotnet run -c Release`.
## Verification
- `dotnet build -c Release` for the engine: no errors and no new warnings.
- `tools/InventorySelectionTests`: 42/42 checks passed.
- Not yet tested in game.

View file

@ -0,0 +1,16 @@
# Items panel: Remove Missing button
## What changed
- `ImGui/Panels/ItemsFace.cs`: a "Remove Missing" button at the top of the Items panel, above the
lists (which can run long), with a tooltip. `AddSelected` takes an optional tooltip.
- `UI/Data/ItemsData.cs`: `ItemsCommands.CleanMissing()` calls RynthAi's `RynthPluginCleanItems`
export, then refreshes the panel.
- What RynthAi does when the button is clicked:
- removes listed weapons and consumables that are no longer in your inventory;
- re-points an entry at an unlisted item of the same name, when your pack has one;
- does nothing while your inventory is still loading;
- reports in chat what it removed and re-pointed.
- With a RynthAi that lacks `RynthPluginCleanItems`, the click is logged and nothing happens.
The engine builds in Release. Not yet tested in game.

View file

@ -0,0 +1,47 @@
# Mini Remote gets the ILT tabs; Guardian moves under the ILT button
## What changed
- **The Mini Remote window hosts the ILT Hub's sections as tabs.** RynthAi draws them on its
`"miniremote-window"` surface: Remote, then on ILT worlds Character, Quests, Pets, Banking, Gear
and Games. The window already fits itself to the size the plugin asks for, so it refits when the
tab changes.
- **New Guardian panel** (`GuardianFace`) in the ILT section.
- It hosts RynthAi's Temple guardian tools through the new embed surface `"guardian"`.
- It is registered when `RynthCore.Plugin.RynthAi.dll` is installed.
- Like Bounties, it has no bar button of its own. The bar's ILT button lists it, on Infinite
Leaftide only. With Bounties and Guardian both present, the ILT button opens a menu.
- The panel is user-sized (540x520 by default), and the plugin fills its body.
- Until RynthAi can draw it, the body says why: not loaded, not logged in, or the embed failed.
- **`/rc guardian [show|hide|toggle]`** is new. **`/rc bounties`** and **`/rc miniremote`** now
take `show|hide|toggle` too; with no argument they toggle, as before. RynthAi uses these to open
the panels from `/ra guardian window` and `/ra bounty`.
- **`/rc ilt`** also reports whether RynthAi's Guardian panel and ILT tabs are available.
- **RynthAi dashboard, Char launcher.**
- Left-click opens the Mini Remote window on its Character tab.
- Right-click lists the Mini Remote, its six ILT tabs, Guardian (when registered) and
Progression. The old "Mini Remote (ILT Hub)" entry and the per-section windows are gone.
- **Wording.**
- Settings > trace categories: "ILT Hub on" is now "ILT on".
- The Mini Remote drawer tooltip now points to the window's ILT tabs.
- The Skills panel's Progression message now says "ILT features".
## Files
- `src/RynthCore.Engine/ImGui/Panels/GuardianFace.cs`: new.
- `src/RynthCore.Engine/EntryPoint.cs`: registers `GuardianFace` with RynthAi.
- `src/RynthCore.Engine/ImGui/ImGuiBar.cs`: `IltPanels` now includes Guardian.
- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs`:
- `/rc bounties|guardian|miniremote [show|hide|toggle]`;
- the helpers `TryPanelMode`, `SetPanelOpen` and `IltPanel`;
- the extra `/rc ilt` line.
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`: the Char launcher and menu
(`ShowMiniRemoteTab`).
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs`, `SettingsFace.cs`,
`SkillsFace.Progression.cs` and `MiniRemoteFace.cs`: wording and comments.
## Testing
- ItemHudTests: 63 assertions pass.
- Engine and plugin both build in Release.
- In-game checks are listed in the matching RynthSuite changelog.

View file

@ -0,0 +1,40 @@
# Mini Remote: one window, resizable quick-launch boxes
## What changed
RynthCore's "Mini Remote" window and RynthAi's floating "MINI REMOTE" are merged into one window.
- **`MiniRemoteFace` hosts RynthAi's Mini Remote** through the new plugin embed surface
`"miniremote-window"`. That covers stats, target, pet, item slots, toggles, bank, rebuff,
translate and the guardian answer, with RynthAi's own Options menu.
- The window fits itself to the size the plugin asks for (`FitWindow`, capped to the screen
height; popped-out windows are left alone).
- RynthAi hides its floating copy while this window shows it.
- Without RynthAi, or when its embed fails, the window falls back to the engine's own slot grid
(per-character `item_huds.txt` slots, More/Fewer slots, drag-and-drop), as before.
- **Grow and shrink the quick-launch boxes** in the fallback grid:
- Ctrl+mouse wheel over the grid changes the box size by 4 px per notch.
- The right-click menu has "Bigger boxes (N px now)", "Smaller boxes" and "Default box size".
- Saved per character in `item_huds.txt` as `slotsize=<px>` (24-72, default 36). The line is
written only when the size isn't the default, so existing files don't change.
- RynthAi's hosted grid has its own size control: Ctrl+wheel, or Options > Slot size.
- **Hub launcher** on the RynthAi dashboard: left-click now toggles this Mini Remote window instead
of RynthAi's floating one. Right-click still opens the Mini Remote drawer, or the window when
the dashboard is popped out.
## Files
- `src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs`: rewritten to host the plugin, with the
fallback grid, the box size controls and the window fit.
- `src/RynthCore.Engine/UI/Data/ItemHudModel.cs`: `ItemHudCharacter.SlotSize`, `WithSlotSize`,
and parsing and writing `slotsize=`.
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`: the Hub launcher opens the Mini Remote window.
- `tools/ItemHudTests/Program.cs`: new `SlotSizes` case covering clamping, edits, round-trip,
default not written, and bad values.
Works best with the matching RynthAi change. An older plugin doesn't know `"miniremote-window"`, so
the window shows the engine grid instead.
## Tests
- ItemHudTests: PASS (63 assertions).

View file

@ -0,0 +1,19 @@
# Settings: Navigation > Getting Back On Route > Go To Closest Waypoint
## What changed
- `UI/Data/SettingsData.cs`:
- new `NavResumeNearest` property (default true);
- new "Getting Back On Route" section on the Navigation page, with a "Go To Closest Waypoint"
checkbox.
- With the option on, RynthAi:
- heads for the closest waypoint on the route at macro start, when a Circular or Linear route
loads, and when nav takes over again after a fight, loot, buff or door that moved the
character 10 yd or more;
- skips a waypoint the character has already walked past.
- With the option off, nav carries on to the waypoint it was heading for, and a loaded route
starts at its first point.
- An older RynthAi ignores the new field. The matching RynthAi keeps its own value when an older
engine doesn't send it.
Not yet tested in game.

View file

@ -0,0 +1,43 @@
# Fix: a popped-out Mini Remote or Guardian crashed the client
Follows the menu changes (`2026-10-11-character-and-server-menus.md`). Pairs with the RynthSuite
change that draws `:popout` surfaces in the current context.
## The crash
Four crashes on 2026-10-11 had the same stack:
```
EndSceneDetour -> EngineFrameController.OnEndScene -> ImGuiPopOuts.RenderAll
-> ImGuiPanelHost.DrawPopped -> MiniRemoteFace.Draw -> DrawRynthAi
-> PluginManager.RenderEmbed -> (RynthAi) -> access violation in coreclr
```
- `ImGuiPopOuts` gives every popped-out panel its own ImGui context.
- `PluginManager.RenderEmbed` called RynthAi from inside it. RynthAi then switched
to the main context, which isn't mid-frame there, and faulted.
- An access violation isn't an exception `RenderEmbed`'s try/catch can stop, so the client died.
- The "MAIN THREAD HANG DETECTED" line before each exit was the runtime writing the 700 MB crash
dump.
## Fix
- `PluginManager.RenderEmbed` checks the current ImGui context. When it isn't the one plugins
were given (a pop-out), the surface goes out as `name:popout`.
- RynthAi with the matching RynthSuite change draws it in the current context.
- Older plugins don't know the name and decline. The Mini Remote then shows the engine's own
slot grid, and the Guardian panel its "not ready" state, instead of crashing.
- This covers every embedded surface: the Mini Remote window, the RynthAi dashboard's Mini Remote
drawer, and the Guardian panel.
- It also returns "not ready" when no ImGui context is current.
## Files
- `src/RynthCore.Engine/Plugins/PluginManager.cs`: `RenderEmbed` (context check and the
`:popout` name), with the export call moved to `RenderEmbedCore`.
- `src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs`: header note on the fallback.
## Testing
- The engine builds in Release, and ItemHudTests pass.
- Not yet checked in game: the popped-out Mini Remote, with a current and with an older RynthAi.

View file

@ -0,0 +1,20 @@
# Settings: On Death > Recall On Death
## What changed
- `UI/Data/SettingsData.cs`:
- new properties `DeathRecallMode` (0 off, 1 spell, 2 item), `DeathRecallSpellId` (default 48,
Primary Portal Recall) and `DeathRecallItem`;
- a new "On Death" section after Safety Stops, with three rows:
- "Recall On Death": Off, Cast a recall spell, or Use a recall item;
- "Recall Spell": the nav editor's recall spells (`NavCommands.RecallIds`), shown only for
the spell choice;
- "Recall Item": the item name, shown only for the item choice.
- The spell names fill in from the client's spell table as it loads; until then they show as
"Spell N (N)".
- What RynthAi does with it: after a death while the macro runs, once respawned, it casts the
recall or uses the item, retries a fizzle, then rejoins the nav route and starts Travel Back To
My Corpse from the landing spot.
- An older RynthAi ignores the new fields.
The engine builds in Release. Not yet tested in game.

View file

@ -0,0 +1,90 @@
# SK engine and UI work through 2026-10-10, rebased on 2026.10.12.1
Replaces the closed per-feature PRs RynthCore #1-#5 and the earlier `sk` commits. This commit
carries everything from those PRs that main doesn't already have, merged onto release 2026.10.12.1
with the conflicts resolved. Work from 2026-10-11 follows in separate commits.
Nothing here changes what 2026.10.12.1 already does unless a setting below says so.
## Merge notes for 2026.10.12.1
- **API v81:** 2026.10.12.1 took v80 for `GetContainerOrder` and `PutItemInContainer`, so
`GetMergeStackResult` moves to v81, after them (engine table, SDK table,
`RynthCoreSdkApiVersion`, `HasGetMergeStackResult`, and the manifest test's slot order).
Plugins built against the earlier SK SDK must be rebuilt.
- **Chat routing:** `ChatRouter` now lives in `UI/Data/ChatRouting.cs`. The standard-filter step
(`RynthChatPresets`) is added there instead of in `ChatData.cs`.
- **Settings:** `LoggingLevel` and `EnablePluginOverlayWindows` sit next to the new
`CloseOnServerDisconnect`; the Items payload keeps both `missingIds` and `autoEquipShield`.
## Launcher and logging
- **Logging level** in the launcher (Error, Warning, Info, Debug, Trace), saved as `LoggingLevel`
in `engine.json`. The engine reads it at start and watches it while running
(`LogSettings`, `LoggingSettingsStore`, `MainWindow.Logging`). Per-category trace switches are
shown with a warning when a category is hidden by the level.
- The heartbeat line is always written, whatever the level, because the launcher uses it to tell
a client is alive (`RynthLog.Heartbeat`).
- `RynthCore.DesktopLog` (new project): rolling launcher log and the .NET desktop x64 prerequisite
check, with host diagnostics in the launcher (`LauncherHostDiagnostics`).
- Install-aware paths: the launcher, injector, loader and status agent find the install folder the
installer recorded (`InstallerHandoff`, `LogPaths`) instead of assuming `C:\Games\RynthCore`.
## Plugin windows and ImGui
- **Plugin overlay windows** while the ImGui shell is off: a plugin that exports
`RynthPluginRenderOverlay` draws its extra ImGui windows over the Avalonia UI.
`engine.json` `"EnablePluginOverlayWindows": false` turns this off. Plugins get the engine's
ImGui context for these windows.
- ImGui draw data is submitted after the Avalonia blit, so ImGui windows stay on top.
- Panel windows are destroyed on the thread that owns them, and a login pop-out waits until the
game window is hooked.
- Docked panels open clear of popped-out windows (`LayeredWindow`).
- `CS0162` (unreachable code) is an error in the engine project: a misplaced statement after a
`return` once left the plugin render snapshot unpublished.
## Items, drag and drop, object data
- **Item drag bridge** (`ItemDragBridge`, `DragDropHooks`): items dragged from the game or from a
popped-out Inventory can be dropped on Mini Remote slots. Game-inventory drags carry the dragged
item, not the previous selection.
- Object name and type are seeded when the object is created, so panels show them before the
first update (`CreateObjectHooks`, `DeleteObjectHooks`).
- Off-thread int property reads are snapshotted from the PWD and kept current with server
updates (`ClientObjectHooks`); IconOverlay and IconUnderlay DIDs are served from the PWD.
- **Merge-stack results** (API v81, `GetMergeStackResult`, after rynth's v80 slots): plugins can see whether a stack merge
went through (`MergeStackResults`). The thunk is cdecl; stdcall corrupted plugin stacks.
## Native crash logging
- `SehTrampoline.c`: the native crash logger records only fatal faults by default, and logs
access violations in the CoreCLR-hosted engine immediately rather than at exit.
## Panels
- **Nav:** route editing in the Nav panel, Breadcrumbs and Route overlay toggles,
and the waypoint list no longer jumps back to the top on every poll.
- **Skills > Progression tab:** XP and augmentation planning laid out like UB's ILT Tools XP and
Augs tabs, an attribute raiser, and per-server augmentation cost settings
(`ProgressionData`). The Char launcher has a menu that opens it.
- **Chat filters:** UB-IT-style standard filters, plain-text custom rule modes, a line tester, and
presets (`RynthChatPresets`).
- **RynthAi dashboard:** Char and Hub launcher buttons, Map and Lua buttons, a Mini Remote drawer,
a Buffs picker in Loaded Files and a Spells window button.
- **Items panel (Avalonia):** Shields section and Add Selected Shield.
- **Inventory:** a menu item that adds an item to RynthAi's item count HUD.
- **Settings:** Charms Tracking tab, an Inventory HUDs button, the Server Features text row, and
one "Describe Items When Selected" toggle (the duplicate "Item Info On Select" row is removed).
- **Loot:** "Include T11 attributes" in the Add to loot profile popup, with a tooltip that covers
the stamped tier and gear grade.
## Build
- `RynthCore.sln` includes `RynthCore.DesktopLog`.
- One `Tmds.DBus.Protocol` 0.21.3 pin in the engine project (GHSA-xrw6-gwf8-vvr9).
## Testing
- Engine (CoreCLR host) and launcher build in Release.
- `tools/PluginManifestTests` pass.
- Each feature was run in game on the SK builds of 2026-10-04 to 2026-10-10.

View file

@ -0,0 +1,44 @@
# Tracker panel: Lum/5m and pass-up rows
Pairs with RynthTracker 0.4.0 in RynthSuite.
## What changed
RynthTracker and RynthAi's Mini Remote now share one session-stats engine (RynthSuite
`Plugins/Shared/SessionStats.cs`), so the Tracker panel and the Mini Remote count XP, luminance and
kills the same way. The Tracker panel shows the new figures:
- **Lum/5m:** luminance earned in the last five minutes. It shows when RynthTracker sends it
(0.4.0 and later), so an older RynthTracker still gets the old rows.
- **Pass/hr and Pass-up:** allegiance pass-up luminance per hour and for the session. These rows
appear only where RynthTracker can tell pass-up apart, which is on ACECustom, where the bank
luminance is read. Fellowship and Zone Share splits arrive the same silent way and are included;
the label tooltip says so.
- **Row order:**
1. Session
2. XP/hr
3. Lum/hr
4. Lum/5m
5. [Pass/hr]
6. [Rad/hr]
7. Kls/hr
8. XP
9. Lum
10. [Pass-up]
11. [Rad]
12. Kills
13. XP/kl
14. Deaths
Rows in brackets appear only on some servers.
## Files
- `src/RynthCore.Engine/UI/Data/PanelSources.cs`: `TrackerSource` reads `l5`, `pk`, `ph` and `pt`;
`TrackerSnapshot.DefaultLabels` includes Lum/5m.
- `src/RynthCore.Engine/ImGui/Panels/P1Faces.cs`: tooltips on the Lum/5m and pass-up labels.
## Testing
- The engine builds in Release, and ItemHudTests pass (63 assertions).
- Not yet checked in game.

View file

@ -0,0 +1,29 @@
# Char menu: Quests and Pets under Character; "Server: <name>" for the server section
## What changed
- **Quests and Pets are universal.** RynthAi's Mini Remote shows those tabs on every server, so
they moved:
- into the Char right-click menu's **Character** half, after Spells. They open the Mini Remote
window on that tab (`/rc miniremote tab quests|pets`);
- out of the Infinite Leaftide server registration (`EntryPoint.RegisterServerMenus`).
- **Guardian stays ILT only**, in the server section, together with:
- the Character, Banking, Gear and Games tabs;
- Bounties (RynthILT);
- Progression.
- **Server section header:** each active section is now titled "Server: <name>", e.g. "Server:
Infinite Leaftide" (`ServerMenus.DrawImGuiMenu`). RynthAi's Mini Remote menu uses the same
header.
- **Char launcher tooltip** now lists Quests and Pets.
## Files
- `src/RynthCore.Engine/EntryPoint.cs`: the ILT tab list without Quests and Pets.
- `src/RynthCore.Engine/UI/ServerMenus.cs`: the "Server: " header.
- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`: Quests and Pets in `CharMenu`; the
tooltip; the `ShowMiniRemoteTab` doc.
## Testing
- The engine builds in Release, and ItemHudTests pass.
- Not yet checked in game.

View file

@ -0,0 +1,19 @@
# Settings: Navigation > Dungeon Patrol
## What changed
- `UI/Data/SettingsData.cs`: new `DunPatrol*` properties and a "Dungeon Patrol" section on the
Navigation page:
- Coverage (combo): Whole dungeon (default) / Loops only / Everything;
- Skip Dead Ends Up To (cells), 0-10, default 3 (hidden for Everything);
- Avoid Lava/Acid Floors, default on;
- Distance From Walls (yd), 0.5-2, default 1;
- Walk Into Rooms From (yd), 3-40, default 10;
- a note that changing them rebuilds a running patrol.
- RynthAi (RynthSuite feature/patrol-settings) builds the dungeon patrol with them and rebuilds a
running patrol, without stopping the macro, once a change has been still for 1 s. The defaults
are the patrol as it was before.
- An older RynthAi ignores the new fields; the matching RynthAi keeps its own values when an older
engine doesn't send them.
Not yet tested in game.

View file

@ -0,0 +1,74 @@
# Characters panel: your other RynthCore clients, with vitals and distance
UtilityBelt's networked character window, as an ImGui panel. It reads the RynthNet plugin's snapshot,
so it shows the other clients on this PC that run RynthNet.
## What changed
- **New panel: Characters.** Open it from its bar button (three people icon), the dashboard's Char
menu, or `/rc characters` (alias `/rc chars`). It exists only when RynthNet is installed.
- **Rows.** This client comes first, dimmed. The others follow in alphabetical order, which stays
stable as characters move: a distance order would reshuffle several times a second for characters
standing together. Each row shows:
- an arrow pointing to the character, turned to where you face;
- the name, plus its server when that isn't yours;
- what it is doing: botting (fighting, navigating, ...), idle, idle in a combat stance, dead,
portal space, or no status yet;
- a warning when its status is more than 5 s old (a frozen client);
- distance in yards and a compass point (N, NE, ...);
- health, stamina and mana bars with current/max;
- where it is: map coordinates, or the dungeon's name from the Atlas.
- **Distance rules** (Sense's): a distance shows when you are both outdoors (or in surface
buildings), or both in the same dungeon landblock. Otherwise the row says "elsewhere" and gives
the dungeon name or the coordinates. A character on another server shows only its server.
- A character this client can see is placed by its object position, which is fresher than its
status.
- **Click** a row to select that character in game when this client can see it. This needs
RynthNet 0.1.1 on that client, for the object id.
- **Right-click** a row for commands, sent as `/rn tell <name>, <command>`:
- Follow me (`/ra follow <you>`);
- Stop following (`/ra follow off`);
- Start macro (`/ra start`);
- Stop macro (`/ra stop`);
- Everyone: follow me (`/rn followme`).
The other client's RynthNet remote setting (`/rn remote`) decides whether they run. A refusal
comes back as a chat line.
- The top line says how many characters there are, or why there are none (RynthNet not loaded or
offline). It also has an "everyone follow me" button and a help tooltip.
- The panel refreshes twice a second while it is open. It works docked and popped out, and follows
the panel text size.
## Files
- `UI/Data/CharactersModel.cs` (new): snapshot parsing, distance, compass, location, state text
and row order. It has no engine dependencies, so the tests compile it in.
- `UI/Data/CharactersData.cs` (new): `CharactersSource` (2 Hz, RynthNet's
`RynthPluginGetSnapshotJson`, plus this client's pose, vitals and object table) and
`CharactersCommands` (`RynthPluginApplyRemoteCommand("rn", ...)`).
- `ImGui/Panels/CharactersFace.cs` (new): the face.
- `UI/Data/RynthNavAtlasData.cs`: `IsMapLandblock`. An indoor cell in a landblock with Atlas
surface places counts as a building, not a dungeon.
- Wiring: `UiSources.cs`, `EntryPoint.cs` (registered when `RynthCore.Plugin.RynthNet.dll` is
installed), `ImGuiBar.cs` (button and icon), `RynthAiFace.cs` (Char menu),
`RynthCoreChatCommands.cs` (`/rc characters`).
Pairs with RynthSuite `feature/characters-panel` (RynthNet 0.1.1, which adds `id` and `cmode` to
the shared status). Older RynthNet clients still show up. They just can't be selected by a click,
and show no combat stance.
## Tests
`tools/CharactersPanelTests`: 84 checks, all passing. They cover:
- parsing the current snapshot and older entries (no id/cmode, no bot, null status, character
select, wrong types);
- bad JSON;
- distance and compass within a landblock and across landblocks;
- the dungeon rules, surface buildings and the coordinates text;
- the state text, the stale marker and the stable order.
An offscreen render with fake characters checked the layout at text sizes 0 and 3, a narrow window,
the tooltip and the menu.
Not yet tested in game.

View file

@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}"
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.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}"
@ -63,6 +65,18 @@ Global
{A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.ActiveCfg = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.Build.0 = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{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-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
@ -179,6 +193,7 @@ Global
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{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}

View file

@ -299,6 +299,13 @@ Write-Host " Total staged: ${totalMb} MB"
Write-Host "Staging complete: $StagingDir" -ForegroundColor Green
# No file we ship may carry the ReadOnly attribute (a read-only source - a git checkout on a
# read-only share, a file copied off an ISO - would otherwise land read-only on the player's PC,
# where the launcher's updater and RynthAi can't overwrite it). 2026-10-13.
$readOnly = @(Get-ChildItem "$ScriptDir\staging" -Recurse -File -Force | Where-Object { $_.IsReadOnly })
foreach ($f in $readOnly) { $f.IsReadOnly = $false }
if ($readOnly.Count -gt 0) { Write-Host " Cleared read-only on $($readOnly.Count) staged file(s)." -ForegroundColor Yellow }
# ── Inno Setup ───────────────────────────────────────────────────────────────
# Auto-detect ISCC if not specified: try standard install location then user-local.
if (-not $IsccPath) {

View file

@ -134,7 +134,7 @@ Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionI
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", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthILT"
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthILT", "RynthThreads", "RynthNet"
foreach ($name in $suitePlugins) {
Step "Building $name"
$proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
@ -182,6 +182,8 @@ Extract this zip into C:\Games - it creates:
C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items)
C:\Games\RynthSuite\RynthSort\ RynthSort plugin (keeps your packs sorted; replaces the RynthSort Lua script)
C:\Games\RynthSuite\RynthILT\ RynthILT plugin (Infinite Leaftide only: the Bounties window's tracker)
C:\Games\RynthSuite\RynthThreads\ RynthThreads plugin (DreamWeave only: Fragment Press results, what each component brings)
C:\Games\RynthSuite\RynthNet\ RynthNet plugin (links your clients on this PC: /ub bc, shared vitals, the Characters panel)
C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas
Then, in the RynthCore launcher's Plugins tab, add the full path of each
@ -270,6 +272,8 @@ $pluginDescriptions = @{
RynthInventory = "Search every character's items."
RynthSort = "Keeps your packs sorted: new loot goes to the pack its rule names."
RynthILT = "Infinite Leaftide only: tracks your ACECustom bounties for the Bounties window."
RynthThreads = "DreamWeave only: records Fragment Press results and works out what each component brings."
RynthNet = "Links your characters on this PC: broadcast commands (/ub bc), shared vitals and the Characters panel."
}
# Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi
# goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers

View file

@ -41,26 +41,40 @@ Name: desktopicon; Description: "Create a &desktop shortcut"; GroupDescription:
; Program files
[Files]
; Launcher + engine runtime + Loot Editor go to {app} (default C:\Games\RynthCore\)
Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; overwritereadonly: a file left read-only on the player's PC is replaced without a question
; (a /SILENT update can't answer one); the build clears ReadOnly on everything staged, and Setup
; doesn't give installed files any attributes, so nothing lands read-only.
Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs overwritereadonly
; Plugin DLL goes to its canonical home next to plugin data dirs.
; Engine does NOT auto-scan this folder — user adds the full DLL path in the
; launcher's Plugins tab to enable the plugin. See BUILD.md "Deploy RynthAi Plugin".
Source: "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "C:\Games\RynthSuite\RynthAi"; Flags: ignoreversion
Source: "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "C:\Games\RynthSuite\RynthAi"; Flags: ignoreversion overwritereadonly
; Data directories (created once; never removed on uninstall)
;
; Permissions: users-modify (2026-10-13). The game client never runs elevated, and RynthAi saves
; metas, navs, loot and settings profiles in these folders. An "install for all users" (elevated)
; Setup creates them as an administrator; on a PC whose C:\ permissions aren't Windows' defaults,
; such folders are read-only for everyone else and RynthAi's saves failed. users-modify gives the
; Users group Modify, inherited by everything inside, every time Setup runs (also on an update, so
; it repairs older installs when that update runs elevated). A non-elevated Setup can only change
; folders its user owns; where it can't, Setup logs "Failed to set permissions" and carries on
; (not an error), and the launcher's Recovery Actions > Fix folder permissions does it instead.
[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\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: "{app}"; Permissions: users-modify
Name: "C:\Games\RynthSuite"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\NavProfiles"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\LootProfiles"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\MetaFiles"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\MetaProfiles"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles\ACEmulator"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\LuaScripts"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\Logs"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\pvars"; Permissions: users-modify; Flags: uninsneveruninstall
Name: "C:\Games\RynthSuite\RynthAi\ItemGiver"; Permissions: users-modify; Flags: uninsneveruninstall
; Shortcuts
[Icons]

View file

@ -1,6 +1,9 @@
# Build-SehTrampoline.ps1
# Compiles RynthCore.SehTrampoline.dll (x86 MSVC) and copies to the runtime.
# Run from anywhere; finds VS automatically via vswhere.
# -NoDeploy: build into bin\ only; leave C:\Games\RynthCore\Runtime untouched.
param([switch]$NoDeploy)
$ErrorActionPreference = "Stop"
@ -32,6 +35,7 @@ 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)"
if ($NoDeploy) { return }
$runtimeDst = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll"
Copy-Item "$out\RynthCore.SehTrampoline.dll" $runtimeDst -Force

View file

@ -0,0 +1,277 @@
/*
* CrashLogFilter.h - which exceptions the native crash logger (SehTrampoline.c) writes.
*
* Pure decision logic: no Win32 calls, no globals. The logger keeps one clf_state and
* calls these under its own lock; native\SehTrampoline\tests\CrashLogFilterTests.c
* runs them directly.
*
* Why: the logger used to write every first-chance AV until a cap of 24 per process.
* Decal's .NET Framework plugins raise a handled null-reference AV in JIT code (clr.dll
* and mscorlib frames) about once a minute, the SAME address each time, so the cap was
* spent within minutes: one client's 24 entries (all within about five minutes) were all
* exAddr 0x433620C8, and its fatal AV at 20:25 under GameTickHooks.UseTimeDetour left
* nothing in native-crash.log.
*
* Now:
* - Logged codes: access violation, fail-fast, stack buffer overrun, stack overflow,
* heap corruption.
* - Each faulting address has a slot with its hit count and the time it was last
* written. The first sighting is written. A repeat is written again (with its count)
* when the count is a power of two, when 30 s have passed since that address was
* last written, or when the code is not an AV. So a contained AV that later recurs
* as the fatal one is not swallowed as "seen before": a fatal fault is usually a
* terminate from some handler, and then no last-chance filter ever runs.
* - Noise is classified, written once per address like the rest, and never charged to
* the AC limit:
* .NET Framework (Decal plugins): faulting module clr.dll, mscorwks.dll, mscorlib;
* managed (the engine's CoreCLR): coreclr.dll, clrjit.dll, System.Private.CoreLib;
* or no module at all (JIT code) with the nearest module-resolved code pointer on the
* stack in one of those. Only AVs are ever noise.
* - A first sighting of anything else (AC's faults) is charged to CLF_MAX_COUNTED, a
* flood guard on DISTINCT addresses only.
* - The last-chance (unhandled) entry is never charged to that limit and has its own
* small one (it happens once in a dying process; the limit only stops a loop).
* - A full address table evicts its least recently written NOISE slot. With no noise
* slot to evict, an AC address is still written (under the limit), just not tracked.
* - The last CLF_RING first-chance records, written or not, are kept in a ring (no I/O
* at exception time). A flush writes those that were not written one by one: the
* last-chance filter flushes, and so does the engine's crash-exit path (TerminateProcess
* and friends, through RC_FlushCrashLog). That recovers the case the dedupe alone
* cannot: the fatal hit of an address seen before, at a count that is not due a
* write, followed by a terminate from a handler, so no last-chance filter ever runs
* (checked with 5, 100 and 1000 contained hits before the fatal one).
*
* Times are GetTickCount milliseconds (32-bit; unsigned subtraction survives the wrap).
*/
#ifndef RYNTHCORE_CRASH_LOG_FILTER_H
#define RYNTHCORE_CRASH_LOG_FILTER_H
#define CLF_MAX_COUNTED 96
#define CLF_MAX_LAST_CHANCE 8
#define CLF_ADDR_SLOTS 128
#define CLF_RELOG_MS 30000u
#define CLF_CODE_ACCESS_VIOLATION 0xC0000005u
#define CLF_CODE_FAIL_FAST 0xC0000602u
#define CLF_CODE_STACK_BUFFER 0xC0000409u
#define CLF_CODE_STACK_OVERFLOW 0xC00000FDu
#define CLF_CODE_HEAP_CORRUPTION 0xC0000374u
/* What raised a fault. Anything but CLF_CLASS_AC is noise. */
typedef enum {
CLF_CLASS_AC = 0, /* AC, Decal native code, the engine's native code: counted */
CLF_CLASS_NETFX = 1, /* the .NET Framework (Decal's managed plugins) */
CLF_CLASS_MANAGED = 2, /* the engine's CoreCLR runtime and its JIT code */
} clf_class;
typedef enum {
CLF_SKIP_CODE = 0, /* not a code the logger writes */
CLF_LOG_COUNTED, /* write it; first sighting, charged to the limit */
CLF_LOG_NOISE, /* write it; first sighting of noise, not charged */
CLF_LOG_REPEAT, /* write it again; a repeat (see hits) */
CLF_LOG_LAST_CHANCE, /* write it; unhandled */
CLF_SKIP_REPEAT, /* a repeat not due to be written */
CLF_SKIP_CAP, /* limit reached */
} clf_decision;
typedef struct {
unsigned int addr;
unsigned int hits; /* sightings, the first included */
unsigned int lastWriteMs;
unsigned char cls; /* clf_class */
unsigned char used;
} clf_slot;
typedef struct {
clf_slot slots[CLF_ADDR_SLOTS];
unsigned int counted; /* AC first sightings charged to the limit */
unsigned int lastChance;
unsigned int noiseRepeats; /* noise repeats not written */
unsigned int otherRepeats; /* other repeats not written */
unsigned int overCap; /* not written: limit reached */
unsigned int untracked; /* AC addresses written but not tracked (table full of AC) */
} clf_state;
static int clf_is_logged_code(unsigned int code)
{
return code == CLF_CODE_ACCESS_VIOLATION || code == CLF_CODE_FAIL_FAST
|| code == CLF_CODE_STACK_BUFFER || code == CLF_CODE_STACK_OVERFLOW
|| code == CLF_CODE_HEAP_CORRUPTION;
}
static int clf_wide_ieq(const wchar_t* a, const char* b)
{
if (!a || !b) return 0;
for (;;) {
wchar_t ca = *a++;
char cb = *b++;
if (ca >= L'A' && ca <= L'Z') ca = (wchar_t)(ca - L'A' + L'a');
if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a');
if (ca != (wchar_t)(unsigned char)cb) return 0;
if (ca == 0) return 1;
}
}
/* Class of a module, by its leaf file name. */
static clf_class clf_module_class(const wchar_t* leaf)
{
if (clf_wide_ieq(leaf, "clr.dll") || clf_wide_ieq(leaf, "mscorwks.dll")
|| clf_wide_ieq(leaf, "mscorlib.dll") || clf_wide_ieq(leaf, "mscorlib.ni.dll"))
return CLF_CLASS_NETFX;
if (clf_wide_ieq(leaf, "coreclr.dll") || clf_wide_ieq(leaf, "clrjit.dll")
|| clf_wide_ieq(leaf, "System.Private.CoreLib.dll"))
return CLF_CLASS_MANAGED;
return CLF_CLASS_AC;
}
/*
* Class of a first-chance exception. faultClass: class of the faulting module (AC when in
* no module). faultInNoModule: the faulting address is in no module (JIT code).
* firstFrameClass: class of the nearest module-resolved code pointer on the stack.
*/
static clf_class clf_classify(unsigned int code, clf_class faultClass, int faultInNoModule, clf_class firstFrameClass)
{
if (code != CLF_CODE_ACCESS_VIOLATION) return CLF_CLASS_AC;
if (faultClass != CLF_CLASS_AC) return faultClass;
if (faultInNoModule) return firstFrameClass;
return CLF_CLASS_AC;
}
static clf_slot* clf_find(clf_state* s, unsigned int addr)
{
int i;
for (i = 0; i < CLF_ADDR_SLOTS; i++)
if (s->slots[i].used && s->slots[i].addr == addr) return &s->slots[i];
return 0;
}
static int clf_is_pow2(unsigned int v) { return v != 0 && (v & (v - 1)) == 0; }
/* A repeat at a tracked address. *hits gets the sighting count. */
static clf_decision clf_repeat(clf_state* s, clf_slot* slot, unsigned int code, unsigned int nowMs, unsigned int* hits)
{
slot->hits++;
if (hits) *hits = slot->hits;
if (clf_is_pow2(slot->hits) || nowMs - slot->lastWriteMs >= CLF_RELOG_MS || code != CLF_CODE_ACCESS_VIOLATION) {
slot->lastWriteMs = nowMs;
return CLF_LOG_REPEAT;
}
if (slot->cls != CLF_CLASS_AC) s->noiseRepeats++; else s->otherRepeats++;
return CLF_SKIP_REPEAT;
}
/* A free slot, else the least recently written noise slot, else none. */
static clf_slot* clf_take_slot(clf_state* s)
{
clf_slot* oldest = 0;
int i;
for (i = 0; i < CLF_ADDR_SLOTS; i++)
if (!s->slots[i].used) return &s->slots[i];
for (i = 0; i < CLF_ADDR_SLOTS; i++) {
clf_slot* c = &s->slots[i];
if (c->cls == CLF_CLASS_AC) continue;
if (!oldest || (int)(c->lastWriteMs - oldest->lastWriteMs) < 0) oldest = c;
}
return oldest;
}
/* First sighting of an address (clf_find found nothing). */
static clf_decision clf_new(clf_state* s, unsigned int code, unsigned int addr, clf_class cls, unsigned int nowMs)
{
clf_slot* slot;
if (cls == CLF_CLASS_AC) {
if (s->counted >= CLF_MAX_COUNTED) { s->overCap++; return CLF_SKIP_CAP; }
s->counted++;
}
slot = clf_take_slot(s);
if (slot) {
slot->addr = addr;
slot->hits = 1;
slot->lastWriteMs = nowMs;
slot->cls = (unsigned char)cls;
slot->used = 1;
} else {
s->untracked++;
}
(void)code;
return cls == CLF_CLASS_AC ? CLF_LOG_COUNTED : CLF_LOG_NOISE;
}
/* The whole first-chance decision in one call (the logger splits it to skip the module
* lookup for repeats). *hits gets the sighting count (1 for a first sighting). */
static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned int addr, clf_class cls,
unsigned int nowMs, unsigned int* hits)
{
clf_slot* slot;
if (hits) *hits = 1;
if (!clf_is_logged_code(code)) return CLF_SKIP_CODE;
slot = clf_find(s, addr);
if (slot) return clf_repeat(s, slot, code, nowMs, hits);
return clf_new(s, code, addr, cls, nowMs);
}
#define CLF_RING 16
/* One first-chance record kept for a later flush. */
typedef struct {
unsigned int seq; /* 1-based push number; 0 = empty */
unsigned int addr, code, eip, tid, tickMs, hits;
unsigned char written; /* written as an entry of its own when it happened */
} clf_rec;
/*
* The last CLF_RING first-chance records. Each record is offered to one flush only:
* a second flush (one exit path calling another) writes nothing new. Sequence numbers
* are 32-bit; a process would need 4 billion logged-code exceptions to wrap them.
*/
typedef struct {
clf_rec r[CLF_RING];
unsigned int pushed; /* records pushed in total */
unsigned int flushedTo; /* every record up to this seq has been offered to a flush */
} clf_ring;
static void clf_ring_push(clf_ring* g, unsigned int addr, unsigned int code, unsigned int eip,
unsigned int tid, unsigned int tickMs, unsigned int hits, int written)
{
clf_rec* x = &g->r[g->pushed % CLF_RING];
g->pushed++;
x->seq = g->pushed;
x->addr = addr;
x->code = code;
x->eip = eip;
x->tid = tid;
x->tickMs = tickMs;
x->hits = hits;
x->written = (unsigned char)(written ? 1 : 0);
}
/*
* Flush: copies into out[CLF_RING], oldest first, the held records that were not written
* and not offered to an earlier flush, and marks everything pushed so far as offered.
* Returns how many were copied. *older gets the records pushed since the last flush that
* the ring no longer holds (written or not).
*/
static int clf_ring_take(clf_ring* g, clf_rec* out, unsigned int* older)
{
unsigned int first = g->pushed > CLF_RING ? g->pushed - CLF_RING : 0; /* held: first+1..pushed */
unsigned int from = g->flushedTo, s;
int n = 0;
if (older) *older = from < first ? first - from : 0;
if (from < first) from = first;
for (s = from + 1; s <= g->pushed; s++) {
const clf_rec* x = &g->r[(s - 1) % CLF_RING];
if (!x->written) out[n++] = *x;
}
g->flushedTo = g->pushed;
return n;
}
/* The last-chance (unhandled) filter. Any code: whatever reaches it is fatal. */
static clf_decision clf_last_chance(clf_state* s)
{
if (s->lastChance >= CLF_MAX_LAST_CHANCE) return CLF_SKIP_CAP;
s->lastChance++;
return CLF_LOG_LAST_CHANCE;
}
#endif

View file

@ -26,12 +26,39 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
/* File version of this native module (bump with every behavioural change). */
#define RC_SEH_TRAMPOLINE_VERSION 6 /* v6: AwfulWaffle's crash logger (per-address dedupe, pid/date,
flush ring, RC_FlushCrashLog, module cache) merged with v3-v5;
v5: crash log handle opened once at install; no CreateFileW
while an exception is being dispatched */
/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */
static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */
static void CrashLoggerFlushOnExit(void);
/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an
* access violation on this thread is about to be caught by our own __except. */
#define RC_SEH_ENTER() (++t_sehDepth)
#define RC_SEH_LEAVE() (--t_sehDepth)
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved)
{
(void)hModule; (void)ul_reason; (void)lpReserved;
(void)hModule;
/* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess),
* which is how AC's own crash handling ends the process: write out any recent
* first-chance AVs so a crash AC swallowed still leaves a trace. */
if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) {
CrashLoggerFlushOnExit();
}
return TRUE;
}
/* Diagnostic: native module version so the engine log can confirm which build is loaded. */
__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void)
{
return RC_SEH_TRAMPOLINE_VERSION;
}
/* ── Cdecl helpers ─────────────────────────────────────────────────────── */
/* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */
@ -40,14 +67,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result)
{
*out_result = NULL;
RC_SEH_ENTER();
__try {
*out_result = fn(arg);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -57,14 +87,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result)
{
*out_result = NULL;
RC_SEH_ENTER();
__try {
*out_result = fn();
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -73,13 +106,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char);
__declspec(dllexport) int __cdecl
SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2)
{
RC_SEH_ENTER();
__try {
fn(arg1, arg2);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -95,13 +131,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s
__declspec(dllexport) int __cdecl
SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId)
{
RC_SEH_ENTER();
__try {
((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -152,14 +191,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg,
unsigned char* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -171,14 +213,17 @@ __declspec(dllexport) int __cdecl
SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_uint_noarg(fn, this_ptr);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -209,36 +254,124 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2,
int* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
/* ── Process-wide native crash logger (VEH) ───────────────────────────────
/* -- Process-wide native crash logger (VEH + last-chance filter) -----------
* 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).
* dedicated file BEFORE the process dies, for the exceptions that bypass the
* engine's managed handlers: 0xC0000005 (AV / corrupted state; CoreCLR will not
* let a managed catch handle one raised in AC code under a managed detour, it
* fail-fasts instead), 0xC0000602 (fail-fast), 0xC0000409 (stack buffer
* overrun), 0xC00000FD (stack overflow) and 0xC0000374 (heap corruption).
* The vectored handler is registered FIRST, so it sees an AV before CoreCLR
* turns it into anything: the entry names the real faulting address and module.
*
* Which entries are written is CrashLogFilter.h's rule (once per address, a repeat
* again at a power-of-two count or after 30 s; .NET Framework and CoreCLR noise not
* charged to the limit; a last-chance entry always). Each entry carries the process id,
* thread id, date and time.
*
* 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.
* fail-fast on an AC-owned thread. It only OBSERVES: both handlers return
* EXCEPTION_CONTINUE_SEARCH (the last-chance one first calls the filter it
* replaced) 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. All buffers are static and used under one
* spin lock (with its owner's thread id, so a fault inside the logger on the same
* thread is passed on, never waited on): a stack overflow leaves the faulting
* thread about one page of stack. x86 (32-bit) context fields only.
*/
#include "CrashLogFilter.h"
/*
* Exception time does as little as it can: the address dedupe runs first (most
* exceptions are repeats and stop there), module names come from a cache built
* outside exception time (install, then RC_RefreshCrashLoggerModules from the engine's
* heartbeat), and the log file is opened once at install, so writing an entry is
* formatting plus WriteFile. Only an address the cache does not cover (a module loaded
* since the last refresh) falls back to GetModuleHandleExW, for the faulting address
* and eip only.
*
* NEVER call CreateFileW (or anything else the engine detours with a managed hook:
* CreateFileA, MessageBoxA/W, ExitProcess, TerminateProcess, RtlExitUserProcess,
* NtTerminateProcess) from the handlers, the flush or DllMain. DatFileShareHooks detours
* kernel32!CreateFileW with a MANAGED delegate; our VEH runs first, on the faulting thread,
* and for a fault in managed code that thread is still in cooperative GC mode, so entering
* the detour is a reverse P/Invoke from cooperative mode: CoreCLR's
* ReversePInvokeBadTransition -> HandleFatalError (event 1023, exit 0x80131506). Seven
* client deaths 2026-09-29..10-12 were that (fixed in v5). The file is opened once, from
* RC_InstallCrashLogger, a normal P/Invoke in preemptive mode.
*
* v6 (merge of AwfulWaffle's logger with v3-v5): AVs inside our own SEH_* wrappers
* (t_sehDepth > 0, which our __except catches) are not written one by one, only kept in
* the flush ring; the Client::UseTime guard (v4) writes its caught AV through this
* writer; process exit (DllMain) flushes ring records from the last 30 s, as v2-v5 did.
*/
#define CL_EXIT_FLUSH_WINDOW_MS 30000u /* ring records this recent are flushed at exit */
#define CL_MAX_GAMETICK 16 /* game-tick guard records per process */
#define CL_MOD_MAX 384
typedef struct {
unsigned int base, end; /* [base, end) */
unsigned char cls; /* clf_class */
char leaf[48]; /* ASCII leaf name, truncated */
} cl_mod;
typedef struct {
cl_mod mods[CL_MOD_MAX];
int count;
} cl_mod_table;
static wchar_t g_crashLogPath[MAX_PATH];
static volatile LONG g_crashCount = 0;
static HANDLE g_logHandle = INVALID_HANDLE_VALUE;
static PVOID g_vehHandle = NULL;
static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL;
static volatile LONG g_logOwner = 0; /* thread id holding the logger, 0 = free */
static clf_state g_filter; /* under g_logOwner */
static clf_ring g_ring; /* under g_logOwner: recent first-chance records */
static clf_rec g_flushRecs[CLF_RING];/* under g_logOwner */
static char g_buf[4096]; /* under g_logOwner */
static wchar_t g_wpath[MAX_PATH]; /* under g_logOwner */
static char g_fallbackLeaf[48]; /* under g_logOwner */
static cl_mod_table g_modTables[2]; /* double buffer: refresh builds the inactive one */
static volatile LONG g_modActive = -1; /* index of the published table, -1 = none */
static volatile LONG g_modRefreshing = 0;
static volatile LONG g_gameTickRecords = 0;
static __declspec(thread) int t_inUef; /* last-chance filter running (guards chain cycles) */
typedef BOOL (WINAPI *PFN_EnumMods)(HANDLE, HMODULE*, DWORD, LPDWORD);
typedef BOOL (WINAPI *PFN_ModInfo)(HANDLE, HMODULE, void*, DWORD);
typedef DWORD (WINAPI *PFN_BaseName)(HANDLE, HMODULE, LPWSTR, DWORD);
typedef struct { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } cl_modinfo;
static int cl_lock(void)
{
LONG me = (LONG)GetCurrentThreadId();
int i;
if (g_logOwner == me) return 0; /* faulted inside the logger: pass it on */
for (i = 0; i < 20000; i++) {
if (InterlockedCompareExchange(&g_logOwner, me, 0) == 0) return 1;
YieldProcessor();
if ((i & 0xFF) == 0xFF) SwitchToThread();
}
return 0; /* owner stuck (suspended?): skip this entry */
}
static void cl_unlock(void) { InterlockedExchange(&g_logOwner, 0); }
static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; }
@ -260,128 +393,428 @@ static char* cl_u(char* p, unsigned int v)
return p;
}
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
static char* cl_sym(char* p, unsigned int addr)
static char* cl_u2(char* p, unsigned int v) { if (v < 10) { *p++ = '0'; } return cl_u(p, v); }
/*
* Rebuild the module cache (NOT at exception time: it takes the loader lock). Builds the
* table no reader is using and publishes it with one interlocked store; refreshes are
* serialized and seconds apart, so a reader never sees its table rebuilt under it.
*/
__declspec(dllexport) void __cdecl
RC_RefreshCrashLoggerModules(void)
{
static PFN_EnumMods pEnum;
static PFN_ModInfo pInfo;
static PFN_BaseName pName;
HMODULE mods[CL_MOD_MAX];
DWORD needed = 0, n, i;
HANDLE self = GetCurrentProcess();
LONG active, next;
cl_mod_table* t;
if (InterlockedCompareExchange(&g_modRefreshing, 1, 0) != 0) return;
if (!pEnum) {
HMODULE k32 = GetModuleHandleW(L"kernel32.dll");
pEnum = (PFN_EnumMods)GetProcAddress(k32, "K32EnumProcessModules");
pInfo = (PFN_ModInfo)GetProcAddress(k32, "K32GetModuleInformation");
pName = (PFN_BaseName)GetProcAddress(k32, "K32GetModuleBaseNameW");
}
if (!pEnum || !pInfo || !pName || !pEnum(self, mods, sizeof(mods), &needed)) {
InterlockedExchange(&g_modRefreshing, 0);
return;
}
n = needed / sizeof(HMODULE);
if (n > CL_MOD_MAX) n = CL_MOD_MAX;
active = g_modActive;
next = active == 0 ? 1 : 0;
t = &g_modTables[next];
t->count = 0;
for (i = 0; i < n; i++) {
cl_modinfo mi;
wchar_t name[64];
DWORD len, k;
cl_mod* m;
if (!pInfo(self, mods[i], &mi, sizeof(mi))) continue;
len = pName(self, mods[i], name, 63);
name[len < 63 ? len : 63] = 0;
m = &t->mods[t->count++];
m->base = (unsigned int)(UINT_PTR)mi.lpBaseOfDll;
m->end = m->base + mi.SizeOfImage;
m->cls = (unsigned char)clf_module_class(name);
for (k = 0; k < sizeof(m->leaf) - 1 && name[k]; k++)
m->leaf[k] = name[k] < 128 ? (char)name[k] : '?';
m->leaf[k] = 0;
}
InterlockedExchange(&g_modActive, next);
InterlockedExchange(&g_modRefreshing, 0);
}
/* Cached module containing addr, or NULL. No API calls. */
static const cl_mod* cl_mod_cached(unsigned int addr)
{
LONG a = g_modActive;
const cl_mod_table* t;
int i;
if (a < 0) return NULL;
t = &g_modTables[a];
for (i = 0; i < t->count; i++)
if (addr >= t->mods[i].base && addr < t->mods[i].end) return &t->mods[i];
return NULL;
}
/*
* Module of addr: the cache, then (allowFallback) the loader. Under the lock. Returns
* the leaf and sets *base and *cls, or NULL (no module: JIT code or garbage).
*/
static const char* cl_module(unsigned int addr, int allowFallback, unsigned int* base, clf_class* cls)
{
const cl_mod* m = cl_mod_cached(addr);
HMODULE hm = NULL;
DWORD n, i, leaf = 0, k;
if (m) { *base = m->base; *cls = (clf_class)m->cls; return m->leaf; }
if (!allowFallback) return 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]; }
if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) return NULL;
n = GetModuleFileNameW(hm, g_wpath, MAX_PATH);
if (n >= MAX_PATH) n = MAX_PATH - 1;
g_wpath[n] = 0;
for (i = 0; i < n; i++) { if (g_wpath[i] == L'\\' || g_wpath[i] == L'/') leaf = i + 1; }
*base = (unsigned int)(UINT_PTR)hm;
*cls = clf_module_class(g_wpath + leaf);
for (k = 0; k < sizeof(g_fallbackLeaf) - 1 && g_wpath[leaf + k]; k++)
g_fallbackLeaf[k] = g_wpath[leaf + k] < 128 ? (char)g_wpath[leaf + k] : '?';
g_fallbackLeaf[k] = 0;
return g_fallbackLeaf;
}
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
static char* cl_sym(char* p, unsigned int addr, int allowFallback)
{
unsigned int base;
clf_class cls;
const char* leaf = cl_module(addr, allowFallback, &base, &cls);
if (leaf) {
p = cl_str(p, leaf);
p = cl_str(p, "+");
p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm);
p = cl_hex(p, addr - base);
} else {
p = cl_hex(p, addr);
}
return p;
}
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
/* Class of the nearest cached-module code pointer on the stack (AC if none found). */
static clf_class cl_first_frame_class(unsigned int esp)
{
DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) {
return EXCEPTION_CONTINUE_SEARCH;
clf_class result = CLF_CLASS_AC;
__try {
unsigned int* sp = (unsigned int*)(UINT_PTR)esp;
int i;
for (i = 0; i < 512; i++) {
unsigned int v = sp[i];
const cl_mod* m;
if (v <= 0x00401000u || v >= 0x7FFF0000u) continue;
m = cl_mod_cached(v);
if (m) { result = (clf_class)m->cls; break; }
}
}
if (InterlockedIncrement(&g_crashCount) > 24) {
return EXCEPTION_CONTINUE_SEARCH;
__except (EXCEPTION_EXECUTE_HANDLER) { result = CLF_CLASS_AC; }
return result;
}
static void cl_write(const char* p, DWORD n)
{
DWORD wr;
if (g_logHandle != INVALID_HANDLE_VALUE) WriteFile(g_logHandle, p, n, &wr, NULL);
}
/* Append " pid=N tid=N date=YYYY-MM-DD time=HH:MM:SS" (local time). */
static char* cl_stamp(char* p)
{
SYSTEMTIME st;
p = cl_str(p, " pid=");
p = cl_u(p, GetCurrentProcessId());
p = cl_str(p, " tid=");
p = cl_u(p, GetCurrentThreadId());
GetLocalTime(&st);
p = cl_str(p, " date=");
p = cl_u(p, st.wYear); p = cl_str(p, "-");
p = cl_u2(p, st.wMonth); p = cl_str(p, "-");
p = cl_u2(p, st.wDay);
p = cl_str(p, " time=");
p = cl_u2(p, st.wHour); p = cl_str(p, ":");
p = cl_u2(p, st.wMinute); p = cl_str(p, ":");
p = cl_u2(p, st.wSecond);
return p;
}
static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits)
{
char* p = g_buf;
CONTEXT* c = ep->ContextRecord;
DWORD code = ep->ExceptionRecord->ExceptionCode;
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
if (g_logHandle == INVALID_HANDLE_VALUE) return;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (");
p = cl_str(p, kind);
p = cl_str(p, ") ====\r\n code=");
p = cl_hex(p, code);
p = cl_str(p, " exAddr=");
p = cl_sym(p, exAddr, 1);
if (hits > 1) { p = cl_str(p, " repeat="); p = cl_u(p, hits); }
p = cl_stamp(p);
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 logged=");
p = cl_u(p, g_filter.counted);
p = cl_str(p, "/");
p = cl_u(p, CLF_MAX_COUNTED);
p = cl_str(p, " noiseRepeats=");
p = cl_u(p, g_filter.noiseRepeats);
p = cl_str(p, " otherRepeats=");
p = cl_u(p, g_filter.otherRepeats);
p = cl_str(p, " overCap=");
p = cl_u(p, g_filter.overCap);
p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip, 1);
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");
cl_write(g_buf, (DWORD)(p - g_buf));
__try {
unsigned int* sp = (unsigned int*)(UINT_PTR)c->Esp;
int i, emitted = 0;
for (i = 0; i < 4096 && emitted < 96; i++) {
unsigned int v = sp[i];
if (v > 0x00401000u && v < 0x7FFF0000u && cl_mod_cached(v)) {
char* q = g_buf;
q = cl_str(q, " +");
q = cl_hex(q, (unsigned int)(i * 4));
q = cl_str(q, " ");
q = cl_sym(q, v, 0);
q = cl_str(q, "\r\n");
cl_write(g_buf, (DWORD)(q - g_buf));
emitted++;
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
const char* m = " <stack sweep faulted>\r\n";
cl_write(m, (DWORD)lstrlenA(m));
}
{
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);
const char* e = "==== END NATIVE CRASH ====\r\n";
cl_write(e, (DWORD)lstrlenA(e));
}
}
/*
* Under the lock: write the recent first-chance records that were not written one by one
* (clf_ring_take), oldest first, so the log ends with the newest, usually the fatal hit.
* Module names from the cache only: no loader call on a dying process.
*/
static void cl_flush_locked(const char* reason, unsigned int code, unsigned int maxAgeMs)
{
unsigned int older = 0;
int n = clf_ring_take(&g_ring, g_flushRecs, &older), i;
char* p;
if (maxAgeMs != 0) {
/* v6: process exit (DllMain) keeps only the recent records, as v2-v5 did; a
* contained AV from long before a normal exit is not crash evidence. */
unsigned int now = GetTickCount();
int k = 0;
for (i = 0; i < n; i++)
if (now - g_flushRecs[i].tickMs <= maxAgeMs) g_flushRecs[k++] = g_flushRecs[i];
n = k;
}
if (n == 0 || g_logHandle == INVALID_HANDLE_VALUE) return;
p = g_buf;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (flush: ");
p = cl_str(p, reason);
p = cl_str(p, ") ====\r\n code=");
p = cl_hex(p, code);
p = cl_stamp(p);
p = cl_str(p, "\r\n recent first-chance records not written one by one, oldest first (");
p = cl_u(p, (unsigned int)n);
p = cl_str(p, " held");
if (older) { p = cl_str(p, ", "); p = cl_u(p, older); p = cl_str(p, " older ones no longer held"); }
p = cl_str(p, "):\r\n");
cl_write(g_buf, (DWORD)(p - g_buf));
for (i = 0; i < n; i++) {
const clf_rec* x = &g_flushRecs[i];
p = g_buf;
p = cl_str(p, " exAddr=");
p = cl_sym(p, x->addr, 0);
p = cl_str(p, " code=");
p = cl_hex(p, x->code);
p = cl_str(p, " eip=");
p = cl_sym(p, x->eip, 0);
p = cl_str(p, " tid=");
p = cl_u(p, x->tid);
p = cl_str(p, " tick=");
p = cl_u(p, x->tickMs);
p = cl_str(p, " repeat=");
p = cl_u(p, x->hits);
p = cl_str(p, "\r\n");
cl_write(g_buf, (DWORD)(p - g_buf));
}
{
const char* e = "==== END NATIVE CRASH ====\r\n";
cl_write(e, (DWORD)lstrlenA(e));
}
}
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
{
DWORD code = ep->ExceptionRecord->ExceptionCode;
if (!clf_is_logged_code(code)) {
return EXCEPTION_CONTINUE_SEARCH; /* cheap exit, no lock, for C++/CLR throws */
}
if (!cl_lock()) { return EXCEPTION_CONTINUE_SEARCH; }
if (code == CLF_CODE_ACCESS_VIOLATION && t_sehDepth > 0) {
/* v6 (v2's rule): an SEH_* wrapper's __except catches this AV (the game-tick guard
* writes its own record), so it is not written one by one. Kept in the flush ring
* only, in case a handler further up turns the process exit into a crash. */
clf_ring_push(&g_ring, (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress, code,
ep->ContextRecord->Eip, GetCurrentThreadId(), GetTickCount(), 1, 0);
cl_unlock();
return EXCEPTION_CONTINUE_SEARCH;
}
{
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
unsigned int now = GetTickCount();
unsigned int hits = 1;
int written = 0;
clf_slot* slot = clf_find(&g_filter, exAddr);
if (slot) {
/* A repeat: decided without touching any module. */
if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) {
cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits);
written = 1;
}
} else {
unsigned int base;
clf_class faultCls = CLF_CLASS_AC;
const char* leaf = cl_module(exAddr, 1, &base, &faultCls);
clf_class cls = clf_classify(code, leaf ? faultCls : CLF_CLASS_AC, leaf == NULL,
leaf == NULL && code == CLF_CODE_ACCESS_VIOLATION ? cl_first_frame_class(ep->ContextRecord->Esp) : CLF_CLASS_AC);
clf_decision d = clf_new(&g_filter, code, exAddr, cls, now);
if (d == CLF_LOG_COUNTED)
cl_write_entry(ep, "first-chance", 1);
else if (d == CLF_LOG_NOISE)
cl_write_entry(ep, cls == CLF_CLASS_NETFX
? "first-chance, .NET Framework noise, not counted"
: "first-chance, managed (CoreCLR) noise, not counted", 1);
written = d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE;
}
/* Kept for a flush (memory only): the fatal hit is often one not written here. */
clf_ring_push(&g_ring, exAddr, code, ep->ContextRecord->Eip, GetCurrentThreadId(), now, hits, written);
}
cl_unlock();
return EXCEPTION_CONTINUE_SEARCH;
}
/* Install the VEH once. logPath = wide path to the dedicated crash log. */
/* Last chance: nothing handled it. Logged, then the filter this one replaced decides. */
static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep)
{
LONG verdict = EXCEPTION_CONTINUE_SEARCH;
/* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */
if (t_inUef) { return EXCEPTION_CONTINUE_SEARCH; }
t_inUef = 1;
if (cl_lock()) {
cl_flush_locked("last chance", ep->ExceptionRecord->ExceptionCode, 0);
if (clf_last_chance(&g_filter) == CLF_LOG_LAST_CHANCE)
cl_write_entry(ep, "LAST-CHANCE, unhandled", 1);
cl_unlock();
}
if (g_prevFilter && g_prevFilter != CrashLastChance) {
verdict = g_prevFilter(ep);
}
t_inUef = 0;
return verdict;
}
/*
* A crash exit is under way (the engine's TerminateProcess / NtTerminateProcess /
* ExitProcess / RtlExitUserProcess detours, for a crash code): write the recent
* first-chance records not written one by one. Each record is written once, so the
* second of two nested exit paths writes nothing. exitCode 0 is the engine's priming
* call and does nothing.
*/
__declspec(dllexport) void __cdecl
RC_FlushCrashLog(unsigned int exitCode)
{
if (exitCode == 0) return;
if (!cl_lock()) return;
cl_flush_locked("crash exit", exitCode, 0);
cl_unlock();
}
/* DllMain, process exit (v2-v5 behaviour): ring records from the last 30 s that were not
* written one by one. AC's own crash handling ends with ExitProcess, sometimes with a code
* the engine does not count as a crash. Cache-only module names; no loader call. */
static void CrashLoggerFlushOnExit(void)
{
if (g_logHandle == INVALID_HANDLE_VALUE) { return; }
if (!cl_lock()) { return; }
cl_flush_locked("process exit", 0, CL_EXIT_FLUSH_WINDOW_MS);
cl_unlock();
}
/*
* Install the VEH once and (re-)assert the last-chance filter. logPath = wide path to the
* dedicated crash log, opened HERE (a normal P/Invoke, preemptive mode; never from a
* handler, see the CreateFileW note above) for the life of the process (append, shared
* for reading, writing and deleting). Safe to call more than once (every engine
* generation does): a later call re-installs the filter if AC or a runtime replaced it,
* and a different path switches files. Also (re)builds the module cache.
*/
__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;
LPTOP_LEVEL_EXCEPTION_FILTER prev;
if (logPath && logPath[0]) {
int i = 0, same = 1;
for (; logPath[i] && i < MAX_PATH - 1; i++) {
if (g_crashLogPath[i] != logPath[i]) { same = 0; }
}
if (g_crashLogPath[i] != 0) { same = 0; }
if ((!same || g_logHandle == INVALID_HANDLE_VALUE) && cl_lock()) {
HANDLE h;
for (i = 0; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; }
g_crashLogPath[i] = 0;
h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h != INVALID_HANDLE_VALUE) {
HANDLE old = g_logHandle;
g_logHandle = h;
if (old != INVALID_HANDLE_VALUE) { CloseHandle(old); }
}
cl_unlock();
}
}
RC_RefreshCrashLoggerModules();
if (!g_vehHandle) {
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
}
prev = SetUnhandledExceptionFilter(CrashLastChance);
if (prev != CrashLastChance) {
g_prevFilter = prev;
}
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
}
/* ── Tagged-text parser guard (native MinHook detour body) ────────────────
@ -437,3 +870,87 @@ __declspec(dllexport) unsigned int __cdecl RC_TagParserSkipCount(void)
{
return (unsigned int)g_tagParserSkips;
}
/* ── Game-tick guard (v4) ─────────────────────────────────────────────────
* Client::UseTime (0x00411FA0) is detoured by a MANAGED hook. An AV inside AC's tick
* (e.g. chatclient.dll+0x1050 copying a ~2 MB chat-server message from a null buffer,
* 2026-10-11, two clients in the same second) unwinds into that managed frame, which
* CoreCLR treats as an unhandled exception and fail-fasts; AC's own handlers further
* up never run. This wrapper catches the AV in native code first.
*
* The filter runs on the faulting thread before unwinding, so it records the faulting
* address, the data address and the module name, and writes a full record (registers +
* stack sweep) to the crash log through the logger's writer (v6), capped at
* CL_MAX_GAMETICK records per process. No CreateFileW here either (see the logger). */
typedef struct {
unsigned int exAddr;
unsigned int dataAddr;
char* module;
int moduleCap;
} GT_FAULT;
/* int __thiscall fn(this) — no stack args; EAX is returned whole, as AC's caller tests AL. */
static int __cdecl _helper_thiscall_int_noarg(void* fn_ptr, void* this_ptr)
{
int result = 0;
__asm {
mov ecx, this_ptr
call fn_ptr
mov result, eax
}
return result;
}
static int gt_filter(PEXCEPTION_POINTERS ep, GT_FAULT* f)
{
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) {
return EXCEPTION_CONTINUE_SEARCH;
}
f->exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
f->dataAddr = ep->ExceptionRecord->NumberParameters >= 2
? (unsigned int)ep->ExceptionRecord->ExceptionInformation[1] : 0;
if (f->module && f->moduleCap > 0) { f->module[0] = 0; }
if (cl_lock()) {
unsigned int base = 0;
clf_class cls;
const char* leaf = cl_module(f->exAddr, 1, &base, &cls);
if (leaf && f->module && f->moduleCap > 0) {
int k = 0;
for (; leaf[k] && k < f->moduleCap - 1; k++) { f->module[k] = leaf[k]; }
f->module[k] = 0;
}
if (InterlockedIncrement(&g_gameTickRecords) <= CL_MAX_GAMETICK) {
cl_write_entry(ep, "AV CAUGHT IN GAME TICK (Client::UseTime guard; tick dropped, client kept running)", 1);
}
cl_unlock();
if (leaf && f->module && f->module[0]) {
f->exAddr -= base; /* module-relative when resolved */
}
}
return EXCEPTION_EXECUTE_HANDLER;
}
/* Calls int __thiscall fn(this) under SEH. Returns 1 when the call completed, 0 when an
* AV was caught; on 0, *out_exAddr is module-relative if module[0] != 0, else absolute. */
__declspec(dllexport) int __cdecl
SEH_GameTickThiscall(void* fn, void* this_ptr, int* out_result,
unsigned int* out_exAddr, unsigned int* out_dataAddr,
char* module, int moduleCap)
{
GT_FAULT f;
f.exAddr = 0; f.dataAddr = 0; f.module = module; f.moduleCap = moduleCap;
*out_result = 0; *out_exAddr = 0; *out_dataAddr = 0;
if (module && moduleCap > 0) { module[0] = 0; }
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_int_noarg(fn, this_ptr);
}
__except(gt_filter(GetExceptionInformation(), &f)) {
RC_SEH_LEAVE();
*out_exAddr = f.exAddr;
*out_dataAddr = f.dataAddr;
return 0;
}
RC_SEH_LEAVE();
return 1;
}

View file

@ -0,0 +1,241 @@
/*
* CrashLogFilterTests.c - offline checks for CrashLogFilter.h (the native crash logger's
* filter). Build and run with Run-CrashLogFilterTests.ps1 (x86 MSVC). Exit 0 = pass.
*/
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include "../CrashLogFilter.h"
static int g_checks, g_failed;
static void check(int ok, const char* what)
{
g_checks++;
if (ok) return;
g_failed++;
printf("[FAIL] %s\n", what);
}
#define AV CLF_CODE_ACCESS_VIOLATION
#define FC(s, code, addr, cls, now) clf_first_chance((s), (code), (addr), (cls), (now), &hits)
static int is_write(clf_decision d)
{
return d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE || d == CLF_LOG_REPEAT;
}
/* Seen in a real log: handled .NET Framework AVs at ONE address spent the old cap,
* and the fatal AC fault later was never written. */
static void netfx_noise_never_spends_the_limit(void)
{
static clf_state s;
unsigned int hits, i, written = 0;
for (i = 0; i < 500; i++)
if (is_write(FC(&s, AV, 0x433620C8u, CLF_CLASS_NETFX, 1000 + i * 10))) written++;
/* first + the power-of-two repeats 2,4,8,16,32,64,128,256 = 9 entries for 500 hits */
check(written == 9, "500 hits of one JIT-code AV: 9 entries (first + powers of two)");
check(s.counted == 0, "and never charged to the limit");
check(s.noiseRepeats == 491, "skipped repeats are counted as noise");
check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 7000) == CLF_LOG_COUNTED, "a later AC fault is still written");
}
/* A contained AV at a known address that later goes fatal. */
static void known_address_going_fatal_is_written(void)
{
static clf_state s;
unsigned int hits, i;
clf_decision d;
for (i = 0; i < 3; i++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000 + i);
d = FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1010);
check(d == CLF_LOG_REPEAT && hits == 4, "3 contained AVs, then a 4th (fatal) at the same address: written, repeat=4");
{
static clf_state t;
unsigned int now = 5000;
for (i = 0; i < 1000; i++) FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + i); /* within 1 s */
d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31000);
check(d == CLF_LOG_REPEAT && hits == 1001, "1000 repeats, then the same address 31 s later: written");
d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31001);
check(d == CLF_SKIP_REPEAT, "and the next one right after is not");
}
{
static clf_state u;
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 100);
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 101);
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 102); /* hits 3: skipped */
d = FC(&u, CLF_CODE_HEAP_CORRUPTION, 0x00500000u, CLF_CLASS_AC, 103);
check(d == CLF_LOG_REPEAT, "a non-AV code at a known address is always written");
}
{
static clf_state w; /* the 32-bit tick wrap */
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF000u);
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF001u);
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF002u);
d = FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0x00007000u); /* ~32 s later, past the wrap */
check(d == CLF_LOG_REPEAT, "the 30 s relog survives the GetTickCount wrap");
}
}
static void ac_faults_limited_per_distinct_address(void)
{
static clf_state s;
unsigned int hits, a;
for (a = 0; a < 50; a++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000);
check(s.counted == 1, "a repeating AC fault is charged once");
for (a = 1; a < CLF_MAX_COUNTED; a++)
check(FC(&s, AV, 0x00500000u + a * 16, CLF_CLASS_AC, 1000) == CLF_LOG_COUNTED,
"distinct addresses written up to the limit");
check(FC(&s, AV, 0x00700000u, CLF_CLASS_AC, 1000) == CLF_SKIP_CAP, "past the limit: skipped");
check(FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000) != CLF_SKIP_CAP,
"a known address is decided as a repeat, never by the limit");
}
static void codes(void)
{
static clf_state s;
unsigned int hits;
check(FC(&s, 0xC00000FDu, 0x1000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack overflow is logged");
check(FC(&s, 0xC0000374u, 0x2000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "heap corruption is logged");
check(FC(&s, 0xC0000409u, 0x3000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack buffer overrun is logged");
check(FC(&s, 0xC0000602u, 0x4000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "fail-fast is logged");
check(FC(&s, 0xE06D7363u, 0x5000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a C++ exception is not");
check(FC(&s, 0x80000003u, 0x6000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a breakpoint is not");
}
static void classification(void)
{
check(clf_module_class(L"clr.dll") == CLF_CLASS_NETFX && clf_module_class(L"MSCORLIB.NI.DLL") == CLF_CLASS_NETFX
&& clf_module_class(L"mscorwks.dll") == CLF_CLASS_NETFX && clf_module_class(L"mscorlib.dll") == CLF_CLASS_NETFX,
"the .NET Framework modules, any case");
check(clf_module_class(L"coreclr.dll") == CLF_CLASS_MANAGED && clf_module_class(L"clrjit.dll") == CLF_CLASS_MANAGED
&& clf_module_class(L"System.Private.CoreLib.dll") == CLF_CLASS_MANAGED,
"the engine's CoreCLR modules are managed noise");
check(clf_module_class(L"acclient.exe") == CLF_CLASS_AC && clf_module_class(L"clr.dllx") == CLF_CLASS_AC
&& clf_module_class(0) == CLF_CLASS_AC, "AC and near-misses are not noise");
check(clf_classify(AV, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_NETFX, "an AV in clr.dll is .NET Framework noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_NETFX) == CLF_CLASS_NETFX, "JIT code under clr frames: .NET Framework noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_MANAGED) == CLF_CLASS_MANAGED, "JIT code under CoreCLR frames: managed noise");
check(clf_classify(AV, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_MANAGED, "an AV in coreclr.dll: managed noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_AC) == CLF_CLASS_AC, "no module under AC frames: AC");
check(clf_classify(AV, CLF_CLASS_AC, 0, CLF_CLASS_NETFX) == CLF_CLASS_AC, "an AV in an AC module is AC whatever is below it");
check(clf_classify(CLF_CODE_STACK_OVERFLOW, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "a stack overflow is never noise");
check(clf_classify(CLF_CODE_HEAP_CORRUPTION, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "heap corruption is never noise");
}
static void managed_noise_is_its_own_bucket(void)
{
static clf_state s;
unsigned int hits, a;
for (a = 0; a < 40; a++)
check(FC(&s, AV, 0x70000000u + a * 16, CLF_CLASS_MANAGED, 1) == CLF_LOG_NOISE, "managed noise written once per address");
check(s.counted == 0, "and never charged to the AC limit");
}
static void last_chance_is_separate(void)
{
static clf_state s;
unsigned int hits, a;
int i, logged = 0;
for (a = 0; a < CLF_MAX_COUNTED + 5; a++)
FC(&s, AV, 0x00700000u + a * 16, CLF_CLASS_AC, 1);
check(s.counted == CLF_MAX_COUNTED, "first-chance limit reached");
check(clf_last_chance(&s) == CLF_LOG_LAST_CHANCE, "the unhandled one is still written");
for (i = 0; i < 20; i++)
if (clf_last_chance(&s) == CLF_LOG_LAST_CHANCE) logged++;
check(logged == CLF_MAX_LAST_CHANCE - 1, "last-chance has its own small limit");
}
static void full_table_evicts_oldest_noise(void)
{
static clf_state s;
unsigned int hits, a;
clf_decision d;
for (a = 0; a < CLF_ADDR_SLOTS; a++)
FC(&s, AV, 0x40000000u + a * 16, CLF_CLASS_NETFX, 1000 + a); /* noise fills it, 0x40000000 oldest */
check(s.counted == 0, "table full of .NET Framework addresses");
d = FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5000);
check(d == CLF_LOG_COUNTED, "an AC fault is written");
check(clf_find(&s, 0x0055FA24u) != 0, "and tracked, in the evicted slot");
check(clf_find(&s, 0x40000000u) == 0, "the least recently written noise slot was evicted");
check(clf_find(&s, 0x40000010u) != 0, "the next one was not");
check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5001) == CLF_LOG_REPEAT && hits == 2, "so its repeat is deduped");
d = FC(&s, AV, 0x41000000u, CLF_CLASS_NETFX, 6000);
check(d == CLF_LOG_NOISE, "a new .NET Framework address is written, evicting an older one");
check(clf_find(&s, 0x0055FA24u) != 0, "AC slots are never evicted");
}
#define FATAL_ADDR 0x00401234u
/* N contained hits at one address, then the fatal one, then
* a terminate from a handler, so no last-chance filter runs. The fatal hit (N+1) is not due
* a write, so only the ring's flush can put it in the log. */
static void fatal_repeat_recovered_by_flush(unsigned int n)
{
clf_state s;
clf_ring g;
clf_rec out[CLF_RING];
unsigned int hits, i, older, now = 5000;
clf_decision d;
int got;
memset(&s, 0, sizeof s);
memset(&g, 0, sizeof g);
for (i = 0; i < n; i++) {
d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + i);
clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + i, hits, is_write(d));
}
d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + n + 1500); /* the fatal hit, 1.5 s later */
check(d == CLF_SKIP_REPEAT && hits == n + 1, "fatal hit N+1 is not due a write: the dedupe alone loses it");
clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + n + 1500, hits, is_write(d));
got = clf_ring_take(&g, out, &older);
check(got >= 1, "the flush has records");
check(got >= 1 && out[got - 1].addr == FATAL_ADDR && out[got - 1].hits == n + 1
&& out[got - 1].tickMs == now + n + 1500, "the flush ends with the fatal hit (N+1)");
for (i = 0; i < (unsigned int)got; i++)
check(!out[i].written, "a flush never repeats a record written on its own");
check(clf_ring_take(&g, out, &older) == 0, "a second flush writes nothing");
}
static void ring_order_overflow_and_written(void)
{
clf_ring g;
clf_rec out[CLF_RING];
unsigned int i, older;
int got;
memset(&g, 0, sizeof g);
clf_ring_push(&g, 0x10, AV, 0, 1, 1, 1, 1); /* written */
clf_ring_push(&g, 0x20, AV, 0, 1, 2, 2, 0);
clf_ring_push(&g, 0x30, AV, 0, 1, 3, 1, 1); /* written */
clf_ring_push(&g, 0x40, AV, 0, 1, 4, 3, 0);
got = clf_ring_take(&g, out, &older);
check(got == 2 && out[0].addr == 0x20 && out[1].addr == 0x40, "only unwritten records, oldest first");
check(older == 0, "nothing lost under the ring size");
for (i = 0; i < 40; i++) clf_ring_push(&g, 0x1000 + i, AV, 0, 1, 100 + i, 2, 0);
got = clf_ring_take(&g, out, &older);
check(got == CLF_RING, "40 unwritten since the last flush: the ring holds the newest 16");
check(older == 24, "and reports the 24 it no longer holds");
check(out[0].addr == 0x1000 + 24 && out[CLF_RING - 1].addr == 0x1000 + 39, "newest 16, oldest first");
clf_ring_push(&g, 0x9999, AV, 0, 1, 500, 2, 0);
got = clf_ring_take(&g, out, &older);
check(got == 1 && out[0].addr == 0x9999 && older == 0, "after a flush, only what came since");
}
int main(void)
{
fatal_repeat_recovered_by_flush(5);
fatal_repeat_recovered_by_flush(100);
fatal_repeat_recovered_by_flush(1000);
ring_order_overflow_and_written();
netfx_noise_never_spends_the_limit();
known_address_going_fatal_is_written();
ac_faults_limited_per_distinct_address();
codes();
classification();
managed_noise_is_its_own_bucket();
last_chance_is_separate();
full_table_evicts_oldest_noise();
printf("%d check(s), %d failed.\n", g_checks, g_failed);
return g_failed == 0 ? 0 : 1;
}

View file

@ -0,0 +1,28 @@
# Run-CrashLogFilterTests.ps1
# Builds and runs CrashLogFilterTests.c (x86 MSVC, the same toolchain as the DLL).
# -OutDir: where the test exe goes (default: native\SehTrampoline\tests\bin). Exit 0 = pass.
param([string]$OutDir = (Join-Path $PSScriptRoot "bin"))
$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"
New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
$exe = Join-Path $OutDir "CrashLogFilterTests.exe"
& $cl /nologo /W4 /WX "$PSScriptRoot\CrashLogFilterTests.c" /Fo"$OutDir\\" /Fe"$exe" /link /MACHINE:X86
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
& $exe
exit $LASTEXITCODE

View file

@ -80,13 +80,31 @@ if (-not $EngineOnly) {
}
$seh = "$repo\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll"
$sehC = "$repo\native\SehTrampoline\SehTrampoline.c"
# bin\ is gitignored, so a checkout keeps whatever DLL was last built there. Until
# 2026-10-12 this shipped a June v1 build over every newer source (v4 was merged):
# its crash logger turned managed NullReferenceExceptions into fatal CLR errors and
# the Client::UseTime guard stayed off. Same staleness rule as Deploy-RynthCore.ps1.
if ((Test-Path $seh) -and (Test-Path $sehC) -and
(Get-Item $sehC).LastWriteTime -gt (Get-Item $seh).LastWriteTime) {
throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c is newer). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1 -NoDeploy, then re-run."
}
if (-not (Test-Path $seh)) { $seh = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" }
$sehDest = Join-Path (Resolve-Path $Target).Path "RynthCore.SehTrampoline.dll"
$sameSeh = (Test-Path $sehDest) -and ((Resolve-Path $seh).Path -eq $sehDest -or
(Get-FileHash $seh).Hash -eq (Get-FileHash $sehDest).Hash)
if (-not $sameSeh) {
# Same move-aside as the loader and shim: a locked copy would otherwise keep every
# new launch on the old trampoline until all clients close.
try { Copy-Item $seh $sehDest -Force -ErrorAction Stop }
catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." }
catch {
try {
Rename-Item $sehDest ("RynthCore.SehTrampoline.dll.old-{0:yyyyMMddHHmmss}" -f (Get-Date)) -ErrorAction Stop
Copy-Item $seh $sehDest -Force -ErrorAction Stop
Write-Host "RynthCore.SehTrampoline.dll was in use: moved the old one aside; new launches get the new one."
}
catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." }
}
}
# App-local runtime: the win-x86 runtime pack the SDK restores (same version the engine was built against).

View file

@ -1,6 +1,8 @@
using System;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using RynthCore;
namespace RynthCore.App.Avalonia;
@ -13,6 +15,18 @@ public partial class App : Application
public override void OnFrameworkInitializationCompleted()
{
try
{
string t = DateTime.Now.ToString("O");
DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher,
$"[{t}] [pid:{Environment.ProcessId}] RynthCore.App.Avalonia started (launcher).");
// Detailed host + sidecar file layout (see LauncherHostDiagnostics) for runtime mis-detection triage.
LauncherHostDiagnostics.AppendDesktopLogBlock(t);
}
catch
{
}
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();

View file

@ -120,4 +120,19 @@ internal static class EngineJsonStore
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);
}
}

View file

@ -0,0 +1,29 @@
using System;
using System.Runtime.InteropServices;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
/// <summary>
/// One-shot values the installer leaves under <c>Software\Rynth</c> for the launcher
/// (e.g. <c>PendingPluginRegistration</c>). Kept out of the shared, read-only
/// <see cref="RynthInstallPaths"/>, which must stay byte-identical with RynthSuite's copy.
/// </summary>
internal static class InstallerHandoff
{
/// <summary>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)
=> SystemInstallSettings.Instance.CurrentUser(valueName)
?? SystemInstallSettings.Instance.LocalMachine(valueName);
/// <summary>Deletes a value from HKCU <c>Software\Rynth</c> once it has been acted on. Best effort.</summary>
public static void DeleteUserSetting(string valueName)
{
try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RynthInstallPaths.RegistryKey, valueName); } catch { }
}
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
}

View file

@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Text;
using System.Threading;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;

View file

@ -0,0 +1,110 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore;
namespace RynthCore.App.Avalonia;
/// <summary>
/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost
/// (<c>RynthCore.exe</c>) sits next to matching <c>.runtimeconfig.json</c> / <c>.deps.json</c> after installer staging.
/// </summary>
internal static class LauncherHostDiagnostics
{
/// <summary>Single line for the in-window activity feed (short).</summary>
internal static string BuildActivitySummaryLine()
{
string exe = TryGetHostExePath();
string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
HostSidecars side = DescribeSidecars(dir);
// x64 FDD tool prereq: same registry keys as installer/RynthCore.iss (see NetDesktopX64Prerequisite).
string suiteTools = NetDesktopX64Prerequisite.IsSatisfied()
? "x64 suite tools: .NET 10+ OK (registry, same as setup)"
: "x64 suite tools: .NET 10+ not found — install x64 runtime from " + NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl;
if (!Environment.Is64BitOperatingSystem)
suiteTools = "x64 suite tools: n/a on 32-bit OS (same as setup)";
return
$"Host: {RuntimeInformation.FrameworkDescription}, arch={RuntimeInformation.ProcessArchitecture}, " +
$"runtimeconfig={(side.RenamedRuntimeConfig ? "RynthCore" : side.LegacyRuntimeConfig ? "App.Avalonia (mismatch?)" : "missing")}, " +
$"deps={(side.RenamedDeps ? "RynthCore" : side.LegacyDeps ? "App.Avalonia (mismatch?)" : "missing")}; {suiteTools}";
}
/// <summary>Writes a detailed block to the desktop rolling launcher log.</summary>
internal static void AppendDesktopLogBlock(string timestampIso)
{
try
{
string exe = TryGetHostExePath();
string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
HostSidecars side = DescribeSidecars(dir);
var sb = new StringBuilder(512);
sb.Append('[').Append(timestampIso).Append("] [pid:").Append(Environment.ProcessId).AppendLine("] Launcher host resolution:");
sb.Append(" ProcessPath: ").AppendLine(exe);
sb.Append(" BaseDirectory: ").AppendLine(AppContext.BaseDirectory);
sb.Append(" Framework: ").AppendLine(RuntimeInformation.FrameworkDescription);
sb.Append(" OSDescription: ").AppendLine(RuntimeInformation.OSDescription);
sb.Append(" ProcessArchitecture: ").AppendLine(RuntimeInformation.ProcessArchitecture.ToString());
sb.Append(" CLR: ").AppendLine(Environment.Version.ToString());
sb.Append(" RynthCore.runtimeconfig.json: ").AppendLine(side.RenamedRuntimeConfig ? "present" : "absent");
sb.Append(" RynthCore.App.Avalonia.runtimeconfig.json: ").AppendLine(side.LegacyRuntimeConfig ? "present (unexpected if exe is RynthCore.exe)" : "absent");
sb.Append(" RynthCore.deps.json: ").AppendLine(side.RenamedDeps ? "present" : "absent");
sb.Append(" RynthCore.App.Avalonia.deps.json: ").AppendLine(side.LegacyDeps ? "present (unexpected if exe is RynthCore.exe)" : "absent");
// Loot/Monster editors are x64 FDD: probe matches RynthCore.iss prerequisite page (64-bit registry view).
sb.Append(" x64 FDD tool runtime (Loot/Monster, same checks as installer): ")
.AppendLine(NetDesktopX64Prerequisite.IsSatisfied() ? "present" : "not detected")
.Append(" .NET 10+ x64 download hub: ")
.AppendLine(NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl);
DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, sb.ToString());
}
catch
{
// Logging must never prevent startup.
}
}
private static string TryGetHostExePath()
{
try
{
// Prefer the actual apphost path (works for published rename to RynthCore.exe).
string? p = Environment.ProcessPath;
if (!string.IsNullOrWhiteSpace(p))
return p;
}
catch
{
// ignore
}
try
{
return typeof(App).Assembly.Location;
}
catch
{
return string.Empty;
}
}
private static HostSidecars DescribeSidecars(string directory)
{
if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
return new HostSidecars(false, false, false, false);
bool renamedRc = File.Exists(Path.Combine(directory, "RynthCore.runtimeconfig.json"));
bool legacyRc = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.runtimeconfig.json"));
bool renamedDeps = File.Exists(Path.Combine(directory, "RynthCore.deps.json"));
bool legacyDeps = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.deps.json"));
return new HostSidecars(renamedRc, legacyRc, renamedDeps, legacyDeps);
}
private readonly record struct HostSidecars(
bool RenamedRuntimeConfig,
bool LegacyRuntimeConfig,
bool RenamedDeps,
bool LegacyDeps);
}

View file

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Launcher-side access to every live logging switch:
/// <list type="bullet">
/// <item>Engine: engine.json "LoggingLevel" (global threshold) and "LogCategories" (per-category emit
/// level). The engine polls engine.json once a second, so edits apply to running clients.</item>
/// <item>RynthAi: Logs\Diagnostics\diagnostics.json "Categories" and "Events" (Off / Trace / Info).
/// RynthAi polls it every couple of seconds and rewrites it with the full catalog on load.</item>
/// </list>
/// </summary>
internal static class LoggingSettingsStore
{
/// <summary>One engine log category as shown in the launcher.</summary>
internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description);
/// <summary>One RynthAi category / event row read from diagnostics.json.</summary>
internal sealed record DiagnosticsRow(string Key, string Level, string Description);
/// <summary>Global level choices (engine.json "LoggingLevel"), most to least quiet.</summary>
internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" };
/// <summary>Engine category emit levels. Info = normal log; Debug/Trace show only at that global level.</summary>
internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" };
/// <summary>RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log).</summary>
internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" };
/// <summary>Must match RynthCore.Engine.LogCategory names and LogSettings defaults.</summary>
internal static readonly EngineCategory[] EngineCategories =
{
new("General", "Info", "Uncategorised engine lines."),
new("D3D9", "Info", "D3D9 hook, EndScene, bootstrapper, matrix capture, nav markers."),
new("Compat", "Info", "Client hooks: objects, combat, movement, vitals, chat."),
new("Render", "Off", "ImGui rendering and Win32 input (very chatty)."),
new("Plugin", "Info", "Plugin loader/manager and every plugin host Log line."),
new("UI", "Info", "Avalonia overlay and panels."),
new("Verbose", "Debug", "Detail lines across all subsystems (Info = always in the normal log)."),
};
private const string EngineCategoriesProperty = "LogCategories";
/// <summary>RynthAi's diagnostics.json (created by RynthAi on its first load).</summary>
internal static string DiagnosticsPath =>
Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json");
// ── Engine ──────────────────────────────────────────────────────────
/// <summary>Current engine category levels; categories missing from engine.json get their defaults.</summary>
internal static Dictionary<string, string> ReadEngineCategoryLevels()
{
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel;
Dictionary<string, JsonElement> fields = EngineJsonStore.Read();
if (fields.TryGetValue(EngineCategoriesProperty, out JsonElement cats) && cats.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty p in cats.EnumerateObject())
{
if (p.Value.ValueKind == JsonValueKind.String && result.ContainsKey(p.Name))
result[p.Name] = p.Value.GetString() ?? result[p.Name];
}
}
return result;
}
/// <summary>Sets one engine category level in engine.json, preserving every other field.</summary>
internal static void SetEngineCategoryLevel(string category, string level)
{
Dictionary<string, string> levels = ReadEngineCategoryLevels();
levels[category] = level;
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
foreach (EngineCategory c in EngineCategories)
w.WriteString(c.Name, levels[c.Name]);
w.WriteEndObject();
}
Dictionary<string, JsonElement> fields = EngineJsonStore.Read();
using var doc = JsonDocument.Parse(ms.ToArray());
fields[EngineCategoriesProperty] = doc.RootElement.Clone();
EngineJsonStore.Write(fields);
}
// ── RynthAi ─────────────────────────────────────────────────────────
/// <summary>
/// Reads RynthAi's category and event rows. Returns false (with empty lists) when diagnostics.json
/// does not exist yet or cannot be parsed (e.g. RynthAi is mid-write; retry later).
/// </summary>
internal static bool TryReadRynthAi(out List<DiagnosticsRow> categories, out List<DiagnosticsRow> events, out string? error)
{
categories = new List<DiagnosticsRow>();
events = new List<DiagnosticsRow>();
error = null;
try
{
if (!File.Exists(DiagnosticsPath))
{
error = "diagnostics.json not found - start RynthAi once to create it.";
return false;
}
if (JsonNode.Parse(File.ReadAllText(DiagnosticsPath)) is not JsonObject root)
{
error = "diagnostics.json is not a JSON object.";
return false;
}
ReadRows(root["Categories"] as JsonArray, "Name", categories);
ReadRows(root["Events"] as JsonArray, "Key", events);
if (categories.Count == 0)
error = "diagnostics.json has no category list - update RynthAi to 0.6.18 or later.";
return true;
}
catch (Exception ex)
{
error = $"diagnostics.json unreadable ({ex.GetType().Name}: {ex.Message}).";
return false;
}
}
/// <summary>Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync.</summary>
internal static void SetRynthAiCategoryLevel(string category, string level)
=> UpdateDiagnostics("Categories", "Name", category, level);
/// <summary>Sets a RynthAi key-event level ("Off", "Trace", "Info").</summary>
internal static void SetRynthAiEventLevel(string eventKey, string level)
=> UpdateDiagnostics("Events", "Key", eventKey, level);
private static void ReadRows(JsonArray? array, string keyField, List<DiagnosticsRow> into)
{
if (array == null) return;
foreach (JsonNode? node in array)
{
if (node is not JsonObject o) continue;
string key = o[keyField]?.GetValue<string>() ?? string.Empty;
if (key.Length == 0) continue;
into.Add(new DiagnosticsRow(
key,
o["Level"]?.GetValue<string>() ?? "Off",
o["Description"]?.GetValue<string>() ?? string.Empty));
}
}
/// <summary>Read-modify-write of one row's Level; every other field in the file is preserved.</summary>
private static void UpdateDiagnostics(string section, string keyField, string key, string level)
{
string path = DiagnosticsPath;
if (JsonNode.Parse(File.ReadAllText(path)) is not JsonObject root)
throw new InvalidDataException("diagnostics.json is not a JSON object.");
if (root[section] is not JsonArray rows)
throw new InvalidDataException($"diagnostics.json has no \"{section}\" list.");
bool found = false;
foreach (JsonNode? node in rows)
{
if (node is JsonObject o && string.Equals(o[keyField]?.GetValue<string>(), key, StringComparison.OrdinalIgnoreCase))
{
o["Level"] = level;
found = true;
}
}
if (!found)
throw new KeyNotFoundException($"\"{key}\" is not in diagnostics.json {section}.");
// RynthAi reads Categories when present, but older readers (and /ra trace status) use Traces.
if (section == "Categories")
{
var traces = new JsonArray();
foreach (JsonNode? node in rows)
{
if (node is JsonObject o && !string.Equals(o["Level"]?.GetValue<string>(), "Off", StringComparison.OrdinalIgnoreCase))
traces.Add(o["Name"]?.GetValue<string>());
}
root["Traces"] = traces;
}
// Atomic swap so RynthAi's poll never reads a half-written file.
string tmp = path + ".tmp";
File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Recovery Actions > Fix folder permissions, and the start-up check that suggests it
/// (src\RynthCore.App\FolderAccess.cs, 2026-10-13). Players reported RynthAi metas and navs not
/// saving: the game client (never elevated) couldn't write in C:\Games\RynthSuite.
/// </summary>
internal partial class MainWindow
{
private const string FixFoldersTitle = "Fix folder permissions";
private bool _folderCheckShown;
/// <summary>The RynthSuite and RynthCore folders, as resolved for this account.</summary>
private static List<string> SuiteAndCoreDirs() =>
new[] { RynthInstallPaths.SuiteDir, RynthInstallPaths.CoreDir }
.Where(Directory.Exists).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
private static Task<(List<FolderAccess.FolderStatus> Folders, FolderAccess.CfaInfo Cfa)> CheckFoldersAsync() =>
Task.Run(() =>
{
var folders = FolderAccess.CheckAll(FolderAccess.FoldersToCheck(RynthInstallPaths.SuiteDir, RynthInstallPaths.CoreDir));
var cfa = FolderAccess.QueryControlledFolderAccess();
return (folders, cfa);
});
/// <summary>The Controlled folder access part of a message ("" when it isn't in the way).</summary>
private static string DescribeCfa(FolderAccess.CfaInfo cfa)
{
var mine = cfa.GameClientBlocks(DateTime.UtcNow);
if (mine.Count > 0)
{
var last = mine[0];
return $"Windows Security's Controlled folder access blocked the game client {mine.Count} time(s) recently " +
$"(last: {last.Time.ToLocalTime():g}, {last.Path}). Permissions can't fix that; allow the client instead:\n" +
FolderAccess.CfaAllowHowTo;
}
if (cfa.On)
return "Controlled folder access (Windows Security ransomware protection) is on. If RynthSuite is in a protected " +
"folder (Documents, Desktop, or one you added), it blocks acclient.exe from saving there. To allow it: " +
FolderAccess.CfaAllowHowTo;
return string.Empty;
}
/// <summary>At start: say so (Activity, log, one dialog) when the client won't be able to save.</summary>
private async Task CheckFolderAccessAtStartupAsync()
{
try
{
var (folders, cfa) = await CheckFoldersAsync();
List<string> problems = FolderAccess.DescribeProblems(folders);
string cfaText = DescribeCfa(cfa);
bool cfaBlocks = cfa.BlocksGameClient;
foreach (string p in problems)
{
LauncherDiag.Info("FOLDERS: " + p);
AppendActivity("Folders: " + p);
}
if (cfaText.Length > 0)
{
LauncherDiag.Info("FOLDERS: " + cfaText.Replace('\n', ' '));
if (cfaBlocks || problems.Count > 0) AppendActivity("Folders: " + cfaText.Replace('\n', ' '));
}
if ((problems.Count == 0 && !cfaBlocks) || _folderCheckShown) return;
_folderCheckShown = true;
if (problems.Count > 0)
{
string msg = "RynthAi won't be able to save metas, navs, loot or settings profiles here:\n\n" +
string.Join("\n", problems.Take(8)) +
(problems.Count > 8 ? $"\n... and {problems.Count - 8} more (Activity tab)." : "") +
"\n\nFix folder permissions gives your Windows account write access to the RynthSuite and RynthCore " +
"folders and clears read-only on their files (one administrator prompt)." +
(cfaText.Length > 0 ? "\n\n" + cfaText : "");
if (await DecalBridgeDialog.AskAsync(this, FixFoldersTitle, msg, "Fix now", "Not now"))
await FixFolderPermissionsAsync(ask: false);
}
else
{
await DecalBridgeDialog.InfoAsync(this, "Saves blocked by Windows Security", cfaText);
}
}
catch (Exception ex)
{
LauncherDiag.Info($"FOLDERS: start-up check failed ({ex.GetType().Name}: {ex.Message})");
}
}
/// <summary>
/// Recovery Actions > Fix folder permissions: one administrator prompt; the elevated launcher
/// (--fix-folder-permissions) grants this account Modify on the RynthSuite and RynthCore
/// folders and clears read-only on their files; then the check runs again.
/// </summary>
private async Task FixFolderPermissionsAsync(bool ask = true)
{
List<string> roots = SuiteAndCoreDirs();
if (roots.Count == 0)
{
await DecalBridgeDialog.InfoAsync(this, FixFoldersTitle, $"Neither {RynthInstallPaths.SuiteDir} nor {RynthInstallPaths.CoreDir} exists.");
return;
}
if (ask)
{
bool yes = await DecalBridgeDialog.AskAsync(this, FixFoldersTitle,
"Gives your Windows account write access (Modify) to these folders and everything in them, and clears " +
"read-only on their files, so RynthAi can save metas, navs, loot and settings profiles:\n\n" +
string.Join("\n", roots) + "\n\nWindows asks for administrator permission once. Nothing else is changed.",
"Fix", "Cancel");
if (!yes)
{
AppendActivity("Fix folder permissions: cancelled; nothing changed.");
return;
}
}
string? sid = WindowsIdentity.GetCurrent().User?.Value;
string? self = Environment.ProcessPath;
if (sid == null || self == null)
{
AppendActivity("Fix folder permissions: couldn't tell who you are or where the launcher is; nothing changed.");
return;
}
string reportPath = Path.Combine(Path.GetTempPath(), $"rynthcore-folderfix-{Guid.NewGuid():N}.txt");
string args = FolderAccess.BuildRepairArguments(sid, roots, reportPath);
LauncherDiag.Info($"FOLDERS: fix folder permissions: {args}");
AppendActivity("Fix folder permissions: waiting for the Windows administrator prompt...");
(DecalBridgeRegistration.Outcome outcome, string runReport) = await Task.Run(() =>
{
var o = DecalBridgeRegistration.RunElevated(self, args, out string r);
return (o, r);
});
string details = string.Empty;
try
{
if (File.Exists(reportPath))
{
details = File.ReadAllText(reportPath).Trim();
File.Delete(reportPath);
}
}
catch { }
LauncherDiag.Info($"FOLDERS: fix folder permissions: {outcome}: {runReport} {details.Replace(Environment.NewLine, " | ")}");
var (folders, cfa) = await CheckFoldersAsync();
List<string> left = FolderAccess.DescribeProblems(folders);
string cfaText = DescribeCfa(cfa);
string summary = left.Count == 0
? "Done: every RynthSuite / RynthCore folder can be written now."
: "Still a problem:\n" + string.Join("\n", left.Take(8));
if (outcome == DecalBridgeRegistration.Outcome.NeedsAdmin)
summary = "Cancelled at the Windows administrator prompt; nothing changed.";
AppendActivity("Fix folder permissions: " + summary.Replace('\n', ' '));
string text = summary +
(details.Length > 0 && outcome != DecalBridgeRegistration.Outcome.NeedsAdmin ? "\n\n" + LastLines(details, 6) : "") +
(cfaText.Length > 0 ? "\n\n" + cfaText : "") +
(left.Count == 0 ? "\n\nRestart the game clients that were running so RynthAi checks again." : "");
await DecalBridgeDialog.InfoAsync(this, FixFoldersTitle, text);
}
private static string LastLines(string text, int n)
{
string[] lines = text.Split('\n');
return string.Join("\n", lines.Skip(Math.Max(0, lines.Length - n)).Select(l => l.TrimEnd('\r')));
}
}

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Runtime tab → Logging card and the live global Logging level box. Every change is written
/// straight to engine.json / diagnostics.json (see <see cref="LoggingSettingsStore"/>); running
/// clients poll those files, so nothing needs a restart or the Save button.
/// </summary>
internal partial class MainWindow
{
private static readonly IBrush LogNameBrush = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush LogMutedBrush = new SolidColorBrush(Color.Parse("#9AA8B3"));
// Set while the rows are being (re)built so programmatic selections don't write files.
private bool _suppressLoggingEvents;
/// <summary>Wires the Logging card and the live global level box. Called once after LoadRuntimeControls.</summary>
private void InitLoggingControls()
{
LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged();
ReloadLoggingButton.Click += (_, _) => BuildLoggingRows();
BuildLoggingRows();
}
/// <summary>Global level changed: persist to the launcher settings and push to engine.json now.</summary>
private void OnGlobalLoggingLevelChanged()
{
if (_suppressLoggingEvents) return;
string level = GetSelectedLoggingLevel();
if (string.Equals(level, _settings.LoggingLevel, StringComparison.OrdinalIgnoreCase)) return;
try
{
_settings.LoggingLevel = level;
SaveSettings();
EngineJsonStore.SetString("LoggingLevel", level);
AppendActivity($"Logging level set to {level} (applied live to running clients).");
}
catch (Exception ex)
{
AppendActivity($"Failed to save logging level: {ex.Message}");
}
}
/// <summary>(Re)builds the engine category, RynthAi category and RynthAi event rows from disk.</summary>
private void BuildLoggingRows()
{
_suppressLoggingEvents = true;
try
{
EngineLogCategoriesPanel.Children.Clear();
Dictionary<string, string> engineLevels = LoggingSettingsStore.ReadEngineCategoryLevels();
foreach (LoggingSettingsStore.EngineCategory cat in LoggingSettingsStore.EngineCategories)
{
string name = cat.Name;
EngineLogCategoriesPanel.Children.Add(BuildLoggingRow(
name, cat.Description, LoggingSettingsStore.EngineCategoryLevels, engineLevels[name],
level =>
{
LoggingSettingsStore.SetEngineCategoryLevel(name, level);
AppendActivity($"Engine log category {name} set to {level} (applied live).");
}));
}
RynthAiLogCategoriesPanel.Children.Clear();
RynthAiLogEventsPanel.Children.Clear();
bool ok = LoggingSettingsStore.TryReadRynthAi(
out List<LoggingSettingsStore.DiagnosticsRow> categories,
out List<LoggingSettingsStore.DiagnosticsRow> events,
out string? error);
foreach (LoggingSettingsStore.DiagnosticsRow row in categories)
{
string key = row.Key;
RynthAiLogCategoriesPanel.Children.Add(BuildLoggingRow(
key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
level =>
{
LoggingSettingsStore.SetRynthAiCategoryLevel(key, level);
AppendActivity($"RynthAi log category {key} set to {level} (applied live).");
}));
}
foreach (LoggingSettingsStore.DiagnosticsRow row in events)
{
string key = row.Key;
RynthAiLogEventsPanel.Children.Add(BuildLoggingRow(
key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
level =>
{
LoggingSettingsStore.SetRynthAiEventLevel(key, level);
AppendActivity($"RynthAi log event {key} set to {level} (applied live).");
}));
}
LoggingStatusText.Text = ok && error == null
? $"engine.json: {EngineJsonStore.Path}\ndiagnostics.json: {LoggingSettingsStore.DiagnosticsPath}"
: $"RynthAi: {error}";
}
catch (Exception ex)
{
LoggingStatusText.Text = $"Failed to load logging settings: {ex.Message}";
}
finally
{
_suppressLoggingEvents = false;
}
}
/// <summary>One "Name | level box | description" row. <paramref name="apply"/> runs on user changes only.</summary>
private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action<string> apply)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("170,110,*") };
grid.Children.Add(new TextBlock
{
Text = name,
Foreground = LogNameBrush,
VerticalAlignment = VerticalAlignment.Center,
});
var combo = new ComboBox { ItemsSource = levels, MinWidth = 100, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) };
int index = Array.FindIndex(levels, l => string.Equals(l, current, StringComparison.OrdinalIgnoreCase));
combo.SelectedIndex = index >= 0 ? index : 0;
combo.SelectionChanged += (_, _) =>
{
if (_suppressLoggingEvents || combo.SelectedItem is not string level) return;
try { apply(level); }
catch (Exception ex)
{
AppendActivity($"Failed to set {name} to {level}: {ex.Message}");
// Show what is actually on disk; posted so the combo raising this event isn't torn down mid-handler.
global::Avalonia.Threading.Dispatcher.UIThread.Post(BuildLoggingRows);
}
};
Grid.SetColumn(combo, 1);
grid.Children.Add(combo);
var desc = new TextBlock
{
Text = description,
Foreground = LogMutedBrush,
TextWrapping = TextWrapping.Wrap,
VerticalAlignment = VerticalAlignment.Center,
};
Grid.SetColumn(desc, 2);
grid.Children.Add(desc);
return grid;
}
}

View file

@ -366,7 +366,17 @@
<CheckBox x:Name="OverrideWindowTitleCheckBox"
Content="Rewrite AC window titles per account"
ToolTip.Tip="Replaces &quot;Asheron's Call&quot; with &quot;Account / Character @ Server&quot; 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 (applies live)" Foreground="#EAF0F4" Margin="0,4,0,0" />
<ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="3"
ToolTip.Tip="Engine log threshold. Written to engine.json immediately; running clients pick it up within a second. Off = errors only.">
<ComboBoxItem Content="Off" />
<ComboBoxItem Content="Error" />
<ComboBoxItem Content="Warning" />
<ComboBoxItem Content="Info" />
<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" />
@ -409,6 +419,42 @@
</StackPanel>
</Border>
<!-- Live logging switches: engine categories (engine.json) and RynthAi categories/events
(diagnostics.json). Rows are built in code (MainWindow.Logging.cs). -->
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="0" Text="Logging" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" VerticalAlignment="Center" />
<Button Grid.Column="1" x:Name="ReloadLoggingButton" Content="Reload" />
</Grid>
<TextBlock Text="Every change is saved immediately and applies to running clients without a restart (engine within 1 s, RynthAi within 2 s). Set any Trace or Debug item to Info to see it in the normal log; Off silences it."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<Expander Header="Engine categories" IsExpanded="True" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="The level each category's lines are written at. A line shows when its level is within the global Logging level above (Info = normal log)."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="EngineLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi categories" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Where each RynthAi category's trace lines go: Off = dropped, Trace = Logs\Diagnostics\Trace file only, Info = trace file and the normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi key events" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Named milestones (Hub login, options refresh, ...). Off = dropped, Trace = trace file while that category is traced, Info = normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogEventsPanel" Spacing="2" />
</StackPanel>
</Expander>
<TextBlock x:Name="LoggingStatusText" TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
@ -424,8 +470,10 @@
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
<Button x:Name="RepairDecalButton" Content="Repair Decal" Margin="0,0,8,8"
ToolTip.Tip="For Decal plugins that don't show up: Windows can make Decal read an old per-user copy of its settings (left by an earlier RynthCore, or by Decal itself), which hides plugins installed since. This backs that copy up to a .reg file in %APPDATA%\RynthCore and removes it, after asking. Close Asheron's Call first." />
<Button x:Name="FixFolderPermissionsButton" Content="Fix folder permissions" Margin="0,0,8,8"
ToolTip.Tip="When RynthAi metas, navs, loot or settings profiles don't save: gives your Windows account write access to the RynthSuite and RynthCore folders and clears read-only on their files (one administrator prompt). Also tells you when Windows Security's Controlled folder access is blocking the game client." />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
<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>

View file

@ -18,6 +18,7 @@ using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using RynthCore.Injector;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
@ -136,6 +137,8 @@ internal partial class MainWindow : Window
SessionList.ItemsSource = _sessionItems;
LoadSettings();
LoadRuntimeControls();
InitLoggingControls();
ApplyInstallerPluginRegistration();
LoadPluginDllPaths();
BuildPluginLoadout();
WireEvents();
@ -149,6 +152,8 @@ internal partial class MainWindow : Window
Closing += (_, _) => SaveWindowLayout();
ShowVersion();
AppendActivity("Avalonia launcher preview ready.");
// One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log).
AppendActivity(LauncherHostDiagnostics.BuildActivitySummaryLine());
_ = RefreshServerStatusesAsync();
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start();
@ -157,6 +162,7 @@ internal partial class MainWindow : Window
{
await AskAboutUsageStatsOnceAsync();
await CleanUpDecalBridgeIfUnusedAsync(atStartup: true);
await CheckFolderAccessAtStartupAsync(); // MainWindow.FolderAccess.cs: can the game client save?
};
}
@ -184,6 +190,7 @@ internal partial class MainWindow : Window
ResetOverlayBarButton.Click += (_, _) => ResetOverlayBar();
CheckDecalBridgeButton.Click += async (_, _) => await CheckDecalBridgeAsync();
RepairDecalButton.Click += async (_, _) => await RepairDecalAsync();
FixFolderPermissionsButton.Click += async (_, _) => await FixFolderPermissionsAsync();
AddPluginDllButton.Click += async (_, _) => await AddPluginDllAsync();
CheckUpdatesButton.Click += async (_, _) => await CheckForUpdatesAsync();
UpdateCardActionButton.Click += async (_, _) => await OnUpdateCardActionAsync();
@ -312,6 +319,8 @@ internal partial class MainWindow : Window
AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch;
AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch;
WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart;
InjectAllRunningAcCheckBox.IsChecked = _settings.InjectAllRunningClients;
SetLoggingLevelSelection(_settings.LoggingLevel);
OverrideWindowTitleCheckBox.IsChecked = _settings.OverrideWindowTitle;
LaunchStaggerMsBox.Value = _settings.LaunchStaggerMs;
CrashRelaunchLimitBox.Value = _settings.CrashRelaunchLimitInWindow;
@ -1485,6 +1494,8 @@ internal partial class MainWindow : Window
_settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true;
_settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true;
_settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true;
_settings.InjectAllRunningClients = InjectAllRunningAcCheckBox.IsChecked == true;
_settings.LoggingLevel = GetSelectedLoggingLevel();
_settings.OverrideWindowTitle = OverrideWindowTitleCheckBox.IsChecked == true;
if (LaunchStaggerMsBox.Value is decimal staggerMs)
_settings.LaunchStaggerMs = (int)staggerMs;
@ -1499,8 +1510,12 @@ internal partial class MainWindow : Window
if (_settings.EnabledPluginIds.Count == 0)
_settings.EnabledPluginIds.Add("rynthcore-engine");
SaveSettings();
SyncPluginPathsToEngineSettings();
if (appendActivity)
{
AppendActivity($"Logging level saved: {_settings.LoggingLevel}.");
AppendActivity("Launch behavior saved.");
}
}
private void SaveAutoLaunchPreference()
@ -2157,6 +2172,78 @@ internal partial class MainWindow : Window
AppendActivity($"Runtime loadout updated: {Path.GetFileName(dllPath)} {(enabled ? "enabled" : "disabled")} (engine.json synced).");
}
/// <summary>
/// Applies the installer's one-shot plugin hand-off: the full installer writes the plugin
/// DLL paths it placed in the user-chosen RynthSuite folder to
/// <c>Software\Rynth\PendingPluginRegistration</c> (';'-separated). Each existing DLL is added
/// to the Plugins list, and any entry with the same file name that no longer exists (e.g. the
/// old <c>C:\Games\RynthSuite\...</c> path after moving the Suite folder) is replaced.
/// Rows pointing inside the RynthCore folder whose file the installer removed are dropped too.
/// The value is consumed once (deleted from HKCU; remembered in settings for HKLM).
/// </summary>
private void ApplyInstallerPluginRegistration()
{
try
{
string? pending = InstallerHandoff.ReadSetting("PendingPluginRegistration");
if (string.IsNullOrWhiteSpace(pending)
|| string.Equals(pending, _settings.AppliedInstallerPluginRegistration, StringComparison.OrdinalIgnoreCase))
return;
_settings.PluginDllPaths ??= [];
var added = new List<string>();
// The installer clears loose DLLs out of the RynthCore folder (old 0.4.x layouts kept plugins
// and SDK DLLs there), so drop rows that pointed inside it and are now gone. Rows elsewhere are
// left alone, since a missing file there may just be on a drive that isn't mounted.
string coreRoot = Path.TrimEndingDirectorySeparator(RynthInstallPaths.CoreDir) + Path.DirectorySeparatorChar;
bool IsRemovedCoreFile(string p) =>
p.StartsWith(coreRoot, StringComparison.OrdinalIgnoreCase) && !File.Exists(p);
int pruned = _settings.PluginDllPaths.RemoveAll(IsRemovedCoreFile);
_settings.DisabledPluginDllPaths.RemoveAll(IsRemovedCoreFile);
foreach (string raw in pending.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string path;
try { path = Path.GetFullPath(raw); } catch { continue; }
if (!File.Exists(path)) continue;
string fileName = Path.GetFileName(path);
// Drop stale rows for the same plugin that point at a file which is gone.
_settings.PluginDllPaths.RemoveAll(p =>
string.Equals(Path.GetFileName(p), fileName, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(p, path, StringComparison.OrdinalIgnoreCase)
&& !File.Exists(p));
if (!_settings.PluginDllPaths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase)))
{
_settings.PluginDllPaths.Add(path);
added.Add(fileName);
}
}
_settings.AppliedInstallerPluginRegistration = pending;
SaveSettings();
InstallerHandoff.DeleteUserSetting("PendingPluginRegistration");
_pluginDllPaths.Clear();
foreach (string p in _settings.PluginDllPaths) _pluginDllPaths.Add(p);
SyncPluginPathsToEngineSettings();
string msg = added.Count > 0
? $"Installer registered plugin(s): {string.Join(", ", added)} (engine.json synced)."
: "Installer plugin registration already up to date.";
if (pruned > 0)
msg += $" Removed {pruned} plugin path(s) for files the installer cleared from {RynthInstallPaths.CoreDir}.";
LauncherDiag.Info("PLUGINS: " + msg);
try { AppendActivity(msg); } catch { }
}
catch (Exception ex)
{
LauncherDiag.Info("PLUGINS: installer registration failed: " + ex.Message);
}
}
private void LoadPluginDllPaths()
{
_pluginDllPaths.Clear();
@ -2245,6 +2332,8 @@ internal partial class MainWindow : Window
.Where(p => !disabled.Contains(p))
.ToList();
EngineJsonStore.SetStringArray("PluginPaths", enabledPaths);
// The engine reads its log verbosity from engine.json on init (EngineSettings.LoggingLevel).
EngineJsonStore.SetString("LoggingLevel", GetSelectedLoggingLevel());
}
catch (Exception ex)
{
@ -2740,18 +2829,28 @@ internal partial class MainWindow : Window
try
{
SetOperationState(true);
Process target = targets.OrderBy(process => process.Id).First();
AppendActivity($"Applying selected loadout to running AC (PID {target.Id}).");
IReadOnlyList<Process> orderedTargets = targets.OrderBy(process => process.Id).ToList();
bool injectAllSessions = InjectAllRunningAcCheckBox.IsChecked == true;
IReadOnlyList<Process> targetsToInject = injectAllSessions
? orderedTargets
: [orderedTargets[0]];
AppendActivity(injectAllSessions
? $"Applying selected loadout to {targetsToInject.Count} running AC session(s)."
: $"Applying selected loadout to first running AC session (PID {targetsToInject[0].Id}).");
InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity));
if (result.Success)
foreach (Process target in targetsToInject)
{
_launchedSessionPids.Add(target.Id);
AppendActivity($"Injection complete for PID {target.Id}.");
}
else
{
AppendActivity($"Injection failed: {result.Summary}");
AppendActivity($"Injecting running AC (PID {target.Id}).");
InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity));
if (result.Success)
{
_launchedSessionPids.Add(target.Id);
AppendActivity($"Injection complete for PID {target.Id}.");
}
else
{
AppendActivity($"Injection failed for PID {target.Id}: {result.Summary}");
}
}
}
catch (Exception ex)
@ -2765,6 +2864,39 @@ internal partial class MainWindow : Window
}
}
private string GetSelectedLoggingLevel()
{
return LoggingLevelComboBox.SelectedItem is ComboBoxItem item
? item.Content?.ToString() ?? "Info"
: "Info";
}
private void SetLoggingLevelSelection(string? loggingLevel)
{
string desiredLevel = string.IsNullOrWhiteSpace(loggingLevel) ? "Info" : loggingLevel.Trim();
if (LoggingLevelComboBox.Items == null)
{
LoggingLevelComboBox.SelectedIndex = 0;
return;
}
foreach (object? item in LoggingLevelComboBox.Items)
{
if (item is not ComboBoxItem comboItem)
continue;
string candidate = comboItem.Content?.ToString() ?? string.Empty;
if (!string.Equals(candidate, desiredLevel, StringComparison.OrdinalIgnoreCase))
continue;
LoggingLevelComboBox.SelectedItem = comboItem;
return;
}
// Unknown saved value: fall back to Info (index 3 after Off, Error, Warning), not the quietest level.
LoggingLevelComboBox.SelectedIndex = 3;
}
private void OnPrimarySelectionChanged()
{
if (_suppressPrimarySelectionChanged)
@ -3104,6 +3236,27 @@ internal partial class MainWindow : Window
// thread not draining the marshalled-action queue), and a stale heartbeat
// file.
private readonly Dictionary<int, DateTime> _wedgeZeroFpsSinceUtc = new();
// PIDs held off for a full-memory dump, and since when (DumpInProgressRule.Decide caps the
// hold at MaxHold). Kept while held or expired, dropped once no dump is in progress.
private readonly Dictionary<int, DateTime> _dumpHoldSinceUtc = new();
// Last write of the newest acclient_oom_<pid>_*.dmp in the shared Dumps folder, or null.
private static DateTime? NewestOomDumpWriteUtc(int pid)
{
try
{
string dir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps");
if (!Directory.Exists(dir)) return null;
DateTime? newest = null;
foreach (string f in Directory.EnumerateFiles(dir, $"{RynthCore.Install.DumpInProgressRule.OomDumpPrefix}{pid}_*.dmp"))
{
DateTime w = File.GetLastWriteTimeUtc(f);
if (newest == null || w > newest) newest = w;
}
return newest;
}
catch { return null; }
}
// fps (1), plug pump rate (2), login (3), qd = main-thread queue depth (4, optional on older engines).
private static readonly System.Text.RegularExpressions.Regex WedgeHbRegex =
new(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?", System.Text.RegularExpressions.RegexOptions.Compiled);
@ -3184,6 +3337,35 @@ internal partial class MainWindow : Window
int read = fs.Read(buf, 0, (int)want);
tail = System.Text.Encoding.UTF8.GetString(buf, 0, read);
// The engine's OUT OF MEMORY full-memory dump suspends every thread for minutes:
// the log goes silent and the main thread looks hung, but killing now would cut
// the dump short. Hold off both kills below while it is being written
// (DumpInProgressRule); the restart for the box that follows is unchanged.
DateTime holdNow = DateTime.UtcNow;
DateTime? heldSince = _dumpHoldSinceUtc.TryGetValue(pid, out DateTime hs) ? hs : null;
var hold = RynthCore.Install.DumpInProgressRule.Decide(tail, fi.LastWriteTimeUtc, NewestOomDumpWriteUtc(pid), heldSince, holdNow);
if (hold == RynthCore.Install.DumpInProgressRule.Hold.Holding)
{
if (heldSince == null)
{
_dumpHoldSinceUtc[pid] = holdNow;
LauncherDiag.Info($"WEDGE: PID {pid} is writing a full-memory dump - kill held off until it ends (at most {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min).");
}
continue;
}
if (hold == RynthCore.Install.DumpInProgressRule.Hold.Expired)
{
if (heldSince is DateTime heldAt && heldAt != DateTime.MinValue)
{
_dumpHoldSinceUtc[pid] = DateTime.MinValue; // logged; stays expired until the signs clear
LauncherDiag.Info($"WEDGE: PID {pid} dump hold expired after {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min - kill checks resume.");
}
}
else
{
_dumpHoldSinceUtc.Remove(pid);
}
if (hbStale)
{
KillWedgedClient(process, pid, activeContexts, activeSessions,

View file

@ -63,6 +63,26 @@ internal static class Program
LauncherDiag.Info($"DECALBRIDGE: install per-user (installer): {report}");
return ok ? 0 : 1;
}
// Recovery Actions > Fix folder permissions, the elevated step (MainWindow.FolderAccess.cs):
// --fix-folder-permissions <user SID> [--report "<file>"] "<folder>" ["<folder>"...]. Never
// falls through to the window: a malformed command exits with 2.
if (Array.Exists(args, a => string.Equals(a, RynthCore.App.FolderAccess.RepairArgument, StringComparison.OrdinalIgnoreCase)))
{
if (!RynthCore.App.FolderAccess.TryParseRepairArguments(args, out string sid, out var roots, out string? reportPath))
{
LauncherDiag.Info("FOLDERS: fix folder permissions (elevated step): malformed command line; nothing changed.");
return 2;
}
var report = RynthCore.App.FolderAccess.Repair(roots, new System.Security.Principal.SecurityIdentifier(sid));
LauncherDiag.Info("FOLDERS: fix folder permissions (elevated step): " + report.ToString().Replace(Environment.NewLine, " | "));
// The report goes back to the launcher that asked, only as a new file of the expected name.
if (reportPath != null && System.IO.Path.GetFileName(reportPath).StartsWith("rynthcore-folderfix-", StringComparison.OrdinalIgnoreCase)
&& reportPath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) && !System.IO.File.Exists(reportPath))
{
try { System.IO.File.WriteAllText(reportPath, report.ToString()); } catch { }
}
return report.Ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-status", StringComparison.OrdinalIgnoreCase)))
{
LauncherDiag.Info($"DECALBRIDGE: status (command line): {RynthCore.App.DecalBridgeRegistration.GetStatus()}");

View file

@ -1,6 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4.
No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the
product version derived from it is what the launcher/About show (BuildVersion.Format). -->
<Version>0.1.5</Version>
<AssemblyVersion>0.1.5.0</AssemblyVersion>
<FileVersion>0.1.5.0</FileVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows7.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
@ -11,6 +17,8 @@
<RootNamespace>RynthCore.App.Avalonia</RootNamespace>
<AssemblyName>RynthCore.App.Avalonia</AssemblyName>
<RuntimeIdentifiers>win-x86</RuntimeIdentifiers>
<!-- Build-Installer.ps1 publishes self-contained so RynthCore.exe does not require a machine-wide
.NET 10 Desktop Runtime. Local dotnet build or dotnet run still use the SDK. -->
<ApplicationIcon>LogoCore.ico</ApplicationIcon>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
</PropertyGroup>
@ -25,10 +33,14 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<!-- Avalonia pulls Tmds.DBus.Protocol 0.20.0 (GHSA-xrw6-gwf8-vvr9; D-Bus is Linux-only, but pin the fixed version). -->
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" />
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
@ -36,6 +48,7 @@
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
<Compile Include="..\RynthCore.App\FolderAccess.cs" Link="Shared\FolderAccess.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
@ -58,6 +71,7 @@
<ItemGroup>
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file in RynthSuite Plugins\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\Shared\DumpInProgressRule.cs" Link="Shared\DumpInProgressRule.cs" />
</ItemGroup>
</Project>

View file

@ -22,7 +22,8 @@ namespace RynthCore.App.Avalonia;
/// - the RynthCore version;
/// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins
/// only as a count, never by name (a private plugin's name could identify its author);
/// - how many crash_*.dmp files the engine wrote since the last report (a count only);
/// - how many crash dumps were written since the last report (a count only): the engine's
/// Logs\dumps\crash_*.dmp and CoreCLR's Logs\dumps\clr_*.dmp;
/// - the Windows major version ("10" or "11").
/// Never: character, account or server names, file paths, or anything else identifying.
///
@ -221,18 +222,30 @@ internal sealed class UsageStats
return "other";
}
/// <summary>crash_*.dmp files written after <paramref name="sinceUtc"/> (hang dumps are not crashes).</summary>
/// <summary>
/// Crash dump names counted: the engine's crash_*.dmp and the CoreCLR fatal-error dumps the
/// loader asks for in the same folder (clr_*.dmp, Loader.c ConfigureCrashDumps).
/// </summary>
private static readonly string[] CrashDumpPatterns = { "crash_*.dmp", "clr_*.dmp" };
/// <summary>
/// Crash dumps (crash_*.dmp, clr_*.dmp) written after <paramref name="sinceUtc"/>. Hang dumps
/// and the OUT OF MEMORY dumps are not crashes.
/// </summary>
public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow)
{
try
{
if (!Directory.Exists(dir)) return 0;
int n = 0;
foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp"))
foreach (string pattern in CrashDumpPatterns)
{
DateTime t = File.GetLastWriteTimeUtc(f);
if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++;
if (n >= MaxCrashes) break;
foreach (string f in Directory.EnumerateFiles(dir, pattern))
{
DateTime t = File.GetLastWriteTimeUtc(f);
if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++;
if (n >= MaxCrashes) return n;
}
}
return n;
}

View file

@ -17,6 +17,8 @@ internal sealed class AppSettings
public bool AutoLaunch { get; set; }
public bool AutoInjectAfterLaunch { get; set; } = true;
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;
@ -68,6 +70,14 @@ internal sealed class AppSettings
/// 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; } = [];

View file

@ -0,0 +1,532 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Xml;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Can this Windows account write where RynthCore and its plugins keep their files, and the
/// launcher's Recovery Actions > Fix folder permissions (2026-10-13).
///
/// Players reported RynthAi metas and navs not saving and "the plugin folders are all read
/// only". On a default Windows install C:\Games\... is writable by every signed-in user, but:
/// - a C:\ whose permissions were changed (hardened / migrated PCs) leaves a folder created by
/// an elevated ("install for all users") setup readable only, so the game client, which runs
/// without administrator rights, can't save there;
/// - files can carry the ReadOnly attribute (copied from a read-only source, a zip, a CD/ISO);
/// - Windows Security's Controlled folder access blocks apps it doesn't know (acclient.exe)
/// from writing in protected folders (Documents, Desktop, ... or folders a player added);
/// - under Program Files, the 32-bit client's writes are silently redirected to
/// %LOCALAPPDATA%\VirtualStore (UAC virtualization), so "saved" files vanish for other tools.
/// <see cref="Check"/> tells which; <see cref="Repair"/> (run elevated, once) grants the player's
/// account Modify on the RynthSuite and RynthCore folders and clears ReadOnly on the files.
/// Explorer's "Read-only" box on a folder is always shown partly ticked and means nothing.
/// </summary>
internal static class FolderAccess
{
/// <summary>The launcher's elevated step: --fix-folder-permissions &lt;user SID&gt; [--report "file"] "folder" ["folder"...].</summary>
public const string RepairArgument = "--fix-folder-permissions";
public const string ReportArgument = "--report";
// ── Check ────────────────────────────────────────────────────────────────
/// <summary>One folder as the current account sees it.</summary>
internal sealed record FolderStatus(string Folder, bool Exists, bool Writable, string? Problem, int ReadOnlyFiles, bool Virtualized)
{
public bool Ok => (!Exists || Writable) && ReadOnlyFiles == 0 && !Virtualized;
}
/// <summary>The folders RynthAi and the engine write in (only those that exist are checked for writes).</summary>
public static List<string> FoldersToCheck(string suiteDir, string coreDir)
{
string ai = Path.Combine(suiteDir, "RynthAi");
return new List<string>
{
suiteDir, ai,
Path.Combine(ai, "MetaFiles"), Path.Combine(ai, "NavProfiles"),
Path.Combine(ai, "LootProfiles"), Path.Combine(ai, "SettingsProfiles"),
coreDir, Path.Combine(coreDir, "Logs"),
};
}
/// <summary>
/// Writes (and deletes) a throw-away file in <paramref name="folder"/> and counts files under
/// it marked read-only (at most <paramref name="maxFiles"/> looked at; junctions not followed).
/// A folder that doesn't exist is not a problem (nothing to save there yet). Never throws.
/// </summary>
public static FolderStatus Check(string folder, bool countReadOnly = true, int maxFiles = 20_000)
{
bool virtualized = IsVirtualizedLocation(folder);
if (!Directory.Exists(folder))
return new FolderStatus(folder, false, false, null, 0, false);
bool writable = true;
string? problem = null;
string probe = Path.Combine(folder, $".rynthcore-write-check-{Environment.ProcessId}-{Guid.NewGuid():N}.tmp");
try
{
using var fs = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose);
fs.WriteByte(0);
}
catch (Exception ex)
{
writable = false;
problem = Describe(ex);
}
finally
{
try { if (File.Exists(probe)) File.Delete(probe); } catch { }
}
int readOnly = countReadOnly ? CountReadOnlyFiles(folder, recursive: false, maxFiles) : 0;
// Windows redirects only writes that would be refused: a writable folder is written for real.
return new FolderStatus(folder, true, writable, problem, readOnly, virtualized && !writable);
}
/// <summary><see cref="Check"/> for each folder; read-only files are counted in each folder's own files.</summary>
public static List<FolderStatus> CheckAll(IEnumerable<string> folders) =>
folders.Distinct(StringComparer.OrdinalIgnoreCase).Select(f => Check(f)).ToList();
/// <summary>The problems in plain words, one line each (empty when everything is fine).</summary>
public static List<string> DescribeProblems(IEnumerable<FolderStatus> statuses)
{
var lines = new List<string>();
foreach (FolderStatus s in statuses)
{
if (s.Exists && !s.Writable)
lines.Add($"{s.Folder}: can't be written by this Windows account ({s.Problem}).");
if (s.ReadOnlyFiles > 0)
lines.Add($"{s.Folder}: {s.ReadOnlyFiles} file(s) marked read-only.");
if (s.Virtualized)
lines.Add($"{s.Folder}: is under Program Files, where Windows silently redirects the game client's saves to " +
"%LOCALAPPDATA%\\VirtualStore (other tools don't see them). Fix folder permissions makes it writable.");
}
return lines;
}
internal static string Describe(Exception ex) => ex switch
{
UnauthorizedAccessException => "access denied",
DirectoryNotFoundException => "folder missing",
IOException io when io.HResult is unchecked((int)0x80070020) or unchecked((int)0x80070021) => "in use by another program",
IOException io when io.HResult is unchecked((int)0x80070070) => "disk full",
_ => ex.Message,
};
/// <summary>Files (not folders) under <paramref name="folder"/> with the ReadOnly attribute; junctions are not followed.</summary>
public static int CountReadOnlyFiles(string folder, bool recursive, int maxFiles = 20_000)
{
int n = 0, seen = 0;
try
{
var opts = new EnumerationOptions
{
RecurseSubdirectories = recursive,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.ReparsePoint,
ReturnSpecialDirectories = false,
};
foreach (string f in Directory.EnumerateFiles(folder, "*", opts))
{
if (++seen > maxFiles) break;
try { if ((File.GetAttributes(f) & FileAttributes.ReadOnly) != 0) n++; } catch { }
}
}
catch { }
return n;
}
/// <summary>Under Program Files (either) or Windows: a legacy 32-bit client's writes there go to VirtualStore.</summary>
public static bool IsVirtualizedLocation(string folder)
{
foreach (Environment.SpecialFolder sf in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86, Environment.SpecialFolder.Windows })
{
string root;
try { root = Environment.GetFolderPath(sf); } catch { continue; }
if (IsSameOrInside(folder, root)) return true;
}
return false;
}
internal static bool IsSameOrInside(string path, string root)
{
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(root)) return false;
string p = path.TrimEnd('\\', '/');
string r = root.TrimEnd('\\', '/');
return p.Equals(r, StringComparison.OrdinalIgnoreCase)
|| p.StartsWith(r + "\\", StringComparison.OrdinalIgnoreCase);
}
// ── Repair (elevated) ────────────────────────────────────────────────────
/// <summary>The elevated step's command line (each folder quoted).</summary>
public static string BuildRepairArguments(string userSid, IEnumerable<string> roots, string? reportPath = null)
{
var sb = new StringBuilder(RepairArgument).Append(' ').Append(userSid);
if (!string.IsNullOrEmpty(reportPath)) sb.Append(' ').Append(ReportArgument).Append(" \"").Append(reportPath).Append('"');
foreach (string r in roots) sb.Append(" \"").Append(r.TrimEnd('\\')).Append('"');
return sb.ToString();
}
/// <summary>Reads <see cref="BuildRepairArguments"/> back. False when it isn't that command or is malformed.</summary>
public static bool TryParseRepairArguments(string[] args, out string userSid, out List<string> roots, out string? reportPath)
{
userSid = string.Empty;
roots = new List<string>();
reportPath = null;
int i = Array.FindIndex(args, a => string.Equals(a, RepairArgument, StringComparison.OrdinalIgnoreCase));
if (i < 0 || i + 1 >= args.Length) return false;
userSid = args[i + 1];
try { _ = new SecurityIdentifier(userSid); }
catch { return false; }
for (int j = i + 2; j < args.Length; j++)
{
if (string.Equals(args[j], ReportArgument, StringComparison.OrdinalIgnoreCase))
{
if (++j >= args.Length) return false;
reportPath = args[j];
continue;
}
roots.Add(args[j]);
}
return roots.Count > 0;
}
/// <summary>
/// A folder the elevated step may change: absolute, existing, not a junction, not a drive
/// root, not Windows / Program Files / ProgramData / a user profile or anything containing
/// one, and recognisably ours (RynthCore.exe in it, or a RynthAi folder / plugin DLL in it).
/// </summary>
public static bool IsSafeRepairRoot(string path, out string why)
{
why = string.Empty;
string full;
try
{
if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path)) { why = "not an absolute path"; return false; }
full = Path.GetFullPath(path).TrimEnd('\\');
}
catch { why = "not a valid path"; return false; }
string root = (Path.GetPathRoot(full) ?? string.Empty).TrimEnd('\\');
if (full.Length <= root.Length) { why = "a drive root"; return false; }
if (full.StartsWith(@"\\", StringComparison.Ordinal)) { why = "a network path"; return false; }
if (!Directory.Exists(full)) { why = "doesn't exist"; return false; }
try
{
if ((File.GetAttributes(full) & FileAttributes.ReparsePoint) != 0) { why = "a junction or link"; return false; }
}
catch { why = "can't be read"; return false; }
foreach (string special in ProtectedFolders())
if (IsSameOrInside(special, full)) { why = $"is (or contains) {special}"; return false; }
if (IsSameOrInside(full, Environment.GetFolderPath(Environment.SpecialFolder.Windows))) { why = "inside Windows"; return false; }
// Inside Program Files is allowed: once the folder is writable, Windows stops redirecting
// the client's saves to VirtualStore.
bool ours = File.Exists(Path.Combine(full, "RynthCore.exe"))
|| Directory.Exists(Path.Combine(full, "RynthAi"))
|| SafeAny(() => Directory.EnumerateFiles(full, "RynthCore.Plugin.*.dll", SearchOption.AllDirectories).Any());
if (!ours) { why = "doesn't look like a RynthCore or RynthSuite folder"; return false; }
return true;
}
private static bool SafeAny(Func<bool> f)
{
try { return f(); } catch { return false; }
}
private static IEnumerable<string> ProtectedFolders()
{
foreach (Environment.SpecialFolder sf in new[]
{
Environment.SpecialFolder.Windows, Environment.SpecialFolder.System, Environment.SpecialFolder.SystemX86,
Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86,
Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolder.UserProfile,
})
{
string p;
try { p = Environment.GetFolderPath(sf); } catch { continue; }
if (!string.IsNullOrEmpty(p)) yield return p.TrimEnd('\\');
}
string? users;
try { users = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } catch { users = null; }
if (!string.IsNullOrEmpty(users)) yield return users.TrimEnd('\\');
}
/// <summary>What <see cref="Repair"/> did.</summary>
internal sealed class RepairReport
{
public int Roots;
public int ExplicitGrants;
public int ReadOnlyCleared;
public int Errors;
public readonly List<string> Lines = new();
public bool Ok => Errors == 0 && Roots > 0;
public override string ToString() => string.Join(Environment.NewLine, Lines);
}
/// <summary>The ACE the repair adds: Modify for the account, inherited by every sub-folder and file.</summary>
internal static FileSystemAccessRule ModifyRule(SecurityIdentifier user, bool container) =>
new(user, FileSystemRights.Modify | FileSystemRights.Synchronize,
container ? InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit : InheritanceFlags.None,
PropagationFlags.None, AccessControlType.Allow);
/// <summary>
/// The elevated step. For each root (checked with <see cref="IsSafeRepairRoot"/>): grants
/// <paramref name="user"/> Modify, inherited by everything below (Windows passes it down to
/// every sub-folder and file that inherits); sub-folders and files that don't inherit (their
/// own protected permissions) get it explicitly; ReadOnly is cleared on every file. Junctions
/// and links are never followed. Errors are counted and reported, never thrown.
/// <paramref name="changePermissions"/> false: only the read-only part (the offline tests,
/// which must not change permissions on the PC they run on).
/// </summary>
public static RepairReport Repair(IEnumerable<string> roots, SecurityIdentifier user, bool changePermissions = true)
{
var report = new RepairReport();
foreach (string raw in roots)
{
if (!IsSafeRepairRoot(raw, out string why))
{
report.Errors++;
report.Lines.Add($"Skipped {raw}: {why}.");
continue;
}
string root = Path.GetFullPath(raw).TrimEnd('\\');
report.Roots++;
if (changePermissions)
try
{
var di = new DirectoryInfo(root);
DirectorySecurity sec = di.GetAccessControl(AccessControlSections.Access);
sec.AddAccessRule(ModifyRule(user, container: true));
di.SetAccessControl(sec);
report.Lines.Add($"{root}: Modify granted to {user.Value} (passed down to everything inside).");
}
catch (Exception ex)
{
report.Errors++;
report.Lines.Add($"{root}: couldn't change its permissions: {ex.Message}");
continue;
}
var opts = new EnumerationOptions
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.ReparsePoint,
ReturnSpecialDirectories = false,
};
int before = report.Errors;
foreach (string d in changePermissions ? SafeEnumerate(() => Directory.EnumerateDirectories(root, "*", opts)) : Array.Empty<string>())
{
try
{
var sub = new DirectoryInfo(d);
DirectorySecurity s = sub.GetAccessControl(AccessControlSections.Access);
if (s.AreAccessRulesProtected)
{
s.AddAccessRule(ModifyRule(user, container: true));
sub.SetAccessControl(s);
report.ExplicitGrants++;
}
}
catch (Exception ex) { Fail(report, d, ex); }
}
foreach (string f in SafeEnumerate(() => Directory.EnumerateFiles(root, "*", opts)))
{
try
{
if (changePermissions)
{
var fi = new FileInfo(f);
FileSecurity s = fi.GetAccessControl(AccessControlSections.Access);
if (s.AreAccessRulesProtected)
{
s.AddAccessRule(ModifyRule(user, container: false));
fi.SetAccessControl(s);
report.ExplicitGrants++;
}
}
FileAttributes a = File.GetAttributes(f);
if ((a & FileAttributes.ReadOnly) != 0)
{
File.SetAttributes(f, a & ~FileAttributes.ReadOnly);
report.ReadOnlyCleared++;
}
}
catch (Exception ex) { Fail(report, f, ex); }
}
if (report.Errors > before + 20)
report.Lines.Add($"... {report.Errors - before - 20} more error(s) under {root} not listed.");
}
report.Lines.Add($"Done: {report.Roots} folder(s); {report.ReadOnlyCleared} read-only file(s) cleared; " +
$"{report.ExplicitGrants} item(s) with their own permissions granted; {report.Errors} error(s).");
return report;
}
private static void Fail(RepairReport report, string path, Exception ex)
{
report.Errors++;
if (report.Lines.Count < 40) report.Lines.Add($"{path}: {ex.Message}");
}
private static IEnumerable<string> SafeEnumerate(Func<IEnumerable<string>> make)
{
IEnumerator<string>? e = null;
try { e = make().GetEnumerator(); } catch { }
if (e == null) yield break;
using (e)
{
while (true)
{
string cur;
try
{
if (!e.MoveNext()) yield break;
cur = e.Current;
}
catch { yield break; }
yield return cur;
}
}
}
// ── Controlled folder access (Windows Security ransomware protection) ────
/// <summary>What Windows Security's Controlled folder access says about the game client.</summary>
internal sealed record CfaInfo(int Mode, bool ModeKnown, List<CfaBlock> RecentBlocks, List<string>? AllowedApps = null)
{
/// <summary>A block older than this is history, not a reason to warn at every start.</summary>
public static readonly TimeSpan Recent = TimeSpan.FromDays(3);
/// <summary>1 = on (blocks), 2 = audit only, 0 = off.</summary>
public bool On => Mode == 1;
/// <summary>The game client was blocked lately, and isn't in the allowed apps since (as far as we can read them).</summary>
public bool BlocksGameClient => GameClientBlocks(DateTime.UtcNow).Count > 0;
public List<CfaBlock> GameClientBlocks(DateTime nowUtc) => RecentBlocks
.Where(b => b.Blocked && IsGameClient(b.Process)
&& (b.Time == default || nowUtc - b.Time.ToUniversalTime() <= Recent)
&& !(AllowedApps ?? new List<string>()).Any(a => string.Equals(a, b.Process, StringComparison.OrdinalIgnoreCase)))
.ToList();
}
internal sealed record CfaBlock(DateTime Time, string Process, string Path, bool Blocked);
internal static bool IsGameClient(string process) =>
process.EndsWith("acclient.exe", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Best effort, no administrator rights needed: the Controlled folder access mode from the
/// registry (Windows Security's switch, or group policy), and the last blocks (Defender event
/// 1123; 1124 = audited) from Microsoft-Windows-Windows Defender/Operational via wevtutil.
/// Never throws; unknown parts stay empty.
/// </summary>
public static CfaInfo QueryControlledFolderAccess(int maxEvents = 50)
{
int mode = 0;
bool known = false;
foreach (string key in new[]
{
@"SOFTWARE\Policies\Microsoft\Windows Defender\Windows Defender Exploit Guard\Controlled Folder Access",
@"SOFTWARE\Microsoft\Windows Defender\Windows Defender Exploit Guard\Controlled Folder Access",
})
{
try
{
using RegistryKey? k = Registry.LocalMachine.OpenSubKey(key);
if (k?.GetValue("EnableControlledFolderAccess") is int v)
{
mode = v;
known = true;
break;
}
if (k != null) known = true;
}
catch { }
}
// Apps already allowed through (Windows Security's list; group policy's is not read).
var allowed = new List<string>();
try
{
using RegistryKey? k = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows Defender\Windows Defender Exploit Guard\Controlled Folder Access\AllowedApplications");
if (k != null) allowed.AddRange(k.GetValueNames());
}
catch { }
var blocks = new List<CfaBlock>();
try
{
string wevtutil = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "wevtutil.exe");
var psi = new ProcessStartInfo(wevtutil)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
};
foreach (string a in new[] { "qe", "Microsoft-Windows-Windows Defender/Operational",
"/q:*[System[(EventID=1123 or EventID=1124)]]", $"/c:{maxEvents}", "/rd:true", "/f:xml" })
psi.ArgumentList.Add(a);
using Process? p = Process.Start(psi);
if (p != null)
{
string xml = p.StandardOutput.ReadToEnd();
p.WaitForExit(10_000);
blocks.AddRange(ParseCfaEvents(xml));
}
}
catch { }
return new CfaInfo(mode, known, blocks, allowed);
}
/// <summary>Defender 1123/1124 events (wevtutil /f:xml output, events back to back) as blocks.</summary>
internal static List<CfaBlock> ParseCfaEvents(string xml)
{
var list = new List<CfaBlock>();
if (string.IsNullOrWhiteSpace(xml)) return list;
try
{
var doc = new XmlDocument();
doc.LoadXml("<Events>" + xml + "</Events>");
var ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("e", "http://schemas.microsoft.com/win/2004/08/events/event");
XmlNodeList? events = doc.SelectNodes("/Events/e:Event", ns);
if (events == null) return list;
foreach (XmlNode ev in events)
{
string id = ev.SelectSingleNode("e:System/e:EventID", ns)?.InnerText ?? "";
string time = ev.SelectSingleNode("e:System/e:TimeCreated/@SystemTime", ns)?.Value ?? "";
string process = "", path = "";
XmlNodeList? data = ev.SelectNodes("e:EventData/e:Data", ns);
if (data != null)
foreach (XmlNode d in data)
{
string name = d.Attributes?["Name"]?.Value ?? "";
if (name.Equals("Process Name", StringComparison.OrdinalIgnoreCase)) process = d.InnerText;
else if (name.Equals("Path", StringComparison.OrdinalIgnoreCase)) path = d.InnerText;
}
DateTime.TryParse(time, null, System.Globalization.DateTimeStyles.RoundtripKind, out DateTime t);
list.Add(new CfaBlock(t, process, path, id == "1123"));
}
}
catch { }
return list;
}
/// <summary>How to let the game client through, in Windows Security's words.</summary>
public const string CfaAllowHowTo =
"Windows Security > Virus & threat protection > Manage ransomware protection > " +
"Allow an app through Controlled folder access > Add an allowed app > Browse all apps, and pick acclient.exe " +
"(in your Asheron's Call folder). Or keep RynthSuite in C:\\Games, which isn't protected unless you added it.";
}

View file

@ -0,0 +1,130 @@
using System.Globalization;
using System.Text;
namespace RynthCore;
/// <summary>
/// Desktop text logs with a fixed size cap and per-day roll retention. Active file lives on the user
/// desktop as <c>{fileStem}.log</c>. When the active file reaches <see cref="MaxActiveFileBytes"/>,
/// it is moved into <c>Desktop\RynthLogs\</c> with a time-stamped name, then a new active file is
/// created. For each <paramref name="fileStem"/> and each calendar day, at most
/// <see cref="MaxRolledFilesPerLocalDay"/> archived files are kept (oldest for that day deleted first).
/// </summary>
public static class DesktopRollingLog
{
// 10 MB active segment, up to 10 rolled segments per local calendar day.
public const long MaxActiveFileBytes = 10L * 1024 * 1024;
public const int MaxRolledFilesPerLocalDay = 10;
private static readonly string DesktopDir =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private static readonly string ArchiveDir = Path.Combine(DesktopDir, "RynthLogs");
/// <summary>Pre-defined stems for the three Rynth products (one file each on the desktop).</summary>
public const string StemEngine = "RynthCore";
public const string StemLauncher = "RynthCore-Launcher";
public const string StemInjector = "RynthCore-Injector";
private static readonly object Gate = new();
/// <param name="fileStem">File name without extension, e.g. <see cref="StemEngine"/>.</param>
public static void AppendLine(string fileStem, string line)
{
string stem = SanitizeStem(fileStem);
string text = line ?? string.Empty;
if (text.Length > 0 && text[^1] is not '\n' and not '\r')
text += Environment.NewLine;
lock (Gate)
{
try
{
string active = Path.Combine(DesktopDir, stem + ".log");
Directory.CreateDirectory(ArchiveDir);
if (File.Exists(active) && new FileInfo(active).Length + Encoding.UTF8.GetByteCount(text) > MaxActiveFileBytes)
RotateToArchive(stem, active);
using var stream = new FileStream(active, FileMode.Append, FileAccess.Write, FileShare.Read);
var bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
catch
{
// Intentionally silent: logging must not crash host.
}
}
}
// Moves current active file to RynthLogs; trims same-day archives for this stem, then the move.
private static void RotateToArchive(string stem, string activePath)
{
string ymd = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
string prefix = stem + "-roll-" + ymd + "-";
PruneOldestRolledForPrefix(prefix);
string destName = prefix + DateTime.Now.ToString("HHmmssfff", CultureInfo.InvariantCulture) + ".log";
string destPath = Path.Combine(ArchiveDir, destName);
if (File.Exists(destPath)) File.Delete(destPath);
try
{
File.Move(activePath, destPath, overwrite: false);
}
catch
{
try
{
if (File.Exists(destPath)) File.Delete(destPath);
}
catch
{
// ignore
}
if (File.Exists(activePath)) File.Delete(activePath);
}
}
// Ensures that after a new file with this prefix is created, at most MaxRolledFilesPerLocalDay rolled files for this prefix+day exist.
private static void PruneOldestRolledForPrefix(string prefix)
{
if (!Directory.Exists(ArchiveDir)) return;
var todaysRolled = new DirectoryInfo(ArchiveDir)
.GetFiles(prefix + "*.log", SearchOption.TopDirectoryOnly)
.OrderBy(f => f.CreationTimeUtc)
.ThenBy(f => f.Name, StringComparer.OrdinalIgnoreCase)
.ToList();
// Delete oldest rolled segments until a new one would not exceed the daily cap.
while (todaysRolled.Count >= MaxRolledFilesPerLocalDay)
{
try
{
todaysRolled[0].Delete();
todaysRolled.RemoveAt(0);
}
catch
{
break;
}
}
}
private static string SanitizeStem(string? stem)
{
if (string.IsNullOrWhiteSpace(stem)) return "RynthLog";
var invalid = Path.GetInvalidFileNameChars();
var b = new StringBuilder(stem.Length);
foreach (var ch in stem.Trim())
{
if (!invalid.Contains(ch) && ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar)
b.Append(ch);
}
string t = b.ToString();
return t.Length == 0 ? "RynthLog" : t;
}
}

View file

@ -0,0 +1,105 @@
// Detects the same "Suite tools" .NET 10+ x64 prerequisite as the Inno installer
// (installer\RynthCore.iss, IsNetDesktop* helpers). If you change registry checks here,
// update RynthCore.iss in lockstep and vice versa.
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using Microsoft.Win32;
namespace RynthCore;
/// <summary>
/// Registry probe for the optional x64 framework-dependent tools (Loot Editor, Monster Editor).
/// Must match <c>IsNetDesktop10PlusX64Present</c> and its helpers in <c>installer/RynthCore.iss</c>
/// (Path A: <c>Microsoft.WindowsDesktop.App</c> shared folders; Path B: <c>sharedhost</c> Version;
/// Path C: <c>InstalledManifests\x64</c> manifest-10. bands). Uses 64-bit registry view from an x86 process.
/// </summary>
[SupportedOSPlatform("windows")]
public static class NetDesktopX64Prerequisite
{
// Same string as RynthCore.iss DotNet10DesktopDownloadUrl (x64 runtime hub; user picks Desktop / ASP.NET as needed).
public const string DotNet10RuntimeDownloadUrl = "https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime";
/// <summary>True if the x64 FDD tool prerequisite is met, or the OS is 32-bit (N/A, same as Inno skip).</summary>
public static bool IsSatisfied()
{
if (!Environment.Is64BitOperatingSystem)
return true;
return
IsWindowsDesktopSharedFramework10Plus()
|| IsDotNet10BandInInstalledManifestsX64()
|| IsSharedHostVersion10PlusX64();
}
// Path A: HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\10.x.y
private static bool IsWindowsDesktopSharedFramework10Plus()
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App");
if (key is null)
return false;
foreach (string name in key.GetSubKeyNames())
{
if (ParseMajorFromVersionFolder(name) >= 10)
return true;
}
return false;
}
// Path B: sharedhost Version 10+ under Setup\InstalledVersions\x64\sharedhost
private static bool IsSharedHostVersion10PlusX64()
{
if (ReadSharedHostMajor(@"SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
return true;
if (ReadSharedHostMajor(@"SOFTWARE\Microsoft\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
return true;
return false;
}
private static int ReadSharedHostMajor(string subKeyPath)
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(subKeyPath);
if (key is null)
return 0;
string? v = key.GetValue("Version") as string;
if (string.IsNullOrWhiteSpace(v))
return 0;
return ParseMajorFromVersionFolder(v.Trim());
}
// Path C: InstalledManifests x64, subkeys like ...Manifest-10.0.100
private static bool IsDotNet10BandInInstalledManifestsX64()
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\Microsoft\dotnet\InstalledManifests\x64");
if (key is null)
return false;
return key.GetSubKeyNames().Any(s => s != null
&& s.IndexOf("Manifest-10.", StringComparison.OrdinalIgnoreCase) >= 0);
}
private static RegistryKey? OpenLocalMachine64() =>
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
/// <summary>First numeric segment of a "10.0.5" style folder or version string (Pascal: Copy before first '.').</summary>
private static int ParseMajorFromVersionFolder(string name)
{
int dot = name.IndexOf('.');
if (dot <= 0)
return 0;
return int.TryParse(
name.AsSpan(0, dot),
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out int m)
? m
: 0;
}
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>RynthCore</RootNamespace>
<AssemblyName>RynthCore.DesktopLog</AssemblyName>
<Version>1.0.1</Version>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AcKeyboardFocus.cs
//
// "Is the player typing into one of AC's own text boxes?" - for the user
// hotkeys (Hotkeys/HotkeyService.cs), which must never fire while the chat
// entry (or a quantity box, a name field...) has the keyboard.
//
// Evidence (AC client decompile, C:\Projects\GhidraTools\decompiled):
// UIElementManager::SetFocusElement (0x0045B970) keeps the element with the
// keyboard focus at manager +0x328 (tells the old one it lost focus with
// element message 0x2F / vtable +0xB4, the new one with 0x2F / +0xB0).
// UIElementManager::KeyPressEvent (0x0045C3E0) and ::ActionHandler (0x0045CD80)
// offer every key to +0x328 first (then +0x32C) and only broadcast it to the
// game (movement, shortcuts) when that element doesn't take it: a non-zero
// +0x328 is the element typed keys go to.
// UIElement::TakeFocus (0x004602C0) sets it; UIElement::Deactivate (0x00461E30)
// and UIElement::RelinquishFocus (0x00461EC0) clear it to 0.
// Only the pointer is read (never dereferenced on the key path). The manager is
// UiElementHooks.Manager (the tooltip hooks' `this`, as AcMouseOver uses); no
// manager = unknown, and the hotkeys then fire only for Ctrl/Alt/F-key combos.
//
// Threads: AC's main thread (the WndProc and EndScene run there).
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class AcKeyboardFocus
{
private const int MgrFocusElement = 0x328;
private const int ElementIdOffset = 0x2E4;
/// <summary>The element with AC's keyboard focus (0 = none), or null when AC's UI manager isn't readable.</summary>
public static IntPtr? FocusElement()
{
try
{
if (!MainThreadGuard.IsOnMainThread()) return null;
IntPtr mgr = UiElementHooks.Manager;
if (mgr == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(mgr + MgrFocusElement, 4)) return null;
return *(IntPtr*)(mgr + MgrFocusElement);
}
catch
{
return null;
}
}
/// <summary>True: an AC text box has the keyboard; false: none; null: unknown.</summary>
public static bool? HasTextFocus()
{
IntPtr? e = FocusElement();
return e == null ? null : e.Value != IntPtr.Zero;
}
/// <summary>For /rc hotkey status: AC's focus element and its id.</summary>
public static string Describe()
{
IntPtr? e = FocusElement();
if (e == null)
return UiElementHooks.Manager == IntPtr.Zero
? "AC keyboard focus: unknown (AC's UI manager not seen yet: the tooltip hooks are off or haven't run)."
: "AC keyboard focus: unknown (not readable).";
if (e.Value == IntPtr.Zero) return "AC keyboard focus: none (keys go to the game).";
uint id = 0;
try
{
if (ClientObjectHooks.IsReadableSpan(e.Value + ElementIdOffset, 4)) id = *(uint*)(e.Value + ElementIdOffset);
}
catch { }
return $"AC keyboard focus: element 0x{e.Value.ToInt64():X8} id 0x{id:X8} (typing: hotkeys held back).";
}
}

View file

@ -152,6 +152,13 @@ internal static class AcMainThreadQueue
// send like DropItem; in the ring so a close queued before the next corpse's UseObject
// goes out first, in the same drain. A = container id.
CloseContainer,
// v82 SalvageDirect (2026-10-12): CM_Inventory::Event_CreateTinkeringTool (the 0x027D salvage
// game action, without the panel). An inventory send like DropItem. The item list doesn't fit
// the four slots: A = the UST, B = the index of the list in _salvageDirectLists.
SalvageDirect,
// v83 RemoveClientObject (2026-10-12): drop a ghost creature from the client
// (DeleteObjectHooks.RemoveNow re-checks on the main thread).
RemoveClientObject,
}
// Four payload slots cover every routed action (the 4th was added for
@ -246,6 +253,35 @@ internal static class AcMainThreadQueue
_ => false,
};
/// <summary>
/// Stops and cancels: the teardown group that still runs after a world transition (every
/// other entry queued during one is dropped). Never dropped as stale either.
/// </summary>
private static bool IsTeardown(in Entry e) => IsTeardownKind(e.Kind, e.A, e.B);
/// <summary>
/// The ONE teardown predicate: the enqueue side (ActionRing admission, the teardown reserve)
/// and the drain side (which entries survive a world transition) both ask it.
/// </summary>
internal static bool IsTeardownKind(ActionKind kind, uint a, uint b) => kind switch
{
ActionKind.SetAutoRun => a == 0,
ActionKind.SetMotion => b == 0,
ActionKind.StopMovement or ActionKind.StopCompletely or ActionKind.CancelAttack
or ActionKind.CloseContainer => true,
_ => false,
};
// World-transition drops: counted, and folded into the rate-limited stale summary line.
private static long _transitionDropped;
public static long TransitionDroppedCount => Interlocked.Read(ref _transitionDropped);
private static void NoteTransitionDrop(string what, long ageMs)
{
Interlocked.Increment(ref _transitionDropped);
NoteStale(what + " (queued during a death/portal/teleport)", ageMs, dropped: true);
}
private static string Describe(in Entry e) => e.Kind switch
{
ActionKind.SetAutoRun => e.A != 0 ? "SetAutoRun(on)" : "SetAutoRun(off)",
@ -256,38 +292,64 @@ internal static class AcMainThreadQueue
_ => e.Kind.ToString(),
};
// The ring (ActionRing: storage, FIFO, admission). 256 entries, the top 32 for teardown
// only, so a ring a bot filled with starts still takes its stops and cancels.
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 const int TeardownReserve = 32;
private static readonly ActionRing<Entry> _ring = new(Capacity, TeardownReserve);
private static long _dropped;
private static long _transitionRejected;
/// <summary>Entries refused because the ring was full (a running total; the heartbeat's qdrop).</summary>
public static long DroppedCount => Interlocked.Read(ref _dropped);
/// <summary>Non-teardown entries refused while the player was in a world transition.</summary>
public static long TransitionRejectedCount => Interlocked.Read(ref _transitionRejected);
// -- The mutator gate ----------------------------------------------------------
// Every AC-mutating helper (ClientHelperHooks, CombatActionHooks, MovementActionHooks,
// CommandInterpreterHooks, ClientCombatHooks, PlayerPhysicsHooks, PlayerTrade,
// PlayerTraining) opens with the same line:
// if (AcMainThreadQueue.MustQueue(teardown: <is this a stop/cancel>)) return Enqueue...;
// Off AC's main thread it queues (as always). ON the main thread it also queues while a
// world transition holds the drains, unless it is being called BY a drain (IsDraining)
// or is teardown: render-thread host actions (ImGui panels, the EndScene plugin calls)
// used to run straight into a world AC was tearing down, around the gate. The queue
// then refuses or holds it like any other queued work (WorldTransitionState).
private static int _drainDepth; // AC main thread only
/// <summary>AC main thread only: a drain is dispatching queued work right now.</summary>
public static bool IsDraining => _drainDepth > 0;
/// <summary>AC main thread only: a direct call now would run into a world transition.</summary>
public static bool ShouldDefer() => !IsDraining && PlayerLifecycleLog.HoldQueuedWork(NowMs);
/// <summary>
/// The one gate every mutator opens with: true = queue instead of calling AC now.
/// <paramref name="teardown"/>: a stop or cancel (IsTeardownKind), which runs at once on
/// the main thread even in a transition.
/// </summary>
public static bool MustQueue(bool teardown) =>
MutatorGate.MustQueue(MainThreadGuard.IsOnMainThread(), teardown, IsDraining, HoldNow);
// Cached (no allocation per call): main thread only, asked only by MutatorGate on it.
private static readonly Func<bool> HoldNow = () => PlayerLifecycleLog.HoldQueuedWork(NowMs);
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, NowMs, Volatile.Read(ref _loginEpoch));
Volatile.Write(ref _tail, tail + 1);
return true;
}
bool teardown = IsTeardownKind(kind, a, b);
// Dead / portaling / settling: a start queued now would be dropped when the window
// ends anyway (WorldTransitionState), so it is refused here and never takes a slot a
// stop needs. Stops and cancels are always taken (the reserve keeps room for them).
var r = _ring.TryEnqueue(new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)),
teardown, PlayerLifecycleLog.InWorldTransition);
if (r == ActionRing<Entry>.Admit.Queued) return true;
// 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.
if (r == ActionRing<Entry>.Admit.Full) Interlocked.Increment(ref _dropped);
else Interlocked.Increment(ref _transitionRejected);
return false;
}
// ── Typed enqueue helpers (called by the public action methods when they
@ -336,19 +398,33 @@ internal static class AcMainThreadQueue
// CommandInterpreter turn, which would change the steering behaviour.
private static int _directHeadingPending;
private static uint _directHeadingBits;
private static long _directHeadingAt;
public static bool EnqueueDirectHeading(float headingDegrees)
{
Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees));
Interlocked.Exchange(ref _directHeadingAt, NowMs);
Volatile.Write(ref _directHeadingPending, 1);
return true;
}
// Main thread only (from Drain). Same order as the pre-queue code: the direct
// snap first, the CommandInterpreter turn only when there is no player.
// World transition: the pending heading is held; once the window ends a heading set
// during it is stale (the bot steers again from where it landed) and is dropped.
private static void DrainDirectHeading()
{
if (Volatile.Read(ref _directHeadingPending) == 0) return;
long now = NowMs;
long at = Interlocked.Read(ref _directHeadingAt);
WorldTransitionState.Verdict v = PlayerLifecycleLog.DecideQueued(now, at, teardown: false);
if (v == WorldTransitionState.Verdict.Hold) return;
if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return;
if (v == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop("heading", now - at);
return;
}
float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits));
try
{
@ -371,18 +447,25 @@ internal static class AcMainThreadQueue
// selects mid-gesture too). Lock-free and allocation-free.
private static int _overlaySelectPending;
private static uint _overlaySelectId;
private static long _overlaySelectAt;
public static bool EnqueueOverlaySelect(uint objectId)
{
if (objectId == 0) return false;
Volatile.Write(ref _overlaySelectId, objectId);
Interlocked.Exchange(ref _overlaySelectAt, NowMs);
Volatile.Write(ref _overlaySelectPending, 1);
return true;
}
// Main thread only (from Drain).
// Main thread only (from Drain). World transition: held, and kept when the window ends:
// it is the user's own click, and SelectFromOverlay re-checks the object still exists.
private static void DrainOverlaySelect()
{
if (Volatile.Read(ref _overlaySelectPending) == 0) return;
if (PlayerLifecycleLog.DecideQueued(NowMs, Interlocked.Read(ref _overlaySelectAt), teardown: true)
== WorldTransitionState.Verdict.Hold)
return;
if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return;
uint id = Volatile.Read(ref _overlaySelectId);
try { ClientHelperHooks.SelectFromOverlay(id); }
@ -449,6 +532,48 @@ internal static class AcMainThreadQueue
public static bool EnqueueSalvageExecute() =>
Enqueue(ActionKind.SalvageExecute, 0, 0, 0);
// ── Salvage-without-panel item lists (v82) ──────────────────────────────────
// A SalvageDirect entry carries its item list here: the producer copies the ids into a fresh
// array and parks it in a free slot (under _salvageDirectLock), the ring entry carries the slot
// index, and the drain takes it back with one Interlocked.Exchange (lock-free, no allocation on
// the main thread). Eight slots: the bot has one request in flight at a time; a full set refuses.
private const int SalvageDirectSlots = 8;
private static readonly uint[]?[] _salvageDirectLists = new uint[]?[SalvageDirectSlots];
private static int _salvageDirectNext;
// Serializes slot claims (the ring has its own lock since ActionRing<T>, PR #8).
private static readonly object _salvageDirectLock = new();
public static bool EnqueueSalvageDirect(uint toolId, uint[] itemIds)
{
if (toolId == 0 || itemIds == null || itemIds.Length == 0) return false;
uint[] copy = (uint[])itemIds.Clone();
lock (_salvageDirectLock)
{
for (int k = 0; k < SalvageDirectSlots; k++)
{
int i = (_salvageDirectNext + k) % SalvageDirectSlots;
if (Volatile.Read(ref _salvageDirectLists[i]) != null) continue;
Volatile.Write(ref _salvageDirectLists[i], copy);
if (!Enqueue(ActionKind.SalvageDirect, toolId, (uint)i, 0))
{
Volatile.Write(ref _salvageDirectLists[i], null);
return false;
}
_salvageDirectNext = (i + 1) % SalvageDirectSlots;
return true;
}
}
Interlocked.Increment(ref _dropped);
return false;
}
/// <summary>Main thread: takes the list a SalvageDirect entry parked (null if none).</summary>
private static uint[]? TakeSalvageDirectList(uint slot) =>
slot < SalvageDirectSlots ? Interlocked.Exchange(ref _salvageDirectLists[slot], null) : null;
public static bool EnqueueRemoveClientObject(uint objectId) =>
Enqueue(ActionKind.RemoveClientObject, objectId, 0, 0);
public static bool EnqueueSetSelectedObject(uint objectId) =>
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
@ -491,6 +616,14 @@ internal static class AcMainThreadQueue
private static long _drainDeferSinceMs;
public static void Drain()
{
// IsDraining: the helpers this dispatches run their AC call directly (MustQueue).
_drainDepth++;
try { DrainCore(); }
finally { _drainDepth--; }
}
private static void DrainCore()
{
if (_disarmed)
{
@ -524,14 +657,23 @@ internal static class AcMainThreadQueue
// 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).
// World transition gate (dead / portal / landblock jump, WorldTransitionState): AC is
// tearing objects down and loading new ones, so nothing queued that mutates the game
// runs now. Chat output (AC's own text window) and the char-select service still do.
long gateNow = NowMs;
bool holding = PlayerLifecycleLog.HoldQueuedWork(gateNow);
DrainChat();
DrainChatCommands();
if (!holding) DrainChatCommands(); // held: their own 15 s age limit still applies
DrainRequestIds();
DrainQueryHealth();
// 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 { }
if (!holding)
{
try { VendorTrade.MainThreadTick(); } catch { }
}
// Char-select service: publishes the UIFlow mode, runs a pending auto-login
// LogOnCharacter request and snapshots the native character list (throttled).
// Pre-login this runs from the Client::UseTime drain (EndScene is not hooked
@ -541,14 +683,19 @@ internal static class AcMainThreadQueue
// Plugin heading snap (coalesced slot). Before the ring and its gesture
// defer: the pre-queue raw write landed immediately, gesture or not, and
// ahead of the SetAutoRun a nav tick queues right after it. Keep both.
// Both are latest-value slots (a heading, a select): held through a world transition,
// then decided by their own drains (a stale heading dropped, a user's select kept).
DrainDirectHeading();
// Overlay click-to-select (Radar dot / nameplate click): also before the
// gesture defer, so a click selects at once even while the bot swings.
DrainOverlaySelect();
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// In a world transition the ring is held whole (FIFO kept): nothing runs, nothing is
// dropped yet. Once it ends, the loop below drops what was queued during it, except
// stops and cancels, which run in order as one teardown group.
if (holding)
return;
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
// to the whole ring) ─────────────────────────────────────────────────
@ -562,7 +709,7 @@ internal static class AcMainThreadQueue
// 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 (_ring.Count > 0)
{
// In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate).
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
@ -576,16 +723,22 @@ internal static class AcMainThreadQueue
}
long runAt = NowMs;
int epochNow = Volatile.Read(ref _loginEpoch);
while (head != tail)
// Bounded to what is queued now plus a capacity's worth: an action that re-queues
// itself can never spin the main thread.
int budget = Capacity * 2;
while (budget-- > 0 && _ring.TryDequeue(out Entry e))
{
Entry e = _slots[head & Mask];
Volatile.Write(ref _head, ++head);
long age = runAt - e.At;
if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop(Describe(e), age);
if (e.Kind == ActionKind.SalvageDirect) TakeSalvageDirectList(e.B); // free its list slot
continue;
}
if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e)))
{
NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true);
tail = Volatile.Read(ref _tail);
if (e.Kind == ActionKind.SalvageDirect) TakeSalvageDirectList(e.B); // free its list slot
continue;
}
if (age > LateActionLogMs)
@ -673,6 +826,13 @@ internal static class AcMainThreadQueue
case ActionKind.SalvageExecute:
ClientHelperHooks.SalvagePanelExecute();
break;
case ActionKind.SalvageDirect:
if (TakeSalvageDirectList(e.B) is uint[] salvageItems)
ClientHelperHooks.SalvageDirect(e.A, salvageItems);
break;
case ActionKind.RemoveClientObject:
DeleteObjectHooks.RemoveNow(e.A);
break;
case ActionKind.SetSelectedObject:
// On the main thread now -> SetSelectedObjectId's gate is
// satisfied and it calls AC's SetSelectedObject directly.
@ -719,8 +879,6 @@ internal static class AcMainThreadQueue
// 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);
}
}
@ -733,22 +891,43 @@ internal static class AcMainThreadQueue
// 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 Id, long At, int Epoch)> _requestIdQueue = new();
private static readonly object _requestIdLock = new();
// A request for an object that already has one pending is merged into it, as the
// QueryHealth slot does: the one appraisal reply answers every caller (PendingIdQueue).
private const int MaxRequestIdQueue = 256;
private static readonly PendingIdQueue _requestIdQueue = new(MaxRequestIdQueue);
private static readonly object _requestIdLock = new();
// Merge only into an entry the drain will still send: half the stale limit leaves room
// for a drain that runs late (a stalled main thread).
private const long RequestIdMergeMaxAgeMs = RequestIdMaxAgeMs / 2;
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueRequestId(uint objectId)
/// <summary>RequestId calls absorbed by an already-pending request for the same object.</summary>
public static long RequestIdMergedCount
{
get { lock (_requestIdLock) return _requestIdQueue.MergedTotal; }
}
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full. A request for an
// object already waiting returns true without queueing a second send.
// <paramref name="who"/> rides with the entry so the drain can mark the real send as the
// engine's (Net/IdRequester.cs); a merge keeps the first requester.
public static bool EnqueueRequestId(uint objectId, Net.IdRequester who = Net.IdRequester.None)
{
if (objectId == 0) return false;
// Dead / portaling / settling: an appraisal queued now is dropped when the window
// ends, so it is refused here (the caller sees false and may ask again later). Nor
// does a request merge into an entry from before the last held drain: that entry is
// dropped when the drain reaches it, and the merged request would go with it.
if (PlayerLifecycleLog.InWorldTransition) return false;
long mergeOnlyAfter = PlayerLifecycleLog.LastBlockedMs;
lock (_requestIdLock)
{
if (_requestIdQueue.Count >= MaxRequestIdQueue)
PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch),
RequestIdMergeMaxAgeMs, mergeOnlyAfter, (byte)who);
if (r == PendingIdQueue.Result.Full)
{
Interlocked.Increment(ref _dropped);
return false;
}
_requestIdQueue.Enqueue((objectId, NowMs, Volatile.Read(ref _loginEpoch)));
return true;
}
}
@ -760,22 +939,42 @@ internal static class AcMainThreadQueue
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
int budget;
lock (_requestIdLock) budget = _requestIdQueue.Count;
if (budget == 0) return;
long now = NowMs;
// World transition (dead / portal / landblock jump): hold every appraisal; once it
// ends, those queued during it are dropped (WorldTransitionState).
if (PlayerLifecycleLog.HoldQueuedWork(now)) return;
int epoch = Volatile.Read(ref _loginEpoch);
while (budget-- > 0)
{
(uint Id, long At, int Epoch) item;
PendingIdQueue.Item item;
lock (_requestIdLock)
{
if (_requestIdQueue.Count == 0) return;
item = _requestIdQueue.Dequeue();
if (!_requestIdQueue.TryDequeue(out item)) return;
}
if (item.Epoch != epoch || now - item.At > RequestIdMaxAgeMs)
{
NoteStale($"RequestId(0x{item.Id:X8})", now - item.At, dropped: true);
continue;
}
try { CombatActionHooks.RequestId(item.Id); } catch { }
if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop($"RequestId(0x{item.Id:X8})", now - item.At);
continue;
}
bool sent = false;
try
{
using (Net.EngineSendMarker.Enter((Net.IdRequester)item.Source))
sent = CombatActionHooks.RequestId(item.Id);
}
catch { }
// AutoId's re-appraisal window starts at the real send, not at the queueing:
// a request dropped here (stale, transition) leaves the object due again.
if (sent)
{
try { AutoIdService.OnSent(item.Id, now); } catch { }
}
}
}
@ -819,6 +1018,7 @@ internal static class AcMainThreadQueue
int budget;
lock (_queryHealthLock) budget = _queryHealthQueue.Count;
long now = NowMs;
if (PlayerLifecycleLog.HoldQueuedWork(now)) return; // world transition: hold
int epoch = Volatile.Read(ref _loginEpoch);
while (budget-- > 0)
{
@ -834,6 +1034,11 @@ internal static class AcMainThreadQueue
NoteStale($"QueryHealth(0x{item.Id:X8})", now - item.At, dropped: true);
continue;
}
if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop($"QueryHealth(0x{item.Id:X8})", now - item.At);
continue;
}
try { CombatActionHooks.QueryHealth(item.Id); } catch { }
}
}
@ -958,9 +1163,7 @@ internal static class AcMainThreadQueue
// 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 CastSlot _cast = new(); // writes under _castLock
private static readonly object _castLock = new();
// Ticks DrainCasts has deferred the pending cast because a motion gesture was
@ -969,30 +1172,27 @@ internal static class AcMainThreadQueue
// 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 long _castDeferDrops;
private static long _castQueuedAt; // TickCount64 when the pending cast was queued (2026-10-06)
/// <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.
// already pending, or during a world transition (CastSlot): the drain would only hold
// it and then drop it, and the slot would refuse every newer cast meanwhile.
public static bool EnqueueCast(uint targetId, uint spellId)
{
CastSlot.Admit admit;
lock (_castLock)
{
if (_castPending != 0) return false;
_castTargetId = targetId;
_castSpellId = spellId;
_castQueuedAt = NowMs;
_castStopWaitNoted = false;
_castPending = 1;
return true;
}
admit = _cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition);
if (admit == CastSlot.Admit.RejectedTransition)
Interlocked.Increment(ref _transitionRejected);
return admit == CastSlot.Admit.Queued;
}
// Casts that waited for a movement stop queued ahead of them (counted once per cast).
// Casts that waited for a movement stop queued ahead of them (counted once per cast;
// the per-cast flag is CastSlot.StopWaitNoted, reset by each new cast).
private static long _castStopWaits;
private static bool _castStopWaitNoted;
/// <summary>Casts that waited one or more ticks for a stop queued ahead of them.</summary>
public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits);
@ -1008,29 +1208,28 @@ internal static class AcMainThreadQueue
/// <summary>
/// True when the action ring holds a movement stop queued at or before <paramref name="castQueuedAt"/>.
/// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so
/// their times rise from head to tail and the walk stops at the first newer one.
/// Main thread only (the ring's sole consumer). An entry's time is taken before ActionRing's
/// producer lock, so two producers can land slightly out of time order: the walk checks every
/// queued entry (at most Capacity) instead of stopping at the first newer one (CastStopRules).
/// </summary>
private static bool StopQueuedAtOrBefore(long castQueuedAt)
{
int head = _head;
int tail = Volatile.Read(ref _tail);
for (int i = head; i != tail; i++)
{
ref readonly Entry e = ref _slots[i & Mask];
if (e.At > castQueuedAt) return false;
if (IsMovementStop(e)) return true;
}
return false;
}
private static bool StopQueuedAtOrBefore(long castQueuedAt) =>
CastStopRules.AnyStopAtOrBefore(_ring, castQueuedAt, static e => e.At, static e => IsMovementStop(e));
// 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).
// cast directly via the SEH trampoline (targeted: FreeHandsAndCastSpell with the target
// passed explicitly, no SelectItem; self: ClientMagicSystem::CastSpell).
public static void DrainCasts()
{
_drainDepth++;
try { DrainCastsCore(); }
finally { _drainDepth--; }
}
private static void DrainCastsCore()
{
if (_disarmed) return; // engine teardown in progress
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path
if (Volatile.Read(ref _cast.Pending) == 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
@ -1049,7 +1248,23 @@ internal static class AcMainThreadQueue
// CastDeferMaxMs the cast is dropped and logged with its age. RynthAi waits up to 7 s
// for a cast's answer before it sends another (ActionPacer), so a drop here can't
// leave two casts in flight.
long castAge = NowMs - Volatile.Read(ref _castQueuedAt);
// World transition (dead / portal / landblock jump): hold the cast; a cast queued
// during it is dropped once it ends (WorldTransitionState). Before the gesture check:
// nothing about the player's motion is read while AC is tearing the world down.
long nowCast = NowMs;
long queuedAt = Volatile.Read(ref _cast.QueuedAt);
WorldTransitionState.Verdict castVerdict = PlayerLifecycleLog.DecideQueued(nowCast, queuedAt, teardown: false);
if (castVerdict == WorldTransitionState.Verdict.Hold)
return;
if (castVerdict == WorldTransitionState.Verdict.Drop)
{
uint droppedSpell;
lock (_castLock) { droppedSpell = _cast.SpellId; _cast.Pending = 0; }
NoteTransitionDrop($"CastSpell({droppedSpell})", nowCast - queuedAt);
return;
}
long castAge = nowCast - queuedAt;
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
{
if (castAge <= CastDeferMaxMs)
@ -1057,7 +1272,7 @@ internal static class AcMainThreadQueue
// Gesture stuck past the deadline — drop the cast instead of injecting
// into a wedged motion graph; the plugin retries via no-chat-resolve.
uint dropped;
lock (_castLock) { dropped = _castSpellId; _castPending = 0; }
lock (_castLock) { dropped = _cast.SpellId; _cast.Pending = 0; }
Interlocked.Increment(ref _castDeferDrops);
NoteStale($"CastSpell({dropped}) behind a gesture", castAge, dropped: true);
return;
@ -1070,13 +1285,13 @@ internal static class AcMainThreadQueue
// locomotion still on, and the queued stops followed as extra MoveToStates. Wait (at
// most until EndScene drains the ring, about one frame; the ring's own gesture defer
// is shorter than CastDeferMaxMs) while one is queued; past the limit cast anyway.
if (StopQueuedAtOrBefore(Volatile.Read(ref _castQueuedAt)))
if (StopQueuedAtOrBefore(queuedAt))
{
if (castAge <= CastDeferMaxMs)
{
if (!_castStopWaitNoted)
if (!_cast.StopWaitNoted)
{
_castStopWaitNoted = true;
_cast.StopWaitNoted = true;
Interlocked.Increment(ref _castStopWaits);
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { }
}
@ -1085,7 +1300,7 @@ internal static class AcMainThreadQueue
}
// ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ──
long castStamp = Volatile.Read(ref _castQueuedAt);
long castStamp = queuedAt;
if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; }
long nowMs = NowMs;
PreCastStep step = PreCastStopRules.Decide(
@ -1122,10 +1337,10 @@ internal static class AcMainThreadQueue
uint target, spell;
lock (_castLock)
{
if (_castPending == 0) return;
target = _castTargetId;
spell = _castSpellId;
_castPending = 0;
if (_cast.Pending == 0) return;
target = _cast.TargetId;
spell = _cast.SpellId;
_cast.Pending = 0;
}
if (castAge > LateActionLogMs)
NoteStale($"CastSpell({spell})", castAge, dropped: false);

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ActionRing.cs
//
// The storage and admission policy of AcMainThreadQueue's action ring: a fixed ring of
// entries, many producers (under one lock), ONE consumer (AC's main thread), FIFO.
//
// Admission: during a world transition the drain holds the ring
// (WorldTransitionState), and a bot keeps queueing starts at ~60 Hz meanwhile, so the
// ring used to fill and then refuse the stops and cancels that matter most. Now:
// - while the caller says a transition is on, non-teardown entries are refused at
// once (they would be dropped when it ends anyway);
// - the top TeardownReserve slots only take teardown entries (stops and cancels), so a
// ring filled by starts before the transition was seen still takes a stop.
// What counts as teardown is the caller's (AcMainThreadQueue.IsTeardownKind, the same
// predicate its drain uses).
//
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal sealed class ActionRing<T> where T : struct
{
public enum Admit
{
Queued,
/// <summary>No room (for a non-teardown entry: none below the teardown reserve).</summary>
Full,
/// <summary>A world transition is on and the entry is not teardown.</summary>
RejectedTransition,
}
private readonly T[] _slots;
private readonly int _mask;
private readonly int _reserve;
private readonly object _lock = new();
// Monotonic counters. Producers advance _tail under _lock; the sole consumer advances _head.
private int _head;
private int _tail;
public ActionRing(int capacityPowerOfTwo, int teardownReserve)
{
if (capacityPowerOfTwo <= 0 || (capacityPowerOfTwo & (capacityPowerOfTwo - 1)) != 0)
throw new System.ArgumentOutOfRangeException(nameof(capacityPowerOfTwo));
if (teardownReserve < 0 || teardownReserve >= capacityPowerOfTwo)
throw new System.ArgumentOutOfRangeException(nameof(teardownReserve));
_slots = new T[capacityPowerOfTwo];
_mask = capacityPowerOfTwo - 1;
_reserve = teardownReserve;
}
public int Capacity => _slots.Length;
public int TeardownReserve => _reserve;
/// <summary>Entries waiting (any thread; a snapshot).</summary>
public int Count => Volatile.Read(ref _tail) - Volatile.Read(ref _head);
/// <summary>Producer side, any thread.</summary>
public Admit TryEnqueue(in T entry, bool teardown, bool inTransition)
{
lock (_lock)
{
if (inTransition && !teardown)
return Admit.RejectedTransition;
int tail = _tail;
int used = tail - Volatile.Read(ref _head);
int limit = teardown ? _slots.Length : _slots.Length - _reserve;
if (used >= limit)
return Admit.Full;
_slots[tail & _mask] = entry;
Volatile.Write(ref _tail, tail + 1);
return Admit.Queued;
}
}
/// <summary>Consumer only: the oldest entry, without removing it.</summary>
public bool TryPeek(out T entry)
{
int head = _head;
if (head == Volatile.Read(ref _tail))
{
entry = default;
return false;
}
entry = _slots[head & _mask];
return true;
}
/// <summary>
/// Consumer only: the entry <paramref name="offset"/> places behind the oldest (0 = the
/// oldest), without removing anything. False past the newest entry.
/// </summary>
public bool TryPeekAt(int offset, out T entry)
{
int head = _head;
if (offset < 0 || offset >= Volatile.Read(ref _tail) - head)
{
entry = default;
return false;
}
entry = _slots[(head + offset) & _mask];
return true;
}
/// <summary>Consumer only: removes the oldest entry (after a successful TryPeek).</summary>
public void Pop()
{
int head = _head;
if (head == Volatile.Read(ref _tail)) return;
_slots[head & _mask] = default;
Volatile.Write(ref _head, head + 1);
}
/// <summary>Consumer only: removes and returns the oldest entry.</summary>
public bool TryDequeue(out T entry)
{
if (!TryPeek(out entry)) return false;
Pop();
return true;
}
}

View file

@ -0,0 +1,87 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AddressSpace.cs
//
// Free user address space and the LARGEST free block, in MB. acclient is 32-bit, so
// "out of memory" usually means fragmentation, not exhaustion: 300 MB may be free in
// total while no single block can take a 16 MB allocation. vafree alone (the
// heartbeat's GlobalMemoryStatusEx total) cannot show that; valargest can.
//
// Walks the regions with VirtualQuery (a few thousand calls, no allocation). Any
// thread; the heartbeat thread calls it once a second and PluginManager around each
// plugin load and unload during a reload. Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class AddressSpace
{
private const uint MEM_FREE = 0x10000;
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_BASIC_INFORMATION
{
public nuint BaseAddress;
public nuint AllocationBase;
public uint AllocationProtect;
public nuint RegionSize; // sequential layout pads after the uint on x64
public uint State;
public uint Protect;
public uint Type;
}
[DllImport("kernel32.dll")]
private static extern nuint VirtualQuery(nuint lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, nuint dwLength);
/// <summary>
/// Total free and largest free block of this process's address space, in MB, or
/// (-1, -1) on failure. Never throws.
/// </summary>
public static (long FreeMb, long LargestFreeMb) FreeAndLargestMb()
{
try
{
ulong free = 0, largest = 0;
nuint addr = 0;
nuint size = (nuint)Marshal.SizeOf<MEMORY_BASIC_INFORMATION>();
int guard = 0;
while (guard++ < 1_000_000)
{
if (VirtualQuery(addr, out MEMORY_BASIC_INFORMATION mbi, size) == 0)
break;
ulong region = mbi.RegionSize;
if (region == 0)
break;
Accumulate(mbi.State == MEM_FREE, region, ref free, ref largest);
nuint next = mbi.BaseAddress + mbi.RegionSize;
if (next <= addr)
break; // wrapped past the top
addr = next;
}
if (guard <= 1)
return (-1, -1);
return ((long)(free >> 20), (long)(largest >> 20));
}
catch
{
return (-1, -1);
}
}
/// <summary>Pure: fold one region into the running totals.</summary>
public static void Accumulate(bool isFree, ulong regionBytes, ref ulong freeBytes, ref ulong largestBytes)
{
if (!isFree) return;
freeBytes += regionBytes;
if (regionBytes > largestBytes) largestBytes = regionBytes;
}
/// <summary>"free=NNNMB largest=NNNMB", for the reload log lines.</summary>
public static string Describe()
{
var (free, largest) = FreeAndLargestMb();
return free < 0 ? "free=? largest=?" : $"free={free}MB largest={largest}MB";
}
}

View file

@ -80,6 +80,9 @@ internal static class AppraisalHooks
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
private static readonly object _cacheLock = new();
// Objects the CLIENT released, whose data is kept a while (ReleasedObjectRetention).
private static readonly ReleasedObjectRetention _released = new();
private static readonly List<uint> _expiredScratch = new();
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
@ -114,19 +117,64 @@ internal static class AppraisalHooks
_bags.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
_released.Clear();
}
}
/// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary>
/// <summary>
/// Drops everything cached for an object: the SERVER deleted it (0xF747, SmartBoxHooks /
/// ServerMessageStream), or its kept-after-release time ran out. Any thread.
/// </summary>
public static void EvictObject(uint guid)
{
lock (_cacheLock)
EvictLocked(guid);
}
// Caller holds _cacheLock.
private static void EvictLocked(uint guid)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
_released.Forget(guid);
}
/// <summary>
/// The CLIENT released an object (AC's BeingDeleted: it left the client's view). Its data is
/// kept for ReleasedObjectRetention.RetainMs, so a re-create inside that time still finds it
/// (AutoId then skips the re-appraisal). Main thread (the BeingDeleted detour).
/// </summary>
public static void OnClientRelease(uint guid, long nowMs)
{
lock (_cacheLock)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
if (!_appraisedGuids.Contains(guid) && !_bags.ContainsKey(guid)) return;
if (!_released.OnRelease(guid, nowMs))
EvictLocked(guid); // the kept-released bound is full: drop it now
}
}
/// <summary>The object was created again: its data is current, not merely kept.</summary>
public static void MarkLive(uint guid)
{
lock (_cacheLock)
_released.Forget(guid);
}
/// <summary>Drops the data of objects released longer ago than the retention time. Timer thread.</summary>
public static int ExpireReleased(long nowMs)
{
lock (_cacheLock)
{
_expiredScratch.Clear();
int n = _released.Expire(nowMs, _expiredScratch);
foreach (uint g in _expiredScratch)
EvictLocked(g);
_expiredScratch.Clear();
return n;
}
}
@ -150,10 +198,7 @@ internal static class AppraisalHooks
if (t < oldestTime) { oldestTime = t; oldest = g; }
}
if (oldest == 0) return;
_bags.Remove(oldest);
_appraisedGuids.Remove(oldest);
_lastIdTime.Remove(oldest);
_spellIdCache.Remove(oldest);
EvictLocked(oldest);
}
}

View file

@ -0,0 +1,319 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdDrain.cs
//
// AutoIdService's backlog: candidates in (any thread), decisions and sends out (the
// drain timer). Everything it needs from the engine comes through IAutoIdWorld, so it
// runs in tools\EngineRobustnessTests against a fake world and a fake clock.
//
// Per tick: take the new candidates, the one-shot login sweep, then look at the pending
// list in order (at most MaxEvaluatedPerTick, at most MaxPerTick sends) and decide each
// one with AutoIdPolicy. Waits stay; skips leave; a send leaves only when the main-thread
// queue took it (a refusal, in a transition or with the ring full, keeps the entry and
// ends this tick's sending).
//
// Login sweep: the pack is created before the 10 Hz object
// snapshot is warm (ClientObjectHooks.PrefetchPositions only starts after the post-login
// bootstrap), so a pack item created at login may still be unplaceable when its create
// candidate is decided. Once per login (and per hot reload, which marks a login), at
// login-complete + DeferMs and with the snapshot warm, every uncached item the player
// owns, and every item in a pack the player owns, becomes a candidate. The 5 a second
// Inventory cap still applies. An Unknown candidate also waits for the snapshot (up to
// AutoIdPolicy.UnknownMaxWaitMs) instead of being dropped at MinAgeMs. Only containers are
// looked into, and a sweep that overflowed the pending list counts as not done: it runs
// again once there is room.
//
// Combat: Inventory sends wait while a cast or attack is in flight
// (Context.CombatBusy, AutoIdPolicy.InCombat; a selected target alone does not count). Each 0xC8 raises AC's busy count, and plugins gate
// their casts on it. The selected target and an open container are not held.
//
// Bounds: _incoming is capped at MaxIncoming (oldest dropped, counted) because the drain
// returns early through a world transition (a long death); the pending list is capped at
// MaxPendingLimited in Limited mode only (All keeps the old unbounded backlog).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Net;
namespace RynthCore.Engine.Compatibility;
/// <summary>What AutoIdDrain reads and does in the engine (a fake in the tests).</summary>
internal interface IAutoIdWorld
{
/// <summary>The object's container and wielder from the object snapshot; false when it is not in it.</summary>
bool TryGetOwnership(uint id, out uint container, out uint wielder);
/// <summary>The object snapshot has been filled at least once (it holds any object at all).</summary>
bool SnapshotWarm { get; }
/// <summary>Ids whose container or wielder is <paramref name="container"/>, from the snapshot.</summary>
int CollectOwned(uint container, Span<uint> dest);
/// <summary>Created and not released (AutoIdEligibility).</summary>
bool IsLive(uint id);
/// <summary>Its appraisal is cached.</summary>
bool HasAppraisal(uint id);
/// <summary>Its appraisal is cached and recent.</summary>
bool IsFresh(uint id);
/// <summary>Queue the 0xC8 for AC's main thread; false = refused (transition, ring full).</summary>
bool QueueIdentify(uint id, IdRequester who);
/// <summary>It holds items (a pack, a chest): only these are looked into by the login sweep.</summary>
bool IsContainer(uint id);
}
internal sealed class AutoIdDrain
{
public const int MaxPerTick = 3;
public const int MaxEvaluatedPerTick = 512;
public const int MaxPendingLimited = 4096;
public const int MaxIncoming = 16384;
public const int MaxSweepItems = 512;
/// <summary>One tick's view of the engine (read by AutoIdService each tick).</summary>
public struct Context
{
public long Now;
public AutoIdMode Mode;
public uint PlayerId;
public uint OpenContainer;
public long OpenedAtMs; // when OpenContainer was opened (0 = unknown)
public long SettleUntilMs; // PlayerLifecycleLog.SettleUntilMs
public long LoginCompleteAtMs; // LoginLifecycleHooks.LoginCompleteAtMs
public bool CombatBusy; // a cast or attack in flight, AutoIdPolicy.InCombat (Inventory waits)
}
private struct Pending
{
public uint Id;
public long AtMs; // created (or moved, or its container opened, or swept) at
public byte Counted; // waits already counted: 1 = age, 2 = defer, 4 = rate, 8 = combat
}
private readonly IAutoIdWorld _w;
private readonly ConcurrentQueue<(uint Id, long AtMs)> _incoming = new();
private int _incomingCount;
private readonly List<Pending> _pending = new(256);
private readonly HashSet<uint> _pendingIds = new();
private int _pendingCount;
private long _lastInventorySendMs;
private long _sweptLoginAt;
private long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _skipCombat, _overflow, _incomingDropped, _refused, _swept;
public AutoIdDrain(IAutoIdWorld world) { _w = world; }
public long SkipMode => Interlocked.Read(ref _skipMode);
public long SkipAge => Interlocked.Read(ref _skipAge);
public long SkipDefer => Interlocked.Read(ref _skipDefer);
public long SkipFresh => Interlocked.Read(ref _skipFresh);
public long SkipRate => Interlocked.Read(ref _skipRate);
/// <summary>Inventory candidates that waited for combat to end (counted once each).</summary>
public long SkipCombat => Interlocked.Read(ref _skipCombat);
/// <summary>Candidates not taken because the Limited pending list was full.</summary>
public long Overflow => Interlocked.Read(ref _overflow);
/// <summary>Oldest new candidates dropped because _incoming was full (the drain was held).</summary>
public long IncomingDropped => Interlocked.Read(ref _incomingDropped);
/// <summary>Sends the main-thread queue refused (kept and tried again).</summary>
public long Refused => Interlocked.Read(ref _refused);
/// <summary>Items the login sweeps made candidates.</summary>
public long Swept => Interlocked.Read(ref _swept);
public int PendingCount => Volatile.Read(ref _pendingCount);
/// <summary>The selected-target path counts its fresh / mode skips here too.</summary>
public void CountSkipFresh() => Interlocked.Increment(ref _skipFresh);
public void CountSkipMode() => Interlocked.Increment(ref _skipMode);
/// <summary>A new candidate (any thread). Past MaxIncoming the oldest waiting one is dropped.</summary>
public void Offer(uint id, long atMs)
{
if (id == 0) return;
_incoming.Enqueue((id, atMs));
if (Interlocked.Increment(ref _incomingCount) > MaxIncoming && _incoming.TryDequeue(out _))
{
Interlocked.Decrement(ref _incomingCount);
Interlocked.Increment(ref _incomingDropped);
}
}
/// <summary>Drain thread: the items in <paramref name="container"/> with nothing cached become candidates.</summary>
public void AddContainerContents(uint container, long atMs, AutoIdMode mode)
{
if (container == 0) return;
Span<uint> ids = stackalloc uint[256];
int n = _w.CollectOwned(container, ids);
for (int i = 0; i < n; i++)
if (_w.IsLive(ids[i]) && !_w.HasAppraisal(ids[i]))
AddPending(ids[i], atMs, mode);
}
/// <summary>Drain thread, once per timer tick. Returns the sends so far (starting at <paramref name="sent"/>).</summary>
public int Tick(in Context c, int sent)
{
TakeIncoming(c.Mode);
LoginSweep(c);
return DrainPending(c, sent);
}
private void TakeIncoming(AutoIdMode mode)
{
while (_incoming.TryDequeue(out (uint Id, long AtMs) x))
{
Interlocked.Decrement(ref _incomingCount);
AddPending(x.Id, x.AtMs, mode);
}
}
private void AddPending(uint id, long atMs, AutoIdMode mode)
{
if (id == 0 || _pendingIds.Contains(id))
return;
if (mode != AutoIdMode.All && _pending.Count >= MaxPendingLimited)
{
Interlocked.Increment(ref _overflow);
return;
}
_pendingIds.Add(id);
_pending.Add(new Pending { Id = id, AtMs = atMs });
}
/// <summary>Once per login-complete stamp, at login + DeferMs with the snapshot warm: the uncached pack.</summary>
private void LoginSweep(in Context c)
{
if (c.Mode != AutoIdMode.Limited || c.LoginCompleteAtMs <= 0 || c.LoginCompleteAtMs == _sweptLoginAt)
return;
if (c.Now < c.LoginCompleteAtMs + AutoIdPolicy.DeferMs || c.PlayerId == 0 || !_w.SnapshotWarm)
return;
// A full pending list: try again on a later tick (no walk, no overflow counted).
if (_pending.Count >= MaxPendingLimited)
return;
Span<uint> top = stackalloc uint[MaxSweepItems];
Span<uint> inner = stackalloc uint[MaxSweepItems];
int n = _w.CollectOwned(c.PlayerId, top);
int before = _pending.Count;
long overflowBefore = Interlocked.Read(ref _overflow);
for (int i = 0; i < n; i++)
{
uint id = top[i];
if (_w.IsLive(id) && !_w.HasAppraisal(id))
AddPending(id, c.LoginCompleteAtMs, c.Mode);
// A side pack: its contents are the pack too. Only a container is looked into.
if (!_w.IsContainer(id))
continue;
int m = _w.CollectOwned(id, inner);
for (int k = 0; k < m; k++)
if (_w.IsLive(inner[k]) && !_w.HasAppraisal(inner[k]))
AddPending(inner[k], c.LoginCompleteAtMs, c.Mode);
}
Interlocked.Add(ref _swept, _pending.Count - before);
// Done only when everything fit; an overflowed sweep runs again once there is room
// (what it already added is not added twice: AddPending skips ids already pending).
if (Interlocked.Read(ref _overflow) == overflowBefore)
_sweptLoginAt = c.LoginCompleteAtMs;
}
private int DrainPending(in Context c, int sent)
{
if (_pending.Count == 0)
{
Volatile.Write(ref _pendingCount, 0);
return sent;
}
long transitionEnd = AutoIdPolicy.TransitionEndMs(c.SettleUntilMs, c.LoginCompleteAtMs);
bool inDefer = AutoIdPolicy.InDefer(c.Now, c.SettleUntilMs, c.LoginCompleteAtMs, inTransition: false);
bool openedAfterSettle = AutoIdPolicy.OpenedAfterSettle(c.OpenedAtMs, transitionEnd);
bool snapshotWarm = _w.SnapshotWarm;
bool sending = true;
int keep = 0, evaluated = 0;
for (int i = 0; i < _pending.Count; i++)
{
Pending p = _pending[i];
if (!sending || sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick)
{
_pending[keep++] = p;
continue;
}
evaluated++;
// Released since it was queued: gone, without spending a send.
if (!_w.IsLive(p.Id))
{
_pendingIds.Remove(p.Id);
continue;
}
AutoIdPolicy.Class cls = Classify(p.Id, c.PlayerId, c.OpenContainer);
bool cached = _w.HasAppraisal(p.Id);
bool fresh = cached && _w.IsFresh(p.Id);
bool rateOk = AutoIdPolicy.InventoryRateAllows(c.Now, _lastInventorySendMs);
AutoIdPolicy.Verdict v = AutoIdPolicy.Decide(c.Mode, cls, c.Now - p.AtMs, inDefer, openedAfterSettle,
fresh, cached, rateOk, snapshotWarm, c.CombatBusy);
switch (v)
{
case AutoIdPolicy.Verdict.Send:
if (!_w.QueueIdentify(p.Id, RequesterFor(cls)))
{
// Refused (a transition began, or the ring is full): keep it, and
// stop sending this tick.
Interlocked.Increment(ref _refused);
_pending[keep++] = p;
sending = false;
break;
}
sent++;
if (cls == AutoIdPolicy.Class.Inventory && c.Mode == AutoIdMode.Limited)
_lastInventorySendMs = c.Now;
_pendingIds.Remove(p.Id);
break;
case AutoIdPolicy.Verdict.WaitAge:
case AutoIdPolicy.Verdict.WaitSnapshot:
if ((p.Counted & 1) == 0) { p.Counted |= 1; Interlocked.Increment(ref _skipAge); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.WaitDefer:
if ((p.Counted & 2) == 0) { p.Counted |= 2; Interlocked.Increment(ref _skipDefer); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.WaitRate:
if ((p.Counted & 4) == 0) { p.Counted |= 4; Interlocked.Increment(ref _skipRate); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.WaitCombat:
if ((p.Counted & 8) == 0) { p.Counted |= 8; Interlocked.Increment(ref _skipCombat); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.SkipFresh:
Interlocked.Increment(ref _skipFresh);
_pendingIds.Remove(p.Id);
break;
default:
Interlocked.Increment(ref _skipMode);
_pendingIds.Remove(p.Id);
break;
}
}
_pending.RemoveRange(keep, _pending.Count - keep);
Volatile.Write(ref _pendingCount, _pending.Count);
return sent;
}
/// <summary>Where the object is now, from the snapshot.</summary>
private AutoIdPolicy.Class Classify(uint id, uint playerId, uint open)
{
if (!_w.TryGetOwnership(id, out uint container, out uint wielder))
return AutoIdPolicy.Classify(false, playerId, open, 0, 0, 0);
uint parent = 0;
if (container != 0 && container != playerId && container != open
&& _w.TryGetOwnership(container, out uint cc, out _))
parent = cc;
return AutoIdPolicy.Classify(true, playerId, open, container, wielder, parent);
}
public static IdRequester RequesterFor(AutoIdPolicy.Class cls) => cls switch
{
AutoIdPolicy.Class.Target => IdRequester.AutoIdTarget,
AutoIdPolicy.Class.Container => IdRequester.AutoIdContainer,
AutoIdPolicy.Class.Inventory => IdRequester.AutoIdInventory,
_ => IdRequester.AutoIdWorld,
};
}

View file

@ -0,0 +1,191 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdEligibility.cs
//
// Which created objects AutoIdService appraises (the decision only; AutoIdService
// does the queueing and the sends).
//
// Before: a client-side release of an object (ACCObjectMaint::DeleteObject, or the
// Decal bridge's delete event) forgot that it had been appraised, so every time the
// client re-created it the engine appraised it again: some objects 16 times in 26
// minutes. Now each object keeps the time its last appraisal was SENT, across client
// releases, and a re-create inside the window (default 10 minutes) is not appraised
// again, unless:
// - the SERVER deleted the object (0xF747 ObjectDelete): it really went away, and
// what comes back under that id is appraised fresh; or
// - the appraisal data is no longer cached (the caller says so): re-appraising is
// then the only way to get it back, so the window never leaves an object with
// nothing cached.
// A release before the queued appraisal went out records no time, so the next create
// is appraised. A create while the object is still live is a duplicate and ignored.
//
// Bounded: at most MaxTracked objects. Prune (from the drain timer, never the create
// path) drops entries that no longer decide anything (released and outside the window
// or never sent), then the oldest released ones. Past the bound a create is still
// admitted, only not tracked.
//
// Pure: no engine state, no locking (the caller locks), and no allocation after
// construction (pre-sized; Dictionary.Remove during enumeration is allowed on
// .NET Core 3+). Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
internal sealed class AutoIdEligibility
{
public const long DefaultWindowMs = 10L * 60 * 1000;
public const int DefaultMaxTracked = 8192;
public enum CreateDecision
{
/// <summary>Queue an appraisal.</summary>
Appraise,
/// <summary>Appraised recently and still cached: skip.</summary>
SkipRecent,
/// <summary>Already live (a second create for it): skip.</summary>
SkipDuplicate,
}
private struct Entry
{
public bool Live; // created and not released since
public long LastSentMs; // when its last appraisal was sent; 0 = none since tracking (re)started
}
private readonly Dictionary<uint, Entry> _map;
private readonly long _windowMs;
private readonly int _maxTracked;
public AutoIdEligibility(long windowMs = DefaultWindowMs, int maxTracked = DefaultMaxTracked)
{
_windowMs = windowMs;
_maxTracked = maxTracked;
_map = new Dictionary<uint, Entry>(maxTracked + 1);
}
public int Count => _map.Count;
public int MaxTracked => _maxTracked;
public long WindowMs => _windowMs;
/// <summary>Re-creates skipped because the last appraisal is recent and still cached.</summary>
public long SkippedRecentTotal { get; private set; }
/// <summary>Creates admitted while the map was full (appraised, not tracked).</summary>
public long UntrackedAdmits { get; private set; }
/// <summary>
/// The client created <paramref name="id"/>. <paramref name="appraisalCached"/>: the
/// engine still holds appraisal data for it (AppraisalHooks).
/// </summary>
public CreateDecision OnCreate(uint id, long nowMs, bool appraisalCached)
{
if (_map.TryGetValue(id, out Entry e))
{
if (e.Live)
return CreateDecision.SkipDuplicate;
e.Live = true;
bool recent = e.LastSentMs != 0 && nowMs - e.LastSentMs < _windowMs;
_map[id] = e;
if (recent && appraisalCached)
{
SkippedRecentTotal++;
return CreateDecision.SkipRecent;
}
return CreateDecision.Appraise;
}
if (_map.Count >= _maxTracked)
{
UntrackedAdmits++;
return CreateDecision.Appraise;
}
_map[id] = new Entry { Live = true, LastSentMs = 0 };
return CreateDecision.Appraise;
}
/// <summary>
/// The appraisal for <paramref name="id"/> was sent: called from the main-thread drain
/// after CombatActionHooks.RequestId succeeded, never at queue time, so a request the
/// drain dropped (stale, a world transition, a new login) records nothing.
/// </summary>
public void OnSent(uint id, long nowMs)
{
if (_map.TryGetValue(id, out Entry e))
{
e.LastSentMs = nowMs == 0 ? 1 : nowMs;
_map[id] = e;
}
}
/// <summary>The client released <paramref name="id"/>; its appraisal time is kept.</summary>
public void OnClientRelease(uint id)
{
if (_map.TryGetValue(id, out Entry e) && e.Live)
{
e.Live = false;
_map[id] = e;
}
}
/// <summary>
/// The server deleted <paramref name="id"/>: the next create under that id is appraised.
/// Liveness is left to the client's own release (it may come before or after this).
/// </summary>
public void OnServerDelete(uint id)
{
if (_map.TryGetValue(id, out Entry e))
{
e.LastSentMs = 0;
_map[id] = e;
}
}
/// <summary>True while <paramref name="id"/> is created and not released (or untracked).</summary>
public bool IsLive(uint id) => !_map.TryGetValue(id, out Entry e) || e.Live;
/// <summary>
/// Keep the map under its bound. First drops entries that decide nothing any more
/// (released, and never sent or outside the window), then, if still at the bound,
/// the released entries sent longest ago. Live entries are never dropped.
/// Returns how many were removed.
/// </summary>
public int Prune(long nowMs)
{
int removed = 0;
foreach (KeyValuePair<uint, Entry> kv in _map)
{
Entry e = kv.Value;
if (!e.Live && (e.LastSentMs == 0 || nowMs - e.LastSentMs >= _windowMs))
{
_map.Remove(kv.Key);
removed++;
}
}
// Still over three quarters full: drop released entries oldest first, in a few
// passes with a shrinking age cut (window/2, /4, /8, then any age). One linear
// pass each, so a prune never costs more than five walks of the map.
int target = _maxTracked * 3 / 4;
for (int pass = 1; pass <= 4 && _map.Count > target; pass++)
{
long minAge = pass < 4 ? _windowMs >> pass : long.MinValue;
foreach (KeyValuePair<uint, Entry> kv in _map)
{
if (_map.Count <= target) break;
if (kv.Value.Live) continue;
if (pass < 4 && nowMs - kv.Value.LastSentMs < minAge) continue;
_map.Remove(kv.Key);
removed++;
}
}
return removed;
}
/// <summary>
/// Fix 2 rule for the selected-target priority appraisal: the target's appraisal is
/// cached and was received less than <paramref name="windowMs"/> ago.
/// </summary>
public static bool IsAppraisalFresh(bool cached, long lastIdUnixSec, long nowUnixSec, long windowMs) =>
cached && lastIdUnixSec > 0 && (nowUnixSec - lastIdUnixSec) * 1000 < windowMs;
}

View file

@ -0,0 +1,233 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdPolicy.cs
//
// Which background appraisals AutoIdService sends (the decision only; AutoIdService
// does the queueing, the lookups and the sends).
//
// Why: in one 26-minute session (1585 s) the client sent 3211 IdentifyObject (0xC8),
// about three quarters of everything it sent, for 2479 objects against 28
// kills. AutoId appraised every object the client created. The bot (RynthAi) already
// appraises what it needs at the point of use (corpse items its loot rules need, the
// selected creature, equipment, meta conditions), so most of that was traffic for
// nothing; it is now limited (engine.json "AutoIdMode", /rc autoid).
//
// Modes:
// All the old behaviour: every created object except the player, the selected
// target with its fresh-cache skip.
// Limited (default) only
// Target the selected target (fresh-cache skip, no age, no defer);
// Container items in the container the player has open now (a corpse,
// a chest, a pack opened through ViewContents);
// Inventory items in the player's own inventory (worn, in the main pack
// or in a side pack) that have no cached appraisal.
// Container and Inventory wait until the object is MinAgeMs old, and until
// DeferMs after a world transition's settle window ends (death, portal,
// teleport, landblock jump; walking into the next landblock is not one),
// and until DeferMs after login completes (login is a transition too:
// a client crashed in AC's CreateObject handling during the
// login create burst). A container the player opened after the last
// transition ended is not deferred. Inventory sends are capped at 5 a
// second and wait while a cast or attack is in flight (a selected
// target alone does not hold them). Creatures, ground items, other players: never.
// Off nothing, the selected target included.
// Plugins calling the host RequestId are not limited by any of this.
//
// Pure: no engine state, no locking. Compiled into tools\EngineRobustnessTests and
// tools\EngineSettingsTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
/// <summary>engine.json "AutoIdMode" (see <see cref="AutoIdPolicy"/>).</summary>
internal enum AutoIdMode { All = 0, Limited = 1, Off = 2 }
internal static class AutoIdPolicy
{
public const AutoIdMode DefaultMode = AutoIdMode.Limited;
/// <summary>Container and Inventory appraisals wait until the object is this old.</summary>
public const long MinAgeMs = 2_000;
/// <summary>Container and Inventory appraisals wait this long after a transition's settle window ends,
/// and after login completes.</summary>
public const long DeferMs = 30_000;
/// <summary>
/// Inventory appraisals go out at most one per this many ms (5 a second). In one case
/// a client crashed in AC's CreateObject handling during the login create burst, 47 s after
/// start, and the pack's appraisals at 30 a second are what that burst must not carry.
/// </summary>
public const long InventoryMinIntervalMs = 200;
/// <summary>
/// An object whose place is unknown because the object snapshot has not been filled yet
/// (at login the pack is created before ClientObjectHooks.PrefetchPositions starts) waits
/// for it this long at most before it is dropped.
/// </summary>
public const long UnknownMaxWaitMs = 120_000;
public enum Class
{
/// <summary>The selected target (the priority path).</summary>
Target,
/// <summary>In the container the player has open now.</summary>
Container,
/// <summary>In the player's own inventory (worn, main pack, side pack).</summary>
Inventory,
/// <summary>Anything else the client knows where it is: a creature, a ground item, another player.</summary>
World,
/// <summary>Not in the engine's object snapshot yet (created moments ago), so its place is unknown.</summary>
Unknown,
}
public enum Verdict
{
/// <summary>Appraise it now.</summary>
Send,
/// <summary>The mode does not appraise this: drop it.</summary>
SkipMode,
/// <summary>Too young: keep it and ask again later.</summary>
WaitAge,
/// <summary>Inside the post-transition defer: keep it and ask again later.</summary>
WaitDefer,
/// <summary>Its appraisal is cached (fresh): drop it.</summary>
SkipFresh,
/// <summary>Inventory over its send rate (InventoryMinIntervalMs): keep it and ask again later.</summary>
WaitRate,
/// <summary>Place unknown and the object snapshot still empty: keep it (up to UnknownMaxWaitMs).</summary>
WaitSnapshot,
/// <summary>Inventory while in combat (a cast or an attack in flight, InCombat): keep it.</summary>
WaitCombat,
}
/// <summary>
/// The decision for one candidate.
/// <paramref name="ageMs"/>: how long the object has existed (or since it moved, for a move).
/// <paramref name="inDefer"/>: inside the post-transition defer window (<see cref="InDefer"/>).
/// <paramref name="openedAfterSettle"/>: Container only, the player opened it after the last
/// settle window ended (<see cref="OpenedAfterSettle"/>), which exempts it from the defer.
/// <paramref name="fresh"/>: its appraisal is cached and recent (Target, Container).
/// <paramref name="cached"/>: its appraisal is cached at all (Inventory).
/// <paramref name="inventoryRateOk"/>: Inventory only, the send rate allows one now (<see cref="InventoryRateAllows"/>).
/// <paramref name="snapshotWarm"/>: Unknown only, the object snapshot has been filled (an
/// object missing from a warm snapshot is not coming; one missing from a cold one may be).
/// <paramref name="combatBusy"/>: Inventory only, a cast or attack is in flight (<see cref="InCombat"/>). Each 0xC8 raises AC's busy count, which plugins gate casts on, so the pack waits.
/// </summary>
public static Verdict Decide(AutoIdMode mode, Class cls, long ageMs, bool inDefer, bool openedAfterSettle,
bool fresh, bool cached, bool inventoryRateOk = true, bool snapshotWarm = true,
bool combatBusy = false)
{
switch (mode)
{
case AutoIdMode.Off:
return Verdict.SkipMode;
case AutoIdMode.All:
// The old behaviour: the create-time eligibility already decided; only the
// selected target has the fresh-cache skip.
if (cls == Class.Target && fresh) return Verdict.SkipFresh;
return Verdict.Send;
default: // Limited
switch (cls)
{
case Class.Target:
return fresh ? Verdict.SkipFresh : Verdict.Send;
case Class.Container:
if (fresh) return Verdict.SkipFresh;
if (ageMs < MinAgeMs) return Verdict.WaitAge;
if (inDefer && !openedAfterSettle) return Verdict.WaitDefer;
return Verdict.Send;
case Class.Inventory:
if (cached) return Verdict.SkipFresh;
if (ageMs < MinAgeMs) return Verdict.WaitAge;
if (inDefer) return Verdict.WaitDefer;
if (combatBusy) return Verdict.WaitCombat;
if (!inventoryRateOk) return Verdict.WaitRate;
return Verdict.Send;
case Class.Unknown:
// Its place shows up in the snapshot within a tick or two; until it is
// MinAgeMs old it may still turn out to be in the open container or the pack.
// While the snapshot has never been filled (login), it waits for it.
if (ageMs < MinAgeMs) return Verdict.WaitAge;
if (!snapshotWarm && ageMs < UnknownMaxWaitMs) return Verdict.WaitSnapshot;
return Verdict.SkipMode;
default: // World
return Verdict.SkipMode;
}
}
}
/// <summary>
/// In combat for the Inventory hold: a cast in flight (<paramref name="castBusy"/>, CastGate) or an
/// attack running. A selected target alone is NOT combat (<paramref name="selectedTarget"/> is taken
/// only so the tests can show that): a hunting bot nearly always has something selected, and the
/// pack (mana stones included) would never be appraised.
/// </summary>
public static bool InCombat(uint selectedTarget, int castBusy, bool attacking) =>
castBusy != 0 || attacking;
/// <summary>
/// When the last transition ended: the later of the settle window's end
/// (WorldTransitionState.SettleUntilMs, 0 = none yet; it only moves on a death, a portal,
/// a teleport or a landblock jump, never on a walk into the next landblock) and login
/// completing (<paramref name="loginCompleteAtMs"/>; login counts as a transition).
/// </summary>
public static long TransitionEndMs(long settleUntilMs, long loginCompleteAtMs) =>
Math.Max(settleUntilMs, loginCompleteAtMs);
/// <summary>
/// Inside the defer: in a transition now, login not complete yet
/// (<paramref name="loginCompleteAtMs"/> 0: the login create burst), or less than
/// <see cref="DeferMs"/> after <see cref="TransitionEndMs"/>.
/// </summary>
public static bool InDefer(long nowMs, long settleUntilMs, long loginCompleteAtMs, bool inTransition) =>
inTransition || loginCompleteAtMs <= 0 || nowMs < TransitionEndMs(settleUntilMs, loginCompleteAtMs) + DeferMs;
/// <summary>The player opened the container (at <paramref name="openedAtMs"/>) after the last transition ended
/// (<paramref name="transitionEndMs"/>, <see cref="TransitionEndMs"/>).</summary>
public static bool OpenedAfterSettle(long openedAtMs, long transitionEndMs) =>
openedAtMs > 0 && openedAtMs >= transitionEndMs;
/// <summary>An Inventory appraisal may go out now: none yet, or the last was at least InventoryMinIntervalMs ago.</summary>
public static bool InventoryRateAllows(long nowMs, long lastInventorySendMs) =>
lastInventorySendMs <= 0 || nowMs - lastInventorySendMs >= InventoryMinIntervalMs;
/// <summary>
/// Where an object is, from its PublicWeenieDesc ownership fields (<paramref name="known"/> =
/// the snapshot had it). <paramref name="containerParent"/> is the container's own container
/// (a side pack's owner), 0 when unknown or none. <paramref name="openContainer"/> is the
/// container the player has open now (0 = none).
/// </summary>
public static Class Classify(bool known, uint playerId, uint openContainer,
uint container, uint wielder, uint containerParent)
{
if (!known) return Class.Unknown;
if (playerId != 0 && (container == playerId || wielder == playerId || (container != 0 && containerParent == playerId)))
return Class.Inventory;
// openContainer != 0 also keeps a ground item (container 0) out of here.
if (openContainer != 0 && (container == openContainer || containerParent == openContainer))
return Class.Container;
return Class.World;
}
public static bool TryParseMode(string? text, out AutoIdMode mode)
{
switch ((text ?? "").Trim().ToLowerInvariant())
{
case "all": mode = AutoIdMode.All; return true;
case "limited": case "limit": mode = AutoIdMode.Limited; return true;
case "off": case "none": mode = AutoIdMode.Off; return true;
default: mode = DefaultMode; return false;
}
}
public static string Name(AutoIdMode mode) => mode switch
{
AutoIdMode.All => "all",
AutoIdMode.Off => "off",
_ => "limited",
};
}

View file

@ -1,17 +1,35 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdService.cs
//
// Automatically sends RequestId (appraisal) for newly-created world objects
// so that property caches (AppraisalHooks int/bool/string) are populated
// without requiring the player to manually select each object.
// Automatically sends RequestId (appraisal) for objects so that property caches
// (AppraisalHooks int/bool/string) are populated without requiring the player to
// manually select each object.
//
// Objects are queued from CreateObjectHooks and drained by a background timer
// with rate-limiting to avoid flooding the server.
// Candidates come from CreateObjectHooks (and the Decal bridge's create event), from
// items the server puts into a container (InventoryPutObjInContainer, SmartBoxHooks'
// game-event hook), from a rescan of a container the player opened, and from the
// one-shot login sweep of the pack. A background timer drains them (AutoIdDrain), at
// most AutoIdDrain.MaxPerTick sends per DrainIntervalMs.
//
// WHICH of them get an appraisal is two rules:
// - AutoIdEligibility (on create): an object the client released and re-created is
// not appraised again within 10 minutes of the last one while its data is still
// cached, unless the server deleted it;
// - AutoIdPolicy (on drain): the AutoIdMode (engine.json "AutoIdMode", /rc autoid).
// Limited (the default) appraises only the selected target, the
// items in the container the player has open, and items in the player's own
// inventory with nothing cached (at most 5 a second); the last two wait for a
// minimum object age and a defer after login and after every world transition.
// All is the old behaviour; Off sends nothing.
//
// Every send is queued with who asked (Net/IdRequester.cs), so the flight recorder tags
// it [eng:autoid-target|autoid-container|autoid-inventory|autoid-world].
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Threading;
using RynthCore.Engine.Net;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
@ -20,25 +38,101 @@ internal static class AutoIdService
// How often the drain timer fires (ms)
private const int DrainIntervalMs = 100;
// Max RequestId calls per drain tick
private const int MaxPerTick = 3;
// A container the player opened is rescanned this long after the open, so items the
// client already knew (created before the open, or by an earlier open) are candidates too.
private const long ContainerRescanDelayMs = AutoIdPolicy.MinAgeMs + 500;
// Skip objects already appraised this session
private static readonly ConcurrentDictionary<uint, byte> _sent = new();
// How long an appraisal stays good enough not to repeat: a client re-create inside
// this window, and the selected-target priority appraisal, skip an object whose
// appraisal is cached and this recent.
private const long ReappraiseWindowMs = AutoIdEligibility.DefaultWindowMs;
// Pending queue
private static readonly ConcurrentQueue<uint> _queue = new();
// Per-object appraisal bookkeeping. Written on AC's main thread (create, client
// release), the plugin pump (server delete) and the drain timer; every access holds
// _gate, for a few dictionary operations only.
private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs);
private static readonly object _gate = new();
private static readonly AutoIdDrain _drain = new(new LiveWorld());
private static int _draining;
private static Timer? _drainTimer;
private static bool _started;
private static volatile int _mode = (int)AutoIdPolicy.DefaultMode;
// The container the player opened last (ViewObjectContents), and when.
private static int _openedContainerId;
private static long _openedAtMs;
private static long _rescanDueMs;
private static long _skippedPriorityFresh;
/// <summary>The engine behind AutoIdDrain: the PWD snapshot, the appraisal cache, eligibility, the main-thread queue.</summary>
private sealed class LiveWorld : IAutoIdWorld
{
public bool TryGetOwnership(uint id, out uint container, out uint wielder) =>
ClientObjectHooks.TryGetObjectOwnershipInfo(id, out container, out wielder, out _);
public bool SnapshotWarm => ClientObjectHooks.HasPwdSnapshot;
public int CollectOwned(uint container, Span<uint> dest) =>
ClientObjectHooks.CollectOwnedIdsFromSnapshot(container, dest);
public bool IsLive(uint id)
{
lock (_gate) return _eligibility.IsLive(id);
}
public bool HasAppraisal(uint id) => AppraisalHooks.HasAppraisalData(id);
public bool IsFresh(uint id) => AutoIdEligibility.IsAppraisalFresh(
AppraisalHooks.HasAppraisalData(id), AppraisalHooks.GetLastIdTime(id),
DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
// 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).
// The appraisal counts as sent only when the main thread sends it (OnSent, from
// AcMainThreadQueue.DrainRequestIds): a queued request dropped there leaves it due again.
// Block-bodied, and named apart from the create-path Enqueue, so
// tools/check_offthread_mutators.py scans it and its allow-list entry covers only this.
public bool QueueIdentify(uint id, IdRequester who)
{
return AcMainThreadQueue.EnqueueRequestId(id, who);
}
public bool IsContainer(uint id) => ClientObjectHooks.IsContainerInSnapshot(id);
}
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
public static long SkippedRecentCount
{
get { lock (_gate) return _eligibility.SkippedRecentTotal; }
}
/// <summary>Selected-target priority appraisals skipped because the target's data is cached and fresh.</summary>
public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh);
/// <summary>The live mode (engine.json "AutoIdMode", /rc autoid).</summary>
public static AutoIdMode Mode => (AutoIdMode)_mode;
/// <summary>Switch the mode now; <paramref name="persist"/> also saves it to engine.json.</summary>
public static void SetMode(AutoIdMode mode, bool persist)
{
_mode = (int)mode;
if (persist)
EngineSettings.AutoIdMode = mode;
RynthLog.Compat($"Compat: AutoId mode {AutoIdPolicy.Name(mode)}.");
}
public static void Start()
{
if (_started)
return;
_started = true;
try { _mode = (int)EngineSettings.AutoIdMode; } catch { }
_drainTimer = new Timer(DrainTick, null, DrainIntervalMs, DrainIntervalMs);
RynthLog.Verbose("Compat: AutoIdService started.");
RynthLog.Verbose($"Compat: AutoIdService started (mode {AutoIdPolicy.Name(Mode)}).");
}
/// <summary>
@ -56,7 +150,8 @@ internal static class AutoIdService
}
/// <summary>
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour.
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour
/// (AC's main thread) and the Decal bridge's create event.
/// </summary>
public static void Enqueue(uint objectId)
{
@ -68,66 +163,291 @@ internal static class AutoIdService
if (playerId != 0 && objectId == playerId)
return;
// Skip if already sent this session
if (!_sent.TryAdd(objectId, 0))
return;
// Created again: data kept since a client release is current again (and still cached
// if the release was inside ReleasedObjectRetention's time).
AppraisalHooks.MarkLive(objectId);
bool cached = AppraisalHooks.HasAppraisalData(objectId);
long now = Environment.TickCount64;
AutoIdEligibility.CreateDecision decision;
lock (_gate)
decision = _eligibility.OnCreate(objectId, now, cached);
_queue.Enqueue(objectId);
if (decision == AutoIdEligibility.CreateDecision.Appraise)
_drain.Offer(objectId, now);
}
/// <summary>
/// Remove an object from the sent set (e.g. when it's destroyed and may be recreated).
/// The server put <paramref name="itemId"/> into <paramref name="containerId"/>
/// (InventoryPutObjInContainer, game event 0x0022; SmartBoxHooks' game-event hook on AC's
/// main thread, or the Decal bridge on the pump). In Limited mode an item that landed in
/// the player's inventory with nothing cached is a candidate; where it landed is decided
/// at the drain, from the object snapshot.
/// </summary>
public static void Evict(uint objectId)
public static void OnPutInContainer(uint itemId, uint containerId)
{
_sent.TryRemove(objectId, out _);
if (itemId == 0 || containerId == 0 || Mode != AutoIdMode.Limited)
return;
if (AppraisalHooks.HasAppraisalData(itemId))
return;
_drain.Offer(itemId, Environment.TickCount64);
}
/// <summary>
/// The client opened <paramref name="containerId"/>'s contents (ViewObjectContents, AC's
/// main thread). Its time decides the defer exemption, and a rescan after the minimum
/// age makes the items already known in it candidates.
/// </summary>
public static void OnContainerOpened(uint containerId)
{
if (containerId == 0) return;
long now = Environment.TickCount64;
Interlocked.Exchange(ref _openedAtMs, now);
Interlocked.Exchange(ref _openedContainerId, unchecked((int)containerId));
Interlocked.Exchange(ref _rescanDueMs, now + ContainerRescanDelayMs);
}
/// <summary>
/// The CLIENT released an object (ACCObjectMaint::DeleteObject, or the Decal bridge's
/// delete event). A queued appraisal for it is skipped; its last appraisal time is kept,
/// so a re-create inside the window is not appraised again.
/// </summary>
public static void OnClientRelease(uint objectId)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnClientRelease(objectId);
}
/// <summary>
/// The SERVER deleted an object (0xF747 ObjectDelete, from the server message stream on
/// the plugin pump). Whatever is created under that id next is appraised.
/// </summary>
public static void OnServerDelete(uint objectId)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnServerDelete(objectId);
// It really went away: its kept identify data goes too.
AppraisalHooks.EvictObject(objectId);
}
/// <summary>
/// The 0xC8 for <paramref name="objectId"/> really went out (AcMainThreadQueue's drain, on
/// AC's main thread, for every RequestId caller). Starts its re-appraisal window.
/// </summary>
public static void OnSent(uint objectId, long nowMs)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnSent(objectId, nowMs);
}
// Last target we issued a priority appraisal for (fires once per target change).
private static uint _lastPriorityTarget;
private static long _lastPruneMs;
private static void DrainTick(object? state)
{
// A slow tick must not overlap the next one: the drain's pending list is this timer's alone.
if (Interlocked.CompareExchange(ref _draining, 1, 0) != 0)
return;
try
{
if (!CombatActionHooks.HasRequestId)
return;
// Dead / portaling / settling: AcMainThreadQueue refuses appraisals now, so the
// backlog waits here instead of being dequeued into a refusal and lost.
if (PlayerLifecycleLog.InWorldTransition)
return;
long now = Environment.TickCount64;
AutoIdMode mode = Mode;
int sent = 0;
uint playerId = ClientHelperHooks.GetPlayerId();
// 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.
// immediately, ahead of the backlog, so a fast kill still gets its max-HP
// appraisal out first. Fires once per change (guarded), so no per-tick
// re-appraisal. Skipped when the target's appraisal is already cached and
// fresh. Exempt from the minimum age, the defers and the inventory cap. A
// refused enqueue forgets the change, so the next tick tries again.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
_lastPriorityTarget = target;
uint playerId = ClientHelperHooks.GetPlayerId();
if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target))
sent++;
if (target != playerId)
{
bool cached = AppraisalHooks.HasAppraisalData(target);
bool fresh = AutoIdEligibility.IsAppraisalFresh(
cached, AppraisalHooks.GetLastIdTime(target), DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
switch (AutoIdPolicy.Decide(mode, AutoIdPolicy.Class.Target, 0, false, false, fresh, cached))
{
case AutoIdPolicy.Verdict.SkipFresh:
Interlocked.Increment(ref _skippedPriorityFresh);
_drain.CountSkipFresh();
break;
case AutoIdPolicy.Verdict.Send:
if (AcMainThreadQueue.EnqueueRequestId(target, IdRequester.AutoIdTarget))
sent++;
else
_lastPriorityTarget = 0;
break;
default:
_drain.CountSkipMode();
break;
}
}
}
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
{
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
// Deleted since it was queued: Evict took it out of _sent. Skip it without
// spending one of the 3 requests per tick. After a big landblock change (the
// 585 deletes of 2026-10-02) the queue otherwise kept asking the server to
// appraise gone objects at 30 a second for half a minute, and live ones waited.
// A delete-then-recreate is queued again by Enqueue, so nothing live is lost.
if (!_sent.ContainsKey(objectId))
continue;
RescanOpenedContainer(now, mode);
// 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++;
uint open = ClientHelperHooks.GetGroundContainerId();
var ctx = new AutoIdDrain.Context
{
Now = now,
Mode = mode,
PlayerId = playerId,
OpenContainer = open,
OpenedAtMs = open != 0 && unchecked((uint)Volatile.Read(ref _openedContainerId)) == open
? Interlocked.Read(ref _openedAtMs) : 0,
SettleUntilMs = PlayerLifecycleLog.SettleUntilMs,
LoginCompleteAtMs = LoginLifecycleHooks.LoginCompleteAtMs,
// Each 0xC8 raises AC's busy count, which plugins gate their casts on: the
// pack waits while a cast is in flight or an attack runs (not for a selection alone).
CombatBusy = AutoIdPolicy.InCombat(target, CastGate.GetCastBusyState(),
ClientActionGates.TryReadAttacking(out bool attacking) && attacking),
};
_drain.Tick(ctx, sent);
// Keep the bookkeeping bounded. Here, off AC's main thread: the create path
// never prunes.
if (now - _lastPruneMs >= 10_000)
{
_lastPruneMs = now;
int removed;
lock (_gate)
removed = _eligibility.Count > _eligibility.MaxTracked / 2 ? _eligibility.Prune(now) : 0;
if (removed > 0)
RynthLog.Verbose($"Compat: AutoIdService pruned {removed} appraisal record(s).");
// Identify data kept after a client release: dropped once its time is up.
int expired = AppraisalHooks.ExpireReleased(now);
if (expired > 0)
RynthLog.Verbose($"Compat: AppraisalHooks dropped {expired} released object(s) past the retention time.");
}
}
catch { }
finally
{
Volatile.Write(ref _draining, 0);
}
}
/// <summary>Limited mode: the items already in a container the player opened become candidates.</summary>
private static void RescanOpenedContainer(long now, AutoIdMode mode)
{
long due = Interlocked.Read(ref _rescanDueMs);
if (due == 0 || now < due)
return;
Interlocked.CompareExchange(ref _rescanDueMs, 0, due);
if (mode != AutoIdMode.Limited)
return;
uint container = unchecked((uint)Volatile.Read(ref _openedContainerId));
if (container == 0 || ClientHelperHooks.GetGroundContainerId() != container)
return; // closed again (or another one opened: its own rescan follows)
_drain.AddContainerContents(container, Interlocked.Read(ref _openedAtMs), mode);
}
// -- counters: /rc autoid and the per-minute log line --
private static readonly IdRequester[] Sources =
{
IdRequester.AutoIdTarget, IdRequester.AutoIdContainer, IdRequester.AutoIdInventory, IdRequester.AutoIdWorld,
IdRequester.Plugin, IdRequester.Self, IdRequester.Ui, IdRequester.None,
};
private static readonly long[] _lastSent = new long[IdRequesters.Count];
private static long _lastForeign, _lastSkipMode, _lastSkipAge, _lastSkipDefer, _lastSkipFresh, _lastSkipRate, _lastSkipCombat;
/// <summary>
/// The last minute's IdentifyObject counts (heartbeat thread, once a minute): sent per
/// requester, cli = sent by AC or Decal (from the flight recorder; ? while it is off),
/// and AutoId's skips by reason. None of its fields contains fps=, plug=, login= or qd=
/// (the launcher's heartbeat regex), and the line does not start with "hb #".
/// </summary>
public static string TakeMinuteLine()
{
long foreign = FlightRecorder.ForeignIdentifyTotal;
long sm = _drain.SkipMode, sa = _drain.SkipAge, sd = _drain.SkipDefer, sf = _drain.SkipFresh, sr = _drain.SkipRate, sc = _drain.SkipCombat;
var sb = new System.Text.StringBuilder(176);
sb.Append("autoid 60s: mode=").Append(AutoIdPolicy.Name(Mode)).Append(" sent");
long total = 0;
foreach (IdRequester who in Sources)
{
long now = IdSendStats.Sent(who);
long d = now - _lastSent[(int)who];
_lastSent[(int)who] = now;
total += d;
if (who == IdRequester.None && d == 0) continue; // unmarked engine sends: shown only when there are any
sb.Append(' ').Append(IdRequesters.Short(who)).Append('=').Append(d);
}
if (foreign >= 0)
{
long d = foreign - _lastForeign;
_lastForeign = foreign;
total += d;
sb.Append(" cli=").Append(d);
}
else
{
sb.Append(" cli=?");
}
sb.Append(" tot=").Append(total);
sb.Append(" skip mode=").Append(sm - _lastSkipMode).Append(" age=").Append(sa - _lastSkipAge)
.Append(" defer=").Append(sd - _lastSkipDefer).Append(" fresh=").Append(sf - _lastSkipFresh)
.Append(" rate=").Append(sr - _lastSkipRate).Append(" combat=").Append(sc - _lastSkipCombat);
sb.Append(" pend=").Append(_drain.PendingCount);
_lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf; _lastSkipRate = sr; _lastSkipCombat = sc;
return sb.ToString();
}
/// <summary>/rc autoid [all|limited|off|status]</summary>
public static string[] HandleCommand(string args)
{
string verb = (args ?? "").Trim();
if (verb.Length > 0 && !verb.Equals("status", StringComparison.OrdinalIgnoreCase))
{
if (!AutoIdPolicy.TryParseMode(verb, out AutoIdMode mode))
return new[] { "Usage: /rc autoid [all|limited|off] (alone: status)" };
SetMode(mode, persist: true);
}
return StatusLines();
}
public static string[] StatusLines()
{
var sent = new System.Text.StringBuilder();
foreach (IdRequester who in Sources)
{
long n = IdSendStats.Sent(who);
if (who == IdRequester.None && n == 0) continue;
sent.Append(sent.Length > 0 ? ", " : "").Append(IdRequesters.Short(who)).Append(' ').Append(n);
}
long foreign = FlightRecorder.ForeignIdentifyTotal;
string modeText = Mode switch
{
AutoIdMode.All => "all (every created object, the old behaviour)",
AutoIdMode.Off => "off (no background appraisals, not even the selected target)",
_ => $"limited (selected target; open container and own inventory after {AutoIdPolicy.MinAgeMs / 1000} s, {AutoIdPolicy.DeferMs / 1000} s after login or a portal/death/teleport; inventory at most {1000 / AutoIdPolicy.InventoryMinIntervalMs}/s, and not while a cast or attack is in flight)",
};
string extra = "";
if (_drain.Overflow > 0) extra += $", overflow {_drain.Overflow}";
if (_drain.IncomingDropped > 0) extra += $", dropped while held {_drain.IncomingDropped}";
return new[]
{
$"AutoId: {modeText}. Saved in engine.json; /rc autoid all|limited|off switches it now. Plugins' own identifies are never limited.",
$"Identifies sent since start: {sent}; by AC or Decal: {(foreign >= 0 ? foreign.ToString() : "? (flight recorder off)")}.",
$"AutoId skipped: mode {_drain.SkipMode}, fresh {_drain.SkipFresh}, recent re-create {SkippedRecentCount}; " +
$"waited: age {_drain.SkipAge}, defer {_drain.SkipDefer}, rate {_drain.SkipRate}, combat {_drain.SkipCombat}; refused {_drain.Refused} (kept); " +
$"login sweep {_drain.Swept}; pending now {_drain.PendingCount}{extra}.",
};
}
}

View file

@ -0,0 +1,59 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CastSlot.cs
//
// AcMainThreadQueue's single-outstanding cast slot (SelectItem + CastSpell pair): one
// pending cast at a time, taken by DrainCasts on AC's game-logic tick.
//
// A cast is refused outright during a world transition (dead, in portal space, or the
// settle window after a teleport): the drain would only hold it and then drop it, and
// meanwhile the slot would refuse every newer cast. The caller (BuffManager /
// CombatManager) already treats false as "retry next tick". Refused like the action ring
// refuses non-teardown work during a transition (ActionRing.Admit.RejectedTransition).
//
// Pure: no engine state, no locking (AcMainThreadQueue holds _castLock for every write;
// DrainCasts reads Pending and QueuedAt with Volatile, hence public fields). Compiled
// into tools\EngineRobustnessTests.
// ============================================================================
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal sealed class CastSlot
{
public enum Admit
{
Queued,
/// <summary>A cast is already pending; nothing changed.</summary>
Busy,
/// <summary>A world transition is in progress; nothing changed.</summary>
RejectedTransition,
}
public int Pending;
public uint TargetId;
public uint SpellId;
/// <summary>TickCount64 when the pending cast was queued.</summary>
public long QueuedAt;
/// <summary>
/// The drain has counted this cast's wait for a movement stop queued before it (once per
/// cast). Reset by every queued cast; set by DrainCasts on the main thread.
/// </summary>
public bool StopWaitNoted;
/// <summary>Under the caller's lock. The slot is written only when this returns Queued.</summary>
public Admit TryEnqueue(uint targetId, uint spellId, long nowMs, bool inTransition)
{
if (inTransition) return Admit.RejectedTransition;
if (Pending != 0) return Admit.Busy;
TargetId = targetId;
SpellId = spellId;
// Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can
// tear on x86. The time and the stop-wait reset first, then the flag that publishes
// them (a release store, so the drain's Volatile.Read of Pending sees both).
Volatile.Write(ref QueuedAt, nowMs);
StopWaitNoted = false;
Volatile.Write(ref Pending, 1);
return Admit.Queued;
}
}

View file

@ -0,0 +1,38 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CastStopRules.cs
//
// The cast drain's question about the action ring: is a movement stop queued at or
// before the pending cast? (AcMainThreadQueue.StopQueuedAtOrBefore: such a stop runs
// first, so the cast's own stop is not sent while AC's locomotion is still on.)
//
// Every queued entry is checked. An entry's time is taken before ActionRing's producer
// lock, so two producers can land slightly out of time order, and a walk that stopped
// at the first entry newer than the cast could miss an older stop queued behind it.
//
// Pure: no engine state. Consumer side of the ring only (AC's main thread). Compiled
// into tools\EngineRobustnessTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class CastStopRules
{
/// <summary>
/// True when any entry in <paramref name="ring"/> was queued at or before
/// <paramref name="castQueuedAt"/> (by <paramref name="queuedAt"/>) and is a movement stop
/// (by <paramref name="isStop"/>). Pass static lambdas: nothing is allocated per call.
/// </summary>
public static bool AnyStopAtOrBefore<T>(ActionRing<T> ring, long castQueuedAt,
Func<T, long> queuedAt, Func<T, bool> isStop) where T : struct
{
int count = ring.Count;
for (int i = 0; i < count; i++)
{
if (!ring.TryPeekAt(i, out T e)) break;
if (queuedAt(e) <= castQueuedAt && isStop(e)) return true;
}
return false;
}
}

View file

@ -51,6 +51,17 @@ internal static class CharacterCaptureHooks
private const int AutoLoginPollIntervalMs = 600;
private const int AutoLoginPollHardTimeoutMs = 120_000;
private const int AutoLoginDirectFailsBeforeClick = 4;
// Bounced back to char-select (2026-10-13): a client relaunched right after a crash got
// into the world and was sent back to char-select 7 s later (the server still held the
// old session), and auto-login had already stood down, so it sat there for 5 hours.
// After entering the world the poll now watches for BounceWindowMs; back at char-select
// inside that window it waits (BounceRetryBaseMs x the bounce count, at most
// BounceRetryMaxMs) and logs on again, up to MaxBounceRetries times.
private const int BounceWindowMs = 90_000;
private const int BounceRetryBaseMs = 20_000;
private const int BounceRetryMaxMs = 120_000;
private const int MaxBounceRetries = 8;
private static int _autoLoginPollStarted;
// Native character-list capture. The 0xF658 packet path is dead (see above),
@ -148,17 +159,38 @@ internal static class CharacterCaptureHooks
long charSelectFirstSeenTick = 0;
int directFailCount = 0;
bool issuedDirect = false;
int bounces = 0;
string status = string.Empty;
try
{
while (EngineThreads.Sleep(AutoLoginPollIntervalMs))
{
if (LoginLifecycleHooks.HasObservedLoginComplete)
bool loginComplete = LoginLifecycleHooks.HasObservedLoginComplete;
bool inWorld = CharacterManagementHooks.TryGetCurrentMode(out int worldMode) && worldMode == GamePlayUIMode;
if (loginComplete || inWorld)
{
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' (LoginComplete observed).");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
RynthLog.Info($"CharacterCapture: '{targetCharacter}' is in the world ({(loginComplete ? "LoginComplete observed" : "GamePlayUI")}); watching {BounceWindowMs / 1000}s for a bounce back to char-select.");
if (!WatchForBounce(targetCharacter))
{
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return; // stayed in the world (or the engine is stopping)
}
if (++bounces > MaxBounceRetries)
{
RynthLog.Warn($"CharacterCapture: '{targetCharacter}' was sent back to char-select {bounces} times; auto-login gives up.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
int waitMs = Math.Min(BounceRetryBaseMs * bounces, BounceRetryMaxMs);
RynthLog.Warn($"CharacterCapture: '{targetCharacter}' was sent back to char-select right after entering the world (bounce {bounces}/{MaxBounceRetries}, probably the server still holding the last session); logging on again in {waitMs / 1000}s.");
if (!WaitAtCharSelect(waitMs))
continue; // the player went in by hand: the next pass watches that
charSelectFirstSeenTick = 0;
directFailCount = 0;
issuedDirect = false;
continue;
}
// One-shot: if the (currently dead) packet path ever fires and
@ -173,11 +205,7 @@ internal static class CharacterCaptureHooks
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;
}
continue; // the in-world watch at the top of the loop takes it
if (mode != CharacterManagementUIMode)
{
@ -199,7 +227,7 @@ internal static class CharacterCaptureHooks
// 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))
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out status))
{
if (!issuedDirect)
{
@ -247,6 +275,39 @@ internal static class CharacterCaptureHooks
}
}
/// <summary>
/// In the world: true if the client is back at char-select within BounceWindowMs,
/// false once it has stayed in the world that long (or the engine is stopping).
/// </summary>
private static bool WatchForBounce(string targetCharacter)
{
long since = Environment.TickCount64;
while (EngineThreads.Sleep(1000))
{
if (Environment.TickCount64 - since >= BounceWindowMs)
{
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' ({BounceWindowMs / 1000}s in the world).");
return false;
}
if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == CharacterManagementUIMode)
return true;
}
return false;
}
/// <summary>Waits <paramref name="ms"/> at char-select; false if the client entered the world meanwhile.</summary>
private static bool WaitAtCharSelect(int ms)
{
long until = Environment.TickCount64 + ms;
while (Environment.TickCount64 < until)
{
if (!EngineThreads.Sleep(1000)) return false;
if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == GamePlayUIMode)
return false;
}
return true;
}
private static void StartCharacterListCapturePoll()
{
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)

View file

@ -177,7 +177,7 @@ internal static class ClientCombatHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
try

View file

@ -36,6 +36,16 @@ internal static class ClientHelperHooks
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void GmSalvageUISalvageDelegate(IntPtr thisPtr);
// CM_Inventory::Event_CreateTinkeringTool(ulong toolId, PackableList<ulong> const& items) - cdecl,
// returns bool. The 0x027D CreateTinkeringTool game action: what gmSalvageUI::Salvage (the panel's
// Salvage button) sends, with the panel's tool (+0x608) and the ids of the items in its list. Chorizite
// map 002AB790 -> live VA 0x006AC790; its one caller is gmSalvageUI::Salvage (call at 0x004CC4DB).
// Same generated Event_* template as Event_DropItem etc., except the list is packed through its own
// vtable (slot 3, PackableList<ulong>::Pack, called once with size 0 for the size, then to write):
// wire = opcode, toolId, count, ids. ACE: GameActionCreateTinkeringTool -> Player.HandleSalvaging.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventCreateTinkeringToolDelegate(uint toolId, IntPtr packableList);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UseEquippedItemDelegate(IntPtr acPlugin, uint sourceObjectId, uint targetObjectId);
@ -170,6 +180,11 @@ internal static class ClientHelperHooks
private const int SendNoticeOpenSalvagePanelVa = 0x006AD4F0;
private const int GmSalvageUIAddNewItemVa = 0x004CC020;
private const int GmSalvageUISalvageVa = 0x004CC430;
// CM_Inventory::Event_CreateTinkeringTool (FALLBACK only; pattern-scanned).
private const int EventCreateTinkeringToolVa = 0x006AC790;
// PackableList<ulong>'s vtable (.rdata), FALLBACK only: read from the immediate gmSalvageUI::Salvage
// writes into its local list (mov [esp+10h], offset vtable @0x004CC448).
private const int PackableListULongVtableVa = 0x007A4ED0;
private static SetSelectedObjectDelegate? _setSelectedObject;
private static UseObjectDelegate? _useObject;
@ -191,6 +206,8 @@ internal static class ClientHelperHooks
private static SendNoticeOpenSalvagePanelDelegate? _sendNoticeOpenSalvagePanel;
private static GmSalvageUIAddNewItemDelegate? _gmSalvageUIAddNewItem;
private static GmSalvageUISalvageDelegate? _gmSalvageUISalvage;
private static EventCreateTinkeringToolDelegate? _eventCreateTinkeringTool;
private static IntPtr _packableListULongVtable;
private static bool _initialized;
private static string _statusMessage = "Not probed yet.";
private static int _interactionLogCount;
@ -219,6 +236,11 @@ internal static class ClientHelperHooks
public static bool HasWriteToChat => _addTextToScroll != null;
public static bool HasInvokeParser => true;
public static bool HasSalvagePanel => _sendNoticeOpenSalvagePanel != null && _gmSalvageUIAddNewItem != null && _gmSalvageUISalvage != null;
/// <summary>v82: <see cref="SalvageDirect"/> (the 0x027D salvage request without the panel).</summary>
public static bool HasSalvageDirect => _eventCreateTinkeringTool != null && _packableListULongVtable != IntPtr.Zero;
/// <summary>Most item ids one <see cref="SalvageDirect"/> request carries. ACE reads any count; 100 ids
/// keep the game action (header + tool + count + ids, 420 bytes) inside one network fragment.</summary>
public const int MaxSalvageDirectItems = 100;
private static int _currentGroundContainerId;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
@ -263,6 +285,17 @@ internal static class ClientHelperHooks
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 ];
// CM_Inventory::Event_CreateTinkeringTool @0x006AC790. The Event_* template with the list argument:
// `mov edi,[esp+20h]` (the list) right after the first call, `call [eax+0Ch]` (the list's Pack), and the
// 0x027D opcode write (C7 01 7D 02 00 00) at the end. Verified unique (1 match @0x006AC790) via
// pe_pattern.py against C:\Games\RynthCore\AcClient and C:\Turbine acclient.exe, 2026-10-12.
private static readonly byte?[] PatEventCreateTinkeringTool = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x7C, 0x24, 0x20, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x89, 0x44, 0x24, 0x18, 0x8B, 0x07, 0x51, 0x8B, 0xCF, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x0C, 0x6A, 0x00, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x89, 0x44, 0x24, 0x0C, 0x8B, 0xD8, 0x56, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x1C, 0xC7, 0x01, 0x7D, 0x02 ];
// Data xref for PackableList<ulong>'s vtable: gmSalvageUI::Salvage builds its local list with
// `mov [esp+10h], vtable` then zeroes head/tail/count (`mov [esp+14h/18h/1Ch], ebx`) and calls
// GetNumUIItems. Operand at +4. Unique (1 site @0x004CC448) in both acclient copies, 2026-10-12.
private static readonly byte?[] PatXrefPackableListULongVtable = [ 0xC7, 0x44, 0x24, 0x10, null, null, null, null, 0x89, 0x5C, 0x24, 0x14, 0x89, 0x5C, 0x24, 0x18, 0x89, 0x5C, 0x24, 0x1C, 0xE8 ];
// PackableList<ulong>::Pack (vtable slot 3) starts push esi; push edi; mov esi,ecx; call pack_size.
private static readonly byte[] PackableListULongPackPrologue = [ 0x56, 0x57, 0x8B, 0xF1, 0xE8 ];
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
@ -327,6 +360,7 @@ internal static class ClientHelperHooks
_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);
BindSalvageDirect(text);
_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();
@ -371,7 +405,7 @@ internal static class ClientHelperHooks
// (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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSetSelectedObject(objectId);
if (_setSelectedObject == null)
@ -400,7 +434,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SelectFromOverlay(uint objectId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueOverlaySelect(objectId);
if (objectId == 0 || _setSelectedObject == null)
@ -433,7 +467,7 @@ internal static class ClientHelperHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseObject(objectId);
if (_useObject == null || !IsValidObjectId(objectId))
@ -466,7 +500,7 @@ internal static class ClientHelperHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId);
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
@ -492,7 +526,7 @@ internal static class ClientHelperHooks
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId);
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
@ -517,7 +551,7 @@ internal static class ClientHelperHooks
{
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount);
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
@ -547,7 +581,7 @@ internal static class ClientHelperHooks
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
@ -604,7 +638,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
@ -656,12 +690,21 @@ internal static class ClientHelperHooks
/// </summary>
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
// Every exit records its outcome in MergeStackResults so the plugin can poll
// GetMergeStackResult instead of guessing from a later inventory snapshot.
if (AcMainThreadQueue.MustQueue(teardown: false))
{
bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
MergeStackResults.Record(sourceObjectId, targetObjectId,
queued ? MergeStackResults.Queued : MergeStackResults.QueueFull);
return queued;
}
if (_eventStackableMerge == null) return false;
if (!IsValidObjectId(sourceObjectId)) return false;
if (!IsValidObjectId(targetObjectId)) return false;
if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
{
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
// Read counts via the PWD fast path (stypes 11/12 are served from
// PublicWeenieDesc directly — no broken InqInt for inventory items).
@ -680,6 +723,7 @@ internal static class ClientHelperHooks
if (room <= 0)
{
RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull);
return false;
}
amount = Math.Min(sourceCount, room);
@ -690,17 +734,24 @@ internal static class ClientHelperHooks
amount = sourceCount;
}
if (amount <= 0) return false;
if (amount <= 0)
{
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
try
{
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
MergeStackResults.Record(sourceObjectId, targetObjectId,
rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0);
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
}
@ -714,7 +765,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot);
if (_eventPutItemInContainer == null) return false;
@ -749,7 +800,7 @@ internal static class ClientHelperHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount);
if (_eventGiveObjectRequest == null) return false;
@ -795,7 +846,7 @@ internal static class ClientHelperHooks
public static bool WieldItem(uint objectId, uint equipMask)
{
// Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0
&& AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask);
@ -825,7 +876,7 @@ internal static class ClientHelperHooks
public static bool DropItem(uint objectId)
{
// Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventDropItem != null && IsValidObjectId(objectId)
&& AcMainThreadQueue.EnqueueDropItem(objectId);
@ -859,7 +910,7 @@ internal static class ClientHelperHooks
public static bool CloseContainer(uint containerId)
{
// An inventory game-action send, like DropItem / WieldItem: main thread only.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return _eventNoLongerViewingContents != null && IsValidObjectId(containerId)
&& AcMainThreadQueue.EnqueueCloseContainer(containerId);
@ -964,6 +1015,7 @@ internal static class ClientHelperHooks
return;
Interlocked.Exchange(ref _currentGroundContainerId, unchecked((int)objectId));
AutoIdService.OnContainerOpened(objectId);
}
public static void NotifyStopViewingObjectContents(uint objectId)
@ -1151,7 +1203,7 @@ internal static class ClientHelperHooks
// same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with
// one consumer, so open -> add -> execute keep their order. Drain calls
// back into this method on the main thread, where the gate is satisfied.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageOpen(toolId);
try
@ -1193,7 +1245,7 @@ internal static class ClientHelperHooks
// queued entry carries only the item id: on the main thread this method
// runs again and re-reads the instance, since the panel may have closed
// or been rebuilt in between.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageAddItem(itemId);
try
@ -1228,7 +1280,7 @@ internal static class ClientHelperHooks
// Off-thread: same shape as SalvagePanelAddItem (instance re-read on the
// main thread when the entry drains).
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageExecute();
try
@ -1243,6 +1295,120 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// Binds CM_Inventory::Event_CreateTinkeringTool and finds PackableList&lt;ulong&gt;'s vtable (the
/// sender packs the item list through it). The vtable is accepted only when its slot 3 lands in the
/// scanned window on PackableList&lt;ulong&gt;::Pack's prologue, so a wrong address leaves
/// <see cref="HasSalvageDirect"/> false instead of handing AC a bad list.
/// </summary>
private static void BindSalvageDirect(AcClientTextSection text)
{
_eventCreateTinkeringTool = null;
_packableListULongVtable = IntPtr.Zero;
try
{
var send = Bind<EventCreateTinkeringToolDelegate>(text, "ClientHelper.Event_CreateTinkeringTool",
PatEventCreateTinkeringTool, EventCreateTinkeringToolVa);
int vtable = HookResolver.ResolveData(text, "ClientHelper.PackableList_ulong_vtable",
PatXrefPackableListULongVtable, 4, PackableListULongVtableVa).Address.ToInt32();
int slotOff = vtable + 3 * 4 - text.TextBaseVa;
if (send == null || slotOff < 0 || slotOff + 4 > text.Bytes.Length)
{
RynthLog.Compat($"Compat: salvage without the panel unavailable (sender {(send == null ? "not found" : "ok")}, vtable 0x{vtable:X8}).");
return;
}
int pack = BitConverter.ToInt32(text.Bytes, slotOff);
int packOff = pack - text.TextBaseVa;
bool prologueOk = packOff >= 0 && packOff + PackableListULongPackPrologue.Length <= text.Bytes.Length;
for (int i = 0; prologueOk && i < PackableListULongPackPrologue.Length; i++)
prologueOk = text.Bytes[packOff + i] == PackableListULongPackPrologue[i];
if (!prologueOk)
{
RynthLog.Compat($"Compat: salvage without the panel unavailable - vtable 0x{vtable:X8} slot 3 (0x{pack:X8}) is not PackableList<ulong>::Pack.");
return;
}
_packableListULongVtable = new IntPtr(vtable);
_eventCreateTinkeringTool = send;
RynthLog.Verbose($"Compat: salvage without the panel ready (PackableList<ulong> vtable 0x{vtable:X8}, Pack 0x{pack:X8}).");
}
catch (Exception ex)
{
_eventCreateTinkeringTool = null;
_packableListULongVtable = IntPtr.Zero;
RynthLog.Compat($"Compat: salvage-without-panel binding failed - {ex.Message}");
}
}
/// <summary>
/// Salvage without the salvage panel: sends the 0x027D CreateTinkeringTool game action (what the
/// panel's Salvage button sends) through AC's own sender, CM_Inventory::Event_CreateTinkeringTool,
/// with <paramref name="toolId"/> (the UST) and <paramref name="itemIds"/> (at most
/// <see cref="MaxSalvageDirectItems"/>). The list is a PackableList&lt;ulong&gt; built on this
/// stack frame (AC's layout: vtable, head, tail, count; nodes of value, next, prev) and only read by
/// the sender, so nothing is allocated in AC's heap and nothing outlives the call. The panel is
/// never opened, nothing in the UI changes, and the client's busy count is not touched.
///
/// ACE (Player.HandleSalvaging) checks the tool is a UST (wcid 20646) the player owns (else
/// "That is not a salvaging tool." / "You do not own that salvage tool!"), then for each id an item
/// in the player's packs (not worn), with a material and workmanship and not retained, is consumed;
/// ids that fail are skipped silently. Salvage bags in the list are merged with the new salvage.
/// The answer: the items' removal, new salvage bags created in the pack, and one "You obtain ..."
/// line per skill (SalvageOperationsResult, printed by ClientUISystem, not the panel).
///
/// Off AC's main thread it is queued (the list is copied); true = sent, or queued.
/// </summary>
public static bool SalvageDirect(uint toolId, uint[] itemIds)
{
if (!HasSalvageDirect || toolId == 0 || itemIds == null || itemIds.Length == 0 || itemIds.Length > MaxSalvageDirectItems)
return false;
foreach (uint id in itemIds)
if (id == 0 || id == toolId) return false;
// PR #8's gate: also queued on the main thread while a death/portal transition holds work.
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageDirect(toolId, itemIds);
return SendCreateTinkeringTool(toolId, itemIds);
}
private static unsafe bool SendCreateTinkeringTool(uint toolId, uint[] itemIds)
{
// Main thread only (SalvageDirect marshals; this is its main-thread half).
if (!MainThreadGuard.IsOnMainThread()) return false;
IntPtr vtable = _packableListULongVtable;
if (_eventCreateTinkeringTool == null || vtable == IntPtr.Zero) return false;
int n = itemIds.Length;
// Header (4 dwords) + n nodes of 3 dwords, all on this frame (n <= 100: at most 1216 bytes).
uint* buf = stackalloc uint[4 + 3 * MaxSalvageDirectItems];
uint* nodes = buf + 4;
for (int i = 0; i < n; i++)
{
uint* node = nodes + 3 * i;
node[0] = itemIds[i]; // value
node[1] = i + 1 < n ? (uint)(nint)(nodes + 3 * (i + 1)) : 0u; // next
node[2] = i > 0 ? (uint)(nint)(nodes + 3 * (i - 1)) : 0u; // prev
}
buf[0] = (uint)vtable.ToInt32(); // vtable
buf[1] = (uint)(nint)nodes; // head
buf[2] = (uint)(nint)(nodes + 3 * (n - 1)); // tail
buf[3] = (uint)n; // count
try
{
byte rv = _eventCreateTinkeringTool(toolId, (IntPtr)buf);
RynthLog.Verbose($"Compat: Event_CreateTinkeringTool tool=0x{toolId:X8} items={n} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_CreateTinkeringTool threw - {ex.Message}");
return false;
}
}
public static bool InvokeParser(string? text)
{
if (string.IsNullOrEmpty(text))
@ -1288,6 +1454,8 @@ internal static class ClientHelperHooks
_sendNoticeOpenSalvagePanel = null;
_gmSalvageUIAddNewItem = null;
_gmSalvageUISalvage = null;
_eventCreateTinkeringTool = null;
_packableListULongVtable = IntPtr.Zero;
_initialized = false;
}

View file

@ -241,6 +241,24 @@ internal static class ClientObjectHooks
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
private static bool _loggedObjectIdentityServe;
private const int ObjectIdentityPrefetchThrottleMs = 500;
// Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's
// PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before
// qualities/appraisal exist. The main-thread snapshot above can't resolve names for
// ~10 s after login (qualities not populated yet), so off-thread readers fall back to
// these seeds when the snapshot has no entry (or reports type 0). Entries live from
// create until delete; the cap only guards against a missed delete hook.
private static readonly object _createSeedLock = new();
private static readonly Dictionary<uint, string> _createSeedNames = new(1024);
private static readonly Dictionary<uint, uint> _createSeedTypes = new(1024);
private const int CreateSeedCap = 16384;
// PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct
// fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy).
// PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down.
private const int PwdNameOffset = 4;
private static int _createSeedCount;
private static bool _loggedCreateSeedServe;
// Every id the same walk visited, swapped whole (readers never see a half-built array).
private static volatile uint[] _liveObjectIds = Array.Empty<uint>();
@ -393,6 +411,7 @@ internal static class ClientObjectHooks
private static readonly object _weeniePtrSwapLock = new();
private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512);
private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512);
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of
// objects with a position but no cached name. Remove once the missing-
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
return false;
// Off-thread: served from the main-thread PWD byte snapshot, never from AC memory.
if (!MainThreadGuard.IsOnMainThread())
return false;
return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value);
if (_getWeenieObject == null)
{
if (!Probe() || _getWeenieObject == null)
@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks
// Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity().
if (!MainThreadGuard.IsOnMainThread())
{
lock (_objectIdentityCacheLock)
{
// A zero snapshot value means qualities weren't populated when the walk
// ran; prefer the create-time descriptor type in that case.
if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0)
return true;
}
if (TryGetCreateSeedType(objectId, out uint seeded))
{
typeFlags = seeded;
return true;
}
// Snapshot hit with flags=0 is still an answer (static scenery often has no type).
lock (_objectIdentityCacheLock)
{
if (_objectTypeCache.TryGetValue(objectId, out typeFlags))
@ -2592,36 +2625,7 @@ internal static class ClientObjectHooks
return TryGetPwdSnapshotInt(objectId, stype, out value);
}
if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0)
{
try
{
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return false;
int pwdBase = _weeniePhysicsObjOffset + 4;
IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset;
// Page-probe BOTH ends of the 4-byte read span (mirrors
// TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted
// weenie whose field straddles a committed/decommitted page boundary is
// an uncatchable AV under NativeAOT; the catch below only covers
// null-page faults. All stypes served here are Marshal.ReadInt32
// (4 bytes), so the span is [fieldAddr, fieldAddr+3].
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
return false;
value = Marshal.ReadInt32(fieldAddr);
return true;
}
catch
{
return false;
}
}
// Fall through to CBaseQualities::InqInt for stypes not in PWD.
// (IsOnMainThread already checked above, before the PWD fast path.)
// CBaseQualities::InqInt for stypes not in PWD.
if (_inqInt == null)
{
if (!Probe() || _inqInt == null)
@ -3341,6 +3345,101 @@ internal static class ClientObjectHooks
}
}
/// <summary>
/// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed
/// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread,
/// after the original returns. The descriptor is server data that exists before the
/// object's qualities do, so this makes names/types readable off-thread immediately
/// instead of after the first successful identity snapshot (~10 s at login).
/// Every read is pointer-validated; a bad descriptor simply records nothing.
/// </summary>
internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc)
{
if (objectId == 0 || weenieDesc == IntPtr.Zero)
return;
try
{
// PublicWeenieDesc derives from PackObj, so a real descriptor starts with an
// acclient.exe vtable; reject anything else before reading fields.
if (!LooksLikeAcHeapObject(weenieDesc))
return;
bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name);
uint typeFlags = 0;
IntPtr typeAddr = weenieDesc + PwdTypeOffset;
bool gotType = IsReadablePointer(typeAddr);
if (gotType)
typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr));
if (!gotName && (!gotType || typeFlags == 0))
return;
lock (_createSeedLock)
{
// Safety valve for a missed delete: drop everything rather than grow forever.
// The live snapshot covers anything still in the world.
if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap)
{
_createSeedNames.Clear();
_createSeedTypes.Clear();
}
if (gotName)
_createSeedNames[objectId] = name;
if (gotType && typeFlags != 0)
_createSeedTypes[objectId] = typeFlags;
}
int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount);
// First few samples let a log reader confirm the descriptor offsets resolve
// to sensible names/types on this client build.
if (seedNo <= 5)
RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}");
if (!_loggedCreateSeedServe && seedNo >= 50)
{
_loggedCreateSeedServe = true;
int names, types;
lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; }
RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject.");
}
}
catch
{
// Descriptor read failures are non-fatal; the periodic snapshot still runs.
}
}
/// <summary>Drops create-time seeds for a deleted object (called from the delete hook).</summary>
internal static void ForgetCreateSeed(uint objectId)
{
lock (_createSeedLock)
{
_createSeedNames.Remove(objectId);
_createSeedTypes.Remove(objectId);
}
}
private static bool TryGetCreateSeedName(uint objectId, out string name)
{
lock (_createSeedLock)
{
if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0)
{
name = seeded;
return true;
}
}
name = string.Empty;
return false;
}
private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags)
{
lock (_createSeedLock)
return _createSeedTypes.TryGetValue(objectId, out typeFlags);
}
public static bool TryGetObjectName(uint objectId, out string name)
{
name = string.Empty;
@ -3356,6 +3455,10 @@ internal static class ClientObjectHooks
return true;
}
}
// Snapshot miss (login burst / object newer than the last walk): serve the
// name captured from the create descriptor.
if (TryGetCreateSeedName(objectId, out name))
return true;
name = string.Empty;
return false;
}
@ -3809,6 +3912,21 @@ internal static class ClientObjectHooks
&& PwdLayout.TryGetInt(e.Bytes, stype, out value);
}
/// <summary>
/// Off-thread read of one 4-byte PWD field by raw offset (the <see cref="TryReadPwdInt32"/>
/// contract) from the main-thread snapshot. False for objects the last walk didn't see.
/// </summary>
private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value)
{
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size)
return false;
if (!TryGetPwdSnapshot(objectId, out PwdEntry e))
return false;
value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(pwdFieldOffset));
return true;
}
private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value)
{
value = 0;
@ -3830,6 +3948,16 @@ internal static class ClientObjectHooks
&& PwdLayout.TryGetInstanceId(e.Bytes, stype, out value);
}
/// <summary>The PWD snapshot has been filled at least once (AutoId: an object missing from it may still come).</summary>
internal static bool HasPwdSnapshot
{
get { lock (_weeniePtrSwapLock) return _pwdFront.Count > 0; }
}
/// <summary>The object holds items (ItemsCapacity, stype 6, &gt; 0 in the PWD snapshot: a pack, a chest).</summary>
internal static bool IsContainerInSnapshot(uint objectId) =>
TryGetPwdSnapshotInt(objectId, 6, out int capacity) && capacity > 0;
/// <summary>
/// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD
/// container or wielder is <paramref name="containerId"/> from the main-thread

View file

@ -332,7 +332,7 @@ internal static class CombatActionHooks
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
if (_meleeAttack == null)
@ -350,7 +350,7 @@ internal static class CombatActionHooks
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
if (_missileAttack == null)
@ -373,7 +373,7 @@ internal static class CombatActionHooks
// (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())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
@ -412,7 +412,7 @@ internal static class CombatActionHooks
// same gate. Queued in the action ring so it keeps FIFO order after an attack
// that is already queued (it used to run at once and could overtake it). The
// drain re-enters here on the main thread, where the gate passes.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueCancelAttack();
try
@ -435,7 +435,7 @@ internal static class CombatActionHooks
// so off-thread calls go to the non-gesture QueryHealth queue and the drain
// re-enters here on the main thread. Callers ignore the result and read the
// async 0x01C0 reply, so "queued" is enough.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
try
@ -461,15 +461,27 @@ internal static class CombatActionHooks
// here on the main thread, where this gate passes and the packet is sent.
// Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps
// the bool's meaning ("requested").
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueRequestId(objectId);
// The caller's EngineSendMarker (Net/IdRequester.cs) says who asked: it rides with a
// queued request, and a send made under it is registered with the flight recorder so
// the 0xC8 shows as [eng:<who>]. Without a marker the send stays [cli].
Net.IdRequester who = Net.EngineSendMarker.Current;
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueRequestId(objectId, who);
// Registered BEFORE the call, so the tag is in place whether AC puts the 0xC8 on the
// wire inside the call or later. A call that fails or throws retires its entry, so it
// cannot mis-tag a later 0xC8 for the same object.
int tag = who != Net.IdRequester.None ? Net.FlightRecorder.EngineSend((byte)who, objectId) : -1;
try
{
return _requestId(objectId);
bool sent = _requestId(objectId);
if (sent) Net.IdSendStats.CountSent(who);
else Net.FlightRecorder.EngineSendFailed(tag, objectId);
return sent;
}
catch
{
Net.FlightRecorder.EngineSendFailed(tag, objectId);
return false;
}
}
@ -504,24 +516,23 @@ internal static class CombatActionHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: false))
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.
// From here on we are ON AC's main thread: the Client::UseTime cast drain
// (AcMainThreadQueue.DrainCasts, before AC's tick) or another main-thread caller.
// Nothing below runs on the plugin pump. What was REVERTED earlier is the
// EndScene drain for casts: EndScene is not the context that drives the cast state
// machine to completion (busy leaked, AC's single cast slot jammed client-wide);
// EngineFrameController's EndScene drain still never runs casts.
// Two native paths, each through the SEH trampoline (__try/__except in
// RynthCore.SehTrampoline.dll), which contains the object-teardown AV
// (0x0055FA24 [null+0x40] / 0x00416C86 [null+0x28]) per call:
// targeted (targetId != 0): GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spell,
// target), the target passed explicitly, NO SelectItem;
// self (targetId == 0): ClientMagicSystem::CastSpell(spell, targetIsSelected=0).
// While the player is dead, portaling or settling after a landblock jump the drain
// holds the cast and drops it once the transition ends (WorldTransitionState).
if (_castSpellClient != null)
{
try

View file

@ -163,7 +163,7 @@ internal static class CommandInterpreterHooks
// 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())
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
if (!TryBindDelegates())
@ -269,7 +269,7 @@ internal static class CommandInterpreterHooks
public static bool SetMotion(uint motion, bool enabled)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _setMotion == null)
return false;
@ -287,7 +287,7 @@ internal static class CommandInterpreterHooks
public static bool StopCompletely()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _stopCompletely == null)
return false;
@ -305,7 +305,7 @@ internal static class CommandInterpreterHooks
public static bool TurnToHeading(float headingDegrees)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
if (!TryBindDelegates() || _turnToHeading == null)
@ -398,7 +398,7 @@ internal static class CommandInterpreterHooks
public static bool TapJump()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTapJump();
if (!TryBindDelegates())
return false;
@ -419,7 +419,7 @@ internal static class CommandInterpreterHooks
public static bool CommenceJump()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueCommenceJump();
if (!TryBindDelegates())
return false;
@ -437,7 +437,7 @@ internal static class CommandInterpreterHooks
public static bool DoJump(bool autonomous)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
if (!TryBindDelegates())
return false;

View file

@ -0,0 +1,24 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CrashExitRule.cs
//
// Is a process exit code a CRASH exit? ProcessExitHooks passes a crash exit straight to
// the original (no managed work on a dying process) after flushing the native crash
// logger's recent first-chance records.
//
// A crash exit is an error-severity status or exception code (both top bits set,
// 0xC0000000 and up): 0xC0000005 an access violation, 0xC0000409 a stack buffer overrun,
// 0xC0000374 heap corruption, and the software exception codes a runtime exits with on an
// unhandled exception, 0xE0434352 (CLR) and 0xE06D7363 (C++).
// EXCEPT 0xFFFFFFFF: ExitProcess(-1) is an ordinary "exit with failure", not a fault. The
// old rule (code >= 0xC0000000) took it for a crash and skipped the orderly shutdown
// of the process.
//
// Pure. Compiled into tools\EngineRobustnessTests.
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal static class CrashExitRule
{
public static bool IsCrashExit(uint code) => (code & 0xC0000000u) == 0xC0000000u && code != 0xFFFFFFFFu;
}

View file

@ -81,6 +81,9 @@ internal static class CreateObjectHooks
if (count <= 0)
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
// Capture name/type from the create descriptor BEFORE the plugin is told about the
// object, so its off-thread classifier can read them on the very first attempt.
ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc);
PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId);
return result;

View file

@ -426,7 +426,7 @@ internal static unsafe class DecalBridgeHost
case BridgeRecordKind.ReleaseObject:
PaletteCache.Remove(arg0);
PluginManager.QueueDeleteObject(arg0);
AutoIdService.Evict(arg0);
AutoIdService.OnClientRelease(arg0);
break;
case BridgeRecordKind.ChangeObject:

View file

@ -21,6 +21,7 @@ internal static class DeleteObjectHooks
private static DeleteObjectDelegate? _originalDeleteObject;
private static DeleteObjectDelegate? _deleteObjectDetour;
private static IntPtr _targetAddress;
private static IntPtr _objectMaint; // ACCObjectMaint* seen on AC's own deletes (RemoveClientObject)
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
@ -68,13 +69,91 @@ internal static class DeleteObjectHooks
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
{
RecursionGuard.Tick("DeleteObjectHooks.DeleteObject");
if (thisPtr != IntPtr.Zero) _objectMaint = thisPtr;
if (objectId != 0)
{
ObjectFreshness.Forget(objectId);
PaletteCache.Remove(objectId);
ClientObjectHooks.ForgetCreateSeed(objectId);
PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId);
AutoIdService.OnClientRelease(objectId);
}
return _originalDeleteObject!(thisPtr, objectId);
}
// ── v83 RemoveClientObject: drop a "ghost" from the client (2026-10-12) ──────────────
// A ghost is an object the client still draws but the server no longer has for this player
// (Drakkon in 0x6146: four Olthoi he stood and swung at for 25 minutes; every attack was
// answered by an immediate AttackDone, they never moved and never died). Nothing ever deletes
// them: only the server's DeleteObject would, and it doesn't know the client still has them.
// This runs the same client function every server DeleteObject ends in -
// ACCObjectMaint::DeleteObject(this, id), the one this hook watches - so the client forgets
// the object the way it forgets a corpse that decays. If the object is real after all, the
// server's next CreateObject for it (when it comes back into view) brings it back.
// Refused: no ACCObjectMaint seen yet (no delete since the hook went in), the player, anything
// that isn't a creature, players, and any object the server sent a message about in the last
// RemoveMinQuietMs (it is real).
/// <summary>An object the server talked about this recently is never removed.</summary>
public const long RemoveMinQuietMs = 5000;
public enum RemoveResult { Removed = 1, Refused = 0, Unavailable = -1, Queued = 2 }
/// <summary>True once AC's own DeleteObject has run (the ACCObjectMaint pointer is known).</summary>
public static bool CanRemove => IsInstalled && _objectMaint != IntPtr.Zero;
/// <summary>Why <paramref name="objectId"/> may not be removed, or null when it may.</summary>
public static string? RemoveRefusal(uint objectId, long nowMs)
{
if (objectId == 0) return "no object";
uint player = ClientHelperHooks.CachedPlayerId;
if (player == 0 || objectId == player) return "the player";
if (!ClientObjectHooks.TryGetSnapshotItemType(objectId, out uint type)) return "not in the client's object table";
if ((type & 0x10) == 0) return "not a creature";
if (ClientObjectHooks.TryGetSnapshotPwdInfo(objectId, out uint bf, out _, out _) && (bf & 0x8) != 0) return "a player";
long age = ObjectFreshness.AgeMs(objectId, nowMs);
if (age >= 0 && age < RemoveMinQuietMs) return $"the server sent a message about it {age} ms ago";
return null;
}
/// <summary>Remove <paramref name="objectId"/> from the client (see above). Off AC's main thread
/// it is queued and checked again when it runs.</summary>
public static RemoveResult RemoveClientObject(uint objectId, out string? refusal)
{
refusal = null;
if (!CanRemove) { refusal = "the client's DeleteObject isn't bound yet"; return RemoveResult.Unavailable; }
refusal = RemoveRefusal(objectId, Environment.TickCount64);
if (refusal != null) return RemoveResult.Refused;
// PR #8's gate: also queued on the main thread while a death/portal transition holds work
// (the queue refuses it then, so the caller sees Refused and asks again later).
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueRemoveClientObject(objectId) ? RemoveResult.Queued : RemoveResult.Refused;
return RemoveNow(objectId) ? RemoveResult.Removed : RemoveResult.Refused;
}
/// <summary>AC's main thread: the checks again, then ACCObjectMaint::DeleteObject.</summary>
internal static bool RemoveNow(uint objectId)
{
if (!CanRemove || !MainThreadGuard.IsOnMainThread()) return false;
string? why = RemoveRefusal(objectId, Environment.TickCount64);
if (why != null)
{
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8}: not removed - {why}.");
return false;
}
try
{
// Through the detour's original: the hook's own bookkeeping (plugins' OnDeleteObject,
// caches) runs as for a server delete.
DeleteObjectDetour(_objectMaint, objectId);
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8}: removed from the client (ghost).");
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8} failed - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
}

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DragDropHooks.cs
// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC
// is actually dragging. AC does not change the selected object when a drag
// starts, so the selection is the previously clicked item, not the dragged one.
//
// The dragged UI element is resolved to an object id with AC's own
// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop
// lands), then handed to ItemDragBridge, which republishes it to ImGui.
//
// Threads: AC's main thread (AC's input / UI processing).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class DragDropHooks
{
// bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY)
private const int StartDragandDropVa = 0x0045E120;
// void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags)
private const int InqDropIconInfoVa = 0x004E3380;
// Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue;
// InqDropIconInfo zeroes its out-params up front).
private static readonly byte?[] StartDragandDropPattern =
[
0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, 0x0F, 0x84,
null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0
];
private static readonly byte?[] InqDropIconInfoPattern =
[
0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, 0x8B, 0x74, 0x24, 0x4C,
0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, 0x89, 0x1F
];
private static IntPtr _originalStartDrag;
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void> _inqDropIconInfo;
private static int _logCount;
/// <summary>The drag-start hook is live, so ItemDragBridge gets the real dragged item.</summary>
public static bool IsInstalled { get; private set; }
public static string StatusMessage { get; private set; } = "Not probed yet.";
public static void Initialize()
{
if (IsInstalled) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
StatusMessage = "acclient.exe not available.";
return;
}
var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa);
var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa);
// A guessed address for either would mean calling or patching the wrong code: pattern hits only.
if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan)
{
StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail}).";
RynthLog.Compat($"Compat: {StatusMessage}");
return;
}
try
{
_inqDropIconInfo = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)inq.Address;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> detour = &StartDragandDropDetour;
MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag);
IsInstalled = true;
StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}.";
RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}");
}
catch (Exception ex)
{
StatusMessage = ex.Message;
RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY)
{
try
{
if (element != IntPtr.Zero && _inqDropIconInfo != null)
{
uint itemId = 0, spellId = 0, flags = 0;
_inqDropIconInfo(element, &itemId, &spellId, &flags);
// Spell-bar drags carry a spell id and no item.
if (itemId != 0)
{
if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); }
ItemDragBridge.OnNativeDragStart(itemId);
}
}
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_originalStartDrag;
return original(manager, element, clickX, clickY);
}
}

View file

@ -104,6 +104,15 @@ internal static class EngineStatusMetrics
w.WriteNumber("queueDropped", queueDropped);
w.WriteNumber("reconciles", reconciles);
w.WriteNumber("forceClears", forceClears);
// AC's main thread frozen (message box or stale beat) and plugin ticks paused for it
// (MainThreadFreeze). pluginTicksPausedMs is a running total: a plugin's stall
// detector subtracts its change over the window it measured.
bool frozen = false; long stallMs = 0, pausedMs = 0;
try { frozen = MainThreadFreeze.Paused; stallMs = MainThreadFreeze.MainThreadStallMs; pausedMs = MainThreadFreeze.PausedTotalMs; }
catch { }
w.WriteBoolean("mainThreadFrozen", frozen);
w.WriteNumber("mainThreadStallMs", stallMs);
w.WriteNumber("pluginTicksPausedMs", pausedMs);
// 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.

View file

@ -49,10 +49,21 @@ internal static class GameTickHooks
private static ThisCallBoolDelegate? _originalUseTime;
private static ThisCallBoolDelegate? _useTimeDetour;
private static IntPtr _originalUseTimePtr;
private static IntPtr _targetAddress;
private static int _installed;
private static int _exitLatch;
// Native SEH guard around AC's tick (SehTrampoline v4+). A native AV that unwinds into
// this managed detour is fatal under CoreCLR; caught natively, it drops one tick instead.
// More than MaxTickFaults within TickFaultWindowMs means AC's state is broken rather than
// one bad message, so the guard turns itself off and the next fault ends the client.
private const int MaxTickFaults = 5;
private const long TickFaultWindowMs = 30_000;
private static bool _tickGuard;
private static int _tickFaults;
private static long _tickFaultWindowStart;
// 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 ];
@ -87,12 +98,14 @@ internal static class GameTickHooks
_targetAddress = resolved.Address;
_useTimeDetour = UseTimeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
_originalUseTimePtr = MinHook.HookCreate(_targetAddress, detourPtr);
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(_originalUseTimePtr);
_tickGuard = SehTrampoline.IsAvailable && SehTrampoline.NativeVersion >= 4;
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.");
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick; " +
(_tickGuard ? "native AV guard on." : $"native AV guard OFF (SehTrampoline v{SehTrampoline.NativeVersion}, needs v4)."));
}
catch (Exception ex)
{
@ -111,15 +124,6 @@ internal static class GameTickHooks
// 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,
@ -130,14 +134,36 @@ internal static class GameTickHooks
try { portaling = TeleportStateHooks.IsPortaling; }
catch { }
// Death / portal space / teleport lines, for lining crashes up with what
// the character was doing (PlayerLifecycleLog).
// the character was doing (PlayerLifecycleLog). Also the world-transition state the
// AcMainThreadQueue drains gate on: sampled BEFORE the cast drain below, so a cast queued
// as the player dies is held in this same tick, not run into the death.
try { PlayerLifecycleLog.SampleOnGameThread(portaling); }
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 { }
// Run AC's own game-logic + physics + animation pass.
int result;
try { result = _originalUseTime!(thisPtr); }
catch { result = 0; }
if (_tickGuard)
{
result = SehTrampoline.GameTickThiscall(_originalUseTimePtr, thisPtr, out bool avCaught,
out uint exAddr, out uint dataAddr, out string module);
// 0 would end AC's game loop; a dropped tick must keep it running.
if (avCaught)
result = OnTickFault(exAddr, dataAddr, module);
}
else
{
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
@ -185,6 +211,18 @@ internal static class GameTickHooks
// 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.)
// Re-sample the world-transition state first: a death, a portal entry or a
// landblock jump can begin INSIDE AC's tick above, and the pre-tick sample would
// let this drain run queued work into it. Edges are logged once whichever sample
// sees them.
try
{
bool portalingAfter = false;
try { portalingAfter = TeleportStateHooks.IsPortaling; }
catch { }
PlayerLifecycleLog.SampleOnGameThread(portalingAfter);
}
catch { }
try { AcMainThreadQueue.Drain(); }
catch { }
// Main-thread snapshots the pump reads instead of AC memory (player id,
@ -214,4 +252,34 @@ internal static class GameTickHooks
// MUST return Client::UseTime's own bool — AC loops do/while on it.
return result;
}
/// <summary>
/// Logs a native AV caught inside Client::UseTime and returns the value the detour hands
/// back to AC's loop (always 1: keep running). Turns the guard off once faults exceed
/// the budget, so a client with corrupted state still dies instead of spinning.
/// </summary>
private static int OnTickFault(uint exAddr, uint dataAddr, string module)
{
long now = Environment.TickCount64;
if (_tickFaults == 0 || now - _tickFaultWindowStart > TickFaultWindowMs)
{
_tickFaultWindowStart = now;
_tickFaults = 0;
}
_tickFaults++;
string where = module.Length > 0 ? $"{module}+0x{exAddr:X}" : $"0x{exAddr:X8}";
try
{
RynthLog.Error($"GameTickHooks: access violation inside Client::UseTime at {where} (data 0x{dataAddr:X8}); " +
$"tick dropped, client kept running (fault {_tickFaults}/{MaxTickFaults} in {TickFaultWindowMs / 1000}s). Full record in native-crash.log.");
if (_tickFaults >= MaxTickFaults)
{
_tickGuard = false;
RynthLog.Error("GameTickHooks: Client::UseTime fault budget exhausted; native AV guard OFF for this session.");
}
}
catch { }
return 1;
}
}

View file

@ -135,6 +135,11 @@ internal static class HeartbeatLogger
// flooding the ring; flat = fine.
long dropped = 0;
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
// qrej = marshalled actions and casts refused during a world transition
// (dead / portal / settle window), a running total kept apart from qdrop: a
// jump in qrej around a teleport is the gate working, not a flood.
long rejected = 0;
try { rejected = AcMainThreadQueue.TransitionRejectedCount; } 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;
@ -155,8 +160,28 @@ internal static class HeartbeatLogger
catch { }
// vafree = free address space (MB): reloads leak engine/plugin copies,
// so a client that dies mid-reload can be checked for running out.
// valargest = the largest free block (MB): a 32-bit client fails an
// allocation on fragmentation long before vafree reaches 0.
string vaField = "";
try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; }
try
{
long free = AddressSpaceMb().FreeMb;
if (free >= 0) vaField = $" vafree={free}MB";
long largest = AddressSpace.FreeAndLargestMb().LargestFreeMb;
if (largest >= 0) vaField += $" valargest={largest}MB";
}
catch { }
// Crash logger module cache (native): rebuilt every 10 s here, so a fault
// never has to call the loader to name a module.
if (tick % 10 == 1)
{
try { SehTrampoline.RefreshCrashLoggerModules(); } catch { }
}
// Safety net for the main-thread message box count (MainThreadFreeze).
MessageBoxHooks.ReconcileStaleMainThreadCount();
// pump=paused = plugin ticks paused because AC's main thread is frozen
// (MainThreadFreeze); omitted while running.
try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; }
catch { }
// req=<type>/<age>s = the client is waiting on an item request (it refuses
// every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both
@ -168,7 +193,8 @@ internal static class HeartbeatLogger
string vpField = "";
try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); }
catch { }
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
// Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat).
RynthLog.Heartbeat($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} qrej={rejected} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
// Every 60 s: garbage collections and the time they paused the process.
// Under the CoreCLR host the engine and managed plugins share one GC, so a
@ -176,6 +202,13 @@ internal static class HeartbeatLogger
if (tick % 60 == 0)
LogGcStats();
// Every 60 s: IdentifyObject (0xC8) sends by who asked, and AutoId's skips
// (AutoIdService.TakeMinuteLine). Its own line, never part of "hb #".
if (tick % 60 == 0)
{
try { RynthLog.Info(AutoIdService.TakeMinuteLine()); } catch { }
}
// Every 5 s: hide and destroy any panel window no live panel owns
// (the "double UI" orphans).
if (tick % 5 == 0)

View file

@ -0,0 +1,527 @@
// ============================================================================
// RynthCore.Engine - Compatibility/InventoryAttributeFilter.cs
// The Inventory panel's attribute filter: rules on an item's attributes
// ("Armor Level >= 300", "Spells contain Legendary", "Fits slot Neck"),
// matched all or any. Pure: no AC reads. The panel supplies each item's
// values through IInventoryFilterFacts (InventoryFilterFacts.cs), so the host
// tests link this file alone.
//
// Two kinds of attribute:
// public what every item sends (value, burden, material, slots...)
// appraised what only an identify returns (armor level, ratings, spells...).
// An item never identified can't be judged on these: Unknown,
// which the panel hides and counts ("N not identified").
// An appraised attribute the item doesn't have counts as 0 / no / "" (a
// weapon's armor level is 0), so "Level to wield <= 150" keeps items with no
// requirement.
//
// Threads: the panel's (render) thread only; the rules are edited and read
// there. Saved as one line in inventory_settings.txt (Serialize / Parse).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Engine.Compatibility;
/// <summary>How a rule compares the attribute.</summary>
internal enum FilterAttrKind : byte { Number, Flag, Text, Choice }
/// <summary>Where the value comes from and how it is turned into what the rule shows.</summary>
internal enum FilterSource : byte
{
/// <summary>From the item's public description (the panel's InventoryItem).</summary>
Public,
/// <summary>An appraised int property (0 when absent).</summary>
Int,
/// <summary>An appraised float property, shown as is.</summary>
Float,
/// <summary>An appraised float multiplier shown as a bonus percent: 1.15 -> 15.</summary>
FloatModPercent,
/// <summary>An appraised float fraction shown as a percent: 0.05 -> 5.</summary>
FloatPercent,
/// <summary>An appraised int that counts as "yes" when not 0.</summary>
IntNonZero,
/// <summary>An appraised bool property.</summary>
Bool,
/// <summary>Worked out by the facts provider (level to wield, set name, spells).</summary>
Special,
}
/// <summary>Every attribute a rule can test. The persisted key is <see cref="FilterAttrInfo.Key"/>, not the number.</summary>
internal enum FilterAttr : byte
{
// Public
Name, Value, Burden, Workmanship, Stack, Material, Slot, Equipped, CastsSpell,
// Appraised
ArmorLevel, MaxDamage, Speed, AttackBonus, MeleeDefense, MissileDefense, MagicDefense,
ElementalDamage, ManaConversion, DamageRating, DamageResistRating, CritRating, CritResistRating,
CritDamageRating, CritDamageResistRating, HealingBoostRating, VitalityRating, WieldLevel,
ArcaneLore, Spellcraft, MaxMana, Tinkers, MaxItemLevel, SetName, Spells, Imbued, Bonded,
Attuned, Retained,
}
/// <summary>One attribute's description: its key, label, kind and where its value lives.</summary>
internal sealed class FilterAttrInfo
{
public FilterAttr Id;
public string Key = string.Empty;
public string Label = string.Empty;
public FilterAttrKind Kind;
public FilterSource Source;
/// <summary>The appraisal property id (STypeInt / STypeFloat / STypeBool); 0 for public and special.</summary>
public uint Stype;
public string Tip = string.Empty;
/// <summary>Needs an identify (any source but Public).</summary>
public bool NeedsId => Source != FilterSource.Public;
}
/// <summary>How a rule tests its attribute. The persisted key is in <see cref="InventoryAttributeFilter.OpKey"/>.</summary>
internal enum FilterOp : byte { AtLeast, AtMost, Equal, NotEqual, Yes, No, Contains, NotContains, Is, IsNot }
/// <summary>What one rule (or the whole filter) says about an item.</summary>
internal enum FilterVerdict : byte { Match, NoMatch, Unknown }
/// <summary>One item's values as a rule sees them. Absent values are 0 / false / "".</summary>
internal interface IInventoryFilterFacts
{
/// <summary>The server's identify answer is cached for this item.</summary>
bool Identified { get; }
double Number(FilterAttrInfo attr);
bool Flag(FilterAttrInfo attr);
string Text(FilterAttrInfo attr);
/// <summary>The item's ValidLocations (EquipMask) bits, for the Slot choice.</summary>
uint SlotMask { get; }
}
/// <summary>One rule. Mutable: the panel's editor changes it in place and bumps the filter's version.</summary>
internal sealed class InventoryFilterRule
{
public FilterAttr Attr;
public FilterOp Op;
public double Number;
public string Text = string.Empty;
/// <summary>The choice's index (Slot: into <see cref="InventoryAttributeFilter.SlotNames"/>).</summary>
public int Choice;
public InventoryFilterRule Clone() => new() { Attr = Attr, Op = Op, Number = Number, Text = Text, Choice = Choice };
}
/// <summary>The rule list, its match mode and on/off; evaluation, description and persistence.</summary>
internal sealed class InventoryAttributeFilter
{
public const int MaxRules = 12;
/// <summary>Off keeps the rules but shows every item.</summary>
public bool Enabled;
/// <summary>True: any rule matching keeps the item. False: every rule must.</summary>
public bool MatchAny;
public readonly List<InventoryFilterRule> Rules = new();
/// <summary>Bumped on every edit, so the panel knows to rebuild its list.</summary>
public int Version { get; private set; }
/// <summary>On, with at least one rule.</summary>
public bool Active => Enabled && Rules.Count > 0;
/// <summary>Some rule needs an identify (so unknown items can exist and appraisals change matches).</summary>
public bool NeedsIdentify
{
get
{
foreach (InventoryFilterRule r in Rules)
if (Info(r.Attr).NeedsId) return true;
return false;
}
}
public void Touch() => Version++;
// ── Attributes ──────────────────────────────────────────────────────
public static readonly FilterAttrInfo[] Attributes = BuildAttributes();
private static FilterAttrInfo[] BuildAttributes()
{
var list = new FilterAttrInfo[(int)FilterAttr.Retained + 1];
void Add(FilterAttr id, string key, string label, FilterAttrKind kind, FilterSource src, uint stype, string tip) =>
list[(int)id] = new FilterAttrInfo { Id = id, Key = key, Label = label, Kind = kind, Source = src, Stype = stype, Tip = tip };
Add(FilterAttr.Name, "name", "Name", FilterAttrKind.Text, FilterSource.Public, 0, "The item's name.");
Add(FilterAttr.Value, "value", "Value", FilterAttrKind.Number, FilterSource.Public, 0, "Pyreal value.");
Add(FilterAttr.Burden, "burden", "Burden", FilterAttrKind.Number, FilterSource.Public, 0, "Burden units (a stack's total).");
Add(FilterAttr.Workmanship, "work", "Workmanship", FilterAttrKind.Number, FilterSource.Public, 0, "1 to 10; 0 for items without one.");
Add(FilterAttr.Stack, "stack", "Stack size", FilterAttrKind.Number, FilterSource.Public, 0, "1 for a single item.");
Add(FilterAttr.Material, "material", "Material", FilterAttrKind.Text, FilterSource.Public, 0, "Steel, Silk, Ruby...");
Add(FilterAttr.Slot, "slot", "Fits slot", FilterAttrKind.Choice, FilterSource.Public, 0, "Where the item can be worn or wielded.");
Add(FilterAttr.Equipped, "equipped", "Equipped", FilterAttrKind.Flag, FilterSource.Public, 0, "Worn or wielded now.");
Add(FilterAttr.CastsSpell, "casts", "Casts a spell", FilterAttrKind.Flag, FilterSource.Public, 0, "Has a use spell (scrolls, gems, wands).");
Add(FilterAttr.ArmorLevel, "al", "Armor level", FilterAttrKind.Number, FilterSource.Int, 28, "Base armor level.");
Add(FilterAttr.MaxDamage, "dmg", "Max damage", FilterAttrKind.Number, FilterSource.Int, 44, "A weapon's maximum damage.");
Add(FilterAttr.Speed, "speed", "Speed", FilterAttrKind.Number, FilterSource.Int, 49, "Weapon speed (lower is faster).");
Add(FilterAttr.AttackBonus, "attack", "Attack bonus %", FilterAttrKind.Number, FilterSource.FloatModPercent, 62, "A weapon's attack skill bonus.");
Add(FilterAttr.MeleeDefense, "meleed", "Melee defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 29, "Melee defense bonus.");
Add(FilterAttr.MissileDefense, "missiled", "Missile defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 149, "Missile defense bonus.");
Add(FilterAttr.MagicDefense, "magicd", "Magic defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 150, "Magic defense bonus.");
Add(FilterAttr.ElementalDamage, "elem", "Elemental damage %", FilterAttrKind.Number, FilterSource.FloatModPercent, 152, "A caster's elemental damage bonus.");
Add(FilterAttr.ManaConversion, "manac", "Mana conversion %", FilterAttrKind.Number, FilterSource.FloatPercent, 144, "A caster's mana conversion bonus.");
Add(FilterAttr.DamageRating, "dr", "Damage rating", FilterAttrKind.Number, FilterSource.Int, 370, "Gear damage rating.");
Add(FilterAttr.DamageResistRating, "drr", "Damage resist rating", FilterAttrKind.Number, FilterSource.Int, 371, "Gear damage resistance rating.");
Add(FilterAttr.CritRating, "cr", "Crit rating", FilterAttrKind.Number, FilterSource.Int, 372, "Gear critical rating.");
Add(FilterAttr.CritResistRating, "crr", "Crit resist rating", FilterAttrKind.Number, FilterSource.Int, 373, "Gear critical resistance rating.");
Add(FilterAttr.CritDamageRating, "cdr", "Crit damage rating", FilterAttrKind.Number, FilterSource.Int, 374, "Gear critical damage rating.");
Add(FilterAttr.CritDamageResistRating, "cdrr", "Crit damage resist rating", FilterAttrKind.Number, FilterSource.Int, 375, "Gear critical damage resistance rating.");
Add(FilterAttr.HealingBoostRating, "heal", "Healing boost rating", FilterAttrKind.Number, FilterSource.Int, 376, "Gear healing boost rating.");
Add(FilterAttr.VitalityRating, "vit", "Vitality rating", FilterAttrKind.Number, FilterSource.Int, 379, "Gear max health (vitality) rating.");
Add(FilterAttr.WieldLevel, "wieldlvl", "Level to wield", FilterAttrKind.Number, FilterSource.Special, 0, "Character level needed; 0 when none.");
Add(FilterAttr.ArcaneLore, "lore", "Arcane lore", FilterAttrKind.Number, FilterSource.Int, 109, "Arcane lore needed to use it.");
Add(FilterAttr.Spellcraft, "spellcraft", "Spellcraft", FilterAttrKind.Number, FilterSource.Int, 106, "The item's spellcraft.");
Add(FilterAttr.MaxMana, "mana", "Max mana", FilterAttrKind.Number, FilterSource.Int, 108, "The item's mana pool.");
Add(FilterAttr.Tinkers, "tinks", "Times tinkered", FilterAttrKind.Number, FilterSource.Int, 171, "Tinkers applied so far.");
Add(FilterAttr.MaxItemLevel, "maxlvl", "Max item level", FilterAttrKind.Number, FilterSource.Int, 319, "Aetheria / cloak / leveling items.");
Add(FilterAttr.SetName, "set", "Armor set", FilterAttrKind.Text, FilterSource.Special, 265, "Soldier's, Adept's, Cloak War Magic...");
Add(FilterAttr.Spells, "spells", "Spells", FilterAttrKind.Text, FilterSource.Special, 0, "Any of the item's spells contains the text.");
Add(FilterAttr.Imbued, "imbued", "Imbued", FilterAttrKind.Flag, FilterSource.IntNonZero, 179, "Has an imbue (crushing blow, armor rend...).");
Add(FilterAttr.Bonded, "bonded", "Bonded", FilterAttrKind.Flag, FilterSource.IntNonZero, 33, "Bonded, sticky or destroyed on drop.");
Add(FilterAttr.Attuned, "attuned", "Attuned", FilterAttrKind.Flag, FilterSource.IntNonZero, 114, "Can't be given away.");
Add(FilterAttr.Retained, "retained", "Retained", FilterAttrKind.Flag, FilterSource.Bool, 91, "Won't be sold or salvaged by accident.");
return list;
}
public static FilterAttrInfo Info(FilterAttr a) => Attributes[(int)a];
public static FilterAttrInfo? InfoByKey(string key)
{
foreach (FilterAttrInfo i in Attributes)
if (string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase)) return i;
return null;
}
// ── Operators ───────────────────────────────────────────────────────
private static readonly FilterOp[] NumberOps = { FilterOp.AtLeast, FilterOp.AtMost, FilterOp.Equal, FilterOp.NotEqual };
private static readonly FilterOp[] FlagOps = { FilterOp.Yes, FilterOp.No };
private static readonly FilterOp[] TextOps = { FilterOp.Contains, FilterOp.NotContains };
private static readonly FilterOp[] ChoiceOps = { FilterOp.Is, FilterOp.IsNot };
/// <summary>The operators that make sense for an attribute kind; the first is the default.</summary>
public static FilterOp[] OpsFor(FilterAttrKind kind) => kind switch
{
FilterAttrKind.Number => NumberOps,
FilterAttrKind.Flag => FlagOps,
FilterAttrKind.Text => TextOps,
_ => ChoiceOps,
};
public static string OpLabel(FilterOp op) => op switch
{
FilterOp.AtLeast => ">=",
FilterOp.AtMost => "<=",
FilterOp.Equal => "=",
FilterOp.NotEqual => "!=",
FilterOp.Yes => "yes",
FilterOp.No => "no",
FilterOp.Contains => "contains",
FilterOp.NotContains => "doesn't contain",
FilterOp.Is => "is",
_ => "is not",
};
public static string OpKey(FilterOp op) => op switch
{
FilterOp.AtLeast => "ge",
FilterOp.AtMost => "le",
FilterOp.Equal => "eq",
FilterOp.NotEqual => "ne",
FilterOp.Yes => "yes",
FilterOp.No => "no",
FilterOp.Contains => "has",
FilterOp.NotContains => "nothas",
FilterOp.Is => "is",
_ => "isnot",
};
private static bool TryOpFromKey(string key, out FilterOp op)
{
for (FilterOp o = FilterOp.AtLeast; o <= FilterOp.IsNot; o++)
if (OpKey(o) == key) { op = o; return true; }
op = default;
return false;
}
/// <summary>A new rule on <paramref name="attr"/> with that attribute's default operator.</summary>
public static InventoryFilterRule NewRule(FilterAttr attr) => new() { Attr = attr, Op = OpsFor(Info(attr).Kind)[0] };
/// <summary>Points <paramref name="rule"/> at another attribute, keeping its operator when it still fits.</summary>
public static void SetAttr(InventoryFilterRule rule, FilterAttr attr)
{
rule.Attr = attr;
if (Array.IndexOf(OpsFor(Info(attr).Kind), rule.Op) < 0) rule.Op = OpsFor(Info(attr).Kind)[0];
if (Info(attr).Kind == FilterAttrKind.Choice) rule.Choice = Math.Clamp(rule.Choice, 0, SlotNames.Length - 1);
}
// ── Evaluation ──────────────────────────────────────────────────────
/// <summary>
/// The whole filter on one item. All: any NoMatch wins, then any Unknown. Any: any Match
/// wins, then any Unknown. Off or empty: Match.
/// </summary>
public FilterVerdict Evaluate(IInventoryFilterFacts facts)
{
if (!Active) return FilterVerdict.Match;
bool unknown = false;
foreach (InventoryFilterRule r in Rules)
{
FilterVerdict v = EvaluateRule(r, facts);
if (v == FilterVerdict.Unknown) unknown = true;
else if (MatchAny && v == FilterVerdict.Match) return FilterVerdict.Match;
else if (!MatchAny && v == FilterVerdict.NoMatch) return FilterVerdict.NoMatch;
}
if (unknown) return FilterVerdict.Unknown;
return MatchAny ? FilterVerdict.NoMatch : FilterVerdict.Match;
}
/// <summary>One rule on one item. Unknown when it needs an identify the item doesn't have.</summary>
public static FilterVerdict EvaluateRule(InventoryFilterRule rule, IInventoryFilterFacts facts)
{
FilterAttrInfo info = Info(rule.Attr);
// A text rule with no text tests nothing: it never hides an item.
if (info.Kind == FilterAttrKind.Text && rule.Text.Length == 0) return FilterVerdict.Match;
if (info.NeedsId && !facts.Identified) return FilterVerdict.Unknown;
bool ok = info.Kind switch
{
FilterAttrKind.Number => CompareNumber(facts.Number(info), rule.Op, rule.Number),
FilterAttrKind.Flag => facts.Flag(info) == (rule.Op == FilterOp.Yes),
FilterAttrKind.Text => facts.Text(info).Contains(rule.Text, StringComparison.OrdinalIgnoreCase) == (rule.Op == FilterOp.Contains),
_ => FitsSlot(facts.SlotMask, rule.Choice) == (rule.Op == FilterOp.Is),
};
return ok ? FilterVerdict.Match : FilterVerdict.NoMatch;
}
/// <summary>
/// Number comparison. Equal allows half a hundredth either way: percents come from floats
/// (1.15 -> 14.999...) and are typed to two places at most.
/// </summary>
public static bool CompareNumber(double value, FilterOp op, double target)
{
const double Eps = 1e-6, EqTol = 0.005;
return op switch
{
FilterOp.AtLeast => value >= target - Eps,
FilterOp.AtMost => value <= target + Eps,
FilterOp.Equal => Math.Abs(value - target) < EqTol,
FilterOp.NotEqual => Math.Abs(value - target) >= EqTol,
_ => false,
};
}
/// <summary>A raw appraised float as the rule shows it.</summary>
public static double Scale(FilterSource source, double raw) => source switch
{
FilterSource.FloatModPercent => raw == 0 ? 0 : (raw - 1.0) * 100.0,
FilterSource.FloatPercent => raw * 100.0,
_ => raw,
};
/// <summary>
/// The level needed to wield: WieldRequirements (158) or WieldRequirements2 (270) = 7
/// (Level) gives WieldDifficulty (160) or WieldDifficulty2 (271). 0 when neither is a level.
/// </summary>
public static int WieldLevel(int req1, int diff1, int req2, int diff2) =>
req1 == WieldRequirementLevel ? diff1 : req2 == WieldRequirementLevel ? diff2 : 0;
public const int WieldRequirementLevel = 7;
public const uint StypeWieldRequirements = 158, StypeWieldDifficulty = 160,
StypeWieldRequirements2 = 270, StypeWieldDifficulty2 = 271;
// ── Slots ───────────────────────────────────────────────────────────
public static readonly string[] SlotNames =
{
"Head", "Chest", "Abdomen", "Upper arms", "Lower arms", "Hands", "Upper legs", "Lower legs", "Feet",
"Neck", "Wrist", "Finger", "Melee weapon", "Shield", "Missile weapon", "Ammunition", "Held (wand, orb)",
"Two-handed weapon", "Trinket", "Cloak", "Aetheria",
};
/// <summary>EquipMask bits per <see cref="SlotNames"/> entry (armor and underclothes share a body part).</summary>
public static readonly uint[] SlotMasks =
{
0x00000001, 0x00000002 | 0x00000200, 0x00000004 | 0x00000400, 0x00000008 | 0x00000800,
0x00000010 | 0x00001000, 0x00000020, 0x00000040 | 0x00002000, 0x00000080 | 0x00004000, 0x00000100,
0x00008000, 0x00030000, 0x000C0000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000,
0x02000000, 0x04000000, 0x08000000, 0x70000000,
};
public static bool FitsSlot(uint validLocations, int choice) =>
choice >= 0 && choice < SlotMasks.Length && (validLocations & SlotMasks[choice]) != 0;
// ── Names (material, armor set) ─────────────────────────────────────
// MaterialType 1..77 (ACE.Entity.Enum.MaterialType), in id order.
private const string MaterialIds =
"Ceramic,Porcelain,Cloth,Linen,Satin,Silk,Velvet,Wool,Gem,Agate,Amber,Amethyst,Aquamarine,Azurite,"
+ "BlackGarnet,BlackOpal,Bloodstone,Carnelian,Citrine,Diamond,Emerald,FireOpal,GreenGarnet,GreenJade,"
+ "Hematite,ImperialTopaz,Jet,LapisLazuli,LavenderJade,Malachite,Moonstone,Onyx,Opal,Peridot,RedGarnet,"
+ "RedJade,RoseQuartz,Ruby,Sapphire,SmokeyQuartz,Sunstone,TigerEye,Tourmaline,Turquoise,WhiteJade,"
+ "WhiteQuartz,WhiteSapphire,YellowGarnet,YellowTopaz,Zircon,Ivory,Leather,ArmoredilloHide,GromnieHide,"
+ "ReedSharkHide,Metal,Brass,Bronze,Copper,Gold,Iron,Pyreal,Silver,Steel,Stone,Alabaster,Granite,Marble,"
+ "Obsidian,Sandstone,Serpentine,Wood,Ebony,Mahogany,Oak,Pine,Teak";
// EquipmentSet 0..140 (ACECustom ACE.Entity.Enum.EquipmentSet), in id order.
private const string SetIds =
"Invalid,Test,Test2,Unknown3,CarraidasBenediction,NobleRelic,AncientRelic,AlduressaRelic,Ninja,EmpyreanRings,"
+ "ArmMindHeart,ArmorPerfectLight,ArmorPerfectLight2,Soldiers,Adepts,Archers,Defenders,Tinkers,Crafters,Hearty,"
+ "Dexterous,Wise,Swift,Hardened,Reinforced,Interlocking,Flameproof,Acidproof,Coldproof,Lightningproof,"
+ "SocietyArmor,ColosseumClothing,GraveyardClothing,OlthoiClothing,NoobieArmor,AetheriaDefense,"
+ "AetheriaDestruction,AetheriaFury,AetheriaGrowth,AetheriaVigor,RareDamageResistance,RareDamageBoost,"
+ "OlthoiArmorDRed,OlthoiArmorCRat,OlthoiArmorCRed,OlthoiArmorDRat,AlduressaRelicUpgrade,AncientRelicUpgrade,"
+ "NobleRelicUpgrade,CloakAlchemy,CloakArcaneLore,CloakArmorTinkering,CloakAssessPerson,CloakLightWeapons,"
+ "CloakMissileWeapons,CloakCooking,CloakCreatureEnchantment,CloakCrossbow,CloakFinesseWeapons,CloakDeception,"
+ "CloakFletching,CloakHealing,CloakItemEnchantment,CloakItemTinkering,CloakLeadership,CloakLifeMagic,"
+ "CloakLoyalty,CloakMace,CloakMagicDefense,CloakMagicItemTinkering,CloakManaConversion,CloakMeleeDefense,"
+ "CloakMissileDefense,CloakSalvaging,CloakSpear,CloakStaff,CloakHeavyWeapons,CloakThrownWeapon,"
+ "CloakTwoHandedCombat,CloakUnarmedCombat,CloakVoidMagic,CloakWarMagic,CloakWeaponTinkering,"
+ "CloakAssessCreature,CloakDirtyFighting,CloakDualWield,CloakRecklessness,CloakShield,CloakSneakAttack,"
+ "Ninja_New,CloakSummoning,ShroudedSoul,DarkenedMind,CloudedSpirit,MinorStingingShroudedSoul,"
+ "MinorSparkingShroudedSoul,MinorSmolderingShroudedSoul,MinorShiveringShroudedSoul,MinorStingingDarkenedMind,"
+ "MinorSparkingDarkenedMind,MinorSmolderingDarkenedMind,MinorShiveringDarkenedMind,MinorStingingCloudedSpirit,"
+ "MinorSparkingCloudedSpirit,MinorSmolderingCloudedSpirit,MinorShiveringCloudedSpirit,"
+ "MajorStingingShroudedSoul,MajorSparkingShroudedSoul,MajorSmolderingShroudedSoul,MajorShiveringShroudedSoul,"
+ "MajorStingingDarkenedMind,MajorSparkingDarkenedMind,MajorSmolderingDarkenedMind,MajorShiveringDarkenedMind,"
+ "MajorStingingCloudedSpirit,MajorSparkingCloudedSpirit,MajorSmolderingCloudedSpirit,"
+ "MajorShiveringCloudedSpirit,BlackfireStingingShroudedSoul,BlackfireSparkingShroudedSoul,"
+ "BlackfireSmolderingShroudedSoul,BlackfireShiveringShroudedSoul,BlackfireStingingDarkenedMind,"
+ "BlackfireSparkingDarkenedMind,BlackfireSmolderingDarkenedMind,BlackfireShiveringDarkenedMind,"
+ "BlackfireStingingCloudedSpirit,BlackfireSparkingCloudedSpirit,BlackfireSmolderingCloudedSpirit,"
+ "BlackfireShiveringCloudedSpirit,ShimmeringShadowsSet,BrownSocietyLocket,YellowSocietyLocket,"
+ "RedSocietyBand,GreenSocietyBand,PurpleSocietyBand,BlueSocietyBand,GauntletGarb,ParagonMissile,"
+ "ParagonCaster,ParagonMelee";
private static readonly string[] Materials = SplitNames(MaterialIds);
private static readonly string[] Sets = SplitNames(SetIds);
/// <summary>"Black Garnet" for MaterialType 15; "" for 0 and ids past the list.</summary>
public static string MaterialName(int materialType) =>
materialType >= 1 && materialType <= Materials.Length ? Materials[materialType - 1] : string.Empty;
/// <summary>"Cloak War Magic" for EquipmentSet 81; "Set 200" for an id past the list; "" for none.</summary>
public static string SetName(int setId) =>
setId <= 0 ? string.Empty
: setId < Sets.Length ? Sets[setId]
: "Set " + setId.ToString(CultureInfo.InvariantCulture);
private static string[] SplitNames(string ids)
{
string[] parts = ids.Split(',');
for (int i = 0; i < parts.Length; i++) parts[i] = Words(parts[i]);
return parts;
}
/// <summary>"CloakWarMagic" -> "Cloak War Magic"; underscores become spaces.</summary>
public static string Words(string id)
{
var sb = new StringBuilder(id.Length + 6);
for (int i = 0; i < id.Length; i++)
{
char c = id[i];
if (c == '_') { sb.Append(' '); continue; }
// A capital starts a word after a lower-case letter or digit, or ends a run of
// capitals when a lower-case letter follows ("ArmorDRed" -> "Armor D Red").
if (i > 0 && char.IsUpper(c))
{
char prev = id[i - 1];
bool nextLower = i + 1 < id.Length && char.IsLower(id[i + 1]);
if (char.IsLower(prev) || char.IsDigit(prev) || (char.IsUpper(prev) && nextLower)) sb.Append(' ');
}
sb.Append(c);
}
return sb.ToString();
}
// ── Description ─────────────────────────────────────────────────────
/// <summary>"Armor level >= 300", "Spells contains Legendary", "Fits slot is Neck".</summary>
public static string Describe(InventoryFilterRule rule)
{
FilterAttrInfo info = Info(rule.Attr);
string what = info.Kind switch
{
FilterAttrKind.Number => " " + rule.Number.ToString("0.##", CultureInfo.InvariantCulture),
FilterAttrKind.Text => " \"" + rule.Text + "\"",
FilterAttrKind.Choice => " " + (rule.Choice >= 0 && rule.Choice < SlotNames.Length ? SlotNames[rule.Choice] : "?"),
_ => string.Empty,
};
return info.Label + " " + OpLabel(rule.Op) + what;
}
/// <summary>The rules joined with " and " / " or ", for the panel's tooltip.</summary>
public string Summary()
{
if (Rules.Count == 0) return "No rules.";
var sb = new StringBuilder();
for (int i = 0; i < Rules.Count; i++)
{
if (i > 0) sb.Append(MatchAny ? " or " : " and ");
sb.Append(Describe(Rules[i]));
}
return sb.ToString();
}
// ── Persistence ─────────────────────────────────────────────────────
/// <summary>
/// One line: "v1;on|off;all|any;" then rules split by ';', each "key,op,number,choice,text"
/// (text URL-escaped so ',' and ';' can't break it).
/// </summary>
public string Serialize()
{
var sb = new StringBuilder("v1;");
sb.Append(Enabled ? "on" : "off").Append(';').Append(MatchAny ? "any" : "all");
foreach (InventoryFilterRule r in Rules)
{
sb.Append(';').Append(Info(r.Attr).Key).Append(',').Append(OpKey(r.Op)).Append(',')
.Append(r.Number.ToString("R", CultureInfo.InvariantCulture)).Append(',')
.Append(r.Choice.ToString(CultureInfo.InvariantCulture)).Append(',')
.Append(Uri.EscapeDataString(r.Text));
}
return sb.ToString();
}
/// <summary>
/// Reads <see cref="Serialize"/>'s line. Unknown attributes and broken rules are skipped,
/// so an older engine's or a hand-edited line still loads what it can.
/// </summary>
public static InventoryAttributeFilter Parse(string? line)
{
var f = new InventoryAttributeFilter();
if (string.IsNullOrWhiteSpace(line)) return f;
string[] parts = line.Trim().Split(';');
if (parts.Length < 3 || parts[0] != "v1") return f;
f.Enabled = parts[1] == "on";
f.MatchAny = parts[2] == "any";
for (int i = 3; i < parts.Length && f.Rules.Count < MaxRules; i++)
{
string[] r = parts[i].Split(',');
if (r.Length < 5) continue;
FilterAttrInfo? info = InfoByKey(r[0]);
if (info == null || !TryOpFromKey(r[1], out FilterOp op)) continue;
if (Array.IndexOf(OpsFor(info.Kind), op) < 0) continue;
if (!double.TryParse(r[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double num) || !double.IsFinite(num)) num = 0;
if (!int.TryParse(r[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int choice)) choice = 0;
string text;
try { text = Uri.UnescapeDataString(r[4]); }
catch (UriFormatException) { text = string.Empty; }
f.Rules.Add(new InventoryFilterRule
{
Attr = info.Id,
Op = op,
Number = num,
Choice = info.Kind == FilterAttrKind.Choice ? Math.Clamp(choice, 0, SlotNames.Length - 1) : choice,
Text = text,
});
}
return f;
}
}

View file

@ -0,0 +1,112 @@
// ============================================================================
// RynthCore.Engine - Compatibility/InventoryFilterFacts.cs
// One item's values for the Inventory panel's attribute filter
// (InventoryAttributeFilter): public ones from the panel's InventoryItem,
// appraised ones from AppraisalHooks' cache (filled by an identify).
//
// Threads: the panel's (render) thread. AppraisalHooks' getters lock their
// cache and PortalSpellTable's lookups read an immutable table, so neither
// touches AC. One instance is re-bound per item (no allocation per item
// except a spells string, built only when a rule asks for it).
// ============================================================================
using System;
using System.Text;
using RynthCore.Engine.ImGuiBackend.Hud;
namespace RynthCore.Engine.Compatibility;
internal sealed class InventoryFilterFacts : IInventoryFilterFacts
{
private InventoryItem _item = null!;
private bool _identified;
private string? _spells;
private readonly uint[] _spellBuf = new uint[64];
private readonly StringBuilder _sb = new(256);
/// <summary>Points the facts at <paramref name="item"/>; cheap.</summary>
public void Bind(InventoryItem item)
{
_item = item;
_identified = AppraisalHooks.HasAppraisalData(item.Id);
_spells = null;
}
public bool Identified => _identified;
public uint SlotMask => _item.ValidLocations;
public double Number(FilterAttrInfo attr)
{
uint id = _item.Id;
switch (attr.Source)
{
case FilterSource.Public:
return attr.Id switch
{
FilterAttr.Value => _item.Value,
FilterAttr.Burden => _item.Burden,
FilterAttr.Workmanship => _item.Workmanship,
FilterAttr.Stack => Math.Max(1, _item.Stack),
_ => 0,
};
case FilterSource.Int:
return AppraisalHooks.TryGetCachedIntProperty(id, attr.Stype, out int i) ? i : 0;
case FilterSource.Float:
case FilterSource.FloatModPercent:
case FilterSource.FloatPercent:
return AppraisalHooks.TryGetCachedDoubleProperty(id, attr.Stype, out double d)
? InventoryAttributeFilter.Scale(attr.Source, d) : 0;
case FilterSource.Special when attr.Id == FilterAttr.WieldLevel:
return InventoryAttributeFilter.WieldLevel(
IntOr0(id, InventoryAttributeFilter.StypeWieldRequirements),
IntOr0(id, InventoryAttributeFilter.StypeWieldDifficulty),
IntOr0(id, InventoryAttributeFilter.StypeWieldRequirements2),
IntOr0(id, InventoryAttributeFilter.StypeWieldDifficulty2));
default:
return 0;
}
}
public bool Flag(FilterAttrInfo attr) => attr.Source switch
{
FilterSource.Public => attr.Id switch
{
FilterAttr.Equipped => _item.Wielder != 0,
FilterAttr.CastsSpell => _item.SpellId != 0,
_ => false,
},
FilterSource.IntNonZero => IntOr0(_item.Id, attr.Stype) != 0,
FilterSource.Bool => AppraisalHooks.TryGetCachedBoolProperty(_item.Id, attr.Stype, out bool b) && b,
_ => false,
};
public string Text(FilterAttrInfo attr) => attr.Id switch
{
FilterAttr.Name => _item.Name,
FilterAttr.Material => InventoryAttributeFilter.MaterialName(_item.MaterialType),
FilterAttr.SetName => InventoryAttributeFilter.SetName(IntOr0(_item.Id, attr.Stype)),
FilterAttr.Spells => _spells ??= SpellNames(),
_ => string.Empty,
};
private static int IntOr0(uint id, uint stype) =>
AppraisalHooks.TryGetCachedIntProperty(id, stype, out int v) ? v : 0;
/// <summary>The appraised spells' names, newline-separated (a rule's text can't span two).</summary>
private string SpellNames()
{
int n = AppraisalHooks.GetObjectSpellIds(_item.Id, _spellBuf, _spellBuf.Length);
if (n <= 0) return string.Empty;
if (!PortalSpellTable.Ready) PortalSpellTable.EnsureLoadQueued();
_sb.Clear();
int shown = Math.Min(n, _spellBuf.Length);
for (int k = 0; k < shown; k++)
{
// Spell ids in an appraisal can carry the layer in the high word.
uint sid = _spellBuf[k] & 0xFFFF;
if (k > 0) _sb.Append('\n');
_sb.Append(PortalSpellTable.TryGetName(sid, out string name) ? name : "spell " + sid);
}
return _sb.ToString();
}
}

View file

@ -0,0 +1,259 @@
// ============================================================================
// RynthCore.Engine - Compatibility/InventoryModel.Batch.cs
// Several items in one go (the Inventory panel's multi-selection): Drop,
// Give to the selected creature, or Move into a pack.
//
// Still one item action at a time (AC refuses a second while one waits): the
// batch hands the next item to the normal request path only after the one
// before it has ended (done, refused, gone or timed out), with a short gap,
// so each item is checked and watched exactly like a single click.
//
// Threads: RequestBatch / CancelBatch / Batch / BatchRunning any thread;
// everything else on AC's main thread (BatchTick, from MainThreadTick). The
// batch keeps running with the panel closed and ends by itself.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>A running or finished batch, for the status row. Immutable.</summary>
internal sealed class InventoryBatchStatus
{
public InventoryActionKind Kind;
public int Total, Done, Failed;
public string TargetName = string.Empty;
public bool Running;
/// <summary>Stop was pressed: it ends after the item in flight.</summary>
public bool Stopping;
/// <summary>"Giving 3 of 12 to Bob" while running, else the summary.</summary>
public string Text = string.Empty;
}
internal static partial class InventoryModel
{
// Between items: lets the server's answer to one settle before the next is sent.
private static readonly long BatchGapTicks = Freq / 4;
/// <summary>The most items one batch takes (a full main pack and its side packs).</summary>
public const int MaxBatch = 400;
// ── Published / inputs (any thread) ─────────────────────────────────
private static InventoryBatchStatus? _batchStatus;
private static InventoryRequest[]? _batchRequested;
private static int _batchActive, _batchCancel;
public static InventoryBatchStatus? Batch => Volatile.Read(ref _batchStatus);
public static bool BatchRunning => Volatile.Read(ref _batchActive) != 0;
/// <summary>
/// Starts acting on <paramref name="items"/> one after another (all of one kind; Drop, Give
/// or Move). Refused while another action or batch is waiting. Any thread.
/// </summary>
public static bool RequestBatch(IReadOnlyList<InventoryRequest> items, out string why)
{
if (items.Count == 0) { why = "Nothing to do."; return false; }
if (items.Count > MaxBatch) { why = $"At most {MaxBatch} items at once."; return false; }
InventoryActionKind kind = items[0].Kind;
if (kind is not (InventoryActionKind.Drop or InventoryActionKind.Give or InventoryActionKind.Move))
{
why = "Only Drop, Give and Move work on several items.";
return false;
}
for (int i = 1; i < items.Count; i++)
{
if (items[i].Kind != kind) { why = "A batch is one kind of action."; return false; }
}
InventoryPending? busy = Pending;
if (busy != null)
{
why = (busy.WaitingForGame ? "Still waiting for the game: " : "Still waiting for the server: ") + busy.Label;
return false;
}
if (Volatile.Read(ref _requested) != null) { why = "Another item action is about to be sent."; return false; }
if (Interlocked.CompareExchange(ref _batchActive, 1, 0) != 0) { why = "Several items are already being sent."; return false; }
var copy = new InventoryRequest[items.Count];
for (int i = 0; i < copy.Length; i++) copy[i] = items[i];
Volatile.Write(ref _batchCancel, 0);
Volatile.Write(ref _batchRequested, copy);
why = string.Empty;
return true;
}
/// <summary>Stop: no more items are sent; the one in flight still ends normally. Any thread.</summary>
public static void CancelBatch()
{
if (!BatchRunning) return;
Volatile.Write(ref _batchCancel, 1);
InventoryBatchStatus? s = Batch;
if (s is { Running: true, Stopping: false })
Volatile.Write(ref _batchStatus, new InventoryBatchStatus
{
Kind = s.Kind, Total = s.Total, Done = s.Done, Failed = s.Failed, TargetName = s.TargetName,
Running = true, Stopping = true, Text = s.Text + " (stopping)",
});
}
// ── Main thread ─────────────────────────────────────────────────────
private static readonly Queue<InventoryRequest> _batchQueue = new();
private static InventoryActionKind _batchKind;
private static int _batchTotal, _batchDone, _batchFailed;
private static string _batchTarget = string.Empty, _batchFirstError = string.Empty;
// The item handed to the request path, until it has ended.
private static InventoryRequest? _batchWaiting;
private static InventoryResult? _batchResultBefore;
private static long _batchNextAt;
/// <summary>Starts a requested batch, counts the item that ended, sends the next one. Main thread.</summary>
private static void BatchTick(long now)
{
InventoryRequest[]? incoming = Interlocked.Exchange(ref _batchRequested, null);
if (incoming != null) StartBatch(incoming, now);
// RequestBatch sets the flag a moment before it hands over the items: they come next tick.
if (_batchTotal == 0) return;
// The item handed over last tick: wait until it has ended, then count it.
if (_batchWaiting != null)
{
if (Busy()) return;
InventoryResult? r = LastResult;
bool ended = r != null && !ReferenceEquals(r, _batchResultBefore);
if (ended && r!.Ok) _batchDone++;
else
{
_batchFailed++;
if (_batchFirstError.Length == 0) _batchFirstError = ended ? r!.Text : "no answer";
}
_batchWaiting = null;
_batchNextAt = now + BatchGapTicks;
PublishBatch(running: true);
}
if (Volatile.Read(ref _batchCancel) != 0) { EndBatch(now, "stopped"); return; }
if (_batchQueue.Count == 0) { EndBatch(now, string.Empty); return; }
if (now < _batchNextAt || Busy()) return;
uint player = ClientHelperHooks.GetPlayerId();
if (player == 0) { FailRest("not in the world"); EndBatch(now, string.Empty); return; }
InventoryRequest next = _batchQueue.Peek();
if (next.Kind == InventoryActionKind.Give
&& (next.TargetId == 0 || next.TargetId == player || !ClientObjectHooks.TryGetItemType(next.TargetId, out _)))
{
FailRest(next.TargetName + " is gone");
EndBatch(now, string.Empty);
return;
}
_batchQueue.Dequeue();
_batchResultBefore = LastResult;
if (Interlocked.CompareExchange(ref _requested, next, null) != null)
{
// Something else got in first (shouldn't happen: Request refuses during a batch).
_batchFailed++;
if (_batchFirstError.Length == 0) _batchFirstError = "another action was in the way";
_batchNextAt = now + BatchGapTicks;
PublishBatch(running: true);
return;
}
_batchWaiting = next;
PublishBatch(running: true);
}
/// <summary>An item action requested, held or in flight (ours or not). Main thread.</summary>
private static bool Busy() => _inFlight != null || _held != null || Volatile.Read(ref _requested) != null;
private static void StartBatch(InventoryRequest[] items, long now)
{
_batchQueue.Clear();
foreach (InventoryRequest r in items) _batchQueue.Enqueue(r);
_batchKind = items[0].Kind;
_batchTotal = items.Length;
_batchDone = _batchFailed = 0;
_batchTarget = items[0].TargetName;
_batchFirstError = string.Empty;
_batchWaiting = null;
_batchResultBefore = null;
_batchNextAt = now;
PublishBatch(running: true);
RynthLog.Compat($"InventoryModel: batch {_batchKind} of {_batchTotal} item(s){(_batchTarget.Length > 0 ? " to " + _batchTarget : "")}.");
}
private static void FailRest(string why)
{
_batchFailed += _batchQueue.Count;
_batchQueue.Clear();
if (_batchFirstError.Length == 0) _batchFirstError = why;
}
/// <summary>Ends the batch: the summary goes to the status row (LastResult) and the log. Main thread.</summary>
private static void EndBatch(long now, string how)
{
bool started = _batchTotal > 0;
int skipped = _batchQueue.Count;
_batchQueue.Clear();
_batchWaiting = null;
if (started)
{
InventoryBatchStatus s = PublishBatch(running: false, how, skipped);
Finish(s.Text, _batchFailed == 0 && skipped == 0, now);
RynthLog.Compat("InventoryModel: " + s.Text);
}
_batchTotal = 0;
Volatile.Write(ref _batchCancel, 0);
Volatile.Write(ref _batchActive, 0);
}
private static InventoryBatchStatus PublishBatch(bool running, string how = "", int skipped = 0)
{
var s = new InventoryBatchStatus
{
Kind = _batchKind, Total = _batchTotal, Done = _batchDone, Failed = _batchFailed,
TargetName = _batchTarget, Running = running,
Stopping = running && Volatile.Read(ref _batchCancel) != 0,
};
s.Text = running
? BatchProgressText(_batchKind, Math.Min(_batchTotal, _batchDone + _batchFailed + 1), _batchTotal, _batchTarget)
+ (s.Stopping ? " (stopping)" : string.Empty)
: BatchSummaryText(_batchKind, _batchDone, _batchFailed, skipped, _batchTotal, _batchTarget, how, _batchFirstError);
Volatile.Write(ref _batchStatus, s);
return s;
}
/// <summary>"Giving 3 of 12 to Bob", "Dropping 3 of 12", "Moving 3 of 12 to Pack".</summary>
internal static string BatchProgressText(InventoryActionKind kind, int n, int total, string target) => kind switch
{
InventoryActionKind.Give => $"Giving {n} of {total} to {target}",
InventoryActionKind.Move => $"Moving {n} of {total} to {target}",
_ => $"Dropping {n} of {total}",
};
/// <summary>"Gave 10 of 12 items to Bob; 2 failed (first: ...)", "Dropped 12 items.", "Stopped: moved 3 of 12...".</summary>
internal static string BatchSummaryText(InventoryActionKind kind, int done, int failed, int skipped, int total,
string target, string how, string firstError)
{
string verb = kind switch
{
InventoryActionKind.Give => "gave",
InventoryActionKind.Move => "moved",
_ => "dropped",
};
string where = kind switch
{
InventoryActionKind.Give => " to " + target,
InventoryActionKind.Move => " to " + target,
_ => string.Empty,
};
string count = done == total ? $"{total} item{(total == 1 ? "" : "s")}" : $"{done} of {total} items";
string text = how.Length > 0
? $"{char.ToUpperInvariant(how[0])}{how[1..]}: {verb} {count}{where}"
: $"{char.ToUpperInvariant(verb[0])}{verb[1..]} {count}{where}";
if (failed > 0) text += $"; {failed} failed";
if (skipped > 0) text += $"; {skipped} not sent";
if (failed > 0 && firstError.Length > 0) text += $" (first: {firstError.TrimEnd('.')})";
return text + ".";
}
}

View file

@ -17,6 +17,9 @@
// One item action at a time: AC keeps one pending inventory request and refuses
// a second ("You can only move or use one item at a time"; ClientActionGates).
// Request() refuses while an action is waiting; nothing is ever queued behind it.
// Several items (the panel's multi-selection) go through RequestBatch
// (InventoryModel.Batch.cs), which feeds them to this same path one at a time,
// each only after the one before it has ended.
//
// The client's own gate (ClientActionGates, read on the main thread here):
// Before the send while AC's pending-request slot holds anyone's request (the
@ -212,7 +215,7 @@ internal sealed class InventoryResult
public long AtTicks;
}
internal static class InventoryModel
internal static partial class InventoryModel
{
// ── Cadence ─────────────────────────────────────────────────────────
private static readonly long Freq = Stopwatch.Frequency;
@ -295,6 +298,11 @@ internal static class InventoryModel
/// </summary>
public static bool Request(InventoryRequest request, out string why)
{
if (BatchRunning)
{
why = "Several items are being sent; wait, or press Stop.";
return false;
}
InventoryPending? busy = Pending;
if (busy != null)
{
@ -357,7 +365,8 @@ internal static class InventoryModel
public static void MainThreadTick()
{
bool open = Volatile.Read(ref _subscribers) > 0;
if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null)
if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null
&& Volatile.Read(ref _batchActive) == 0)
return;
if (!MainThreadGuard.IsOnMainThread())
return;
@ -375,6 +384,8 @@ internal static class InventoryModel
_lastWatch = now;
Watch(now);
}
// After the watch, so an item that just ended is counted before the next is sent.
if (Volatile.Read(ref _batchActive) != 0) BatchTick(now);
if (!open) return;
bool dirty = Volatile.Read(ref _dirty) != 0;
@ -392,6 +403,7 @@ internal static class InventoryModel
SampleTarget();
}
HoverTick(now);
IdentifyQueueTick(now);
}
catch (Exception ex)
{
@ -420,6 +432,7 @@ internal static class InventoryModel
{
_items.Clear(); // another character: nothing carries over
_identified.Clear();
ClearIdentifyQueue();
_lastPlayer = player;
_lastSignature = 0;
_playerName = string.Empty;
@ -1118,7 +1131,8 @@ internal static class InventoryModel
_identified[id] = now;
_lastIdentify = now;
sentRecently = true;
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
using (Net.EngineSendMarker.Enter(Net.IdRequester.Ui))
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
tip = null; // rebuild below with "identifying"
}
@ -1127,6 +1141,70 @@ internal static class InventoryModel
Volatile.Write(ref _tooltip, BuildTooltip(id, appraised, !appraised && sentRecently));
}
// ── Identify queue (the attribute filter's "Identify N") ────────────
private static readonly long QueuedIdentifyGapTicks = Freq / 4; // 4 a second
private const int MaxQueuedIdentifies = 1024;
private static readonly object IdQueueSync = new();
private static readonly Queue<uint> _idQueue = new(); // guarded by IdQueueSync
private static readonly HashSet<uint> _idQueued = new(); // guarded by IdQueueSync
private static long _lastQueuedIdentify;
/// <summary>Items still waiting in the identify queue. Any thread.</summary>
public static int IdentifyQueueCount
{
get { lock (IdQueueSync) return _idQueue.Count; }
}
/// <summary>
/// Asks the server to identify <paramref name="ids"/>, a few a second on AC's main thread
/// while the panel is open. Items already appraised, sent in the last minute, already
/// queued or no longer carried are skipped. Any thread.
/// </summary>
public static void QueueIdentify(IReadOnlyList<uint> ids)
{
lock (IdQueueSync)
{
foreach (uint id in ids)
{
if (id == 0 || _idQueue.Count >= MaxQueuedIdentifies) continue;
if (_idQueued.Add(id)) _idQueue.Enqueue(id);
}
}
}
/// <summary>Drops every queued identify. Any thread.</summary>
public static void ClearIdentifyQueue()
{
lock (IdQueueSync)
{
_idQueue.Clear();
_idQueued.Clear();
}
}
/// <summary>Main thread: sends the next queued identify that still needs sending.</summary>
private static void IdentifyQueueTick(long now)
{
if (now - _lastQueuedIdentify < QueuedIdentifyGapTicks) return;
while (true)
{
uint id;
lock (IdQueueSync)
{
if (!_idQueue.TryDequeue(out id)) return;
_idQueued.Remove(id);
}
if (AppraisalHooks.HasAppraisalData(id) || !_items.ContainsKey(id)) continue;
if (_identified.TryGetValue(id, out long sentAt) && now - sentAt < IdentifyRepeatTicks) continue;
if (_identified.Count > 2048) _identified.Clear();
_identified[id] = now;
_lastQueuedIdentify = now;
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
return;
}
}
private static InventoryTooltip BuildTooltip(uint id, bool appraised, bool identifying)
{
var lines = new List<string>(8);

View file

@ -30,6 +30,11 @@ internal static class LoginLifecycleHooks
public static bool IsInstalled { get; private set; }
public static bool HasObservedLoginComplete { get; private set; }
/// <summary>When login completed (TickCount64), or 0 before it / after a logout. A hot reload
/// marks it at the reload. AutoId defers its background appraisals 30 s past it.</summary>
public static long LoginCompleteAtMs => System.Threading.Interlocked.Read(ref _loginCompleteAtMs);
private static long _loginCompleteAtMs;
public static string StatusMessage => _statusMessage;
public static event Action? LoginComplete;
@ -100,6 +105,7 @@ internal static class LoginLifecycleHooks
public static void ResetObservation()
{
HasObservedLoginComplete = false;
System.Threading.Interlocked.Exchange(ref _loginCompleteAtMs, 0);
// Queued engine work (appraisals, health queries, chat, actions) from this login is stale
// for the next one (2026-10-06, AcMainThreadQueue).
try { AcMainThreadQueue.NewLoginEpoch(); } catch { }
@ -137,6 +143,7 @@ internal static class LoginLifecycleHooks
return;
HasObservedLoginComplete = true;
System.Threading.Interlocked.Exchange(ref _loginCompleteAtMs, Environment.TickCount64);
_statusMessage = $"Login complete observed via {source}.";
RynthLog.Verbose($"Compat: login complete observed via {source}.");
LoginComplete?.Invoke();

View file

@ -343,7 +343,18 @@ internal static unsafe class LogoffOriginProbe
bool inWorld = false;
try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { }
if (!inWorld)
{
// Before LoginComplete too (2026-10-13): a relaunched client that never had any
// input carries an idle time of years (last input 0), and AC logged Drakkon off
// 0.7 s after he entered the world, before LoginComplete arrived, so the
// in-world refresh below never ran. Keep the clock fresh at char-select as well.
if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput() && !_preWorldRefreshLogged)
{
_preWorldRefreshLogged = true;
RynthLog.Info($"LogoffProbe: reset the client's idle clock before entering the world ({idle:0}s idle) so the idle auto-logoff can't fire on arrival (PreventIdleLogoff; logged once).");
}
return;
}
if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60)
{
@ -387,6 +398,7 @@ internal static unsafe class LogoffOriginProbe
}
private const double IdleRefreshAfterSec = 120;
private static bool _preWorldRefreshLogged;
private static long _lastIdleRefreshLogMs = -600_000;
/// <summary>Sets the input manager's last-input time to Timer::cur_time, as real input

View file

@ -105,17 +105,27 @@ internal static class MainThreadSnapshots
try { EnchantmentHooks.PrefetchWatchedObjectEnchantments(); } catch { }
// Inventory panel: sends the one requested item action, watches it, and
// captures the packs (throttled; returns at once while the panel is closed
// and nothing is in flight). Only while the player object is live.
try { InventoryModel.MainThreadTick(); } catch { }
// and nothing is in flight). Only while the player object is live, and held
// through a world transition (dead / portal / landblock jump): it SENDS item
// actions, and those wait like the AcMainThreadQueue's (WorldTransitionState).
if (!PlayerLifecycleLog.InWorldTransition)
{
try { InventoryModel.MainThreadTick(); } catch { }
}
// Skills panel: ranks, XP spent and buffs (500 ms, only while the panel is open).
// After the enchantment snapshot so its buffs are this tick's.
try { PlayerProgressHooks.Prefetch(); } catch { }
}
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
try { VaultFeed.MainThreadTick(playerLive); } catch { }
// Both send server commands (a mastery raise, a vault withdraw), so like the
// Inventory panel they wait out a world transition; their requests stay pending.
if (!PlayerLifecycleLog.InWorldTransition)
{
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
try { VaultFeed.MainThreadTick(playerLive); } catch { }
}
}
}

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per
/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of
/// only "queued". Before this, a merge the engine skipped (target already full) or that AC
/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair
/// and logged a "confirmed failure". Thread-safe; bounded.
/// </summary>
internal static class MergeStackResults
{
// ABI status codes (GetMergeStackResult return value). Never renumber.
public const int None = 0; // no request recorded for this pair (or it aged out)
public const int Queued = 1; // accepted onto the main-thread queue, not executed yet
public const int Sent = 2; // Event_StackableMerge sent for 'amount' units
public const int TargetFull = 3; // skipped: target stack already at max stack size
public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw
public const int QueueFull = 5; // main-thread queue full; request dropped before execution
private struct Entry { public int Status; public int Amount; public long TickMs; }
private const int MaxEntries = 512; // prune threshold
private const long PruneAgeMs = 120_000; // results older than this are dropped on prune
private static readonly object _lock = new();
private static readonly Dictionary<ulong, Entry> _results = new();
private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target;
/// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary>
public static void Record(uint source, uint target, int status, int amount = 0)
{
long now = Environment.TickCount64;
lock (_lock)
{
if (_results.Count >= MaxEntries)
Prune(now);
_results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now };
}
}
/// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/>
/// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary>
public static int Get(uint source, uint target, out int amount, out int ageMs)
{
amount = 0;
ageMs = 0;
lock (_lock)
{
if (!_results.TryGetValue(Key(source, target), out Entry e))
return None;
amount = e.Amount;
long age = Environment.TickCount64 - e.TickMs;
ageMs = age > int.MaxValue ? int.MaxValue : (int)age;
return e.Status;
}
}
// Drops aged results; if everything is recent, clears the map (callers re-request anyway).
private static void Prune(long now)
{
List<ulong>? old = null;
foreach (var kv in _results)
if (now - kv.Value.TickMs > PruneAgeMs)
(old ??= new List<ulong>()).Add(kv.Key);
if (old == null)
{
_results.Clear();
return;
}
foreach (ulong k in old)
_results.Remove(k);
}
}

View file

@ -12,15 +12,22 @@
// Now the text is in the log, and the watchdog names the open dialog in its
// hang report (see Describe).
//
// The detour only observes: it always calls the original and returns its
// result. Installed per engine generation; EngineLifecycle's
// MH_DisableHook(ALL) removes it on reload.
// The detour only observes, with one exception (2026-10-12): AC's "Failed to
// establish connection to the server" box (a relaunch that logged in too soon
// after a crash, or the server down). AC's game loop waits on it, so the
// Close on server disconnect check never ran and the client sat there for
// 10 minutes. With that setting on, the box is answered OK without being
// shown (AC then exits, as when the button is clicked), and if the client is
// still open 20 s later the window is sent WM_CLOSE (again at 40 s).
// Installed per engine generation; EngineLifecycle's MH_DisableHook(ALL)
// removes it on reload.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
@ -52,6 +59,13 @@ internal static class MessageBoxHooks
private static volatile string? _openDescription;
private static long _openedAtTicks;
private static int _openCount;
// Boxes open on AC's MAIN thread: the main thread is inside a modal loop, so the plugin
// pump's freeze gate (MainThreadFreeze) pauses plugin ticks at once.
private static int _mainThreadOpenCount;
/// <summary>Message boxes open right now on AC's main thread. Any thread.</summary>
public static int MainThreadOpenCount => Volatile.Read(ref _mainThreadOpenCount);
public static void Initialize()
{
@ -114,34 +128,94 @@ internal static class MessageBoxHooks
{
MessageBoxDelegate? original = wide ? _originalW : _originalA;
string? description = null;
bool counted = false;
long opened = Environment.TickCount64;
int result = 0;
try
{
description = Opened(text, caption, type, wide);
}
catch { /* observation only: never block the dialog */ }
int result = original != null ? original(hWnd, text, caption, type) : 0;
try
{
long secs = (Environment.TickCount64 - opened) / 1000;
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
if (Interlocked.Decrement(ref _openCount) <= 0)
try
{
Interlocked.Exchange(ref _openCount, 0);
_openDescription = null;
// Counted first: the freeze gate must see the box even if the rest throws.
bool mainThread = MainThreadGuard.IsOnMainThread();
if (mainThread)
{
Interlocked.Increment(ref _mainThreadOpenCount);
counted = true;
}
string body = Read(text, wide);
// AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never
// writes a dump, and the launcher later kills the client as wedged. Decide and
// write ONE full-memory dump now, before anything here allocates more (the stack
// walk and the description below), and before the box shows (this thread waits:
// the box would hold it anyway, and the user's OK must not let AC run on and
// exit mid-dump).
if (OutOfMemoryBoxRule.IsOutOfMemoryBox(body, mainThread))
CrashDump.WriteOutOfMemoryDumpOnce(Flatten(body));
description = Opened(body, caption, type, wide, mainThread);
}
catch { /* observation only: never block the dialog */ }
// The one box answered without showing it (Close on server disconnect, 2026-10-12).
result = AnswerConnectionFailure(text, wide)
? IDOK
: original != null ? original(hWnd, text, caption, type) : 0;
}
finally
{
// First, and whatever happened above: a leaked count would pause plugin ticks for good.
if (counted && Interlocked.Decrement(ref _mainThreadOpenCount) < 0)
Interlocked.Exchange(ref _mainThreadOpenCount, 0);
try
{
long secs = (Environment.TickCount64 - opened) / 1000;
if (Interlocked.Decrement(ref _openCount) <= 0)
{
Interlocked.Exchange(ref _openCount, 0);
_openDescription = null;
}
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
}
catch { }
}
catch { }
return result;
}
private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide)
private const int IDOK = 1;
private static int _connectionFailureAnswered;
/// <summary>
/// True for AC's connection-failure box while Close on server disconnect is on: answered
/// OK unseen, with a WM_CLOSE fallback if AC doesn't exit by itself. Never throws.
/// </summary>
private static bool AnswerConnectionFailure(IntPtr text, bool wide)
{
try
{
if (!EngineSettings.CloseOnServerDisconnect) return false;
if (!Read(text, wide).StartsWith("Failed to establish connection to the server", StringComparison.OrdinalIgnoreCase))
return false;
RynthLog.Warn("MessageBoxHooks: the connection failed - answering AC's box (OK) unseen so the client exits " +
"and a launcher can relaunch it (Close on server disconnect, Settings > Misc).");
if (Interlocked.Exchange(ref _connectionFailureAnswered, 1) == 0)
{
var fallback = new Thread(() =>
{
for (int i = 1; i <= 2; i++)
{
Thread.Sleep(20_000);
ServerDisconnectClose.CloseClientNow($"the client is still open {i * 20}s after the connection-failure box");
}
}) { IsBackground = true, Name = "RynthCore connection-failure close" };
fallback.Start();
}
return true;
}
catch { return false; }
}
private static string Opened(string body, IntPtr caption, uint type, bool wide, bool mainThread)
{
string body = Read(text, wide);
string title = Read(caption, wide);
bool mainThread = MainThreadGuard.IsOnMainThread();
// The first frame outside user32 and this file: who asked for the dialog.
string caller = "?";
@ -165,6 +239,63 @@ internal static class MessageBoxHooks
return description;
}
// -- Stale main-thread count (safety net) ------------------------------------
// The count is decremented in Show's finally, so it should never leak; if it ever reads
// non-zero while AC's main thread owns no dialog window for 30 s, it is reset (and
// logged), so a leak can never pause plugin ticks for good. Heartbeat thread, 1 Hz.
private const long StaleCountResetMs = 30_000;
private static long _countWithoutBoxSinceMs;
private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool EnumThreadWindows(uint threadId, EnumThreadWndProc callback, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder name, int max);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
private static bool MainThreadOwnsDialog()
{
uint tid = MainThreadGuard.MainThreadId;
if (tid == 0) return false;
bool found = false;
var name = new System.Text.StringBuilder(64);
EnumThreadWindows(tid, (h, _) =>
{
name.Clear();
if (GetClassNameW(h, name, name.Capacity) > 0 && name.ToString() == "#32770" && IsWindowVisible(h))
{
found = true;
return false;
}
return true;
}, IntPtr.Zero);
return found;
}
/// <summary>Heartbeat thread, about once a second. Never throws.</summary>
public static void ReconcileStaleMainThreadCount()
{
try
{
long now = Environment.TickCount64;
// The OOM dump runs before the box window exists: counted, no dialog yet, legitimately.
if (MainThreadOpenCount <= 0 || CrashDump.FullDumpInProgress || MainThreadOwnsDialog())
{
_countWithoutBoxSinceMs = 0;
return;
}
if (_countWithoutBoxSinceMs == 0) { _countWithoutBoxSinceMs = now; return; }
if (now - _countWithoutBoxSinceMs < StaleCountResetMs) return;
int was = Interlocked.Exchange(ref _mainThreadOpenCount, 0);
_countWithoutBoxSinceMs = 0;
RynthLog.Warn($"MessageBoxHooks: main-thread box count was {was} with no dialog open on AC's main thread for {StaleCountResetMs / 1000}s - reset to 0.");
}
catch { }
}
private static string Read(IntPtr p, bool wide)
{
if (p == IntPtr.Zero) return "";

View file

@ -151,7 +151,7 @@ internal static class MovementActionHooks
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
@ -179,7 +179,7 @@ internal static class MovementActionHooks
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
@ -207,7 +207,7 @@ internal static class MovementActionHooks
public static bool JumpNonAutonomous(float extent)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueJump(extent);
if (_jumpNonAutonomous == null)
@ -231,7 +231,7 @@ internal static class MovementActionHooks
if (_autonomyLevel == null)
return false;
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSetAutonomyLevel(level);
try

View file

@ -0,0 +1,28 @@
// ============================================================================
// RynthCore.Engine - Compatibility/MutatorGate.cs
//
// The decision behind AcMainThreadQueue.MustQueue, the one line every AC-mutating helper
// opens with: call AC now, or queue the call?
// - off AC's main thread: queue (AC is single-threaded);
// - on it, called BY a queue drain: call now (the drain already applied the gate);
// - on it, a stop or cancel (teardown): call now, even in a world transition;
// - on it otherwise: queue while a world transition holds the drains (render-thread host
// actions used to run straight into a world AC was tearing down), else call now.
// holding is asked last and only when it matters (it is main-thread state).
//
// Pure. Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class MutatorGate
{
public static bool MustQueue(bool onMainThread, bool teardown, bool draining, Func<bool> holding)
{
if (!onMainThread) return true;
if (draining || teardown) return false;
return holding();
}
}

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ObjectFreshness.cs
// When the server last sent anything about each object (2026-10-12, "ghost"
// monsters: objects the client still draws but the server no longer has for
// this player - no swing at them ever animates, they never move or die).
//
// Fed by SmartBoxHooks.DispatchSmartBoxEventDetour with every object-addressed
// message (create, position, motion, vector, state, parent, pickup, effects,
// object description, update object); a delete forgets the id. Read by the
// plugin API's RemoveClientObject (v83) as a safety check: an object the server
// talked about in the last few seconds is real and is never removed.
// AC's main thread writes; any thread reads (lock). Bounded: a full table is
// cleared wholesale (advisory data).
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
internal static class ObjectFreshness
{
private static readonly object Sync = new();
private static readonly Dictionary<uint, long> LastMessage = new(1024);
private const int MaxEntries = 16384;
/// <summary>True for server messages whose u32 after the opcode is the object they are about.</summary>
public static bool IsObjectMessage(uint opcode) => opcode switch
{
0xF745 => true, // CreateObject
0xF748 => true, // UpdatePosition
0xF749 => true, // ParentEvent
0xF74A => true, // PickupEvent
0xF74B => true, // SetState
0xF74C => true, // UpdateMotion
0xF74E => true, // VectorUpdate
0xF754 => true, // PlayScriptId
0xF755 => true, // PlayEffect
0xF625 => true, // ObjDescEvent
0xF7DB => true, // UpdateObject
_ => false,
};
/// <summary>A server message <paramref name="opcode"/> about <paramref name="objectId"/> arrived at <paramref name="nowMs"/>.</summary>
public static void Note(uint opcode, uint objectId, long nowMs)
{
if (objectId == 0) return;
if (opcode == 0xF747) { Forget(objectId); return; } // DeleteObject
if (!IsObjectMessage(opcode)) return;
lock (Sync)
{
if (LastMessage.Count >= MaxEntries && !LastMessage.ContainsKey(objectId)) LastMessage.Clear();
LastMessage[objectId] = nowMs;
}
}
public static void Forget(uint objectId)
{
lock (Sync) LastMessage.Remove(objectId);
}
/// <summary>Milliseconds since the server last sent a message about <paramref name="objectId"/>,
/// or -1 when it sent none since the engine started watching (or the table was cleared).</summary>
public static long AgeMs(uint objectId, long nowMs)
{
lock (Sync)
return LastMessage.TryGetValue(objectId, out long t) ? Math.Max(0, nowMs - t) : -1;
}
public static void Clear()
{
lock (Sync) LastMessage.Clear();
}
}

View file

@ -0,0 +1,115 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PendingIdQueue.cs
//
// The pending queue behind AcMainThreadQueue's RequestId (0xC8 appraisal) slot.
// A bounded FIFO of (object id, enqueue time, login epoch) that MERGES a request
// for an object already waiting, the way the QueryHealth slot does: one appraisal
// reply answers every caller that asked for it. Before this, AutoId's priority
// appraisal, its create backlog and the plugins' RequestIdFn each queued their own
// copy; one dump had 437 of 3211 identifies repeat an object within 125 ms.
//
// A pending entry only absorbs a new request while it is from the same login and
// young enough that the drain will still send it (MergeMaxAgeMs). An entry the drain
// would drop as stale, or one from an earlier login, takes no merges: the new
// request is queued on its own so it is not lost with the old one.
//
// Pure data structure: no engine state, no locking (the caller holds its lock), and
// no allocation after construction (a fixed ring). Compiled into
// tools\EngineRobustnessTests.
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal sealed class PendingIdQueue
{
public enum Result
{
/// <summary>Added as a new pending request.</summary>
Queued,
/// <summary>The object already had a pending request; nothing added.</summary>
Merged,
/// <summary>The queue is full; the request was not taken.</summary>
Full,
}
public readonly struct Item
{
public readonly uint Id;
public readonly long At;
public readonly int Epoch;
/// <summary>Who asked (Net.IdRequester as a byte): the first request's, a merge keeps it.</summary>
public readonly byte Source;
public Item(uint id, long at, int epoch, byte source = 0)
{
Id = id;
At = at;
Epoch = epoch;
Source = source;
}
}
private readonly Item[] _ring;
private int _head; // index of the oldest item
private int _count;
public PendingIdQueue(int capacity)
{
if (capacity <= 0) throw new System.ArgumentOutOfRangeException(nameof(capacity));
_ring = new Item[capacity];
}
public int Count => _count;
public int Capacity => _ring.Length;
/// <summary>Requests absorbed by an already-pending entry since construction.</summary>
public long MergedTotal { get; private set; }
/// <summary>
/// Queue a request for <paramref name="id"/>, or merge it into a pending one for the
/// same object from the same <paramref name="epoch"/> that is at most
/// <paramref name="mergeMaxAgeMs"/> old at <paramref name="nowMs"/> and was queued AFTER
/// <paramref name="mergeOnlyAfterMs"/> (the last moment a world transition held the
/// drains: an entry from before then is dropped when the drain reaches it, and a request
/// merged into it would be lost with it).
/// </summary>
public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0, byte source = 0)
{
for (int i = 0; i < _count; i++)
{
ref readonly Item q = ref _ring[(_head + i) % _ring.Length];
if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs
&& (mergeOnlyAfterMs <= 0 || q.At > mergeOnlyAfterMs)) // 0 = no transition: no floor
{
MergedTotal++;
return Result.Merged;
}
}
if (_count >= _ring.Length)
return Result.Full;
_ring[(_head + _count) % _ring.Length] = new Item(id, nowMs, epoch, source);
_count++;
return Result.Queued;
}
public bool TryDequeue(out Item item)
{
if (_count == 0)
{
item = default;
return false;
}
item = _ring[_head];
_ring[_head] = default;
_head = (_head + 1) % _ring.Length;
_count--;
return true;
}
public void Clear()
{
System.Array.Clear(_ring);
_head = 0;
_count = 0;
}
}

View file

@ -10,8 +10,14 @@
// teleport. With these lines a crash can be lined up with what the character
// was doing.
//
// Also the world-transition gate (WorldTransitionState): while the player is dead,
// portaling, or settling after either or after a landblock jump, AcMainThreadQueue
// holds every queued game-mutating call instead of running it into a world AC is
// tearing down (a client died right after a death recall's landblock jump).
//
// Sampled from GameTickHooks.UseTimeDetour on AC's main thread, before AC's
// tick, so the reads see a consistent world. Alloc-free except on an edge.
// tick and before the cast drain, so the reads see a consistent world and the gate
// knows about a death in the same tick. Alloc-free except on an edge.
// ============================================================================
using System;
@ -21,20 +27,53 @@ namespace RynthCore.Engine.Compatibility;
internal static class PlayerLifecycleLog
{
private static bool _init;
// Main thread only (the UseTime sample and both main-thread drains).
private static readonly WorldTransitionState _state = new();
private static long _settleUntil; // published copy for other threads
private static volatile bool _portaling, _dead;
private static long _transitionUntil;
private const long TransitionSettleMs = 5_000;
private static long _portalEnteredAt, _diedAt;
/// <summary>
/// Dead, in portal space, or within 5 s after either: AC is tearing down and
/// loading the world, so nothing should poke at its state (BusyCountHooks'
/// force-clear). As of the last game tick; any thread.
/// Dead, in portal space, or within 5 s after either or after a landblock jump: AC is
/// tearing down and loading the world, so nothing should poke at its state
/// (BusyCountHooks' force-clear). As of the last game tick; any thread.
/// </summary>
public static bool InWorldTransition =>
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _transitionUntil);
private static uint _landblock;
private static long _portalEnteredAt, _diedAt;
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil);
/// <summary>
/// When the last settle window ends (TickCount64; 0 = no transition yet), as of the last
/// game tick; any thread. Moves only on a death, a portal, a teleport or a landblock jump,
/// never on a walk into the next landblock (AutoIdPolicy's post-transition defer).
/// </summary>
public static long SettleUntilMs => Interlocked.Read(ref _settleUntil);
/// <summary>
/// AC main thread only (the queue drains): true = hold everything queued now (see
/// WorldTransitionState for the rule).
/// </summary>
public static bool HoldQueuedWork(long nowMs)
{
bool hold = _state.CheckHolding(nowMs);
if (hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
return hold;
}
/// <summary>AC main thread only: what a drain does with one queued item (WorldTransitionState.Decide).</summary>
public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown)
{
WorldTransitionState.Verdict v = _state.Decide(nowMs, queuedAtMs, teardown);
if (v == WorldTransitionState.Verdict.Hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
return v;
}
private static long _lastBlockedPublished;
/// <summary>
/// The last moment a drain was held by a world transition (0 = never), for other threads:
/// queued work from at or before it is dropped when the drains reach it.
/// </summary>
public static long LastBlockedMs => Interlocked.Read(ref _lastBlockedPublished);
/// <summary>AC main thread, once per game tick.</summary>
public static void SampleOnGameThread(bool portaling)
@ -52,51 +91,44 @@ internal static class PlayerLifecycleLog
cell = c;
uint landblock = cell >> 16;
if (!_init)
{
_init = true;
_portaling = portaling;
_dead = dead;
_landblock = landblock;
return;
}
long now = Environment.TickCount64;
if (dead || portaling || _dead || _portaling)
Interlocked.Exchange(ref _transitionUntil, now + TransitionSettleMs);
if (dead != _dead)
{
if (dead)
{
_diedAt = now;
RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
else
RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}.");
_dead = dead;
}
WorldTransitionState.Edge edges = _state.Sample(now, dead, portaling, landblock);
_dead = _state.Dead;
_portaling = _state.Portaling;
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
if (edges == WorldTransitionState.Edge.None)
return;
if (portaling != _portaling)
if ((edges & WorldTransitionState.Edge.Died) != 0)
{
if (portaling)
{
_portalEnteredAt = now;
string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : "";
RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
else
RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}.");
_portaling = portaling;
_diedAt = now;
RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
if ((edges & WorldTransitionState.Edge.Revived) != 0)
RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}.");
if ((edges & WorldTransitionState.Edge.PortalEntered) != 0)
{
_portalEnteredAt = now;
string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : "";
RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
if ((edges & WorldTransitionState.Edge.PortalExited) != 0)
RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}.");
if ((edges & WorldTransitionState.Edge.LandblockJump) != 0)
RynthLog.Info($"[Lifecycle] landblock jump 0x{_state.PreviousLandblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
}
if (landblock != 0 && _landblock != 0 && landblock != _landblock)
{
int dx = (int)((landblock >> 8) & 0xFF) - (int)((_landblock >> 8) & 0xFF);
int dy = (int)(landblock & 0xFF) - (int)(_landblock & 0xFF);
if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1)
RynthLog.Info($"[Lifecycle] landblock jump 0x{_landblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}.");
}
if (landblock != 0) _landblock = landblock;
/// <summary>
/// AC main thread (SmartBoxHooks, after AC handled 0xF751 PlayerTeleport): a teleport starts
/// now. The settle window runs from here, published at once for the enqueue side.
/// </summary>
public static void OnTeleportMessage()
{
long now = Environment.TickCount64;
bool started = _state.OnTeleportMessage(now);
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
if (started)
RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
}
private static string Ago(long since, long now) =>

View file

@ -385,7 +385,7 @@ internal static class PlayerPhysicsHooks
// Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain
// calls back in here on the main thread (and falls back to the
// CommandInterpreter turn there when there is no player, as before).
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg);
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
@ -457,7 +457,7 @@ internal static class PlayerPhysicsHooks
// raw write racing AC's own motion-graph tick is a guaranteed torn
// write, not just an AV risk. Reachable off-thread via Jumper.cs's
// ReleaseJump on the Decal-coexistence pump thread.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
if (!TryGetCMotionInterp(out IntPtr cmi))

View file

@ -141,7 +141,7 @@ internal static unsafe class PlayerTrade
/// <summary>Ask <paramref name="targetId"/> to trade (0x01F6 OpenTradeNegotiations).</summary>
public static bool Open(uint targetId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventOpenTradeNegotiations != null && targetId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0);
if (_eventOpenTradeNegotiations == null || targetId == 0) return false;
@ -153,7 +153,7 @@ internal static unsafe class PlayerTrade
/// <summary>Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free.</summary>
public static bool Add(uint itemId, uint slot)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventAddToTrade != null && itemId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot);
if (_eventAddToTrade == null || itemId == 0) return false;
@ -165,7 +165,7 @@ internal static unsafe class PlayerTrade
/// <summary>Empty both sides of the window (0x0204 ResetTrade).</summary>
public static bool Reset()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0);
if (_eventResetTrade == null) return false;
byte rv = _eventResetTrade();
@ -176,7 +176,7 @@ internal static unsafe class PlayerTrade
/// <summary>Close the trade (0x01F7 CloseTradeNegotiations).</summary>
public static bool Close()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0);
if (_eventCloseTradeNegotiations == null) return false;
byte rv = _eventCloseTradeNegotiations();
@ -187,7 +187,7 @@ internal static unsafe class PlayerTrade
/// <summary>Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade).</summary>
public static bool Accept()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0);
if (_tradeSystemAcceptTrade == null) return false;
IntPtr system = TradeSystemWithTrade();
@ -200,7 +200,7 @@ internal static unsafe class PlayerTrade
/// <summary>Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade).</summary>
public static bool Decline()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0);
if (_tradeSystemDeclineTrade == null) return false;
IntPtr system = TradeSystemWithTrade();

View file

@ -121,7 +121,7 @@ internal static unsafe class PlayerTraining
RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world");
return false;
}
if (defer || !MainThreadGuard.IsOnMainThread())
if (defer || AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);
byte rv = kind switch

View file

@ -47,28 +47,6 @@ internal static class ProcessExitHooks
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint NtTerminateProcessDelegate(IntPtr processHandle, uint exitStatus);
// kernel32!RaiseFailFastException — what __fastfail() / abort() / FailFast
// route through. Doesn't take an exit code; takes EXCEPTION_RECORD + CONTEXT.
// We don't need the params, just the call-site capture.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RaiseFailFastExceptionDelegate(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags);
// ntdll!RtlFailFast(NTSTATUS) — internally executes `int 0x29` (the
// __fastfail intrinsic). The kernel handles 0x29 directly and terminates
// the process WITHOUT re-entering user mode through ExitProcess /
// TerminateProcess / RaiseFailFastException. Hooking RtlFailFast itself
// is the only way to capture this path before the kernel takes over.
// Used by: stack-cookie failures (/GS), heap corruption checks, CRT
// abort paths on newer toolchains, NTDLL's own internal asserts.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFastDelegate(uint code);
// ntdll!RtlFailFast2(NTSTATUS, EXCEPTION_RECORD*) — newer variant that
// also passes an exception record. Same semantics: the kernel terminates
// the process via int 0x29 without revisiting user mode.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFast2Delegate(uint code, IntPtr pExceptionRecord);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
@ -103,43 +81,9 @@ internal static class ProcessExitHooks
private static RtlExitUserProcessDelegate? _rtlExitOriginal;
private static NtTerminateProcessDelegate? _ntTermDetour;
private static NtTerminateProcessDelegate? _ntTermOriginal;
private static RaiseFailFastExceptionDelegate? _failFastDetour;
private static RaiseFailFastExceptionDelegate? _failFastOriginal;
private static RtlFailFastDelegate? _rtlFailFastDetour;
private static RtlFailFastDelegate? _rtlFailFastOriginal;
private static RtlFailFast2Delegate? _rtlFailFast2Detour;
private static RtlFailFast2Delegate? _rtlFailFast2Original;
private static int _installed;
private static int _logged; // ensure we log at most once even if both fire
// Re-entrancy latch for the fail-fast family (RaiseFailFastException,
// RtlFailFast, RtlFailFast2). In the NativeAOT-inside-acclient environment
// a fail-fast does NOT terminate the way it does in a normal process: the
// runtime/AC exception machinery swallows or continues the fail-fast
// exception, so kernel32!RaiseFailFastException RETURNS instead of killing
// the process. Its caller then re-invokes it, hitting our MinHook again →
// detour re-enters → calls the original again → ~190K-deep recursion that
// exhausts the 8 MB stack and AVs in ntdll (the recursing code is this
// exit logger itself, so nothing downstream can ever log it). Latch is
// process-wide and never reset — a fail-fast is terminal by contract;
// there is no "recovery", we only need to die cleanly and once.
private static int _inFailFast;
/// <summary>
/// Terminate without any possibility of re-entering a ProcessExitHooks
/// detour. Each call target is a MinHook *trampoline* (relocated original
/// prologue + jump PAST our hook), so none of them route back through our
/// detours. Used to break the fail-fast bounce.
/// </summary>
private static void HardTerminateNoReentry(uint code)
{
try { _ntTermOriginal?.Invoke(new IntPtr(-1), code); } catch { }
try { _rtlExitOriginal?.Invoke(code); } catch { }
try { _exitOriginal?.Invoke(code); } catch { }
try { Environment.Exit(unchecked((int)code)); } catch { }
}
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
@ -178,23 +122,13 @@ internal static class ProcessExitHooks
RynthLog.Info($"ProcessExitHooks: hooked kernel32!TerminateProcess @ 0x{terminateTarget.ToInt32():X8}.");
}
// ── DO NOT HOOK RaiseFailFastException (proven fatal 2026-05-16) ──
// Dump analysis of the every-few-minutes silent crash showed a
// 190K-deep stack overflow whose repeating frame pair is
// <ReverseOpenStaticDelegateStub>...RaiseFailFastExceptionDelegate
// ↔ RhpReversePInvokeAttachOrTrapThread2. The NativeAOT reverse-
// P/Invoke transition that enters a managed detour for this export
// itself re-triggers RaiseFailFastException, so the detour recurses
// through the transition shim BEFORE any managed code (incl. any
// re-entrancy guard) can run. Unfixable from the managed side — the
// only correct action is to not hook it. A real fail-fast then
// terminates cleanly (as designed) instead of our hook converting
// it into the guaranteed stack-overflow crash. Same applies to
// ntdll!RtlFailFast / RtlFailFast2 below. The other exit hooks
// (ExitProcess/TerminateProcess/RtlExitUserProcess/NtTerminate) are
// safe — exiting the process does not re-enter those from within
// the transition, and they log clean interceptions.
// DO NOT HOOK RaiseFailFastException, RtlFailFast or RtlFailFast2 (proven fatal
// in practice): the reverse-P/Invoke transition into a managed detour for those
// exports re-triggered the fail-fast itself (190K-deep recursion through the
// transition shim, before any managed guard could run). Their detour bodies were
// dead code and are gone, so nothing can switch them back on by
// accident: a managed body on the fail-fast path turns a crash that would leave
// a dump into a silent one.
// ntdll-level hooks — catch paths that bypass kernel32 entirely.
IntPtr ntdll = GetModuleHandleW("ntdll.dll");
if (ntdll != IntPtr.Zero)
@ -223,38 +157,6 @@ internal static class ProcessExitHooks
RynthLog.Info($"ProcessExitHooks: hooked ntdll!NtTerminateProcess @ 0x{ntTermTarget.ToInt32():X8}.");
}
// RtlFailFast / RtlFailFast2 — NOT HOOKED. Same NativeAOT
// reverse-P/Invoke re-entry recursion as RaiseFailFastException
// (see the block above). Hooking these with a managed detour
// is the every-few-minutes crash. Leave them alone; a genuine
// fail-fast terminates cleanly. (On this Windows build the
// GetProcAddress for these also failed historically anyway.)
if (false && ntdll != IntPtr.Zero)
{
HookExport(ntdll, "RtlFailFast", out IntPtr rtlFailFastTarget);
if (rtlFailFastTarget != IntPtr.Zero)
{
_rtlFailFastDetour = RtlFailFastDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFastDetour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFastTarget, detourPtr);
_rtlFailFastOriginal = Marshal.GetDelegateForFunctionPointer<RtlFailFastDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFastTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast @ 0x{rtlFailFastTarget.ToInt32():X8}.");
}
HookExport(ntdll, "RtlFailFast2", out IntPtr rtlFailFast2Target);
if (rtlFailFast2Target != IntPtr.Zero)
{
_rtlFailFast2Detour = RtlFailFast2Detour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFast2Detour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFast2Target, detourPtr);
_rtlFailFast2Original = Marshal.GetDelegateForFunctionPointer<RtlFailFast2Delegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFast2Target);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast2 @ 0x{rtlFailFast2Target.ToInt32():X8}.");
}
}
}
}
catch (Exception ex)
@ -272,6 +174,15 @@ internal static class ProcessExitHooks
private static void ExitProcessDetour(uint exitCode)
{
// A crash exit goes straight to the original, before any managed work (IsCrashExit).
// The reverse-P/Invoke transition into this detour is the only managed step left; a
// native pass-through would remove that too; it is possible but not done here.
if (IsCrashExit(exitCode))
{
SehTrampoline.FlushCrashLog(exitCode); // native, allocation-free
_exitOriginal!(exitCode);
return;
}
LogTermination("ExitProcess", IntPtr.Zero, exitCode);
// Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this,
// hooks stay installed, our threads (TickPump, Avalonia STA) keep
@ -283,44 +194,45 @@ internal static class ProcessExitHooks
catch { /* original never returns; swallow if it somehow does */ }
}
// A crash exit: an NTSTATUS error or exception code (0xC0000000 and up: 0xC0000005 an
// access violation, 0xE0434352 a CLR exception). The process is dying of a fault, often
// from inside the runtime's own fatal-error path; managed work here (logging, a
// MiniDumpWriteDump) can deadlock or fault again there and leave nothing at all. So a crash
// exit is passed straight to the original. The evidence comes from places that do not
// need managed code on the way out: the native crash logger (SehTrampoline.c, its vectored
// handler sees the fault first) and CoreCLR's own createdump (native\Loader\Loader.c, ConfigureCrashDumps). This
// replaces the managed crash dump written here before, which left nothing for real crashes.
// The one call made first, SehTrampoline.FlushCrashLog, is a raw native call: it writes
// the crash logger's recent first-chance records that were not written one by one (the
// fatal hit of an address seen before is usually among them; a terminate from a handler
// never reaches the last-chance filter). Which codes count: CrashExitRule.
private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);
private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode)
{
// Only log when terminating ourselves — TerminateProcess on other
// process handles is a normal Process.Kill and not what we're hunting.
// hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle.
// Only log when terminating ourselves: TerminateProcess on other process handles is a
// normal Process.Kill and not what we're hunting. hProcess == -1 is the pseudo-handle.
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
if (selfKill)
{
LogTermination("TerminateProcess", hProcess, exitCode);
DumpCrashOnce("TerminateProcess", exitCode);
if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode);
else LogTermination("TerminateProcess", hProcess, exitCode);
}
try { return _terminateOriginal!(hProcess, exitCode); }
catch { return false; }
}
// A crash exit (an NTSTATUS error code, 0xC0000000 and up: 0xC0000005 is an access
// violation) on the way out: write a minidump once, while the faulting frames are still on
// the stack. The runtime ends the process with TerminateProcess after a native AV under one
// of our detours, so no unhandled exception ever reaches a crash watcher (procdump -e saw
// nothing for Lucy's Town Network crashes, 10-01 19:46 and 10-02 15:55).
private static int _crashDumped;
private static void DumpCrashOnce(string via, uint code)
{
if (code < 0xC0000000u || System.Threading.Interlocked.Exchange(ref _crashDumped, 1) != 0) return;
try
{
if (CrashDump.WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash"))
RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})");
}
catch { }
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess();
private static void RtlExitUserProcessDetour(uint exitStatus)
{
if (IsCrashExit(exitStatus)) // see ExitProcessDetour
{
SehTrampoline.FlushCrashLog(exitStatus);
_rtlExitOriginal!(exitStatus);
return;
}
LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus);
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
@ -333,57 +245,14 @@ internal static class ProcessExitHooks
bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle();
if (selfKill)
{
LogTermination("NtTerminateProcess", processHandle, exitStatus);
DumpCrashOnce("NtTerminateProcess", exitStatus);
// A second flush (TerminateProcess calls this) writes nothing: records are written once.
if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus);
else LogTermination("NtTerminateProcess", processHandle, exitStatus);
}
try { return _ntTermOriginal!(processHandle, exitStatus); }
catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ }
}
private static void RaiseFailFastExceptionDetour(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
// Re-entered: the original bounced back through our hook instead
// of terminating. Forwarding again is the 190K-deep stack-overflow
// recursion. Break it — die now, non-recursively.
HardTerminateNoReentry(dwFlags);
return;
}
LogTermination("RaiseFailFastException", IntPtr.Zero, dwFlags);
try { _failFastOriginal!(pExceptionRecord, pContext, dwFlags); }
catch { }
// A real fail-fast never returns. In this environment it can — don't
// let the caller spin re-raising it; terminate deterministically.
HardTerminateNoReentry(dwFlags);
}
private static void RtlFailFastDetour(uint code)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast", IntPtr.Zero, code);
try { _rtlFailFastOriginal!(code); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
private static void RtlFailFast2Detour(uint code, IntPtr pExceptionRecord)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast2", IntPtr.Zero, code);
try { _rtlFailFast2Original!(code, pExceptionRecord); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
/// <summary>ExitProcess/TerminateProcess was called: the process is closing.</summary>
public static bool TerminationIntercepted => Volatile.Read(ref _logged) != 0;

View file

@ -456,7 +456,9 @@ internal static class PropertyUpdateHooks
if (objectId != 0)
{
EvictObject(objectId);
AppraisalHooks.EvictObject(objectId);
// A client release keeps the identify data a while (a server delete,
// 0xF747, evicts it): see ReleasedObjectRetention.
AppraisalHooks.OnClientRelease(objectId, Environment.TickCount64);
}
}
}

View file

@ -0,0 +1,77 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ReleasedObjectRetention.cs
//
// How long AppraisalHooks keeps an object's identify data after the CLIENT released it
// (AC's BeingDeleted, which fires for every object leaving the client's view).
//
// Before: the data was evicted on every client release, so when the
// object came back into view AutoId found nothing cached and appraised it again: the
// 10-minute re-appraisal window (AutoIdEligibility) almost never applied. Now the data is
// kept for RetainMs after a client release and dropped:
// - when RetainMs has passed (Expire, from AutoIdService's timer);
// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject);
// - at a session clear (logout), and under AppraisalHooks' object cap.
// A re-create (OnLive) makes the object current again.
//
// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock).
// Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
internal sealed class ReleasedObjectRetention
{
public const long DefaultRetainMs = 10L * 60 * 1000;
public const int DefaultMaxReleased = 4096;
private readonly Dictionary<uint, long> _releasedAt;
private readonly long _retainMs;
private readonly int _max;
public ReleasedObjectRetention(long retainMs = DefaultRetainMs, int maxReleased = DefaultMaxReleased)
{
_retainMs = retainMs;
_max = maxReleased;
_releasedAt = new Dictionary<uint, long>(maxReleased + 1);
}
public int Count => _releasedAt.Count;
public long RetainMs => _retainMs;
/// <summary>
/// The client released <paramref name="id"/> (which has cached data). Returns true when the
/// data is kept for now; false when it must be dropped at once (the bound is reached and
/// nothing has expired to make room).
/// </summary>
public bool OnRelease(uint id, long nowMs)
{
if (_releasedAt.ContainsKey(id)) { _releasedAt[id] = nowMs; return true; }
if (_releasedAt.Count >= _max) return false;
_releasedAt[id] = nowMs == 0 ? 1 : nowMs;
return true;
}
/// <summary>The object is current again (re-created), or its data was dropped for another reason.</summary>
public void Forget(uint id) => _releasedAt.Remove(id);
public bool IsReleased(uint id) => _releasedAt.ContainsKey(id);
/// <summary>Released ids whose data has outlived RetainMs: removed here and added to <paramref name="expired"/>.</summary>
public int Expire(long nowMs, List<uint> expired)
{
int n = 0;
foreach (KeyValuePair<uint, long> kv in _releasedAt)
{
if (nowMs - kv.Value < _retainMs) continue;
expired.Add(kv.Key);
n++;
}
for (int i = expired.Count - n; i < expired.Count; i++)
_releasedAt.Remove(expired[i]);
return n;
}
public void Clear() => _releasedAt.Clear();
}

View file

@ -81,6 +81,12 @@ namespace RynthCore.Engine.Compatibility;
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
/// opens the panel; with text it sends that report now, with the recent log attached
/// (the panel is where the log can be left out). One report a minute.</item>
/// <item><c>/rc autoid [all|limited|off]</c> - which background appraisals the engine's AutoId
/// sends (<see cref="AutoIdService"/>, <see cref="AutoIdPolicy"/>; saved in engine.json);
/// alone it reports the mode and the identify counts by who asked.</item>
/// <item><c>/rc hotkeys</c> - opens Settings &gt; Hotkeys. <c>/rc hotkey list | add &lt;combo&gt; &lt;action or
/// /command&gt; | remove &lt;combo&gt; | enable|disable &lt;combo&gt; | actions | status | on|off</c> - the user
/// hotkeys (<see cref="Hotkeys.HotkeyService"/>; saved for the PC in hotkeys.txt).</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -288,6 +294,18 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc autoid [all|limited|off] : which background appraisals AutoId sends (alone: status)
if (IsVerb(sub, "autoid", out string autoIdArgs))
{
try
{
foreach (string l in AutoIdService.HandleCommand(autoIdArgs))
Reply(l);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc autoid failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream
if (IsVerb(sub, "netmsg", out string netArgs))
{
@ -310,6 +328,97 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc bounties|guardian [show|hide|toggle] : the ILT section's panels, like the bar's
// ILT button (Bounties: the RynthILT plugin's tracker; Guardian: RynthAi's Temple
// guardian tools). Only on Infinite Leaftide with the plugin installed.
if (IsVerb(sub, "bounties", out string panelArgs) || IsVerb(sub, "bounty", out panelArgs) || IsVerb(sub, "bountys", out panelArgs))
{
IltPanel(ImGuiBackend.Panels.BountiesFace.Title, "Bounties", "RynthILT", panelArgs);
return true;
}
if (IsVerb(sub, "guardian", out panelArgs) || IsVerb(sub, "guardians", out panelArgs))
{
IltPanel(ImGuiBackend.Panels.GuardianFace.Title, "Guardian", "RynthAi", panelArgs);
return true;
}
// /rc miniremote [show|hide|toggle|tab <tab>] : the ImGui Mini Remote panel, like its bar
// button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of
// RynthAi's tabs (character, quests, pets, banking, gear, games; none = the remote).
if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title))
Reply("The Mini Remote panel isn't available (the ImGui layer is off?).");
else if (IsVerb(remoteArgs, "tab", out string tab))
{
ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title);
UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab");
}
else if (!TryPanelMode(remoteArgs, out bool? show))
Reply("Usage: /rc miniremote [show|hide|toggle|tab <tab>]");
else
SetPanelOpen(ImGuiBackend.Panels.MiniRemoteFace.Title, show);
return true;
}
// /rc skills [show|hide|toggle] : the ImGui Skills panel; /rc progression opens it on its
// Progression tab (ILT worlds; the tab shows once RynthAi reports ILT features).
if (IsVerb(sub, "skills", out string skillsArgs))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
Reply("The Skills panel isn't available (the ImGui layer is off?).");
else if (!TryPanelMode(skillsArgs, out bool? show))
Reply("Usage: /rc skills [show|hide|toggle]");
else
SetPanelOpen(ImGuiBackend.Panels.SkillsFace.Title, show);
return true;
}
if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
Reply("The Skills panel isn't available (the ImGui layer is off?).");
else
ImGuiBackend.Panels.SkillsFace.ShowProgression();
return true;
}
// /rc spells [show|hide|toggle] : RynthAi's Spells window (spell catalog, buff profiles).
if (IsVerb(sub, "spells", out string spellsArgs))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.RynthAiFace.Title))
Reply("The Spells window comes with RynthAi; it isn't installed.");
else if (!TryPanelMode(spellsArgs, out bool? show))
Reply("Usage: /rc spells [show|hide|toggle]");
else
UI.Data.RynthAiCommands.ApplyRemoteCommand("spells", show == null ? "toggle" : show.Value ? "show" : "hide");
return true;
}
// /rc hotkeys : Settings > Hotkeys. /rc hotkey list|add|remove|enable|disable|actions|status|on|off
// (Hotkeys/HotkeyService.cs; "/rc hotkeys <verb>" works too).
if (IsVerb(sub, "hotkeys", out string hotkeyArgs) && hotkeyArgs.Length == 0)
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title))
Reply("The Settings panel isn't available (the ImGui layer is off?). /rc hotkey list|add|remove work here in chat.");
else
{
ImGuiBackend.Panels.SettingsFace.RequestTab(ImGuiBackend.Panels.HotkeysSettingsUi.TabName);
if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title))
UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title);
}
return true;
}
if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs))
{
try
{
foreach (string l in Hotkeys.HotkeyService.HandleCommand(hotkeyArgs))
Reply(l);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hotkey failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
switch (sub.ToLowerInvariant())
{
case "rl":
@ -318,6 +427,7 @@ internal static class RynthCoreChatCommands
// loader's reload shuts this engine down, and this handler runs
// inside AC's outgoing-chat hook.
RynthLog.Compat("RynthCoreChatCommands: /rc rl — engine reload requested.");
EntryPoint.NoteManualReload(); // by hand: not held for combat (EntryPoint.DeferReloadWhilePluginsObject)
System.Threading.ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
return true;
@ -338,6 +448,15 @@ internal static class RynthCoreChatCommands
UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title);
return true;
case "characters":
case "chars":
// The ImGui Characters panel (your other RynthCore clients, through RynthNet).
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.CharactersFace.Title))
Reply("The Characters panel needs the RynthNet plugin (add it in the launcher's Plugins tab).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.CharactersFace.Title);
return true;
case "itemcount":
case "itemhud":
// The ImGui Item Count panel (open/close), like its bar button.
@ -347,28 +466,6 @@ internal static class RynthCoreChatCommands
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title);
return true;
case "bounties":
case "bounty":
case "bountys":
// The ImGui Bounties panel (ILT section: ACECustom bounties, the RynthILT plugin's
// tracker), like the ILT bar button. Only on Infinite Leaftide with RynthILT installed.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title))
Reply("The Bounties panel isn't available (the RynthILT plugin isn't installed, or the ImGui layer is off).");
else if (!IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.BountiesFace.Title))
Reply("Bounties are an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.BountiesFace.Title);
return true;
case "remote":
case "miniremote":
// The ImGui Mini Remote panel (open/close), like its bar button.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title))
Reply("The Mini Remote panel isn't available (the ImGui layer is off?).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.MiniRemoteFace.Title);
return true;
case "resetbar":
case "barreset":
RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position.");
@ -624,9 +721,12 @@ internal static class RynthCoreChatCommands
Reply($"ILT: {(v.IsIlt ? "Infinite Leaftide" : "not Infinite Leaftide")} - {v.Reason}.");
Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; "
+ $"override {IltInfo.Override}. Lists: {IltInfo.ListsDescription}.");
Reply(ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title)
? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
: "RynthILT: not installed, so there is no ILT section.");
bool bounties = ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title);
bool guardian = ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.GuardianFace.Title);
Reply(bounties ? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
: "RynthILT: not installed (no Bounties panel).");
Reply(guardian ? "RynthAi: installed (Guardian: the ILT bar button or /rc guardian; the ILT tabs: the Mini Remote)."
: "RynthAi: not installed (no Guardian panel or ILT tabs).");
}
private static void HandleMasteryCommand()
@ -670,6 +770,42 @@ internal static class RynthCoreChatCommands
Reply(ImGuiBackend.UnderUiLayer.Describe());
}
/// <summary>
/// "" / "toggle" → null (flip), "show" / "on" / "open" → true, "hide" / "off" / "close" →
/// false. False for anything else.
/// </summary>
private static bool TryPanelMode(string args, out bool? show)
{
show = null;
switch (args.Trim().ToLowerInvariant())
{
case "": case "toggle": return true;
case "show": case "on": case "open": show = true; return true;
case "hide": case "off": case "close": show = false; return true;
default: return false;
}
}
/// <summary>Opens (true), closes (false) or toggles (null) an ImGui panel, like its bar button.</summary>
private static void SetPanelOpen(string title, bool? show)
{
if (show == null || show.Value != ImGuiBackend.ImGuiPanelHost.IsOpen(title))
UI.PanelRouter.Toggle(title);
}
/// <summary>"/rc bounties|guardian [show|hide|toggle]": one of the ILT section's panels.</summary>
private static void IltPanel(string title, string label, string plugin, string args)
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(title))
Reply($"The {label} panel isn't available (the {plugin} plugin isn't installed, or the ImGui layer is off).");
else if (!TryPanelMode(args, out bool? show))
Reply($"Usage: /rc {label.ToLowerInvariant()} [show|hide|toggle]");
else if (show != false && !IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(title))
Reply($"{label} is an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
else
SetPanelOpen(title, show);
}
private static bool IsVerb(string sub, string verb, out string args)
{
args = string.Empty;

View file

@ -28,6 +28,7 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -43,15 +44,114 @@ internal static class SehTrampoline
/// 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. Writes the faulting 32-bit context + a module-resolved stack
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602
/// (RaiseFailFast) classes that bypass managed handlers. Observes only.
/// sweep to <paramref name="logPath"/>. v6 (PR #8): each faulting address once, repeats
/// at power-of-two counts or after 30 s, .NET/CoreCLR noise not charged to the cap, the
/// unhandled-exception entry always; a 16-record ring of the rest is flushed on a crash
/// exit (RC_FlushCrashLog), from the last-chance filter, and at process exit (last 30 s).
/// AVs caught by the SEH_* wrappers only go to that ring. Observes only.
/// Caveat: "pure native" held only while nothing it calls had a managed detour. Before v5
/// it called CreateFileW from the handlers, and DatFileShareHooks detours CreateFileW in
/// managed code, so older DLLs are not installed while that hook is on (see below).
/// </summary>
public static void InstallCrashLogger(string logPath)
{
try { _InstallCrashLogger(logPath); }
try
{
// v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs);
// v1 (no version export) logged every first-chance AV.
uint version = NativeVersion;
if (version < SafeCrashLoggerVersion && DatFileShareHooks.IsInstalled)
{
// v1-v4 open native-crash.log with CreateFileW from inside the VEH, which runs
// first, on the faulting thread. DatFileShareHooks detours CreateFileW with a
// managed delegate, so for a fault in managed code (any NullReferenceException:
// the thread is still in cooperative mode) that is a reverse P/Invoke from
// cooperative mode, and CoreCLR ends the process: ReversePInvokeBadTransition,
// event 1023 "internal error in the .NET Runtime at IP coreclr.dll+0x256E19",
// exit 0x80131506. Seven client deaths 2026-09-29..10-12 were this. v5 opens the
// file here instead (a normal P/Invoke), so the handlers never call CreateFileW.
RynthLog.Warn($"SehTrampoline: native crash logger NOT installed - the loaded RynthCore.SehTrampoline.dll is v{version}, " +
$"whose logger calls CreateFileW inside exception handling; with the DAT share hook's managed CreateFileW detour " +
$"that turns any NullReferenceException into a fatal CLR error. Needs v{SafeCrashLoggerVersion}+ " +
"(rebuild native\\SehTrampoline, then restart the client). A logger an earlier engine generation installed in " +
"this client stays active until the client restarts.");
return;
}
_InstallCrashLogger(logPath);
string mode = version >= 6 ? "once per address + repeats, flush ring"
: version >= 2 ? "fatal-only" : "logs every first-chance AV";
RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}, {mode}) -> {logPath}");
}
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
ResolveFlushCrashLog();
}
// RC_FlushCrashLog, resolved once here (0 = a DLL older than the export). Called through a
// raw unmanaged function pointer, so the crash path binds and compiles nothing: the call
// is primed below with code 0, which the native side ignores.
private static nint _flushCrashLog;
private static unsafe void ResolveFlushCrashLog()
{
try
{
nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll");
nint fn = module == 0 ? 0 : GetProcAddress(module, "RC_FlushCrashLog");
if (fn == 0)
{
RynthLog.Compat("SehTrampoline: RC_FlushCrashLog not exported (older DLL); crash exits will not flush the crash log's recent records.");
return;
}
((delegate* unmanaged[Cdecl]<uint, void>)fn)(0); // prime: code 0 is a no-op
_flushCrashLog = fn;
}
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: RC_FlushCrashLog unavailable - {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>
/// A crash exit is under way (ProcessExitHooks): write the crash logger's recent first-chance
/// records that were not written one by one, such as the fatal repeat of an address seen
/// before. Native and allocation-free; writes each record once, so a second call (one exit
/// path calling another) writes nothing.
/// </summary>
public static unsafe void FlushCrashLog(uint exitCode)
{
nint fn = _flushCrashLog;
if (fn == 0 || exitCode == 0) return;
((delegate* unmanaged[Cdecl]<uint, void>)fn)(exitCode);
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")]
private static extern nint GetModuleHandleW(string name);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true)]
private static extern nint GetProcAddress(nint module, string name);
private static int _moduleRefreshUnavailable;
/// <summary>
/// Rebuilds the crash logger's module cache (module names at exception time come from it,
/// so the handler never calls the loader). Heartbeat thread, every few seconds. A DLL
/// older than the export is tolerated: the first failure stops the calls.
/// </summary>
public static void RefreshCrashLoggerModules()
{
if (!_available || Volatile.Read(ref _moduleRefreshUnavailable) != 0) return;
try { _RefreshCrashLoggerModules(); }
catch (Exception ex)
{
Interlocked.Exchange(ref _moduleRefreshUnavailable, 1);
RynthLog.Compat($"SehTrampoline: crash-logger module refresh unavailable - {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// First native version whose crash logger opens its file at install time and never calls
/// CreateFileW while an exception is being dispatched (see SehTrampoline.c, cl_append_file).
/// </summary>
public const uint SafeCrashLoggerVersion = 5;
// ── Tag-parser guard (native detour) ───────────────────────────────────
/// <summary>Address of the native tag-parser null-guard detour (RC_TagParserGuard),
/// for the engine to pass to MinHook as the detour target.</summary>
@ -70,6 +170,32 @@ internal static class SehTrampoline
/// </summary>
public static bool IsAvailable => _available;
private static int _nativeVersion = -1;
/// <summary>
/// Version of the loaded native DLL (0 when unavailable, 1 when it predates the version
/// export). A running client keeps the DLL it started with, so a newer engine can meet
/// an older trampoline; gate newer exports on this.
/// </summary>
public static uint NativeVersion
{
get
{
int cached = System.Threading.Volatile.Read(ref _nativeVersion);
if (cached >= 0)
return (uint)cached;
uint version = 0;
if (_available)
{
try { version = _SehTrampolineVersion(); }
catch (EntryPointNotFoundException) { version = 1; }
catch { version = 0; }
}
System.Threading.Volatile.Write(ref _nativeVersion, (int)version);
return version;
}
}
// ── P/Invoke declarations ──────────────────────────────────────────────
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrUint",
@ -100,10 +226,23 @@ internal static class SehTrampoline
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* arg2, int* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_GameTickThiscall",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _GameTickThiscall(IntPtr fn, IntPtr thisPtr, int* outResult,
uint* outExAddr, uint* outDataAddr, byte* module, int moduleCap);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_InstallCrashLogger",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SehTrampolineVersion",
CallingConvention = CallingConvention.Cdecl)]
private static extern uint _SehTrampolineVersion();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_RefreshCrashLoggerModules",
CallingConvention = CallingConvention.Cdecl)]
private static extern void _RefreshCrashLoggerModules();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress();
@ -191,4 +330,24 @@ internal static class SehTrampoline
avCaught = _ThiscallIntUintPtr(fn, thisPtr, arg1, outStruct, &result) == 0;
return result;
}
/// <summary>
/// int __thiscall fn(this) — Client::UseTime. Requires <see cref="NativeVersion"/> &gt;= 4.
/// On a caught AV: avCaught=true, result 0, and the fault location; <paramref name="exAddr"/>
/// is relative to <paramref name="module"/> when that is non-empty, else absolute.
/// The native side also writes the full record to native-crash.log.
/// </summary>
public static unsafe int GameTickThiscall(IntPtr fn, IntPtr thisPtr, out bool avCaught,
out uint exAddr, out uint dataAddr, out string module)
{
const int ModuleCap = 64;
byte* name = stackalloc byte[ModuleCap];
int result;
uint ex, data;
avCaught = _GameTickThiscall(fn, thisPtr, &result, &ex, &data, name, ModuleCap) == 0;
exAddr = ex;
dataAddr = data;
module = avCaught ? (Marshal.PtrToStringAnsi((IntPtr)name) ?? string.Empty) : string.Empty;
return result;
}
}

View file

@ -16,6 +16,8 @@ internal static class SmartBoxHooks
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
private const uint VectorUpdateOpcode = 0x0000F74E;
private const uint UpdateObjectOpcode = 0x0000F7DB;
private const uint ServerObjectDeleteOpcode = 0x0000F747;
private const uint PlayerTeleportOpcode = 0x0000F751;
// ACSmartBox::DispatchSmartBoxEvent
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
@ -131,11 +133,23 @@ internal static class SmartBoxHooks
try
{
ObjectFreshness.Note(info.Opcode, info.RawObjectId, Environment.TickCount64); // ghost check (RemoveClientObject)
if (info.Opcode == PositionUpdateOpcode && info.RawObjectId != 0)
NotePlayerMotionEcho(blob, info);
TryQueueHealthUpdate(blob, info);
TryQueueDamageEvent(blob, info);
// Always on (no server-message capture needed), after AC handled the message:
// 0xF747 ObjectDelete [opcode][objectId]: the SERVER deleted it (AutoId re-arms it
// and its kept identify data goes), unlike the client's own view releases;
// 0xF751 PlayerTeleport: a teleport starts, so queued game actions hold for the
// settle window from this moment (WorldTransitionState), whatever the per-tick
// teleport_in_progress sample catches.
if (info.Opcode == ServerObjectDeleteOpcode && info.RawObjectId != 0)
AutoIdService.OnServerDelete(info.RawObjectId);
else if (info.Opcode == PlayerTeleportOpcode)
PlayerLifecycleLog.OnTeleportMessage();
if (info.RawObjectId != 0 &&
(info.Opcode == PositionUpdateOpcode ||
info.Opcode == PlayerPositionUpdateOpcode ||
@ -379,6 +393,15 @@ internal static class SmartBoxHooks
RecordWeenieError(eventType, unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), 0);
break;
case 0x0022: // InventoryPutObjInContainer: [item u32][container u32][placement][type].
// AutoId (Limited): an item that landed in the player's inventory with
// nothing cached is a candidate. Here, not on the server message stream,
// so it works with that stream off (engine.json / /rc netmsg off).
if (size >= 12)
AutoIdService.OnPutInContainer(
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))),
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))));
break;
case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] —
// the server refused an inventory change (wield, move, ...).
// Layout from UIQueueManager::ProcessNetBlobData's inline case
@ -632,6 +655,7 @@ internal static class SmartBoxHooks
if (critOff + 4 > size) return;
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off)));
double share = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(data, off + 4))); // damage / the monster's max health
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, critOff)));
if (damage == 0 || damage > 1_000_000) return;
@ -642,8 +666,8 @@ internal static class SmartBoxHooks
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
// RynthVision combat text: the attacker event names the monster hit.
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0);
// RynthVision combat text (and the plate of a monster with no health feed): the attacker event names the monster hit.
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0, attacker ? share : 0);
}
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
@ -767,6 +791,7 @@ internal static class SmartBoxHooks
return;
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off)));
double share = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(payloadPtr, off + 4))); // damage / the monster's max health
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, critOff)));
if (damage == 0 || damage > 1_000_000)
@ -779,7 +804,7 @@ internal static class SmartBoxHooks
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0);
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0, attacker ? share : 0);
}
catch
{

View file

@ -0,0 +1,146 @@
// ============================================================================
// RynthCore.Engine - Compatibility/WorldTransitionState.cs
//
// Is the player in a world transition: dead, in portal space (teleporting), or
// within SettleMs after either, or after a landblock JUMP (a teleport, not walking
// into the next landblock)? AC is then tearing objects down and loading new ones,
// and nothing the engine queued for the main thread may run against it.
//
// Seen in a real crash: a client died right after a death recall's landblock
// jump (0x00AE -> 0xA9B4), under GameTickHooks.UseTimeDetour, which runs queued casts
// before AC's tick; a queued SetAutoRun(off) had run 1047 ms late a moment before.
// The engine's own queued work runs inside those ticks, so it is the first
// suspect.
//
// Gate rule for queued game-mutating work (AcMainThreadQueue, at its drains):
// - while in transition, everything is HELD: nothing queued runs;
// - once it ends, work queued at or before the last moment a drain saw the
// transition is DROPPED (casts, selects, uses, moves, appraisals: the plugins
// re-send what they still want), EXCEPT teardown work: stops and cancels (autorun
// off, a motion off, StopMovement, StopCompletely, CancelAttack, a container close),
// which still run, in queue order, as one group. A dropped stop can leave the
// character running or turning, and AcMainThreadQueue never drops stops.
//
// Walking across a landblock boundary is not a transition: it happens constantly in a
// fight, AC streams the neighbour in without tearing the player's world down, and a 5 s
// hold there would stall every border fight.
//
// Pure: AC main thread only (single writer and reader: the UseTime sample and both
// main-thread drains). Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal sealed class WorldTransitionState
{
public const long SettleMs = 5_000;
[Flags]
public enum Edge
{
None = 0,
Died = 1,
Revived = 2,
PortalEntered = 4,
PortalExited = 8,
LandblockJump = 16,
}
private bool _init;
public bool Dead { get; private set; }
public bool Portaling { get; private set; }
public uint Landblock { get; private set; }
public uint PreviousLandblock { get; private set; }
/// <summary>The settle window runs until this TickCount64.</summary>
public long SettleUntilMs { get; private set; }
/// <summary>Last time a gate check saw the transition (0 = never).</summary>
public long LastBlockedMs { get; private set; }
/// <summary>One game-tick sample. Returns the edges crossed (for the lifecycle log).</summary>
public Edge Sample(long nowMs, bool dead, bool portaling, uint landblock)
{
if (!_init)
{
_init = true;
Dead = dead;
Portaling = portaling;
Landblock = landblock;
if (dead || portaling) SettleUntilMs = nowMs + SettleMs;
return Edge.None;
}
Edge edges = Edge.None;
if (dead || portaling || Dead || Portaling)
SettleUntilMs = nowMs + SettleMs;
if (dead != Dead) { edges |= dead ? Edge.Died : Edge.Revived; Dead = dead; }
if (portaling != Portaling) { edges |= portaling ? Edge.PortalEntered : Edge.PortalExited; Portaling = portaling; }
if (landblock != 0 && Landblock != 0 && landblock != Landblock)
{
if (IsJump(Landblock, landblock))
{
edges |= Edge.LandblockJump;
SettleUntilMs = Math.Max(SettleUntilMs, nowMs + SettleMs);
}
}
if (landblock != 0 && landblock != Landblock)
{
PreviousLandblock = Landblock;
Landblock = landblock;
}
return edges;
}
/// <summary>
/// The server's PlayerTeleport message (0xF751) arrived: a teleport begins now, whether or not
/// a tick sample ever sees teleport_in_progress or a landblock jump (a recall into the next
/// landblock shows neither). Starts (or extends) the settle window. Returns false when the
/// window was already running past it.
/// </summary>
public bool OnTeleportMessage(long nowMs)
{
long until = nowMs + SettleMs;
if (until <= SettleUntilMs) return false;
SettleUntilMs = until;
return true;
}
/// <summary>Two landblocks more than one apart on either axis: a teleport, not a walk.</summary>
public static bool IsJump(uint from, uint to)
{
int dx = (int)((to >> 8) & 0xFF) - (int)((from >> 8) & 0xFF);
int dy = (int)(to & 0xFF) - (int)(from & 0xFF);
return Math.Abs(dx) > 1 || Math.Abs(dy) > 1;
}
/// <summary>Dead, portaling, or inside the settle window.</summary>
public bool InTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs;
public enum Verdict { Run, Hold, Drop }
/// <summary>
/// A drain's check for the head of a queue: true = hold everything queued now. Records the
/// moment, so work queued up to here is judged by <see cref="Decide"/> once it ends.
/// </summary>
public bool CheckHolding(long nowMs)
{
if (!InTransition(nowMs)) return false;
LastBlockedMs = nowMs;
return true;
}
/// <summary>
/// What a drain does with one queued item: Hold while in transition; afterwards Drop it
/// if it was queued during the transition (at or before the last held drain) unless it is
/// <paramref name="teardown"/> work, which Runs; anything queued after the transition Runs.
/// </summary>
public Verdict Decide(long nowMs, long queuedAtMs, bool teardown)
{
if (CheckHolding(nowMs)) return Verdict.Hold;
if (LastBlockedMs != 0 && queuedAtMs <= LastBlockedMs)
return teardown ? Verdict.Run : Verdict.Drop;
return Verdict.Run;
}
}

View file

@ -6,6 +6,12 @@
// always-on procdump (which also dumped on every clean exit and every handled
// first-chance AV, so a .dmp's existence never meant a real crash).
//
// Also writes ONE full-memory dump when AC shows its OUT OF MEMORY box
// (MessageBoxHooks): that box is modal, so the process never crashes and Windows
// never writes a dump; the launcher later kills the client as wedged
// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and
// holds no heap, which is what an out-of-memory needs.
//
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
// threads internally while it snapshots them, which is exactly what we want for
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
@ -14,6 +20,7 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine;
@ -46,6 +53,14 @@ internal static class CrashDump
private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData
private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported)
// MiniDumpWithFullMemory (0x2) is as old as MiniDumpNormal, so dbghelp 6.1 takes it.
private const uint DumpTypeFull = 0x00000002 | 0x00000004; // FullMemory + WithHandleData
private const uint DumpTypeFullFallback = 0x00000002; // FullMemory only
// dbghelp is single-threaded: every MiniDumpWriteDump in this process goes through this
// lock, so the hang watchdog's small dump can never run alongside the OOM full dump.
private static readonly object DumpLock = new();
/// <summary>
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
@ -60,40 +75,7 @@ internal static class CrashDump
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None);
bool ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypePreferred, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
int err = ok ? 0 : Marshal.GetLastWin32Error();
// ERROR_INVALID_PARAMETER (87) ⇒ AC's ancient dbghelp 6.1 rejected a flag.
// Retry with bare MiniDumpNormal (universally supported, still has every
// thread stack — what we need to read the deadlock's lock holder).
if (!ok && err == 87)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypeFallback, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: rich flags rejected by AC's old dbghelp 6.1 — wrote bare Normal dump, reason={reason}");
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} reason={reason}");
// Don't leave a 0-byte .dmp behind — it reads as a crash marker
// during triage (observed: hang_17692_20260611_114430.dmp, 0
// bytes, main thread suspended mid-exception-dispatch).
try { fs.Close(); File.Delete(dumpPath); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(dumpPath).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB) reason={reason}");
return true;
return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason);
}
catch (Exception ex)
{
@ -101,4 +83,215 @@ internal static class CrashDump
return false;
}
}
// Writes one dump to <paramref name="path"/>. On ERROR_INVALID_PARAMETER (87: AC's ancient
// dbghelp 6.1 rejected a flag) retries with <paramref name="fallbackType"/>. Never leaves a
// 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed:
// hang_17692_20260611_114430.dmp, 0 bytes, main thread suspended mid-exception-dispatch).
private static bool WriteDumpFile(string path, uint type, uint fallbackType, string reason)
{
lock (DumpLock)
{
bool ok;
int err;
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
type, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (!ok && err == 87 && fallbackType != type)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
fallbackType, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: flags 0x{type:X} rejected by AC's old dbghelp 6.1 - wrote type 0x{fallbackType:X}, reason={reason}");
}
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} type=0x{type:X} reason={reason}");
try { File.Delete(path); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(path).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {path} ({size / 1024}KB) reason={reason}");
return true;
}
}
// -- OUT OF MEMORY full-memory dump --------------------------------------
/// <summary>Full dumps kept in the Dumps folder (a full dump is about the size of the process).</summary>
internal const int OutOfMemoryDumpsKept = 3;
internal const string OutOfMemoryDumpPrefix = "acclient_oom_";
// Longest the showing thread waits for the dump writer before letting the box open anyway.
private const int FullDumpWaitMs = 300_000;
private static int _oomDumpLatch;
private static volatile bool _fullDumpInProgress;
private static volatile string? _fullDumpWrittenPath;
/// <summary>True while the OUT OF MEMORY full dump is being written (the watchdog holds off).</summary>
internal static bool FullDumpInProgress => _fullDumpInProgress;
/// <summary>The OUT OF MEMORY full dump written this session, or null.</summary>
internal static string? FullDumpWrittenPath => _fullDumpWrittenPath;
/// <summary>C:\Games\RynthCore\Dumps by default (beside Logs, under the install folder).</summary>
internal static string OutOfMemoryDumpDirectory => Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps");
/// <summary>
/// Once per process: write a full-memory dump to <see cref="OutOfMemoryDumpDirectory"/>, log
/// its path, and keep only the newest <see cref="OutOfMemoryDumpsKept"/> of these dumps.
/// Called on the thread about to show AC's OUT OF MEMORY box, which waits here until the
/// dump is written (on its own thread, so the showing thread's stack is captured at rest).
/// Never throws.
/// </summary>
internal static void WriteOutOfMemoryDumpOnce(string? reason)
{
if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return;
string why = "AC OUT OF MEMORY box: " + (reason ?? "?");
_fullDumpInProgress = true;
// The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every
// thread, so the log goes silent for the whole dump, which would otherwise read as a dead
// engine and get the client killed mid-dump.
try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); }
catch { }
Thread? writer = null;
try
{
writer = new Thread(() =>
{
// The flag stays up until the writer itself is done, even past a timed-out Join.
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}) { IsBackground = true, Name = "RynthCore.OomDump" };
writer.Start();
}
catch (Exception ex)
{
// No thread to be had (out of memory, after all): write it from this one.
try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { }
writer = null;
}
try
{
if (writer == null)
{
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}
else if (!writer.Join(FullDumpWaitMs))
{
RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going).");
}
}
catch (Exception ex)
{
try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
/// <summary>Log line written before the OUT OF MEMORY full dump starts (read by the launcher).</summary>
internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted;
/// <summary>Log line written once the writer has finished, whatever the outcome.</summary>
internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded;
private static void FinishFullDump()
{
_fullDumpInProgress = false;
try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { }
}
private static void WriteOutOfMemoryDumpCore(string reason)
{
try
{
string dir = OutOfMemoryDumpDirectory;
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason))
{
_fullDumpWrittenPath = path;
RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump: {path}");
// Only after the new dump succeeded: a failed write never costs an older one.
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept);
}
else
{
RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead.");
WriteSelfDump(reason, out _, "oom-small");
}
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in
/// <paramref name="dir"/>. The folder is shared by every client: a dump whose name carries
/// the pid of ANOTHER process that is still running is never deleted (it may still be
/// writing it, or about to report it), and is not counted against <paramref name="keep"/>.
/// Never throws.
/// </summary>
internal static int PruneDumps(string dir, string prefix, int keep)
{
int deleted = 0;
try
{
FileInfo[] files = new DirectoryInfo(dir).GetFiles(prefix + "*.dmp");
Array.Sort(files, (a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc));
int kept = 0;
int self = Environment.ProcessId;
foreach (FileInfo f in files)
{
int pid = DumpPid(f.Name, prefix);
if (pid > 0 && pid != self && IsProcessAlive(pid))
continue; // another live client's dump: not ours to delete
if (kept < Math.Max(0, keep)) { kept++; continue; }
string name = f.Name;
long length = 0;
try { length = f.Length; } catch { }
try
{
f.Delete();
deleted++;
RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB).");
}
catch { /* in use by a debugger, or already gone */ }
}
}
catch { }
return deleted;
}
/// <summary>The pid in "prefix&lt;pid&gt;_...dmp", or 0.</summary>
internal static int DumpPid(string fileName, string prefix)
{
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0;
int start = prefix.Length, end = start;
while (end < fileName.Length && char.IsDigit(fileName[end])) end++;
return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0;
}
private static bool IsProcessAlive(int pid)
{
try
{
using var p = System.Diagnostics.Process.GetProcessById(pid);
return !p.HasExited;
}
catch
{
return false;
}
}
}

View file

@ -458,6 +458,11 @@ internal static class EndSceneHook
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
}
// ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub)
// is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene;
// guarded internally, so an ImGui draw failure can't skip the original EndScene.
EngineFrameController.RenderDeferredImGui();
}
catch (Exception ex)
{

View file

@ -164,11 +164,13 @@ internal static class EngineLifecycle
// → AC chat box stops receiving input after a reload). Idempotent —
// no-ops if Init never ran or the ImGui path already tore it down.
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
Step("HotkeyService.Shutdown", () => Hotkeys.HotkeyService.Shutdown());
// Stop the dispatch-file watcher and the auto-ID drain timer before the
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.

View file

@ -12,6 +12,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Collections.Generic;
using ImGuiNET;
using RynthCore;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
@ -45,7 +46,21 @@ public static class EntryPoint
private static readonly Queue<string> RecentLogLines = new();
private static long _recentLogSeq;
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
internal enum EngineLogLevel
{
/// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary>
Off = -1,
Error = 0,
Warning = 1,
Info = 2,
Debug = 3,
Trace = 4
}
/// <summary>Active engine logging threshold loaded from engine settings.</summary>
internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
/// <summary>Legacy convenience flag used by existing verbose call sites.</summary>
internal static bool VerboseLogging = false;
/// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
@ -190,8 +205,14 @@ public static class EntryPoint
}
catch { }
// engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold
// and per-category levels first so every line written below honours them. The watcher
// started later re-reads them whenever the launcher edits the file.
string logSummary = LogSettings.Reload();
// Set up the unified log sink BEFORE anything else so all
// subsequent failures are captured in C:\Games\RynthCore\Logs.
// subsequent failures are captured in <CoreDir>\Logs (installer-chosen;
// resolved here on the init worker, never under the loader lock).
LogPaths.EnsureLogDirectory();
if (_initCount <= 1)
{
@ -206,10 +227,18 @@ public static class EntryPoint
InstallManagedExceptionHandlers();
RynthLog.Info("================================================================");
RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}");
RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}");
RynthLog.Info("================================================================");
// The banner bypasses the category levels: it must be in every log, whatever engine.json says.
LogTagged("engine", "================================================================", "INF");
LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF");
LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF");
LogTagged("engine", $" logging {logSummary}", "INF");
LogTagged("engine", "================================================================", "INF");
string hiddenCategories = LogSettings.HiddenCategoriesWarning();
if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories);
// Live logging config: launcher edits to engine.json apply without a client restart.
// Stopped in EngineLifecycle.Shutdown before the module can be unloaded.
LogSettings.StartWatcher();
CrashLogger.Install();
@ -217,18 +246,10 @@ public static class EntryPoint
// logging AC's main-thread native stack when its EndScene beat stalls.
MainThreadHangWatchdog.Start();
// MultiClientHooks.Initialize installs MinHook detours synchronously
// here, BEFORE InitWorker spawns and runs the main PreloadNativeDll
// pass. If we don't preload minhook.x86.dll first, the P/Invoke
// into minhook fails with DllNotFoundException and the multi-
// client hook silently skips — which means AC's
// Client::IsAlreadyRunning check fires unpatched on the second-
// and-later concurrent acclient.exe processes.
string? earlyEngineDir = GetEngineDirectory();
if (!string.IsNullOrEmpty(earlyEngineDir))
PreloadNativeDll(earlyEngineDir, "minhook.x86.dll");
else
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
// MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
// minhook.x86.dll before InitWorker runs, so preload it from the engine directory;
// otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients.
TryPreloadMinHookForEarlyInit();
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock
@ -339,6 +360,33 @@ public static class EntryPoint
return new string(buffer, 0, (int)length);
}
/// <summary>
/// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can
/// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path
/// (which often resolves against the AC client directory, not <c>Runtime\</c>).
/// </summary>
private static void TryPreloadMinHookForEarlyInit()
{
try
{
string? engineDir = GetEngineDirectory();
if (string.IsNullOrEmpty(engineDir))
{
RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory.");
return;
}
if (PreloadNativeDll(engineDir, "minhook.x86.dll"))
RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})");
else
RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir}).");
}
catch (Exception ex)
{
RynthLog.Info($"Early MinHook preload exception: {ex.Message}");
}
}
/// <summary>
/// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a
/// stable pointer inside the engine's own module image — used by
@ -518,6 +566,44 @@ public static class EntryPoint
/// (RynthAi/RynthChat/RynthVision) on the user's launcher selection.
/// Filename match (not full-path) so users can keep the DLL anywhere.
/// </summary>
private static bool _serverMenusRegistered;
/// <summary>
/// The server sections of the Char and Mini Remote menus (UI.ServerMenus): each server once,
/// then the items of the installed plugins that have windows for it. A server whose plugins
/// are all missing gets no items, so its section never shows.
/// </summary>
private static void RegisterServerMenus(bool rynthAi, bool rynthIlt)
{
if (_serverMenusRegistered) return;
_serverMenusRegistered = true;
// Infinite Leaftide: IltInfo (host / world name lists, or "/rc ilt on" for the session).
UI.ServerMenus.DefineServer("ilt", "Infinite Leaftide", static () => IltInfo.IsIlt, "/rc ilt on");
if (rynthAi)
{
// RynthAi's ILT features: the Mini Remote's ILT tabs (shown once the server reports each
// on). Its Quests and Pets tabs are universal: the Character half of the menus.
foreach ((string label, string tab) in new[]
{
("Character", "character"), ("Banking", "banking"), ("Gear", "gear"), ("Charms", "charms"), ("Games", "games"),
})
{
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem(label, "/rc miniremote tab " + tab,
$"The Mini Remote's {label} tab (RynthAi).", "tab:" + tab));
}
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Guardian", "/rc guardian toggle",
"Temple of Enlightenment guardians: riddle answers and Give (RynthAi)."));
}
if (rynthIlt)
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Bounties", "/rc bounties toggle",
"ACECustom bounties and your progress on each (RynthILT)."));
if (rynthAi)
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Progression", "/rc progression",
"XP planner, augmentations and enlightenment (the Skills panel's Progression tab)."));
UI.ServerMenus.PushToRynthAi = rynthAi;
}
private static bool HasPluginDll(string dllFileName)
{
var paths = Plugins.EngineSettings.PluginPaths;
@ -695,6 +781,8 @@ public static class EntryPoint
Step("account hooks", AccountHooks.Initialize);
Step("client combat hooks", () => ClientCombatHooks.Probe());
Step("selected-target hooks", SelectedTargetHooks.Initialize);
// Which item AC is dragging (AC keeps the old selection during a drag).
Step("drag-start hook", DragDropHooks.Initialize);
Step("smartbox hooks", SmartBoxHooks.Initialize);
Step("player vitals hooks", PlayerVitalsHooks.Initialize);
Step("enchantment hooks", () => EnchantmentHooks.Initialize());
@ -993,10 +1081,16 @@ public static class EntryPoint
ImGuiBackend.Panels.VisionFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
ImGuiBackend.Panels.RynthNavFace.Register();
// The ILT section (Infinite Leaftide): its faces exist only with RynthILT
// installed, and the bar's ILT button shows them only on ILT (IltInfo).
// Characters (your other RynthCore clients, through RynthNet): only with RynthNet installed.
if (HasPluginDll("RynthCore.Plugin.RynthNet.dll"))
ImGuiBackend.Panels.CharactersFace.Register();
// The ILT section (Infinite Leaftide): each face exists only with its plugin
// installed (Bounties: RynthILT, Guardian: RynthAi), and the bar's ILT button
// shows them only on ILT (IltInfo).
if (HasPluginDll("RynthCore.Plugin.RynthILT.dll"))
ImGuiBackend.Panels.BountiesFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
ImGuiBackend.Panels.GuardianFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
ImGuiBackend.Panels.ChatFace.Register();
@ -1021,6 +1115,7 @@ public static class EntryPoint
// RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded.
RynthAiDashboardState.EnsureLoaded();
}
RegisterServerMenus(HasPluginDll("RynthCore.Plugin.RynthAi.dll"), HasPluginDll("RynthCore.Plugin.RynthILT.dll"));
if (trackerPresent)
TrackerSettings.EnsureLoaded();
// Hide the docked Avalonia bar before it is built if the ImGui bar stands in.
@ -1686,10 +1781,34 @@ public static class EntryPoint
internal static void LogVerbose(string message)
{
if (VerboseLogging)
if (ShouldLog(EngineLogLevel.Debug))
Log(message);
}
/// <summary>
/// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines
/// never pass; an Off threshold blocks everything (errors bypass this gate).
/// </summary>
internal static bool ShouldLog(EngineLogLevel level)
=> level != EngineLogLevel.Off && level <= LoggingLevel;
/// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary>
internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
{
if (string.IsNullOrWhiteSpace(configuredLevel))
return EngineLogLevel.Info;
string normalized = configuredLevel.Trim();
if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Debug;
if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Warning;
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
? parsed
: EngineLogLevel.Info;
}
internal static string[] GetRecentLogLines()
{
lock (LogLock)

View file

@ -0,0 +1,709 @@
// ============================================================================
// RynthCore.Engine - Hotkeys/HotkeyModel.cs
//
// User hotkeys (Settings > Hotkeys, /rc hotkey): a key with Ctrl/Alt/Shift runs
// a built-in action (start/stop the macro, toggle Combat, open a panel...) or any
// chat command ("/ra start", "/rn bc /ra stop", "/lua myscript go").
//
// This file is the pure part, with no engine dependencies, so tools/HotkeyTests
// compiles it as is: key names and combo parsing/formatting, the built-in action
// list, matching a key press against the bindings (exact modifiers, key-down edge
// only), the "is the player typing" rule, conflict warnings, the /rc hotkey
// argument parser and the per-PC file (%LOCALAPPDATA%\RynthCore\hotkeys.txt).
// The engine side (key messages, running actions, the Settings section) is
// Hotkeys/HotkeyService.cs and ImGui/Panels/HotkeysSettingsUi.cs.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace RynthCore.Engine.Hotkeys;
[Flags]
internal enum HotkeyMods
{
None = 0,
Ctrl = 1,
Alt = 2,
Shift = 4,
}
/// <summary>A key (Win32 virtual-key code) and the modifiers held with it.</summary>
internal readonly record struct KeyCombo(int Vk, HotkeyMods Mods)
{
public bool IsEmpty => Vk == 0;
public override string ToString() => HotkeyKeys.Format(this);
}
/// <summary>Key names, and combo text ("Ctrl+Shift+F1") both ways.</summary>
internal static class HotkeyKeys
{
public const int VK_BACK = 0x08, VK_TAB = 0x09, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11,
VK_MENU = 0x12, VK_PAUSE = 0x13, VK_ESCAPE = 0x1B, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22,
VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28,
VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D,
VK_NUMPAD0 = 0x60, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E,
VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F12 = 0x7B, VK_F24 = 0x87, VK_SCROLL = 0x91,
VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5,
VK_OEM_3 = 0xC0;
private static readonly Dictionary<int, string> NameByVk = BuildNames();
private static readonly Dictionary<string, int> VkByName = BuildLookup();
private static Dictionary<int, string> BuildNames()
{
var n = new Dictionary<int, string>();
for (int c = 'A'; c <= 'Z'; c++) n[c] = ((char)c).ToString();
for (int c = '0'; c <= '9'; c++) n[c] = ((char)c).ToString();
for (int i = 0; i < 24; i++) n[VK_F1 + i] = "F" + (i + 1);
for (int i = 0; i < 10; i++) n[VK_NUMPAD0 + i] = "Num" + i;
n[VK_MULTIPLY] = "Num*"; n[VK_ADD] = "Num+"; n[VK_SUBTRACT] = "Num-"; n[VK_DECIMAL] = "Num."; n[VK_DIVIDE] = "Num/";
n[VK_BACK] = "Backspace"; n[VK_TAB] = "Tab"; n[VK_RETURN] = "Enter"; n[VK_PAUSE] = "Pause";
n[VK_ESCAPE] = "Esc"; n[VK_SPACE] = "Space";
n[VK_PRIOR] = "PageUp"; n[VK_NEXT] = "PageDown"; n[VK_END] = "End"; n[VK_HOME] = "Home";
n[VK_LEFT] = "Left"; n[VK_UP] = "Up"; n[VK_RIGHT] = "Right"; n[VK_DOWN] = "Down";
n[VK_INSERT] = "Insert"; n[VK_DELETE] = "Delete"; n[VK_SCROLL] = "ScrollLock";
// US-layout punctuation (the OEM keys keep their codes on other layouts; the name is the US one).
n[0xBA] = ";"; n[0xBB] = "="; n[0xBC] = ","; n[0xBD] = "-"; n[0xBE] = "."; n[0xBF] = "/";
n[VK_OEM_3] = "`"; n[0xDB] = "["; n[0xDC] = "\\"; n[0xDD] = "]"; n[0xDE] = "'";
return n;
}
private static Dictionary<string, int> BuildLookup()
{
var d = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in NameByVk) d[kv.Value] = kv.Key;
void Alias(string name, int vk) => d[name] = vk;
Alias("PgUp", VK_PRIOR); Alias("PgDn", VK_NEXT); Alias("PageDn", VK_NEXT);
Alias("Ins", VK_INSERT); Alias("Del", VK_DELETE); Alias("Escape", VK_ESCAPE);
Alias("Return", VK_RETURN); Alias("Spacebar", VK_SPACE); Alias("Back", VK_BACK);
Alias("Plus", 0xBB); Alias("Equals", 0xBB); Alias("Minus", 0xBD); Alias("Comma", 0xBC);
Alias("Period", 0xBE); Alias("Slash", 0xBF); Alias("Backslash", 0xDC); Alias("Semicolon", 0xBA);
Alias("Quote", 0xDE); Alias("Apostrophe", 0xDE); Alias("Backtick", VK_OEM_3); Alias("Grave", VK_OEM_3);
Alias("Tilde", VK_OEM_3); Alias("LBracket", 0xDB); Alias("RBracket", 0xDD);
Alias("NumMultiply", VK_MULTIPLY); Alias("NumAdd", VK_ADD); Alias("NumPlus", VK_ADD);
Alias("NumSubtract", VK_SUBTRACT); Alias("NumMinus", VK_SUBTRACT); Alias("NumDecimal", VK_DECIMAL);
Alias("NumDivide", VK_DIVIDE); Alias("Scroll", VK_SCROLL);
for (int i = 0; i < 10; i++) { Alias("Numpad" + i, VK_NUMPAD0 + i); Alias("Kp" + i, VK_NUMPAD0 + i); }
return d;
}
/// <summary>The key's name ("F1", "Num5", "PageUp", ";"), or "Key 0x.." for one without a name.</summary>
public static string KeyName(int vk) => NameByVk.TryGetValue(vk, out string? n) ? n : $"Key 0x{vk:X2}";
/// <summary>Shift, Ctrl, Alt (either side) and the Windows keys: held with a key, never bound alone.</summary>
public static bool IsModifierKey(int vk) =>
vk is VK_SHIFT or VK_CONTROL or VK_MENU or VK_LSHIFT or VK_RSHIFT or VK_LCONTROL or VK_RCONTROL
or VK_LMENU or VK_RMENU or VK_LWIN or VK_RWIN or VK_APPS;
/// <summary>A key a hotkey may use: any named key except Esc (it cancels and closes things).</summary>
public static bool IsBindable(int vk) => vk != VK_ESCAPE && NameByVk.ContainsKey(vk);
public static bool IsFunctionKey(int vk) => vk >= VK_F1 && vk <= VK_F24;
public static string Format(KeyCombo c)
{
if (c.IsEmpty) return "(none)";
var sb = new StringBuilder();
if ((c.Mods & HotkeyMods.Ctrl) != 0) sb.Append("Ctrl+");
if ((c.Mods & HotkeyMods.Alt) != 0) sb.Append("Alt+");
if ((c.Mods & HotkeyMods.Shift) != 0) sb.Append("Shift+");
sb.Append(KeyName(c.Vk));
return sb.ToString();
}
/// <summary>
/// "Ctrl+Shift+F1", "alt+num+", "Shift + PgDn" (spaces and case don't matter). Modifiers come
/// first, each followed by '+'; what's left is the key's name.
/// </summary>
public static bool TryParse(string? text, out KeyCombo combo, out string error)
{
combo = default;
error = string.Empty;
string s = (text ?? string.Empty).Replace(" ", string.Empty).Replace("\t", string.Empty);
if (s.Length == 0) { error = "No key given."; return false; }
HotkeyMods mods = HotkeyMods.None;
while (true)
{
int plus = s.IndexOf('+');
if (plus <= 0 || plus == s.Length - 1) break; // no modifier left ("+" alone or at the end is a key)
HotkeyMods m = s[..plus].ToLowerInvariant() switch
{
"ctrl" or "control" or "ctl" => HotkeyMods.Ctrl,
"alt" => HotkeyMods.Alt,
"shift" => HotkeyMods.Shift,
_ => HotkeyMods.None,
};
if (m == HotkeyMods.None) break;
mods |= m;
s = s[(plus + 1)..];
}
if (s.ToLowerInvariant() is "ctrl" or "control" or "alt" or "shift")
{
error = "A modifier alone can't be a hotkey; add a key (e.g. Ctrl+F1).";
return false;
}
if (!VkByName.TryGetValue(s, out int vk))
{
error = $"Unknown key '{s}'. Keys: A-Z, 0-9, F1-F24, Num0-Num9, Num* Num+ Num- Num. Num/, " +
"Home End PageUp PageDown Insert Delete, Up Down Left Right, Space Tab Enter Backspace, ; = , - . / ` [ \\ ] '.";
return false;
}
if (vk == VK_ESCAPE)
{
error = "Esc can't be a hotkey (it cancels and closes things).";
return false;
}
combo = new KeyCombo(vk, mods);
return true;
}
}
/// <summary>
/// A built-in action. <see cref="Panel"/>: the panel title it opens/closes, for panel actions.
/// <see cref="Chat"/>: the chat command it runs ("/ra targetlock"); "{0}" is the binding's parameter
/// (<see cref="HotkeyBinding.Command"/>), for an action with a <see cref="Param"/> (e.g. the meta state).
/// <see cref="Group"/>: the dropdown section ("" = the RynthCore built-ins). <see cref="Tip"/>: a plain tooltip.
/// </summary>
internal sealed record HotkeyAction(string Id, string Name, string? Panel = null, string? Chat = null,
string Group = "", string Tip = "", string? Param = null)
{
public bool HasParam => Param != null;
}
internal static class HotkeyActions
{
/// <summary>The action id of a binding that runs <see cref="HotkeyBinding.Command"/> as a chat command.</summary>
public const string Command = "command";
public const string PanelPrefix = "panel:";
public const string VTankPrefix = "vt:";
public const string VTankGroup = "VTank-style";
/// <summary>The parameterized "Meta: set state" action (its binding's Command is the state name).</summary>
public const string MetaStateId = VTankPrefix + "metastate";
private static HotkeyAction V(string id, string name, string tip, string? chat = null, string? param = null) =>
new(VTankPrefix + id, name, Chat: chat, Group: VTankGroup, Tip: tip, Param: param);
private static HotkeyAction P(string title, string? name = null) =>
new(PanelPrefix + title, "Open/close " + (name ?? title), title);
/// <summary>Built-ins, in the order the Settings dropdown shows them.</summary>
public static readonly HotkeyAction[] BuiltIns =
{
new("macro", "Start/stop the macro"),
new("combat", "Toggle Combat"),
new("buffing", "Toggle Buffing"),
new("navigation", "Toggle Navigation"),
new("looting", "Toggle Looting"),
new("meta", "Toggle Meta"),
new("forcerebuff", "Force rebuff"),
new("patrol", "Start dungeon patrol"),
new("autosort", "Toggle auto-sort (RynthSort)"),
new("reload", "Reload the engine"),
P("RynthAi", "the RynthAi dashboard"),
P("Radar"),
P("Dungeon Map"),
P("Inventory"),
P("Items"),
P("Settings"),
P("Characters"),
P("Chat"),
P("Meta", "the Meta editor"),
P("Nav", "the Nav editor"),
P("Lua"),
P("Damage"),
P("Mini Remote"),
P("Skills"),
P("Vision"),
P("Sense"),
P("Item Count"),
P("Loot Editor"),
P("RynthNav"),
// VTank's hotkey actions, by VTank's names. Those RynthCore already had run the same code
// as the built-ins above; the rest run a RynthAi /ra command (also usable as a chat command).
V("metastate", "Meta: set state...", "Switches the meta to the state you pick (/ra setmetastate <state>).",
"/ra setmetastate {0}", param: "State"),
V("startstop", "Start/Stop", "Starts or stops the macro."),
V("targetlock", "Target lock", "Makes the macro attack the monster you have selected, ahead of everything else. " +
"Press it again on the same monster to let go (/ra targetlock).", "/ra targetlock"),
V("navigation", "Navigation", "Turns Navigation on or off."),
V("looting", "Looting", "Turns Looting on or off."),
V("combat", "Combat", "Turns Combat on or off."),
V("buffing", "Buffing", "Turns Buffing on or off."),
V("forcebuff", "Force buff", "Recasts every buff now, whatever time is left."),
V("cancelforcebuff", "Cancel force buff", "Stops a force buff in progress."),
V("meleelow", "MeleeLow", "Melee attacks go low (/ra meleelow).", "/ra meleelow"),
V("meleemid", "MeleeMid", "Melee attacks go to the middle (/ra meleemid).", "/ra meleemid"),
V("meleehigh", "MeleeHigh", "Melee attacks go high (/ra meleehigh).", "/ra meleehigh"),
V("navaddpt", "NavAddPt", "Adds a waypoint where you stand to the loaded route (/ra navaddpt).", "/ra navaddpt"),
V("testitem", "TestItem", "Checks the selected item against your loot profile and says what it would do (/ra testitem).", "/ra testitem"),
V("propertydump", "PropertyDump", "Lists every property of the selected object in chat (/ra propertydump).", "/ra propertydump"),
V("recharge", "Recharge", "One heal, stamina or mana top-off now, using your Top Off settings, " +
"even with the macro stopped (/ra recharge).", "/ra recharge"),
V("navprio", "NavPrio", "Turns Boost Nav Priority on or off (/ra navprio).", "/ra navprio"),
V("lootprio", "LootPrio", "Turns Boost Loot Priority on or off (/ra lootprio).", "/ra lootprio"),
V("navlootprio", "NavLootPrio", "Turns Boost Nav Priority and Boost Loot Priority on together, or both off " +
"when both are on (/ra navlootprio).", "/ra navlootprio"),
V("lootthiscont", "LootThisCont", "Loots the corpse or chest you have open now, even one the macro would skip. " +
"Never house storage or your own packs (/ra lootthis).", "/ra lootthis"),
};
/// <summary>The chat command a <see cref="HotkeyAction.Chat"/> action runs for this binding (its parameter filled in).</summary>
public static string ChatFor(HotkeyAction a, HotkeyBinding b) =>
a.Chat == null ? string.Empty : a.Chat.Replace("{0}", b.Command.Trim()).Trim();
private static string Norm(string s)
{
var sb = new StringBuilder(s.Length);
foreach (char c in s)
if (!char.IsWhiteSpace(c) && c != '-' && c != '_') sb.Append(char.ToLowerInvariant(c));
return sb.ToString();
}
/// <summary>A built-in by id ("combat", "panel:Dungeon Map"), loosely ("panel dungeonmap", "dungeon map",
/// "Toggle Combat"); null if none.</summary>
public static HotkeyAction? Resolve(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
string t = text.Trim();
if (t.StartsWith("panel ", StringComparison.OrdinalIgnoreCase)) t = PanelPrefix + t[6..];
string n = Norm(t);
foreach (HotkeyAction a in BuiltIns)
if (Norm(a.Id) == n || Norm(a.Name) == n) return a;
foreach (HotkeyAction a in BuiltIns) // a panel's title alone
if (a.Panel != null && Norm(a.Panel) == n) return a;
foreach (HotkeyAction a in BuiltIns) // a VTank-style id without "vt:" ("startstop", "targetlock")
if (a.Group == VTankGroup && Norm(a.Id) == VTankPrefix + n) return a;
return null;
}
public static HotkeyAction? Find(string id)
{
foreach (HotkeyAction a in BuiltIns)
if (string.Equals(a.Id, id, StringComparison.OrdinalIgnoreCase)) return a;
return null;
}
/// <summary>What the binding does, for lists ("Toggle Combat", "Chat: /ra start", "Meta: Hunting").</summary>
public static string Describe(HotkeyBinding b)
{
if (string.Equals(b.Action, Command, StringComparison.OrdinalIgnoreCase))
return b.Command.Length > 0 ? "Chat: " + b.Command : "Chat: (no command)";
HotkeyAction? a = Find(b.Action);
if (a == null) return $"Unknown action '{b.Action}'";
string param = b.Command.Trim();
if (string.Equals(a.Id, MetaStateId, StringComparison.OrdinalIgnoreCase))
return param.Length > 0 ? "Meta: " + param : "Meta: (no state)";
if (a.HasParam) return param.Length > 0 ? $"{a.Name} {param}" : $"{a.Name} (no {a.Param!.ToLowerInvariant()})";
return a.Group.Length > 0 ? $"{a.Name} ({a.Group})" : a.Name;
}
/// <summary>
/// An action that takes a parameter, and the text after it: "metastate Hunting" or "vt:metastate
/// Hunting" -> (Meta: set state, "Hunting"). Null if the text doesn't start with one.
/// </summary>
public static (HotkeyAction Action, string Param)? ResolveWithParam(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
string t = text.Trim();
for (int sp = t.IndexOf(' '); sp > 0; sp = t.IndexOf(' ', sp + 1))
{
string head = t[..sp];
if (Resolve(head) is { HasParam: true } a) return (a, t[(sp + 1)..].Trim());
}
return null;
}
}
/// <summary>One hotkey: the combo, a built-in action id or <see cref="HotkeyActions.Command"/>, and its chat command.</summary>
internal sealed record HotkeyBinding(KeyCombo Combo, string Action, string Command = "", bool Enabled = true)
{
public bool IsCommand => string.Equals(Action, HotkeyActions.Command, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Turning a key message into a combo and finding its binding.</summary>
internal static class HotkeyMatch
{
/// <summary>
/// WM_KEYDOWN / WM_SYSKEYDOWN lParam bit 30 is the key's previous state: set on auto-repeat.
/// A hotkey fires on the first key-down only, never on repeats.
/// </summary>
public static bool IsFreshPress(long lParam) => (lParam & 0x40000000) == 0;
/// <summary>lParam bit 24: an extended key (numpad Enter, the arrow/navigation block).</summary>
public static bool IsExtended(long lParam) => (lParam & 0x01000000) != 0;
/// <summary>
/// The virtual key a binding is matched on: left/right modifiers fold into Shift/Ctrl/Alt, and
/// numpad Enter (extended Return) gives 0: AC keeps it for its own functions, as the chat code does.
/// </summary>
public static int NormalizeVk(int vk, bool extended)
{
if (vk == HotkeyKeys.VK_RETURN && extended) return 0;
return vk switch
{
HotkeyKeys.VK_LSHIFT or HotkeyKeys.VK_RSHIFT => HotkeyKeys.VK_SHIFT,
HotkeyKeys.VK_LCONTROL or HotkeyKeys.VK_RCONTROL => HotkeyKeys.VK_CONTROL,
HotkeyKeys.VK_LMENU or HotkeyKeys.VK_RMENU => HotkeyKeys.VK_MENU,
_ => vk,
};
}
public static HotkeyMods Mods(bool ctrl, bool alt, bool shift) =>
(ctrl ? HotkeyMods.Ctrl : 0) | (alt ? HotkeyMods.Alt : 0) | (shift ? HotkeyMods.Shift : 0);
/// <summary>The first enabled binding for exactly this key and these modifiers (Ctrl+F1 doesn't fire on Ctrl+Shift+F1).</summary>
public static HotkeyBinding? Find(IReadOnlyList<HotkeyBinding> bindings, KeyCombo pressed)
{
if (pressed.IsEmpty) return null;
foreach (HotkeyBinding b in bindings)
if (b.Enabled && b.Combo == pressed) return b;
return null;
}
}
/// <summary>What the engine knows when a key goes down.</summary>
/// <param name="InWorld">A character is in the world (not at character select).</param>
/// <param name="GameFocused">The foreground window is this client's (the game or one of our windows).</param>
/// <param name="RynthTextFocus">A RynthCore text box has the keyboard: RynthChat's input, an ImGui text
/// field (io.WantTextInput), a popped-out panel's text box, an Avalonia text box.</param>
/// <param name="AcTextFocus">AC's own UI has a keyboard focus element (its chat entry being typed in, a
/// quantity box...): true / false, or null when AC's UI manager isn't readable.</param>
internal readonly record struct TypingState(bool InWorld, bool GameFocused, bool RynthTextFocus, bool? AcTextFocus);
internal enum HotkeyGate
{
Fire,
NotInWorld,
NotFocused,
RynthTyping,
AcTyping,
/// <summary>AC's focus is unknown and the key could be typing (no Ctrl/Alt, not an F key).</summary>
AcUnknownTextKey,
}
internal static class HotkeyRules
{
/// <summary>
/// Whether a bound key may fire. Never while the player is typing: in a RynthCore text box or in
/// AC's own chat entry. When AC's focus can't be read, only keys that can't be typing fire.
/// </summary>
public static HotkeyGate Check(in TypingState s, KeyCombo combo)
{
if (!s.InWorld) return HotkeyGate.NotInWorld;
if (!s.GameFocused) return HotkeyGate.NotFocused;
if (s.RynthTextFocus) return HotkeyGate.RynthTyping;
if (s.AcTextFocus == true) return HotkeyGate.AcTyping;
if (s.AcTextFocus == null && !CantBeTyping(combo)) return HotkeyGate.AcUnknownTextKey;
return HotkeyGate.Fire;
}
/// <summary>Ctrl or Alt held, or an F key: a combo no text box takes as typing.</summary>
public static bool CantBeTyping(KeyCombo c) =>
(c.Mods & (HotkeyMods.Ctrl | HotkeyMods.Alt)) != 0 || HotkeyKeys.IsFunctionKey(c.Vk);
public static string Describe(HotkeyGate g) => g switch
{
HotkeyGate.Fire => "hotkeys fire",
HotkeyGate.NotInWorld => "not in the world",
HotkeyGate.NotFocused => "the game window isn't focused",
HotkeyGate.RynthTyping => "typing in a RynthCore text box",
HotkeyGate.AcTyping => "typing in AC's chat (or another AC text box)",
HotkeyGate.AcUnknownTextKey => "AC's typing state is unknown; only Ctrl/Alt/F-key hotkeys fire",
_ => g.ToString(),
};
}
/// <summary>Warnings for a combo: bound twice, or one AC itself uses. Warnings only; the binding is allowed.</summary>
internal static class HotkeyConflicts
{
/// <summary>Why AC may want this key itself (null if it's not a common AC key).</summary>
public static string? CommonAcKey(KeyCombo c)
{
bool ctrlAlt = (c.Mods & (HotkeyMods.Ctrl | HotkeyMods.Alt)) != 0;
if (ctrlAlt) return null;
bool shift = (c.Mods & HotkeyMods.Shift) != 0;
int vk = c.Vk;
// Movement: with or without Shift (Shift switches walk/run while held).
if (vk is 'W' or 'A' or 'S' or 'D' or 'Q' or 'E' or 'Z' or 'X' or 'C'
or HotkeyKeys.VK_UP or HotkeyKeys.VK_DOWN or HotkeyKeys.VK_LEFT or HotkeyKeys.VK_RIGHT)
return "AC moves your character with it";
if (shift) return null;
if (vk == HotkeyKeys.VK_SPACE) return "AC jumps with it";
if (vk == HotkeyKeys.VK_RETURN) return "AC opens its chat with it";
if (vk is >= '0' and <= '9') return "AC's shortcut bar uses the number keys";
if (vk is HotkeyKeys.VK_TAB or HotkeyKeys.VK_BACK or HotkeyKeys.VK_OEM_3 or HotkeyKeys.VK_HOME
or HotkeyKeys.VK_END or HotkeyKeys.VK_PRIOR or HotkeyKeys.VK_NEXT or HotkeyKeys.VK_INSERT or HotkeyKeys.VK_DELETE)
return "AC's default keymap uses it";
return null;
}
/// <summary>
/// Every warning for giving <paramref name="combo"/> to a binding. <paramref name="ignoreIndex"/>: the
/// binding being edited (it doesn't conflict with itself).
/// </summary>
public static List<string> Warnings(IReadOnlyList<HotkeyBinding> bindings, KeyCombo combo, int ignoreIndex = -1)
{
var list = new List<string>();
if (combo.IsEmpty) return list;
for (int i = 0; i < bindings.Count; i++)
{
if (i == ignoreIndex || bindings[i].Combo != combo) continue;
bool firstWins = ignoreIndex < 0 ? true : i < ignoreIndex;
list.Add($"{combo} is also bound to \"{HotkeyActions.Describe(bindings[i])}\"" +
(bindings[i].Enabled ? (firstWins ? " (that one fires, it's higher in the list)." : " (this one fires, it's higher in the list).")
: " (switched off)."));
}
if (CommonAcKey(combo) is { } why)
list.Add($"{combo}: {why}. While the hotkey is on, AC won't get that key.");
return list;
}
/// <summary>Indexes of enabled bindings that share their combo with an earlier enabled one (they never fire).</summary>
public static List<int> Shadowed(IReadOnlyList<HotkeyBinding> bindings)
{
var seen = new HashSet<KeyCombo>();
var shadowed = new List<int>();
for (int i = 0; i < bindings.Count; i++)
{
if (!bindings[i].Enabled) continue;
if (!seen.Add(bindings[i].Combo)) shadowed.Add(i);
}
return shadowed;
}
}
internal enum HotkeyVerb { Help, List, Actions, Status, Add, Remove, Enable, Disable, On, Off, Error }
/// <summary>A parsed "/rc hotkey ..." line.</summary>
internal sealed record HotkeyCommand(HotkeyVerb Verb, KeyCombo Combo = default, string Action = "", string ChatCommand = "",
string Error = "");
internal static class HotkeyCommandParser
{
public const string Usage =
"Usage: /rc hotkey list | add <combo> <action or /command> | remove <combo> | enable|disable <combo> | " +
"actions | status | on|off. Combo e.g. F5, Ctrl+1, Alt+Shift+Num3. /rc hotkeys opens Settings > Hotkeys.";
/// <summary>Parses the arguments after "/rc hotkey".</summary>
public static HotkeyCommand Parse(string? args)
{
string a = (args ?? string.Empty).Trim();
if (a.Length == 0) return new HotkeyCommand(HotkeyVerb.Help);
int sp = a.IndexOf(' ');
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
switch (verb)
{
case "help": case "?": return new HotkeyCommand(HotkeyVerb.Help);
case "list": case "ls": return new HotkeyCommand(HotkeyVerb.List);
case "actions": return new HotkeyCommand(HotkeyVerb.Actions);
case "status": return new HotkeyCommand(HotkeyVerb.Status);
case "on": return rest.Length == 0 ? new HotkeyCommand(HotkeyVerb.On) : WithCombo(HotkeyVerb.Enable, rest);
case "off": return rest.Length == 0 ? new HotkeyCommand(HotkeyVerb.Off) : WithCombo(HotkeyVerb.Disable, rest);
case "remove": case "rm": case "del": case "delete": return WithCombo(HotkeyVerb.Remove, rest);
case "enable": return WithCombo(HotkeyVerb.Enable, rest);
case "disable": return WithCombo(HotkeyVerb.Disable, rest);
case "add": case "bind": case "set": return ParseAdd(rest);
default: return Fail($"Unknown '/rc hotkey {verb}'. {Usage}");
}
}
private static HotkeyCommand WithCombo(HotkeyVerb verb, string rest)
{
if (rest.Length == 0) return Fail($"Which key? e.g. /rc hotkey {verb.ToString().ToLowerInvariant()} Ctrl+F1");
return HotkeyKeys.TryParse(rest, out KeyCombo combo, out string err) ? new HotkeyCommand(verb, combo) : Fail(err);
}
private static HotkeyCommand ParseAdd(string rest)
{
// The combo is one word (no spaces inside: "Ctrl+Shift+F1"); the rest is the action.
int sp = rest.IndexOf(' ');
if (rest.Length == 0 || sp < 0)
return Fail("Usage: /rc hotkey add <combo> <action or /command>, e.g. /rc hotkey add F5 macro or /rc hotkey add Ctrl+F1 /ra start");
string comboText = rest[..sp];
string what = rest[(sp + 1)..].Trim();
if (!HotkeyKeys.TryParse(comboText, out KeyCombo combo, out string err)) return Fail(err);
if (what.StartsWith('/'))
return new HotkeyCommand(HotkeyVerb.Add, combo, HotkeyActions.Command, what);
HotkeyAction? action = HotkeyActions.Resolve(what);
if (action == null && HotkeyActions.ResolveWithParam(what) is { } withParam)
{
if (withParam.Param.Length == 0)
return Fail($"'{withParam.Action.Name}' needs a {withParam.Action.Param!.ToLowerInvariant()}.");
return new HotkeyCommand(HotkeyVerb.Add, combo, withParam.Action.Id, withParam.Param);
}
if (action is { HasParam: true })
return Fail($"'{action.Name}' needs a {action.Param!.ToLowerInvariant()}: /rc hotkey add {comboText} {action.Id} <{action.Param.ToLowerInvariant()}>");
if (action == null)
return Fail($"Unknown action '{what}'. Use a chat command starting with / or a built-in (/rc hotkey actions).");
return new HotkeyCommand(HotkeyVerb.Add, combo, action.Id);
}
private static HotkeyCommand Fail(string error) => new(HotkeyVerb.Error, Error: error);
}
/// <summary>The bindings and the master switch, as saved.</summary>
internal sealed record HotkeyFile(bool Enabled, List<HotkeyBinding> Bindings);
/// <summary>
/// %LOCALAPPDATA%\RynthCore\hotkeys.txt, for every client on this PC. Text, one binding a line:
/// "on|off &lt;TAB&gt; combo &lt;TAB&gt; action &lt;TAB&gt; chat command". RYNTHCORE_HOTKEYS_FILE points a test at its own file.
/// </summary>
internal static class HotkeyStore
{
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
public static string FilePath
{
get
{
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "hotkeys.txt");
}
}
public static string Serialize(HotkeyFile file)
{
var sb = new StringBuilder();
sb.Append("# RynthCore hotkeys (Settings > Hotkeys, /rc hotkey). Shared by every client on this PC.\n");
sb.Append("# One per line: on|off <TAB> combo <TAB> action <TAB> chat command (action \"command\").\n");
sb.Append("enabled=").Append(file.Enabled ? '1' : '0').Append('\n');
foreach (HotkeyBinding b in file.Bindings)
{
if (b.Combo.IsEmpty) continue;
bool keepsText = b.IsCommand || HotkeyActions.Find(b.Action)?.HasParam == true; // a chat command, or a parameter
string cmd = keepsText ? b.Command.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ').Trim() : string.Empty;
sb.Append(b.Enabled ? "on" : "off").Append('\t').Append(HotkeyKeys.Format(b.Combo)).Append('\t')
.Append(b.Action).Append('\t').Append(cmd).Append('\n');
}
return sb.ToString();
}
/// <summary>Reads the file's text; bad lines are skipped (never throws).</summary>
public static HotkeyFile Parse(string? text)
{
var file = new HotkeyFile(true, new List<HotkeyBinding>());
bool enabled = true;
if (string.IsNullOrEmpty(text)) return file;
foreach (string raw in text.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
if (line.StartsWith("enabled=", StringComparison.OrdinalIgnoreCase))
{
enabled = line.Substring(8).Trim() != "0";
continue;
}
string[] f = line.Split('\t', 4);
if (f.Length < 3) continue;
if (!HotkeyKeys.TryParse(f[1], out KeyCombo combo, out _)) continue;
string action = f[2].Trim();
if (action.Length == 0) continue;
string cmd = f.Length > 3 ? f[3].Trim() : string.Empty;
bool on = !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase);
file.Bindings.Add(new HotkeyBinding(combo, action, cmd, on));
}
return file with { Enabled = enabled };
}
public static HotkeyFile Load()
{
try
{
string path = FilePath;
return File.Exists(path) ? Parse(File.ReadAllText(path)) : new HotkeyFile(true, new List<HotkeyBinding>());
}
catch
{
return new HotkeyFile(true, new List<HotkeyBinding>());
}
}
/// <summary>Writes the file (temp file, then replace). Returns false on an I/O error.</summary>
public static bool Save(HotkeyFile file)
{
try
{
string path = FilePath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, Serialize(file));
File.Move(tmp, path, overwrite: true);
return true;
}
catch
{
return false;
}
}
/// <summary>The file's last write time (UTC), or MinValue if it doesn't exist.</summary>
public static DateTime LastWriteUtc()
{
try
{
string path = FilePath;
return File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
}
catch
{
return DateTime.MinValue;
}
}
}
/// <summary>
/// Which key-ups and chars belong to a key a hotkey took. A hotkey's key-down is eaten, so are its
/// auto-repeats, the char Windows makes from it and its key-up: AC sees none of that keystroke.
/// Any other key passes untouched. Pure state, driven by HotkeyService on AC's thread.
/// </summary>
internal sealed class HotkeyKeyTracker
{
private readonly bool[] _eaten = new bool[256];
private bool _eatNextChar;
/// <summary>A hotkey took this key-down: eat the rest of the keystroke.</summary>
public void Took(int vk)
{
if ((uint)vk < 256) _eaten[vk] = true;
_eatNextChar = true;
}
/// <summary>True if this key's keystroke is being eaten (a repeat of a key a hotkey took).</summary>
public bool IsEaten(int vk) => (uint)vk < 256 && _eaten[vk];
/// <summary>Key-down of another key: a char after it is that key's, not ours.</summary>
public void OtherKeyDown() => _eatNextChar = false;
/// <summary>A WM_CHAR / WM_SYSCHAR: eat it when it's the one our key-down made.</summary>
public bool TakeChar()
{
bool eat = _eatNextChar;
_eatNextChar = false;
return eat;
}
/// <summary>A key-up: true (eat it) when its key-down was a hotkey's.</summary>
public bool KeyUp(int vk)
{
_eatNextChar = false;
if ((uint)vk >= 256 || !_eaten[vk]) return false;
_eaten[vk] = false;
return true;
}
/// <summary>Focus lost: Windows sends no key-ups for keys still down; forget them.</summary>
public void Reset()
{
Array.Clear(_eaten);
_eatNextChar = false;
}
}

View file

@ -0,0 +1,487 @@
// ============================================================================
// RynthCore.Engine - Hotkeys/HotkeyService.cs
//
// The engine side of the user hotkeys (model and rules: HotkeyModel.cs).
//
// Keys: Win32Backend's WndProc subclass hands every key message here on AC's
// main thread (after RynthChat's own input capture, before AC and ImGui see
// it). A bound combo fires on its first key-down only (never on auto-repeat),
// in the world, with the client in the foreground and nobody typing: not in a
// RynthCore text box (RynthChat, an ImGui field, a pop-out's box) and not in
// AC's own chat entry (AcKeyboardFocus: AC's UI focus element). The keystroke
// that fires is eaten (down, repeats, its char and its up); unbound keys pass
// through untouched.
//
// Actions run the way the panels run them: RynthAi/RynthSort exports through
// the UI hub's pump (RynthAiCommands, RynthSortCommands), panels through
// PanelRouter.Toggle, chat commands through AcMainThreadQueue (the next
// main-thread drain, outside this keystroke's WndProc frame, so AC's chat bar
// is never driven re-entrantly: see Win32Backend's WM_RYNTHCORE_CHAT note).
//
// Storage: %LOCALAPPDATA%\RynthCore\hotkeys.txt for every client on the PC
// (HotkeyStore). Each client looks at the file's time at most every 2 s, so a
// change made in one client reaches the others without a restart.
//
// Settings capture ("press a key"): the Settings section asks for the next
// combo (BeginCapture); the next non-modifier key-down is taken for it (Esc
// cancels) and AC never sees it.
//
// Hot reload: no event subscriptions, no threads; everything here is this
// generation's statics. Shutdown cancels a capture.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.Hotkeys;
internal static class HotkeyService
{
private const uint WM_KILLFOCUS = 0x0008, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107;
private const long FileCheckMs = 2000;
private const long CaptureTimeoutMs = 15000;
[DllImport("user32.dll")] private static extern short GetKeyState(int nVirtKey);
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
private static readonly object Sync = new();
private static HotkeyFile _file = new(true, new List<HotkeyBinding>()); // replaced, never edited in place
private static bool _loaded;
private static DateTime _seenWriteUtc = DateTime.MinValue;
private static long _nextFileCheckMs;
private static int _pendingSaves;
private static readonly HotkeyKeyTracker Tracker = new(); // AC's main thread only
// Capture for the Settings section (main thread: the WndProc and ImGui both run there).
private static bool _capturing;
private static long _captureStartedMs;
private static KeyCombo? _captured;
private static bool _captureCancelled;
private static string _captureNote = string.Empty;
private static HotkeyGate _lastGate = HotkeyGate.Fire;
private static readonly uint OurPid = (uint)Environment.ProcessId;
// ── Bindings ───────────────────────────────────────────────────────────
/// <summary>The bindings and master switch now (reloaded when another client changed the file). Any thread.</summary>
public static HotkeyFile Current
{
get
{
EnsureFresh();
return Volatile.Read(ref _file);
}
}
private static void EnsureFresh()
{
long now = Environment.TickCount64;
if (_loaded && now < Volatile.Read(ref _nextFileCheckMs)) return;
lock (Sync)
{
if (_loaded && now < _nextFileCheckMs) return;
_nextFileCheckMs = now + FileCheckMs;
if (Volatile.Read(ref _pendingSaves) > 0) return; // our own write is on its way; don't read a half-old file
DateTime w = HotkeyStore.LastWriteUtc();
if (_loaded && w == _seenWriteUtc) return;
HotkeyFile loaded = HotkeyStore.Load();
bool first = !_loaded;
_loaded = true;
_seenWriteUtc = w;
Volatile.Write(ref _file, loaded);
if (first || loaded.Bindings.Count > 0)
RynthLog.UI($"Hotkeys: {(first ? "loaded" : "reloaded")} {loaded.Bindings.Count} binding(s) from {HotkeyStore.FilePath} (hotkeys {(loaded.Enabled ? "on" : "off")}).");
}
}
private static void Commit(HotkeyFile next)
{
lock (Sync)
{
_loaded = true;
Volatile.Write(ref _file, next);
Interlocked.Increment(ref _pendingSaves);
}
UI.UiBackgroundWriter.Enqueue("hotkeys", () =>
{
bool ok = HotkeyStore.Save(next);
lock (Sync)
{
if (ok) _seenWriteUtc = HotkeyStore.LastWriteUtc();
Interlocked.Decrement(ref _pendingSaves);
}
if (!ok) RynthLog.UI($"Hotkeys: could not write {HotkeyStore.FilePath}.");
});
}
private static List<HotkeyBinding> Copy() => new(Current.Bindings);
public static void SetMasterEnabled(bool on)
{
HotkeyFile f = Current;
if (f.Enabled != on) Commit(f with { Enabled = on, Bindings = new List<HotkeyBinding>(f.Bindings) });
}
public static void Add(HotkeyBinding b)
{
List<HotkeyBinding> list = Copy();
list.Add(b);
Commit(Current with { Bindings = list });
}
/// <summary>Replaces binding <paramref name="index"/> (from <see cref="Current"/>); false if it's gone.</summary>
public static bool Replace(int index, HotkeyBinding b)
{
List<HotkeyBinding> list = Copy();
if ((uint)index >= (uint)list.Count) return false;
list[index] = b;
Commit(Current with { Bindings = list });
return true;
}
public static bool RemoveAt(int index)
{
List<HotkeyBinding> list = Copy();
if ((uint)index >= (uint)list.Count) return false;
list.RemoveAt(index);
Commit(Current with { Bindings = list });
return true;
}
/// <summary>Moves binding <paramref name="index"/> up (-1) or down (+1): the higher of two with one key fires.</summary>
public static bool Move(int index, int delta)
{
List<HotkeyBinding> list = Copy();
int to = index + delta;
if ((uint)index >= (uint)list.Count || (uint)to >= (uint)list.Count) return false;
(list[index], list[to]) = (list[to], list[index]);
Commit(Current with { Bindings = list });
return true;
}
private static int RemoveCombo(KeyCombo combo)
{
List<HotkeyBinding> list = Copy();
int n = list.RemoveAll(b => b.Combo == combo);
if (n > 0) Commit(Current with { Bindings = list });
return n;
}
private static int SetComboEnabled(KeyCombo combo, bool on)
{
List<HotkeyBinding> list = Copy();
int n = 0;
for (int i = 0; i < list.Count; i++)
if (list[i].Combo == combo && list[i].Enabled != on) { list[i] = list[i] with { Enabled = on }; n++; }
if (n > 0) Commit(Current with { Bindings = list });
return n;
}
// ── Capture (Settings: "press a key") ──────────────────────────────────
public static bool Capturing => _capturing;
public static void BeginCapture()
{
_capturing = true;
_captured = null;
_captureCancelled = false;
_captureNote = string.Empty;
_captureStartedMs = Environment.TickCount64;
}
public static void CancelCapture()
{
if (!_capturing) return;
_capturing = false;
_captureCancelled = true;
}
/// <summary>A key that couldn't be taken during the capture ("Numpad Enter can't be a hotkey").</summary>
public static string CaptureNote => _captureNote;
/// <summary>
/// The Settings section, each frame while it waits: true once the capture ended, with the combo, or
/// null when it was cancelled (Esc, timeout).
/// </summary>
public static bool TryTakeCapture(out KeyCombo? combo)
{
combo = null;
if (_capturing && Environment.TickCount64 - _captureStartedMs > CaptureTimeoutMs)
{
_capturing = false;
_captureCancelled = true;
}
if (_capturing) return false;
if (_captured is { } c) { _captured = null; combo = c; return true; }
if (_captureCancelled) { _captureCancelled = false; return true; }
return false;
}
// ── Keys (Win32Backend.WndProcHook, AC's main thread) ──────────────────
/// <summary>
/// One key message. True: it belongs to a hotkey (or to a Settings capture) and must not reach AC
/// or ImGui. <paramref name="rynthTextFocus"/>: a RynthCore text box has the keyboard.
/// </summary>
public static bool HandleKeyMessage(uint msg, IntPtr wParam, IntPtr lParam, bool rynthTextFocus)
{
try
{
switch (msg)
{
case WM_KILLFOCUS:
Tracker.Reset();
return false;
case WM_CHAR:
case WM_SYSCHAR:
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
return Tracker.TakeChar();
case WM_KEYUP:
case WM_SYSKEYUP:
return Tracker.KeyUp(HotkeyMatch.NormalizeVk((int)wParam, HotkeyMatch.IsExtended(lParam.ToInt64())));
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
return KeyDown((int)wParam, lParam.ToInt64(), rynthTextFocus);
default:
return false;
}
}
catch (Exception ex)
{
RynthLog.UI($"Hotkeys: key message threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool Down(int vk) => (GetKeyState(vk) & 0x8000) != 0;
private static HotkeyMods HeldMods() =>
HotkeyMatch.Mods(Down(HotkeyKeys.VK_CONTROL), Down(HotkeyKeys.VK_MENU), Down(HotkeyKeys.VK_SHIFT));
private static bool KeyDown(int rawVk, long lParam, bool rynthTextFocus)
{
int vk = HotkeyMatch.NormalizeVk(rawVk, HotkeyMatch.IsExtended(lParam));
if (_capturing)
{
if (HotkeyKeys.IsModifierKey(vk)) return false; // held for the combo; let it through
Tracker.Took(vk);
if (vk == HotkeyKeys.VK_ESCAPE) { CancelCapture(); return true; }
if (vk == 0 || !HotkeyKeys.IsBindable(vk))
{
_captureNote = vk == 0 ? "Numpad Enter can't be a hotkey (AC keeps it)." : $"{HotkeyKeys.KeyName(vk)} can't be a hotkey.";
return true; // keep waiting
}
_captured = new KeyCombo(vk, HeldMods());
_capturing = false;
return true;
}
if (Tracker.IsEaten(vk))
{
Tracker.Took(vk); // auto-repeat of a key a hotkey took: eat it and its char too
return true;
}
Tracker.OtherKeyDown();
if (vk == 0 || HotkeyKeys.IsModifierKey(vk) || !HotkeyMatch.IsFreshPress(lParam)) return false;
HotkeyFile file = Current;
if (!file.Enabled || file.Bindings.Count == 0) return false;
var combo = new KeyCombo(vk, HeldMods());
HotkeyBinding? b = HotkeyMatch.Find(file.Bindings, combo);
if (b == null) return false;
HotkeyGate gate = HotkeyRules.Check(ReadTypingState(rynthTextFocus), combo);
if (gate != _lastGate)
{
_lastGate = gate;
if (gate != HotkeyGate.Fire) RynthLog.UI($"Hotkeys: {combo} held back - {HotkeyRules.Describe(gate)}.");
}
if (gate != HotkeyGate.Fire) return false;
Tracker.Took(vk);
RynthLog.UI($"Hotkeys: {combo} -> {HotkeyActions.Describe(b)}.");
Run(b);
return true;
}
private static TypingState ReadTypingState(bool rynthTextFocus) => new(
InWorld: LoginLifecycleHooks.HasObservedLoginComplete,
GameFocused: ForegroundIsOurs(),
RynthTextFocus: rynthTextFocus,
AcTextFocus: AcKeyboardFocus.HasTextFocus());
private static bool ForegroundIsOurs()
{
IntPtr fg = GetForegroundWindow();
if (fg == IntPtr.Zero) return false;
GetWindowThreadProcessId(fg, out uint pid);
return pid == OurPid;
}
// ── Actions ────────────────────────────────────────────────────────────
/// <summary>Runs a binding's action. Main thread (from the key); plugin work is posted to the pump.</summary>
public static void Run(HotkeyBinding b)
{
if (b.IsCommand)
{
if (b.Command.Trim().Length == 0) return;
if (!AcMainThreadQueue.EnqueueChatCommand(b.Command.Trim()))
Reply("Hotkey: the chat command queue is full; try again.");
return;
}
HotkeyAction? a = HotkeyActions.Find(b.Action);
if (a == null)
{
Reply($"Hotkey {b.Combo}: unknown action '{b.Action}' (edit it in Settings > Hotkeys).");
return;
}
if (a.Panel != null)
{
string title = UI.PanelRouter.Canonical(a.Panel);
if (!ImGuiBackend.ImGuiPanelHost.HasFace(title))
Reply($"Hotkey {b.Combo}: the {a.Panel} panel isn't available (its plugin isn't loaded, or the ImGui layer is off).");
else
UI.PanelRouter.Toggle(title);
return;
}
if (a.Chat != null)
{
// VTank-style actions that are RynthAi /ra commands (the same as typing them).
if (a.HasParam && b.Command.Trim().Length == 0)
{
Reply($"Hotkey {b.Combo}: '{a.Name}' has no {a.Param!.ToLowerInvariant()} (edit it in Settings > Hotkeys).");
return;
}
if (!AcMainThreadQueue.EnqueueChatCommand(HotkeyActions.ChatFor(a, b)))
Reply("Hotkey: the chat command queue is full; try again.");
return;
}
switch (a.Id)
{
case "macro": case "vt:startstop": UI.Data.RynthAiCommands.ToggleMacro(); break;
case "combat": case "vt:combat": UI.Data.RynthAiCommands.ToggleSubsystem(0); break;
case "buffing": case "vt:buffing": UI.Data.RynthAiCommands.ToggleSubsystem(1); break;
case "navigation": case "vt:navigation": UI.Data.RynthAiCommands.ToggleSubsystem(2); break;
case "looting": case "vt:looting": UI.Data.RynthAiCommands.ToggleSubsystem(3); break;
case "meta": UI.Data.RynthAiCommands.ToggleSubsystem(4); break;
case "forcerebuff": case "vt:forcebuff": UI.Data.RynthAiCommands.ForceRebuff(); break;
case "vt:cancelforcebuff": UI.Data.RynthAiCommands.CancelForceRebuff(); break;
case "patrol": UI.Data.RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}", refreshPatrol: true); break;
case "autosort": UI.Data.RynthSortCommands.ToggleAuto(); break;
case "reload":
// As /rc rl and the bar's RL: signalled from a pool thread (the reload shuts this engine down).
RynthLog.Compat("Hotkeys: engine reload requested.");
EntryPoint.NoteManualReload();
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
break;
default:
Reply($"Hotkey {b.Combo}: '{a.Name}' isn't wired up in this engine.");
break;
}
}
private static void Reply(string text) => AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1);
// ── /rc hotkey ─────────────────────────────────────────────────────────
/// <summary>"/rc hotkey ..." (args after "hotkey"): the reply lines.</summary>
public static List<string> HandleCommand(string args)
{
var lines = new List<string>();
HotkeyCommand c = HotkeyCommandParser.Parse(args);
HotkeyFile f = Current;
switch (c.Verb)
{
case HotkeyVerb.Help:
lines.Add(HotkeyCommandParser.Usage);
break;
case HotkeyVerb.Error:
lines.Add(c.Error);
break;
case HotkeyVerb.List:
if (f.Bindings.Count == 0) { lines.Add("No hotkeys. Add one in Settings > Hotkeys (/rc hotkeys) or with /rc hotkey add <combo> <action or /command>."); break; }
lines.Add($"Hotkeys ({(f.Enabled ? "on" : "OFF: /rc hotkey on")}):");
List<int> shadowed = HotkeyConflicts.Shadowed(f.Bindings);
for (int i = 0; i < f.Bindings.Count; i++)
{
HotkeyBinding b = f.Bindings[i];
lines.Add($" {b.Combo} - {HotkeyActions.Describe(b)}{(b.Enabled ? "" : " (off)")}{(shadowed.Contains(i) ? " (never fires: an earlier hotkey has this key)" : "")}");
}
break;
case HotkeyVerb.Actions:
lines.Add("Built-in actions (or any chat command starting with /):");
foreach (string group in new[] { "", HotkeyActions.VTankGroup })
{
var sb = new System.Text.StringBuilder(group.Length > 0 ? " " + group + ": " : " ");
foreach (HotkeyAction a in HotkeyActions.BuiltIns)
{
if (a.Group != group) continue;
if (sb.Length > 150) { lines.Add(sb.ToString().TrimEnd(',', ' ')); sb.Clear().Append(" "); }
sb.Append(a.Id);
if (a.HasParam) sb.Append(" <").Append(a.Param!.ToLowerInvariant()).Append('>');
sb.Append(", ");
}
lines.Add(sb.ToString().TrimEnd(',', ' '));
}
break;
case HotkeyVerb.Status:
lines.Add($"Hotkeys {(f.Enabled ? "on" : "off")}, {f.Bindings.Count} bound, file {HotkeyStore.FilePath}.");
lines.Add("Last held back: " + (_lastGate == HotkeyGate.Fire ? "nothing" : HotkeyRules.Describe(_lastGate)) + ".");
lines.Add(AcKeyboardFocus.Describe());
break;
case HotkeyVerb.On:
case HotkeyVerb.Off:
SetMasterEnabled(c.Verb == HotkeyVerb.On);
lines.Add(c.Verb == HotkeyVerb.On ? "Hotkeys on." : "Hotkeys off (bindings kept; /rc hotkey on turns them back on).");
break;
case HotkeyVerb.Add:
{
var b = new HotkeyBinding(c.Combo, c.Action, c.ChatCommand);
List<string> warn = HotkeyConflicts.Warnings(f.Bindings, c.Combo);
Add(b);
lines.Add($"Hotkey added: {c.Combo} - {HotkeyActions.Describe(b)}.");
foreach (string w in warn) lines.Add("Note: " + w);
if (!f.Enabled) lines.Add("Hotkeys are off; /rc hotkey on turns them on.");
break;
}
case HotkeyVerb.Remove:
{
int n = RemoveCombo(c.Combo);
lines.Add(n == 0 ? $"No hotkey on {c.Combo}." : $"Removed {n} hotkey(s) on {c.Combo}.");
break;
}
case HotkeyVerb.Enable:
case HotkeyVerb.Disable:
{
bool on = c.Verb == HotkeyVerb.Enable;
int n = SetComboEnabled(c.Combo, on);
lines.Add(n == 0 ? $"No hotkey on {c.Combo} to switch {(on ? "on" : "off")}." : $"{c.Combo}: {(on ? "on" : "off")}.");
break;
}
}
return lines;
}
/// <summary>Engine shutdown: a capture in progress ends (the next generation starts clean).</summary>
public static void Shutdown()
{
_capturing = false;
_captured = null;
Tracker.Reset();
}
}

View file

@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
using RynthCore.Install;
namespace RynthCore.Engine.ImGuiBackend;
@ -48,6 +49,9 @@ internal static class EngineFrameController
private static bool _imguiInitFailed;
private static bool _coreResolved;
private static bool _pluginsInitialized;
// Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
private static int _pluginInitContextWaits;
private const int PluginInitContextMaxWaits = 300;
private static IntPtr _context;
private static IntPtr _gameHwnd;
@ -61,6 +65,26 @@ internal static class EngineFrameController
/// </summary>
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
private static int _pumpFrameFaults; // PumpPluginFrame throws caught (pump thread only)
// ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
// log shows whether frames start, which branch runs and whether draw data is submitted.
private const long HeartbeatIntervalMs = 30_000;
private static long _engineErrorCount;
private static long _nextEngineErrorLogAt;
private static bool _loggedFirstSubmit;
private static int _loggedBranch = -1;
private static string _initFailStep = "unknown";
private static long _drawSubmits;
private static long _nextHeartbeatAt;
// Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
// Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
// the next NewFrame on the main context.
private static IntPtr _deferredSubmitDevice;
// Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
private static long _deferredUiTicks;
private static long _lastFrameTicks;
private static int _frameCount;
@ -103,7 +127,10 @@ internal static class EngineFrameController
return true;
if (!EnsureCore(pDevice))
{
_initFailStep = "EnsureCore (game window not found)";
return false;
}
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
@ -131,7 +158,7 @@ internal static class EngineFrameController
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
@ -155,10 +182,16 @@ internal static class EngineFrameController
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
{
_initFailStep = "Win32Backend.Init";
return false;
}
if (!DX9Backend.InitImGui(pDevice))
{
_initFailStep = "DX9Backend.InitImGui";
return false;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
@ -229,6 +262,8 @@ internal static class EngineFrameController
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled.
// A frame that throws before its build must not resubmit last frame's draw data.
_deferredSubmitDevice = IntPtr.Zero;
try
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
@ -344,10 +379,10 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
// (EndSceneHook, after this returns) stays topmost while both stacks
// run, matching input order: Avalonia gets the first hit test.
// The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
// EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
// the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
// matches: Win32Backend gives ImGui the mouse while it wants it.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
@ -370,17 +405,33 @@ internal static class EngineFrameController
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
if (imguiBuilt)
{
_deferredUiTicks = ticks;
_deferredSubmitDevice = pDevice;
}
else
{
UiFrameStats.Record(ticks);
}
}
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
// An exception here skips everything after it this frame (including RunImGuiFrame), so
// the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
_engineErrorCount++;
long errNow = Environment.TickCount64;
if (_engineErrorCount == 1)
RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
else if (errNow >= _nextEngineErrorLogAt)
RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
if (errNow >= _nextEngineErrorLogAt)
_nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
}
finally
{
@ -442,14 +493,26 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
// Plugins only get the ImGui context when they may draw with it
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
// don't need plugins to see it, and handing it over switched
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
// Plugins only get the ImGui context when they may draw with it: the
// ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
// windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
// Info; RynthPluginRenderOverlay). RynthAi only reads the context for
// those windows, so this does not switch it into a legacy-ImGui setup.
bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
|| (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
// _context is written by the render thread (Init); this is the pump thread.
IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
if (!_pluginsInitialized)
{
// The plugin host copies the context once at init, so wait for the
// render path's ImGui init (first ImGui frame) rather than hand over
// zero for the whole session. Bounded: a failed or stalled ImGui init
// must not hold plugins (and the bot) back.
if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
&& ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
return;
if (pluginsDraw && pluginContext == IntPtr.Zero)
RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
_pluginsInitialized = true;
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
@ -471,7 +534,13 @@ internal static class EngineFrameController
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
// The first one with its stack, then counted (a step throwing every frame
// would otherwise write a line per pump tick).
int n = ++_pumpFrameFaults;
if (n == 1)
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} (caught; repeats are counted){Environment.NewLine}{ex}");
else if (n % StepFaultLog.RepeatEvery == 0)
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} - {n} times so far, still caught.");
}
finally
{
@ -501,9 +570,16 @@ internal static class EngineFrameController
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|| D3D9.VideoPatch.WantsBanner;
|| D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
}
/// <summary>
/// In the world, with the shell off, and some loaded plugin exports
/// RynthPluginRenderOverlay: its windows need a frame every frame.
/// </summary>
private static bool PluginOverlayWindowsLive =>
PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen
@ -544,7 +620,8 @@ internal static class EngineFrameController
}
private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
|| PluginOverlayWindowsLive;
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
@ -573,6 +650,7 @@ internal static class EngineFrameController
if (!Init(pDevice))
{
_imguiInitFailed = true;
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false;
}
}
@ -596,7 +674,6 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
bool frameEnded = false;
try
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
@ -644,6 +721,9 @@ internal static class EngineFrameController
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
// a payload the client's drop targets (Mini Remote slots) see this frame.
ItemDragBridge.SubmitMainFrame(io);
ImGuiTextFocus.BeginFrame();
if (_dropImGuiTextFocus)
{
@ -653,11 +733,29 @@ internal static class EngineFrameController
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
int branch;
if (Plugins.EngineSettings.EnableImGuiShell)
{
branch = 1;
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
else if (PluginOverlayWindowsLive)
{
branch = 2;
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
// plugins' full ImGui UIs.
PluginManager.RenderOverlayAll();
}
else
{
branch = 0;
}
if (branch != _loggedBranch)
{
_loggedBranch = branch;
RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
}
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
@ -744,6 +842,24 @@ internal static class EngineFrameController
_prevAvaloniaText = avaloniaText;
}
/// <summary>
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
/// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
/// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws.
/// </summary>
public static void RenderDeferredImGui()
{
IntPtr device = _deferredSubmitDevice;
if (device == IntPtr.Zero)
return;
_deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
long t0 = Stopwatch.GetTimestamp();
SubmitImGuiFrame(device);
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice)
{
@ -751,7 +867,15 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
_drawSubmits++;
if (!_loggedFirstSubmit)
{
_loggedFirstSubmit = true;
RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
}
LogHeartbeatIfDue(drawData);
}
catch (Exception ex)
{
@ -763,6 +887,29 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
/// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
/// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
/// </summary>
private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
{
long now = Environment.TickCount64;
if (now < _nextHeartbeatAt) return;
bool first = _nextHeartbeatAt == 0;
_nextHeartbeatAt = now + HeartbeatIntervalMs;
if (first) return; // first interval starts now; the first-frame line already covers t=0
int lists = 0, vertices = 0;
unsafe
{
// ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
byte* p = (byte*)drawData.NativePtr;
if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
}
RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
}
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();

View file

@ -57,12 +57,14 @@ internal static class ImGuiBar
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
private static readonly string[] ImGuiOnlyBarPanels =
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title,
Panels.CharactersFace.Title };
// The ILT section: the RynthILT plugin's ImGui-only panels. They never get buttons of their
// own; one ILT button stands for them, shown only on Infinite Leaftide (IltInfo.IsIlt) and
// only for the ones registered (EntryPoint registers them when RynthILT is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title };
// The ILT section: ImGui-only Infinite Leaftide panels (Bounties from RynthILT, Guardian from
// RynthAi). They never get buttons of their own; one ILT button stands for them, shown only
// on Infinite Leaftide (IltInfo.IsIlt) and only for the ones registered (EntryPoint registers
// each when its plugin is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title, Panels.GuardianFace.Title };
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
@ -88,6 +90,7 @@ internal static class ImGuiBar
["Log"] = PhosphorIcons.TerminalWindow,
["Item Count"] = PhosphorIcons.Bag,
["Mini Remote"] = PhosphorIcons.SquaresFour,
["Characters"] = PhosphorIcons.UsersThree,
// Plugin windows with a bar button of their own (script windows, by title).
["RynthSort"] = PhosphorIcons.SortAscending,
["Oracle"] = PhosphorIcons.Sparkle,
@ -261,6 +264,8 @@ internal static class ImGuiBar
public static void Draw(float s)
{
// The bar draws every frame the ImGui shell is up: keep RynthAi's server menu current.
RynthCore.Engine.UI.ServerMenus.Tick();
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
@ -389,8 +394,8 @@ internal static class ImGuiBar
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
}
// The ILT section: one button, only on Infinite Leaftide with RynthILT's panels
// registered. With one panel it toggles that panel; with more it opens a menu.
// The ILT section: one button, only on Infinite Leaftide with ILT panels registered
// (Bounties, Guardian). With one panel it toggles that panel; with more it opens a menu.
int iltCount = IltPanelCount();
if (iltCount > 0)
{
@ -418,7 +423,11 @@ internal static class ImGuiBar
ImGuiNET.ImGui.SameLine(0, 6 * s);
if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel))
{
// By hand: not held while a plugin objects (combat, looting); the player chose the moment.
EntryPoint.NoteManualReload();
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
}
ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init.");
if (ResolveFace() == PanelFace.ImGui)

Some files were not shown because too many files have changed in this diff Show more