RynthSuite as of 2026-09-05 (internal a5ff5c2)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:23:05 -04:00
commit 0a4b611a90
166 changed files with 186537 additions and 0 deletions

155
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,155 @@
name: Build & Release
# Trigger manually (Actions tab → Run workflow) or automatically on version tags.
on:
workflow_dispatch:
inputs:
version:
description: 'Version number (e.g. 1.0) — creates tag v<version>'
required: true
default: '1.0'
rynthcore_ref:
description: 'RynthCore ref to build against (tag/branch/SHA). Blank = matching version tag, else default branch.'
required: false
default: ''
push:
tags:
- 'v*'
jobs:
build:
runs-on: windows-latest
permissions:
contents: write
steps:
# ── Checkout both repos as siblings ───────────────────────────────────────
# The plugin csproj references ..\..\..\RynthCore\src\... (3 levels up),
# so RynthCore must be a sibling of RynthSuite under a common parent.
- name: Checkout RynthSuite
uses: actions/checkout@v4
# Pin the sibling to the matching version tag so a tagged release is
# REPRODUCIBLE (otherwise the plugin builds against whatever RynthCore main
# is at build time). Falls back to the default branch (with a CI warning)
# if the matching tag doesn't exist yet.
- name: Checkout RynthCore (sibling, pinned)
shell: pwsh
run: |
$parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent
$dest = "$parent\RynthCore"
if ("${{ github.event_name }}" -eq "push") { $want = "${{ github.ref_name }}" }
else { $want = "v${{ github.event.inputs.version }}" }
$override = "${{ github.event.inputs.rynthcore_ref }}"
if ($override) { $want = $override }
Write-Host "Cloning RynthCore to: $dest (pin target: $want)"
git clone https://github.com/tombohar/RynthCore.git $dest
if ($LASTEXITCODE -ne 0) { throw "git clone RynthCore failed" }
git -C $dest fetch --tags --quiet
if ($want -and (git -C $dest rev-parse --verify --quiet "$want^{commit}")) {
git -C $dest checkout --quiet $want
if ($LASTEXITCODE -ne 0) { throw "checkout RynthCore $want failed" }
Write-Host "RynthCore pinned to: $want"
} else {
Write-Host "::warning::RynthCore ref '$want' not found; building against default branch HEAD (NOT reproducible)"
}
Write-Host "RynthCore at commit: $(git -C $dest rev-parse HEAD)"
# ── Toolchain ─────────────────────────────────────────────────────────────
- name: Setup .NET 10
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
# ── Determine version ──────────────────────────────────────────────────────
- name: Resolve version
id: ver
shell: pwsh
run: |
if ("${{ github.event_name }}" -eq "workflow_dispatch") {
$v = "${{ github.event.inputs.version }}"
} else {
$v = "${{ github.ref_name }}".TrimStart('v')
}
echo "version=$v" >> $env:GITHUB_OUTPUT
echo "tag=v$v" >> $env:GITHUB_OUTPUT
Write-Host "Building version: $v"
# ── Validation gate (fail the release before building if it trips) ─────────
# LootSdk golden tests: 60+ assertions on the loot-profile parser/SDK that
# backs the LootEditor and the bundled plugin. Self-contained in this repo.
- name: Validation gate — LootSdk golden tests
shell: pwsh
run: |
dotnet run --project "$env:GITHUB_WORKSPACE\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release
if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" }
# ── Build LootEditor ───────────────────────────────────────────────────────
- name: Build LootEditor
shell: pwsh
run: |
dotnet publish "$env:GITHUB_WORKSPACE\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" `
-c Release -r win-x64 --self-contained true `
--output "$env:GITHUB_WORKSPACE\publish\LootEditor"
if ($LASTEXITCODE -ne 0) { throw "LootEditor publish failed" }
- name: Zip LootEditor
shell: pwsh
run: |
Compress-Archive -Path "$env:GITHUB_WORKSPACE\publish\LootEditor\*" `
-DestinationPath "$env:GITHUB_WORKSPACE\RynthCore.LootEditor.zip"
# ── Build MonsterEditor ────────────────────────────────────────────────────
- name: Build MonsterEditor
shell: pwsh
run: |
dotnet publish "$env:GITHUB_WORKSPACE\Tools\RynthCore.MonsterEditor\RynthCore.MonsterEditor.csproj" `
-c Release -r win-x64 --self-contained true `
--output "$env:GITHUB_WORKSPACE\publish\MonsterEditor"
if ($LASTEXITCODE -ne 0) { throw "MonsterEditor publish failed" }
- name: Zip MonsterEditor
shell: pwsh
run: |
Compress-Archive -Path "$env:GITHUB_WORKSPACE\publish\MonsterEditor\*" `
-DestinationPath "$env:GITHUB_WORKSPACE\RynthCore.MonsterEditor.zip"
# ── Build Plugin (NativeAOT x86) ───────────────────────────────────────────
- name: Build Plugin
shell: pwsh
run: |
dotnet publish "$env:GITHUB_WORKSPACE\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" `
-c Release
if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed" }
# ── Tag (manual dispatch only) ─────────────────────────────────────────────
- name: Create tag (manual dispatch)
if: github.event_name == 'workflow_dispatch'
shell: pwsh
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag "${{ steps.ver.outputs.tag }}" -m "Release ${{ steps.ver.outputs.tag }}"
git push origin "${{ steps.ver.outputs.tag }}"
# ── GitHub Release ─────────────────────────────────────────────────────────
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.tag }}
name: RynthSuite ${{ steps.ver.outputs.tag }}
files: |
RynthCore.LootEditor.zip
RynthCore.MonsterEditor.zip
Plugins/RynthCore.Plugin.RynthAi/bin/Release/net10.0-windows/win-x86/publish/RynthCore.Plugin.RynthAi.dll
body: |
## Downloads
| File | Description |
|------|-------------|
| `RynthCore.LootEditor.zip` | Loot profile editor — extract and run `RynthCore.LootEditor.exe` |
| `RynthCore.MonsterEditor.zip` | Monster database editor — extract and run `RynthCore.MonsterEditor.exe` |
| `RynthCore.Plugin.RynthAi.dll` | Plugin DLL — drop into `C:\Games\RynthCore\Runtime\Plugins\` to update without reinstalling |
> **New install?** Use the [RynthCore installer](https://github.com/tombohar/RynthCore/releases/latest) instead — it sets up everything automatically.

38
.gitignore vendored Normal file
View file

@ -0,0 +1,38 @@
# Build outputs
bin/
obj/
publish/
artifacts/
TestResults/
# IDE and local tooling
.vs/
.vscode/
.idea/
.claude/
*.user
*.pubxml.user
*.suo
*.userosscache
*.rsuser
# Local app data
.appdata/
.localappdata/
# Logs and transient files
*.log
*.tmp
*.temp
*.cache
Thumbs.db
Desktop.ini
# Local secrets and machine-specific config
.env
.env.*
*.secrets.json
secrets.*
appsettings.Local.json
appsettings.*.local.json

87
BUILD.md Normal file
View file

@ -0,0 +1,87 @@
# Build & Deploy
RynthSuite ships two build flavors:
- **Plugins** (`Plugins/RynthCore.Plugin.RynthAi/`) — **NativeAOT x86** DLLs targeting `net10.0-windows`. You must use `dotnet publish`, not `dotnet build` — a regular build produces a managed-only DLL that the engine loader rejects.
- **Tools and SDK** (`Tools/`, `Shared/RynthCore.LootSdk/`) — managed `net10.0` projects. **Cross-platform.** Build with normal `dotnet build` on Windows, Linux, or macOS.
## Prerequisites
- **.NET 10 SDK** (x86 components required for the plugin's NativeAOT publish; the Tools build with the regular SDK on any OS)
- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads — required by the NativeAOT ILC linker (Windows only, plugin only)
- RynthCore cloned at `C:\Projects\RynthCore\` (sibling to RynthSuite — project references point there)
- RynthSuite cloned at `C:\Projects\RynthSuite\`
If the plugin build fails with `'vswhere.exe' is not recognized`, add the VS Installer directory to PATH:
```powershell
$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer"
```
## Publish — Plugin (NativeAOT)
Always clean first — incremental NativeAOT builds can silently skip recompilation and produce a stale DLL.
```powershell
cd C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi
Remove-Item -Recurse -Force obj\Release, bin\Release -ErrorAction SilentlyContinue
dotnet publish -c Release
```
Output: `bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll` (~7 MB)
The plugin's MSBuild target also copies the published DLL into RynthCore's engine `bin\Release\net10.0-windows\win-x86\Plugins\` so a freshly built engine picks it up automatically. (RynthCore's engine publish has previously had a bug where it could overwrite the real plugin with a stale stub from `RynthCore/Plugins/`. That stale stub has been removed from RynthCore — if you see this regress, check that `C:\Projects\RynthCore\Plugins\` doesn't exist.)
## Build — Tools & SDK (cross-platform)
Plain `dotnet build` works for these:
```powershell
cd C:\Projects\RynthSuite\Tools\RynthCore.LootEditor
dotnet build -c Release
```
```powershell
cd C:\Projects\RynthSuite\Tools\RynthCore.MonsterEditor
dotnet build -c Release
```
```powershell
cd C:\Projects\RynthSuite\Tools\RynthCore.LootSdkTests
dotnet build -c Release
dotnet run -c Release
```
These projects target `net10.0` (no `-windows` suffix) and use Avalonia 11.2.3, so they build and run identically on Windows, Linux, and macOS.
## Deploy — Plugin
**AC can stay open** — plugins are shadow-copied at load time, so the file is not locked.
The recommended deploy location is `C:\Games\RynthSuite\RynthAi\` — alongside the plugin's data files (nav profiles, loot profiles, metas). Add this DLL path in the RynthCore launcher's **Plugins** tab. Paths are persisted to `%AppData%\RynthCore\engine.json`.
```powershell
copy bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthSuite\RynthAi\
```
Alternatively, deploy to the engine's built-in plugin directory (no launcher configuration needed):
```powershell
copy bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthCore\Runtime\Plugins\
```
After deploying a plugin with AC running, click **RL** on the RynthCore overlay bar to hot-reload.
## Verify
| File | Expected Size | If Wrong |
|------|--------------|----------|
| `RynthCore.Plugin.RynthAi.dll` | ~7 MB | If ~1 MB, you ran `dotnet build` instead of `dotnet publish` (no NativeAOT exports) |
To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory.
## Gotchas
- **`dotnet build` is not enough for the plugin.** NativeAOT only runs during `dotnet publish`. A `dotnet build` produces a valid managed DLL that compiles fine but has no unmanaged exports and will be silently ignored by the engine.
- **Clean before publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish.
- **Tools and SDK do not need `dotnet publish`.** They're plain managed assemblies — `dotnet build` is fine and faster.

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 tombohar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,166 @@
# RynthAi Activity Arbiter — rewrite plan
## STATUS: steps 1-5 all landed 2026-09-04 — NOT yet soaked
All five migration steps are in code. `ActivityArbiter.Apply` is the sole writer
of every `BotAction` string; the buff and salvage gap-fills, the four
`_*PausedNav` flags, the `IsCorpseNavigationClaimActive` nav gate, and
NavigationEngine's two self-promoting writes are all deleted. `OnTick` now asks
one question — what did the arbiter decide — and the string is a display
projection.
**Steps 4 and 5 shipped in the same build, which the Risk Controls below
explicitly warn against.** That was a deliberate scope call (2026-09-04), not an
oversight: it means a regression in the full loop has a two-step bisect surface
rather than one. Soak the patrol → aggro → fight → loot → salvage → resume loop
before trusting it, and if it misbehaves, suspect step 5 (the OnTick collapse)
before step 4 (the Looting/Salvaging migration) — step 5 changed who ticks, step
4 only changed who writes.
Remaining known deviations from the target design:
- The three UI resets (`LegacyDashboardRenderer` ×2, `LegacyNavigationUi` ×1)
still write `"Default"` directly on stop/reset. They are cosmetic — the
arbiter overwrites on the next tick — and were deliberately left alone.
- `OnTick` is not literally `switch(Current){ winner.Tick() }`. Manager call
order (salvage → mana/pet → crafting → combat/corpse → nav) carries behaviour
the plan never enumerated, so the decision gates *whether* each runs rather
than replacing the sequence wholesale.
- `NavigationEngine.Tick`'s own `shouldNav` still reads the string. It is now
redundant by construction (OnTick is the sole caller and only calls Tick when
the decision is Navigating) and is kept as an inner assertion, not a second
authority. One residual predating the migration: during a portal action with
Combat/Looting decided, that gate takes the stop path instead of running the
teleport detection the portal exception exists for. Closing it means deciding
whether nav should route-walk while combat owns the tick — a live-session
question, not a refactor.
- The Meta integration below is still deferred, and remains the right shape.
Worth noting the migration made it easier: meta mutates `_settings` (routes,
enables), and those are now arbiter *inputs*, so a meta write is recomputed
into the decision on the next tick instead of fighting a written string.
## Problem (proven 2026-05-15)
`LegacyUiSettings.BotAction` is a bare `string` written from ~20 sites across 6
files (BuffManager, CombatManager, CorpseOpenController, NavigationEngine, 2 UI
files, RynthAiPlugin gap-fill). No single owner. `RynthAiPlugin.OnTick` is a
~200-line imperative priority cascade with explicit "Gap-fill" hacks and a soup
of hand-managed pause flags (`_buffingPausedNav`, `_combatPausedNav`,
`_corpsePausedNav`, `_combatEndedAt`).
Priority is emergent from (tick order) × (each manager's bespoke gate) × (who
wrote the string last this tick). "Bot just stands there" = every subsystem
inspects the string, each concludes "not my turn," nobody executes, bot idles.
Unfixable by patching: each patch is another gap-fill that moves the dead zone.
## Target design
```
enum BotActivity { Idle, Navigating, Salvaging, Looting, Combat, Buffing }
// priority low→high: Idle < Navigating < Salvaging < Looting < Combat < Buffing
// (user-confirmed 2026-05-15)
```
Single `ActivityArbiter`. Each tick:
1. `arbiter.Decide()` calls a **pure** `WantsToRun()` query on each subsystem —
no game commands, no state writes, no BotAction mutation. Returns
`(bool wants, string reason)`.
2. Arbiter picks the highest-priority subsystem whose `WantsToRun()==true`.
3. Arbiter is the **sole writer** of `BotAction` (kept as string only for UI /
back-compat; derived from the winning `BotActivity`).
4. Arbiter calls **only the winner's** `Execute()`. Losers do nothing.
5. Arbiter logs every activity transition with the reason.
Structural property that kills the entire "stands there" bug class: claims are
recomputed from scratch every tick. Nothing persists. Combat cannot "hold a
lock" — no engageable target this tick → it doesn't claim → Navigation wins →
bot moves. No retained state to wedge. The pause-flag soup is deleted entirely;
"pause nav for combat" becomes "combat won the tick, nav's Execute didn't run."
## Subsystem `WantsToRun()` predicates (pure, cheap, no side effects)
- **Buffing**: `EnableBuffing && _buffManager.NeedsAnyBuff()` (already exists —
used by the gap-fill at RynthAiPlugin.cs:385).
- **Combat**: `EnableCombat && CombatManager has an engageable target` — needs a
new pure `HasEngageableTarget` (scanned target in range, not blacklisted, AC
combat-actable). Distinct from existing `HasTargets` which is too broad and
caused the squat-without-fighting bug.
- **Looting**: `CorpseOpenController has a reachable corpse with loot or a
pending loot action` — needs pure `HasLootWork`.
- **Salvaging**: `_salvageManager.IsBusy || queue non-empty` (IsBusy exists).
- **Navigating**: `IsMacroRunning && EnableNavigation && route loaded && not at
route end` — extract from NavigationEngine.Tick's `shouldNav` minus the
BotAction checks (those become the arbiter's job).
## Migration order (one testable step per commit)
1. **Add `BotActivity` enum + `ActivityArbiter` skeleton.** Arbiter computes the
winner from the predicates and writes BotAction. Do NOT yet remove manager
writes — run arbiter in "shadow mode": it logs `Arbiter: would pick X
(reason)` next to the real BotAction so we can compare its decision to the
legacy cascade on real sessions WITHOUT changing behavior. **Test: confirm
arbiter's shadow decision matches sane expectation across combat/nav/buff.**
2. **Flip arbiter to authoritative for the Navigating↔Combat boundary only.**
Remove CombatManager's 4 BotAction writes + NavigationEngine's gate; both now
read `arbiter.Current`. Leave Buffing/Looting/Salvage on the legacy path.
**Test: the exact "stands there surrounded by mobs / 2-steps-and-stops"
repro. This is the highest-value, smallest-surface step.**
3. **Migrate Buffing** into the arbiter; delete the RynthAiPlugin gap-fill
(lines ~380-389) and BuffManager's 6 writes. **Test: buff cycle + combat
interleave; no "You're too busy" lock.**
4. **Migrate Looting + Salvaging**; delete CorpseOpenController's 5 writes, the
salvage gap-fill (~line 434), and all `_*PausedNav` flags. **Test: full
loop — patrol → aggro → fight → loot → salvage → resume patrol.**
*(DONE 2026-09-04. `HasLootWork` answers "is there loot work in range"
rather than "have I claimed a corpse", so the decision leads the claim
instead of lagging a tick behind it and handing nav a free step.)*
5. **Delete dead code**: the entire OnTick imperative cascade, pause flags,
`_combatEndedAt`. OnTick becomes `arbiter.Tick()`.
*(DONE 2026-09-04, with two deliberate deviations. `_combatEndedAt` SURVIVES
as loot-grace: corpse CreateObjects arrive a tick or two after the kill, and
deleting it would let nav walk away from a body that is about to exist. It is
no longer a lock — it feeds the pure `HasLootWork` predicate, which is the
property that mattered. And `BoostNavPriority`/`BoostLootPriority`, which the
cascade implemented by stomping the string, became inputs to `Decide()`.)*
## Risk controls
- Step 1 is shadow-mode: zero behavior change, pure observability. Validates the
arbiter's decisions against reality before it controls anything.
- Each subsequent step is independently testable and revertable (one subsystem
at a time).
- The state-change logging added 2026-05-15 (`Nav: state`, `Combat: state`)
stays — it's exactly the instrumentation needed to validate each step.
- Do NOT do steps 2-5 in one session without a test between each. The failure
mode of this whole project is untested control-flow changes regressing a
working state.
## Non-goals
- NOT rewriting CombatManager targeting, BuffManager spell selection, or
NavigationEngine pathing. Those work. Only the coordination/arbitration glue
is replaced.
- NOT touching the engine (RynthCore) — this is entirely RynthAi plugin-side.
## Deferred inbound integration: Meta (added 2026-05-17)
The meta-system review (`Docs/MetaManager_Review.md` §3.1/§3.2) found that
MetaManager is an unaccounted-for ~20th writer of `BotAction`/state: meta
actions (`SetState`, `SetRAOption`→`VtOptionMap`, `EmbedNav`) mutate
`_settings` one tick *after* the arbiter decides, so meta silently fights the
arbiter. The proper fix is to make Meta a **declared arbiter input** (a
high-priority claimant when a meta rule wants to force a state), not a post-hoc
settings mutator.
This is intentionally **deferred** — it is NOT one of steps 2-5 above and must
not be bolted onto a half-migrated arbiter mid-soak (same failure mode the Risk
Controls warn about). Sequence it as its own step **after** steps 2-5 land and
soak clean: add a `Meta` claimant to the arbiter with priority above the
operational activities (a fired meta `SetState` should win over Combat/Nav
cycling), and delete meta's direct `_settings` writes in favour of an arbiter
claim. Until then, the meta-review Day1-Week1 changes (locking, recursion guard,
schema, observability) are independent and already shipped.

View file

@ -0,0 +1,211 @@
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Centralized activity priority arbiter — replacement for the distributed
/// string-based BotAction state machine. See ACTIVITY_ARBITER_PLAN.md.
///
/// Migration state (2026-09-04): STEP 5 of 5 — COMPLETE. Apply() is the SOLE
/// writer of every BotAction string (Buffing / Combat / Looting / Salvaging /
/// Navigating / Default). No manager writes it any more; the OnTick buff and
/// salvage gap-fills and the four hand-managed nav pause flags are gone. The
/// string is now a display projection of <see cref="Current"/>, and Current is
/// what gates the OnTick body.
///
/// ShadowObserve() is the step-1 observation path, kept for re-validating a
/// predicate change against a live session without giving it control.
///
/// Priority (user-confirmed 2026-05-15), low→high:
/// Idle &lt; Navigating &lt; Salvaging &lt; Looting &lt; Combat &lt; Buffing
///
/// The two Boost* user settings invert part of that order. They used to be
/// implemented by stomping the string from the OnTick cascade ("if boosting nav
/// and the action is Combat/Looting, force it back to Default"), which is
/// exactly the multi-writer pattern this class exists to kill. They are inputs
/// to Decide() now — see the override block there.
/// </summary>
internal enum BotActivity
{
Idle = 0,
Navigating = 1,
Salvaging = 2,
Looting = 3,
Combat = 4,
Buffing = 5,
}
/// <summary>
/// Immutable snapshot of the pure "do you want to run" signals, captured once
/// per tick by the caller. The arbiter is a pure function of this snapshot —
/// no side effects, no game commands, no state writes. That purity is the
/// whole point: the decision is recomputed from scratch every tick, so no
/// subsystem can wedge the bot by leaving a stale lock behind.
/// </summary>
internal readonly struct ArbiterInputs
{
public readonly bool MacroRunning;
public readonly bool WantBuffing; // pending cast, vital recharge, or EnableBuffing && NeedsAnyBuff()
public readonly bool WantCombat; // EnableCombat && has engageable target
public readonly bool WantLooting; // open container, claimed corpse, unlooted corpse in range, or loot grace
public readonly bool WantSalvaging; // salvage queue / busy
public readonly bool WantNav; // macro && navEnabled && route loaded
/// <summary>Actively engaged (a live attack target), not merely "something is engageable".</summary>
public readonly bool CombatEngaged;
/// <summary>BoostNavPriority — navigation preempts combat and looting.</summary>
public readonly bool BoostNav;
/// <summary>BoostLootPriority — looting preempts combat.</summary>
public readonly bool BoostLoot;
/// <summary>
/// Fellowship-follow is steering. A display sub-state of Navigating, not a
/// priority tier of its own: it changes the projected string to "Following"
/// but never changes who wins the tick.
/// </summary>
public readonly bool FollowActive;
public ArbiterInputs(bool macroRunning, bool wantBuffing, bool wantCombat,
bool wantLooting, bool wantSalvaging, bool wantNav,
bool combatEngaged = false, bool boostNav = false, bool boostLoot = false,
bool followActive = false)
{
MacroRunning = macroRunning;
WantBuffing = wantBuffing;
WantCombat = wantCombat;
WantLooting = wantLooting;
WantSalvaging = wantSalvaging;
WantNav = wantNav;
CombatEngaged = combatEngaged;
BoostNav = boostNav;
BoostLoot = boostLoot;
FollowActive = followActive;
}
}
internal sealed class ActivityArbiter
{
private readonly System.Action<string> _log;
private string _lastShadowKey = "";
public ActivityArbiter(System.Action<string> log) => _log = log;
/// <summary>
/// Pure decision: highest-priority subsystem that wants to run.
/// Returns Idle when the macro is stopped or nobody wants to run.
/// </summary>
public static BotActivity Decide(in ArbiterInputs s)
{
if (!s.MacroRunning) return BotActivity.Idle;
// Buffing is unconditionally top priority — buffs are survival, and a
// cast awaiting server confirmation must not be preempted mid-flight.
// No Boost* flag outranks it.
if (s.WantBuffing) return BotActivity.Buffing;
// ── User priority overrides ────────────────────────────────────────
// BoostNavPriority: nav outranks combat and looting. Only meaningful
// when there is actually a route to run, hence the WantNav guard —
// without it the flag just starved combat and the bot stood among mobs
// without hunting.
if (s.BoostNav && s.WantNav) return BotActivity.Navigating;
// BoostLootPriority: looting outranks combat — EXCEPT while actively
// engaged. A mob already swinging at you gets fought whatever the flag
// says; otherwise "walk to the corpse" starves combat and the bot takes
// hits with zero attack ticks. That is the 2026-06-03 audit's P1#1,
// which was a hatch bolted onto the OnTick cascade and becomes this one
// clause instead.
if (s.BoostLoot && s.WantLooting && !s.CombatEngaged) return BotActivity.Looting;
// ── Default order ─────────────────────────────────────────────────
if (s.WantCombat) return BotActivity.Combat;
if (s.WantLooting) return BotActivity.Looting;
if (s.WantSalvaging) return BotActivity.Salvaging;
if (s.WantNav) return BotActivity.Navigating;
return BotActivity.Idle;
}
/// <summary>
/// Map a BotActivity to the legacy BotAction string the rest of the
/// codebase (and UI) still reads. Single source of truth for the mapping
/// so there is exactly one writer.
/// </summary>
public static string ToBotAction(BotActivity a) => a switch
{
BotActivity.Buffing => "Buffing",
BotActivity.Combat => "Combat",
BotActivity.Looting => "Looting",
BotActivity.Salvaging => "Salvaging",
BotActivity.Navigating => "Navigating",
_ => "Default",
};
/// <summary>
/// STEP 1 shadow mode. Compute the would-be decision and log it whenever
/// it (or the legacy BotAction it's being compared against) changes.
/// Caller still runs the legacy cascade; this only observes.
/// </summary>
public void ShadowObserve(in ArbiterInputs s, string legacyBotAction)
{
BotActivity decision = Decide(in s);
string wouldBe = ToBotAction(decision);
bool agrees = string.Equals(wouldBe, string.IsNullOrEmpty(legacyBotAction) ? "Default" : legacyBotAction,
System.StringComparison.OrdinalIgnoreCase);
string key = $"{decision} want[buff={s.WantBuffing} cbt={s.WantCombat} loot={s.WantLooting} salv={s.WantSalvaging} nav={s.WantNav}] legacy={legacyBotAction} agree={agrees}";
if (key == _lastShadowKey) return;
_lastShadowKey = key;
_log($"Arbiter[shadow]: would={wouldBe} legacy={legacyBotAction} agree={agrees} | {key}");
}
/// <summary>The arbiter's most recent decision. Authoritative as of Step 5.</summary>
public BotActivity Current { get; private set; } = BotActivity.Idle;
private const System.StringComparison OIC = System.StringComparison.OrdinalIgnoreCase;
/// <summary>
/// Sole writer of BotAction, for every activity. Being the single writer is
/// what eliminates the stuck-lock "bot just stands there" freeze: the
/// decision is recomputed from the pure inputs every tick, so no manager can
/// strand a lock it forgot to release, and there is no ordering in which two
/// writers can disagree.
///
/// Returns the decision so the caller can gate the tick body on it — the
/// typed value is the authority; the string exists for the UI, the Meta
/// expression engine, and CombatManager's canRun read.
/// </summary>
public BotActivity Apply(in ArbiterInputs s, LegacyUi.LegacyUiSettings settings)
{
BotActivity decision = Decide(in s);
Current = decision;
string legacy = settings.BotAction ?? "Default";
// "Following" is Navigating's display variant, not a priority tier —
// NavigationEngine used to write it itself (and self-promote "Default"
// to "Navigating"), which was the last violation of the single-writer
// invariant this class's own comments claimed to hold.
string desired = decision == BotActivity.Navigating && s.FollowActive
? "Following"
: ToBotAction(decision);
if (!string.Equals(legacy, desired, OIC))
{
settings.BotAction = desired;
LogDecisionIfChanged(decision, s, desired, wrote: true);
}
else
{
LogDecisionIfChanged(decision, s, legacy, wrote: false);
}
return decision;
}
private string _lastDecisionKey = "";
private void LogDecisionIfChanged(BotActivity decision, in ArbiterInputs s, string botAction, bool wrote)
{
string key = $"{decision} wrote={wrote} ba={botAction} want[buff={s.WantBuffing} cbt={s.WantCombat} loot={s.WantLooting} salv={s.WantSalvaging} nav={s.WantNav}]"
+ $" eng={s.CombatEngaged} boost[nav={s.BoostNav} loot={s.BoostLoot}]";
if (key == _lastDecisionKey) return;
_lastDecisionKey = key;
_log($"Arbiter[step5]: {key}");
}
}

View file

@ -0,0 +1,485 @@
// AcStubs.cs — Minimal stub types for AC client interop.
// TODO: Replace each stub with a proper RynthCore implementation, one at a time.
using System;
using System.Collections.Generic;
using RynthCore.Loot; // AcObjectClass, AcSkillType live in the shared SDK
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// STypeInt keys used with TryGetObjectIntProperty / WorldObjectCache.GetIntProperty.
/// Values match Chorizite STypes.cs STypeInt sequential enum.
/// </summary>
public enum LongValueKey
{
TemplateType = 2, // WeenieType / creature template type ID
ItemsCapacity = 6, // max items a container can hold
ContainersCapacity = 7, // max sub-containers a container can hold
Locations = 9, // equipment slot bitmask (valid equip locations)
CurrentWieldedLocation = 10, // slot item is currently wielded in (0 = not wielded)
MaxStackSize = 11, // max stack size (StackMax)
StackCount = 12, // current stack size (StackSize)
DamageType = 45, // DAMAGE_TYPE flags
MaximumHealth = 39, // creature base max HP (STypeInt 39)
CreatureType = 62, // creature type / species ID
// AUGMENTATION_INCREASED_SPELL_DURATION — Archmage's Endurance, stacks 5x.
// Each rank adds +20% enchantment duration. Verified against Chorizite
// AcClient/STypes.cs STypeInt ordinal 238.
AugmentationIncreasedSpellDuration = 238,
// Legacy alias kept for call-site compatibility
EquippedSlots = 10,
}
/// <summary>
/// STypeString keys used with TryGetObjectStringProperty / WorldObjectCache.GetStringProperty.
/// Values match Chorizite's STypeString sequential enum.
/// </summary>
public enum StringValueKey
{
Name = 1,
ShortDesc = 15,
LongDesc = 16,
PluralName = 20,
DisplayName = 42,
}
/// <summary>
/// STypeFloat keys used with TryGetObjectDoubleProperty / WorldObjectCache.GetDoubleProperty.
/// Values match Chorizite's STypeFloat sequential enum.
/// </summary>
public enum DoubleValueKey
{
DamageVariance = 22,
CurrentPowerMod = 23,
AccuracyMod = 24,
WeaponDefense = 29,
UseRadius = 54,
WeaponOffense = 61,
DamageMod = 62,
PowerLevel = 86,
AccuracyLevel = 87,
}
// ── Combat mode int constants (matches acclient.exe CM_Combat enum) ────────
public static class CombatMode
{
public const int NonCombat = 1;
public const int Melee = 2;
public const int Missile = 4;
public const int Magic = 8;
}
// ── WorldObject stub ───────────────────────────────────────────────────────
// TODO: Populate from OnCreateObject + TryGetObjectName/Position events
public class WorldObject
{
public int Id { get; }
public string Name { get; }
public AcObjectClass ObjectClass { get; }
public int Container => Cache?.GetContainerId(Id) ?? 0;
public int Wielder => Cache?.GetWielderId(Id) ?? 0;
public int WieldedLocation => _wieldedLocationDirect >= 0 ? _wieldedLocationDirect : (Cache?.GetWieldedLocation(Id) ?? 0);
// Direct override for items discovered by lightweight scan (bypasses cache)
internal int _wieldedLocationDirect = -1;
// Remote full-inventory capture (P1): stashed by WorldObjectCache during the direct-inventory
// BFS walk so the snapshot is self-contained. _directContainerId/_directSlot come from the BFS
// structure (the container we just enumerated + the item's index in its contents array) — more
// reliable than a live Container read, which AutoCram showed can return 0/stale off-thread.
internal int _directContainerId; // parent container GUID (player or a side-pack), 0 if unset
internal int _directSlot = -1; // 0-based position in GetContainerContents(), -1 if unset
public int DirectContainerId => _directContainerId;
public int DirectSlot => _directSlot;
public WorldObject(int id, string name, AcObjectClass objectClass = AcObjectClass.Unknown)
{
Id = id;
Name = name ?? "";
ObjectClass = objectClass;
}
// Set by WorldObjectCache when it creates/updates this object
internal WorldObjectCache? Cache { get; set; }
public int Values(LongValueKey key, int defaultValue)
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
public int Values(int key, int defaultValue)
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
public string Values(StringValueKey key, string defaultValue)
=> Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
public double Values(DoubleValueKey key, double defaultValue)
=> Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
}
// ── SpellInfo stub ────────────────────────────────────────────────────────
public class SpellInfo
{
public int Id { get; }
public string Name { get; }
/// <summary>
/// Spell family — groups all tiers of the same spell (e.g. Strength Self I–VIII).
/// Derived by stripping tier suffixes from the spell name.
/// </summary>
public int Family { get; }
/// <summary>Spell LEVEL 1-8 (the roman-numeral tier of THIS spell), or 0 if not derivable.
/// Roman suffix (e.g. "... VII"=7) first; else "Incantation of ..."=8 and tier-7 lore names=7.
/// This is the spell's own level — distinct from the caster's highest castable tier.</summary>
public int Level { get; }
public SpellInfo(int id, string name)
{
Id = id;
Name = name ?? "";
Family = ComputeFamily(Name);
Level = ComputeLevel(Name);
}
private static readonly string[] TierSuffixes =
{
" Self VIII", " Self VII", " Self VI", " Self V", " Self IV", " Self III", " Self II", " Self I",
" Other VIII", " Other VII", " Other VI", " Other V", " Other IV", " Other III", " Other II", " Other I",
" VIII", " VII", " VI", " V", " IV", " III", " II", " I",
};
/// <summary>
/// Maps tier 7 lore names back to their base spell names so all tiers
/// of the same spell produce the same family hash. Without this,
/// "Inferno's Bane" (tier 7) and "Incantation of Flame Bane" (tier 8)
/// would hash to different families, breaking timer lookups.
/// </summary>
private static readonly Dictionary<string, string> LoreToBase = new(StringComparer.OrdinalIgnoreCase)
{
// Creature buffs
{ "Might of the Lugians", "Strength" },
{ "Preservance", "Endurance" }, { "Perseverance", "Endurance" },
{ "Honed Control", "Coordination" },
{ "Hastening", "Quickness" },
{ "Inner Calm", "Focus" },
{ "Mind Blossom", "Willpower" },
{ "Aura of Defense", "Invulnerability" },
{ "Aura of Deflection", "Impregnability" },
{ "Aura of Resistance", "Magic Resistance" },
// Life protections
{ "Executor's Blessing", "Armor" },
{ "Caustic Blessing", "Acid Protection" },
{ "Blessing of the Blade Turner", "Blade Protection" },
{ "Blessing of the Mace Turner", "Bludgeoning Protection" },
{ "Icy Blessing", "Cold Protection" },
{ "Fiery Blessing", "Fire Protection" },
{ "Storm's Blessing", "Lightning Protection" },
{ "Blessing of the Arrow Turner", "Piercing Protection" },
{ "Battlemage's Blessing", "Mana Renewal" },
{ "Robustify", "Regeneration" },
{ "Unflinching Persistence", "Rejuvenation" }, { "Unfinching Persistance", "Rejuvenation" },
{ "Adja's Intervention", "Heal" },
{ "Robustification", "Revitalize" },
{ "Meditative Trance", "Stamina to Mana" },
{ "Rushed Recovery", "Stamina to Health" },
// Skill masteries
{ "Topheron's Blessing", "Monster Attunement" },
{ "Kaluhc's Blessing", "Person Attunement" },
{ "Aliester's Blessing", "Arcane Enlightenment" },
{ "Jibril's Blessing", "Armor Tinkering Expertise" },
{ "Yoshi's Blessing", "Item Tinkering Expertise" },
{ "Koga's Blessing", "Weapon Tinkering Expertise" },
{ "Nuhmidira's Blessing", "Mana Conversion Mastery" },
{ "Saladur's Blessing", "Sprint" },
{ "Jahannan's Blessing", "Jumping Mastery" },
{ "Odif's Blessing", "Fealty" }, { "Odif's Boon", "Fealty" },
{ "Ar-Pei's Blessing", "Leadership Mastery" },
{ "Ketnan's Blessing", "Deception Mastery" },
{ "Avalenne's Blessing", "Healing Mastery" },
{ "Oswald's Blessing", "Lockpick Mastery" },
{ "Morimoto's Blessing", "Cooking Mastery" },
{ "Lilitha's Blessing", "Fletching Mastery" },
{ "Silencia's Blessing", "Alchemy Mastery" },
{ "Adja's Blessing", "Creature Enchantment Mastery" },
{ "Celcynd's Blessing", "Item Enchantment Mastery" },
{ "Harlune's Blessing", "Life Magic Mastery" },
{ "Hieromancer's Blessing", "War Magic Mastery" },
// Weapon auras
{ "Aura of Infected Caress", "Blood Drinker" },
{ "Aura of Mystic's Blessing", "Hermetic Link" },
{ "Aura of Elysa's Sight", "Heart Seeker" },
{ "Aura of Infected Spirit Carress", "Spirit Drinker" },
{ "Aura of Infected Spirit Caress", "Spirit Drinker" },
{ "Aura of Atlan's Alacrity", "Swift Killer" },
{ "Aura of Cragstone's Will", "Defender" },
// Armor banes
{ "Brogard's Defiance", "Impenetrability" },
{ "Olthoi's Bane", "Acid Bane" },
{ "Swordsman's Bane", "Blade Bane" }, { "Swordman's Bane", "Blade Bane" },
{ "Tusker's Bane", "Bludgeoning Bane" },
{ "Inferno's Bane", "Flame Bane" },
{ "Gelidite's Bane", "Frost Bane" },
{ "Astyrrian's Bane", "Lightning Bane" },
{ "Archer's Bane", "Piercing Bane" },
};
// Derive the spell's own level (1-8). Roman suffix wins; else an "Incantation of ..."
// form is level 8 and a recognized tier-7 lore name is level 7. 0 = not derivable.
private static int ComputeLevel(string spellName)
{
if (string.IsNullOrEmpty(spellName)) return 0;
int sp = spellName.TrimEnd().LastIndexOf(' ');
if (sp >= 0)
{
switch (spellName.Trim()[(sp + 1)..].ToUpperInvariant())
{
case "I": return 1;
case "II": return 2;
case "III": return 3;
case "IV": return 4;
case "V": return 5;
case "VI": return 6;
case "VII": return 7;
case "VIII": return 8;
}
}
if (spellName.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) return 8;
if (LoreToBase.ContainsKey(spellName.Trim())) return 7;
return 0;
}
private static int ComputeFamily(string spellName)
{
string n = spellName;
// 1. Strip tier suffixes (e.g. " Self VII", " VIII")
foreach (var s in TierSuffixes)
{
if (n.EndsWith(s, StringComparison.OrdinalIgnoreCase))
{ n = n[..^s.Length].Trim(); break; }
}
// 2. Map tier 7 lore names to base names BEFORE stripping prefixes,
// since lore names like "Aura of Infected Caress" include the prefix.
if (LoreToBase.TryGetValue(n, out string? baseName))
n = baseName;
// 3. Strip "Incantation of " and "Aura of " prefixes (handles
// "Aura of Incantation of X Self" layered prefix forms)
bool changed = true;
while (changed)
{
changed = false;
if (n.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase))
{ n = n[15..].Trim(); changed = true; }
if (n.StartsWith("Aura of ", StringComparison.OrdinalIgnoreCase))
{ n = n[8..].Trim(); changed = true; }
}
// 4. Strip " Self" / " Other" target suffixes, then lowercase
n = n.Replace(" Self", "").Replace(" Other", "").Trim().ToLowerInvariant();
// FNV-1a — deterministic across sessions (String.GetHashCode is randomized in .NET 5+)
unchecked
{
int hash = (int)2166136261u;
foreach (char c in n)
hash = (hash ^ c) * 16777619;
return (int)((uint)hash & 0x7FFFFFFF); // strip sign bit, keep positive
}
}
}
// ── SpellTable stub ────────────────────────────────────────────────────────
// Backed by SpellDatabase (embedded SpellData.txt)
public static class SpellTableStub
{
public static SpellInfo? GetById(int spellId)
{
string name = SpellDatabase.GetSpellNameOrId(spellId);
// GetSpellNameOrId returns the id as a string if not found
if (name == spellId.ToString()) return null;
return new SpellInfo(spellId, name);
}
}
// ── Character skills ───────────────────────────────────────────────────────
// Reads live skill data via CACQualities::InqSkillLevel / InqSkillAdvancementClass.
// SKILL_ADVANCEMENT_CLASS: UNDEF=0, UNTRAINED=1, TRAINED=2, SPECIALIZED=3.
public class CharacterSkillInfo
{
public int Training { get; }
public int Buffed { get; }
public CharacterSkillInfo(int training, int buffed)
{
Training = training;
Buffed = buffed;
}
}
public class CharacterSkills
{
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
private uint _playerId;
// Last successful (training, buffed) read per skill. The host call can
// transiently fail before the engine seeds the player qualities ptr; a
// failed read is NOT the same as "skill untrained" and must not be
// reported as (0,0) (that pins ComputeTier to tier 1 and trips
// IsSkillUsable false → bot casts level-1 spells and runs unbuffed).
private readonly Dictionary<AcSkillType, CharacterSkillInfo> _lastGood = new();
private bool _loggedReadFailure;
public CharacterSkills(RynthCore.PluginSdk.RynthCoreHost host)
{
_host = host;
}
public void SetPlayerId(uint playerId) => _playerId = playerId;
public CharacterSkillInfo this[AcSkillType skill]
{
get
{
if (_playerId == 0 || !_host.HasGetObjectSkill)
return new CharacterSkillInfo(2, 250); // fallback stubs
uint stype = AcSkillTypeToSTypeSkill(skill);
if (stype == 0)
return new CharacterSkillInfo(2, 250);
if (_host.TryGetObjectSkill(_playerId, stype, out int buffed, out int training))
{
bool hadGood = _lastGood.TryGetValue(skill, out var prev);
// A "successful" read of buffed <= 0 for a skill that is
// trained, or that previously read a real value, is an engine
// qualities artifact — not a legitimate skill level. A live,
// trained, in-world skill's buffed value (base + attributes +
// augs + enchantments) is never literally 0; the engine can
// momentarily return success+0 when InqSkill transiently
// fails during a state transition, or the off-thread snapshot
// serves a briefly-zeroed entry. Trusting it here would poison
// _lastGood with (training, 0) permanently → ComputeTier pins
// to tier 1 → war magic collapses to level-1 streaks for the
// rest of the session. Reject it: keep last-good (self-heals
// the instant a real value returns), else the capable stub.
// A genuinely untrained skill (training < 2, never any good
// read) still flows through with its real value as before —
// the training-based gates exclude it, not this.
bool zeroArtifact = buffed <= 0 &&
(training >= 2 || (hadGood && prev.Buffed > 0));
if (!zeroArtifact)
{
var info = new CharacterSkillInfo(training, buffed);
_lastGood[skill] = info;
return info;
}
if (hadGood)
return prev;
if (!_loggedReadFailure)
{
_loggedReadFailure = true;
_host.Log($"[RynthAi] CharacterSkills: host returned success+buffed=0 for trained skill {skill} (player=0x{_playerId:X8}, stype={stype}, training={training}) — engine qualities artifact, not a real level. Using capable-stub fallback until a real read lands (NOT collapsing tier).");
}
return new CharacterSkillInfo(2, 250);
}
// Host read failed. Prefer the last good read; if we never had
// one, fall back to the same "assume capable" stub the other
// unknown-state branches use so the bot stays functional rather
// than silently dropping to tier-1/unbuffed. Surface it once.
if (_lastGood.TryGetValue(skill, out var cached))
return cached;
if (!_loggedReadFailure)
{
_loggedReadFailure = true;
_host.Log($"[RynthAi] CharacterSkills: host skill read failed (player=0x{_playerId:X8}, skill={skill}, stype={stype}) — engine player-qualities ptr likely not seeded. Using capable-stub fallback until a real read lands.");
}
return new CharacterSkillInfo(2, 250);
}
}
/// <summary>
/// Maps AcSkillType to AC's internal STypeSkill sequential enum values
/// (from Chorizite STypes.cs STypeSkill enum, 0-based sequential).
/// </summary>
public static uint AcSkillTypeToSTypeSkill(AcSkillType skill) => skill switch
{
AcSkillType.MeleeDefense => 6,
AcSkillType.MissileDefense => 7,
AcSkillType.MagicDefense => 15,
AcSkillType.ItemEnchantment => 32,
AcSkillType.LifeMagic => 33,
AcSkillType.CreatureEnchantment => 31,
AcSkillType.WarMagic => 34,
AcSkillType.VoidMagic => 43,
AcSkillType.HeavyWeapons => 44,
AcSkillType.LightWeapons => 45,
AcSkillType.FinesseWeapons => 46,
AcSkillType.TwoHandedCombat => 41,
AcSkillType.Shield => 48,
AcSkillType.DualWield => 49,
AcSkillType.Recklessness => 50,
AcSkillType.SneakAttack => 51,
AcSkillType.DirtyFighting => 52,
AcSkillType.ArcaneLore => 14,
AcSkillType.ArmorTinkering => 29,
AcSkillType.ItemTinkering => 18,
AcSkillType.MagicItemTinkering => 30,
AcSkillType.WeaponTinkering => 28,
AcSkillType.Salvaging => 40,
AcSkillType.Run => 24,
AcSkillType.Jump => 22,
AcSkillType.Loyalty => 36,
AcSkillType.Leadership => 35,
AcSkillType.Deception => 20,
AcSkillType.Healing => 21,
AcSkillType.Lockpick => 23,
AcSkillType.Cooking => 39,
AcSkillType.Fletching => 37,
AcSkillType.Alchemy => 38,
AcSkillType.ManaConversion => 16,
AcSkillType.AssessCreature => 27,
AcSkillType.AssessPerson => 19,
AcSkillType.Summoning => 54,
_ => 0,
};
}
// ── Enchantment stub ───────────────────────────────────────────────────────
public class EnchantmentInfo
{
public int SpellId { get; }
public double TimeRemaining { get; }
public EnchantmentInfo(int spellId, double timeRemaining) { SpellId = spellId; TimeRemaining = timeRemaining; }
}
// ── Player vitals cache ────────────────────────────────────────────────────
// Updated from OnUpdateHealth + periodic TryGetPlayerVitals polls
public class PlayerVitalsCache
{
public uint MaxHealth { get; set; }
public uint CurrentHealth { get; set; }
public uint MaxMana { get; set; }
public uint CurrentMana { get; set; }
public uint MaxStamina { get; set; }
public uint CurrentStamina { get; set; }
public int HealthPct => MaxHealth > 0 ? (int)(CurrentHealth * 100u / MaxHealth) : 100;
public int ManaPct => MaxMana > 0 ? (int)(CurrentMana * 100u / MaxMana) : 100;
public int StaminaPct => MaxStamina > 0 ? (int)(CurrentStamina * 100u / MaxStamina) : 100;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,68 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Stuck-state backstop for the engine's CMotionInterp cast-gesture gate
/// (<c>_host.CanCastNow</c>). That gate reads <c>[CMI+0x80]</c>; if it ever
/// stays non-zero indefinitely — a server-refused "You're too busy!" can leave
/// a one-shot motion node that never pops, and the +0x80 offset was never 100%
/// pinned offline — BOTH the buff (<c>BuffManager.OnHeartbeat</c>) and combat
/// (<c>CombatManager</c> magic) paths hard-return on <c>!CanCastNow</c> every
/// tick and the bot freezes standing in place. The engine has no self-recovery
/// for this and there is no BusyCount-style watchdog.
///
/// Logic: pass the gate through untouched while it behaves; if it has been
/// continuously closed longer than any legitimate cast wind-up+release, declare
/// it stuck and report "clear", then keep reporting clear until the engine gate
/// genuinely recovers (raw == true again). When overriding we are exactly in
/// the documented "engine without the gate" mode (CanCastNow defaults true) —
/// the <c>SpellCastIntervalMs</c> throttle and the "too busy" PARK path remain
/// the anti-spam guarantees, so this cannot reintroduce the 0x00460D1D
/// refusal-loop AV.
/// </summary>
internal static class CastGateWatchdog
{
// Longer than any real AC cast gesture (~1–3s). Continuously closed past
// this ⇒ the gate is stuck, not a legitimate in-progress gesture.
private const double StuckMs = 4000;
private static DateTime _closedSince = DateTime.MinValue;
private static bool _overriding;
/// <summary>
/// Effective "clear to cast": the raw engine gate plus a stuck backstop.
/// Call with <c>_host.CanCastNow</c>; optionally pass a logger for the
/// one-shot stuck/recovered transitions.
/// </summary>
public static bool CanCastNow(bool rawCanCastNow, Action<string>? log = null)
{
if (rawCanCastNow)
{
if (_overriding)
{
log?.Invoke("[CastGate] engine gate recovered — stuck override cleared.");
_overriding = false;
}
_closedSince = DateTime.MinValue;
return true;
}
// Raw gate reports a gesture in progress.
if (_overriding)
return true; // already declared stuck; stay open until the engine gate recovers
if (_closedSince == DateTime.MinValue)
_closedSince = DateTime.Now;
if ((DateTime.Now - _closedSince).TotalMilliseconds > StuckMs)
{
_overriding = true;
log?.Invoke($"[CastGate] CanCastNow stuck false >{StuckMs:F0}ms — overriding gate open " +
"(SpellCastIntervalMs throttle + 'too busy' PARK remain the anti-spam backstop).");
return true;
}
return false;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,508 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Win32;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Spell component data read from client_portal.dat (SpellComponentTable, ID 0x0E00000F).
///
/// Binary format (little-endian):
/// Header: uint32 fileId | uint16 count | uint16 skip
/// Per entry:
/// uint32 key (component ID)
/// uint16 nameLen
/// byte[] nameBytes (nibble-swapped ASCII, length = nameLen)
/// byte[] pad (pad name to 4-byte boundary from nameLen field start)
/// uint32 category (SpellComponentCategory: 0=Scarab,1=Herb,2=PowderedGem,…)
/// uint32 icon
/// uint32 type (ComponentType / SpellComponentCategory as enum value)
/// uint32 gesture
/// float time (gesture speed)
/// uint16 textLen
/// byte[] textBytes (nibble-swapped ASCII, length = textLen)
/// byte[] pad (pad text to 4-byte boundary from textLen field start)
/// float cdm (Component Destruction Modifier = BurnRate)
///
/// String decoding: each byte → nibble-swap → ((b << 4) | (b >> 4)) & 0xFF
/// </summary>
internal static class ComponentDatabase
{
public sealed class ComponentRecord
{
public uint Id;
public string Name = "";
public uint Category;
public uint IconId;
public uint Type;
public uint GestureId;
public float GestureSpeed;
public string Word = "";
public float BurnRate;
public string CategoryName => Category switch
{
0 => "Scarab",
1 => "Herb",
2 => "PowderedGem",
3 => "AlchemicalSubstance",
4 => "Talisman",
5 => "Taper",
6 => "Pea",
_ => $"Unknown({Category})"
};
public string TypeName => Type switch
{
1 => "Scarab",
2 => "Herb",
3 => "Powder",
4 => "Potion",
5 => "Talisman",
6 => "Taper",
7 => "Pea",
_ => $"Unknown({Type})"
};
}
private static readonly Dictionary<uint, ComponentRecord> _cache = new();
// spellId → required component ids, decrypted account-INDEPENDENTLY from
// the SpellTable (0x0E00000E) via the Name+Desc key (see ParseSpellTable).
// The per-account scramble (GetSpellFormula) only re-rolls the taper slots,
// which we treat as "any taper", so the account name is never needed.
private static readonly Dictionary<int, uint[]> _spellComps = new();
private static bool _spellCompsLoaded;
private static bool _loaded;
private static readonly object _lock = new();
private static Action<string>? _log;
public static void SetLog(Action<string> log) => _log = log;
public static bool IsLoaded => _loaded;
public static void EnsureLoaded(Action<string>? log = null)
{
lock (_lock)
{
if (_loaded) return;
LoadFromDat(log);
}
}
private static void LoadFromDat(Action<string>? log)
{
log ??= _log;
string? datPath = FindPortalDat();
if (datPath == null)
{
log?.Invoke("[ComponentDB] Could not find portal.dat");
return;
}
try
{
log?.Invoke($"[ComponentDB] Opening {Path.GetFileName(datPath)}");
using var dat = new DatDatabase();
if (!dat.Open(datPath))
{
log?.Invoke($"[ComponentDB] Failed to open dat: {string.Join(", ", dat.DiagLog)}");
return;
}
byte[]? raw = dat.GetFileData(0x0E00000F);
if (raw == null || raw.Length < 8)
{
log?.Invoke("[ComponentDB] SpellComponentTable (0x0E00000F) not found");
return;
}
int found = Parse(raw, log);
_loaded = found > 0;
log?.Invoke($"[ComponentDB] Loaded {found} component(s) from dat.");
// Same open dat: pull the SpellTable so the combat resolver can
// predictively skip a spell whose components the char lacks.
try
{
byte[]? spellRaw = dat.GetFileData(0x0E00000E);
if (spellRaw == null || spellRaw.Length < 8)
{
log?.Invoke("[ComponentDB] SpellTable (0x0E00000E) not found");
}
else
{
int spells = ParseSpellTable(spellRaw, log);
_spellCompsLoaded = spells > 0;
log?.Invoke($"[ComponentDB] Loaded comp formulas for {spells} spell(s).");
LogSpellCompSample(log);
}
}
catch (Exception ex)
{
log?.Invoke($"[ComponentDB] SpellTable parse error: {ex.GetType().Name}: {ex.Message}");
}
}
catch (Exception ex)
{
log?.Invoke($"[ComponentDB] Error: {ex.GetType().Name}: {ex.Message}");
}
}
private static int Parse(byte[] raw, Action<string>? log)
{
using var ms = new MemoryStream(raw);
using var r = new BinaryReader(ms);
uint fileId = r.ReadUInt32(); // 0x0E00000F
ushort count = r.ReadUInt16();
r.ReadUInt16(); // skip unknown uint16
log?.Invoke($"[ComponentDB] fileId=0x{fileId:X8} count={count}");
int found = 0;
for (int i = 0; i < count; i++)
{
if (r.BaseStream.Position + 4 > raw.Length) break;
uint key = r.ReadUInt32();
string name = ReadNibbleString(r);
uint category = r.ReadUInt32();
uint icon = r.ReadUInt32();
uint type = r.ReadUInt32();
uint gesture = r.ReadUInt32();
float time = r.ReadSingle();
string text = ReadNibbleString(r);
float cdm = r.ReadSingle();
if (!string.IsNullOrEmpty(name))
{
_cache[key] = new ComponentRecord
{
Id = key,
Name = name,
Category = category,
IconId = icon,
Type = type,
GestureId = gesture,
GestureSpeed = time,
Word = text,
BurnRate = cdm,
};
found++;
}
}
return found;
}
/// <summary>
/// Reads a nibble-swapped string: uint16 len, len bytes (each byte nibble-swapped), pad to 4-byte.
/// </summary>
private static string ReadNibbleString(BinaryReader r)
{
ushort len = r.ReadUInt16();
byte[] b = r.ReadBytes(len);
// Pad to next 4-byte boundary from the start of the uint16 field (2 + len bytes used so far)
int pad = (4 - (2 + len) % 4) % 4;
if (pad > 0) r.ReadBytes(pad);
for (int i = 0; i < b.Length; i++)
b[i] = (byte)((b[i] << 4) | (b[i] >> 4));
return Encoding.ASCII.GetString(b).TrimEnd('\0');
}
private static string? FindPortalDat()
{
// 1. Process directory (we're injected into acclient.exe — dat is alongside it)
try
{
string? exePath = Environment.ProcessPath;
if (!string.IsNullOrEmpty(exePath))
{
string? dir = Path.GetDirectoryName(exePath);
if (dir != null)
{
foreach (var name in new[] { "client_portal.dat", "portal.dat" })
{
string full = Path.Combine(dir, name);
if (File.Exists(full)) return full;
}
}
}
}
catch { }
// 2. Common install paths
string[] searchDirs =
{
@"C:\Turbine\Asheron's Call",
@"C:\Program Files\Turbine\Asheron's Call",
@"C:\Program Files (x86)\Turbine\Asheron's Call",
@"C:\Games\Asheron's Call",
@"C:\AC",
@"C:\Asheron's Call",
@"D:\Turbine\Asheron's Call",
@"D:\Games\Asheron's Call",
};
foreach (var dir in searchDirs)
{
if (!Directory.Exists(dir)) continue;
foreach (var name in new[] { "client_portal.dat", "portal.dat" })
{
string full = Path.Combine(dir, name);
if (File.Exists(full)) return full;
}
}
// 3. Registry
try
{
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Turbine\Asheron's Call");
if (key != null)
{
string? installPath = key.GetValue("InstallPath") as string;
if (!string.IsNullOrEmpty(installPath))
{
foreach (var name in new[] { "client_portal.dat", "portal.dat" })
{
string full = Path.Combine(installPath, name);
if (File.Exists(full)) return full;
}
}
}
}
catch { }
return null;
}
public static string GetComponentName(uint id)
{
EnsureLoaded();
return _cache.TryGetValue(id, out var r) ? r.Name : $"Unknown Component ({id})";
}
public static bool TryGetRecord(uint id, out ComponentRecord? rec)
{
EnsureLoaded();
return _cache.TryGetValue(id, out rec);
}
// ── SpellTable (0x0E00000E) → required components ────────────────────────
//
// Layout per ACE.DatLoader (SpellTable.cs / SpellBase.cs): file id u32,
// then a PackedHashTable<u32 spellId, SpellBase>. SpellBase fields are read
// in order; the component SET is recovered from the 8 raw comp slots minus
// a key derived from the spell's (de-obfuscated) Name+Desc bytes — this is
// ACCOUNT-INDEPENDENT. The further per-account GetSpellFormula scramble
// only re-rolls taper slots, so we never need the account name. We must
// read every SpellBase field (including the variable meta block) so the
// sequential hash table stays aligned to the next entry.
private static int ParseSpellTable(byte[] raw, Action<string>? log)
{
using var ms = new MemoryStream(raw);
using var r = new BinaryReader(ms);
r.ReadUInt32(); // file id 0x0E00000E
ushort total = r.ReadUInt16(); // PackedHashTable: totalObjects
r.ReadUInt16(); // bucket size (unused in C#)
int n = 0;
for (int i = 0; i < total; i++)
{
if (r.BaseStream.Position + 4 > raw.Length) break;
uint spellId = r.ReadUInt32();
uint[] comps = ReadSpellBaseFormula(r);
_spellComps[(int)spellId] = comps;
n++;
}
return n;
}
private static uint[] ReadSpellBaseFormula(BinaryReader r)
{
byte[] nameB = ReadObf(r); Align(r);
byte[] descB = ReadObf(r); Align(r);
r.ReadUInt32(); // School
r.ReadUInt32(); // Icon
r.ReadUInt32(); // Category
r.ReadUInt32(); // Bitfield
r.ReadUInt32(); // BaseMana
r.ReadSingle(); // BaseRangeConstant
r.ReadSingle(); // BaseRangeMod
r.ReadUInt32(); // Power
r.ReadSingle(); // SpellEconomyMod
r.ReadUInt32(); // FormulaVersion
r.ReadSingle(); // ComponentLoss
uint metaType = r.ReadUInt32(); // MetaSpellType (SpellType enum)
r.ReadUInt32(); // MetaSpellId
// SpellType: Enchantment=1, PortalSummon=7, FellowEnchantment=12.
if (metaType == 1 || metaType == 12)
r.ReadBytes(16); // Duration(double)+DegradeModifier(f)+DegradeLimit(f)
else if (metaType == 7)
r.ReadBytes(8); // PortalLifetime(double)
var rawComps = new List<uint>(8);
for (int j = 0; j < 8; j++)
{
uint c = r.ReadUInt32();
if (c > 0) rawComps.Add(c);
}
// Trailing SpellBase fields — consume so the next entry stays aligned.
r.ReadUInt32(); // CasterEffect
r.ReadUInt32(); // TargetEffect
r.ReadUInt32(); // FizzleEffect
r.ReadDouble(); // RecoveryInterval
r.ReadSingle(); // RecoveryAmount
r.ReadUInt32(); // DisplayOrder
r.ReadUInt32(); // NonComponentTargetType
r.ReadUInt32(); // ManaMod
return DecryptFormula(rawComps, nameB, descB);
}
private static byte[] ReadObf(BinaryReader r)
{
ushort len = r.ReadUInt16();
byte[] b = r.ReadBytes(len);
for (int i = 0; i < b.Length; i++)
b[i] = (byte)((b[i] >> 4) | (b[i] << 4));
return b;
}
private static void Align(BinaryReader r)
{
long d = r.BaseStream.Position % 4;
if (d != 0) r.BaseStream.Position += (4 - d);
}
// ACE SpellTable.ComputeHash, operating directly on the de-obfuscated
// CP1252 bytes (identity vs. ACE's 1252 round-trip for printable spell
// text) so there is no CodePages/encoding dependency under NativeAOT.
private static uint Hash(byte[] bytes)
{
long result = 0;
foreach (byte bb in bytes)
{
sbyte c = (sbyte)bb;
result = c + (result << 4);
if ((result & 0xF0000000) != 0)
result = (result ^ ((result & 0xF0000000) >> 24)) & 0x0FFFFFFF;
}
return (uint)result;
}
private const uint HIGHEST_COMP_ID = 198; // "Essence of Kemeroi" (Void); per ACE
private static uint[] DecryptFormula(List<uint> rawComps, byte[] nameB, byte[] descB)
{
uint key = (Hash(nameB) % 0x12107680u) + (Hash(descB) % 0xBEADCF45u);
var comps = new uint[rawComps.Count];
for (int i = 0; i < rawComps.Count; i++)
{
uint comp = unchecked(rawComps[i] - key);
if (comp > HIGHEST_COMP_ID) comp &= 0xFF;
comps[i] = comp;
}
return comps;
}
private static void LogSpellCompSample(Action<string>? log)
{
if (log == null) return;
// 4439 = "Incantation of Flame Bolt" (the spell that triggered this).
// Eyeball the resolved comp names in-game to confirm the parse.
foreach (int sid in new[] { 4439, 2 })
{
if (!_spellComps.TryGetValue(sid, out var ids)) continue;
var names = new List<string>();
foreach (uint cid in ids)
names.Add(_cache.TryGetValue(cid, out var rc) ? rc.Name : $"#{cid}");
log($"[ComponentDB] sample spell {sid} comps: {string.Join(", ", names)}");
}
}
public static bool TryGetRequiredComponentIds(int spellId, out uint[]? ids)
{
EnsureLoaded();
return _spellComps.TryGetValue(spellId, out ids);
}
/// <summary>
/// Predictive component gate. Returns false ONLY when a required non-taper
/// component this spell needs is positively absent from
/// <paramref name="inventoryNamesLower"/>. Unknown spell formula,
/// unresolvable comp record, parse unavailable, or taper slots (account-
/// scrambled → treated as "any taper present") never block — those defer
/// to the empirical no-components safety net so a parse gap can't wedge
/// combat.
/// </summary>
public static bool HasAllComponents(int spellId, HashSet<string> inventoryNamesLower)
{
EnsureLoaded();
if (!_spellCompsLoaded) return true;
if (!_spellComps.TryGetValue(spellId, out var ids) || ids.Length == 0) return true;
bool taperChecked = false, hasAnyTaper = false;
foreach (uint cid in ids)
{
if (!_cache.TryGetValue(cid, out var rec) || rec == null) continue;
// Category 5 = Taper. The per-account scramble re-rolls which
// taper; a presence check only needs "the char carries tapers".
if (rec.Category == 5)
{
if (!taperChecked)
{
foreach (var nm in inventoryNamesLower)
if (nm.Contains("taper")) { hasAnyTaper = true; break; }
taperChecked = true;
}
if (!hasAnyTaper) return false;
continue;
}
if (string.IsNullOrEmpty(rec.Name)) continue;
if (!inventoryNamesLower.Contains(rec.Name.ToLowerInvariant()))
return false;
}
return true;
}
/// <summary>
/// Scarab-only predictive gate. Returns false ONLY when this spell's
/// required SCARAB (SpellComponentCategory 0) is positively absent from
/// <paramref name="inventoryNamesLower"/>. Every other category (herb,
/// powder, potion, talisman, taper, pea) is ignored — ACE war casting
/// does not require the dat's full historical recipe, and demanding it
/// over-rejects every tier (verified pid 42260, 2026-05-17). Unknown
/// formula / unresolved comp record / parse-unavailable never block
/// (defer to the live cast rather than wedge selection).
/// </summary>
public static bool HasRequiredScarab(int spellId, HashSet<string> inventoryNamesLower)
{
EnsureLoaded();
if (!_spellCompsLoaded) return true;
if (!_spellComps.TryGetValue(spellId, out var ids) || ids.Length == 0) return true;
foreach (uint cid in ids)
{
if (!_cache.TryGetValue(cid, out var rec) || rec == null) continue;
if (rec.Category != 0) continue; // only scarabs gate
if (string.IsNullOrEmpty(rec.Name)) continue;
if (!inventoryNamesLower.Contains(rec.Name.ToLowerInvariant()))
return false; // required scarab absent
}
return true;
}
}

View file

@ -0,0 +1,356 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Reads fellowship membership directly from AC client memory.
///
/// Memory layout (from UB's AcClient structs / acclient.exe analysis):
///
/// Static pointers:
/// 0x0087150C = ClientFellowshipSystem** s_pFellowshipSystem
/// 0x00844C08 = UInt32* player_iid (our character ID)
///
/// ClientFellowshipSystem:
/// +0x10 = CFellowship* m_pFellowship (null if not in fellowship)
///
/// CFellowship / Fellowship:
/// +0x0C = PackableHashData** _buckets (hash table bucket array)
/// +0x10 = UInt32 _table_size (number of buckets)
/// +0x14 = UInt32 _currNum (member count)
/// +0x18 = PStringBase _name (fellowship name, char*)
/// +0x1C = UInt32 _leader (leader character ID)
/// +0x20 = int _share_xp
/// +0x24 = int _even_xp_split
/// +0x28 = int _open_fellow
/// +0x2C = int _locked
///
/// PackableHashData (hash table entry for each member):
/// +0x00 = UInt32 _key (member character ID)
/// +0x04 = Fellow _data:
/// +0x04 = Fellow.PackObj vtable (4 bytes)
/// +0x08 = Fellow._name (PStringBase = char*, 4 bytes)
/// +0x0C = Fellow._level (UInt32)
/// +0x1C = Fellow._share_loot (int)
/// +0x20 = Fellow._max_health (UInt32)
/// +0x28 = Fellow._max_mana (UInt32)
/// +0x2C = Fellow._current_health (UInt32)
/// +0x34 = PackableHashData* _next (next in chain, null = end)
/// </summary>
public class FellowshipTracker : IDisposable
{
// Static memory addresses in acclient.exe
private static readonly IntPtr ADDR_FELLOWSHIP_SYSTEM = new IntPtr(0x0087150C);
private static readonly IntPtr ADDR_PLAYER_IID = new IntPtr(0x00844C08);
// ── Page-validity probe ─────────────────────────────────────────────
// Every read below is a raw dereference into AC's single-threaded native
// state (the fellowship object graph is mutated by AC's main thread with
// no locking). In Decal-coexistence mode this class is ticked from
// RynthAi's own 30 Hz pump thread, not AC's main thread, so a read here
// can race a member join/leave/teardown and land on a freed or
// mid-reassignment pointer. Under NativeAOT, try/catch does NOT reliably
// catch the resulting access violation (see the engine's identical
// IsReadablePointer in ClientObjectHooks.cs — same crash class, same
// fix). VirtualQuery-probe every pointer before dereferencing it instead
// of relying on the catch blocks to save us.
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
private const uint PAGE_NOACCESS = 0x01;
private const uint PAGE_GUARD = 0x100;
private const uint MEM_COMMIT = 0x1000;
[DllImport("kernel32.dll")]
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
private static bool IsReadablePointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero) return false;
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return false;
if (mbi.State != MEM_COMMIT) return false;
if ((mbi.Protect & PAGE_NOACCESS) != 0 || (mbi.Protect & PAGE_GUARD) != 0) return false;
return true;
}
// Struct offsets
private const int OFF_SYS_FELLOWSHIP = 0x10;
private const int OFF_FEL_BUCKETS = 0x0C;
private const int OFF_FEL_TABLE_SIZE = 0x10;
private const int OFF_FEL_CURR_NUM = 0x14;
private const int OFF_FEL_NAME = 0x18;
private const int OFF_FEL_LEADER = 0x1C;
private const int OFF_FEL_SHARE_XP = 0x20;
private const int OFF_FEL_EVEN_SPLIT = 0x24;
private const int OFF_FEL_OPEN = 0x28;
private const int OFF_FEL_LOCKED = 0x2C;
// Hash entry offsets
private const int OFF_ENTRY_KEY = 0x00;
private const int OFF_ENTRY_NAME_PTR = 0x08;
private const int OFF_ENTRY_LEVEL = 0x0C;
private const int OFF_ENTRY_NEXT = 0x34;
private Dictionary<int, string> _memberCache = new();
private DateTime _lastRefresh = DateTime.MinValue;
private const double REFRESH_INTERVAL_MS = 2000;
public FellowshipTracker() { }
public void Dispose() { }
public bool IsInFellowship
{
get { try { return GetFellowshipPtr() != IntPtr.Zero; } catch { return false; } }
}
public int MemberCount
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return 0;
IntPtr addr = fel + OFF_FEL_CURR_NUM;
if (!IsReadablePointer(addr)) return 0;
return Marshal.ReadInt32(addr);
}
catch { return 0; }
}
}
public string FellowshipName
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return "";
IntPtr addr = fel + OFF_FEL_NAME;
if (!IsReadablePointer(addr)) return "";
return ReadPString(addr);
}
catch { return ""; }
}
}
public int LeaderId
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return 0;
IntPtr addr = fel + OFF_FEL_LEADER;
if (!IsReadablePointer(addr)) return 0;
return Marshal.ReadInt32(addr);
}
catch { return 0; }
}
}
public bool IsLeader
{
get
{
try
{
int leader = LeaderId;
if (leader == 0) return false;
if (!IsReadablePointer(ADDR_PLAYER_IID)) return false;
int myId = Marshal.ReadInt32(ADDR_PLAYER_IID);
return leader == myId;
}
catch { return false; }
}
}
public bool IsOpen
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return false;
IntPtr addr = fel + OFF_FEL_OPEN;
return IsReadablePointer(addr) && Marshal.ReadInt32(addr) == 1;
}
catch { return false; }
}
}
public bool IsLocked
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return false;
IntPtr addr = fel + OFF_FEL_LOCKED;
return IsReadablePointer(addr) && Marshal.ReadInt32(addr) == 1;
}
catch { return false; }
}
}
public bool ShareXP
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return false;
IntPtr addr = fel + OFF_FEL_SHARE_XP;
return IsReadablePointer(addr) && Marshal.ReadInt32(addr) == 1;
}
catch { return false; }
}
}
public bool IsMember(string name)
{
if (string.IsNullOrEmpty(name)) return false;
RefreshIfNeeded();
foreach (var kvp in _memberCache)
if (kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
public bool IsMember(int characterId)
{
RefreshIfNeeded();
return _memberCache.ContainsKey(characterId);
}
public IEnumerable<string> GetMemberNames()
{
RefreshIfNeeded();
return _memberCache.Values;
}
public string GetMemberName(int index)
{
RefreshIfNeeded();
int i = 0;
foreach (var kvp in _memberCache) { if (i == index) return kvp.Value; i++; }
return "";
}
public int GetMemberId(int index)
{
RefreshIfNeeded();
int i = 0;
foreach (var kvp in _memberCache) { if (i == index) return kvp.Key; i++; }
return 0;
}
private IntPtr GetFellowshipPtr()
{
if (!IsReadablePointer(ADDR_FELLOWSHIP_SYSTEM)) return IntPtr.Zero;
int sysPtr = Marshal.ReadInt32(ADDR_FELLOWSHIP_SYSTEM);
if (sysPtr == 0) return IntPtr.Zero;
IntPtr sysFieldAddr = new IntPtr(sysPtr + OFF_SYS_FELLOWSHIP);
if (!IsReadablePointer(sysFieldAddr)) return IntPtr.Zero;
int felPtr = Marshal.ReadInt32(sysFieldAddr);
if (felPtr == 0) return IntPtr.Zero;
IntPtr fel = new IntPtr(felPtr);
return IsReadablePointer(fel) ? fel : IntPtr.Zero;
}
private void RefreshIfNeeded()
{
if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;
_lastRefresh = DateTime.Now;
_memberCache.Clear();
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return;
IntPtr bucketsAddr = fel + OFF_FEL_BUCKETS;
IntPtr tableSizeAddr = fel + OFF_FEL_TABLE_SIZE;
IntPtr currNumAddr = fel + OFF_FEL_CURR_NUM;
if (!IsReadablePointer(bucketsAddr) || !IsReadablePointer(tableSizeAddr) || !IsReadablePointer(currNumAddr))
return;
int bucketsPtr = Marshal.ReadInt32(bucketsAddr);
int tableSize = Marshal.ReadInt32(tableSizeAddr);
int currNum = Marshal.ReadInt32(currNumAddr);
// Fellowship caps at 9 members; a corrupt/mid-mutation table_size
// here (bogus large value) would otherwise turn the bucket loop
// below into an unbounded scan over garbage addresses.
if (bucketsPtr == 0 || tableSize == 0 || tableSize > 64 || currNum == 0 || currNum > 9)
return;
if (!IsReadablePointer(new IntPtr(bucketsPtr)))
return;
int maxMembers = Math.Min(currNum, 9);
int found = 0;
for (int b = 0; b < tableSize && found < maxMembers; b++)
{
IntPtr bucketSlotAddr = new IntPtr(bucketsPtr + b * 4);
if (!IsReadablePointer(bucketSlotAddr)) continue;
int entryPtr = Marshal.ReadInt32(bucketSlotAddr);
// Chain guard: a corrupted/circular bucket chain (mid-mutation
// read racing AC's main thread) must not spin this pump thread
// forever — cap the walk independent of the found-count exit.
int chainGuard = 0;
while (entryPtr != 0 && found < maxMembers && chainGuard++ < 32)
{
IntPtr entry = new IntPtr(entryPtr);
if (!IsReadablePointer(entry)) break;
IntPtr keyAddr = entry + OFF_ENTRY_KEY;
IntPtr nameFieldAddr = entry + OFF_ENTRY_NAME_PTR;
IntPtr nextAddr = entry + OFF_ENTRY_NEXT;
if (!IsReadablePointer(keyAddr) || !IsReadablePointer(nameFieldAddr) || !IsReadablePointer(nextAddr))
break;
int memberId = Marshal.ReadInt32(keyAddr);
string name = ReadPString(nameFieldAddr);
if (memberId != 0 && !string.IsNullOrEmpty(name))
{ _memberCache[memberId] = name; found++; }
entryPtr = Marshal.ReadInt32(nextAddr);
}
}
}
catch { }
}
private string ReadPString(IntPtr addr)
{
try
{
if (!IsReadablePointer(addr)) return "";
int bufPtr = Marshal.ReadInt32(addr);
if (bufPtr == 0) return "";
IntPtr strAddr = new IntPtr(bufPtr + 0x14);
if (!IsReadablePointer(strAddr)) return "";
string? raw = Marshal.PtrToStringAnsi(strAddr);
if (raw == null) return "";
if (raw.Length > 64) raw = raw[..64];
return raw;
}
catch { return ""; }
}
}

View file

@ -0,0 +1,562 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Automates missile ammunition management.
///
/// Triggers when ammo slot is empty:
/// 1. Can craft better ammo than loose inventory? → Craft (up to 2x), then equip
/// 2. Loose ammo available? → Equip best one
/// 3. Can craft anything? → Craft, then equip
///
/// Crafting is chat-driven: issues UseObjectOn (ApplyItem), waits for "You make" chat,
/// then advances to the next combine or equips. Retries every 2s if no response.
/// </summary>
public class MissileCraftingManager
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private WorldObjectCache? _objectCache;
private CharacterSkills? _charSkills;
public bool IsBusy { get; set; } = false;
/// <summary>Live combat mode — read from AC each access (1=peace, 2=melee, 4=missile, 8=magic).</summary>
public int CurrentCombatMode =>
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
public void SetObjectCache(WorldObjectCache cache) => _objectCache = cache;
public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills;
public enum CraftState { Idle, Evaluating, Combining, EquippingAmmo }
public CraftState State { get; private set; } = CraftState.Idle;
public bool IsCrafting => State != CraftState.Idle;
public string StatusMessage { get; private set; } = "";
private DateTime _phaseStart = DateTime.MinValue;
private DateTime _lastAmmoCheck = DateTime.MinValue;
private DateTime _lastApplyAttempt = DateTime.MinValue;
private const int AMMO_CHECK_INTERVAL_MS = 5000;
private const int APPLY_RETRY_MS = 2000;
private const int CRAFT_TIMEOUT_MS = 15000;
private const int EQUIP_DELAY_MS = 500;
private int _headBundleId = 0;
private int _shaftBundleId = 0;
private AmmoRecipe? _currentRecipe = null;
private int _equipTargetId = 0;
private bool _allCombinesDone = false;
private WeaponCategory _lastWeaponCategory = WeaponCategory.Bow;
private readonly Queue<int[]> _pendingBundlePairs = new();
private int _totalCombines = 0;
private int _combinesCompleted = 0;
// ══════════════════════════════════════════════════════════════════
// RECIPE DATABASE
// ══════════════════════════════════════════════════════════════════
public enum WeaponCategory { Bow, Crossbow, Atlatl }
public class AmmoRecipe
{
public string HeadBundleName = "";
public string ShaftBundleName = "";
public string OutputName = "";
public WeaponCategory Category;
public bool RequiresSpecialized;
public int Priority;
}
public static readonly List<AmmoRecipe> AllRecipes = new List<AmmoRecipe>
{
// ── ARROWS (Bow) ───────────────────────────────────────────
new() { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Lethal Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 40 },
new() { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Deadly Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 30 },
new() { HeadBundleName = "Wrapped Bundle of Greater Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Greater Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 20 },
new() { HeadBundleName = "Wrapped Bundle of Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 10 },
new() { HeadBundleName = "Wrapped Bundle of Armor Piercing Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Armor Piercing Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 6 },
new() { HeadBundleName = "Wrapped Bundle of Broad Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Broad Head Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 5 },
new() { HeadBundleName = "Wrapped Bundle of Blunt Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Blunt Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 4 },
new() { HeadBundleName = "Wrapped Bundle of Frog Crotch Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Frog Crotch Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 3 },
new() { HeadBundleName = "Wrapped Bundle of Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 1 },
// ── QUARRELS (Crossbow) ────────────────────────────────────
new() { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Lethal Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 40 },
new() { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Deadly Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 30 },
new() { HeadBundleName = "Wrapped Bundle of Greater Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Greater Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 20 },
new() { HeadBundleName = "Wrapped Bundle of Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 10 },
new() { HeadBundleName = "Wrapped Bundle of Armor Piercing Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Armor Piercing Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 6 },
new() { HeadBundleName = "Wrapped Bundle of Broad Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Broad Head Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 5 },
new() { HeadBundleName = "Wrapped Bundle of Blunt Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Blunt Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 4 },
new() { HeadBundleName = "Wrapped Bundle of Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 1 },
// ── DARTS (Atlatl) ─────────────────────────────────────────
new() { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Lethal Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 40 },
new() { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Deadly Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 30 },
new() { HeadBundleName = "Wrapped Bundle of Greater Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Greater Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 20 },
new() { HeadBundleName = "Wrapped Bundle of Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 10 },
new() { HeadBundleName = "Wrapped Bundle of Armor Piercing Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Armor Piercing Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 6 },
new() { HeadBundleName = "Wrapped Bundle of Broad Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Broad Head Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 5 },
new() { HeadBundleName = "Wrapped Bundle of Blunt Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Blunt Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 4 },
new() { HeadBundleName = "Wrapped Bundle of Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 1 },
};
public MissileCraftingManager(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
_settings = settings;
}
// ══════════════════════════════════════════════════════════════════
// MAIN TICK
// ══════════════════════════════════════════════════════════════════
public void ProcessCrafting()
{
if (!_settings.EnableMissileCrafting) return;
if (IsBusy) return;
switch (State)
{
case CraftState.Idle: ProcessIdle(); break;
case CraftState.Evaluating: ProcessEvaluating(); break;
case CraftState.Combining: ProcessCombining(); break;
case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break;
}
}
// ══════════════════════════════════════════════════════════════════
// CHAT HANDLER — called from RynthAiPlugin.OnChatWindowText
// ══════════════════════════════════════════════════════════════════
public void HandleChat(string text)
{
if (State != CraftState.Combining) return;
if (string.IsNullOrEmpty(text)) return;
if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return;
_combinesCompleted++;
ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})");
if (_pendingBundlePairs.Count > 0)
{
var pair = _pendingBundlePairs.Dequeue();
_headBundleId = pair[0];
_shaftBundleId = pair[1];
_lastApplyAttempt = DateTime.MinValue;
StatusMessage = $"Crafting {_currentRecipe!.OutputName} (batch {_combinesCompleted + 1})...";
}
else
{
_allCombinesDone = true;
}
}
// ══════════════════════════════════════════════════════════════════
// IDLE
// ══════════════════════════════════════════════════════════════════
private void ProcessIdle()
{
if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return;
_lastAmmoCheck = DateTime.Now;
var inv = GetInventory(forceRefresh: true);
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category))
return;
_lastWeaponCategory = category;
if (HasWieldedAmmo(inv, category))
return;
ChatLog($"No wielded {GetCategoryLabel(category)}s. Evaluating...");
SetState(CraftState.Evaluating);
}
// ══════════════════════════════════════════════════════════════════
// EVALUATING
// ══════════════════════════════════════════════════════════════════
private void ProcessEvaluating()
{
var inv = GetInventory(forceRefresh: true);
WeaponCategory category = ResolveWeaponCategory(inv);
int trainingLevel = _charSkills?[AcSkillType.Fletching].Training ?? 2;
AmmoRecipe? bestCraftable = null;
foreach (var recipe in AllRecipes
.Where(r => r.Category == category)
.OrderByDescending(r => r.Priority))
{
if (recipe.RequiresSpecialized && trainingLevel < 3) continue;
if (!recipe.RequiresSpecialized && trainingLevel < 2) continue;
bool hasHead = inv.Any(i => MatchesRecipeComponent(i.Name, recipe.HeadBundleName));
bool hasShaft = inv.Any(i => MatchesRecipeComponent(i.Name, recipe.ShaftBundleName));
if (hasHead && hasShaft) { bestCraftable = recipe; break; }
}
int bestExistingPriority = 0;
WorldObject? bestExistingAmmo = null;
foreach (var item in inv)
{
if (!IsLooseAmmo(item, category)) continue;
int pri = GetAmmoPriority(item, category);
if (pri > bestExistingPriority) { bestExistingPriority = pri; bestExistingAmmo = item; }
}
if (bestCraftable != null && bestCraftable.Priority > bestExistingPriority)
{ StartCrafting(bestCraftable, inv); return; }
if (bestExistingAmmo != null)
{
_equipTargetId = bestExistingAmmo.Id;
ChatLog($"Equipping {bestExistingAmmo.Name}");
SetState(CraftState.EquippingAmmo);
return;
}
if (bestCraftable != null)
{ StartCrafting(bestCraftable, inv); return; }
Reset("No ammo and no bundles available");
}
private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv)
{
_currentRecipe = recipe;
_pendingBundlePairs.Clear();
_combinesCompleted = 0;
_allCombinesDone = false;
try { _host.ChangeCombatMode(CombatMode.NonCombat); } catch { }
var headItems = inv.Where(i => MatchesRecipeComponent(i.Name, recipe.HeadBundleName)).ToList();
var shaftItems = inv.Where(i => MatchesRecipeComponent(i.Name, recipe.ShaftBundleName)).ToList();
if (headItems.Count == 0 || shaftItems.Count == 0)
{
Reset($"No bundles available for {recipe.OutputName} ({headItems.Count} head, {shaftItems.Count} shaft)");
return;
}
// Check stack sizes to decide how many combines (1 or 2)
int availableHeads = headItems[0].Values(LongValueKey.StackCount, 1);
int availableShafts = shaftItems[0].Values(LongValueKey.StackCount, 1);
int pairCount = Math.Min(2, Math.Min(availableHeads, availableShafts));
// Queue combines with same IDs — server decrements stacked bundles
for (int i = 0; i < pairCount; i++)
_pendingBundlePairs.Enqueue(new[] { headItems[0].Id, shaftItems[0].Id });
_totalCombines = pairCount;
var first = _pendingBundlePairs.Dequeue();
_headBundleId = first[0];
_shaftBundleId = first[1];
ChatLog($"Crafting {recipe.OutputName} x{_totalCombines}");
StatusMessage = $"Crafting {recipe.OutputName}...";
_lastApplyAttempt = DateTime.MinValue;
SetState(CraftState.Combining);
}
// ══════════════════════════════════════════════════════════════════
// COMBINING
// ══════════════════════════════════════════════════════════════════
private void ProcessCombining()
{
if (_allCombinesDone)
{
StatusMessage = $"Equipping {_currentRecipe!.OutputName}...";
_equipTargetId = 0;
SetState(CraftState.EquippingAmmo);
return;
}
if ((DateTime.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS)
{
if (_combinesCompleted > 0)
{
ChatLog($"Timeout after {_combinesCompleted} combine(s). Equipping what we have.");
_equipTargetId = 0;
SetState(CraftState.EquippingAmmo);
}
else
{
Reset("Craft timed out — no response from server");
}
return;
}
if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS)
{
try
{
if (!_host.UseObjectOn((uint)_headBundleId, (uint)_shaftBundleId))
{
ChatLog($"UseObjectOn returned false for 0x{_headBundleId:X8} -> 0x{_shaftBundleId:X8}");
_lastApplyAttempt = DateTime.Now;
return;
}
_lastApplyAttempt = DateTime.Now;
StatusMessage = $"Combining -> {_currentRecipe!.OutputName} ({_combinesCompleted + 1}/{_totalCombines})...";
}
catch (Exception ex)
{
Reset($"Combine failed: {ex.Message}");
}
}
}
// ══════════════════════════════════════════════════════════════════
// EQUIPPING
// ══════════════════════════════════════════════════════════════════
private void ProcessEquippingAmmo()
{
if ((DateTime.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return;
try
{
var inv = GetInventory(forceRefresh: true);
int targetId = _equipTargetId;
if (targetId == 0)
{
WeaponCategory cat = ResolveWeaponCategory(inv);
var ammo = FindBestAmmoInInventory(cat, inv);
if (ammo != null) targetId = ammo.Id;
}
if (targetId != 0)
{
_host.UseObject((uint)targetId);
ChatLog($"Equipped ammo (id=0x{targetId:X8})");
Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}");
}
else
{
if ((DateTime.Now - _phaseStart).TotalMilliseconds < CRAFT_TIMEOUT_MS)
{
StatusMessage = $"Waiting for {_currentRecipe?.OutputName ?? GetCategoryLabel(_lastWeaponCategory)} to appear...";
return;
}
ChatLog("Could not find ammo to equip.");
Reset("Equip timed out — no ammo found");
}
}
catch (Exception ex)
{
ChatLog($"Equip error: {ex.Message}");
Reset($"Equip failed: {ex.Message}");
}
}
// ══════════════════════════════════════════════════════════════════
// HELPERS
// ══════════════════════════════════════════════════════════════════
// ── Direct inventory scan (bypasses WorldObjectCache to avoid crash) ────
private List<WorldObject> GetInventory(bool forceRefresh = false)
=> _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new();
private WeaponCategory ResolveWeaponCategory(IEnumerable<WorldObject> inventory)
{
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category))
{
_lastWeaponCategory = category;
return category;
}
return _lastWeaponCategory;
}
private bool TryGetWieldedMissileCategory(IEnumerable<WorldObject> inventory, out WeaponCategory category)
{
foreach (var item in inventory)
{
if (!IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
continue;
category = GetWeaponCategory(item.Name);
return true;
}
category = WeaponCategory.Bow;
return false;
}
private bool HasWieldedAmmo(IEnumerable<WorldObject> inventory, WeaponCategory category)
{
foreach (var item in inventory)
{
if (!IsPlayerWielded(item))
continue;
if (IsLooseAmmo(item, category))
return true;
}
return false;
}
private bool IsPlayerWielded(WorldObject item)
{
if (item.WieldedLocation <= 0)
return false;
uint playerId = _host.GetPlayerId();
if (playerId == 0)
return false;
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
}
private static bool LooksLikeMissileWeapon(WorldObject item)
{
if (item.ObjectClass == AcObjectClass.MissileWeapon)
return true;
if (string.IsNullOrWhiteSpace(item.Name))
return false;
return item.Name.IndexOf("crossbow", StringComparison.OrdinalIgnoreCase) >= 0
|| item.Name.IndexOf("atlatl", StringComparison.OrdinalIgnoreCase) >= 0
|| item.Name.IndexOf("bow", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static WeaponCategory GetWeaponCategory(string name)
{
if (name.IndexOf("crossbow", StringComparison.OrdinalIgnoreCase) >= 0) return WeaponCategory.Crossbow;
if (name.IndexOf("atlatl", StringComparison.OrdinalIgnoreCase) >= 0) return WeaponCategory.Atlatl;
return WeaponCategory.Bow;
}
private static bool IsLooseAmmo(WorldObject item, WeaponCategory category)
{
string n = item.Name;
if (string.IsNullOrEmpty(n)) return false;
string normalized = NormalizeItemName(n);
if (normalized.Contains("bundle") || normalized.Contains("wrapped")) return false;
if (normalized.Contains("arrowhead") || normalized.Contains("arrowshaft")) return false;
if (normalized.Contains("quarrelhead") || normalized.Contains("quarrelshaft")) return false;
if (normalized.Contains("darthead") || normalized.Contains("dartshaft")) return false;
return category switch
{
WeaponCategory.Bow => normalized.Contains("arrow"),
WeaponCategory.Crossbow => normalized.Contains("quarrel") || normalized.Contains("bolt"),
WeaponCategory.Atlatl => normalized.Contains("dart"),
_ => false,
};
}
private static int GetAmmoPriority(WorldObject item, WeaponCategory category)
{
if (string.IsNullOrEmpty(item.Name)) return 0;
foreach (var recipe in AllRecipes.Where(r => r.Category == category).OrderByDescending(r => r.Priority))
if (item.Name.Equals(recipe.OutputName, StringComparison.OrdinalIgnoreCase)) return recipe.Priority;
return 1;
}
private WorldObject? FindBestAmmoInInventory(WeaponCategory category, IEnumerable<WorldObject> inventory)
{
int bestPri = 0;
WorldObject? best = null;
foreach (var item in inventory)
{
if (!IsLooseAmmo(item, category)) continue;
int pri = GetAmmoPriority(item, category);
if (pri > bestPri) { bestPri = pri; best = item; }
}
return best;
}
private static bool MatchesRecipeComponent(string itemName, string recipeName)
{
if (string.IsNullOrWhiteSpace(itemName) || string.IsNullOrWhiteSpace(recipeName))
return false;
string itemNorm = NormalizeItemName(itemName);
string recipeNorm = NormalizeItemName(recipeName);
if (itemNorm == recipeNorm)
return true;
// Recipe components are always "Wrapped Bundle of ..." — a finished arrow/quarrel/
// dart must never match a component slot. Its bare name (e.g. "arrow") is a substring
// of "...arrowshafts"/"...arrowheads", so the loose substring test below would otherwise
// pick up already-crafted ammo as a component, making the bot try to combine a finished
// arrow onto a bundle and stall forever.
if (!itemNorm.Contains("bundle"))
return false;
return itemNorm.Contains(recipeNorm) || recipeNorm.Contains(itemNorm);
}
// Names come from the object cache, so the length is attacker-ish input as far as
// this frame is concerned — an unbounded stackalloc on it can blow the stack
// (2026-06-03 audit P2). Item names are far under this; anything longer heaps.
private const int MaxStackNameChars = 256;
private static string NormalizeItemName(string value)
{
char[]? rented = value.Length > MaxStackNameChars ? new char[value.Length] : null;
Span<char> buffer = rented is null ? stackalloc char[MaxStackNameChars] : rented;
int count = 0;
foreach (char ch in value)
{
if (!char.IsLetterOrDigit(ch))
continue;
buffer[count++] = char.ToLowerInvariant(ch);
}
return new string(buffer[..count]);
}
private static string GetCategoryLabel(WeaponCategory cat) => cat switch
{
WeaponCategory.Bow => "Arrow",
WeaponCategory.Crossbow => "Quarrel",
WeaponCategory.Atlatl => "Dart",
_ => "Ammo",
};
private void SetState(CraftState newState)
{
State = newState;
_phaseStart = DateTime.Now;
}
private void Reset(string reason)
{
if (State != CraftState.Idle || reason.IndexOf("bundle", StringComparison.OrdinalIgnoreCase) >= 0)
ChatLog(reason);
StatusMessage = reason;
State = CraftState.Idle;
_currentRecipe = null;
_headBundleId = 0;
_shaftBundleId = 0;
_equipTargetId = 0;
_allCombinesDone = false;
_combinesCompleted = 0;
_totalCombines = 0;
_pendingBundlePairs.Clear();
}
private void ChatLog(string msg)
{
try { _host.WriteToChat($"[RynthAi Craft] {msg}", 1); } catch { }
}
}

View file

@ -0,0 +1,290 @@
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Combat;
/// <summary>
/// Evaluates vTank-compatible monster match expressions against a target.
/// Syntax: range>5 && species==drudge
/// Variables: true, false, name, species, typeid, maxhp, range, hasshield, metastate
/// Operators (by precedence low→high): || && == != &lt; > &lt;= >= # + - * / %
/// Grouping with ( ).
/// </summary>
internal sealed class MonsterMatchEvaluator
{
private readonly WorldObjectCache _cache;
private readonly uint _playerId;
// Context — set before each eval
private WorldObject? _target;
private string _metaState = "Default";
public MonsterMatchEvaluator(WorldObjectCache cache, uint playerId)
{
_cache = cache;
_playerId = playerId;
}
public bool Evaluate(string expression, WorldObject target, string metaState)
{
if (string.IsNullOrWhiteSpace(expression)) return false;
_target = target;
_metaState = metaState ?? "Default";
try
{
int pos = 0;
string result = ParseOr(expression.Trim(), ref pos);
return IsTruthy(result);
}
catch
{
return false;
}
}
// ── Parser (recursive descent, left-to-right) ────────────────────────────
private string ParseOr(string s, ref int pos)
{
string left = ParseAnd(s, ref pos);
while (TryConsumeOp(s, ref pos, "||"))
{
string right = ParseAnd(s, ref pos);
left = (IsTruthy(left) || IsTruthy(right)) ? "1" : "0";
}
return left;
}
private string ParseAnd(string s, ref int pos)
{
string left = ParseComparison(s, ref pos);
while (TryConsumeOp(s, ref pos, "&&"))
{
string right = ParseComparison(s, ref pos);
left = (IsTruthy(left) && IsTruthy(right)) ? "1" : "0";
}
return left;
}
private string ParseComparison(string s, ref int pos)
{
string left = ParseAddSub(s, ref pos);
SkipWs(s, ref pos);
string? op = null;
if (TryConsumeOp(s, ref pos, "==")) op = "==";
else if (TryConsumeOp(s, ref pos, "!=")) op = "!=";
else if (TryConsumeOp(s, ref pos, ">=")) op = ">=";
else if (TryConsumeOp(s, ref pos, "<=")) op = "<=";
else if (TryConsumeOp(s, ref pos, "#")) op = "#";
else if (TryConsumeChar(s, ref pos, '>')) op = ">";
else if (TryConsumeChar(s, ref pos, '<')) op = "<";
if (op == null) return left;
string right = ParseAddSub(s, ref pos);
if (op == "#")
{
try { return Regex.IsMatch(left, right, RegexOptions.IgnoreCase) ? "1" : "0"; }
catch { return "0"; }
}
if (double.TryParse(left, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double ln) &&
double.TryParse(right, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double rn))
{
return op switch
{
"==" => ln == rn ? "1" : "0",
"!=" => ln != rn ? "1" : "0",
">" => ln > rn ? "1" : "0",
"<" => ln < rn ? "1" : "0",
">=" => ln >= rn ? "1" : "0",
"<=" => ln <= rn ? "1" : "0",
_ => "0",
};
}
// String comparison
int cmp = string.Compare(left, right, StringComparison.OrdinalIgnoreCase);
return op switch
{
"==" => cmp == 0 ? "1" : "0",
"!=" => cmp != 0 ? "1" : "0",
">" => cmp > 0 ? "1" : "0",
"<" => cmp < 0 ? "1" : "0",
">=" => cmp >= 0 ? "1" : "0",
"<=" => cmp <= 0 ? "1" : "0",
_ => "0",
};
}
private string ParseAddSub(string s, ref int pos)
{
string left = ParseMulDiv(s, ref pos);
while (true)
{
SkipWs(s, ref pos);
if (TryConsumeChar(s, ref pos, '+'))
{
string right = ParseMulDiv(s, ref pos);
if (TryNum(left, out double l) && TryNum(right, out double r))
left = Fmt(l + r);
else
left = left + right;
}
else if (TryConsumeChar(s, ref pos, '-'))
{
string right = ParseMulDiv(s, ref pos);
if (TryNum(left, out double l) && TryNum(right, out double r))
left = Fmt(l - r);
}
else break;
}
return left;
}
private string ParseMulDiv(string s, ref int pos)
{
string left = ParseUnary(s, ref pos);
while (true)
{
SkipWs(s, ref pos);
char c = pos < s.Length ? s[pos] : '\0';
if (c == '*') { pos++; string r = ParseUnary(s, ref pos); left = TryNum(left, out double l) && TryNum(r, out double rv) ? Fmt(l * rv) : "0"; }
else if (c == '/') { pos++; string r = ParseUnary(s, ref pos); left = TryNum(left, out double l) && TryNum(r, out double rv) && rv != 0 ? Fmt(l / rv) : "0"; }
else if (c == '%') { pos++; string r = ParseUnary(s, ref pos); left = TryNum(left, out double l) && TryNum(r, out double rv) && rv != 0 ? Fmt((int)l % (int)rv) : "0"; }
else break;
}
return left;
}
private string ParseUnary(string s, ref int pos)
{
SkipWs(s, ref pos);
if (pos < s.Length && s[pos] == '(')
{
pos++; // consume '('
string inner = ParseOr(s, ref pos);
SkipWs(s, ref pos);
if (pos < s.Length && s[pos] == ')') pos++;
return inner;
}
return ParseAtom(s, ref pos);
}
private string ParseAtom(string s, ref int pos)
{
SkipWs(s, ref pos);
if (pos >= s.Length) return "";
// Quoted string
if (s[pos] == '"' || s[pos] == '\'')
{
char q = s[pos++];
int start = pos;
while (pos < s.Length && s[pos] != q) pos++;
string val = s.Substring(start, pos - start);
if (pos < s.Length) pos++;
return val;
}
// Read token: letters, digits, _, ., - (no spaces)
int begin = pos;
while (pos < s.Length && !IsTokenEnd(s[pos])) pos++;
string token = s.Substring(begin, pos - begin).Trim();
return ResolveVariable(token);
}
private static bool IsTokenEnd(char c) =>
c == '>' || c == '<' || c == '=' || c == '!' || c == '&' || c == '|' ||
c == ')' || c == '(' || c == '#' || c == '*' || c == '/' || c == '%' ||
c == '+' || c == ' ' || c == '\t';
// ── Variable resolution ───────────────────────────────────────────────────
private string ResolveVariable(string token)
{
if (string.IsNullOrEmpty(token)) return "";
switch (token.ToLowerInvariant())
{
case "true": return "1";
case "false": return "0";
case "name": return _target?.Name ?? "";
case "metastate": return _metaState;
case "range":
{
if (_target == null) return "9999";
double d = _cache.Distance(_target.Id, (int)_playerId);
return d < 0 ? "9999" : Fmt(d);
}
case "maxhp":
{
if (_target == null) return "0";
int hp = _target.Values(LongValueKey.MaximumHealth, 0);
return hp.ToString();
}
case "typeid":
{
if (_target == null) return "0";
int tid = _target.Values(LongValueKey.TemplateType, 0);
return tid.ToString();
}
case "species":
{
if (_target == null) return "";
// CreatureType (STypeInt 62) maps to AC creature-type IDs; return as string int.
// Use 'typeid' for exact type matching; 'species' returns the creature type int.
int ct = _target.Values(LongValueKey.CreatureType, 0);
return ct.ToString();
}
case "hasshield":
{
// Shield detection requires enumerating target equip slots — not yet available.
return "0";
}
default:
// Treat as literal string/number
return token;
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static bool IsTruthy(string s) =>
!string.IsNullOrEmpty(s) && s != "0" && s != "false";
private static bool TryNum(string s, out double v) =>
double.TryParse(s, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out v);
private static string Fmt(double v) =>
v == Math.Truncate(v)
? ((long)v).ToString()
: v.ToString("G", System.Globalization.CultureInfo.InvariantCulture);
private static void SkipWs(string s, ref int pos)
{
while (pos < s.Length && (s[pos] == ' ' || s[pos] == '\t')) pos++;
}
private static bool TryConsumeOp(string s, ref int pos, string op)
{
SkipWs(s, ref pos);
if (pos + op.Length <= s.Length && s.AsSpan(pos, op.Length).Equals(op, StringComparison.Ordinal))
{
pos += op.Length;
return true;
}
return false;
}
private static bool TryConsumeChar(string s, ref int pos, char c)
{
if (pos < s.Length && s[pos] == c) { pos++; return true; }
return false;
}
}

View file

@ -0,0 +1,399 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Combat-pet summoning state machine.
///
/// AC/ACE combat pets are summoned from "essence" items (PetDevices). Using an
/// essence with no target spawns a pet that fights alongside the player for a
/// short, data-driven lifespan, then despawns. Each successful use consumes one
/// charge (the item's <c>Structure</c> property); when a device runs dry it is
/// refilled by using an "Encapsulated Spirit" on it (which restores it to
/// MaxStructure and consumes one spirit). Only ONE pet may be active at a time —
/// the server names the summoned creature "<c>&lt;PlayerName&gt;'s &lt;PetName&gt;</c>",
/// which is how we detect whether a pet is already up.
///
/// Behaviour (per user spec):
/// * Summon only when mobs are near — at least <c>PetMinMonsters</c> scanned,
/// attackable monsters within <c>CustomPetRange</c> — and no pet is currently
/// active. Re-summon when the pet despawns mid-fight.
/// * Auto-refill an empty essence from an Encapsulated Spirit in inventory
/// (gated on <c>PetAutoRefill</c>).
///
/// Mirrors <see cref="ManaStoneManager"/>: busy-gated, chat-driven, timeout-
/// guarded, one in-flight action at a time. Entirely plugin-side; the only AC
/// actions issued are <c>Host.UseObject</c> (summon) and <c>Host.UseObjectOn</c>
/// (refill), both selection-free.
/// </summary>
internal sealed class PetManager
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache _objectCache;
private readonly CombatManager? _combat;
private readonly CharacterSkills? _skills;
private enum PetState { Idle, Summoning, Refilling }
private PetState _state = PetState.Idle;
private int _activeDeviceId;
private int _activeSpiritId;
private int _preActionCharges = -1; // device charges read just before issuing a summon (-1 = unreadable)
private long _actionIssuedAt;
private long _lastThinkAt;
// After issuing a summon (or learning a pet is already up via chat) assume a
// pet is active for at least this long, so we don't re-issue before the new
// pet's CreateObject lands in the cache. Name-detection takes over once it does.
private long _assumePetActiveUntil;
// Devices that just failed (skill too low, timed out, empty with no spirit)
// get parked so we advance to the next configured essence instead of looping.
private readonly Dictionary<int, long> _deviceCooldownUntil = new();
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
// by name; it is never itself a summon device.
private const string EncapsulatedSpiritName = "Encapsulated Spirit";
private const long ThinkIntervalMs = 1000;
private const long ActionTimeoutMs = 8000;
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
private const long DeviceNoSpiritCooldownMs = 15_000;
private string _playerName = string.Empty;
private long _playerNameAt;
private static long NowMs => Environment.TickCount64;
public PetManager(RynthCoreHost host, LegacyUiSettings settings,
WorldObjectCache objectCache, CombatManager? combat,
CharacterSkills? skills)
{
_host = host;
_settings = settings;
_objectCache = objectCache;
_combat = combat;
_skills = skills;
}
// ── Public API ─────────────────────────────────────────────────────────────
public void OnHeartbeat(int busyCount)
{
if (!_settings.SummonPets) { Reset(); return; }
if (!_settings.IsMacroRunning) { Reset(); return; }
long now = NowMs;
// Positive completion checks for the in-flight action (don't wait for chat).
if (_state == PetState.Summoning)
{
// Success once the server decremented the device's charge (Structure)
// or the summoned creature is now visible in the cache.
if (SummonLanded() || IsPetActive())
{
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
GoIdle();
}
}
else if (_state == PetState.Refilling)
{
bool spiritGone = _activeSpiritId != 0 && _objectCache[_activeSpiritId] == null;
if (spiritGone || DeviceHasCharges(_activeDeviceId))
{
_host.Log($"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
GoIdle();
}
}
// Timeout BEFORE the busy gate — busyCount can stick > 0 (a server-side
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
_host.Log($"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
if (_activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs;
// A summon that we simply couldn't confirm very likely DID work — assume
// a pet for a bit so we don't immediately re-issue into "already active".
if (_state == PetState.Summoning)
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
Reset();
return;
}
if (busyCount > 0) return;
if (now - _lastThinkAt < ThinkIntervalMs) return;
_lastThinkAt = now;
if (_state == PetState.Idle)
TryBeginAction(now);
}
public void OnChatWindowText(string? text)
{
if (string.IsNullOrEmpty(text)) return;
if (_state == PetState.Summoning)
{
// "<pet> is already active" — a pet is up but our detection lagged. Back off.
if (text.Contains("is already active", StringComparison.OrdinalIgnoreCase))
{
_assumePetActiveUntil = NowMs + AssumeActiveAfterSummonMs;
GoIdle();
return;
}
// "... does not have enough charges to function!" — essence is empty.
// Drop to Idle; the next think tick reads Structure==0 and refills it.
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
{
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
GoIdle();
return;
}
return;
}
if (_state == PetState.Refilling)
{
// "You add the spirit to the essence." (success) / "This essence is
// already full." (our Structure read was stale — also done).
if (text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase)
|| text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase))
{
GoIdle();
}
}
}
// ── Decision ───────────────────────────────────────────────────────────────
private void TryBeginAction(long now)
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
if (IsPetActive()) return;
// Only summon when mobs are near (the user's trigger).
if (!MonstersNearby()) return;
// Skill gate: must have Summoning trained to use any essence.
if (!IsSummoningTrained()) return;
if (!_host.HasUseObject) return;
// Use the first usable configured essence (panel order).
foreach (int deviceId in EnumeratePetDevices())
{
if (_deviceCooldownUntil.TryGetValue(deviceId, out long until) && now < until)
continue;
int charges = ReadCharges(deviceId); // -1 = unreadable
if (charges != 0)
{
// Has charges (or unreadable → attempt; an empty one is rejected
// harmlessly with no charge cost and we'll refill on the chat).
IssueSummon(deviceId, charges);
return;
}
// charges == 0 → empty. Auto-refill from an Encapsulated Spirit.
if (_settings.PetAutoRefill)
{
int spiritId = FindEncapsulatedSpirit();
if (spiritId != 0)
{
IssueRefill(deviceId, spiritId);
return;
}
}
// Out of charges and no spirit (or refill off): park this essence
// briefly and move on to the next configured one.
_deviceCooldownUntil[deviceId] = now + DeviceNoSpiritCooldownMs;
}
}
private void IssueSummon(int deviceId, int charges)
{
// Don't fire the essence-use while a cast gesture is animating — AC
// refuses item use mid-gesture, which would burn the 8s timeout and a
// 30s device park for nothing. No state change; caller retries next tick.
if (!_host.CanCastNow) return;
_state = PetState.Summoning;
_activeDeviceId = deviceId;
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_host.UseObject(unchecked((uint)deviceId));
}
private void IssueRefill(int deviceId, int spiritId)
{
if (!_host.HasUseObjectOn) return;
if (!_host.CanCastNow) return; // same gesture gate as IssueSummon
_state = PetState.Refilling;
_activeDeviceId = deviceId;
_activeSpiritId = spiritId;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
_host.UseObjectOn(unchecked((uint)spiritId), unchecked((uint)deviceId));
}
private void GoIdle()
{
_state = PetState.Idle;
_actionIssuedAt = 0;
_preActionCharges = -1;
}
private void Reset()
{
_state = PetState.Idle;
_activeDeviceId = 0;
_activeSpiritId = 0;
_preActionCharges = -1;
_actionIssuedAt = 0;
}
// ── Signals ──────────────────────────────────────────────────────────────────
/// <summary>True once a successful summon has decremented the device's charges.</summary>
private bool SummonLanded()
{
if (_activeDeviceId == 0 || _preActionCharges < 0) return false;
int cur = ReadCharges(_activeDeviceId);
return cur >= 0 && cur < _preActionCharges;
}
private bool DeviceHasCharges(int deviceId) => ReadCharges(deviceId) > 0;
/// <summary>Device remaining charges (Structure). -1 if unreadable.</summary>
private int ReadCharges(int deviceId)
{
if (!_host.HasGetObjectIntProperty) return -1;
return _host.TryGetObjectIntProperty(unchecked((uint)deviceId),
(uint)AcIntProperty.Structure, out int s) ? s : -1;
}
/// <summary>At least PetMinMonsters attackable monsters within CustomPetRange.</summary>
private bool MonstersNearby()
{
if (_combat == null) return false;
int need = Math.Max(1, _settings.PetMinMonsters);
double range = Math.Max(1, _settings.CustomPetRange);
int count = 0;
var scanned = _combat.ScannedTargets;
for (int i = 0; i < scanned.Count; i++)
{
if (scanned[i].Distance <= range && ++count >= need)
return true;
}
return false;
}
private bool IsSummoningTrained()
{
if (_skills == null) return true; // can't read skills → don't block
// Training: 0=UNDEF, 1=UNTRAINED, 2=TRAINED, 3=SPECIALIZED.
return _skills[AcSkillType.Summoning].Training >= 2;
}
/// <summary>
/// A combat pet is up if a live creature named "&lt;PlayerName&gt;'s …" exists in
/// the cache — the server names summoned pets exactly that (Pet.Init).
/// </summary>
private bool IsPetActive()
{
string me = PlayerName();
if (me.Length == 0) return false;
string prefix = me + "'s ";
foreach (var wo in _objectCache.GetLandscape())
{
if (wo == null) continue;
string n = wo.Name;
if (!string.IsNullOrEmpty(n) && n.StartsWith(prefix, StringComparison.Ordinal))
return true;
}
return false;
}
private string PlayerName()
{
long now = NowMs;
if (_playerName.Length > 0 && now - _playerNameAt < 30_000) return _playerName;
uint pid = _host.GetPlayerId();
if (pid != 0 && _host.TryGetObjectName(pid, out string n) && !string.IsNullOrEmpty(n))
{
_playerName = n;
_playerNameAt = now;
}
return _playerName;
}
// ── Inventory lookups ─────────────────────────────────────────────────────────
/// <summary>
/// Resolve each configured Type=="Pet" rule to a concrete in-inventory device
/// id: prefer the exact instance the user added, else any same-named essence
/// (handles a re-looted/replaced essence after the original was consumed).
/// </summary>
private IEnumerable<int> EnumeratePetDevices()
{
int playerId = unchecked((int)_host.GetPlayerId());
foreach (var rule in _settings.ConsumableRules)
{
if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) continue;
var byId = _objectCache[rule.Id];
if (byId != null && IsOwnedByPlayer(byId, playerId)) { yield return rule.Id; continue; }
if (string.IsNullOrWhiteSpace(rule.Name)) continue;
foreach (var wo in _objectCache.AllKnownObjects())
{
if (wo == null) continue;
if (wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase)
&& IsOwnedByPlayer(wo, playerId))
{
yield return wo.Id;
break;
}
}
}
}
private int FindEncapsulatedSpirit()
{
int playerId = unchecked((int)_host.GetPlayerId());
foreach (var wo in _objectCache.AllKnownObjects())
{
if (wo == null) continue;
if (!IsOwnedByPlayer(wo, playerId)) continue;
if (!string.IsNullOrEmpty(wo.Name)
&& wo.Name.Contains(EncapsulatedSpiritName, StringComparison.OrdinalIgnoreCase))
return wo.Id;
}
return 0;
}
/// <summary>True if the item's container chain roots at the player's pack (not a corpse).</summary>
private bool IsOwnedByPlayer(WorldObject item, int playerId)
{
if (item.ObjectClass == AcObjectClass.Corpse) return false;
if (item.Wielder != 0 && playerId != 0 && item.Wielder != playerId) return false;
if (item.Container != 0 && playerId != 0 && item.Container != playerId)
{
var owner = _objectCache[item.Container];
if (owner == null || owner.ObjectClass == AcObjectClass.Corpse) return false;
if (owner.Wielder != playerId && owner.Container != playerId) return false;
}
return true;
}
}

Binary file not shown.

View file

@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace RynthCore.Plugin.RynthAi;
public static class SpellDatabase
{
private static readonly Dictionary<int, string> _spellNames = new();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
{
{ 47, "Primary Portal Tie" }, { 48, "Primary Portal Recall" },
{ 157, "Summon Primary Portal I" }, { 158, "Summon Primary Portal II" },
{ 1634, "Portal Sending" }, { 1635, "Lifestone Recall" },
{ 1636, "Lifestone Sending" }, { 1637, "Summon Primary Portal III" },
{ 2023, "Recall the Sanctuary" }, { 2041, "Aerlinthe Recall" },
{ 2358, "Lyceum Recall" }, { 2644, "Lifestone Tie" },
{ 2645, "Portal Recall" }, { 2646, "Secondary Portal Tie" },
{ 2647, "Secondary Portal Recall" }, { 2648, "Summon Secondary Portal I" },
{ 2649, "Summon Secondary Portal II" }, { 2650, "Summon Secondary Portal III" },
{ 2813, "Mount Lethe Recall" }, { 2931, "Recall Aphus Lassel" },
{ 2941, "Ulgrim's Recall" }, { 2943, "Recall to the Singularity Caul" },
{ 3865, "Glenden Wood Recall" }, { 3929, "Rossu Morta Chapterhouse Recall" },
{ 3930, "Whispering Blade Chapterhouse Recall" }, { 4084, "Bur Recall" },
{ 4198, "Paradox-touched Olthoi Infested Area Recall" }, { 4213, "Colosseum Recall" },
{ 4907, "Celestial Hand Stronghold Recall" }, { 4908, "Eldrytch Web Stronghold Recall" },
{ 4909, "Radiant Blood Stronghold Recall" }, { 5175, "Facility Hub Recall" },
{ 5330, "Gear Knight Invasion Area Camp Recall" }, { 5541, "Lost City of Neftet Recall" },
{ 6150, "Rynthid Recall" }, { 6321, "Viridian Rise Recall" },
{ 6322, "Viridian Rise Great Tree Recall" },
};
public static bool IsLoaded => _loaded;
public static void Load(Action<string>? log = null)
{
_spellNames.Clear();
_loaded = false;
try
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "RynthCore.Plugin.RynthAi.Combat.SpellData.txt";
using Stream? stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
log?.Invoke($"[RynthAi] ERROR: Could not find embedded resource: {resourceName}");
return;
}
using StreamReader reader = new(stream, detectEncodingFromByteOrderMarks: true);
string? line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] columns = line.Split('\t');
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
_spellNames[spellId] = columns[1].Trim();
}
_loaded = _spellNames.Count > 0;
}
catch (Exception ex)
{
log?.Invoke($"[RynthAi] Spell Load Error: {ex.Message}");
}
}
public static string GetSpellName(int spellId)
{
if (_spellNames.TryGetValue(spellId, out string? name)) return name;
if (_builtinSpells.TryGetValue(spellId, out string? builtin)) return builtin;
return $"Unknown Spell ({spellId})";
}
public static string GetSpellNameOrId(int spellId)
{
if (_spellNames.TryGetValue(spellId, out string? name)) return name;
if (_builtinSpells.TryGetValue(spellId, out string? builtin)) return builtin;
return spellId.ToString();
}
/// <summary>
/// Returns true if the spell exists in the database.
/// TODO: Replace with real "is spell known" check from AC memory.
/// </summary>
public static bool IsSpellKnown(int spellId)
{
return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
}
/// <summary>Builds a name→id reverse map for SpellManager initialisation.</summary>
public static Dictionary<string, int> BuildNameToIdMap()
{
var map = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in _spellNames)
map[kvp.Value] = kvp.Key;
foreach (var kvp in _builtinSpells)
map.TryAdd(kvp.Value, kvp.Key);
return map;
}
/// <summary>Looks up a spell ID by exact name (case-insensitive).</summary>
public static int GetIdByName(string name)
{
foreach (var kvp in _spellNames)
if (kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase))
return kvp.Key;
foreach (var kvp in _builtinSpells)
if (kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase))
return kvp.Key;
return 0;
}
}

View file

@ -0,0 +1,362 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public class SpellManager
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private CharacterSkills? _charSkills;
private uint _playerId;
// Spell ids a cast empirically proved the char does NOT know (AC sent zero
// chat back → silently dropped). This is the trustworthy "unknown" signal:
// the engine IsSpellKnown oracle is known-broken (hardcoded VA, returns
// true for unknown spells), so tier-down can't rely on it. BuffManager
// feeds these in on a no-chat timeout; TryGetId then skips them so
// GetDynamicSelfBuffId falls to the next lower (known) tier and caches it.
private readonly HashSet<int> _unresolvableSpellIds = new();
// Authoritative known-spell inventory: snapshot of the char's actual
// spellbook, read by the engine ON AC's main thread (the per-spell
// IsSpellKnown function is mis-bound and lies "true" for unknown spells;
// the off-thread pump can't read AC live). Populated via host
// ReadKnownSpells. Empty = snapshot cold → TryGetId degrades to the
// legacy path (no regression).
private readonly HashSet<int> _knownSpellIds = new();
private DateTime _lastKnownRefreshUtc = DateTime.MinValue;
private const double KnownRefreshThrottleMs = 3000;
public Dictionary<string, int> SpellDictionary { get; private set; } =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
// Map base spell names to their exact Level 7 Lore counterparts
private readonly Dictionary<string, string[]> LoreNames = new(StringComparer.OrdinalIgnoreCase)
{
{ "Strength", new[] { "Might of the Lugians" } },
{ "Endurance", new[] { "Preservance", "Perseverance" } },
{ "Coordination", new[] { "Honed Control" } },
{ "Quickness", new[] { "Hastening" } },
{ "Focus", new[] { "Inner Calm" } },
{ "Willpower", new[] { "Mind Blossom" } },
{ "Invulnerability", new[] { "Aura of Defense" } },
{ "Impregnability", new[] { "Aura of Deflection" } },
{ "Magic Resistance", new[] { "Aura of Resistance" } },
{ "Armor", new[] { "Executor's Blessing" } },
{ "Acid Protection", new[] { "Caustic Blessing" } },
{ "Blade Protection", new[] { "Blessing of the Blade Turner" } },
{ "Bludgeoning Protection", new[] { "Blessing of the Mace Turner" } },
{ "Cold Protection", new[] { "Icy Blessing" } },
{ "Fire Protection", new[] { "Fiery Blessing" } },
{ "Lightning Protection", new[] { "Storm's Blessing" } },
{ "Mana Renewal", new[] { "Battlemage's Blessing" } },
{ "Piercing Protection", new[] { "Blessing of the Arrow Turner" } },
{ "Regeneration", new[] { "Robustify" } },
{ "Rejuvenation", new[] { "Unflinching Persistence", "Unfinching Persistance" } },
{ "Heal", new[] { "Adja's Intervention" } },
{ "Revitalize", new[] { "Robustification" } },
{ "Stamina to Mana", new[] { "Meditative Trance" } },
{ "Stamina to Health", new[] { "Rushed Recovery" } },
{ "Monster Attunement", new[] { "Topheron's Blessing" } },
{ "Person Attunement", new[] { "Kaluhc's Blessing" } },
{ "Arcane Enlightenment", new[] { "Aliester's Blessing" } },
{ "Armor Tinkering Expertise", new[] { "Jibril's Blessing" } },
{ "Item Tinkering Expertise", new[] { "Yoshi's Blessing" } },
{ "Weapon Tinkering Expertise", new[] { "Koga's Blessing" } },
{ "Mana Conversion Mastery", new[] { "Nuhmidura's Blessing" } },
{ "Sprint", new[] { "Saladur's Blessing" } },
{ "Jumping Mastery", new[] { "Jahannan's Blessing" } },
{ "Fealty", new[] { "Odif's Blessing", "Odif's Boon" } },
{ "Leadership Mastery", new[] { "Ar-Pei's Blessing" } },
{ "Deception Mastery", new[] { "Ketnan's Blessing" } },
{ "Healing Mastery", new[] { "Avalenne's Blessing" } },
{ "Lockpick Mastery", new[] { "Oswald's Blessing" } },
{ "Cooking Mastery", new[] { "Morimoto's Blessing" } },
{ "Fletching Mastery", new[] { "Lilitha's Blessing" } },
{ "Alchemy Mastery", new[] { "Silencia's Blessing" } },
{ "Creature Enchantment Mastery", new[] { "Adja's Blessing" } },
{ "Item Enchantment Mastery", new[] { "Celcynd's Blessing" } },
{ "Life Magic Mastery", new[] { "Harlune's Blessing" } },
{ "War Magic Mastery", new[] { "Hieromancer's Blessing" } },
{ "Blood Drinker", new[] { "Aura of Infected Caress" } },
{ "Hermetic Link", new[] { "Aura of Mystic's Blessing" } },
{ "Heart Seeker", new[] { "Aura of Elysa's Sight" } },
{ "Spirit Drinker", new[] { "Aura of Infected Spirit Carress", "Aura of Infected Spirit Caress" } },
{ "Swift Killer", new[] { "Aura of Atlan's Alacrity" } },
{ "Defender", new[] { "Aura of Cragstone's Will" } },
{ "Impenetrability", new[] { "Brogard's Defiance" } },
{ "Acid Bane", new[] { "Olthoi's Bane" } },
{ "Blade Bane", new[] { "Swordsman's Bane", "Swordman's Bane" } },
{ "Bludgeoning Bane", new[] { "Tusker's Bane" } },
{ "Flame Bane", new[] { "Inferno's Bane" } },
{ "Frost Bane", new[] { "Gelidite's Bane" } },
{ "Lightning Bane", new[] { "Astyrrian's Bane" } },
{ "Piercing Bane", new[] { "Archer's Bane" } },
};
public SpellManager(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
_settings = settings;
}
public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills;
public void SetPlayerId(uint playerId) => _playerId = playerId;
public void InitializeNatively()
{
try
{
if (!SpellDatabase.IsLoaded)
SpellDatabase.Load(msg => _host.WriteToChat(msg, 2));
SpellDictionary = SpellDatabase.BuildNameToIdMap();
_host.WriteToChat($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1);
}
catch (Exception ex)
{
_host.WriteToChat("[RynthAi] Spell init error: " + ex.Message, 2);
}
}
/// <summary>
/// Returns the highest castable spell tier for combat (offensive/debuff) casts.
/// Uses the combat thresholds in LegacyUiSettings (MinSkillLevelTier1..8) which are
/// padded above AC's hard minimums (1/50/100/150/200/250/300/350) to avoid fizzles
/// during fights.
/// </summary>
public int GetHighestSpellTier(AcSkillType skill)
=> ComputeTier(skill,
_settings.MinSkillLevelTier1, _settings.MinSkillLevelTier2,
_settings.MinSkillLevelTier3, _settings.MinSkillLevelTier4,
_settings.MinSkillLevelTier5, _settings.MinSkillLevelTier6,
_settings.MinSkillLevelTier7, _settings.MinSkillLevelTier8);
/// <summary>
/// Same as <see cref="GetHighestSpellTier"/> but uses the Buffing-specific thresholds
/// (BuffMinSkillLevelTier1..8). Buffing fizzles are inexpensive — just retry next
/// heartbeat — so these defaults sit closer to AC's hard minimums, ensuring a
/// 390-buffed caster actually receives Incantation-tier self buffs.
/// </summary>
public int GetHighestBuffSpellTier(AcSkillType skill)
=> ComputeTier(skill,
_settings.BuffMinSkillLevelTier1, _settings.BuffMinSkillLevelTier2,
_settings.BuffMinSkillLevelTier3, _settings.BuffMinSkillLevelTier4,
_settings.BuffMinSkillLevelTier5, _settings.BuffMinSkillLevelTier6,
_settings.BuffMinSkillLevelTier7, _settings.BuffMinSkillLevelTier8);
private int ComputeTier(AcSkillType skill, int t1, int t2, int t3, int t4, int t5, int t6, int t7, int t8)
{
int buffed = _charSkills != null ? _charSkills[skill].Buffed : 250;
if (buffed >= t8) return 8;
if (buffed >= t7) return 7;
if (buffed >= t6) return 6;
if (buffed >= t5) return 5;
if (buffed >= t4) return 4;
if (buffed >= t3) return 3;
if (buffed >= t2) return 2;
return 1;
}
private static string GetRomanNumeral(int tier) => tier switch
{
1 => "I", 2 => "II", 3 => "III", 4 => "IV",
5 => "V", 6 => "VI", 7 => "VII", 8 => "VIII",
_ => "I"
};
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill)
{
RefreshKnownSpells(); // keep the authoritative inventory current (throttled)
// Self-buffs use the buffing-specific thresholds so the user can tune
// buffing tier independently from combat tier.
int maxTier = GetHighestBuffSpellTier(magicSkill);
string cleanBase = baseSpellName.Replace(" Self", "").Trim();
for (int tier = maxTier; tier >= 1; tier--)
{
if (tier == 8)
{
if (TryGetId($"Incantation of {cleanBase} Self", out int id1)) return id1;
if (TryGetId($"Incantation of {cleanBase}", out int id2)) return id2;
if (TryGetId($"Aura of Incantation of {cleanBase} Self", out int id3)) return id3;
if (TryGetId($"Aura of Incantation of {cleanBase}", out int id4)) return id4;
}
else if (tier == 7)
{
if (LoreNames.TryGetValue(cleanBase, out string[]? lores))
foreach (string lore in lores)
if (TryGetId(lore, out int idL)) return idL;
if (TryGetId($"{cleanBase} Self VII", out int id7a)) return id7a;
if (TryGetId($"{cleanBase} VII", out int id7b)) return id7b;
if (TryGetId($"Aura of {cleanBase} Self VII", out int id7c)) return id7c;
if (TryGetId($"Aura of {cleanBase} VII", out int id7d)) return id7d;
}
else
{
string numeral = GetRomanNumeral(tier);
if (TryGetId($"{cleanBase} Self {numeral}", out int idNum1)) return idNum1;
if (TryGetId($"{cleanBase} {numeral}", out int idNum2)) return idNum2;
if (TryGetId($"Aura of {cleanBase} Self {numeral}", out int idNum3)) return idNum3;
if (TryGetId($"Aura of {cleanBase} {numeral}", out int idNum4)) return idNum4;
}
}
return 0;
}
/// <summary>
/// Record that a spell id is not actually castable by this character
/// (empirically: a cast of it got zero chat back). Resolution will skip
/// it from now on so the family falls to the next lower tier.
/// </summary>
public void MarkSpellUnresolvable(int spellId)
{
if (spellId > 0) _unresolvableSpellIds.Add(spellId);
}
/// <summary>Persisted by BuffManager so the tier-7→6 drop is learned once
/// (first rebuff per char) then instant on every later session/RL.</summary>
public IReadOnlyCollection<int> UnresolvableSpellIds => _unresolvableSpellIds;
/// <summary>
/// Public, authoritative name→id resolver shared by the combat war/void
/// path so it gets the SAME logic the buff path uses: unresolvable skip +
/// the main-thread <c>_knownSpellIds</c> snapshot (the engine IsSpellKnown
/// oracle is mis-bound and lies "true" for unknown spells). A char that
/// doesn't know e.g. the tier-8 Incantation resolves false here, so the
/// caller's tier loop drops to a tier it actually knows. Call
/// <see cref="RefreshKnownSpells"/> on the consuming path first to keep the
/// snapshot warm even when not buffing.
/// </summary>
public bool TryResolveSpellId(string exactName, out int spellId)
=> TryGetId(exactName, out spellId);
/// <summary>
/// Combat-facing resolver. Deterministic: name → id via the dictionary,
/// then REQUIRES membership in the authoritative warm spellbook snapshot.
/// Deliberately does NOT consult <c>_unresolvableSpellIds</c> (the
/// empirical no-chat blacklist) or the mis-bound engine oracle — combat
/// selection is purely predictive (known ∧ scarab ∧ tier ∧ shape), so
/// nothing here can self-poison. Cold snapshot ⇒ false (combat waits for
/// the snapshot to warm rather than blind-casting an unknown spell).
/// </summary>
public bool TryResolveKnownSpellId(string exactName, out int spellId)
{
spellId = 0;
if (!SpellDictionary.TryGetValue(exactName, out int id)) return false;
if (_knownSpellIds.Count == 0) return false; // cold — don't guess
if (!_knownSpellIds.Contains(id)) return false; // char doesn't know it
spellId = id;
return true;
}
/// <summary>
/// True once the authoritative main-thread spellbook snapshot has been
/// populated. While false (cold: pre-login, fast cold-login before the
/// qualities ptr seeds, or an engine without ReadKnownSpells) TryGetId
/// degrades to the mis-bound IsSpellKnown oracle, which lies "true" for
/// unknown spells. The combat resolver uses this to refuse to blind-pick
/// the tier-8 Incantation during a cold window.
/// </summary>
public bool IsKnownSnapshotWarm => _knownSpellIds.Count > 0;
/// <summary>
/// True if the authoritative main-thread spellbook snapshot contains this
/// id. Only meaningful when <see cref="IsKnownSnapshotWarm"/> is true.
/// Used by the combat no-chat valve to refuse to blacklist a spell the
/// char demonstrably KNOWS — no chat for a known spell means the cast
/// didn't execute (off-thread busy-count leak), NOT "unknown/no comps".
/// </summary>
public bool IsKnownSpellId(int id) => _knownSpellIds.Contains(id);
/// <summary>
/// Refresh the known-spell inventory from the engine's main-thread
/// spellbook snapshot (host ReadKnownSpells). Throttled. Safe no-op if the
/// host API is absent (old engine) or the snapshot is still cold — the set
/// just stays empty and TryGetId keeps using the legacy path.
/// </summary>
public void RefreshKnownSpells()
{
if ((DateTime.UtcNow - _lastKnownRefreshUtc).TotalMilliseconds < KnownRefreshThrottleMs)
return;
_lastKnownRefreshUtc = DateTime.UtcNow;
try
{
if (!_host.HasReadKnownSpells) return;
// Grow the buffer until it is NOT completely filled. A full buffer means
// the spellbook was TRUNCATED — and because higher spell tiers carry
// higher ids, the dropped entries are exactly the high-tier self-buffs
// (Strength Self VI/VII/VIII, Incantations…). That collapses the tier
// walk to the low-id tier that survived (Strength Self I = id 2). A full
// buffing mage knows well over 2048 spells, so a fixed 2048 cap is the
// real "casts level 1" bug. Cap at 65536 as a sanity bound.
uint[] buf;
int n;
int cap = 8192;
while (true)
{
buf = new uint[cap];
n = _host.ReadKnownSpells(buf, buf.Length);
if (n < cap || cap >= 65536) break; // got the whole spellbook (or hit sanity cap)
cap *= 2;
}
if (n <= 0) return; // cold/unavailable — keep whatever we have
var fresh = new HashSet<int>();
int take = Math.Min(n, buf.Length);
for (int i = 0; i < take; i++)
if (buf[i] != 0) fresh.Add(unchecked((int)buf[i]));
if (fresh.Count == 0) return;
_knownSpellIds.Clear();
foreach (int id in fresh) _knownSpellIds.Add(id);
// Purge stale blacklist entries. The empirical blacklist accumulates
// false positives from lag-induced no-chat timeouts and persists to
// disk across sessions — higher tiers get permanently suppressed,
// causing tier walk-down to level 1. Now that the snapshot is
// authoritative, any blacklisted spell the char demonstrably knows
// was a false positive; remove it so the correct tier resolves.
_unresolvableSpellIds.RemoveWhere(id => _knownSpellIds.Contains(id));
}
catch { }
}
private bool TryGetId(string exactName, out int spellId)
{
if (!SpellDictionary.TryGetValue(exactName, out spellId))
return false;
// Authoritative snapshot wins unconditionally when warm: if the char
// demonstrably knows the spell, trust that over the empirical blacklist
// (which can be poisoned by lag-induced no-chat timeouts).
if (_knownSpellIds.Count > 0)
{
if (_knownSpellIds.Contains(spellId)) return true;
spellId = 0;
return false;
}
// Snapshot cold — fall back to the empirical blacklist. The mis-bound
// engine IsSpellKnown is still bounded by _unresolvableSpellIds so the
// tier walk doesn't spin on silently-dropped unknown spells.
if (_unresolvableSpellIds.Contains(spellId))
{
spellId = 0;
return false;
}
if (_playerId != 0 && _host.HasIsSpellKnown)
{
_host.IsSpellKnown(_playerId, unchecked((uint)spellId), out bool known);
if (!known) { spellId = 0; return false; }
return true;
}
if (SpellDatabase.IsSpellKnown(spellId)) return true;
spellId = 0;
return false;
}
}

View file

@ -0,0 +1,62 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Shared serializer for weapon/wand equip actions across BuffManager and
/// CombatManager (and any other subsystem that swaps the wielded item).
///
/// AC allows only ONE item action in flight at a time. Two UseObject equips
/// fired within ~1s — the buff↔combat wand/sword flap, or CombatManager's own
/// re-equip + EquipWeaponAndSetStance in the same tick — collide and trigger
/// the "you can only move or use one item at a time" notice, and in the worst
/// case an object-teardown access violation (DBOCache::DestroyObj). Each
/// subsystem had its OWN equip throttle (_lastEquipTime, _pendingWieldId) but
/// they didn't know about each other, so cross-subsystem swaps still raced.
///
/// This gate is a single shared instance both managers consult: a swap is only
/// allowed if no other swap has been issued within MinIntervalMs. The loser
/// yields and retries on a later tick. Spell casts and non-weapon item actions
/// (loot moves, corpse opens) do NOT go through here.
/// </summary>
public sealed class WeaponSwapGate
{
private readonly object _lock = new();
private long _lastSwapTickMs = long.MinValue / 4;
private string _lastSwapBy = "";
/// <summary>
/// Minimum milliseconds between two weapon swaps. ~3s comfortably covers
/// AC's equip + stance-change settle (matches the existing 3000ms cast
/// equip-gate in CombatManager) so a swap fully resolves before the next.
/// </summary>
public int MinIntervalMs { get; set; } = 3000;
/// <summary>
/// Atomically claim the swap slot. Returns true (recording the swap) when
/// no swap has occurred within MinIntervalMs; false when the caller must
/// wait. Only mutates state when it returns true, so a denied caller never
/// "wastes" the slot.
/// </summary>
public bool TryBeginSwap(string requestedBy)
{
long now = Environment.TickCount64;
lock (_lock)
{
if (now - _lastSwapTickMs < MinIntervalMs)
return false;
_lastSwapTickMs = now;
_lastSwapBy = requestedBy ?? "";
return true;
}
}
/// <summary>Milliseconds since the last successful swap (diagnostics).</summary>
public long MsSinceLastSwap
{
get { lock (_lock) { return Environment.TickCount64 - _lastSwapTickMs; } }
}
/// <summary>Who last claimed a swap (diagnostics).</summary>
public string LastSwapBy { get { lock (_lock) { return _lastSwapBy; } } }
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Persistent record of observed creature data — vitals, resists, armor, spells.
/// Captured passively from IdentifyObject responses and QueryHealth replies.
/// Keyed by Name (with optional Wcid disambiguator) in CreatureProfileStore.
/// </summary>
public sealed class CreatureProfile
{
public string Name { get; set; } = string.Empty;
public uint Wcid { get; set; }
public int CreatureType { get; set; }
public uint MaxHealth { get; set; }
public uint MaxStamina { get; set; }
public uint MaxMana { get; set; }
public int ArmorLevel { get; set; }
public double ResistSlash { get; set; } = 1.0;
public double ResistPierce { get; set; } = 1.0;
public double ResistBludgeon { get; set; } = 1.0;
public double ResistFire { get; set; } = 1.0;
public double ResistCold { get; set; } = 1.0;
public double ResistAcid { get; set; } = 1.0;
public double ResistElectric { get; set; } = 1.0;
public List<uint> KnownSpellIds { get; set; } = new();
public int Samples { get; set; }
public string LastSeen { get; set; } = string.Empty;
public string Notes { get; set; } = string.Empty;
}

View file

@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Thread-safe disk-backed store of CreatureProfile records.
/// File: C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json
/// Shared across all characters; engine writes, optional external editor reads.
/// Keyed by composite "name|wcid" so tier variants don't collide.
/// </summary>
internal sealed class CreatureProfileStore
{
private const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
private const string FileName = "creatures.json";
private readonly object _lock = new();
private readonly Dictionary<string, CreatureProfile> _byKey
= new(StringComparer.OrdinalIgnoreCase);
private string _lastSavedJson = string.Empty;
private bool _dirty;
private string FilePath => Path.Combine(Folder, FileName);
public void Load()
{
lock (_lock)
{
_byKey.Clear();
string path = FilePath;
if (!File.Exists(path)) return;
try
{
string json = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(json)) return;
var dict = JsonSerializer.Deserialize(
json, RynthAiJsonContext.Default.CreatureProfileDict);
if (dict != null)
{
foreach (var kv in dict)
_byKey[kv.Key] = kv.Value;
}
_lastSavedJson = json;
}
catch
{
// Corrupt file — start fresh.
}
}
}
/// <summary>Persist if anything changed since last save. Cheap to call from a tick.</summary>
public void SaveIfDirty()
{
lock (_lock)
{
if (!_dirty) return;
_dirty = false;
try
{
Directory.CreateDirectory(Folder);
string json = JsonSerializer.Serialize(
_byKey, RynthAiJsonContext.Default.CreatureProfileDict);
if (json == _lastSavedJson) return;
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, json);
File.Copy(tmp, FilePath, overwrite: true);
try { File.Delete(tmp); } catch { }
_lastSavedJson = json;
}
catch
{
}
}
}
/// <summary>Lookup by exact composite key.</summary>
public bool TryGet(string name, uint wcid, out CreatureProfile? profile)
{
lock (_lock)
{
return _byKey.TryGetValue(MakeKey(name, wcid), out profile);
}
}
/// <summary>
/// Lookup by name only. Prefers an exact-name match with the highest sample count.
/// Returns false if no record matches.
/// </summary>
public bool TryGetByName(string name, out CreatureProfile? profile)
{
profile = null;
if (string.IsNullOrEmpty(name)) return false;
lock (_lock)
{
CreatureProfile? best = null;
foreach (var kv in _byKey)
{
if (string.Equals(kv.Value.Name, name, StringComparison.OrdinalIgnoreCase))
{
if (best == null || kv.Value.Samples > best.Samples)
best = kv.Value;
}
}
profile = best;
return best != null;
}
}
/// <summary>Lookup by wcid (for UI joins). Returns the first profile with this Wcid.</summary>
public bool TryGetByWcid(uint wcid, out CreatureProfile? profile)
{
profile = null;
if (wcid == 0) return false;
lock (_lock)
{
foreach (var kv in _byKey)
{
if (kv.Value.Wcid == wcid) { profile = kv.Value; return true; }
}
}
return false;
}
/// <summary>
/// Merge a new observation into the store. Fields with value 0 / empty are
/// ignored so partial samples don't clobber better data.
/// </summary>
public void Upsert(CreatureProfile sample)
{
if (string.IsNullOrEmpty(sample.Name)) return;
lock (_lock)
{
string key = MakeKey(sample.Name, sample.Wcid);
if (!_byKey.TryGetValue(key, out var existing))
{
existing = new CreatureProfile
{
Name = sample.Name,
Wcid = sample.Wcid,
};
_byKey[key] = existing;
}
if (sample.CreatureType != 0) existing.CreatureType = sample.CreatureType;
// Vitals: take the max observed (handles partial samples + minor variation).
if (sample.MaxHealth > existing.MaxHealth) existing.MaxHealth = sample.MaxHealth;
if (sample.MaxStamina > existing.MaxStamina) existing.MaxStamina = sample.MaxStamina;
if (sample.MaxMana > existing.MaxMana) existing.MaxMana = sample.MaxMana;
if (sample.ArmorLevel > 0) existing.ArmorLevel = sample.ArmorLevel;
// Resists: overwrite when sample is plausibly a fresh appraisal (non-default).
if (sample.ResistSlash != 1.0) existing.ResistSlash = sample.ResistSlash;
if (sample.ResistPierce != 1.0) existing.ResistPierce = sample.ResistPierce;
if (sample.ResistBludgeon != 1.0) existing.ResistBludgeon = sample.ResistBludgeon;
if (sample.ResistFire != 1.0) existing.ResistFire = sample.ResistFire;
if (sample.ResistCold != 1.0) existing.ResistCold = sample.ResistCold;
if (sample.ResistAcid != 1.0) existing.ResistAcid = sample.ResistAcid;
if (sample.ResistElectric != 1.0) existing.ResistElectric = sample.ResistElectric;
if (sample.KnownSpellIds.Count > 0)
{
var seen = new HashSet<uint>(existing.KnownSpellIds);
foreach (uint id in sample.KnownSpellIds)
{
if (seen.Add(id))
existing.KnownSpellIds.Add(id);
}
}
existing.Samples++;
existing.LastSeen = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
_dirty = true;
}
}
/// <summary>
/// Returns the lowest resist (the creature's weakest damage type). 1.0 means "no data".
/// </summary>
public static (string Type, double Resist) GetWeakest(CreatureProfile p)
{
var pairs = new (string, double)[]
{
("slash", p.ResistSlash),
("pierce", p.ResistPierce),
("bludgeon", p.ResistBludgeon),
("fire", p.ResistFire),
("cold", p.ResistCold),
("acid", p.ResistAcid),
("electric", p.ResistElectric),
};
string bestType = "slash";
double best = double.MaxValue;
foreach (var pair in pairs)
{
if (pair.Item2 < best)
{
best = pair.Item2;
bestType = pair.Item1;
}
}
return (bestType, best);
}
private static string MakeKey(string name, uint wcid)
{
return wcid == 0
? name.Trim()
: name.Trim() + "|" + wcid.ToString();
}
}

View file

@ -0,0 +1,661 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Per-CHARACTER learned combat damage. Damage scales with the caster's
/// skill/buffs AND the weapon used AND the spell, so unlike CreatureProfileStore
/// (shared HP/resists — monster intrinsics) this is per character, stored next to
/// that character's settings:
/// ...\SettingsProfiles\ACEmulator\&lt;charName&gt;\monster_damage.txt
///
/// Learned, all as running averages:
/// • HpPool[wcid] — total damage to kill (≈ HP), weapon-independent
/// • HpManual[wcid] — USER-entered HP override (UI edit); wins over everything
/// • Cast[weapon|wcid|element|tier].AvgDamage — damage of one such cast (all hits)
/// • Cast[...].CritAvg / NonCritAvg — split crit vs non-crit average damage
/// • Cast[...].AvgCastsToKill — how many such casts it takes to kill
///
/// AvgCastsToKill is what makes ONE-SHOTS work: a one-shot is simply "avg ≈ 1
/// cast", so combat can swap right after the first cast — the damage math can't,
/// because nothing has landed yet when the prediction is made.
///
/// Flat line-based text (not JSON) so it stays NativeAOT-trivial and hand-editable.
/// The monster NAME is included on every row so the file is readable without a
/// wcid lookup:
/// H|&lt;wcid&gt;|&lt;name&gt;|&lt;hpToKill&gt;|&lt;samples&gt;
/// M|&lt;wcid&gt;|&lt;name&gt;|&lt;hp&gt; (manual HP override)
/// D|&lt;wcid&gt;|&lt;name&gt;|&lt;weaponId&gt;|&lt;element&gt;|&lt;tier&gt;|&lt;avgDamage&gt;|&lt;dmgSamples&gt;|&lt;avgCastsToKill&gt;|&lt;killSamples&gt;|&lt;critAvg&gt;|&lt;critSamples&gt;|&lt;nonCritAvg&gt;|&lt;nonCritSamples&gt;
/// (The loader also accepts the older 9/10-field name-less / crit-less D rows so existing data carries over.)
/// </summary>
internal sealed class MonsterDamageStore
{
private const double Alpha = 0.25; // EMA weight for each new sample
private sealed class CastStat
{
public double Avg; // avg damage per cast (all hits)
public int Samples; // damage observations
public double AvgCastsToKill; // avg number of these casts to kill the mob
public int KillSamples; // kills observed with this cast as the finisher
public double CritAvg; // avg damage of CRITICAL hits
public int CritSamples; // crit observations
public double NonCritAvg; // avg damage of non-crit hits
public int NonCritSamples; // non-crit observations
}
private sealed class WcidProfile
{
public string Name = ""; // last-seen monster name (for the readable file + UI)
public double HpPool; // 0 = unknown (learned total damage to kill)
public int HpSamples;
public double HpManual; // 0 = unset; user-entered HP override (UI), authoritative when > 0
public uint WeaponManual; // 0 = unset; user-picked weapon override for this wcid (Damage panel)
public uint OffhandManual; // 0 = unset; user-picked offhand override for this wcid (Damage panel; stored only)
public int LastTier = NoTier; // most-recent cast tier (negative = ring); NoTier = unset this session
// key = "weaponId|element|tier"
public readonly Dictionary<string, CastStat> Casts =
new(StringComparer.OrdinalIgnoreCase);
}
private const int NoTier = int.MinValue; // sentinel: no cast observed for this wcid yet
private readonly object _lock = new();
private readonly Dictionary<uint, WcidProfile> _byWcid = new();
private string _filePath = string.Empty;
private bool _dirty;
// Per-character DEFAULT weapon: the fallback every monster without its own weapon override uses,
// so editing it sweeps all "Default" monsters at once. 0 = unset (fall through to learned-best).
private uint _defaultWeapon;
private static string CastKey(uint weaponId, string element, int tier) =>
weaponId.ToString(CultureInfo.InvariantCulture) + "|" + (element ?? "") + "|" +
tier.ToString(CultureInfo.InvariantCulture);
// Names can't contain '|' (the field separator); AC names never do, but be safe.
private static string SafeName(string? name) =>
string.IsNullOrEmpty(name) ? "" : name.Replace('|', '/').Trim();
private static string Num(double d) => d.ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>Point the store at a character's folder and load its file. Safe to call again on character change.</summary>
public void SetCharacter(string charFolder)
{
lock (_lock)
{
_byWcid.Clear();
_defaultWeapon = 0;
_dirty = false;
_filePath = string.IsNullOrWhiteSpace(charFolder)
? string.Empty
: Path.Combine(charFolder, "monster_damage.txt");
}
Load();
}
public void Load()
{
lock (_lock)
{
_byWcid.Clear();
_defaultWeapon = 0;
if (string.IsNullOrEmpty(_filePath) || !File.Exists(_filePath)) return;
try
{
foreach (string raw in File.ReadAllLines(_filePath))
{
string line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
string[] f = line.Split('|');
if (f.Length >= 2 && f[0] == "DEF")
{
// DEF|weaponId — per-character default weapon (sweeping fallback)
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dw))
_defaultWeapon = dw;
}
else if (f.Length >= 4 && f[0] == "H")
{
// New: H|wcid|name|hp|samples ; Old: H|wcid|hp|samples
bool hasName = f.Length >= 5;
int hi = hasName ? 3 : 2;
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint hw)
&& double.TryParse(f[hi], NumberStyles.Float, CultureInfo.InvariantCulture, out double hp)
&& int.TryParse(f[hi + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int hs))
{
var p = Get(hw);
p.HpPool = hp;
p.HpSamples = hs;
if (hasName && f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 4 && f[0] == "M")
{
// M|wcid|name|hp — manual HP override
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint mw)
&& double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out double mhp))
{
var p = Get(mw);
p.HpManual = mhp < 0 ? 0 : mhp;
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 4 && f[0] == "W")
{
// W|wcid|name|weaponId — per-monster weapon override (Damage panel)
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint ww)
&& uint.TryParse(f[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint wid))
{
var p = Get(ww);
p.WeaponManual = wid;
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 4 && f[0] == "O")
{
// O|wcid|name|offhandId — per-monster offhand override (Damage panel; stored only)
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint ow)
&& uint.TryParse(f[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint oid))
{
var p = Get(ow);
p.OffhandManual = oid;
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 9 && f[0] == "D")
{
// New: D|wcid|name|weaponId|element|tier|avg|dmgS|avgCasts|killS|critAvg|critS|nonCritAvg|nonCritS (14 fields)
// Mid: D|wcid|name|weaponId|element|tier|avg|dmgS|avgCasts|killS (10 fields)
// Old: D|wcid|weaponId|element|tier|avg|dmgS|avgCasts|killS (9 fields)
bool hasName = f.Length >= 10;
int b = hasName ? 3 : 2; // index of weaponId
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dw)
&& uint.TryParse(f[b], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint wid)
&& int.TryParse(f[b + 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int tier)
&& double.TryParse(f[b + 3], NumberStyles.Float, CultureInfo.InvariantCulture, out double avg)
&& int.TryParse(f[b + 4], NumberStyles.Integer, CultureInfo.InvariantCulture, out int ds)
&& double.TryParse(f[b + 5], NumberStyles.Float, CultureInfo.InvariantCulture, out double ack)
&& int.TryParse(f[b + 6], NumberStyles.Integer, CultureInfo.InvariantCulture, out int ks))
{
var p = Get(dw);
if (hasName && f[2].Length > 0) p.Name = f[2];
var cast = new CastStat
{
Avg = avg, Samples = ds, AvgCastsToKill = ack, KillSamples = ks,
};
// Crit split appended in the 14-field form (only present when hasName).
if (hasName && f.Length >= 14)
{
if (double.TryParse(f[10], NumberStyles.Float, CultureInfo.InvariantCulture, out double ca)) cast.CritAvg = ca;
if (int.TryParse(f[11], NumberStyles.Integer, CultureInfo.InvariantCulture, out int cs)) cast.CritSamples = cs;
if (double.TryParse(f[12], NumberStyles.Float, CultureInfo.InvariantCulture, out double nca)) cast.NonCritAvg = nca;
if (int.TryParse(f[13], NumberStyles.Integer, CultureInfo.InvariantCulture, out int ncs)) cast.NonCritSamples = ncs;
}
p.Casts[CastKey(wid, f[b + 1], tier)] = cast;
}
}
}
}
catch
{
// Corrupt file — start fresh; it rewrites on next save.
}
}
}
/// <summary>Persist if anything changed. Cheap to call from a tick.</summary>
public void SaveIfDirty()
{
lock (_lock)
{
if (!_dirty || string.IsNullOrEmpty(_filePath)) return;
_dirty = false;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_filePath)!);
var sb = new StringBuilder();
sb.Append("# RynthAi per-character monster damage learning (auto-generated).\n");
sb.Append("# H|wcid|name|hpToKill|samples\n");
sb.Append("# M|wcid|name|hp (manual HP override, set in the Damage panel)\n");
sb.Append("# W|wcid|name|weaponId (per-monster weapon override, set in the Damage panel)\n");
sb.Append("# O|wcid|name|offhandId (per-monster offhand override, set in the Damage panel)\n");
sb.Append("# D|wcid|name|weaponId|element|tier|avgDamage|dmgSamples|avgCastsToKill|killSamples|critAvg|critSamples|nonCritAvg|nonCritSamples\n");
sb.Append("# DEF|weaponId (per-character default weapon — fallback for every monster without its own override)\n");
if (_defaultWeapon != 0)
sb.Append("DEF|").Append(_defaultWeapon).Append('\n');
foreach (var kv in _byWcid)
{
var p = kv.Value;
string name = p.Name;
if (p.HpSamples > 0)
sb.Append("H|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(Num(p.HpPool)).Append('|').Append(p.HpSamples).Append('\n');
if (p.HpManual > 0)
sb.Append("M|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(Num(p.HpManual)).Append('\n');
if (p.WeaponManual != 0)
sb.Append("W|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(p.WeaponManual).Append('\n');
if (p.OffhandManual != 0)
sb.Append("O|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(p.OffhandManual).Append('\n');
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
if (kp.Length < 3) continue;
var v = c.Value;
sb.Append("D|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(kp[0]).Append('|').Append(kp[1]).Append('|').Append(kp[2]).Append('|')
.Append(Num(v.Avg)).Append('|').Append(v.Samples).Append('|')
.Append(Num(v.AvgCastsToKill)).Append('|').Append(v.KillSamples).Append('|')
.Append(Num(v.CritAvg)).Append('|').Append(v.CritSamples).Append('|')
.Append(Num(v.NonCritAvg)).Append('|').Append(v.NonCritSamples).Append('\n');
}
}
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, sb.ToString());
File.Copy(tmp, _filePath, overwrite: true);
try { File.Delete(tmp); } catch { }
}
catch
{
}
}
}
/// <summary>
/// Fold one observed cast's damage into the (weapon, wcid, element, tier) running
/// average, split by crit vs non-crit. <paramref name="crit"/> comes from the
/// AttackerNotification crit flag (melee/missile) or the combat-log parse (magic).
/// </summary>
public void RecordHit(uint weaponId, uint wcid, string name, string element, int tier, double damage, bool crit)
{
if (wcid == 0 || damage <= 0) return;
lock (_lock)
{
SetNameLocked(wcid, name);
Get(wcid).LastTier = tier;
var s = GetCast(wcid, weaponId, element, tier);
s.Avg = s.Samples == 0 ? damage : s.Avg + Alpha * (damage - s.Avg);
s.Samples++;
if (crit)
{
s.CritAvg = s.CritSamples == 0 ? damage : s.CritAvg + Alpha * (damage - s.CritAvg);
s.CritSamples++;
}
else
{
s.NonCritAvg = s.NonCritSamples == 0 ? damage : s.NonCritAvg + Alpha * (damage - s.NonCritAvg);
s.NonCritSamples++;
}
_dirty = true;
}
}
/// <summary>
/// Fold a confirmed kill into both the wcid's HP-to-kill estimate (from total
/// damage) and the finishing cast's casts-to-kill estimate (from the fight's
/// cast count). For a one-shot that finishing cast is the single cast, so
/// AvgCastsToKill → 1.
/// </summary>
public void RecordKill(uint weaponId, uint wcid, string name, string element, int tier, int castCount, double totalDamage)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
SetNameLocked(wcid, name);
p.LastTier = tier;
if (totalDamage > 0)
{
p.HpPool = p.HpSamples == 0 ? totalDamage : p.HpPool + Alpha * (totalDamage - p.HpPool);
p.HpSamples++;
}
if (castCount > 0)
{
var s = GetCast(wcid, weaponId, element, tier);
s.AvgCastsToKill = s.KillSamples == 0 ? castCount : s.AvgCastsToKill + Alpha * (castCount - s.AvgCastsToKill);
s.KillSamples++;
}
_dirty = true;
}
}
/// <summary>Note the tier of the most-recent cast at a wcid (negative = ring) so the Damage tab's
/// collapsed row shows the LATEST tier used. In-memory only (not persisted) — resets per session.</summary>
public void NoteCast(uint wcid, int tier, string? name = null)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
p.LastTier = tier;
if (!string.IsNullOrEmpty(name)) SetNameLocked(wcid, name);
}
}
/// <summary>The latest tier used against this wcid (negative = ring). Falls back to the tier of the
/// most-killed cast entry when nothing was cast this session; 0 if unknown.</summary>
public int GetLastTier(uint wcid)
{
lock (_lock)
{
if (!_byWcid.TryGetValue(wcid, out var p)) return 0;
if (p.LastTier != NoTier) return p.LastTier;
int bestTier = 0, bestKills = -1;
foreach (var c in p.Casts)
{
if (c.Value.KillSamples > bestKills)
{
bestKills = c.Value.KillSamples;
string[] kp = c.Key.Split('|'); // weaponId|element|tier
if (kp.Length >= 3 && int.TryParse(kp[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int t))
bestTier = t;
}
}
return bestTier;
}
}
/// <summary>Average damage of one (weapon, element, tier) cast on this wcid. samples=0 when unlearned.</summary>
public double GetAvgDamage(uint weaponId, uint wcid, string element, int tier, out int samples)
{
samples = 0;
if (wcid == 0) return 0;
lock (_lock)
{
if (_byWcid.TryGetValue(wcid, out var p) && p.Casts.TryGetValue(CastKey(weaponId, element, tier), out var s))
{
samples = s.Samples;
return s.Avg;
}
}
return 0;
}
/// <summary>Average number of (weapon, element, tier) casts to kill this wcid. killSamples=0 when unlearned (≈1 ⇒ one-shot).</summary>
public double GetAvgCastsToKill(uint weaponId, uint wcid, string element, int tier, out int killSamples)
{
killSamples = 0;
if (wcid == 0) return 0;
lock (_lock)
{
if (_byWcid.TryGetValue(wcid, out var p) && p.Casts.TryGetValue(CastKey(weaponId, element, tier), out var s))
{
killSamples = s.KillSamples;
return s.AvgCastsToKill;
}
}
return 0;
}
/// <summary>Learned total-damage-to-kill for this wcid, or 0 if not yet learned.</summary>
public double GetLearnedHp(uint wcid)
{
if (wcid == 0) return 0;
lock (_lock)
return _byWcid.TryGetValue(wcid, out var p) ? p.HpPool : 0;
}
/// <summary>User-entered HP override for this wcid (0 = none). Authoritative when &gt; 0.</summary>
public double GetManualHp(uint wcid)
{
if (wcid == 0) return 0;
lock (_lock)
return _byWcid.TryGetValue(wcid, out var p) ? p.HpManual : 0;
}
/// <summary>Set (or clear, with hp &lt;= 0) the manual HP override for a wcid. Persists on next save.</summary>
public void SetManualHp(uint wcid, double hp, string? name = null)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
p.HpManual = hp <= 0 ? 0 : hp;
if (!string.IsNullOrEmpty(name)) SetNameLocked(wcid, name);
_dirty = true;
}
}
/// <summary>User-picked weapon override for this wcid (0 = none, fall back to GetBestWeapon).</summary>
public uint GetManualWeapon(uint wcid)
{
if (wcid == 0) return 0;
lock (_lock)
return _byWcid.TryGetValue(wcid, out var p) ? p.WeaponManual : 0;
}
/// <summary>Set (0 clears) the per-monster weapon override. Persists on next save.</summary>
public void SetManualWeapon(uint wcid, uint weaponId, string? name = null)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
p.WeaponManual = weaponId;
if (!string.IsNullOrEmpty(name)) SetNameLocked(wcid, name);
_dirty = true;
}
}
/// <summary>User-picked offhand override for this wcid (0 = none). Stored only — combat does not equip it.</summary>
public uint GetManualOffhand(uint wcid)
{
if (wcid == 0) return 0;
lock (_lock)
return _byWcid.TryGetValue(wcid, out var p) ? p.OffhandManual : 0;
}
/// <summary>Set (0 clears) the per-monster offhand override. Persists on next save.</summary>
public void SetManualOffhand(uint wcid, uint offhandId, string? name = null)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
p.OffhandManual = offhandId;
if (!string.IsNullOrEmpty(name)) SetNameLocked(wcid, name);
_dirty = true;
}
}
/// <summary>
/// The weapon the system "thinks is best" for this wcid, from learned data:
/// fewest average casts-to-kill (weapons with KillSamples ≥ 2), else highest
/// average damage-per-cast (weapons with Samples ≥ 3). Aggregated per weaponId
/// across the wcid's element/tier rows. Returns 0 when there isn't enough data.
/// Fewest-casts naturally captures element effectiveness empirically (the wand
/// that kills a fire-weak mob fastest tends to be the fire wand).
/// </summary>
public uint GetBestWeapon(uint wcid)
{
if (wcid == 0) return 0;
lock (_lock)
{
if (!_byWcid.TryGetValue(wcid, out var p) || p.Casts.Count == 0) return 0;
// Aggregate per weaponId (sample-weighted) across element/tier rows.
var byWeapon = new Dictionary<uint, (double castsW, int kills, double dmgW, int dmg)>();
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
if (kp.Length < 1
|| !uint.TryParse(kp[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint wid)
|| wid == 0) continue;
var v = c.Value;
byWeapon.TryGetValue(wid, out var a);
a.castsW += v.AvgCastsToKill * v.KillSamples;
a.kills += v.KillSamples;
a.dmgW += v.Avg * v.Samples;
a.dmg += v.Samples;
byWeapon[wid] = a;
}
uint bestByCasts = 0; double bestCasts = double.MaxValue;
uint bestByDmg = 0; double bestDmg = 0;
foreach (var kv in byWeapon)
{
var a = kv.Value;
if (a.kills >= 2)
{
double avgCasts = a.castsW / a.kills;
if (avgCasts > 0 && avgCasts < bestCasts) { bestCasts = avgCasts; bestByCasts = kv.Key; }
}
if (a.dmg >= 3)
{
double avgDmg = a.dmgW / a.dmg;
if (avgDmg > bestDmg) { bestDmg = avgDmg; bestByDmg = kv.Key; }
}
}
return bestByCasts != 0 ? bestByCasts : bestByDmg;
}
}
/// <summary>The per-character default weapon (0 = unset). Every monster without its own
/// override falls back to this, so editing it sweeps all "Default" monsters at once.</summary>
public uint GetDefaultWeapon()
{
lock (_lock) return _defaultWeapon;
}
public void SetDefaultWeapon(uint weaponId)
{
lock (_lock) { if (_defaultWeapon == weaponId) return; _defaultWeapon = weaponId; _dirty = true; }
}
/// <summary>Weapon combat should wield for this wcid: per-monster override if set, else the
/// per-character default weapon, else the learned best (0 = none of those).</summary>
public uint GetEffectiveWeapon(uint wcid)
{
uint manual = GetManualWeapon(wcid);
if (manual != 0) return manual;
uint def; lock (_lock) def = _defaultWeapon;
return def != 0 ? def : GetBestWeapon(wcid);
}
/// <summary>Delete one learned (weapon, element, tier) row for a wcid. Drops the wcid entirely if nothing's left.</summary>
public bool DeleteRow(uint wcid, uint weaponId, string element, int tier)
{
lock (_lock)
{
if (!_byWcid.TryGetValue(wcid, out var p)) return false;
bool removed = p.Casts.Remove(CastKey(weaponId, element, tier));
if (removed)
{
if (p.Casts.Count == 0 && p.HpSamples == 0 && p.HpManual <= 0 && p.HpPool <= 0
&& p.WeaponManual == 0 && p.OffhandManual == 0)
_byWcid.Remove(wcid);
_dirty = true;
}
return removed;
}
}
/// <summary>Delete ALL learned history for a wcid (every weapon/spell + HP). For a character upgrade reset.</summary>
public bool DeleteWcid(uint wcid)
{
lock (_lock)
{
bool removed = _byWcid.Remove(wcid);
if (removed) _dirty = true;
return removed;
}
}
/// <summary>
/// Master reset: zero every LEARNED statistic (damage averages, crit/non-crit,
/// casts-to-kill, kills, learned HP pool) while KEEPING monster names, the cast
/// rows themselves (so the table still lists the monsters), and the user's manual
/// overrides (HpManual, WeaponManual, OffhandManual). Re-fighting re-learns from scratch.
/// </summary>
public void ClearAllStats()
{
lock (_lock)
{
foreach (var p in _byWcid.Values)
{
p.HpPool = 0;
p.HpSamples = 0;
foreach (var c in p.Casts.Values)
{
c.Avg = 0; c.Samples = 0;
c.AvgCastsToKill = 0; c.KillSamples = 0;
c.CritAvg = 0; c.CritSamples = 0;
c.NonCritAvg = 0; c.NonCritSamples = 0;
}
}
_dirty = true;
}
}
/// <summary>One learned row for the UI: a (wcid, weapon, element, tier) cast stat.</summary>
public readonly record struct DamageRow(
uint Wcid, string Name, double HpPool, double HpManual,
uint WeaponId, string Element, int Tier,
double AvgDamage, int DmgSamples,
double AvgCritDamage, int CritSamples,
double AvgNonCritDamage, int NonCritSamples,
double AvgCastsToKill, int KillSamples);
/// <summary>Snapshot all learned rows for live display. Cheap; copies under lock.</summary>
public List<DamageRow> Snapshot()
{
var list = new List<DamageRow>();
lock (_lock)
{
foreach (var kv in _byWcid)
{
var p = kv.Value;
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
uint weaponId = kp.Length >= 1 && uint.TryParse(kp[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint w) ? w : 0;
string element = kp.Length >= 2 ? kp[1] : "";
int tier = kp.Length >= 3 && int.TryParse(kp[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int t) ? t : 0;
var v = c.Value;
list.Add(new DamageRow(kv.Key, p.Name, p.HpPool, p.HpManual, weaponId, element, tier,
v.Avg, v.Samples, v.CritAvg, v.CritSamples, v.NonCritAvg, v.NonCritSamples,
v.AvgCastsToKill, v.KillSamples));
}
}
}
return list;
}
private void SetNameLocked(uint wcid, string name)
{
string n = SafeName(name);
if (n.Length == 0) return;
Get(wcid).Name = n;
}
private WcidProfile Get(uint wcid)
{
if (!_byWcid.TryGetValue(wcid, out var p))
{
p = new WcidProfile();
_byWcid[wcid] = p;
}
return p;
}
private CastStat GetCast(uint wcid, uint weaponId, string element, int tier)
{
var casts = Get(wcid).Casts;
string key = CastKey(weaponId, element, tier);
if (!casts.TryGetValue(key, out var s))
{
s = new CastStat();
casts[key] = s;
}
return s;
}
}

View file

@ -0,0 +1,310 @@
// ============================================================================
// DoorInteractionController.cs — partial class RynthAiPlugin
//
// Detects closed doors while the macro is running and automatically opens them.
// Optionally uses lockpicks from the Consumable Items list if the door is
// locked (UseObject fails to open it).
//
// State machine: None → Opening → CheckingResult → Unlocking → RetryOpen → Cooldown
// ============================================================================
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private int _doorTargetId;
private long _doorActionAt;
private int _doorAttempts;
private bool _doorPausedNav;
private DoorState _doorState = DoorState.None;
private long _doorLastDiagAt;
// Doors we've already opened — skip for 60s so we don't re-target them
private readonly System.Collections.Generic.Dictionary<int, long> _doorOpenedRecently = new();
private const long DoorBusyTimeoutMs = 3000;
private const long DoorCooldownMs = 5000;
private const long DoorOpenedSkipMs = 60000;
private const int DoorMaxAttempts = 3;
private const float YardsToMeters = 0.9144f;
private enum DoorState
{
None,
Opening,
CheckingResult,
Unlocking,
RetryOpen,
Cooldown
}
/// <summary>
/// Called each tick when the macro is running.
/// Returns true if door interaction is blocking navigation.
/// </summary>
private bool TickDoorInteraction()
{
var settings = _dashboard?.Settings;
if (settings == null || !settings.IsMacroRunning || !settings.OpenDoors)
{
ResetDoorState();
return false;
}
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
// Clean up stale entries from the recently-opened dict
if (_doorOpenedRecently.Count > 0)
{
var expired = _doorOpenedRecently
.Where(kv => now - kv.Value >= DoorOpenedSkipMs)
.Select(kv => kv.Key).ToList();
foreach (var key in expired)
_doorOpenedRecently.Remove(key);
}
// ── Idle: scan for a nearby closed door ─────────────────────────────
if (_doorState == DoorState.None)
{
int doorId = FindNearestClosedDoor(settings.OpenDoorRange, now);
if (doorId == 0) return false;
Host.Log($"[RynthAi] Door: targeting 0x{(uint)doorId:X8} (state={GetDoorStateDebug(doorId)}, busy={_busyCount})");
_doorTargetId = doorId;
_doorState = DoorState.Opening;
_doorAttempts = 0;
_doorActionAt = now;
_navigationEngine?.Stop();
if (Host.HasStopCompletely) Host.StopCompletely();
_doorPausedNav = true;
Host.UseObject(unchecked((uint)doorId));
return true;
}
// ── Timeout guard (only for action-waiting states) ────────────────
if (_doorState is DoorState.Opening or DoorState.Unlocking or DoorState.RetryOpen
&& now - _doorActionAt > DoorBusyTimeoutMs)
{
// Check if the door opened while we were waiting (slow state propagation)
if (IsDoorOpen(_doorTargetId))
{
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened (late detect) — ready for next");
MarkDoorOpenedAndReset(now);
return false;
}
_doorAttempts++;
if (_doorAttempts >= DoorMaxAttempts)
{
Host.Log($"[RynthAi] Door: max attempts ({DoorMaxAttempts}) for 0x{(uint)_doorTargetId:X8}, cooldown");
_doorState = DoorState.Cooldown;
_doorActionAt = now;
return true;
}
Host.Log($"[RynthAi] Door: timeout in {_doorState}, retry #{_doorAttempts} for 0x{(uint)_doorTargetId:X8} (busy={_busyCount})");
_doorState = DoorState.Opening;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
return true;
}
switch (_doorState)
{
case DoorState.Opening:
if (_busyCount > 0) return true;
if (IsDoorOpen(_doorTargetId))
{
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened OK — ready for next");
MarkDoorOpenedAndReset(now);
return false;
}
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} not open after use ({GetDoorStateDebug(_doorTargetId)}), checking result");
_doorState = DoorState.CheckingResult;
_doorActionAt = now;
return true;
case DoorState.CheckingResult:
if (!settings.AutoUnlockDoors)
{
Host.Log("[RynthAi] Door: not open & auto-unlock off, cooldown");
_doorState = DoorState.Cooldown;
_doorActionAt = now;
return true;
}
var lockpick = FindLockpickInConsumables();
if (lockpick == null)
{
Host.Log("[RynthAi] Door: locked but no lockpick in consumables, cooldown");
_doorState = DoorState.Cooldown;
_doorActionAt = now;
return true;
}
Host.Log($"[RynthAi] Door: using lockpick {lockpick.Name} on 0x{(uint)_doorTargetId:X8}");
_doorState = DoorState.Unlocking;
_doorActionAt = now;
Host.UseObjectOn(unchecked((uint)lockpick.Id), unchecked((uint)_doorTargetId));
return true;
case DoorState.Unlocking:
if (_busyCount > 0) return true;
Host.Log($"[RynthAi] Door: unlock done, retrying open 0x{(uint)_doorTargetId:X8}");
_doorState = DoorState.RetryOpen;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
return true;
case DoorState.RetryOpen:
if (_busyCount > 0) return true;
if (IsDoorOpen(_doorTargetId))
{
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} unlocked & opened OK — ready for next");
MarkDoorOpenedAndReset(now);
return false;
}
_doorAttempts++;
if (_doorAttempts >= DoorMaxAttempts)
{
Host.Log($"[RynthAi] Door: max attempts after unlock for 0x{(uint)_doorTargetId:X8}, cooldown");
_doorState = DoorState.Cooldown;
_doorActionAt = now;
}
else
{
_doorState = DoorState.Opening;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
}
return true;
case DoorState.Cooldown:
if (now - _doorActionAt >= DoorCooldownMs)
{
Host.Log($"[RynthAi] Door: cooldown done for 0x{(uint)_doorTargetId:X8}, resetting");
ResetDoorState();
}
return _doorState != DoorState.None;
}
return false;
}
private void MarkDoorOpenedAndReset(long now)
{
_doorOpenedRecently[_doorTargetId] = now;
ResetDoorState();
}
private void ResetDoorState()
{
_doorTargetId = 0;
_doorState = DoorState.None;
_doorAttempts = 0;
_doorPausedNav = false;
}
private int FindNearestClosedDoor(float rangeYards, long now)
{
if (_objectCache == null || _playerId == 0) return 0;
float rangeMeters = rangeYards * YardsToMeters;
int bestId = 0;
double bestDist = double.MaxValue;
bool hasBitfield = Host.HasGetObjectBitfield;
int totalLandscape = 0, doorsFound = 0, openSkipped = 0, recentSkipped = 0;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
uint uid = unchecked((uint)wo.Id);
totalLandscape++;
// Doors have static GUIDs (< 0x80000000)
if (uid >= 0x80000000u) continue;
// Primary: BF_DOOR bitfield check
if (hasBitfield)
{
if (!Host.TryGetObjectBitfield(uid, out uint bf) || (bf & 0x1000u) == 0)
continue;
}
else
{
string nl = (wo.Name ?? string.Empty).ToLowerInvariant();
if (!nl.Contains("door") && !nl.Contains("gate") && !nl.Contains("hatch") && !nl.Contains("portcullis"))
continue;
}
doorsFound++;
// Skip doors we recently opened
if (_doorOpenedRecently.TryGetValue(wo.Id, out long openedAt) && (now - openedAt) < DoorOpenedSkipMs)
{
recentSkipped++;
continue;
}
// Skip already-open doors
if (IsDoorOpen(wo.Id))
{
openSkipped++;
continue;
}
double dist = _objectCache.Distance(unchecked((int)_playerId), wo.Id);
if (dist > rangeMeters || dist >= bestDist) continue;
bestDist = dist;
bestId = wo.Id;
}
// Periodic diagnostic when doors are nearby but none targeted
if (bestId == 0 && doorsFound > 0 && (now - _doorLastDiagAt) >= 5000)
{
_doorLastDiagAt = now;
Host.Log($"[RynthAi] Door scan: {totalLandscape} landscape, {doorsFound} doors, {openSkipped} open, {recentSkipped} recent-skip, range={rangeMeters:F1}m");
}
return bestId;
}
private bool IsDoorOpen(int doorId)
{
uint uid = unchecked((uint)doorId);
// Primary: read CPhysicsObj::m_state directly — ETHEREAL_PS (0x4) = open
if (Host.HasGetObjectState && Host.TryGetObjectState(uid, out uint physState))
return (physState & 0x4u) != 0;
// Fallback: DoMotionHooks tracks MotionOn/MotionOff per object
if (Host.HasGetObjectMotionOn && Host.TryGetObjectMotionOn(uid, out bool isOn))
return isOn;
return false;
}
private string GetDoorStateDebug(int doorId)
{
uint uid = unchecked((uint)doorId);
if (Host.HasGetObjectState && Host.TryGetObjectState(uid, out uint ps))
return $"phys=0x{ps:X8} ethereal={(ps & 0x4u) != 0}";
if (Host.HasGetObjectMotionOn && Host.TryGetObjectMotionOn(uid, out bool on))
return $"motionOn={on}";
return "no-state";
}
private ConsumableRule? FindLockpickInConsumables()
{
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null) return null;
return settings.ConsumableRules
.Where(r => r.Type.Equals("Lockpick", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(r => _objectCache[r.Id] != null);
}
}

View file

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// On-disk persistence for discovered dungeon hazard cells (lava / acid / fire pools).
///
/// Hazards are static world geometry — they never move and are identical for every
/// character — so the store is keyed by <b>landblock</b>, not by character, and lives in
/// one shared global folder. The first time a hotspot is sighted in a dungeon it is
/// written here; on every later visit the patrol builder seeds these cells before it
/// constructs the route, so the route avoids them from the very first waypoint instead of
/// having to discover and reroute around them again.
///
/// One file per landblock keeps multi-box writers in different dungeons from contending,
/// and <see cref="Append"/> does a read-merge-write union so two boxes exploring the SAME
/// dungeon both keep their discoveries. Format is one cell-id hex per line (comment-safe):
/// trivial to read, merge, and hand-edit.
/// </summary>
internal static class DungeonHazardStore
{
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi\DungeonHazards";
private static string PathFor(uint landblockKey)
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");
/// <summary>
/// Returns the persisted hazard cell-ids for a landblock, or an empty set if none have
/// been recorded (or the file is missing/unreadable). Never throws.
/// </summary>
public static HashSet<uint> Load(uint landblockKey)
{
var set = new HashSet<uint>();
try
{
string path = PathFor(landblockKey);
if (!File.Exists(path)) return set;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
// Accept optional 0x prefix.
if (line.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
line = line.Substring(2);
if (uint.TryParse(line, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint cell))
set.Add(cell);
}
}
catch { /* unreadable store — behave as if empty */ }
return set;
}
/// <summary>Landblock keys that have a persisted hazard file, ascending. Never throws.</summary>
public static List<uint> ListLandblocks()
{
var result = new List<uint>();
try
{
if (!Directory.Exists(Folder)) return result;
foreach (string path in Directory.GetFiles(Folder, "*.txt"))
{
string name = System.IO.Path.GetFileNameWithoutExtension(path);
if (uint.TryParse(name, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb))
result.Add(lb);
}
result.Sort();
}
catch { }
return result;
}
/// <summary>Number of hazard cells recorded for a landblock (0 if none). Never throws.</summary>
public static int Count(uint landblockKey) => Load(landblockKey).Count;
/// <summary>Removes a single cell from a landblock's persisted set. Never throws.</summary>
public static void RemoveCell(uint landblockKey, uint cellId)
{
try
{
var existing = Load(landblockKey);
if (!existing.Remove(cellId)) return;
if (existing.Count == 0) { Clear(landblockKey); return; }
var lines = new List<string>(existing.Count);
foreach (uint c in existing) lines.Add($"0x{c:X8}");
string path = PathFor(landblockKey);
string tmp = path + ".tmp";
File.WriteAllLines(tmp, lines);
File.Copy(tmp, path, overwrite: true);
File.Delete(tmp);
}
catch { }
}
/// <summary>Deletes the persisted hazards for one landblock. Never throws.</summary>
public static void Clear(uint landblockKey)
{
try
{
string path = PathFor(landblockKey);
if (File.Exists(path)) File.Delete(path);
}
catch { }
}
/// <summary>Deletes every persisted-hazard file. Never throws.</summary>
public static void ClearAll()
{
try
{
if (!Directory.Exists(Folder)) return;
foreach (string path in Directory.GetFiles(Folder, "*.txt"))
File.Delete(path);
}
catch { }
}
/// <summary>
/// Records a newly-discovered hazard cell. Read-merge-writes so a concurrent box in the
/// same dungeon does not clobber the other's discoveries. No-op (no rewrite) if the cell
/// is already on disk. Never throws.
/// </summary>
public static void Append(uint landblockKey, uint cellId)
{
try
{
Directory.CreateDirectory(Folder);
var existing = Load(landblockKey);
if (!existing.Add(cellId)) return; // already persisted
var lines = new List<string>(existing.Count);
foreach (uint c in existing)
lines.Add($"0x{c:X8}");
// Atomic-ish: write a temp then move over the target so a crash mid-write
// can't leave a half-written file.
string path = PathFor(landblockKey);
string tmp = path + ".tmp";
File.WriteAllLines(tmp, lines);
File.Copy(tmp, path, overwrite: true);
File.Delete(tmp);
}
catch { /* best-effort persistence — a lost write just means we re-learn it */ }
}
}

View file

@ -0,0 +1,285 @@
// Detector C — offline lava/acid hazard-cell detection from EnvCell surface textures.
//
// WHY: AC environmental hazards are server-side `HotSpot` weenies, and ~75/120 templates set
// PropertyBool.Visibility=true, so ACE never broadcasts them to the client (Player_Tracking.cs:58
// "object is meant for server side only"). A live object scan (WorldObjectCache.MaybeRegisterHazard,
// name-pattern on a *visible* object) therefore structurally cannot see the invisible majority.
// What IS always observable offline is the lava/acid FLOOR TEXTURE the dungeon author painted into
// the EnvCell, sitting in client_portal.dat. Detector C reads that texture directly and pre-emptively
// marks matching cells hazardous at patrol-build time — no first-hit, no broadcast, no visible object.
//
// RESOLUTION CHAIN (all verified):
// EnvCell (cell.dat) -> ushort[numSurfaces] palette
// -> (0x08000000u | surfIdx) -> Surface file (portal.dat 0x0800xxxx)
// -> Surface.Type (uint @ OFFSET 0, NO leading-id skip)
// if (Type & (Base1Image 0x2 | Base1ClipMap 0x4)) -> OrigTextureId (uint, next) <-- HAZARD KEY
// else: ColorValue (solid color) -> not a texture
// (confirmed against AcTextures.cs:50-59 / Surface.cs:23 and real portal.dat bytes
// file 0x08000000 = 04 00 00 00 | F2 25 00 05 -> Type=0x4, OrigTextureId=0x050025F2.)
//
// SCOPE: texture-only detection has its own blind spot — air/fog/cloud/mana-field and explicitly
// invisible-floor hotspots carry no distinctive floor texture. Detector C SUPPLEMENTS the live
// name-detector + reactive marking; it does not replace them. All three write the same idempotent
// WorldObjectCache._hazardCells set, so they compose.
//
// THREADING: pure DatDatabase.GetFileData reads — no live AC object access — so this adds no
// off-thread-AV / object-teardown risk. Runs on the patrol-build (pump) thread, cached per landblock.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardSurfaces
{
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi";
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
private static readonly object _gate = new();
// OrigTextureIds (0x05) the user/learner has flagged as lava/acid/fire floors. Lazy-loaded.
private static HashSet<uint>? _hazardTextures;
// surfIdx -> OrigTextureId (0 = solid color / missing). Surfaces are global across dungeons,
// so a process-wide memo is correct and keeps per-landblock scans cheap.
private static readonly Dictionary<ushort, uint> _surfTexCache = new();
// Per-landblock computed hazard-cell set (recomputed when the texture set changes).
private static uint _cachedLandblock;
private static HashSet<uint>? _cachedCells;
// ── Hazard-texture set (persistent, user-editable) ─────────────────────────
private static HashSet<uint> Textures()
{
// caller holds _gate
if (_hazardTextures != null) return _hazardTextures;
var set = new HashSet<uint>();
try
{
if (File.Exists(SetPath))
{
foreach (string raw in File.ReadAllLines(SetPath))
{
string line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
if (line.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) line = line.Substring(2);
if (uint.TryParse(line, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint t))
set.Add(t);
}
}
}
catch { /* unreadable set — behave as empty */ }
_hazardTextures = set;
return set;
}
public static bool IsHazardTexture(uint origTextureId)
{
if (origTextureId == 0) return false;
lock (_gate) return Textures().Contains(origTextureId);
}
public static int HazardTextureCount { get { lock (_gate) return Textures().Count; } }
public static List<uint> ListHazardTextures()
{
lock (_gate) { var l = new List<uint>(Textures()); l.Sort(); return l; }
}
/// <summary>Flags a texture id as hazardous, persists it, and invalidates the cell cache. True if newly added.</summary>
public static bool AddHazardTexture(uint origTextureId)
{
if (origTextureId == 0) return false;
lock (_gate)
{
if (!Textures().Add(origTextureId)) return false;
Persist();
_cachedCells = null; _cachedLandblock = 0;
return true;
}
}
/// <summary>Unflags a texture id, persists, and invalidates the cell cache. True if it was present.</summary>
public static bool RemoveHazardTexture(uint origTextureId)
{
lock (_gate)
{
if (!Textures().Remove(origTextureId)) return false;
Persist();
_cachedCells = null; _cachedLandblock = 0;
return true;
}
}
private static void Persist()
{
// caller holds _gate
try
{
Directory.CreateDirectory(Folder);
var lines = new List<string>
{
"# RynthAi Detector C — hazard floor textures (0x05 OrigTextureId), one hex id per line.",
"# Flag a lava/acid floor with: /ra hazard surfaces then /ra hazard learnhere (or texture add 0x<id>).",
};
var sorted = new List<uint>(_hazardTextures!);
sorted.Sort();
foreach (uint t in sorted) lines.Add($"0x{t:X8}");
string tmp = SetPath + ".tmp";
File.WriteAllLines(tmp, lines);
File.Copy(tmp, SetPath, overwrite: true); // best-effort; Load is defensive against a torn file
File.Delete(tmp);
}
catch { /* best-effort persistence */ }
}
/// <summary>Drops the in-memory set + cell cache so the next query reloads from disk (after a hand-edit).</summary>
public static void Reload()
{
lock (_gate) { _hazardTextures = null; _cachedCells = null; _cachedLandblock = 0; }
}
public static void InvalidateCells()
{
lock (_gate) { _cachedCells = null; _cachedLandblock = 0; }
}
// ── Surface resolution ─────────────────────────────────────────────────────
/// <summary>
/// Resolves a 16-bit EnvCell surface-palette index to its 0x05 OrigTextureId via portal.dat.
/// Returns 0 for solid-color / missing / non-image surfaces. Memoized process-wide. Never throws.
/// </summary>
public static uint ResolveOrigTextureId(DatDatabase? portal, ushort surfIdx)
{
lock (_gate)
if (_surfTexCache.TryGetValue(surfIdx, out uint cached)) return cached;
uint tex = 0;
try
{
byte[]? d = portal?.GetFileData(0x08000000u | surfIdx);
if (d != null && d.Length >= 8)
{
// Surface (0x08) body begins at offset 0 with uint Type — NO leading file-id.
uint type = BitConverter.ToUInt32(d, 0);
if ((type & (0x2u | 0x4u)) != 0) // Base1Image | Base1ClipMap -> has a texture
tex = BitConverter.ToUInt32(d, 4); // OrigTextureId (0x05 SurfaceTexture id)
}
}
catch { tex = 0; }
lock (_gate) _surfTexCache[surfIdx] = tex;
return tex;
}
/// <summary>Reads an EnvCell's surface palette → (surfIdx, OrigTextureId) pairs. For diagnostics. Never throws.</summary>
public static List<(ushort surfIdx, uint texId)> GetCellSurfaces(DatDatabase? cellDat, DatDatabase? portal, uint cellId)
{
var result = new List<(ushort, uint)>();
try
{
byte[]? data = cellDat?.GetFileData(cellId);
if (data == null || data.Length < 16) return result;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32(); // id, flags, dupId
byte numSurfaces = r.ReadByte();
r.ReadByte(); // numPortals
r.ReadUInt16(); // numVisibleCells
for (int i = 0; i < numSurfaces; i++)
{
if (ms.Position + 2 > ms.Length) break;
ushort s = r.ReadUInt16();
result.Add((s, ResolveOrigTextureId(portal, s)));
}
}
catch { }
return result;
}
/// <summary>Distinct non-zero OrigTextureIds present in an EnvCell's surface palette. Never throws.</summary>
private static HashSet<uint> CellTextureSet(DatDatabase? cellDat, DatDatabase? portal, uint cellId)
{
var set = new HashSet<uint>();
foreach (var (_, texId) in GetCellSurfaces(cellDat, portal, cellId))
if (texId != 0) set.Add(texId);
return set;
}
// ── Per-landblock hazard-cell computation ──────────────────────────────────
/// <summary>
/// Returns (cached) the EnvCells in the landblock whose surface palette contains a flagged
/// hazard texture. Cheap no-op re-call for the same landblock. Pure dat reads. Never throws.
/// </summary>
public static HashSet<uint> ComputeHazardCells(uint landblockKey, DatDatabase? cellDat, DatDatabase? portal)
{
lock (_gate)
if (_cachedCells != null && _cachedLandblock == landblockKey) return _cachedCells;
var cells = new HashSet<uint>();
try
{
if (cellDat != null && portal != null && HazardTextureCount > 0)
{
foreach (uint cellId in cellDat.GetLandblockCellIds(landblockKey))
{
foreach (uint texId in CellTextureSet(cellDat, portal, cellId))
{
if (IsHazardTexture(texId)) { cells.Add(cellId); break; }
}
}
}
}
catch { }
lock (_gate) { _cachedCells = cells; _cachedLandblock = landblockKey; }
return cells;
}
// ── Learn-here (precision-guarded auto-flag) ───────────────────────────────
/// <summary>
/// Stand in a hazard cell and call this: it flags the cell's surface texture(s) that are RARE
/// across the landblock (the texture only lava/acid cells use), while rejecting the common
/// floor/wall textures. This is the safe auto-bootstrap — it avoids the catastrophic failure of
/// learning a ubiquitous floor texture and banning the whole dungeon. Returns the newly-flagged ids.
/// </summary>
public static List<uint> LearnFromCell(uint cellId, DatDatabase? cellDat, DatDatabase? portal,
double rareFractionMax = 0.25)
{
var learned = new List<uint>();
try
{
if (cellDat == null || portal == null) return learned;
uint landblockKey = cellId >> 16;
var freq = new Dictionary<uint, int>();
int totalCells = 0;
foreach (uint cid in cellDat.GetLandblockCellIds(landblockKey))
{
var texs = CellTextureSet(cellDat, portal, cid);
if (texs.Count == 0) continue;
totalCells++;
foreach (uint t in texs) freq[t] = freq.GetValueOrDefault(t) + 1;
}
if (totalCells == 0) return learned;
foreach (uint t in CellTextureSet(cellDat, portal, cellId))
{
double frac = freq.GetValueOrDefault(t) / (double)totalCells;
if (frac <= rareFractionMax && AddHazardTexture(t))
learned.Add(t);
}
}
catch { }
return learned;
}
}

View file

@ -0,0 +1,741 @@
// DungeonPathfinder — cell-graph builder + A* for autonomous dungeon navigation.
//
// ADJACENCY MODEL — uses portal records, not visible-cell lists.
//
// The EnvCell header has two adjacency fields:
// • numVisibleCells / visible-cell list — cells visible for LOD rendering. This includes
// cells reachable through multiple doorways (A can see C through B). Using this for
// pathfinding creates diagonal edges that cut through walls.
// • numPortals / portal records — cells sharing a physical doorway with this cell.
// This is the correct walking adjacency: every edge is a real door opening.
//
// WAYPOINTS — portal midpoints, not cell centres.
//
// Navigating straight from cell-A centre to cell-B centre can cut through a corner if the
// doorway is offset from the line between centres. Instead we navigate to the midpoint of
// the two cell centres — which approximates the doorway position on the cell boundary —
// then continue to the next portal midpoint, and finally to the user's exact destination.
//
// Pipeline:
// 1. BuildGraph(landblockKey, cellDat)
// → parse every EnvCell header, read portal records for true walking adjacency
// → return Dictionary<cellId, DungeonNavNode>
// 2. NearestCell(graph, ns, ew) → snap a position to the nearest node
// 3. FindPath(start, goal, graph) → A*, returns ordered List<cellId>
// 4. BuildNavRoute(path, graph, destNS, destEW)
// → portal midpoints as waypoints + exact destination at the end
// 5. Set settings.CurrentRoute = route; settings.EnableNavigation = true;
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi;
internal sealed class DungeonNavNode
{
public uint CellId;
public double NS, EW;
public float Z;
public List<uint> Neighbors = new(); // portal-connected cells only
}
internal static class DungeonPathfinder
{
// Angle threshold (degrees) above which a portal edge is classified as a drop.
// A slope has significant horizontal movement relative to its Z change — its
// centre-to-centre angle is well below 45°. A drop is near-vertical (the two
// cell centres are almost directly above each other) so the angle approaches 90°.
// 45° = equal horizontal and vertical movement. Ramps are typically 10-25°,
// a direct floor-shaft drop is 60-90°.
private const double DropAngleDeg = 45.0;
// Returns true when the portal edge between a and b is a drop the bot cannot
// traverse by walking. Uses a slope-angle calculation:
// - Convert NS/EW (nav coords) to raw world units (×240) so they share the
// same scale as Z.
// - atan2(|dZ|, dHoriz) > DropAngleDeg → drop.
// Near-zero horizontal distance (rooms stacked vertically) is always a drop.
private static bool IsDropEdge(DungeonNavNode a, DungeonNavNode b)
{
double dZ = Math.Abs(b.Z - a.Z);
if (dZ < 0.5) return false; // trivially flat
double dNS = (b.NS - a.NS) * 240.0;
double dEW = (b.EW - a.EW) * 240.0;
double dHoriz = Math.Sqrt(dNS * dNS + dEW * dEW);
if (dHoriz < 1.0) return true; // near-vertical shaft
double angleDeg = Math.Atan2(dZ, dHoriz) * (180.0 / Math.PI);
return angleDeg > DropAngleDeg;
}
private static uint _cachedLandblockKey;
private static Dictionary<uint, DungeonNavNode>? _cachedGraph;
/// <summary>Returns the cached graph for the landblock, rebuilding if stale.</summary>
public static Dictionary<uint, DungeonNavNode> GetGraph(uint landblockKey, DatDatabase cellDat)
{
if (_cachedLandblockKey == landblockKey && _cachedGraph != null)
return _cachedGraph;
_cachedGraph = BuildGraph(landblockKey, cellDat);
_cachedLandblockKey = landblockKey;
return _cachedGraph;
}
public static void InvalidateCache()
{
_cachedGraph = null;
_cachedLandblockKey = 0;
}
// ── Graph construction ──────────────────────────────────────────────────
/// <summary>
/// Parses every EnvCell header and builds an adjacency graph from portal records.
/// Only cells that share a physical doorway become neighbours — visible-cell lists
/// are ignored to prevent diagonal shortcuts through walls.
///
/// EnvCell binary layout:
/// uint id, flags, dupId
/// byte numSurfaces, byte numPortals, ushort numVisibleCells
/// ushort[numSurfaces] ← surface IDs, skipped
/// ushort envId, ushort cellStruct
/// float posX, posY, posZ ← cell centre in landblock-local space
/// float rotW, rotX, rotY, rotZ
/// CellPortal[numPortals]: ← each 8 bytes = 4 × ushort
/// ushort flags
/// ushort polygonId ← portal poly key in CellStruct (not needed here)
/// ushort otherCellId ← lower 16 bits of connected cell
/// ushort otherPortalId
/// ushort[numVisibleCells] ← skipped
/// </summary>
private static Dictionary<uint, DungeonNavNode> BuildGraph(uint landblockKey, DatDatabase cellDat)
{
var nodes = new Dictionary<uint, DungeonNavNode>();
float gx = ((landblockKey >> 8) & 0xFF) * 192f;
float gy = (landblockKey & 0xFF) * 192f;
var cellIds = cellDat.GetLandblockCellIds(landblockKey);
foreach (uint cellId in cellIds)
{
byte[]? data = cellDat.GetFileData(cellId);
if (data == null || data.Length < 36) continue;
try
{
using var ms = new MemoryStream(data);
using var reader = new BinaryReader(ms);
reader.ReadUInt32(); // id
reader.ReadUInt32(); // flags
reader.ReadUInt32(); // dup id
byte numSurfaces = reader.ReadByte();
byte numPortals = reader.ReadByte();
ushort numVisibleCells = reader.ReadUInt16();
ms.Seek(numSurfaces * 2, SeekOrigin.Current); // skip surface IDs
reader.ReadUInt16(); // envId
reader.ReadUInt16(); // cellStructure
float posX = reader.ReadSingle();
float posY = reader.ReadSingle();
float posZ = reader.ReadSingle();
ms.Seek(16, SeekOrigin.Current); // skip rotation
// Read portal records — these are the true walking adjacency.
// Each portal record: flags(2) + polygonId(2) + otherCellId(2) + otherPortalId(2) = 8 bytes
var neighbors = new List<uint>(numPortals);
for (int i = 0; i < numPortals; i++)
{
if (ms.Position + 8 > ms.Length) break;
reader.ReadUInt16(); // flags
reader.ReadUInt16(); // polygonId (portal poly key — not needed for nav)
ushort otherCellLo = reader.ReadUInt16();
reader.ReadUInt16(); // otherPortalId
// Only include EnvCells (lower word 0x0100–0xFFFD)
if (otherCellLo < 0x0100 || otherCellLo > 0xFFFD) continue;
uint nid = (landblockKey << 16) | otherCellLo;
if (nid != cellId)
neighbors.Add(nid);
}
// worldX = lbX × 192 + posX → EW = (worldX/24 − 1019.5) / 10
double ew = ((posX + gx) / 24.0 - 1019.5) / 10.0;
double ns = ((posY + gy) / 24.0 - 1019.5) / 10.0;
nodes[cellId] = new DungeonNavNode
{
CellId = cellId,
NS = ns,
EW = ew,
Z = posZ,
Neighbors = neighbors
};
}
catch { /* malformed cell — skip */ }
}
return nodes;
}
// ── Query helpers ────────────────────────────────────────────────────────
/// <summary>
/// Returns the cell ID whose centre is closest to (ns, ew, z). Returns 0 if empty.
/// For multi-level dungeons, z is the player's world Z used to prefer same-floor cells.
/// Cells within 8 world units in Z (same floor band) are preferred; falls back to 2D
/// nearest-only if the dungeon has no cells in that band (e.g. z unknown / single level).
/// </summary>
public static uint NearestCell(Dictionary<uint, DungeonNavNode> graph, double ns, double ew, float z = float.NaN)
{
const float zBand = 8f;
uint best2d = 0;
double best2dDist = double.MaxValue;
uint bestZ = 0;
double bestZDist = double.MaxValue;
bool useZ = !float.IsNaN(z);
foreach (var node in graph.Values)
{
double dNS = node.NS - ns;
double dEW = node.EW - ew;
double d = dNS * dNS + dEW * dEW;
if (d < best2dDist) { best2dDist = d; best2d = node.CellId; }
if (useZ && Math.Abs(node.Z - z) <= zBand && d < bestZDist)
{
bestZDist = d; bestZ = node.CellId;
}
}
return (useZ && bestZ != 0) ? bestZ : best2d;
}
/// <summary>
/// Nearest non-hazard cell to evacuate to when the patrol start cell is itself a hazard
/// (player standing in acid/lava). Prefers a directly-connected, walkable (non-drop) neighbor —
/// guaranteed reachable through a doorway — and only falls back to the geometrically nearest
/// safe cell anywhere when the player is surrounded (deep in a pool with no safe neighbor).
/// Returns 0 if the graph has no non-hazard cell at all.
/// </summary>
public static uint NearestSafeCell(
Dictionary<uint, DungeonNavNode> graph, uint fromCell,
IReadOnlySet<uint> hazards, float z = float.NaN)
{
if (!graph.TryGetValue(fromCell, out var from)) return 0;
// 1) Prefer a walkable non-hazard doorway neighbor (closest by distance).
uint bestNb = 0;
double bestNbDist = double.MaxValue;
foreach (uint nb in from.Neighbors)
{
if (hazards != null && hazards.Contains(nb)) continue;
if (!graph.TryGetValue(nb, out var nbNode)) continue;
if (IsDropEdge(from, nbNode)) continue;
double dN = nbNode.NS - from.NS, dE = nbNode.EW - from.EW;
double d = dN * dN + dE * dE;
if (d < bestNbDist) { bestNbDist = d; bestNb = nb; }
}
if (bestNb != 0) return bestNb;
// 2) Fall back to the geometrically nearest safe cell anywhere (same-floor preferred).
const float zBand = 8f;
uint best2d = 0; double best2dDist = double.MaxValue;
uint bestZ = 0; double bestZDist = double.MaxValue;
bool useZ = !float.IsNaN(z);
foreach (var node in graph.Values)
{
if (node.CellId == fromCell) continue;
if (hazards != null && hazards.Contains(node.CellId)) continue;
double dN = node.NS - from.NS, dE = node.EW - from.EW;
double d = dN * dN + dE * dE;
if (d < best2dDist) { best2dDist = d; best2d = node.CellId; }
if (useZ && Math.Abs(node.Z - z) <= zBand && d < bestZDist) { bestZDist = d; bestZ = node.CellId; }
}
return (useZ && bestZ != 0) ? bestZ : best2d;
}
// ── A* ───────────────────────────────────────────────────────────────────
/// <summary>
/// Finds the shortest portal-connected path from startCell to goalCell,
/// skipping any edge classified as a drop by IsDropEdge and any neighbor cell
/// in <paramref name="hazardCells"/> (lava / acid pools, etc.).
/// Returns ordered List of cell IDs, or empty if unreachable.
/// </summary>
public static List<uint> FindPath(
uint startCell, uint goalCell,
Dictionary<uint, DungeonNavNode> graph,
IReadOnlySet<uint>? hazardCells = null)
{
if (!graph.ContainsKey(startCell) || !graph.ContainsKey(goalCell))
return new List<uint>();
if (startCell == goalCell)
return new List<uint> { startCell };
var goalNode = graph[goalCell];
var gScore = new Dictionary<uint, double> { [startCell] = 0.0 };
var cameFrom = new Dictionary<uint, uint>();
var open = new PriorityQueue<uint, double>();
var closed = new HashSet<uint>();
open.Enqueue(startCell, H(graph[startCell], goalNode));
while (open.Count > 0)
{
uint current = open.Dequeue();
if (!closed.Add(current)) continue;
if (current == goalCell) return Reconstruct(cameFrom, current);
if (!graph.TryGetValue(current, out var curNode)) continue;
double gCur = gScore.GetValueOrDefault(current, double.MaxValue);
foreach (uint nbId in curNode.Neighbors)
{
if (closed.Contains(nbId)) continue;
if (!graph.TryGetValue(nbId, out var nbNode)) continue;
if (IsDropEdge(curNode, nbNode)) continue;
// Goal cell is allowed even if marked hazardous (the player asked to go there).
if (nbId != goalCell && hazardCells != null && hazardCells.Contains(nbId)) continue;
double dNS = curNode.NS - nbNode.NS;
double dEW = curNode.EW - nbNode.EW;
double tentG = gCur + Math.Sqrt(dNS * dNS + dEW * dEW);
if (tentG < gScore.GetValueOrDefault(nbId, double.MaxValue))
{
cameFrom[nbId] = current;
gScore[nbId] = tentG;
open.Enqueue(nbId, tentG + H(nbNode, goalNode));
}
}
}
return new List<uint>();
}
private static double H(DungeonNavNode a, DungeonNavNode b)
{
double dNS = a.NS - b.NS, dEW = a.EW - b.EW;
return Math.Sqrt(dNS * dNS + dEW * dEW);
}
private static List<uint> Reconstruct(Dictionary<uint, uint> cameFrom, uint goal)
{
var path = new List<uint>();
uint cur = goal;
while (true) { path.Add(cur); if (!cameFrom.TryGetValue(cur, out cur)) break; }
path.Reverse();
return path;
}
// ── Route construction ───────────────────────────────────────────────────
/// <summary>
/// Converts a cell-path into a Once-type NavRouteParser.
///
/// Waypoint sequence for path [A, B, C, D] navigating to (destNS, destEW):
/// midpoint(A,B) → midpoint(B,C) → midpoint(C,D) → (destNS, destEW)
///
/// Each midpoint approximates the portal position at the cell boundary.
/// Navigating through doorway midpoints prevents the bot from steering
/// into walls when doorways are offset from the cell-to-cell straight line.
/// </summary>
public static NavRouteParser BuildNavRoute(
List<uint> cellPath,
Dictionary<uint, DungeonNavNode> graph,
double destNS, double destEW)
{
var route = new NavRouteParser { RouteType = NavRouteType.Once };
for (int i = 0; i + 1 < cellPath.Count; i++)
{
if (!graph.TryGetValue(cellPath[i], out var a)) continue;
if (!graph.TryGetValue(cellPath[i + 1], out var b)) continue;
AddPortalWaypoints(route, a, b);
}
// Final destination — the user's exact target, not just a cell centre.
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = destNS, EW = destEW });
SimplifyRoute(route);
return route;
}
// Adds a pre-approach waypoint (30% into the transition from A) followed by the
// portal midpoint (50%). The pre-approach aligns the bot perpendicular to the
// doorway before it enters, preventing it from clipping sloped or narrow entrances.
private static void AddPortalWaypoints(NavRouteParser route, DungeonNavNode a, DungeonNavNode b)
{
double dNS = b.NS - a.NS, dEW = b.EW - a.EW;
double dZ = b.Z - a.Z;
// DungeonNavNode.Z is in raw AC units; NavPoint.Z must be in nav-format
// (raw / 240) so that RouteHeightToWorldY(navZ) = navZ * 240 = rawZ.
double navZA = a.Z / 240.0;
route.Points.Add(new NavPoint
{
Type = NavPointType.Point,
NS = a.NS + dNS * 0.3,
EW = a.EW + dEW * 0.3,
Z = navZA + (dZ / 240.0) * 0.3,
});
route.Points.Add(new NavPoint
{
Type = NavPointType.Point,
NS = a.NS + dNS * 0.5,
EW = a.EW + dEW * 0.5,
Z = navZA + (dZ / 240.0) * 0.5,
});
}
// Removes intermediate Point waypoints that lie within thresholdYards of the
// straight line through their neighbours. Runs repeatedly until stable.
// Control points (Pause/Chat/Recall/PortalNPC) are always preserved.
private static void SimplifyRoute(NavRouteParser route, double thresholdYards = 1.5)
{
bool changed = true;
while (changed)
{
changed = false;
for (int i = 1; i + 1 < route.Points.Count; i++)
{
if (route.Points[i].Type != NavPointType.Point) continue;
if (SegDistYards(route.Points[i - 1], route.Points[i + 1], route.Points[i]) < thresholdYards)
{
route.Points.RemoveAt(i--);
changed = true;
}
}
}
}
// Perpendicular distance (yards) from p to the line through a and b.
private static double SegDistYards(NavPoint a, NavPoint b, NavPoint p)
{
double acNS = b.NS - a.NS, acEW = b.EW - a.EW;
double len = Math.Sqrt(acNS * acNS + acEW * acEW);
if (len < 1e-9)
return Math.Sqrt((p.NS - a.NS) * (p.NS - a.NS) + (p.EW - a.EW) * (p.EW - a.EW)) * 240.0;
double abNS = p.NS - a.NS, abEW = p.EW - a.EW;
return Math.Abs(abNS * acEW - abEW * acNS) / len * 240.0;
}
// ── Patrol route ────────────────────────────────────────────────────────
// Safety valves: if convergence pruning collapses the graph too far (e.g. a
// linear dungeon with no cycles), fall back to the full reachable set.
private const int PatrolMinKeepNodes = 8;
private const double PatrolMinKeepFraction = 0.20;
/// <summary>
/// Returns the 2-core of the dungeon's walkable subgraph — the subset of
/// cells where every node has at least two walkable neighbours within the
/// set. Dead-end spurs of any length are stripped by repeatedly removing
/// leaf nodes (degree ≤ 1) until none remain. Only corridors that form
/// part of a cycle or connect two junctions survive, which is exactly the
/// "main route" a patrol bot should follow.
///
/// Falls back to the full reachable set if the pruned graph would be too
/// small to be useful (small or purely linear dungeons).
/// </summary>
private static HashSet<uint> GetMainRouteNodes(
Dictionary<uint, DungeonNavNode> graph, uint startCell,
IReadOnlySet<uint>? hazardCells = null)
{
// BFS to collect all cells reachable from startCell without drops or hazards.
// The start cell is always kept (player is already standing there) even if
// it's somehow marked hazardous — we can't refuse to start the patrol.
var reachable = new HashSet<uint>();
var queue = new Queue<uint>();
if (graph.ContainsKey(startCell))
{
queue.Enqueue(startCell);
reachable.Add(startCell);
while (queue.Count > 0)
{
uint cur = queue.Dequeue();
if (!graph.TryGetValue(cur, out var node)) continue;
foreach (uint nb in node.Neighbors)
{
if (reachable.Contains(nb)) continue;
if (!graph.ContainsKey(nb)) continue;
if (IsDropEdge(node, graph[nb])) continue;
if (hazardCells != null && hazardCells.Contains(nb)) continue;
reachable.Add(nb);
queue.Enqueue(nb);
}
}
}
int originalCount = reachable.Count;
var pruned = new HashSet<uint>(reachable);
// Prune to convergence: repeatedly remove every node whose effective
// degree within `pruned` is ≤ 1. Each pass peels one cell from every
// branch tip; iterating until no changes remain strips dead-end spurs
// of any depth, leaving only the 2-core (cycles + through-corridors).
while (true)
{
var toRemove = new List<uint>();
foreach (uint id in pruned)
{
if (id == startCell) continue; // always keep spawn cell
if (!graph.TryGetValue(id, out var node)) continue;
int deg = 0;
foreach (uint nb in node.Neighbors)
{
if (pruned.Contains(nb) && graph.ContainsKey(nb) &&
!IsDropEdge(node, graph[nb]))
{
deg++;
if (deg > 1) break;
}
}
if (deg <= 1) toRemove.Add(id);
}
if (toRemove.Count == 0) break;
foreach (uint id in toRemove) pruned.Remove(id);
}
// Fall back to full reachable set if pruning collapsed the graph.
if (pruned.Count < PatrolMinKeepNodes ||
pruned.Count < originalCount * PatrolMinKeepFraction)
return reachable;
return pruned;
}
/// <summary>
/// Generates a Circular patrol route over the dungeon's main route (the cells from
/// <see cref="GetMainRouteNodes"/>).
///
/// Uses a route-inspection (Chinese-postman-style) closed walk rather than a DFS tree
/// traversal: it covers every corridor once and — crucially — TAKES loop-closing edges,
/// so a cycle is walked once and the bot continues forward instead of running to the end
/// of a loop and backtracking the way it came. Only true dead-ends and bridges are
/// re-tread (the unavoidable in-and-out), via the shortest reconnecting path. The walk is
/// closed back to the start so the Circular route returns home.
/// </summary>
public static NavRouteParser BuildPatrolRoute(
Dictionary<uint, DungeonNavNode> graph,
uint startCell,
IReadOnlySet<uint>? hazardCells = null)
{
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells);
// Undirected walkable subgraph over mainRoute (portal-adjacent, non-drop). mainRoute is
// already hazard-filtered, so membership there implies non-hazard.
var adj = new Dictionary<uint, List<uint>>();
var edges = new HashSet<ulong>();
foreach (uint c in mainRoute)
{
if (!graph.TryGetValue(c, out var cn)) continue;
foreach (uint nb in cn.Neighbors)
{
if (!mainRoute.Contains(nb) || !graph.TryGetValue(nb, out var nbn)) continue;
if (IsDropEdge(cn, nbn)) continue;
if (!adj.TryGetValue(c, out var list)) { list = new List<uint>(); adj[c] = list; }
list.Add(nb);
edges.Add(EdgeKey(c, nb));
}
}
var route = new NavRouteParser { RouteType = NavRouteType.Circular };
// Euler start: the player's cell if it borders a corridor, else the nearest cell that does.
uint walkStart = (adj.TryGetValue(startCell, out var sList) && sList.Count > 0)
? startCell
: NearestCellWithEdges(graph, adj, startCell);
if (walkStart == 0 || edges.Count == 0)
{
SimplifyRoute(route);
return route; // nothing walkable — caller's empty-route guard handles it
}
// Greedy edge-covering closed walk.
var walk = new List<uint> { walkStart };
var remaining = new HashSet<ulong>(edges);
uint cur = walkStart;
// Hard bound: every edge is consumed once and each exhausted vertex triggers at most one
// reconnection (which is itself followed by an edge consumption), so this can't spin forever.
int guard = edges.Count * 4 + mainRoute.Count + 16;
while (remaining.Count > 0 && guard-- > 0)
{
uint next = 0; bool found = false;
if (adj.TryGetValue(cur, out var nbrs))
{
foreach (uint nb in nbrs)
if (remaining.Contains(EdgeKey(cur, nb))) { next = nb; found = true; break; }
}
if (found)
{
remaining.Remove(EdgeKey(cur, next));
walk.Add(next);
cur = next;
}
else
{
// Out of fresh corridors here — hop (shortest path) to the nearest cell that still
// has one. These re-tread edges are the unavoidable dead-end/bridge repeats.
var path = BfsToUnusedEdge(adj, cur, remaining);
if (path == null) break; // remaining edges unreachable (disconnected) — stop
for (int i = 1; i < path.Count; i++) walk.Add(path[i]);
cur = path[path.Count - 1];
}
}
// Close the loop back to the start so the Circular route returns home.
if (cur != walkStart)
{
var back = BfsPath(adj, cur, walkStart);
if (back != null) for (int i = 1; i < back.Count; i++) walk.Add(back[i]);
}
for (int i = 0; i + 1 < walk.Count; i++)
{
if (!graph.TryGetValue(walk[i], out var a)) continue;
if (!graph.TryGetValue(walk[i + 1], out var b)) continue;
AddPortalWaypoints(route, a, b);
}
SimplifyRoute(route);
return route;
}
// Canonical undirected-edge key (order-independent).
private static ulong EdgeKey(uint a, uint b)
=> a < b ? ((ulong)a << 32) | b : ((ulong)b << 32) | a;
// Nearest subgraph cell that has at least one corridor edge (for an Euler start when the player
// stands on an edge-less cell, e.g. a stripped spur). 0 if the subgraph has no edges.
private static uint NearestCellWithEdges(
Dictionary<uint, DungeonNavNode> graph, Dictionary<uint, List<uint>> adj, uint fromCell)
{
if (!graph.TryGetValue(fromCell, out var from))
{
foreach (var kv in adj) if (kv.Value.Count > 0) return kv.Key;
return 0;
}
uint best = 0; double bestD = double.MaxValue;
foreach (var kv in adj)
{
if (kv.Value.Count == 0) continue;
if (!graph.TryGetValue(kv.Key, out var n)) continue;
double dN = n.NS - from.NS, dE = n.EW - from.EW;
double d = dN * dN + dE * dE;
if (d < bestD) { bestD = d; best = kv.Key; }
}
return best;
}
// Shortest hop-path src→dst over the subgraph (inclusive endpoints), or null if unreachable.
private static List<uint>? BfsPath(Dictionary<uint, List<uint>> adj, uint src, uint dst)
{
if (src == dst) return new List<uint> { src };
var prev = new Dictionary<uint, uint>();
var seen = new HashSet<uint> { src };
var q = new Queue<uint>();
q.Enqueue(src);
while (q.Count > 0)
{
uint c = q.Dequeue();
if (!adj.TryGetValue(c, out var ns)) continue;
foreach (uint nb in ns)
{
if (!seen.Add(nb)) continue;
prev[nb] = c;
if (nb == dst) return RebuildPath(prev, src, dst);
q.Enqueue(nb);
}
}
return null;
}
// Shortest hop-path from src to the nearest cell that still has an unused edge, or null.
private static List<uint>? BfsToUnusedEdge(
Dictionary<uint, List<uint>> adj, uint src, HashSet<ulong> remaining)
{
var prev = new Dictionary<uint, uint>();
var seen = new HashSet<uint> { src };
var q = new Queue<uint>();
q.Enqueue(src);
while (q.Count > 0)
{
uint c = q.Dequeue();
if (c != src && HasUnusedEdge(adj, c, remaining))
return RebuildPath(prev, src, c);
if (!adj.TryGetValue(c, out var ns)) continue;
foreach (uint nb in ns)
{
if (!seen.Add(nb)) continue;
prev[nb] = c;
q.Enqueue(nb);
}
}
return null;
}
private static bool HasUnusedEdge(Dictionary<uint, List<uint>> adj, uint cell, HashSet<ulong> remaining)
{
if (!adj.TryGetValue(cell, out var ns)) return false;
foreach (uint nb in ns) if (remaining.Contains(EdgeKey(cell, nb))) return true;
return false;
}
private static List<uint> RebuildPath(Dictionary<uint, uint> prev, uint src, uint dst)
{
var path = new List<uint> { dst };
uint c = dst;
while (c != src && prev.TryGetValue(c, out uint p)) { path.Add(p); c = p; }
path.Reverse();
return path;
}
// ── Convenience entry point ──────────────────────────────────────────────
/// <summary>
/// One-shot: build graph, A* from player to dest, return a ready-to-run NavRouteParser.
/// Returns null if graph is empty, player/dest cell not found, or no path exists.
/// </summary>
public static NavRouteParser? NavigateTo(
uint landblockKey, DatDatabase cellDat,
double playerNS, double playerEW, float playerZ,
double destNS, double destEW,
out int nodeCount, out int pathLength,
IReadOnlySet<uint>? hazardCells = null)
{
nodeCount = 0;
pathLength = 0;
var graph = GetGraph(landblockKey, cellDat);
nodeCount = graph.Count;
if (nodeCount == 0) return null;
// Use player Z for both start and goal — assumes destination is on the same floor.
uint startCell = NearestCell(graph, playerNS, playerEW, playerZ);
uint goalCell = NearestCell(graph, destNS, destEW, playerZ);
if (startCell == 0 || goalCell == 0) return null;
// IsDropEdge filters out jumps — AC requires a jump to initiate a drop
// and the navigation engine has no jump primitive yet.
// If the destination is only reachable via a drop this returns null.
var path = FindPath(startCell, goalCell, graph, hazardCells);
pathLength = path.Count;
if (pathLength == 0) return null;
return BuildNavRoute(path, graph, destNS, destEW);
}
}

View file

@ -0,0 +1,3 @@
// Expose shared SDK types project-wide so files that reference AcObjectClass,
// AcSkillType, LootAction etc. don't each need their own using directive.
global using RynthCore.Loot;

View file

@ -0,0 +1,231 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// UtilityBelt-compatible jumper. Mirrors UB Jumper.cs flag flow:
/// isTurning → needToJump → waitingForJump. Letters in the command name
/// pick held motions (w=fwd, x=back, z=strafeL, c=strafeR, s=run modifier),
/// optional heading faces first, msToHoldDown is the jump power (0-1000).
/// </summary>
internal sealed class Jumper
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly Action<string> _chat;
private bool _isTurning;
private bool _needToJump;
private bool _charging;
private bool _waitingForJump;
private bool _addW, _addX, _addZ, _addC, _addShift;
private int _msToHoldDown;
private float _targetHeading;
private DateTime _turningStartedAt;
private DateTime _chargeStartedAt;
private DateTime _jumpStartedAt;
private TimeSpan _enableNavTimer;
private bool _pausedNav;
private bool _prevEnableNavigation;
public bool IsBusy => _isTurning || _needToJump || _charging || _waitingForJump;
public Jumper(RynthCoreHost host, LegacyUiSettings settings, Action<string> chat)
{
_host = host;
_settings = settings;
_chat = chat;
}
public bool Start(string directionLetters, float? faceHeading, int msToHoldDown)
{
if (IsBusy)
{
_chat("[RynthAi] You are already jumping. Try again later.");
return false;
}
if (msToHoldDown < 0 || msToHoldDown > 1000)
{
_chat("[RynthAi] holdtime should be 0-1000 (ms).");
return false;
}
_msToHoldDown = msToHoldDown;
_addW = directionLetters.Contains('w');
_addX = directionLetters.Contains('x');
_addZ = directionLetters.Contains('z');
_addC = directionLetters.Contains('c');
_addShift = directionLetters.Contains('s');
bool needToTurn = faceHeading.HasValue;
if (needToTurn)
{
float h = faceHeading!.Value;
if (h < 0 || h >= 360)
{
_chat("[RynthAi] heading should be 0-359.");
return false;
}
_targetHeading = h;
}
else
{
_targetHeading = _host.TryGetPlayerHeading(out float curr) ? curr : 0f;
}
PauseNav();
_needToJump = true;
_isTurning = needToTurn;
if (_isTurning)
{
_turningStartedAt = DateTime.UtcNow;
if (_host.HasTurnToHeading)
_host.TurnToHeading(_targetHeading);
_host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
}
else
{
_host.Log($"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms");
}
return true;
}
public void Cancel()
{
RestoreNav();
_isTurning = _needToJump = _charging = _waitingForJump = false;
_addW = _addX = _addZ = _addC = _addShift = false;
}
public void Tick()
{
if (!IsBusy) return;
try
{
// TurnToHeading is an instant quaternion snap; the heading read
// doesn't always reflect it immediately, so just wait a short
// settle window rather than polling for a match.
if (_isTurning && DateTime.UtcNow - _turningStartedAt >= TimeSpan.FromMilliseconds(150))
{
_isTurning = false;
if (_host.TryGetPlayerHeading(out float current))
_host.Log($"[Jumper] Turn done heading={current:F1}");
}
if (_needToJump && !_isTurning)
{
_needToJump = false;
_enableNavTimer = TimeSpan.FromMilliseconds(_msToHoldDown + 2000);
BeginJump();
}
if (_charging && DateTime.UtcNow - _chargeStartedAt >= TimeSpan.FromMilliseconds(_msToHoldDown))
{
_charging = false;
ReleaseJump();
_waitingForJump = true;
_jumpStartedAt = DateTime.UtcNow;
}
if (_waitingForJump && DateTime.UtcNow - _jumpStartedAt >= _enableNavTimer)
{
RestoreNav();
_waitingForJump = false;
_addW = _addX = _addZ = _addC = _addShift = false;
_host.Log("[Jumper] Settle complete -> idle");
}
}
catch (Exception ex)
{
_host.Log($"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}");
Cancel();
}
}
private void BeginJump()
{
// Start the spacebar-down phase. The power bar charges while held.
// Release is handled in Tick() after _msToHoldDown ms via ReleaseJump(),
// which writes the motion vector directly into CMotionInterp right
// before DoJump — mirrors UB's UBHelper.Jumper. We deliberately do NOT
// SetMotion here, because SetMotion would start walking the character
// *before* the jump, and the velocity wouldn't be baked into the
// physics sim at DoJump time anyway.
bool started;
if (_host.HasCommenceJump)
{
started = _host.CommenceJump();
_charging = started;
_chargeStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
{
started = _host.HasTapJump && _host.TapJump();
_waitingForJump = started;
_jumpStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] TapJump fallback ok={started} " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
if (!started)
{
// Deep-audit finding #7 (2026-06-18): a rejected jump (both hook
// paths unavailable/failed) left every flag false -> IsBusy false
// on the very next Tick(), but PauseNav() from Start() was never
// undone. Nav stayed force-disabled for the rest of the session —
// a real "bot just stands there" cause with no error visible to
// the user beyond this one chat line. Restore nav on the spot.
_chat("[RynthAi] Jump hooks unavailable.");
RestoreNav();
}
}
private void ReleaseJump()
{
// Prefer LaunchJumpWithMotion — writes velocity into CMotionInterp,
// calls DoJump(1), clears motion. Falls back to plain DoJump only if
// the engine is older than v52.
bool released;
if (_host.HasLaunchJumpWithMotion)
{
released = _host.LaunchJumpWithMotion(_addShift, _addW, _addX, _addZ, _addC);
_host.Log($"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
{
released = _host.HasDoJump && _host.DoJump(true);
_host.Log($"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms");
}
}
private void PauseNav()
{
_prevEnableNavigation = _settings.EnableNavigation;
if (_settings.EnableNavigation)
{
_settings.EnableNavigation = false;
_pausedNav = true;
}
}
private void RestoreNav()
{
if (_pausedNav)
{
_settings.EnableNavigation = _prevEnableNavigation;
_pausedNav = false;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,184 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyLuaUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
// Delegates for the main plugin to hook into
public Action? OnSettingsChanged;
public Action<string>? OnExecuteRequested;
public Action? OnStopRequested;
// Internal State
private readonly string _luaFolder = @"C:\Games\RynthSuite\RynthAi\LuaScripts";
private string _newLuaFileName = "MyScript";
private int _selectedLuaIdx = 0;
private readonly List<string> _luaFiles = new();
private readonly string _selectedSnippetKey = "--- Select Snippet ---";
private readonly Dictionary<string, string> _luaSnippets = new()
{
{ "--- Select Snippet ---", "" },
{ "📍 Move to Coord", "RynthAi:GoTo(\"0.0N\", \"0.0E\")" },
{ "🌀 Use Portal/NPC", "RynthAi:UsePortal(\"Portal Name\")" },
{ "📏 Get Distance", "local dist = RynthAi:GetDistance(\"Object Name\")\nprint(\"Distance: \" .. dist)" },
{ "🛑 Emergency Stop", "RynthAi:Stop()" }
};
public LegacyLuaUi(LegacyUiSettings settings, RynthCoreHost host)
{
_settings = settings;
_host = host;
RefreshLuaFiles();
}
public void RefreshLuaFiles()
{
_luaFiles.Clear();
_luaFiles.Add("None");
if (Directory.Exists(_luaFolder))
{
foreach (string file in Directory.GetFiles(_luaFolder, "*.lua"))
_luaFiles.Add(Path.GetFileNameWithoutExtension(file));
}
}
public void Render()
{
if (!DashWindows.ShowLua)
return;
ImGui.SetNextWindowSize(new Vector2(600, 500), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Lua Scripts##RynthAiLua", ref DashWindows.ShowLua))
{
ImGui.End();
return;
}
// Safety Checks
_settings.LuaScript ??= "";
_settings.LuaConsoleOutput ??= "";
// 1. File & Snippet Bar
RenderTopBar();
ImGui.Separator();
// 2. Toolbar (Run, Stop, Clear)
RenderToolbar();
ImGui.Separator();
// 3. Editor & Console
RenderEditorAndConsole();
ImGui.End();
}
private void RenderTopBar()
{
ImGui.SetNextItemWidth(120);
string preview = (_selectedLuaIdx < _luaFiles.Count) ? _luaFiles[_selectedLuaIdx] : "None";
if (ImGui.BeginCombo("##LoadLua", preview))
{
for (int i = 0; i < _luaFiles.Count; i++)
{
if (ImGui.Selectable(_luaFiles[i], _selectedLuaIdx == i))
{
_selectedLuaIdx = i;
if (_luaFiles[i] != "None")
{
string path = Path.Combine(_luaFolder, _luaFiles[i] + ".lua");
if (File.Exists(path))
{
_settings.LuaScript = File.ReadAllText(path);
OnSettingsChanged?.Invoke();
}
}
}
}
ImGui.EndCombo();
}
ImGui.SameLine();
if (ImGui.Button("🔄")) RefreshLuaFiles();
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
ImGui.InputText("##SaveAs", ref _newLuaFileName, 64);
ImGui.SameLine();
if (ImGui.Button("💾"))
{
if (!Directory.Exists(_luaFolder)) Directory.CreateDirectory(_luaFolder);
File.WriteAllText(Path.Combine(_luaFolder, _newLuaFileName + ".lua"), _settings.LuaScript);
_host.Log($"Saved Lua script: {_newLuaFileName}.lua");
RefreshLuaFiles();
}
ImGui.SameLine();
RenderSnippets();
}
private void RenderSnippets()
{
ImGui.SetNextItemWidth(150);
if (ImGui.BeginCombo("##Snippets", _selectedSnippetKey))
{
foreach (var s in _luaSnippets)
{
if (ImGui.Selectable(s.Key))
{
if (!string.IsNullOrEmpty(_settings.LuaScript) && !_settings.LuaScript.EndsWith('\n'))
_settings.LuaScript += "\n";
_settings.LuaScript += s.Value;
OnSettingsChanged?.Invoke();
}
}
ImGui.EndCombo();
}
}
private void RenderToolbar()
{
if (ImGui.Button("▶ Run Script")) OnExecuteRequested?.Invoke(_settings.LuaScript);
ImGui.SameLine();
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.7f, 0.1f, 0.1f, 1.0f));
if (ImGui.Button("🛑 Stop")) OnStopRequested?.Invoke();
ImGui.PopStyleColor();
ImGui.SameLine();
if (ImGui.Button("🧹 Clear Console"))
{
_settings.LuaConsoleOutput = "--- Console Cleared ---";
OnSettingsChanged?.Invoke();
}
}
private void RenderEditorAndConsole()
{
float editorH = ImGui.GetContentRegionAvail().Y - 150;
ImGui.InputTextMultiline("##LuaEditor", ref _settings.LuaScript, 50000, new Vector2(-1, editorH), ImGuiInputTextFlags.AllowTabInput);
ImGui.TextDisabled("Console Output:");
if (ImGui.BeginChild("LuaConsole", new Vector2(-1, 0), ImGuiChildFlags.Borders, ImGuiWindowFlags.HorizontalScrollbar))
{
ImGui.TextUnformatted(_settings.LuaConsoleOutput);
if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY())
ImGui.SetScrollHereY(1.0f);
}
ImGui.EndChild();
}
}

View file

@ -0,0 +1,675 @@
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyAdvancedSettingsUi
{
private readonly LegacyUiSettings _settings;
private MissileCraftingManager? _missileCraftingManager;
// Scratch buffer for the "never attack" name entry box.
private string _newBlacklistName = "";
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
private static readonly string[] MovementModes = { "Legacy (Autorun)", "Tier 1 (CM_Movement)", "Tier 2 (MoveToPosition)" };
public LegacyAdvancedSettingsUi(LegacyUiSettings settings)
{
_settings = settings;
}
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr;
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
public void Render()
{
if (!_settings.ShowAdvancedWindow)
return;
ImGui.SetNextWindowSize(new Vector2(600, 400), ImGuiCond.FirstUseEver);
if (ImGui.Begin("RynthAi Advanced Settings", ref _settings.ShowAdvancedWindow))
{
ImGui.BeginChild("AdvancedSidebar", new Vector2(150, 0), ImGuiChildFlags.Borders);
for (int i = 0; i < _settings.AdvancedTabs.Length; i++)
{
if (ImGui.Selectable(_settings.AdvancedTabs[i], _settings.SelectedAdvancedTab == i))
_settings.SelectedAdvancedTab = i;
}
ImGui.EndChild();
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.BeginChild("AdvancedContent", new Vector2(0, -ImGui.GetFrameHeightWithSpacing()), ImGuiChildFlags.Borders);
RenderTabContent(_settings.SelectedAdvancedTab);
ImGui.EndChild();
if (ImGui.Button("Close"))
_settings.ShowAdvancedWindow = false;
ImGui.EndGroup();
}
ImGui.End();
}
private void RenderTabContent(int tabIndex)
{
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
return;
string tabName = _settings.AdvancedTabs[tabIndex];
ImGui.TextColored(new Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}");
ImGui.Separator();
ImGui.Spacing();
switch (tabName)
{
case "Display":
ImGui.Checkbox("Show Target Stamina / Mana", ref _settings.ShowTargetStaminaMana);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When enabled, displays stamina and mana bars\nfor the selected target (requires appraisal data).");
break;
case "UI":
ImGui.Text("Radar");
ImGui.Separator();
ImGui.Checkbox("Get Rid of Retail Radar", ref _settings.SuppressRetailRadar);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Suppress the game's built-in radar (bezel, compass, coords, blips).");
ImGui.Checkbox("Show RynthRadar", ref _settings.ShowRynthRadar);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Render the custom square radar widget (indoor walls + dot markers, works outdoors).");
ImGui.Checkbox("Radar Click-Through", ref _settings.RadarClickThrough);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mouse events over the radar pass through to the game instead of the widget.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Chat");
ImGui.Checkbox("Show RynthChat", ref _settings.ShowRynthChat);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Render the custom chat viewer (scrollback + channel coloring).");
ImGui.Checkbox("Chat Click-Through", ref _settings.ChatClickThrough);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mouse events over the chat pass through to the game. The gear button stays clickable.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Power Bar");
ImGui.Checkbox("Get Rid of Retail Power Bar", ref _settings.SuppressRetailPowerbar);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden.");
break;
case "Misc":
if (ImGui.Checkbox("Enable FPS Limit", ref _settings.EnableFPSLimit)) { }
if (_settings.EnableFPSLimit)
{
ImGui.Indent();
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Focused FPS", ref _settings.TargetFPSFocused, 10, 240);
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Background FPS", ref _settings.TargetFPSBackground, 5, 60);
ImGui.Unindent();
}
ImGui.Separator();
ImGui.Spacing();
ImGui.Checkbox("Auto Cram", ref _settings.EnableAutocram);
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.");
}
ImGui.Spacing();
ImGui.Checkbox("Peace Mode When Idle", ref _settings.PeaceModeWhenIdle);
ImGui.Checkbox("Start Macro On Login", ref _settings.StartMacroOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts the macro when RynthAi loads.");
ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Missile Arc Velocities (m/s)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Per-weapon projectile speed used for line-of-sight arc checks.\nLower velocity = higher arc. Tune until LoS matches in-game hits.\nDungeons always use linear checks to avoid false ceiling blocks.");
ImGui.Checkbox("Use Arcs for Missile LoS", ref _settings.UseArcs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When off, all missile LoS checks are linear (eye-to-eye).");
if (_settings.UseArcs)
{
ImGui.Indent();
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Bow", ref _settings.BowArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Crossbow", ref _settings.CrossbowArcVelocity, 10.0f, 80.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Atlatl", ref _settings.AtlatlArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.Unindent();
}
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Monster Blacklist");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Casts Before Blacklist", ref _settings.BlacklistAttempts, 1, 20);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How many offensive casts that deal NO damage (each judged after the settle window) before a mob is blacklisted.");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Blacklist Timeout (sec)", ref _settings.BlacklistTimeoutSec, 5, 120);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How long a blacklisted mob is ignored before re-trying.");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Cast Settle (ms)", ref _settings.BlacklistCastSettleMs, 250, 15000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Grace after a cast before it counts as a no-damage miss — lets the damage/health packet arrive so good targets aren't blacklisted prematurely.");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("No Progress Timeout (sec)", ref _settings.TargetNoProgressTimeoutSec, 0, 300);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Blacklist a target after being engaged this many seconds without dealing damage.\n" +
"0 = disabled. Default 60s. Useful for targets stuck in geometry or unreachable.");
ImGui.Spacing();
ImGui.Text("Never Attack (by name)");
ImGui.SetNextItemWidth(220);
bool addByEnter = ImGui.InputTextWithHint("##blacklistName", "Monster name (e.g. Drudge)",
ref _newBlacklistName, 64, ImGuiInputTextFlags.EnterReturnsTrue);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Monsters whose name CONTAINS this text (case-insensitive) are never\n" +
"targeted, faced, or attacked. This manual do-not-attack list is\n" +
"separate from the automatic no-damage blacklist above.");
ImGui.SameLine();
if ((ImGui.Button("Add##blacklist") || addByEnter) && !string.IsNullOrWhiteSpace(_newBlacklistName))
{
string entry = _newBlacklistName.Trim();
bool exists = false;
for (int i = 0; i < _settings.MonsterNameBlacklist.Count; i++)
if (string.Equals(_settings.MonsterNameBlacklist[i], entry, StringComparison.OrdinalIgnoreCase))
{ exists = true; break; }
if (!exists) _settings.MonsterNameBlacklist.Add(entry);
_newBlacklistName = "";
}
if (_settings.MonsterNameBlacklist.Count == 0)
{
ImGui.TextDisabled("(empty — any monster may be attacked)");
}
else
{
int removeIdx = -1;
for (int i = 0; i < _settings.MonsterNameBlacklist.Count; i++)
{
ImGui.PushID(i);
if (ImGui.SmallButton("X")) removeIdx = i;
ImGui.SameLine();
ImGui.TextUnformatted(_settings.MonsterNameBlacklist[i]);
ImGui.PopID();
}
if (removeIdx >= 0) _settings.MonsterNameBlacklist.RemoveAt(removeIdx);
}
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Give Queue");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 50, 2000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minimum delay between each item sent by /ra givea commands.\nLower = faster but may drop items if the server can't keep up.");
break;
case "Recharge":
ImGui.Text("Self Vitals (%)");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100);
ImGui.Spacing();
ImGui.Text("Top-Off Vitals (%)");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Top HP", ref _settings.TopOffHP, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Top Stam", ref _settings.TopOffStam, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Top Mana", ref _settings.TopOffMana, 0, 100);
ImGui.Spacing();
ImGui.Text("Helper Settings (%)");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Heal Others", ref _settings.HealOthersAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam Others", ref _settings.RestamOthersAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Infuse Others", ref _settings.InfuseOthersAt, 0, 100);
break;
case "Melee Combat":
ImGui.Text("Attack Power & Height");
ImGui.Separator();
ImGui.Checkbox("Use Recklessness", ref _settings.UseRecklessness);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When enabled and Recklessness is trained, auto power uses 80% instead of 100%.");
ImGui.Spacing();
bool meleeAuto = _settings.MeleeAttackPower < 0;
if (ImGui.Checkbox("Melee Auto Power", ref meleeAuto))
_settings.MeleeAttackPower = meleeAuto ? -1 : 100;
ImGui.Indent();
ImGui.SetNextItemWidth(150);
if (meleeAuto)
{
int displayVal = 100;
ImGui.BeginDisabled();
ImGui.SliderInt("Melee Power %", ref displayVal, 0, 100);
ImGui.EndDisabled();
}
else
{
ImGui.SliderInt("Melee Power %", ref _settings.MeleeAttackPower, 0, 100);
}
ImGui.Unindent();
ImGui.SetNextItemWidth(120);
ImGui.Combo("Melee Attack Height", ref _settings.MeleeAttackHeight, AttackHeights, AttackHeights.Length);
ImGui.Spacing();
bool missileAuto = _settings.MissileAttackPower < 0;
if (ImGui.Checkbox("Missile Auto Power", ref missileAuto))
_settings.MissileAttackPower = missileAuto ? -1 : 100;
ImGui.Indent();
ImGui.SetNextItemWidth(150);
if (missileAuto)
{
int displayVal = 100;
ImGui.BeginDisabled();
ImGui.SliderInt("Missile Power %", ref displayVal, 0, 100);
ImGui.EndDisabled();
}
else
{
ImGui.SliderInt("Missile Power %", ref _settings.MissileAttackPower, 0, 100);
}
ImGui.Unindent();
ImGui.SetNextItemWidth(120);
ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length);
ImGui.Separator();
ImGui.Spacing();
ImGui.Checkbox("Use Native Attack", ref _settings.UseNativeAttack);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows).");
ImGui.Spacing();
ImGui.Checkbox("Summon Pets", ref _settings.SummonPets);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Pet Min Monsters", ref _settings.PetMinMonsters);
break;
case "Spell Combat":
ImGui.Text("War/Void Casting Settings");
ImGui.Separator();
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Spell Interval (ms)", ref _settings.SpellCastIntervalMs, 100, 1500);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Delay between BUFF / utility spell casts (not combat).\n" +
"Lower = faster buff chains. 400ms is a good balance.\n" +
"Below 200ms may cause fizzles or dropped casts on laggy servers.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 250, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Delay between offensive (war/void) COMBAT casts only.\n" +
"Spacing casts ~1-2s (1500ms default) stops back-to-back\n" +
"\"You're too busy!\" refusals that drop casts and cost kills.\n" +
"Does NOT affect buffing speed.");
ImGui.Spacing();
ImGui.Checkbox("Cast Dispel Self", ref _settings.CastDispelSelf);
ImGui.Spacing();
ImGui.Text("Ring Spell Override");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Min Ring Targets", ref _settings.MinRingTargets);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Spell Difficulty (Min Buffed Skill)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minimum buffed skill level required to cast each spell tier.\nRaise these above AC's hard minimums (1/50/100/150/200/250/300/350) to avoid fizzles.");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 1", ref _settings.MinSkillLevelTier1);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 2", ref _settings.MinSkillLevelTier2);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 3", ref _settings.MinSkillLevelTier3);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 4", ref _settings.MinSkillLevelTier4);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 5", ref _settings.MinSkillLevelTier5);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 6", ref _settings.MinSkillLevelTier6);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 7", ref _settings.MinSkillLevelTier7);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 8", ref _settings.MinSkillLevelTier8);
break;
case "Ranges":
ImGui.Text("Standard Ranges (Yards)");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Monster Range", ref _settings.MonsterRange);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Disengage Range", ref _settings.MonsterDisengageRange);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3).");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Ring Range", ref _settings.RingRange);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Approach Range", ref _settings.ApproachRange);
ImGui.Spacing();
ImGui.Text("Corpse Acquisition (Yards)");
ImGui.Separator();
ImGui.SetNextItemWidth(180);
ImGui.InputDouble("Corpse Max (yd)", ref _settings.CorpseApproachRangeMax, 0.5, 1.0, "%.1f");
ImGui.SetNextItemWidth(180);
ImGui.InputDouble("Corpse Min (yd)", ref _settings.CorpseApproachRangeMin, 0.5, 1.0, "%.1f");
break;
case "Navigation":
ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority);
ImGui.SetNextItemWidth(120);
ImGui.InputFloat("Follow/Nav Min", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Arrival distance in yards. Also sets the nav marker ring radius.");
ImGui.Spacing();
ImGui.Text("Nav Marker Display");
ImGui.SetNextItemWidth(120);
ImGui.SliderFloat("Ring Thickness", ref _settings.NavRingThickness, 1.0f, 16.0f, "%.0f");
ImGui.SetNextItemWidth(120);
ImGui.SliderFloat("Line Thickness", ref _settings.NavLineThickness, 1.0f, 16.0f, "%.0f");
ImGui.SetNextItemWidth(120);
ImGui.SliderFloat("Height Offset", ref _settings.NavHeightOffset, -5.0f, 5.0f, "%.2f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Vertical offset for nav markers above the ground. Negative = lower.");
ImGui.SetNextItemWidth(120);
ImGui.SliderFloat("Slope Sink", ref _settings.NavSlopeSink, 0.0f, 8.0f, "%.2f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Extra downward offset on slopes only. 0 = off; flat ground unaffected.");
ImGui.Checkbox("Show Terrain Passability", ref _settings.ShowTerrainPassability);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Highlight impassable terrain triangles in red.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Doors");
ImGui.Checkbox("Open Doors While Navigating", ref _settings.OpenDoors);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically open doors encountered during navigation.");
if (_settings.OpenDoors)
{
ImGui.SetNextItemWidth(180);
ImGui.SliderFloat("Door Detection Range (yd)", ref _settings.OpenDoorRange, 0.1f, 70.0f, "%.1f");
ImGui.Checkbox("Auto-Unlock Doors", ref _settings.AutoUnlockDoors);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If a door is locked, try to use a lockpick from your Consumable Items list.");
}
ImGui.Spacing();
ImGui.Text("Movement Engine");
ImGui.SetNextItemWidth(200);
ImGui.Combo("Mode", ref _settings.MovementMode, MovementModes, MovementModes.Length);
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip(
"Legacy: SetAutorun + smooth heading servo (TurnToHeading)\n" +
"Tier 1: SetAutorun + CM_Movement turn commands (DoMovement)\n" +
"Tier 2: Client physics MoveToPosition (not built yet — falls back to Legacy)");
}
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Steering");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Stop & Turn Angle", ref _settings.NavStopTurnAngle, 1f, 5f, "%.0f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Stop forward motion and turn in place when heading error exceeds this.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Resume Run Angle", ref _settings.NavResumeTurnAngle, 1f, 5f, "%.0f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Resume running once the turn-in-place error drops below this.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Dead Zone", ref _settings.NavDeadZone, 0.5f, 1f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Ignore heading corrections smaller than this.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Sweep Detect Mult", ref _settings.NavSweepMult, 0.5f, 1f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Closest-approach detection radius multiplier.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Lookahead (yd)", ref _settings.NavLookaheadYards, 0.5f, 1f, "%.1f");
if (_settings.NavLookaheadYards < 0f) _settings.NavLookaheadYards = 0f;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mode 0 (heading servo) max turn speed. Higher = snappier turns, lower = gentler. Ignored by Tier 1 / Tier 2.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Tier1 Turn Speed", ref _settings.NavTier1TurnSpeed, 0.1f, 0.5f, "%.2f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Tier 1 (CM_Movement) DoMovement turn-command speed. Only used when Movement Engine = Tier 1.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Post-Portal Delay (s)", ref _settings.PostPortalDelaySec, 0.25f, 1f, "%.2f");
if (_settings.PostPortalDelaySec < 0f) _settings.PostPortalDelaySec = 0f;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Seconds to settle after any portal/recall teleport before nav resumes.");
if (_settings.MovementMode == 2)
{
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Tier 2 Tuning");
ImGui.SetNextItemWidth(100);
ImGui.InputFloat("Speed##t2", ref _settings.T2Speed, 0.1f, 0.5f, "%.1f");
ImGui.SetNextItemWidth(100);
ImGui.InputFloat("Walk Within (yd)", ref _settings.T2WalkWithinYd, 1f, 5f, "%.0f");
ImGui.SetNextItemWidth(100);
ImGui.InputFloat("Stop Distance (yd)", ref _settings.T2DistanceTo, 0.1f, 0.5f, "%.1f");
ImGui.SetNextItemWidth(100);
ImGui.InputFloat("Reissue Timeout (ms)", ref _settings.T2ReissueMs, 100f, 500f, "%.0f");
ImGui.SetNextItemWidth(100);
ImGui.InputFloat("Max Range (yd)", ref _settings.T2MaxRangeYd, 50f, 100f, "%.0f");
ImGui.SetNextItemWidth(100);
ImGui.InputInt("Max Landblock Dist", ref _settings.T2MaxLandblocks, 1);
}
break;
case "Buffing":
ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing);
ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle);
ImGui.Spacing();
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Rebuff With (seconds left)", ref _settings.RebuffSecondsRemaining, 30, 1800);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Recast a self buff when its remaining duration drops below this value.\n" +
"Default 300 (5 minutes). Lower values rebuff more eagerly; very low\n" +
"values (<60s) risk a gap between the old buff dropping and the new one\n" +
"landing.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Minimum buffed skill level required to cast each self-buff tier.\n" +
"Separate from Spell Combat thresholds so you can tune buffing\n" +
"more aggressively — buff fizzles just retry on the next heartbeat.\n" +
"AC's hard minimums are 1/50/100/150/200/250/300/350.");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 1##Buff", ref _settings.BuffMinSkillLevelTier1);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 2##Buff", ref _settings.BuffMinSkillLevelTier2);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 3##Buff", ref _settings.BuffMinSkillLevelTier3);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 4##Buff", ref _settings.BuffMinSkillLevelTier4);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 5##Buff", ref _settings.BuffMinSkillLevelTier5);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 6##Buff", ref _settings.BuffMinSkillLevelTier6);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 7##Buff", ref _settings.BuffMinSkillLevelTier7);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Level 8##Buff", ref _settings.BuffMinSkillLevelTier8);
break;
case "Looting":
ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority);
ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses);
ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled);
if (_settings.LootJumpEnabled)
{
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Jump Height", ref _settings.LootJumpHeight, 1, 100);
}
ImGui.Spacing();
ImGui.Text("Corpse Ownership");
ImGui.SetNextItemWidth(180);
ImGui.Combo("Loot From", ref _settings.LootOwnership, LootOwnershipModes, LootOwnershipModes.Length);
ImGui.Spacing();
ImGui.Text("Inventory Management");
ImGui.Checkbox("Enable Autostack", ref _settings.EnableAutostack);
ImGui.Checkbox("Enable Autocram", ref _settings.EnableAutocram);
ImGui.Checkbox("Combine Salvage Bags", ref _settings.EnableCombineSalvage);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After the salvage queue empties, move same-name bags together so the server merges them.");
ImGui.Checkbox("Combine Bags During Salvage", ref _settings.CombineBagsDuringSalvage);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel — the salvage operation merges them into a single bag.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Loot Timers (ms)");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Inter-Item Delay", ref _settings.LootInterItemDelayMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Content Settle", ref _settings.LootContentSettleMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Closing Delay", ref _settings.LootClosingDelayMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Assess Window", ref _settings.LootAssessWindowMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Corpse Open Retry", ref _settings.LootOpenRetryMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Corpse Timeout", ref _settings.LootCorpseTimeoutMs);
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Salvage Timers (ms) - First / Fast");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Open (First)", ref _settings.SalvageOpenDelayFirstMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Open (Fast)", ref _settings.SalvageOpenDelayFastMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Add Item (First)", ref _settings.SalvageAddDelayFirstMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Add Item (Fast)", ref _settings.SalvageAddDelayFastMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Salvage Click", ref _settings.SalvageSalvageDelayMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Result (First)", ref _settings.SalvageResultDelayFirstMs);
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Result (Fast)", ref _settings.SalvageResultDelayFastMs);
break;
case "Crafting":
ImGui.Text("Missile Ammo Crafting");
ImGui.Separator();
ImGui.Spacing();
ImGui.Checkbox("Enable Missile Crafting", ref _settings.EnableMissileCrafting);
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Auto-manage missile ammo when the ammo slot is empty or low.");
}
if (!_settings.EnableMissileCrafting)
{
ImGui.TextDisabled("(Disabled)");
break;
}
ImGui.Spacing();
if (_missileCraftingManager != null)
{
string stateLabel = _missileCraftingManager.State.ToString();
Vector4 stateColor = _missileCraftingManager.IsCrafting
? new Vector4(0.9f, 0.7f, 0.2f, 1.0f)
: new Vector4(0.5f, 0.5f, 0.5f, 1.0f);
ImGui.Text("State:");
ImGui.SameLine();
ImGui.TextColored(stateColor, stateLabel);
if (!string.IsNullOrEmpty(_missileCraftingManager.StatusMessage))
ImGui.TextWrapped(_missileCraftingManager.StatusMessage);
}
break;
default:
ImGui.Text($"Settings for {tabName} are currently under development.");
break;
}
}
}

View file

@ -0,0 +1,158 @@
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal static class LegacyDashboardDrawing
{
public static void GridBtn(string label, string icon, ref bool flag)
{
bool wasOn = flag;
const float h = 30f;
ImGui.PushStyleColor(ImGuiCol.Button, LegacyDashboardRenderer.ColBtnFill);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, LegacyDashboardRenderer.ColBtnHov);
ImGui.PushStyleColor(ImGuiCol.ButtonActive, LegacyDashboardRenderer.ColBtnAct);
ImGui.PushStyleColor(ImGuiCol.Border, wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColBtnBord);
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f);
ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4f);
Vector2 start = ImGui.GetCursorScreenPos();
if (ImGui.Button($"##{label}", new Vector2(-1f, h))) flag = !flag;
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(4);
float w = ImGui.GetItemRectSize().X;
Vector2 text = ImGui.CalcTextSize(label);
DrawIcon(icon, start + new Vector2(8, 6), wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute, 16f);
ImGui.SetCursorScreenPos(start + new Vector2(30, (h - text.Y) / 2));
ImGui.TextColored(wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextDim, label);
ImGui.SetCursorScreenPos(start + new Vector2(0, h + 2));
ImGui.Dummy(new Vector2(w, 0));
}
public static void DrawSquareToggle(string icon, ref bool state, Vector2 pos, string id)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float s = 30f;
Vector4 bg = state ? LegacyDashboardRenderer.ColBtnOn : LegacyDashboardRenderer.ColBarBg;
Vector4 iconCol = state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(bg), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(6, 6), iconCol, 18f);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(s, s))) state = !state;
}
public static void DrawWideToggle(string label, string icon, ref bool state, Vector2 pos, string id, float width, float height)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector4 bg = state ? LegacyDashboardRenderer.ColBtnOn : LegacyDashboardRenderer.ColBarBg;
Vector4 iconCol = state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(bg), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(4, (height - 12) / 2), iconCol, 12f);
Vector2 text = ImGui.CalcTextSize(label);
dl.AddText(pos + new Vector2(18, (height - text.Y) / 2), ImGui.ColorConvertFloat4ToU32(state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextDim), label);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(width, height))) state = !state;
}
public static void DrawSegmentedBar(float pct, float width)
{
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 10f, gap = 2f;
const int segments = 15;
float sw = (width - (segments - 1) * gap) / segments;
for (int i = 0; i < segments; i++)
{
float t = (float)i / (segments - 1);
Vector4 col = i / (float)segments <= pct ? GetGradientCol(t) : LegacyDashboardRenderer.ColBarBg;
dl.AddRectFilled(pos + new Vector2(i * (sw + gap), 0), pos + new Vector2(i * (sw + gap) + sw, h), ImGui.ColorConvertFloat4ToU32(col), 1f);
}
ImGui.Dummy(new Vector2(width, h + 2));
}
public static void DrawCompactVitalBar(string label, float pct, Vector4 color, string valText, float width)
{
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 10f;
float safePct = Math.Clamp(pct, 0f, 1f);
dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColBarBg), 3f);
dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 3f);
string text = $"{label} {valText}";
dl.AddText(pos + new Vector2(4, -2), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 0.9f)), text);
ImGui.Dummy(new Vector2(width, h + 1));
}
public static void DrawVitalRow(string icon, string label, float pct, Vector4 color, string valText)
{
float width = ImGui.GetContentRegionAvail().X - 4f;
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 14f;
dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColBarBg), 4f);
float safePct = Math.Clamp(pct, 0f, 1f);
dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 4f);
DrawIcon(icon, pos + new Vector2(4, 0), LegacyDashboardRenderer.ColTextDim, 13f);
dl.AddText(pos + new Vector2(22, -1), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 1)), $"{label}: {(int)(safePct * 100)}% ({valText})");
ImGui.Dummy(new Vector2(width, h + 1));
}
private static Vector4 GetGradientCol(float t)
{
if (t < 0.33f) { float f = t / 0.33f; return new Vector4(1f, f, 0f, 1f); }
if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; return new Vector4(1f - f, 1f, 0f, 1f); }
float g = (t - 0.66f) / 0.34f;
return new Vector4(0f, 1f, g, 1f);
}
private static void DrawIcon(string type, Vector2 pos, Vector4 color, float s)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
uint col = ImGui.ColorConvertFloat4ToU32(color);
switch (type)
{
case "gear":
dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 3.5f, col, 12, 1.5f);
for (int i = 0; i < 8; i++) { float a = i * (MathF.PI * 2f / 8f); dl.AddLine(pos + new Vector2(s / 2 + MathF.Cos(a) * s / 3, s / 2 + MathF.Sin(a) * s / 3), pos + new Vector2(s / 2 + MathF.Cos(a) * s / 2, s / 2 + MathF.Sin(a) * s / 2), col, 2f); }
break;
case "target":
dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 2.5f, col, 12, 1.5f); dl.AddLine(pos + new Vector2(s / 2, 0), pos + new Vector2(s / 2, s), col, 1.5f); dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s, s / 2), col, 1.5f);
break;
case "wrench":
dl.AddCircle(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col, 8, 1.5f); dl.AddLine(pos + new Vector2(s * 0.4f, s * 0.4f), pos + new Vector2(s * 0.9f, s * 0.9f), col, 2f);
break;
case "map":
dl.AddRect(pos, pos + new Vector2(s, s), col, 1.5f); dl.AddLine(pos + new Vector2(s / 2, 2), pos + new Vector2(s / 2, s - 2), col, 1.5f); dl.AddLine(pos + new Vector2(2, s / 2), pos + new Vector2(s - 2, s / 2), col, 1.5f);
break;
case "bag":
dl.AddRectFilled(pos + new Vector2(2, s / 3), pos + new Vector2(s - 2, s), col, 2f); dl.AddCircle(pos + new Vector2(s / 2, s / 4), s / 5, col, 8, 1.5f);
break;
case "shield":
dl.AddLine(pos + new Vector2(s * 0.2f, 0), pos + new Vector2(s * 0.8f, 0), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.8f, 0), pos + new Vector2(s * 0.8f, s * 0.6f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.5f, s), pos + new Vector2(s * 0.2f, s * 0.6f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.2f, 0), col, 1.5f);
break;
case "code":
dl.AddLine(pos + new Vector2(s * 0.3f, 2), pos + new Vector2(0, s / 2), col, 1.5f); dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s * 0.3f, s - 2), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.7f, 2), pos + new Vector2(s, s / 2), col, 1.5f); dl.AddLine(pos + new Vector2(s, s / 2), pos + new Vector2(s * 0.7f, s - 2), col, 1.5f);
break;
case "heart":
dl.AddCircleFilled(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col); dl.AddCircleFilled(pos + new Vector2(s * 0.7f, s * 0.3f), s * 0.25f, col); dl.AddTriangleFilled(pos + new Vector2(s * 0.05f, s * 0.4f), pos + new Vector2(s * 0.95f, s * 0.4f), pos + new Vector2(s * 0.5f, s * 0.9f), col);
break;
case "run":
dl.AddCircle(pos + new Vector2(s * 0.5f, s * 0.2f), s * 0.15f, col, 8, 1.5f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.35f), pos + new Vector2(s * 0.5f, s * 0.65f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.2f, s * 0.9f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.8f, s * 0.9f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.4f), pos + new Vector2(s * 0.8f, s * 0.4f), col, 1.5f);
break;
case "drop":
dl.AddCircleFilled(pos + new Vector2(s * 0.5f, s * 0.7f), s * 0.25f, col); dl.AddTriangleFilled(pos + new Vector2(s * 0.25f, s * 0.65f), pos + new Vector2(s * 0.75f, s * 0.65f), pos + new Vector2(s * 0.5f, s * 0.1f), col);
break;
case "sword":
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.7f), pos + new Vector2(s * 0.9f, s * 0.1f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.4f, s * 0.8f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.1f, s * 0.9f), pos + new Vector2(s * 0.3f, s * 0.7f), col, 2f);
break;
case "shoe":
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.8f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.8f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.6f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s * 0.5f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.5f), pos + new Vector2(s * 0.5f, s * 0.2f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.2f), col, 2f);
break;
case "buff":
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.5f, s * 0.8f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.5f), pos + new Vector2(s * 0.8f, s * 0.5f), col, 2f); dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.3f), pos + new Vector2(s * 0.5f, s * 0.1f), col, 1.5f); dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.1f), pos + new Vector2(s * 0.7f, s * 0.3f), col, 1.5f);
break;
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,460 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyMonstersUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
private readonly Action _onMonstersChanged;
private readonly Action _onLaunchExternalEditor;
private readonly Func<(uint Id, string Name)?> _getCurrentTarget;
/// <summary>Set by the dashboard so we can show captured stats per monster row.</summary>
public Func<string, CreatureProfile?>? CreatureLookup { get; set; }
private string _newMonsterName = string.Empty;
private string _newMonsterCategory = string.Empty;
private readonly Dictionary<string, bool> _categoryExpanded = new(StringComparer.OrdinalIgnoreCase);
// Expression popup state
private int _exprEditIndex = -1;
private string _exprEditBuffer = string.Empty;
// Category rename popup state
private string _catRenameFrom = string.Empty;
private string _catRenameBuffer = string.Empty;
private static readonly string[] Elements =
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly uint OnColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 1.0f, 0.2f, 1.0f));
private static readonly uint OffColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 0.3f, 0.3f, 1.0f));
private static readonly uint ExprOnColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 0.85f, 0.4f, 1.0f));
private static readonly uint CatHeaderBg = ImGui.ColorConvertFloat4ToU32(new Vector4(0.10f, 0.18f, 0.26f, 1.0f));
public LegacyMonstersUi(
LegacyUiSettings settings,
RynthCoreHost host,
Action onMonstersChanged,
Action onLaunchExternalEditor,
Func<(uint Id, string Name)?> getCurrentTarget)
{
_settings = settings;
_host = host;
_onMonstersChanged = onMonstersChanged;
_onLaunchExternalEditor = onLaunchExternalEditor;
_getCurrentTarget = getCurrentTarget;
}
public void Render()
{
if (!DashWindows.ShowMonsters) return;
ImGui.SetNextWindowSize(new Vector2(860, 480), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Monsters##RynthAiMonsters", ref DashWindows.ShowMonsters))
{
ImGui.End();
return;
}
if (ImGui.Button("External Editor", new Vector2(130, 24)))
_onLaunchExternalEditor();
ImGui.SameLine();
ImGui.TextDisabled("(opens standalone Avalonia editor)");
ImGui.Separator();
DrawTable();
ImGui.Separator();
DrawAddRow();
ImGui.End();
}
private void DrawTable()
{
// 19 columns: 10 toggles + Name + P + DmgType + ExVuln + Weapon + Offhand + PetDmg + [E] + Del
if (!ImGui.BeginTable(
"MonstersGrid", 19,
ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.Borders |
ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY,
new Vector2(0, 330)))
return;
ImGui.TableSetupColumn("F", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("B", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("G", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("I", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Y", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("V", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("A", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Bl", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("R", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("S", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("P", ImGuiTableColumnFlags.WidthFixed, 30);
ImGui.TableSetupColumn("Dmg type", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableSetupColumn("Ex Vuln", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableSetupColumn("Weapon", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Offhand", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("PetDmg", ImGuiTableColumnFlags.WidthFixed, 70);
ImGui.TableSetupColumn("[E]", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableHeadersRow();
int deleteIndex = -1;
string? currentCat = null;
bool currentCatOpen = true;
for (int i = 0; i < _settings.MonsterRules.Count; i++)
{
var rule = _settings.MonsterRules[i];
bool isDefault = rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
string cat = string.IsNullOrEmpty(rule.Category) ? "Default" : rule.Category;
// Category header row
if (!string.Equals(cat, currentCat, StringComparison.OrdinalIgnoreCase))
{
currentCat = cat;
if (!_categoryExpanded.ContainsKey(cat))
_categoryExpanded[cat] = true;
currentCatOpen = _categoryExpanded[cat];
ImGui.TableNextRow();
ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, CatHeaderBg);
ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, CatHeaderBg);
ImGui.TableNextColumn(); // col 0: expand toggle
string arrow = currentCatOpen ? "v" : ">";
ImGui.PushStyleColor(ImGuiCol.Button, Vector4.Zero);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(1,1,1,0.1f));
if (ImGui.SmallButton($"{arrow}##cat_{cat}"))
{
currentCatOpen = !currentCatOpen;
_categoryExpanded[cat] = currentCatOpen;
}
ImGui.PopStyleColor(2);
// Name col: category label + right-click rename
ImGui.TableSetColumnIndex(10);
ImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1f), cat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Right-click to rename category");
if (ImGui.BeginPopupContextItem($"catctx_{cat}"))
{
ImGui.Text("Rename category:");
if (_catRenameFrom != cat)
{
_catRenameFrom = cat;
_catRenameBuffer = cat;
}
ImGui.SetNextItemWidth(180);
ImGui.InputText("##catren", ref _catRenameBuffer, 64);
if (ImGui.Button("Apply") && !string.IsNullOrWhiteSpace(_catRenameBuffer))
{
string newName = _catRenameBuffer.Trim();
foreach (var r in _settings.MonsterRules)
if (string.Equals(r.Category, cat, StringComparison.OrdinalIgnoreCase))
r.Category = newName;
if (_categoryExpanded.TryGetValue(cat, out bool v))
{
_categoryExpanded.Remove(cat);
_categoryExpanded[newName] = v;
}
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
}
if (!currentCatOpen) continue;
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (DrawToggleLight($"##F{i}", rule.Fester, OnColor, OffColor, "F: Fester (Decrepitude's Grasp / Fester Other I-VIII)"))
{ rule.Fester = !rule.Fester; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##B{i}", rule.Broadside, OnColor, OffColor, "B: Broadside (Broadside of a Barn / Missile Weapons Ineptitude I-VIII)"))
{ rule.Broadside = !rule.Broadside; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##G{i}", rule.GravityWell, OnColor, OffColor, "G: Gravity Well (Vulnerability Other I-VIII)"))
{ rule.GravityWell = !rule.GravityWell; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##I{i}", rule.Imperil, OnColor, OffColor, "I: Imperil (Gossamer Flesh / Imperil Other I-VIII)"))
{ rule.Imperil = !rule.Imperil; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Y{i}", rule.Yield, OnColor, OffColor, "Y: Yield (Magic Yield Other I-VIII)"))
{ rule.Yield = !rule.Yield; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##V{i}", rule.Vuln, OnColor, OffColor, "V: Vulnerability (element-matched)"))
{ rule.Vuln = !rule.Vuln; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##A{i}", rule.UseArc, OnColor, OffColor, "A: Arc spells\nFor Melee/Missile: Attack toggle"))
{ rule.UseArc = !rule.UseArc; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Bl{i}", rule.UseBolt, OnColor, OffColor, "Bl: Bolt spells (default)\nIf none of A/Bl/R/S = no attack (buff bot)"))
{ rule.UseBolt = !rule.UseBolt; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##R{i}", rule.UseRing, OnColor, OffColor, "R: Ring spells"))
{ rule.UseRing = !rule.UseRing; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##S{i}", rule.UseStreak, OnColor, OffColor, "S: Streak spells"))
{ rule.UseStreak = !rule.UseStreak; _onMonstersChanged(); }
ImGui.TableNextColumn();
CreatureProfile? profile = CreatureLookup?.Invoke(rule.Name);
if (isDefault) ImGui.TextColored(new Vector4(1, 1, 0, 1), rule.Name);
else if (profile != null) ImGui.TextColored(new Vector4(0.55f, 0.95f, 0.65f, 1f), rule.Name);
else ImGui.TextUnformatted(rule.Name);
if (profile != null && ImGui.IsItemHovered())
ImGui.SetTooltip(BuildProfileTooltip(profile));
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int pr = rule.Priority;
if (ImGui.InputInt($"##P{i}", ref pr, 0)) { rule.Priority = pr; _onMonstersChanged(); }
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##Dmg{i}", rule.DamageType, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("Auto", rule.DamageType == "Auto")) { rule.DamageType = "Auto"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##d{i}", rule.DamageType == el)) { rule.DamageType = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##Vuln{i}", rule.ExVuln, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("None", rule.ExVuln == "None")) { rule.ExVuln = "None"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##v{i}", rule.ExVuln == el)) { rule.ExVuln = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string wepLabel = "<AUTO>";
if (rule.WeaponId != 0) { var w = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.WeaponId); if (w != null) wepLabel = w.Name; }
if (ImGui.BeginCombo($"##Wep{i}", wepLabel, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.WeaponId == 0)) { rule.WeaponId = 0; _onMonstersChanged(); }
foreach (var item in _settings.ItemRules)
if (ImGui.Selectable(item.Name + $"##wep{i}_{item.Id}", rule.WeaponId == item.Id)) { rule.WeaponId = item.Id; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string offLabel = "<AUTO>";
if (rule.OffhandId != 0) { var o = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.OffhandId); if (o != null) offLabel = o.Name; }
if (ImGui.BeginCombo($"##Off{i}", offLabel, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.OffhandId == 0)) { rule.OffhandId = 0; _onMonstersChanged(); }
foreach (var item in _settings.ItemRules)
if (ImGui.Selectable(item.Name + $"##off{i}_{item.Id}", rule.OffhandId == item.Id)) { rule.OffhandId = item.Id; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##PetDmg{i}", rule.PetDamage, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("PAuto", rule.PetDamage == "PAuto")) { rule.PetDamage = "PAuto"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##p{i}", rule.PetDamage == el)) { rule.PetDamage = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
// [E] expression button
ImGui.TableNextColumn();
bool hasExpr = !string.IsNullOrWhiteSpace(rule.MatchExpression);
if (hasExpr) ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.1f, 0.5f, 0.2f, 1f));
if (ImGui.SmallButton($"E##e{i}"))
{
_exprEditIndex = i;
_exprEditBuffer = rule.MatchExpression ?? "";
ImGui.OpenPopup($"ExprEdit{i}");
}
if (hasExpr)
{
ImGui.PopStyleColor();
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Expression: {rule.MatchExpression}");
}
else if (ImGui.IsItemHovered())
{
ImGui.SetTooltip(
"Set a match expression.\n" +
"Examples:\n" +
" range>5\n" +
" range>5 && name==drudge ravener\n" +
" metastate==combat\n" +
"Variables: name, range, typeid, maxhp, metastate, true, false");
}
// Expression edit popup (rendered outside table to avoid clipping)
if (ImGui.BeginPopup($"ExprEdit{i}"))
{
ImGui.Text($"Expression for: {rule.Name}");
ImGui.TextColored(new Vector4(0.6f, 0.8f, 1f, 1f),
"Variables: name, range, typeid, maxhp, metastate, true, false");
ImGui.SetNextItemWidth(360);
ImGui.InputText("##exprval", ref _exprEditBuffer, 256);
if (ImGui.Button("Apply", new Vector2(80, 22)))
{
rule.MatchExpression = _exprEditBuffer.Trim();
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.SameLine();
if (ImGui.Button("Clear", new Vector2(80, 22)))
{
rule.MatchExpression = "";
_exprEditBuffer = "";
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
// Del
ImGui.TableNextColumn();
if (isDefault)
{
ImGui.TextDisabled("-");
}
else
{
if (ImGui.SmallButton($"X##del{i}"))
deleteIndex = i;
}
}
ImGui.EndTable();
if (deleteIndex >= 0 && deleteIndex < _settings.MonsterRules.Count)
{
_settings.MonsterRules.RemoveAt(deleteIndex);
_onMonstersChanged();
}
}
private void DrawAddRow()
{
if (!ImGui.BeginTable("AddTable", 4))
return;
ImGui.TableSetupColumn("NameIn", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("CatIn", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("AddBtn", ImGuiTableColumnFlags.WidthFixed, 60);
ImGui.TableSetupColumn("AddSelBtn", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##NewMonName", "Monster name...", ref _newMonsterName, 64);
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##NewMonCat", "Category...", ref _newMonsterCategory, 64);
ImGui.TableNextColumn();
if (ImGui.Button("Add", new Vector2(60, 22)))
TryAddMonster(_newMonsterName, _newMonsterCategory);
ImGui.TableNextColumn();
if (ImGui.Button("Add Sel", new Vector2(80, 22)))
{
var target = _getCurrentTarget();
if (target.HasValue && !string.IsNullOrWhiteSpace(target.Value.Name))
TryAddMonster(target.Value.Name, _newMonsterCategory);
}
ImGui.EndTable();
}
private void TryAddMonster(string name, string category)
{
if (string.IsNullOrWhiteSpace(name)) return;
if (_settings.MonsterRules.Any(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) return;
_settings.MonsterRules.Add(new MonsterRule
{
Name = name.Trim(),
Category = category.Trim(),
DamageType = "Auto",
WeaponId = 0,
});
_newMonsterName = string.Empty;
_onMonstersChanged();
}
private static string BuildProfileTooltip(CreatureProfile p)
{
var sb = new System.Text.StringBuilder();
sb.Append("Captured: ").Append(p.Name);
if (p.Wcid != 0) sb.Append(" (wcid ").Append(p.Wcid).Append(')');
sb.Append('\n');
if (p.MaxHealth > 0) sb.Append("HP: ").Append(p.MaxHealth).Append('\n');
if (p.MaxStamina > 0) sb.Append("Stam: ").Append(p.MaxStamina).Append('\n');
if (p.MaxMana > 0) sb.Append("Mana: ").Append(p.MaxMana).Append('\n');
if (p.ArmorLevel > 0) sb.Append("Armor: ").Append(p.ArmorLevel).Append('\n');
var (weakType, weakVal) = CreatureProfileStore.GetWeakest(p);
if (weakVal < 1.0)
sb.Append("Weak: ").Append(weakType).Append(" (").Append(weakVal.ToString("0.00")).Append(")\n");
sb.Append("Resists: ")
.Append("Sl ").Append(p.ResistSlash.ToString("0.00")).Append(" ")
.Append("Pi ").Append(p.ResistPierce.ToString("0.00")).Append(" ")
.Append("Bl ").Append(p.ResistBludgeon.ToString("0.00")).Append('\n')
.Append(" ")
.Append("Fi ").Append(p.ResistFire.ToString("0.00")).Append(" ")
.Append("Co ").Append(p.ResistCold.ToString("0.00")).Append(" ")
.Append("Ac ").Append(p.ResistAcid.ToString("0.00")).Append(" ")
.Append("El ").Append(p.ResistElectric.ToString("0.00")).Append('\n');
if (p.KnownSpellIds.Count > 0)
sb.Append("Spells observed: ").Append(p.KnownSpellIds.Count).Append('\n');
sb.Append("Samples: ").Append(p.Samples);
if (!string.IsNullOrEmpty(p.LastSeen))
sb.Append(" (last: ").Append(p.LastSeen).Append(')');
return sb.ToString();
}
private static bool DrawToggleLight(string id, bool isOn, uint onColor, uint offColor, string? tooltip = null)
{
Vector2 pos = ImGui.GetCursorScreenPos();
ImGui.GetWindowDrawList().AddRectFilled(
pos + new Vector2(2, 2),
pos + new Vector2(12, 12),
isOn ? onColor : offColor,
10.0f);
ImGui.InvisibleButton(id, new Vector2(14, 14));
if (tooltip != null && ImGui.IsItemHovered())
ImGui.SetTooltip(tooltip);
return ImGui.IsItemClicked();
}
}

View file

@ -0,0 +1,275 @@
using System;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyNavigationUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
public Action? OnSettingsChanged;
private readonly string[] _routeTypes = { "Once", "Circular", "Linear", "Follow" };
private readonly string[] _addModes = { "End", "Above", "Below" };
private int _addModeIdx = 0;
private int _selectedRouteIndex = -1;
public LegacyNavigationUi(LegacyUiSettings settings, RynthCoreHost host)
{
_settings = settings;
_host = host;
}
public void Render()
{
ImGui.SetNextWindowSize(new Vector2(400, 480), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Navigation##RynthAiNav", ref DashWindows.ShowNavigation))
{
ImGui.End();
return;
}
string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath);
ImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}");
if (!string.IsNullOrEmpty(_settings.NavStatusLine))
{
var statusColor = _settings.NavIsStuck
? new Vector4(0.91f, 0.70f, 0.20f, 1.00f) // amber
: new Vector4(0.25f, 0.85f, 0.45f, 1.00f); // green
ImGui.TextColored(statusColor, _settings.NavStatusLine);
}
ImGui.Spacing();
bool navActive = _settings.IsMacroRunning && _settings.EnableNavigation;
if (navActive)
{
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.50f, 0.10f, 0.10f, 1f));
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.70f, 0.15f, 0.15f, 1f));
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.35f, 0.08f, 0.08f, 1f));
if (ImGui.Button("Stop Navigation", new Vector2(-1, 28)))
_settings.EnableNavigation = false;
ImGui.PopStyleColor(3);
}
else
{
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.38f, 0.10f, 1f));
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.15f, 0.55f, 0.15f, 1f));
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.08f, 0.28f, 0.08f, 1f));
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
{
_settings.IsMacroRunning = true;
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
_settings.BotAction = "Default";
}
ImGui.PopStyleColor(3);
}
ImGui.Separator();
int rTypeIdx = 0;
if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) rTypeIdx = 1;
else if (_settings.CurrentRoute.RouteType == NavRouteType.Linear) rTypeIdx = 2;
else if (_settings.CurrentRoute.RouteType == NavRouteType.Follow) rTypeIdx = 3;
ImGui.SetNextItemWidth(100);
if (ImGui.Combo("Route Type", ref rTypeIdx, _routeTypes, _routeTypes.Length))
{
if (rTypeIdx == 0) _settings.CurrentRoute.RouteType = NavRouteType.Once;
else if (rTypeIdx == 1) _settings.CurrentRoute.RouteType = NavRouteType.Circular;
else if (rTypeIdx == 2) _settings.CurrentRoute.RouteType = NavRouteType.Linear;
else if (rTypeIdx == 3) _settings.CurrentRoute.RouteType = NavRouteType.Follow;
TryAutoSaveNav();
}
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
ImGui.Combo("Insert", ref _addModeIdx, _addModes, _addModes.Length);
ImGui.Spacing();
if (ImGui.Button("Add Waypoint", new Vector2(100, 25)))
{
// Stop any active turn motion so the character doesn't keep spinning
_host.SetMotion(0x6500000D, false); // TurnRight
_host.SetMotion(0x6500000E, false); // TurnLeft
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))
{
if (NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew))
{
var newPt = new NavPoint
{
NS = ns,
EW = ew,
Z = z
};
InsertPoint(newPt);
}
}
}
ImGui.SameLine();
if (ImGui.Button("Add Portal", new Vector2(100, 25)))
{
_host.Log("Compat: Add Portal not yet implemented in RynthCore.");
}
ImGui.SameLine();
if (ImGui.Button("Add Recall", new Vector2(100, 25)))
{
ImGui.OpenPopup("RecallPopup");
}
if (ImGui.BeginPopup("RecallPopup"))
{
int[] ids = {
48, 2645, 2647,
1635, 1636,
157, 158, 1637,
2648, 2649, 2650,
2931, 2023, 2041, 2358, 2813, 2941, 2943,
3865, 3929, 3930, 4084, 4198, 4213,
4907, 4908, 4909,
5175, 5330, 5541, 6150, 6321, 6322
};
for (int ri = 0; ri < ids.Length; ri++)
{
string name = $"Spell {ids[ri]}";
if (ImGui.Selectable($"{name} ({ids[ri]})"))
{
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))
{
if (NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew))
{
var newPt = new NavPoint
{
Type = NavPointType.Recall,
NS = ns,
EW = ew,
Z = z,
SpellId = ids[ri]
};
InsertPoint(newPt);
_host.Log($"Added Recall: {name} ({ids[ri]})");
}
}
}
}
ImGui.EndPopup();
}
ImGui.SameLine();
if (ImGui.Button("Clear Route", new Vector2(100, 25)))
{
_settings.CurrentRoute.Points.Clear();
_settings.ActiveNavIndex = 0;
TryAutoSaveNav();
DisposeRouteGraphics();
OnSettingsChanged?.Invoke();
}
ImGui.SameLine();
if (ImGui.Button("Save Route", new Vector2(100, 25)))
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
{
try
{
_settings.CurrentRoute.Save(_settings.CurrentNavPath);
_host.Log("Route saved.");
}
catch (Exception ex)
{
_host.Log($"Failed to save route: {ex.Message}");
}
}
}
if (ImGui.BeginListBox("##RoutePoints", new Vector2(-1, 200)))
{
for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++)
{
ImGui.PushID($"route_pt_{i}");
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.2f, 0.2f, 1f));
if (ImGui.Button("X", new Vector2(20, 20)))
{
_settings.CurrentRoute.Points.RemoveAt(i);
if (_selectedRouteIndex == i) _selectedRouteIndex = -1;
else if (_selectedRouteIndex > i) _selectedRouteIndex--;
if (_settings.ActiveNavIndex == i) _settings.ActiveNavIndex = 0;
else if (_settings.ActiveNavIndex > i) _settings.ActiveNavIndex--;
TryAutoSaveNav();
UpdateRouteGraphics();
OnSettingsChanged?.Invoke();
ImGui.PopStyleColor();
ImGui.PopID();
break;
}
ImGui.PopStyleColor();
ImGui.SameLine();
string prefix = " ";
if (i == _settings.ActiveNavIndex) prefix = "==>";
bool isSelected = (_selectedRouteIndex == i);
if (ImGui.Selectable($"{prefix} [{i}] {_settings.CurrentRoute.Points[i]}", isSelected))
{
_selectedRouteIndex = i;
}
ImGui.PopID();
}
ImGui.EndListBox();
}
ImGui.End();
}
public void InsertPoint(NavPoint newPt)
{
if (_addModeIdx == 0 || _settings.CurrentRoute.Points.Count == 0)
_settings.CurrentRoute.Points.Add(newPt);
else if (_addModeIdx == 1 && _selectedRouteIndex >= 0)
_settings.CurrentRoute.Points.Insert(_selectedRouteIndex, newPt);
else if (_addModeIdx == 2 && _selectedRouteIndex >= 0)
_settings.CurrentRoute.Points.Insert(_selectedRouteIndex + 1, newPt);
else
_settings.CurrentRoute.Points.Add(newPt);
TryAutoSaveNav();
UpdateRouteGraphics();
OnSettingsChanged?.Invoke();
}
public void TryAutoSaveNav()
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
{
try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } catch { }
}
}
public void UpdateRouteGraphics()
{
// 3D rendering not yet ported to RynthCore
}
public void DisposeRouteGraphics()
{
// 3D rendering not yet ported to RynthCore
}
}

View file

@ -0,0 +1,776 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
public static class DashWindows
{
public static bool ShowMacroRules;
public static bool ShowMonsters;
public static bool ShowNavigation;
public static bool ShowWeapons;
public static bool ShowLua;
public static bool ShowDungeonMap;
}
public sealed class LegacyUiSettings
{
// ── Runtime-only state — never persisted ────────────────────────────────
[JsonIgnore] public bool IsMacroRunning;
/// <summary>Meta state — set only by meta actions (SetState, CallState, ReturnFromCall, UI, meta load).</summary>
[JsonIgnore] public string CurrentState = "Default";
/// <summary>Bot action state — what the bot is doing right now (Default, Combat, Looting, Navigating, Buffing).
/// Separate from meta state so operational cycling doesn't corrupt meta rule matching.</summary>
[JsonIgnore] public string BotAction = "Default";
[JsonIgnore] public bool IsRecordingNav;
public bool EnableBuffing = true;
public bool EnableCombat;
public bool EnableNavigation;
public bool EnableLooting;
public bool EnableMeta;
public bool EnableRaycasting = true;
public bool MetaDebug;
public int MovementMode;
public float NavStopTurnAngle = 20f;
public float NavResumeTurnAngle = 10f;
public float NavDeadZone = 4f;
public float NavSweepMult = 2.5f;
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
public float PostPortalDelaySec = 4.0f;
public float T2Speed = 1.0f;
public float T2DistanceTo = 0.5f;
public float T2ReissueMs = 2000f;
public float T2MaxRangeYd = 500f;
public int T2MaxLandblocks = 3;
public float T2WalkWithinYd = 5f;
public string CurrentNavPath = string.Empty;
public string CurrentLootPath = string.Empty;
public string CurrentMetaPath = string.Empty;
public int MacroSettingsIdx = 1;
public int NavProfileIdx = 1;
public int LootProfileIdx;
public int MetaProfileIdx = 1;
public bool EnableAutostack = true;
public bool EnableAutocram = true;
public bool EnableCombineSalvage = true;
public bool CombineBagsDuringSalvage = true;
public bool ShowTargetStaminaMana;
public bool EnableMissileCrafting = true;
public int MissileCraftAmmoThreshold = 1000;
public int LootInterItemDelayMs = 50;
public int LootContentSettleMs = 100;
public int LootEmptyCorpseMs = 300;
public int LootClosingDelayMs = 200;
public int LootAssessWindowMs = 200;
public int LootRetryTimeoutMs = 500;
public int LootOpenRetryMs = 1500;
public int LootCorpseTimeoutMs = 12000;
public bool LootJumpEnabled = false;
public int LootJumpHeight = 10; // 0–100; maps to 0.0–1.0 JumpNonAutonomous extent
public int SalvageOpenDelayFirstMs = 400;
public int SalvageOpenDelayFastMs = 50;
public int SalvageAddDelayFirstMs = 600;
public int SalvageAddDelayFastMs = 50;
public int SalvageSalvageDelayMs = 50;
public int SalvageResultDelayFirstMs = 1000;
public int SalvageResultDelayFastMs = 250;
public bool UseDispelItems;
public bool CastDispelSelf;
public bool AutoFellowMgmt;
public bool MChargesWhenOff;
public int HealAt = 60;
public int RestamAt = 30;
public int GetManaAt = 40;
public int TopOffHP = 95;
public int TopOffStam = 95;
public int TopOffMana = 95;
public int HealOthersAt = 50;
public int RestamOthersAt = 10;
public int InfuseOthersAt = 10;
public int MonsterRange = 50;
// Disengage distance for an already-locked target (hysteresis deadband).
// 0 = auto (MonsterRange + 3). Must exceed MonsterRange or it's ignored.
// Without the deadband, the small step-back AC applies on combat-mode entry
// can push a mob just past MonsterRange, dropping it and flipping to peace,
// then re-approaching — an endless engage/peace oscillation at the edge.
public int MonsterDisengageRange = 0;
public int RingRange = 5;
public int ApproachRange = 4;
public int MinRingTargets = 4;
public float FollowNavMin = 1.5f;
// VTank navclosestoprange: stop this many LANDBLOCK FRACTIONS short of a finite
// (Once) route's final point (×240 = yards; 0.00625 ≈ 1.5yd). 0 = off. Runtime-
// set by migrated metas; not persisted.
public float NavCloseStopRange = 0f;
public float NavRingThickness = 6.0f;
public float NavLineThickness = 6.0f;
public float NavHeightOffset = 0.05f;
public float NavSlopeSink = 1.5f;
public bool ShowTerrainPassability = true;
public double MaxMonRange = 12.0;
public bool SummonPets;
public int CustomPetRange = 5;
public int PetMinMonsters = 1;
public bool PetAutoRefill = true; // auto-consume Encapsulated Spirits to recharge empty essences
public bool AdvancedOptions;
public bool MineOnly = true;
public bool ShowEditor;
public double CorpseApproachRangeMax = 10.0;
public double CorpseApproachRangeMin = 2.0;
public bool BoostNavPriority;
public bool BoostLootPriority;
public bool OpenDoors;
public float OpenDoorRange = 5.0f;
public bool AutoUnlockDoors;
public int LootOwnership;
public bool LootOnlyRareCorpses;
public bool PeaceModeWhenIdle = true;
public bool RebuffWhenIdle;
/// <summary>
/// Re-cast a self buff when its remaining duration drops below this many seconds.
/// Default 300 (5 minutes). Lower values rebuff more eagerly; very low values
/// (under ~60s) risk recasting between an old buff dropping and the new one
/// landing.
/// </summary>
public int RebuffSecondsRemaining = 300;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
public int BlacklistAttempts = 3;
public int BlacklistTimeoutSec = 30;
/// <summary>
/// Grace after an offensive cast before it's judged a "miss". A cast only
/// counts toward BlacklistAttempts if no damage landed on the target within
/// this window — so blacklisting is driven by confirmed no-damage casts,
/// not wall-clock time / damage-packet latency. Default 1500ms.
/// </summary>
public int BlacklistCastSettleMs = 1500;
/// <summary>
/// Blacklist a target after being engaged with it for this many seconds without
/// dealing any damage. 0 = disabled. Default 60s.
/// </summary>
public int TargetNoProgressTimeoutSec = 0; // 0 = disabled; set to e.g. 120 to blacklist stuck targets
/// <summary>
/// User-configured "never attack" list. Any monster whose name CONTAINS one
/// of these entries (case-insensitive) is excluded from combat target
/// acquisition entirely — never scanned, faced, or attacked. This is a manual
/// do-not-attack list, separate from the automatic no-damage blacklist above.
/// Edited in Advanced → Combat → Monster Blacklist.
/// </summary>
public List<string> MonsterNameBlacklist { get; set; } = new();
public int GiveQueueIntervalMs = 150;
public int SpellCastIntervalMs = 400;
/// <summary>
/// Minimum delay between offensive (war/void) COMBAT spell casts, in ms.
/// Combat magic uses this instead of <see cref="SpellCastIntervalMs"/> so
/// attack pacing can be slowed (~1-2s) without slowing buff chains. Default
/// 1500ms ("a second or two") — spacing offensive casts stops back-to-back
/// "You're too busy!" refusals that drop casts and cost kills. ≤0 ⇒ 1500.
/// </summary>
public int AttackSpellIntervalMs = 1500;
public int MeleeAttackPower = -1;
public int MissileAttackPower = -1;
/// <summary>
/// Physical-attack path. FALSE (default since 2026-09-04) = the direct
/// explicit-target path: Event_TargetedMelee/MissileAttack take the target
/// id as an argument and never touch AC's single selection global
/// (0x00871E54), so combat no longer clobbers the inventory item you have
/// selected. TRUE = AC's native ClientCombatSystem pipeline, which has no
/// target argument and therefore must be preceded by SelectItem(targetId) —
/// that SelectItem was the last selection clobber in the combat hot path.
///
/// This defaulted to true until now for one reason: the direct path does not
/// turn the character to face the monster, and swings/arrows at the wrong
/// heading go nowhere (ExplicitTarget_Combat_Findings_2026-06-03.md §5). The
/// facing servo in CombatManager.OnHeartbeat now covers both melee and
/// missile on the non-native path, which is exactly what that blocker asked
/// for, so the default flips.
///
/// Kept as a setting rather than hard-gated: the servo has not been soaked
/// against a moving target across a long session, and re-ticking this box in
/// the Advanced settings UI restores the old behaviour live, without a
/// rebuild, if the swings look wrong.
/// </summary>
public bool UseNativeAttack = false;
public bool UseRecklessness;
public int MeleeAttackHeight = 1;
public int MissileAttackHeight = 1;
// Projectile arc velocities for missile-weapon LoS checks.
// Lower velocity = higher arc. Must approximate the AC client trajectory
// so dungeon-ceiling hits are detected.
public bool UseArcs = true;
public float BowArcVelocity = 25.0f;
public float CrossbowArcVelocity = 40.0f;
public float AtlatlArcVelocity = 22.0f;
public float MagicArcVelocity = 25.0f;
public bool EnableFPSLimit = true;
public int TargetFPSFocused = 60;
public int TargetFPSBackground = 30;
// Minimum buffed skill level required to cast spells of each tier — for COMBAT casts.
// Defaults are tuned above AC's hard minimums (1/50/100/150/200/250/300/350) to avoid fizzles.
public int MinSkillLevelTier1 = 35;
public int MinSkillLevelTier2 = 85;
public int MinSkillLevelTier3 = 135;
public int MinSkillLevelTier4 = 185;
public int MinSkillLevelTier5 = 235;
public int MinSkillLevelTier6 = 285;
public int MinSkillLevelTier7 = 335;
public int MinSkillLevelTier8 = 435;
// Minimum buffed skill level required to cast self-buffs of each tier.
// Defaults match the spell combat thresholds so new installs work consistently.
public int BuffMinSkillLevelTier1 = 35;
public int BuffMinSkillLevelTier2 = 85;
public int BuffMinSkillLevelTier3 = 135;
public int BuffMinSkillLevelTier4 = 185;
public int BuffMinSkillLevelTier5 = 235;
public int BuffMinSkillLevelTier6 = 285;
public int BuffMinSkillLevelTier7 = 335;
public int BuffMinSkillLevelTier8 = 435;
public bool EnableManaTapping = false;
public int ManaTapMinMana = 2500;
public int ManaStoneKeepCount = 5;
public List<MonsterRule> MonsterRules { get; set; } = new();
public List<ItemRule> ItemRules { get; set; } = new();
public List<ConsumableRule> ConsumableRules { get; set; } = new();
public List<BuffRule> BuffRules { get; set; } = new();
public List<MetaRule> MetaRules { get; set; } = new();
/// <summary>
/// Guards every read/enumerate/mutate of <see cref="MetaRules"/>. The list
/// is touched from the plugin-tick thread (MetaManager.Think) AND the
/// Avalonia dispatcher thread (MetaPanel poll → BuildMetaJson /
/// HandleMetaCommand). List&lt;T&gt; is not thread-safe; concurrent
/// enumerate+mutate corrupts the heap. Hold this lock for the full duration
/// of any MetaRules access.
/// </summary>
[JsonIgnore]
public object MetaRulesLock { get; } = new();
/// <summary>
/// Bumped on an *in-place* rule edit (a slot replaced, possibly changing a
/// rule's State) so MetaManager's per-state index rebuilds. Add/delete/load
/// change the list ref or count and are detected without this.
/// </summary>
[JsonIgnore]
public int MetaRulesStructuralVersion;
private Dictionary<string, List<string>> _embeddedNavs =
new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// NAV routes embedded inside the currently-loaded .af/.met macro,
/// keyed by name. Persisted so meta EmbedNav actions still resolve
/// after a client restart without reloading the source file.
/// Setter re-wraps incoming dict with OrdinalIgnoreCase comparer so
/// JSON round-trip keeps case-insensitive lookups working.
/// </summary>
public Dictionary<string, List<string>> EmbeddedNavs
{
get => _embeddedNavs;
set => _embeddedNavs = value != null
? new Dictionary<string, List<string>>(value, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
}
public string LuaScript = "-- Enter your Lua script here\nprint('RynthAi Lua Loaded')";
[JsonIgnore] public string LuaConsoleOutput = "--- RynthAi Lua Console ---";
public string SelectedProfile = "Default";
[JsonIgnore] public NavRouteParser CurrentRoute { get; set; } = new();
public int ActiveNavIndex;
public bool ShowAdvancedWindow;
public int SelectedAdvancedTab;
// ── Persisted window/UI state ───────────────────────────────────────────
public float WindowPosX = -1f;
public float WindowPosY = -1f;
public float WindowSizeX = 430f;
public float WindowSizeY = 452f;
public bool WindowLocked;
public bool DashboardVisible = true;
public bool DashboardMinimized;
public float BgOpacity = 0.95f;
public bool DashShowWeapons;
public bool DashShowLua;
public bool DashShowNavigation;
public bool DashShowMacroRules;
public bool DashShowMonsters;
public bool DashShowDungeonMap;
public bool MapShowDoors = true;
public bool MapShowCreatures = true;
public bool MapShowToolbar = true;
public float MapBgOpacity = 1.0f;
public bool MapRotateWithPlayer = false;
// Radar dungeon-wall overlay
public bool ShowRadarWalls = false; // WIP — renders as black box, disabled by default
public float RadarWallWorldRange = 35f; // world units shown edge-to-edge on the radar
// When true, the engine suppresses the vanilla retail radar entirely.
public bool SuppressRetailRadar = false;
// When true, the engine no-ops the gmPowerbarUI notices so the vanilla
// attack/magic power bar never appears on screen.
public bool SuppressRetailPowerbar = false;
// Custom chat viewer
public bool ShowRynthChat = false;
public float ChatOpacity = 0.15f;
public int ChatMaxLines = 500;
public bool ChatShowTimestamps = false;
public bool ChatClickThrough = false; // mouse passes through to game; gear stays clickable
// When true, the custom RynthRadar widget is rendered.
public bool ShowRynthRadar = false;
public bool RadarRotateWithPlayer = false; // false = north-up; true = player always faces up
public float RadarOpacity = 0.85f;
public float RadarZoom = 3.5f; // pixels per world unit
public bool RadarShowMonsters = true;
public bool RadarShowNpcs = true;
public bool RadarShowPortals = true;
public bool RadarShowDoors = true;
// Grid-cell radius (0.5m per cell) of the "visited" paint stamp placed each
// frame around the player. Higher = walls light up from further away.
public int RadarWallPaintRadius = 3;
public bool RadarCircular = false; // false = square frame, true = circular
public bool RadarClickThrough = false; // mouse passes through to the game
// Persisted radar window placement. -1 = never saved; the first session
// applies the default size and captures the position once it's shown.
public float RadarPosX = -1f;
public float RadarPosY = -1f;
public float RadarSizeX = 260f;
public float RadarSizeY = 284f;
[JsonIgnore]
public readonly string[] AdvancedTabs =
{
"Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
"Ranges", "Navigation", "Buffing", "Crafting", "Looting"
};
[JsonIgnore]
public bool ForceStateReset { get; set; }
[JsonIgnore]
public string NavStatusLine = string.Empty;
[JsonIgnore]
public bool NavIsStuck = false;
// Runtime-only: the object id of the portal/NPC the nav engine is actively
// using (resolved by FirePortalNpcUse), or 0 when not using one. Lets the
// marker renderer draw a ring + line to the portal's REAL position, since
// the PortalNPC waypoint's stored coordinate is an unreliable placeholder.
[JsonIgnore]
public uint ActivePortalObjId = 0;
// Fellowship-follow: when on, nav steers toward the live target instead of a
// route. Runtime-only (off each session; enable via /ra follow on).
[JsonIgnore]
public bool FollowMode = false;
// Resolved object id of the follow target (the fellowship leader), published
// by the plugin each tick; 0 when not in a fellowship / target not loaded.
[JsonIgnore]
public uint FollowTargetId = 0;
public LegacyUiSettings()
{
}
public void EnsureDefaultRule()
{
List<MonsterRule> existingDefaults = MonsterRules.Where(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)).ToList();
MonsterRule trueDefault;
if (existingDefaults.Count > 0)
{
trueDefault = existingDefaults[0];
MonsterRules.RemoveAll(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
}
else
{
trueDefault = new MonsterRule { Name = "Default", Priority = 1, DamageType = "Auto", WeaponId = 0 };
}
MonsterRules.Insert(0, trueDefault);
}
}
public sealed class MonsterRule
{
public string Name { get; set; } = "New Monster";
public string Category { get; set; } = "";
public string MatchExpression { get; set; } = "";
public int Priority { get; set; } = 1;
public string DamageType { get; set; } = "Auto";
public int WeaponId { get; set; }
public bool Fester { get; set; }
public bool Broadside { get; set; }
public bool GravityWell { get; set; }
public bool Imperil { get; set; }
public bool Yield { get; set; }
public bool Vuln { get; set; }
public bool UseArc { get; set; }
public bool UseRing { get; set; }
public bool UseStreak { get; set; }
public bool UseBolt { get; set; } = true;
public string ExVuln { get; set; } = "None";
public int OffhandId { get; set; }
public string PetDamage { get; set; } = "PAuto";
}
public sealed class BuffRule
{
public string SpellName { get; set; } = string.Empty;
public int SpellId { get; set; }
public bool Enabled { get; set; } = true;
}
public sealed class ItemRule
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Action { get; set; } = "Loot";
public string Element { get; set; } = "Slash";
public bool KeepBuffed { get; set; } = true;
}
/// <summary>JSON wire-format types used by the engine-side Avalonia MonstersPanel.</summary>
public sealed class MonstersBridgePayload
{
public List<MonsterRule> Rules { get; set; } = new();
public List<MonsterBridgeItem> Items { get; set; } = new();
public string CurrentTargetName { get; set; } = string.Empty;
/// <summary>Captured creature data per rule name (uppercased), filled by the plugin.</summary>
public Dictionary<string, MonsterCapturedInfo> Captured { get; set; } = new();
}
public sealed class MonsterBridgeItem
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public sealed class MonsterCapturedInfo
{
public uint MaxHealth { get; set; }
public int ArmorLevel { get; set; }
public string WeakestType { get; set; } = string.Empty;
public double WeakestValue { get; set; } = 1.0;
public int Samples { get; set; }
}
public sealed class ConsumableRule
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Type { get; set; } = "General";
}
/// <summary>Bridge payload for the engine-side Avalonia ItemsPanel.</summary>
public sealed class ItemsBridgePayload
{
public List<ItemRule> Weapons { get; set; } = new();
public List<ConsumableRule> Consumables { get; set; } = new();
public bool EnableManaTapping { get; set; }
public int ManaTapMinMana { get; set; }
public int ManaStoneKeepCount { get; set; }
public string CurrentTargetName { get; set; } = string.Empty;
}
// ── Nav bridge types ─────────────────────────────────────────────────────────
public sealed class NavBridgePoint
{
public int Idx { get; set; }
public string Type { get; set; } = string.Empty; // "Point", "Recall", "Pause", "Chat", "PortalNPC"
public string Desc { get; set; } = string.Empty; // NavPoint.ToString()
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
}
public sealed class NavBridgePayload
{
public string ActiveNavName { get; set; } = string.Empty;
public string NavStatusLine { get; set; } = string.Empty;
public bool NavIsStuck { get; set; }
public bool MacroRunning { get; set; }
public bool NavigationEnabled{ get; set; }
public int RouteType { get; set; } // 1=Circular,2=Linear,3=Follow,4=Once
public int ActiveNavIndex { get; set; }
public List<string> NavFiles { get; set; } = new();
public List<NavBridgePoint> Points { get; set; } = new();
}
/// <summary>One-shot command sent from the Avalonia NavPanel to the plugin.</summary>
public sealed class NavCommand
{
public string Cmd { get; set; } = string.Empty;
public int SpellId { get; set; }
public int Index { get; set; }
public int RouteType { get; set; }
public int AddMode { get; set; } // 0=End, 1=Above, 2=Below
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
}
/// <summary>Bridge payload for the engine-side Avalonia SettingsPanel.</summary>
public sealed class SettingsBridgePayload
{
// Display
public bool ShowTargetStaminaMana { get; set; }
// UI
public bool SuppressRetailRadar { get; set; }
public bool ShowRynthRadar { get; set; }
public bool RadarClickThrough { get; set; }
public bool ShowRynthChat { get; set; }
public bool ChatClickThrough { get; set; }
public bool SuppressRetailPowerbar { get; set; }
// Misc
public bool EnableFPSLimit { get; set; }
public int TargetFPSFocused { get; set; }
public int TargetFPSBackground { get; set; }
public bool EnableAutocram { get; set; }
public bool PeaceModeWhenIdle { get; set; }
public bool StartMacroOnLogin { get; set; }
public bool PatrolOnLogin { get; set; }
public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; }
public float CrossbowArcVelocity { get; set; }
public float AtlatlArcVelocity { get; set; }
public float MagicArcVelocity { get; set; }
public int BlacklistAttempts { get; set; }
public int BlacklistTimeoutSec { get; set; }
public int BlacklistCastSettleMs { get; set; }
public int TargetNoProgressTimeoutSec { get; set; }
public int GiveQueueIntervalMs { get; set; }
// Recharge
public int HealAt { get; set; }
public int RestamAt { get; set; }
public int GetManaAt { get; set; }
public int TopOffHP { get; set; }
public int TopOffStam { get; set; }
public int TopOffMana { get; set; }
public int HealOthersAt { get; set; }
public int RestamOthersAt { get; set; }
public int InfuseOthersAt { get; set; }
// Melee Combat
public bool UseRecklessness { get; set; }
public int MeleeAttackPower { get; set; }
public int MeleeAttackHeight { get; set; }
public int MissileAttackPower { get; set; }
public int MissileAttackHeight { get; set; }
public bool UseNativeAttack { get; set; }
public bool SummonPets { get; set; }
public int PetMinMonsters { get; set; }
// Spell Combat
public int SpellCastIntervalMs { get; set; }
public int AttackSpellIntervalMs { get; set; }
public bool CastDispelSelf { get; set; }
public int MinRingTargets { get; set; }
public int MinSkillLevelTier1 { get; set; }
public int MinSkillLevelTier2 { get; set; }
public int MinSkillLevelTier3 { get; set; }
public int MinSkillLevelTier4 { get; set; }
public int MinSkillLevelTier5 { get; set; }
public int MinSkillLevelTier6 { get; set; }
public int MinSkillLevelTier7 { get; set; }
public int MinSkillLevelTier8 { get; set; }
// Ranges
public int MonsterRange { get; set; }
public int MonsterDisengageRange { get; set; }
public int RingRange { get; set; }
public int ApproachRange { get; set; }
public double CorpseApproachRangeMax { get; set; }
public double CorpseApproachRangeMin { get; set; }
// Navigation
public bool BoostNavPriority { get; set; }
public float FollowNavMin { get; set; }
public float NavRingThickness { get; set; }
public float NavLineThickness { get; set; }
public float NavHeightOffset { get; set; }
public float NavSlopeSink { get; set; }
public bool ShowTerrainPassability { get; set; }
public bool OpenDoors { get; set; }
public float OpenDoorRange { get; set; }
public bool AutoUnlockDoors { get; set; }
public int MovementMode { get; set; }
public float NavStopTurnAngle { get; set; }
public float NavResumeTurnAngle { get; set; }
public float NavDeadZone { get; set; }
public float NavSweepMult { get; set; }
public float NavLookaheadYards { get; set; }
public float NavTurnRateDegPerSec { get; set; }
public float NavTier1TurnSpeed { get; set; }
public float PostPortalDelaySec { get; set; }
public float T2Speed { get; set; }
public float T2WalkWithinYd { get; set; }
public float T2DistanceTo { get; set; }
public float T2ReissueMs { get; set; }
public float T2MaxRangeYd { get; set; }
public int T2MaxLandblocks { get; set; }
// Buffing
public bool EnableBuffing { get; set; }
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; }
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
public int BuffMinSkillLevelTier4 { get; set; }
public int BuffMinSkillLevelTier5 { get; set; }
public int BuffMinSkillLevelTier6 { get; set; }
public int BuffMinSkillLevelTier7 { get; set; }
public int BuffMinSkillLevelTier8 { get; set; }
// Crafting (read-only state)
public bool EnableMissileCrafting { get; set; }
public string MissileCraftingState { get; set; } = string.Empty;
public bool MissileCraftingActive { get; set; }
public string MissileCraftingStatus { get; set; } = string.Empty;
// Looting
public bool EnableLooting { get; set; }
public bool BoostLootPriority { get; set; }
public bool LootOnlyRareCorpses { get; set; }
public bool LootJumpEnabled { get; set; }
public int LootJumpHeight { get; set; }
public int LootOwnership { get; set; }
public bool EnableAutostack { get; set; }
public bool EnableCombineSalvage { get; set; }
public bool CombineBagsDuringSalvage { get; set; }
public int LootInterItemDelayMs { get; set; }
public int LootContentSettleMs { get; set; }
public int LootEmptyCorpseMs { get; set; }
public int LootClosingDelayMs { get; set; }
public int LootAssessWindowMs { get; set; }
public int LootRetryTimeoutMs { get; set; }
public int LootOpenRetryMs { get; set; }
public int LootCorpseTimeoutMs { get; set; }
public int SalvageOpenDelayFirstMs { get; set; }
public int SalvageOpenDelayFastMs { get; set; }
public int SalvageAddDelayFirstMs { get; set; }
public int SalvageAddDelayFastMs { get; set; }
public int SalvageSalvageDelayMs { get; set; }
public int SalvageResultDelayFirstMs { get; set; }
public int SalvageResultDelayFastMs { get; set; }
}
public enum MetaConditionType
{
Never,
Always,
All,
Any,
ChatMessage,
PackSlots_LE,
SecondsInState_GE,
CharacterDeath,
AnyVendorOpen,
VendorClosed,
InventoryItemCount_LE,
InventoryItemCount_GE,
MonsterNameCountWithinDistance,
MonsterPriorityCountWithinDistance,
NeedToBuff,
NoMonstersWithinDistance,
Landblock_EQ,
Landcell_EQ,
PortalspaceEntered,
PortalspaceExited,
Not,
SecondsInStateP_GE,
TimeLeftOnSpell_GE,
TimeLeftOnSpell_LE,
BurdenPercentage_GE,
DistAnyRoutePT_GE,
Expression,
ChatMessageCapture,
NavrouteEmpty,
MainHealthLE,
MainHealthPHE,
MainManaLE,
MainManaPHE,
MainStamLE,
VitaePHE
}
public enum MetaActionType
{
None,
ChatCommand,
SetMetaState,
EmbeddedNavRoute,
All,
CallMetaState,
ReturnFromCall,
ExpressionAction,
ChatExpression,
SetWatchdog,
ClearWatchdog,
GetRAOption,
SetRAOption,
CreateView,
DestroyView,
DestroyAllViews
}
public sealed class MetaRule
{
public string State { get; set; } = "Default";
public MetaConditionType Condition { get; set; }
public string ConditionData { get; set; } = string.Empty;
public MetaActionType Action { get; set; }
public string ActionData { get; set; } = string.Empty;
public List<MetaRule> Children { get; set; } = new();
public List<MetaRule> ActionChildren { get; set; } = new();
/// <summary>Disabled rules are excluded from the per-state index so they
/// never evaluate. Default true; missing in old JSON/.af → stays true
/// (the property initializer runs, so backward-compatible).</summary>
public bool Enabled { get; set; } = true;
[JsonIgnore]
public bool HasFired { get; set; }
/// <summary>Last time this rule's action executed — drives the red-flash UI.</summary>
[JsonIgnore]
public DateTime LastFiredAt { get; set; } = DateTime.MinValue;
}

View file

@ -0,0 +1,323 @@
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyWeaponsUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
private WorldObjectCache? _worldFilter;
private static readonly string[] Elements =
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly string[] ConsumableTypes =
{ "General", "Lockpick", "HealthKit", "ManaStone", "Stamina", "Pet" };
public LegacyWeaponsUi(LegacyUiSettings settings, RynthCoreHost host)
{
_settings = settings;
_host = host;
}
public void SetWorldFilter(WorldObjectCache cache) => _worldFilter = cache;
public void Render()
{
if (!DashWindows.ShowWeapons) return;
ImGui.SetNextWindowSize(new Vector2(480, 440), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Items##RynthAiWeapons", ref DashWindows.ShowWeapons))
{
ImGui.End();
return;
}
// ── Weapons Section ─────────────────────────────────────────────────
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Weapons");
ImGui.Spacing();
if (ImGui.BeginTable("WeaponsTable", 3,
ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable))
{
ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Element", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 50);
ImGui.TableHeadersRow();
for (int i = 0; i < _settings.ItemRules.Count; i++)
{
var rule = _settings.ItemRules[i];
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool inCache = _worldFilter?[rule.Id] != null;
if (inCache)
{
ImGui.TextUnformatted(rule.Name);
}
else
{
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 1f), rule.Name);
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 0.7f), "(Gone)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Item not in inventory.\nRemove and re-add the correct weapon.");
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int elemIdx = Array.IndexOf(Elements, rule.Element);
if (elemIdx < 0) elemIdx = 0;
if (ImGui.Combo($"##Elem{i}", ref elemIdx, Elements, Elements.Length))
rule.Element = Elements[elemIdx];
ImGui.TableNextColumn();
if (ImGui.SmallButton($"Del##w{i}"))
{
foreach (var mr in _settings.MonsterRules)
if (mr.WeaponId == rule.Id) mr.WeaponId = 0;
_settings.ItemRules.RemoveAt(i);
ImGui.EndTable();
ImGui.End();
return;
}
}
ImGui.EndTable();
}
bool canAdd = _host.HasGetSelectedItemId;
if (!canAdd) ImGui.BeginDisabled();
if (ImGui.Button("Add Selected Weapon", new Vector2(160, 24)))
{
AddSelectedWeapon();
}
if (!canAdd) ImGui.EndDisabled();
ImGui.SameLine();
ImGui.TextDisabled("(Click a weapon in inventory first)");
// ── Consumable Items Section ────────────────────────────────────────
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Consumable Items");
ImGui.Spacing();
if (ImGui.BeginTable("ConsumablesTable", 3,
ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable))
{
ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 50);
ImGui.TableHeadersRow();
for (int i = 0; i < _settings.ConsumableRules.Count; i++)
{
var rule = _settings.ConsumableRules[i];
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool inCache = _worldFilter?[rule.Id] != null;
if (inCache)
{
ImGui.TextUnformatted(rule.Name);
}
else
{
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 1f), rule.Name);
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 0.7f), "(Gone)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Item not in inventory.\nRemove and re-add the correct item.");
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int typeIdx = Array.IndexOf(ConsumableTypes, rule.Type);
if (typeIdx < 0) typeIdx = 0;
if (ImGui.Combo($"##CType{i}", ref typeIdx, ConsumableTypes, ConsumableTypes.Length))
rule.Type = ConsumableTypes[typeIdx];
ImGui.TableNextColumn();
if (ImGui.SmallButton($"Del##c{i}"))
{
_settings.ConsumableRules.RemoveAt(i);
ImGui.EndTable();
ImGui.End();
return;
}
}
ImGui.EndTable();
}
if (!canAdd) ImGui.BeginDisabled();
if (ImGui.Button("Add Selected Consumable", new Vector2(180, 24)))
{
AddSelectedConsumable();
}
if (!canAdd) ImGui.EndDisabled();
ImGui.SameLine();
ImGui.TextDisabled("(Click an item in inventory first)");
// ── Mana Stone Tapping ──────────────────────────────────────────────
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Mana Stone Tapping");
ImGui.Spacing();
ImGui.Text("Keep up to:");
ImGui.SameLine();
ImGui.SetNextItemWidth(70);
ImGui.DragInt("##StoneKeep", ref _settings.ManaStoneKeepCount, 0.2f, 1, 999);
if (_settings.ManaStoneKeepCount < 1) _settings.ManaStoneKeepCount = 1;
if (_settings.ManaStoneKeepCount > 999) _settings.ManaStoneKeepCount = 999;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Maximum number of mana stones to keep in inventory.\nStones on corpses are skipped once this count is reached.");
ImGui.SameLine(0, 16);
ImGui.Checkbox("Enable Tapping", ref _settings.EnableManaTapping);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Use mana stones on inventory items with high MaxMana,\nthen apply the charged stone to the player to recharge gear.");
if (_settings.EnableManaTapping)
{
ImGui.SameLine(0, 16);
ImGui.Text("Min MaxMana:");
ImGui.SameLine();
ImGui.SetNextItemWidth(90);
ImGui.DragInt("##TapThresh", ref _settings.ManaTapMinMana, 50f, 100, 99999);
if (_settings.ManaTapMinMana < 100) _settings.ManaTapMinMana = 100;
if (_settings.ManaTapMinMana > 99999) _settings.ManaTapMinMana = 99999;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Only tap items whose MaxMana is at or above this value.");
}
ImGui.End();
}
public void AddSelectedWeapon()
{
uint selId = _host.GetSelectedItemId();
if (selId == 0)
{
_host.WriteToChat("[RynthAi] No item selected — click a weapon in your inventory first.", 1);
return;
}
if (_worldFilter == null) { _host.WriteToChat("[RynthAi] Object cache not ready.", 1); return; }
var wo = _worldFilter[(int)selId];
if (wo == null)
_host.WriteToChat($"[RynthAi] Item 0x{selId:X8} not in cache — try again.", 1);
else if (!IsWeapon(wo))
_host.WriteToChat("[RynthAi] Selected item is not a weapon or wand.", 1);
else if (_settings.ItemRules.Any(x => x.Id == wo.Id))
_host.WriteToChat($"[RynthAi] {wo.Name} is already in the list.", 1);
else
{
string element = DetectWeaponElement(wo);
_settings.ItemRules.Add(new ItemRule
{
Id = wo.Id,
Name = wo.Name,
Element = element,
Action = "Weapon",
});
_host.WriteToChat($"[RynthAi] Added weapon: {wo.Name} (0x{(uint)wo.Id:X8}) [{element}]", 1);
}
}
public void AddSelectedConsumable()
{
uint selId = _host.GetSelectedItemId();
if (selId == 0)
{
_host.WriteToChat("[RynthAi] No item selected — click an item in your inventory first.", 1);
return;
}
if (_worldFilter == null) { _host.WriteToChat("[RynthAi] Object cache not ready.", 1); return; }
var wo = _worldFilter[(int)selId];
if (wo == null)
_host.WriteToChat($"[RynthAi] Item 0x{selId:X8} not in cache — try again.", 1);
else if (_settings.ConsumableRules.Any(x => x.Id == wo.Id))
_host.WriteToChat($"[RynthAi] {wo.Name} is already in the list.", 1);
else
{
string type = DetectConsumableType(wo);
_settings.ConsumableRules.Add(new ConsumableRule
{
Id = wo.Id,
Name = wo.Name,
Type = type,
});
_host.WriteToChat($"[RynthAi] Added consumable: {wo.Name} (0x{(uint)wo.Id:X8}) [{type}]", 1);
}
}
private static bool IsWeapon(WorldObject wo) =>
wo.ObjectClass == AcObjectClass.MeleeWeapon ||
wo.ObjectClass == AcObjectClass.MissileWeapon ||
wo.ObjectClass == AcObjectClass.WandStaffOrb;
/// <summary>Auto-detect weapon element from the DamageType int property.</summary>
private static string DetectWeaponElement(WorldObject wo)
{
// DamageType (STypeInt 45) — AC damage type flags
int dt = wo.Values(LongValueKey.DamageType, 0);
if (dt == 0) return "Slash"; // no data — default
// Check flags in order of specificity (elemental first, then physical)
if ((dt & 1024) != 0) return "Nether";
if ((dt & 16) != 0) return "Fire";
if ((dt & 8) != 0) return "Cold";
if ((dt & 64) != 0) return "Lightning";
if ((dt & 32) != 0) return "Acid";
if ((dt & 1) != 0) return "Slash";
if ((dt & 2) != 0) return "Pierce";
if ((dt & 4) != 0) return "Bludgeon";
return "Slash";
}
/// <summary>Auto-detect consumable type from item name.</summary>
private static string DetectConsumableType(WorldObject wo)
{
string name = wo.Name;
if (string.IsNullOrEmpty(name)) return "General";
// Health items
if (name.Contains("Heal", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Health", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Elixir of Healing", StringComparison.OrdinalIgnoreCase))
return "HealthKit";
// Mana items
if (name.Contains("Mana", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase))
return "ManaStone";
// Stamina items
if (name.Contains("Stamina", StringComparison.OrdinalIgnoreCase))
return "Stamina";
// Lockpicks
if (name.Contains("Lockpick", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Lock Pick", StringComparison.OrdinalIgnoreCase))
return "Lockpick";
// Combat-pet summoning essences (PetDevices) — consumed by PetManager.
if (name.Contains("Essence", StringComparison.OrdinalIgnoreCase))
return "Pet";
return "General";
}
}

View file

@ -0,0 +1,25 @@
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class MetaRuleDto
{
public string State { get; set; } = "Default";
public int Condition { get; set; }
public string ConditionData { get; set; } = string.Empty;
public int Action { get; set; }
public string ActionData { get; set; } = string.Empty;
public List<MetaRuleDto> Children { get; set; } = new();
public List<MetaRuleDto> ActionChildren { get; set; } = new();
public bool Enabled { get; set; } = true;
}
internal sealed class MetaCommand
{
public string Op { get; set; } = string.Empty;
public int Index { get; set; } = -1;
public string Value { get; set; } = string.Empty;
public string Path { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
public MetaRuleDto? Rule { get; set; }
}

View file

@ -0,0 +1,42 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal static class NavCoordinateHelper
{
public static bool TryGetNavCoords(RynthCoreHost host, out double northSouth, out double eastWest)
{
northSouth = 0;
eastWest = 0;
if (host.TryGetCurCoords(out northSouth, out eastWest))
return true;
if (host.TryGetPlayerPose(out uint fallbackCellId, out float fallbackX, out float fallbackY, out _, out _, out _, out _, out _))
return TryConvertPoseToCoords(fallbackCellId, fallbackX, fallbackY, out northSouth, out eastWest);
return false;
}
internal static bool TryConvertPoseToCoords(uint objCellId, float x, float y, out double northSouth, out double eastWest)
{
northSouth = 0;
eastWest = 0;
uint landblock = objCellId >> 16;
if (landblock == 0)
return false;
int lbX = (int)((objCellId >> 24) & 0xFF);
int lbY = (int)((objCellId >> 16) & 0xFF);
// Match the classic radar/Coordinates() basis exactly:
// EW = ((Landcell >> 24) * 8 + X / 24 - 1019.5) / 10
// NS = (((Landcell >> 16) & 0xFF) * 8 + Y / 24 - 1019.5) / 10
eastWest = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
northSouth = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
return !double.IsNaN(northSouth) && !double.IsNaN(eastWest) &&
!double.IsInfinity(northSouth) && !double.IsInfinity(eastWest);
}
}

View file

@ -0,0 +1,262 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
public enum NavRouteType
{
Circular = 1,
Linear = 2,
Follow = 3,
Once = 4
}
// Waypoint types as serialized by uTank2 / VirindiTank ".nav" files. Trailer
// layouts below were reverse-engineered from 933 real VTank routes (2026-06-15);
// see Docs/Nav_DeepDive_2026-06-15.md. Type 1 (plain Portal) and any other type
// are intentionally absent — they never appear in real routes here and would
// need their on-disk layout confirmed before being parsed.
public enum NavPointType
{
Point = 0,
Recall = 2, // trailer: spellId
Pause = 3, // trailer: pauseMs
Chat = 4, // trailer: command string
OpenVendor = 5, // trailer: vendorId(int), vendorName(string)
PortalNPC = 6, // VTank "Portal": use a portal object by name. trailer: name, class, tie, ew, ns, z
Npc = 7 // VTank "NPC": use/talk an NPC by name. trailer: name, class, tie, ew, ns, z
}
public sealed class NavPoint
{
public NavPointType Type { get; set; }
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
public int SpellId { get; set; }
public int PauseTimeMs { get; set; }
public string ChatCommand { get; set; } = string.Empty;
// Portal (6) / Npc (7) target name; for OpenVendor (5) the vendor's name.
public string TargetName { get; set; } = string.Empty;
public int ObjectClass { get; set; }
public bool IsTie { get; set; }
// OpenVendor (5): the captured vendor object id from the route.
public uint VendorId { get; set; }
// Portal/Npc (6/7): the captured world location of the portal/NPC object,
// usable to disambiguate same-named objects. Stored in the legacy
// PortalExit* fields so existing references keep compiling.
public double PortalExitNS { get; set; }
public double PortalExitEW { get; set; }
public double PortalExitZ { get; set; }
// Retained for source compatibility only; no longer read or written (real
// VTank Portal waypoints carry one object location, not exit+land coords).
public double PortalLandNS { get; set; }
public double PortalLandEW { get; set; }
public double PortalLandZ { get; set; }
public override string ToString()
{
return Type switch
{
NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}",
NavPointType.Recall => $"[Recall] Spell {SpellId}",
NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0:F1}s",
NavPointType.Chat => $"[Chat] {ChatCommand}",
NavPointType.OpenVendor => $"[Vendor] {TargetName}",
NavPointType.PortalNPC => $"[Portal] {TargetName}",
NavPointType.Npc => $"[NPC] {TargetName}",
_ => $"[Unknown] {(int)Type}"
};
}
}
public sealed class NavRouteParser
{
public NavRouteType RouteType { get; set; }
public List<NavPoint> Points { get; set; } = new();
/// <summary>
/// Non-null if the last load hit an unknown waypoint type or a malformed
/// line. The route still holds whatever points parsed cleanly before that.
/// </summary>
public string? LoadWarning { get; private set; }
/// <summary>
/// Trailer line count (lines AFTER the 5-line type/EW/NS/Z/flag prologue)
/// for each known waypoint type. Single source of truth so the parser and
/// any external line-counter (e.g. AfFileParser) cannot drift apart — the
/// drift between the two is what corrupted Portal routes pre-2026-06-15.
/// </summary>
public static int TrailerLineCount(NavPointType t) => t switch
{
NavPointType.Recall => 1,
NavPointType.Pause => 1,
NavPointType.Chat => 1,
NavPointType.OpenVendor => 2,
NavPointType.PortalNPC => 6,
NavPointType.Npc => 6,
_ => 0 // Point (and any zero-trailer type)
};
public static bool IsKnownType(int t) =>
t is 0 or 2 or 3 or 4 or 5 or 6 or 7;
public static NavRouteParser Load(string filePath, Action<string>? warn = null)
{
try
{
if (!File.Exists(filePath))
return new NavRouteParser();
return LoadFromLines(File.ReadAllLines(filePath), warn);
}
catch (Exception ex)
{
var route = new NavRouteParser { LoadWarning = $"Nav: failed to read '{filePath}': {ex.Message}" };
warn?.Invoke(route.LoadWarning);
return route;
}
}
public static NavRouteParser LoadFromLines(IList<string> lines, Action<string>? warn = null)
{
var route = new NavRouteParser();
if (lines.Count < 3 || !lines[0].Contains("uTank2 NAV 1.2", StringComparison.OrdinalIgnoreCase))
return route;
if (!int.TryParse(lines[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int routeType) ||
!int.TryParse(lines[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int pointCount))
{
route.LoadWarning = "Nav: malformed header (route-type / point-count not integers)";
warn?.Invoke(route.LoadWarning);
return route;
}
route.RouteType = (NavRouteType)routeType;
int idx = 3;
for (int i = 0; i < pointCount && idx < lines.Count; i++)
{
// Each point spans several lines. Localize any parse failure to this
// single point so one bad/unknown waypoint cannot desync and corrupt
// every following waypoint in the file.
int pointStart = idx;
try
{
int typeRaw = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
if (!IsKnownType(typeRaw))
{
route.LoadWarning =
$"Nav: unknown waypoint type {typeRaw} at point {i + 1} (line {pointStart}); " +
$"stopped to avoid desync ({route.Points.Count} pts loaded). " +
"Report this type so support can be added.";
warn?.Invoke(route.LoadWarning);
break;
}
var pt = new NavPoint
{
Type = (NavPointType)typeRaw,
EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture)
};
idx++; // skip the flag / colour line
switch (pt.Type)
{
case NavPointType.Recall:
pt.SpellId = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
break;
case NavPointType.Pause:
pt.PauseTimeMs = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
break;
case NavPointType.Chat:
pt.ChatCommand = lines[idx++];
break;
case NavPointType.OpenVendor:
pt.VendorId = uint.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.TargetName = lines[idx++];
break;
case NavPointType.PortalNPC:
case NavPointType.Npc:
pt.TargetName = lines[idx++];
pt.ObjectClass = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.IsTie = ParseTieFlag(lines[idx++]);
pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
break;
}
route.Points.Add(pt);
}
catch (Exception ex)
{
route.LoadWarning =
$"Nav: parse error at point {i + 1} (line {pointStart}): {ex.Message}; " +
$"stopped ({route.Points.Count} pts loaded)";
warn?.Invoke(route.LoadWarning);
break;
}
}
return route;
}
private static bool ParseTieFlag(string s)
{
if (bool.TryParse(s, out bool b)) return b; // "True"/"False" (VTank wire format)
return s != null && s.Trim() == "1"; // tolerate numeric tie flags
}
public void Save(string filePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath) ?? ".");
using var writer = new StreamWriter(filePath, false);
writer.WriteLine("uTank2 NAV 1.2");
writer.WriteLine((int)RouteType);
writer.WriteLine(Points.Count);
foreach (NavPoint point in Points)
{
writer.WriteLine((int)point.Type);
writer.WriteLine(point.EW.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.NS.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.Z.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("0");
switch (point.Type)
{
case NavPointType.Recall:
writer.WriteLine(point.SpellId);
break;
case NavPointType.Pause:
writer.WriteLine(point.PauseTimeMs);
break;
case NavPointType.Chat:
writer.WriteLine(point.ChatCommand);
break;
case NavPointType.OpenVendor:
writer.WriteLine(point.VendorId.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.TargetName);
break;
case NavPointType.PortalNPC:
case NavPointType.Npc:
writer.WriteLine(point.TargetName);
writer.WriteLine(point.ObjectClass.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.IsTie ? "True" : "False");
writer.WriteLine(point.PortalExitEW.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.PortalExitNS.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.PortalExitZ.ToString(CultureInfo.InvariantCulture));
break;
}
}
}
}

View file

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
// DTOs polled by the engine-side Avalonia radar panel. Geometry (walls/fills)
// is only emitted when the engine's cached MapVersion (= landblock id) differs
// from the live one, so the steady-state payload is small.
//
// Coordinate convention: world-space landblock coords (px + (lb>>8 & 0xFF)*192,
// py + (lb & 0xFF)*192). The engine projects to screen using player pose +
// zoom + heading.
internal sealed class RadarSnapshotPayload
{
[JsonPropertyName("mapVersion")] public uint MapVersion { get; set; }
[JsonPropertyName("geometryIncluded")] public bool GeometryIncluded { get; set; }
[JsonPropertyName("isIndoor")] public bool IsIndoor { get; set; }
[JsonPropertyName("player")] public RadarPlayer Player { get; set; } = new();
// AC NS/EW (positive = N/E). Only meaningful outdoors; indoor renders the
// landblock id instead. Set to NaN when the host can't resolve them.
[JsonPropertyName("ns")] public double Ns { get; set; } = double.NaN;
[JsonPropertyName("ew")] public double Ew { get; set; } = double.NaN;
[JsonPropertyName("layerZs")] public List<float> LayerZs { get; set; } = new();
[JsonPropertyName("currentLayerZ")] public float CurrentLayerZ { get; set; }
// Per-layer wall segments. Flattened: ax, ay, bx, by, gx, gy × N (6 floats/seg).
[JsonPropertyName("walls")] public List<RadarWallLayer> Walls { get; set; } = new();
// Fallback floor strips when no baked texture exists. x0, y0, x1, y1, type × N.
[JsonPropertyName("fills")] public List<RadarFillLayer> Fills { get; set; } = new();
// Per-layer pre-merged visited floor strips. x0, y0, x1, y1 × N.
[JsonPropertyName("visited")] public List<RadarVisitedLayer> Visited { get; set; } = new();
// All marker kinds included; engine filters by user setting.
[JsonPropertyName("markers")] public List<RadarMarker> Markers { get; set; } = new();
}
internal sealed class RadarPlayer
{
[JsonPropertyName("cellId")] public uint CellId { get; set; }
[JsonPropertyName("landblock")] public uint Landblock { get; set; }
[JsonPropertyName("x")] public float X { get; set; } // landblock-local
[JsonPropertyName("y")] public float Y { get; set; }
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("worldX")] public float WorldX { get; set; } // global (px + lb*192)
[JsonPropertyName("worldY")] public float WorldY { get; set; }
[JsonPropertyName("heading")] public float Heading { get; set; } // degrees, AC convention
}
internal sealed class RadarWallLayer
{
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("segments")] public float[] Segments { get; set; } = Array.Empty<float>();
}
internal sealed class RadarFillLayer
{
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
}
internal sealed class RadarVisitedLayer
{
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
}
// Kind: 0 = monster, 1 = npc, 2 = portal, 3 = door
internal sealed class RadarMarker
{
[JsonPropertyName("kind")] public byte Kind { get; set; }
[JsonPropertyName("x")] public float X { get; set; } // world-space
[JsonPropertyName("y")] public float Y { get; set; }
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("label")] public string? Label { get; set; }
}
[JsonSerializable(typeof(RadarSnapshotPayload))]
[JsonSourceGenerationOptions(WriteIndented = false)]
internal partial class RadarSnapshotJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,23 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
[JsonSerializable(typeof(LegacyUiSettings))]
[JsonSerializable(typeof(List<MonsterRule>), TypeInfoPropertyName = "MonsterRuleList")]
[JsonSerializable(typeof(List<ConsumableRule>), TypeInfoPropertyName = "ConsumableRuleList")]
[JsonSerializable(typeof(Dictionary<string, CreatureProfile>), TypeInfoPropertyName = "CreatureProfileDict")]
[JsonSerializable(typeof(MonstersBridgePayload))]
[JsonSerializable(typeof(SettingsBridgePayload))]
[JsonSerializable(typeof(NavBridgePayload))]
[JsonSerializable(typeof(ItemsBridgePayload))]
[JsonSerializable(typeof(NavCommand))]
[JsonSerializable(typeof(MetaRuleDto))]
[JsonSerializable(typeof(MetaCommand))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,
PropertyNameCaseInsensitive = true)]
internal partial class RynthAiJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,395 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// RynthChat — viewer for incoming chat lines. Subscribes to the plugin's
/// OnChatWindowText handler (via Push). The retail chatbox can be hidden via
/// SuppressRetailChat while AC's chat input/command pipeline still works in the
/// background — typed commands and tells continue to function unchanged.
/// </summary>
internal sealed class RynthChatUi
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly object _lock = new();
private readonly List<ChatLine> _lines = new(512);
private bool _open = true;
private bool _wantScrollToBottom = true;
private bool _prevLDown;
private bool _prevRDown;
// Input field state — Enter outside any widget focuses the input,
// Enter inside the input submits, Esc clears the buffer. The input row
// is always rendered so the scrollback area has a stable layout.
private bool _focusInputNextFrame;
private bool _swallowFirstEnter;
private string _inputBuffer = string.Empty;
public Action? OnSettingChanged { get; set; }
/// <summary>
/// Routes a submitted line. Set by the plugin so /ra, /mt, /ub etc. can be
/// handled locally by OnChatBarEnter before falling back to InvokeChatParser.
/// Without this, plugin slash commands would be keyboard-simulated into the
/// (invisible) retail chatbar — unreliable with ImGui focus in the picture.
/// </summary>
public Action<string>? OnSubmit { get; set; }
public RynthChatUi(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
_settings = settings;
}
private readonly record struct ChatLine(string Text, int ChatType, DateTime At);
/// <summary>Append a chat line (called from RynthAiPlugin.OnChatWindowText).</summary>
public void Push(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return;
lock (_lock)
{
_lines.Add(new ChatLine(text, chatType, DateTime.Now));
int max = Math.Max(50, _settings.ChatMaxLines);
int overflow = _lines.Count - max;
if (overflow > 0)
_lines.RemoveRange(0, overflow);
}
_wantScrollToBottom = true;
}
/// <summary>Snapshot the most recent lines (text + chat-type) for the remote status feed. Thread-safe.</summary>
public (string Text, int Type)[] SnapshotRecent(int max)
{
lock (_lock)
{
int n = Math.Min(Math.Max(0, max), _lines.Count);
var outArr = new (string, int)[n];
int start = _lines.Count - n;
for (int i = 0; i < n; i++)
outArr[i] = (_lines[start + i].Text, _lines[start + i].ChatType);
return outArr;
}
}
public void Render()
{
if (!_settings.ShowRynthChat) return;
bool snapShowTs = _settings.ChatShowTimestamps;
float snapOp = _settings.ChatOpacity;
int snapMax = _settings.ChatMaxLines;
ImGui.SetNextWindowSize(new Vector2(520, 220), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSizeConstraints(new Vector2(220, 110), new Vector2(2400, 1400));
// Use ImGui's native WindowBg with the user's opacity so the platform
// layer can translate it into Platform_SetWindowAlpha on detached
// viewports — that gives a uniformly translucent OS window instead of
// a black-cleared one with a transparent paint over the top.
float opCfg = Math.Clamp(_settings.ChatOpacity, 0f, 1f);
ImGui.SetNextWindowBgAlpha(opCfg);
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.05f, 0.07f, 0.10f, 1f));
// NoBringToFrontOnFocus keeps the gear sub-window (rendered after) on top
// even when the user clicks into the main chat (to drag, resize, or select text).
ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar
| ImGuiWindowFlags.NoCollapse
| ImGuiWindowFlags.NoBringToFrontOnFocus;
if (_settings.ChatClickThrough)
{
flags |= ImGuiWindowFlags.NoInputs
| ImGuiWindowFlags.NoMove
| ImGuiWindowFlags.NoResize;
}
bool visible = ImGui.Begin("##RynthChat", ref _open, flags);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
if (!visible) { ImGui.End(); return; }
Vector2 winPos = ImGui.GetWindowPos();
Vector2 winSize = ImGui.GetWindowSize();
// ImGui paints the WindowBg for us (with platform alpha on detached
// viewports). Just add a thin border for drag/resize affordance.
var dl = ImGui.GetWindowDrawList();
float op = opCfg;
uint br = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.34f, 0.40f, 1f));
dl.AddRect(winPos, winPos + winSize, br, 4f, ImDrawFlags.None, 1.5f);
// Gear visual is painted directly on the chat's drawlist (so it's always
// visible above the bg, on the same viewport, regardless of z-order).
// Clicks are detected manually below so they work whether the chat has
// NoInputs (click-through) or not, and on detached viewports.
const float btn = 14f;
Vector2 gearPos = new Vector2(winPos.X + winSize.X - btn - 4f, winPos.Y + 4f);
Vector2 gearBR = gearPos + new Vector2(btn, btn);
var io = ImGui.GetIO();
bool gearHovered = io.MousePos.X >= gearPos.X && io.MousePos.X < gearBR.X
&& io.MousePos.Y >= gearPos.Y && io.MousePos.Y < gearBR.Y;
uint gearBg = ImGui.ColorConvertFloat4ToU32(gearHovered
? new Vector4(0.25f, 0.30f, 0.40f, 0.95f)
: new Vector4(0f, 0f, 0f, 0.65f));
uint gearBorder = ImGui.ColorConvertFloat4ToU32(new Vector4(0.40f, 0.45f, 0.55f, 0.85f));
dl.AddRectFilled(gearPos, gearBR, gearBg, 2f);
dl.AddRect(gearPos, gearBR, gearBorder, 2f, ImDrawFlags.None, 1f);
Vector2 gearTs = ImGui.CalcTextSize("*");
Vector2 gearTextPos = new(gearPos.X + (btn - gearTs.X) * 0.5f, gearPos.Y + (btn - gearTs.Y) * 0.5f);
dl.AddText(gearTextPos, 0xFFFFFFFFu, "*");
// Track L/R click transitions via raw IO state (IsMouseClicked is filtered
// by hovered-window logic, which fails when the chat has NoInputs or sits
// on a detached viewport). We compare current to previous frame ourselves.
bool curLDown = io.MouseDown[0];
bool curRDown = io.MouseDown[1];
bool lClick = curLDown && !_prevLDown;
bool rClick = curRDown && !_prevRDown;
_prevLDown = curLDown;
_prevRDown = curRDown;
bool inChatRect = io.MousePos.X >= winPos.X && io.MousePos.X < winPos.X + winSize.X
&& io.MousePos.Y >= winPos.Y && io.MousePos.Y < winPos.Y + winSize.Y;
bool wantOpenSettings = (gearHovered && lClick) || (inChatRect && rClick);
if (wantOpenSettings)
ImGui.OpenPopup("##rchat_settings");
RenderSettingsPopup();
// Input row is always rendered at the bottom so the scrollback has a
// stable layout and never gets covered when typing.
const float InputRowH = 24f;
float reservedBottom = InputRowH + 4f;
// Scrollback child below the gear. Width reserves room for the gear
// button on the right; height reserves room for the input row below.
ImGui.SetCursorScreenPos(new Vector2(winPos.X + 4f, winPos.Y + 4f));
Vector2 childSize = new Vector2(winSize.X - 8f - btn - 6f, winSize.Y - 8f - reservedBottom);
ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
if (ImGui.BeginChild("##rchat_scroll", childSize,
ImGuiChildFlags.None,
ImGuiWindowFlags.NoBackground))
{
// Snapshot under the lock — the producer is on a different thread.
ChatLine[] snap;
lock (_lock) { snap = _lines.ToArray(); }
for (int i = 0; i < snap.Length; i++)
{
var line = snap[i];
var col4 = ColorForType(line.ChatType);
if (snapShowTs)
{
string ts = line.At.ToString("HH:mm:ss ");
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.55f, 0.62f, 0.70f, 1f));
ImGui.TextUnformatted(ts);
ImGui.PopStyleColor();
ImGui.SameLine(0, 0);
}
ImGui.PushStyleColor(ImGuiCol.Text, col4);
ImGui.TextWrapped(line.Text);
ImGui.PopStyleColor();
}
if (_wantScrollToBottom)
{
ImGui.SetScrollHereY(1.0f);
_wantScrollToBottom = false;
}
}
ImGui.EndChild();
ImGui.PopStyleColor();
// ── Input row (always visible) ──────────────────────────────────
{
float inputY = winPos.Y + winSize.Y - InputRowH - 2f;
ImGui.SetCursorScreenPos(new Vector2(winPos.X + 4f, inputY));
ImGui.SetNextItemWidth(winSize.X - 8f);
if (_focusInputNextFrame)
{
ImGui.SetKeyboardFocusHere();
_focusInputNextFrame = false;
}
// Use the simple 3-arg overload (no flags) so ImGui.NET's internal
// resize callback handles ref-string growth correctly. Enter detection
// is done manually via IsKeyPressed while the input is focused — this
// avoids both the "callback != NULL" assertion and the buffer-corruption
// that comes from supplying a custom user-callback.
//
// FrameBg is tinted to match the chat body so the input looks like
// part of the same panel at whatever opacity the user picked.
Vector4 frameCol = new Vector4(0.05f, 0.07f, 0.10f, op);
Vector4 frameHovered = new Vector4(0.08f, 0.11f, 0.15f, op);
Vector4 frameActive = new Vector4(0.10f, 0.14f, 0.18f, op);
ImGui.PushStyleColor(ImGuiCol.FrameBg, frameCol);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, frameHovered);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, frameActive);
ImGui.InputText("##rchat_input", ref _inputBuffer, 256u);
ImGui.PopStyleColor(3);
bool isFocused = ImGui.IsItemFocused();
bool enterPressed = ImGui.IsKeyPressed(ImGuiKey.Enter, false)
|| ImGui.IsKeyPressed(ImGuiKey.KeypadEnter, false);
// Eat the same Enter that activated the input, so we don't immediately
// submit an empty message on first focus.
if (_swallowFirstEnter)
{
_swallowFirstEnter = false;
enterPressed = false;
}
if (isFocused && enterPressed)
{
string toSend = _inputBuffer.Trim();
if (!string.IsNullOrEmpty(toSend))
{
if (OnSubmit != null)
OnSubmit(toSend);
else if (_host.HasInvokeChatParser)
_host.InvokeChatParser(toSend);
}
_inputBuffer = string.Empty;
// Defocus our window so WASD/key input flows back to the game.
ImGui.SetWindowFocus(null);
}
// Esc clears the buffer.
if (isFocused && ImGui.IsKeyPressed(ImGuiKey.Escape, false))
_inputBuffer = string.Empty;
}
ImGui.End();
if (snapShowTs != _settings.ChatShowTimestamps
|| snapMax != _settings.ChatMaxLines
|| MathF.Abs(snapOp - _settings.ChatOpacity) > 0.001f)
{
OnSettingChanged?.Invoke();
}
}
private void RenderSettingsPopup()
{
if (!ImGui.BeginPopup("##rchat_settings")) return;
ImGui.Text("Chat Settings");
ImGui.Separator();
ImGui.SetNextItemWidth(140);
ImGui.SliderFloat("Opacity", ref _settings.ChatOpacity, 0.15f, 1f, "%.2f");
ImGui.SetNextItemWidth(140);
ImGui.SliderInt("Max Lines", ref _settings.ChatMaxLines, 50, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Scrollback capacity. Older lines are dropped when this limit is hit.");
ImGui.Checkbox("Timestamps", ref _settings.ChatShowTimestamps);
ImGui.Checkbox("Click-Through", ref _settings.ChatClickThrough);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mouse passes through to the game. The gear button stays clickable.\nTurn off again from the gear or Advanced Settings.");
if (ImGui.Button("Clear##rchat_clear"))
{
lock (_lock) _lines.Clear();
}
ImGui.SameLine();
if (ImGui.Button("Copy Recent##rchat_copy"))
{
const int lastN = 100;
ChatLine[] tail;
lock (_lock)
{
int start = Math.Max(0, _lines.Count - lastN);
tail = _lines.GetRange(start, _lines.Count - start).ToArray();
}
var sb = new System.Text.StringBuilder();
foreach (var l in tail) sb.AppendLine(l.Text);
ImGui.SetClipboardText(sb.ToString());
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Copy the last 100 lines to the clipboard.");
ImGui.EndPopup();
}
/// <summary>Maps an AC eChatTypes value to a display colour.
/// Values come from gmMainChatUI's incoming text dispatch — see
/// Chorizite enum.cs eChatTypes for the canonical list.</summary>
private static Vector4 ColorForType(int chatType) => chatType switch
{
// 0x02 Speech, 0x03 SpeechDirect (you-target), 0x04 SpeechDirectSend (you sending)
2 => new Vector4(0.95f, 0.95f, 0.95f, 1f), // Speech — white
3 => new Vector4(1.00f, 0.55f, 0.85f, 1f), // SpeechDirect (tells to you) — pink
4 => new Vector4(1.00f, 0.55f, 0.85f, 1f), // tells you sent — pink
// 0x05 SystemEvent — soft white-blue
5 => new Vector4(0.85f, 0.90f, 1.00f, 1f),
// 0x06 Combat (general), 0x15 CombatEnemy, 0x16 CombatSelf
6 => new Vector4(1.00f, 0.80f, 0.50f, 1f), // combat — amber
0x15 => new Vector4(1.00f, 0.55f, 0.45f, 1f), // enemy hits you — red-orange
0x16 => new Vector4(0.55f, 1.00f, 0.55f, 1f), // your hits — green
// 0x07 Magic (general), 0x11 MagicCasting
7 => new Vector4(0.55f, 0.80f, 1.00f, 1f), // magic — light blue
0x11 => new Vector4(0.55f, 0.80f, 1.00f, 1f),
// Channels
0x08 => new Vector4(0.70f, 0.95f, 0.90f, 1f), // Channel — teal
0x09 => new Vector4(0.70f, 0.95f, 0.90f, 1f),
0x0A => new Vector4(0.85f, 0.85f, 0.55f, 1f), // SocialChannel — pale yellow
0x0B => new Vector4(0.85f, 0.85f, 0.55f, 1f),
// 0x0C Emote
0x0C => new Vector4(0.75f, 1.00f, 0.75f, 1f),
// 0x0D Advancement (level up etc.)
0x0D => new Vector4(1.00f, 0.95f, 0.30f, 1f),
// 0x0E Abuse, 0x0F Help
0x0E => new Vector4(1.00f, 0.40f, 0.40f, 1f),
0x0F => new Vector4(0.55f, 1.00f, 1.00f, 1f),
// 0x10 Appraisal — soft cyan
0x10 => new Vector4(0.65f, 0.90f, 1.00f, 1f),
// 0x12 Allegiance, 0x13 Fellowship
0x12 => new Vector4(1.00f, 0.55f, 1.00f, 1f), // allegiance — magenta
0x13 => new Vector4(0.55f, 1.00f, 0.85f, 1f), // fellowship — mint
// 0x14 World broadcast
0x14 => new Vector4(1.00f, 0.45f, 0.65f, 1f),
// 0x17 Recall
0x17 => new Vector4(0.85f, 0.70f, 1.00f, 1f),
// 0x18 Craft, 0x19 Salvaging
0x18 => new Vector4(0.95f, 0.80f, 0.50f, 1f),
0x19 => new Vector4(0.85f, 0.95f, 0.55f, 1f),
// 0x1A Transient (mouseover etc.)
0x1A => new Vector4(0.70f, 0.75f, 0.80f, 1f),
// 0x1B General, 0x1C Trade, 0x1D LFG, 0x1E Roleplay
0x1B => new Vector4(0.85f, 0.95f, 1.00f, 1f),
0x1C => new Vector4(0.65f, 1.00f, 0.65f, 1f),
0x1D => new Vector4(1.00f, 0.85f, 0.55f, 1f),
0x1E => new Vector4(1.00f, 0.75f, 0.95f, 1f),
// 0x1F AdminTell — bright orange so it pops
0x1F => new Vector4(1.00f, 0.55f, 0.20f, 1f),
// 0x20 Olthoi, 0x21 Society
0x20 => new Vector4(0.85f, 0.45f, 0.25f, 1f),
0x21 => new Vector4(0.85f, 0.95f, 1.00f, 1f),
// Default / AllChannels / unknown
_ => new Vector4(0.92f, 0.92f, 0.92f, 1f),
};
private static uint SetAlpha(uint col, float alpha)
{
uint a = (uint)(Math.Clamp(alpha, 0f, 1f) * 255f);
return (col & 0x00FFFFFF) | (a << 24);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,415 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// AutoCram + AutoStack. Ported from the legacy NexSuite2 LootManager.
///
/// AutoCram moves non-equipped loose items out of the player's main pack into
/// sub-packs so the main pack stays empty for new loot pickups.
///
/// AutoStack merges two partial stacks of the same item (arrows, components,
/// salvage, pyreals, etc.) by dropping the smaller one onto the larger one's
/// slot — the server auto-merges stackable same-type items at the same slot.
/// </summary>
public sealed class InventoryManager
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache _cache;
private DateTime _nextInventoryActionTime = DateTime.MinValue;
// ── Confirm-via-snapshot + per-entry TTL/backoff state (P1b + P2b) ────────
// Replaces the old wholesale 30s _failedStackPairs/_cramBlacklist clear, which
// re-attempted (and re-relogged) a genuinely-unmovable item every 30s and could
// not tell a successful enqueue from a failed one.
//
// PENDING = a move/merge was enqueued; we have NOT yet confirmed it landed. The
// engine return is enqueue-accepted, not moved-confirmed (AcMainThreadQueue
// gesture-defers a move up to ~250 ticks ≈ 4-8s), so success and failure are
// indistinguishable at the call site. We confirm on a LATER snapshot.
private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; }
private sealed class Backoff { public DateTime NextRetry; public int Attempts; public DateTime LastTouched; }
private readonly Dictionary<int, Pending> _cramPending = new(); // item id -> in-flight move
private readonly Dictionary<int, Backoff> _cramBackoff = new(); // item id -> confirmed-fail backoff
private readonly Dictionary<string, Pending> _stackPending = new(); // "tgt_src" -> in-flight merge
private readonly Dictionary<string, Backoff> _stackBackoff = new(); // "tgt_src" -> confirmed-fail backoff
private DateTime _lastBackoffPrune = DateTime.MinValue;
// Grace window for confirm-via-snapshot. MUST be strictly larger than the
// AcMainThreadQueue max gesture-defer (DrainDeferTickCap=250 ticks ≈ 4-8s at the
// 30-63 Hz tick rate). A shorter window mis-flags in-flight moves as failures and
// falsely backs them off. 10s gives clear headroom above the 8s worst case.
private const double MoveConfirmGraceMs = 10000.0;
// Per-entry backoff: exponential from a base, capped. A genuinely-unmovable item
// backs off instead of retrying every 30s.
private const double BackoffBaseMs = 5000.0; // first retry after a confirmed fail
private const double BackoffMaxMs = 300000.0; // cap at 5 min
private const int MaxAttemptsBudget = 6; // after this, park far out (still age-pruned)
// Age-prune cadence + max idle age (replaces the wholesale clear as the memory bound).
private const double BackoffPruneIntervalMs = 60000.0;
private const double BackoffMaxIdleMs = 600000.0;
// AC item-type flags we care about for cram filtering
private const uint ItemTypeContainer = 0x00000200;
public InventoryManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache cache)
{
_host = host;
_settings = settings;
_cache = cache;
}
// Kept as a no-op for call-site compatibility. Scans are now driven by
// the backoff timer below — we re-scan every 2 seconds when idle, every
// 500 ms after an action, so external "dirty" signals aren't needed.
public void MarkDirty() { }
public void OnHeartbeat(int busyCount)
{
if (!_settings.IsMacroRunning) return;
if (busyCount != 0) return; // don't move items while the client is busy (casting, crafting, etc.)
// Age-prune the per-entry backoff/pending maps (replaces the old wholesale
// 30s clear, which was also the de-facto memory bound). Dead ids / pair-keys
// that haven't been touched in BackoffMaxIdleMs are dropped so they don't
// accumulate across a multi-hour session; live backoff state persists so a
// genuinely-unmovable item stays backed off.
if ((DateTime.Now - _lastBackoffPrune).TotalMilliseconds >= BackoffPruneIntervalMs)
{
PruneBackoff();
_lastBackoffPrune = DateTime.Now;
}
if (DateTime.Now < _nextInventoryActionTime) return;
// Snapshot inventory once per tick — both passes use the same list.
var inv = _cache.GetDirectInventory(forceRefresh: true).ToList();
uint playerId = _host.GetPlayerId();
if (playerId == 0 || inv.Count == 0) return;
// AutoCram runs before AutoStack — clearing space in the main pack is
// higher priority than tidying partials, and the two passes can starve
// each other if AutoStack keeps finding new partial pairs every tick.
if (ProcessAutoCram(inv, (int)playerId))
{
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(500);
return;
}
if (ProcessAutoStack(inv, (int)playerId))
{
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(500);
return;
}
// Nothing to do — back off re-scan for a bit.
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(2000);
}
// ── AutoCram ──────────────────────────────────────────────────────────
private bool ProcessAutoCram(List<WorldObject> inv, int playerId)
{
if (!_settings.EnableAutocram) return false;
int crammable = 0;
foreach (var item in inv)
{
if (item.Container != playerId) continue; // only main pack
if (item.Values(LongValueKey.EquippedSlots, 0) != 0) continue; // not worn/wielded
if (item.ObjectClass == AcObjectClass.Container) continue; // don't cram containers
// Confirm-via-snapshot: if a prior cram of this item is still in flight,
// check whether it actually moved out of the main pack. Moved => handled
// (drop pending). Still here past the grace window => CONFIRMED failure
// => start/advance per-entry backoff. (P1b)
if (_cramPending.TryGetValue(item.Id, out var cp))
{
if (item.Container != playerId)
{
_cramPending.Remove(item.Id); // moved — success confirmed
_cramBackoff.Remove(item.Id);
continue;
}
if ((DateTime.Now - cp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
continue; // still in flight — don't re-enqueue or blacklist
_cramPending.Remove(item.Id);
RegisterFailure(_cramBackoff, item.Id);
_host.Log($"[RynthAi] AutoCram: CONFIRMED move failure id=0x{item.Id:X8} (still in main pack after {MoveConfirmGraceMs:0}ms) — backing off");
continue;
}
// Backed-off after a confirmed failure: skip until NextRetry.
if (_cramBackoff.TryGetValue(item.Id, out var cb) && DateTime.Now < cb.NextRetry)
continue;
// Skip items the user has registered in the RynthAi Weapons tab —
// those are weapons they want to keep accessible at the top level.
if (_settings.ItemRules.Any(r => r.Id == item.Id)) continue;
// Name-based foci guard — focis are also classified as containers above,
// but catch named edge cases where itemType isn't set yet.
if (!string.IsNullOrEmpty(item.Name)
&& item.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0)
continue;
// Capacity check — if this item has its own item slots, treat it as a pack.
if (item.Values(LongValueKey.ItemsCapacity, 0) > 0) continue;
if (item.Values(LongValueKey.ContainersCapacity, 0) > 0) continue;
crammable++;
int targetPack = WorldObjectCache.FindPackFor(inv, playerId, includeMainPack: false, requireFree: 2);
if (targetPack == 0)
{
// Overflow tolerance (P0, 2026-06-24): no SUB-pack has room. The item is
// ALREADY loose in the main pack (loop precondition: item.Container ==
// playerId), so there is nothing to strand — moving it into the main pack
// would be a useless self-move. Only treat this as a genuine "inventory
// full" condition when the main pack ITSELF is full. Reuse the proven
// 102-mainUsed calc (RynthAiPlugin.cs:594-604 / BuffManager.cs:2156-2188).
int mainUsed = 0;
foreach (var m in inv)
{
if (m.Container != playerId) continue;
if (m.ObjectClass == AcObjectClass.Container) continue;
if (m.ObjectClass == AcObjectClass.Foci) continue;
if (m.Values(LongValueKey.EquippedSlots, 0) != 0) continue;
mainUsed++;
}
int mainFree = 102 - mainUsed;
if (mainFree > 0)
_host.Log($"[RynthAi] AutoCram: {crammable} crammable items but no open sub-pack; main pack has room (mainFree={mainFree}) — leaving items in main pack");
else
_host.Log($"[RynthAi] AutoCram: {crammable} crammable items and inventory genuinely full (no sub-pack room, mainUsed={mainUsed}/102)");
break; // no open SUB-pack — stop scanning this tick (engine gate makes any future move fail-closed)
}
int amount = item.Values(LongValueKey.StackCount, 1);
if (amount < 1) amount = 1;
_host.Log($"[RynthAi] AutoCram: move {item.Name} id=0x{item.Id:X8} -> pack=0x{(uint)targetPack:X8} slot=0 amount={amount}");
bool ok = _host.MoveItemInternal(
unchecked((uint)item.Id),
unchecked((uint)targetPack),
slot: 0,
amount: amount);
if (!ok)
{
// Enqueue itself was rejected (engine guard, e.g. amount<=0 or the P0
// full-owned-container gate) — that IS a confirmed failure now.
RegisterFailure(_cramBackoff, item.Id);
_host.Log($"[RynthAi] AutoCram: MoveItemInternal REJECTED id=0x{item.Id:X8} pack=0x{(uint)targetPack:X8} amount={amount} — backing off");
return true; // one action per tick
}
// Enqueue accepted — record as PENDING and confirm on a later snapshot (do
// NOT blacklist; success and a deferred-but-pending move look identical here).
_cramPending[item.Id] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId };
return true; // one action per tick
}
return false;
}
// FindOpenPack DELETED (P2a) — replaced by the shared
// WorldObjectCache.FindPackFor(host, inv, playerId, includeMainPack:false, requireFree:2).
// AutoCram uses includeMainPack:FALSE (cram empties the main pack — must NOT target
// it or it spins) and requireFree:2 (anti-churn margin so a single mis-count can't
// tip a near-full sub-pack). It reuses AutoCram's single per-tick `inv` snapshot via
// the snapshot overload (no extra BFS / no double-refresh).
// ── AutoStack ─────────────────────────────────────────────────────────
private bool ProcessAutoStack(List<WorldObject> inv, int playerId)
{
if (!_settings.EnableAutostack) return false;
// Build candidate list — items belonging to the player (directly or in a sub-pack).
var playerItems = new List<WorldObject>();
foreach (var item in inv)
{
bool inPlayerScope;
if (item.Container == playerId) inPlayerScope = true;
else
{
var container = inv.FirstOrDefault(c => c.Id == item.Container);
inPlayerScope = container != null && container.Container == playerId;
}
if (inPlayerScope) playerItems.Add(item);
}
// Group by name, keep only stackable items with >1 in the same group.
var groupList = playerItems
.Where(x => GetMaxStackSize(x) > 1)
.GroupBy(x => x.Name)
.Where(g => g.Count() > 1)
.ToList();
foreach (var g in groupList)
{
int max = GetMaxStackSize(g.First());
// Read raw stack counts. Sentinel -999 distinguishes "InqInt failed" from
// "real stack of 1" (a freshly-looted single doesn't have STACK_SIZE in the
// qualities table because 1 is the implicit default).
var withCounts = g
.Select(x => (Item: x, Raw: x.Values(LongValueKey.StackCount, -999)))
.ToList();
// For merging, treat InqInt failure as a stack of 1 (legitimate single stack).
// Partials = anything below the cap. Sorted descending so we walk from
// largest target down to find one that fits with the smallest source.
var parts = withCounts
.Select(t => (t.Item, Count: t.Raw == -999 ? 1 : t.Raw))
.Where(t => t.Count > 0 && t.Count < max)
.OrderByDescending(t => t.Count)
.ToList();
if (parts.Count < 2) continue;
// Drain ALL partials of this group across ticks (P2b): walk candidate
// target/source pairs (largest target, smallest viable source) and pick
// the first pair NOT pending and NOT backed-off. The old code only ever
// tried parts[0]+parts[last] and then BLOCKED that exact pair on success,
// starving multi-partial groups (tapers/scarabs) of consolidation.
(WorldObject Item, int Count)? chosenTarget = null;
(WorldObject Item, int Count)? chosenSource = null;
string? pairKey = null;
for (int ti = 0; ti < parts.Count && chosenTarget == null; ti++)
{
for (int si = parts.Count - 1; si > ti; si--)
{
string key = parts[ti].Item.Id + "_" + parts[si].Item.Id;
// Confirm-via-snapshot: a prior merge of this pair either consumed
// the source (id vanished from inv) or grew the target. Either =>
// success; drop pending. Source gone counts as success, NOT an
// unreadable failure.
if (_stackPending.TryGetValue(key, out var sp))
{
bool sourceGone = !inv.Any(x => x.Id == parts[si].Item.Id);
if (sourceGone)
{
_stackPending.Remove(key);
_stackBackoff.Remove(key);
continue; // this pair resolved — try another
}
if ((DateTime.Now - sp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
continue; // still in flight — skip this pair this tick
_stackPending.Remove(key);
RegisterFailure(_stackBackoff, key);
_host.Log($"[RynthAi] AutoStack: CONFIRMED merge failure {key} (source survived after {MoveConfirmGraceMs:0}ms) — backing off");
continue;
}
if (_stackBackoff.TryGetValue(key, out var sb) && DateTime.Now < sb.NextRetry)
continue; // backed off — try another pair
chosenTarget = parts[ti];
chosenSource = parts[si];
pairKey = key;
break;
}
}
if (chosenTarget == null || chosenSource == null || pairKey == null)
continue; // every pair in this group is pending/backed-off — next group
var target = chosenTarget.Value;
var source = chosenSource.Value;
_host.Log($"[RynthAi] AutoStack: merge {source.Item.Name} src=0x{source.Item.Id:X8}({source.Count}) -> tgt=0x{target.Item.Id:X8}({target.Count}) max={max}");
bool ok = _host.MergeStackInternal(
unchecked((uint)source.Item.Id),
unchecked((uint)target.Item.Id));
if (!ok)
{
RegisterFailure(_stackBackoff, pairKey);
_host.Log($"[RynthAi] AutoStack: MergeStackInternal REJECTED src=0x{source.Item.Id:X8} tgt=0x{target.Item.Id:X8} — backing off");
return true; // one action per tick
}
// Enqueue accepted — record PENDING, confirm on a later snapshot. Do NOT
// add the pair-key on success (the old bug that poisoned good merges and
// starved multi-partial consolidation).
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId };
return true; // one action per tick
}
return false;
}
// ── Per-entry backoff helpers (P2b) ───────────────────────────────────
// Advance exponential backoff for a confirmed failure. Generic over the key type
// so cram (int id) and stack (string pair-key) share one implementation.
private static void RegisterFailure<TKey>(Dictionary<TKey, Backoff> map, TKey key) where TKey : notnull
{
if (!map.TryGetValue(key, out var b))
{
b = new Backoff { Attempts = 0 };
map[key] = b;
}
b.Attempts++;
b.LastTouched = DateTime.Now;
int shift = b.Attempts - 1;
if (shift > 6) shift = 6; // cap the shift so the multiply can't overflow
double delay = BackoffBaseMs * (1 << shift); // 5s,10s,20s,40s,80s,160s,320s→capped
if (delay > BackoffMaxMs) delay = BackoffMaxMs;
// Past the attempt budget, park far out (still age-pruned) instead of looping.
if (b.Attempts >= MaxAttemptsBudget) delay = BackoffMaxMs;
b.NextRetry = DateTime.Now.AddMilliseconds(delay);
}
// Age-prune dead/idle entries so the maps don't grow unbounded across a long
// session (the wholesale clear used to be the de-facto bound).
private void PruneBackoff()
{
DateTime now = DateTime.Now;
PruneMap(_cramBackoff, b => b.LastTouched, now);
PruneMap(_stackBackoff, b => b.LastTouched, now);
PruneMap(_cramPending, p => p.EnqueuedAt, now);
PruneMap(_stackPending, p => p.EnqueuedAt, now);
}
private static void PruneMap<TKey, TVal>(Dictionary<TKey, TVal> map, Func<TVal, DateTime> stamp, DateTime now)
where TKey : notnull
{
List<TKey>? dead = null;
foreach (var kv in map)
if ((now - stamp(kv.Value)).TotalMilliseconds > BackoffMaxIdleMs)
(dead ??= new()).Add(kv.Key);
if (dead != null)
foreach (var k in dead) map.Remove(k);
}
// ── Stack-size lookup ─────────────────────────────────────────────────
private static int GetMaxStackSize(WorldObject item)
{
int max = item.Values(LongValueKey.MaxStackSize, 0);
if (max > 1) return max;
// Name-based fallbacks for items whose quality property didn't resolve yet.
string n = item.Name;
if (string.IsNullOrEmpty(n)) return 1;
if (n.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return 25000;
if (n.Contains("Trade Note", StringComparison.OrdinalIgnoreCase)) return 100;
if (n.Contains("Taper", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Scarab", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Prismatic", StringComparison.OrdinalIgnoreCase)) return 100;
if (n.Contains("Arrow", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Bolt", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Quarrel", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Atlatl Dart", StringComparison.OrdinalIgnoreCase)) return 250;
if (n.Contains("Pea", StringComparison.OrdinalIgnoreCase)
|| n.Contains("Grain", StringComparison.OrdinalIgnoreCase)) return 100;
// Salvage bags are intentionally NOT here — each bag is a unique item
// with quality props; they do not stack.
return 1;
}
}

View file

@ -0,0 +1,75 @@
using System.Text.RegularExpressions;
using RynthCore.Loot;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// Evaluates SDK LootCondition/LootRule/LootProfile data against live AC WorldObjects.
/// Kept separate from the SDK so the editor has zero AC dependencies.
/// </summary>
public static class LootEvaluator
{
private static readonly int[] RatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 };
public static bool Evaluate(LootCondition condition, WorldObject item, CharacterSkills? skills)
=> condition switch
{
ObjectClassCondition c => item.ObjectClass == (AcObjectClass)(int)c.ObjectClass,
LongValKeyGECondition c => item.Values(c.Key, 0) >= c.Value,
LongValKeyLECondition c => item.Values(c.Key, 0) <= c.Value,
LongValKeyECondition c => item.Values(c.Key, 0) == c.Value,
LongValKeyNECondition c => item.Values(c.Key, 0) != c.Value,
LongValKeyFlagCondition c => (item.Values(c.Key, 0) & c.FlagValue) != 0,
DoubleValKeyGECondition c => item.Values((DoubleValueKey)c.Key, 0.0) >= c.Value,
DoubleValKeyLECondition c => item.Values((DoubleValueKey)c.Key, 0.0) <= c.Value,
StringValueCondition c => EvalString(item, c),
TotalRatingsGECondition c => EvalTotalRatings(item) >= c.Value,
MinDamageGECondition c => EvalMinDamage(item) >= c.Value,
DamagePercentGECondition c => item.Values(DoubleValueKey.DamageMod, 0.0) * 100.0 >= c.Value,
CharacterSkillGECondition c => skills == null || skills[(AcSkillType)(int)c.Skill].Buffed >= c.Value,
_ => true, // unknown condition type — pass optimistically
};
public static bool Matches(LootRule rule, WorldObject item, CharacterSkills? skills)
{
if (!rule.Enabled) return false;
foreach (var cond in rule.Conditions)
if (!Evaluate(cond, item, skills)) return false;
return true;
}
/// <summary>
/// Returns the first matching rule's action, or null if nothing matched.
/// Callers treat null as "leave on corpse" — do not pick up.
/// </summary>
public static (LootAction action, LootRule? rule) Classify(
LootProfile profile, WorldObject item, CharacterSkills? skills)
{
foreach (var rule in profile.Rules)
if (Matches(rule, item, skills)) return (rule.Action, rule);
return (LootAction.Sell, null);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static bool EvalString(WorldObject item, StringValueCondition c)
{
string value = item.Values((StringValueKey)c.Key, string.Empty);
return Regex.IsMatch(value, c.Pattern,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
private static int EvalTotalRatings(WorldObject item)
{
int total = 0;
foreach (int k in RatingKeys) total += item.Values(k, 0);
return total;
}
private static double EvalMinDamage(WorldObject item)
{
int maxDamage = item.Values(54, 0); // STypeInt MAX_DAMAGE
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
return maxDamage - variance * maxDamage;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using RynthCore.Loot.VTank;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// Character + host context that VTank rules need to evaluate beyond the item
/// itself: buffed/base skill values, character level, main-pack empty slots,
/// item spell IDs/palettes. Built once per evaluation pass and re-used across
/// rules (cheap lookups cached internally).
/// </summary>
public sealed class VTankLootContext
{
public RynthCoreHost Host { get; }
public uint PlayerId { get; }
private readonly Dictionary<uint, (int Buffed, int Base)> _skillCache = new();
private readonly Dictionary<uint, string[]> _spellNameCache = new();
private readonly Dictionary<uint, uint[]> _spellIdCache = new();
private int? _level;
private int? _mainPackEmptySlots;
public VTankLootContext(RynthCoreHost host, uint playerId)
{
Host = host;
PlayerId = playerId;
}
public (int Buffed, int Base) GetSkill(uint stypeSkill)
{
if (_skillCache.TryGetValue(stypeSkill, out var cached)) return cached;
(int Buffed, int Base) result = (0, 0);
if (PlayerId != 0 && Host.HasGetObjectSkill
&& Host.TryGetObjectSkill(PlayerId, stypeSkill, out int buffed, out int training))
result = (buffed, training); // VTank "Base" == advancement class check; we use training as a proxy
_skillCache[stypeSkill] = result;
return result;
}
public int GetLevel()
{
if (_level.HasValue) return _level.Value;
int lvl = 0;
if (PlayerId != 0 && Host.HasGetObjectIntProperty
&& Host.TryGetObjectIntProperty(PlayerId, 25 /* STypeInt.LEVEL */, out int v))
lvl = v;
_level = lvl;
return lvl;
}
public int GetMainPackEmptySlots()
{
if (_mainPackEmptySlots.HasValue) return _mainPackEmptySlots.Value;
int used = 0;
if (Cache != null && PlayerId != 0)
{
int playerIdSigned = unchecked((int)PlayerId);
foreach (var wo in Cache.GetDirectInventory(forceRefresh: false))
{
if (wo.Container != playerIdSigned) continue;
if (wo.ObjectClass == AcObjectClass.Container) continue;
if (wo.ObjectClass == AcObjectClass.Foci) continue;
if (wo.Values(LongValueKey.EquippedSlots, 0) > 0) continue;
used++;
}
}
int slots = Math.Max(0, 102 - used);
_mainPackEmptySlots = slots;
return slots;
}
private readonly Dictionary<uint, (uint[] SubIds, uint[] Offsets)> _paletteCache = new();
public (uint[] SubIds, uint[] Offsets) GetItemPalettes(uint itemId)
{
if (_paletteCache.TryGetValue(itemId, out var cached)) return cached;
var empty = (Array.Empty<uint>(), Array.Empty<uint>());
if (!Host.HasGetObjectPalettes) { _paletteCache[itemId] = empty; return empty; }
var subIds = new uint[16];
var offsets = new uint[16];
int n = Host.GetObjectPalettes(itemId, subIds, offsets, 16);
if (n <= 0) { _paletteCache[itemId] = empty; return empty; }
int take = Math.Min(n, 16);
var ids2 = new uint[take];
var offs2 = new uint[take];
Array.Copy(subIds, ids2, take);
Array.Copy(offsets, offs2, take);
var result = (ids2, offs2);
_paletteCache[itemId] = result;
return result;
}
public uint[] GetItemSpellIds(uint itemId)
{
if (_spellIdCache.TryGetValue(itemId, out var ids)) return ids;
uint[] result = Array.Empty<uint>();
if (Host.HasGetObjectSpellIds)
{
uint[] buf = new uint[64];
int n = Host.GetObjectSpellIds(itemId, buf, buf.Length);
if (n > 0)
{
int take = Math.Min(n, buf.Length);
result = new uint[take];
Array.Copy(buf, result, take);
}
}
_spellIdCache[itemId] = result;
return result;
}
public string[] GetItemSpellNames(uint itemId)
{
if (_spellNameCache.TryGetValue(itemId, out var cached)) return cached;
uint[] ids = GetItemSpellIds(itemId);
var names = new string[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
SpellInfo? info = SpellTableStub.GetById((int)ids[i]);
names[i] = info?.Name ?? string.Empty;
}
_spellNameCache[itemId] = names;
return names;
}
internal WorldObjectCache? Cache { get; set; }
}
/// <summary>
/// Evaluates a VTankLootRule against a WorldObject. All matching logic is here
/// so the LootSdk types stay pure-data and the editor can reference them
/// without dragging in plugin/host dependencies.
/// </summary>
public static class VTankLootEvaluator
{
public static bool Match(VTankLootRule rule, WorldObject? item, VTankLootContext? ctx = null)
{
if (item is null) return false;
if (rule.Conditions.Count == 0) return true; // unconditional rule
try
{
uint itemId = unchecked((uint)item.Id);
foreach (var cond in rule.Conditions)
{
if (!Match(cond, item, itemId, ctx))
return false;
}
return true;
}
catch
{
return false;
}
}
private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx)
{
var d = cond.DataLines;
return cond.NodeType switch
{
VTankNodeTypes.SpellNameMatch => MatchSpellNameMatch(itemId, ctx, d),
VTankNodeTypes.StringValueMatch => MatchStringValue(item, d),
VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val,
VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) <= val,
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally
VTankNodeTypes.ObjectClass => (int)item.ObjectClass == ReadInt(d, 0),
VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0),
VTankNodeTypes.SpellMatch => MatchSpellMatch(itemId, ctx, d),
VTankNodeTypes.MinDamageGE => MatchMinDamageGE(item, d),
VTankNodeTypes.LongValKeyFlagExists => Long(d) is var (flag,fkey) && (item.Values((LongValueKey)fkey, 0) & flag) != 0,
VTankNodeTypes.LongValKeyE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) == val,
VTankNodeTypes.LongValKeyNE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) != val,
VTankNodeTypes.AnySimilarColor => true, // needs portal.dat — optimistic
VTankNodeTypes.SimilarColorArmorType => true, // needs portal.dat — optimistic
VTankNodeTypes.SlotSimilarColor => true, // needs portal.dat — optimistic
VTankNodeTypes.SlotExactPalette => MatchSlotExactPalette(itemId, ctx, d),
VTankNodeTypes.CharacterSkillGE => ctx is null || ctx.GetSkill(unchecked((uint)ReadInt(d, 1))).Buffed >= ReadInt(d, 0),
VTankNodeTypes.CharacterMainPackEmptySlotsGE => ctx is null || ctx.GetMainPackEmptySlots() >= ReadInt(d, 0),
VTankNodeTypes.CharacterLevelGE => ctx is null || ctx.GetLevel() >= ReadInt(d, 0),
VTankNodeTypes.CharacterLevelLE => ctx is null || ctx.GetLevel() <= ReadInt(d, 0),
VTankNodeTypes.CharacterBaseSkill => MatchCharacterBaseSkill(ctx, d),
VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, d),
VTankNodeTypes.BuffedMissileDamageGE => MatchBuffedMissileDamageGE(item, d),
VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(54, 0) >= ReadDouble(d, 0),
VTankNodeTypes.TotalRatingsGE => MatchTotalRatingsGE(item, d),
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false, // not implemented
VTankNodeTypes.DisabledRule => MatchDisabledRule(d),
_ => throw new InvalidOperationException($"Unsupported VTank loot node type {cond.NodeType}."),
};
}
// ── Matchers needing more than a one-liner ───────────────────────────────
// NOTE: all three regex matchers go through Meta.RegexCache rather than
// `new Regex(...)`. ClassifyItemAgainstProfile runs this evaluator against
// every loot rule for every corpse item on the plugin tick thread, and a
// loot-snob profile has hundreds of spell-name / string regex rules. Compiling
// each pattern per match (the old code) cost hundreds of regex *compilations*
// per item — the dominant cost of "scanning which items to keep", and it
// stalled the shared tick (combat/nav) while looting. The cache reuses the
// constructed interpreter instance; match semantics are identical (a bad
// pattern caches null ⇒ no match, same as the old throw→outer-catch→false).
private static bool MatchSpellNameMatch(uint itemId, VTankLootContext? ctx, IList<string> d)
{
if (ctx is null) return true;
Regex? rx = Meta.RegexCache.Get(d[0], RegexOptions.IgnoreCase);
if (rx is null) return false;
foreach (string n in ctx.GetItemSpellNames(itemId))
if (!string.IsNullOrEmpty(n) && rx.IsMatch(n)) return true;
return false;
}
private static bool MatchStringValue(WorldObject item, IList<string> d)
{
string pattern = d[0];
int key = ReadInt(d, 1);
string value = item.Values((StringValueKey)key, string.Empty);
return Meta.RegexCache.IsMatch(value, pattern, RegexOptions.IgnoreCase);
}
private static bool MatchSpellMatch(uint itemId, VTankLootContext? ctx, IList<string> d)
{
if (ctx is null) return true;
string pos = d[0];
string neg = d[1];
int count = ReadInt(d, 2);
Regex? rxPos = Meta.RegexCache.Get(pos, RegexOptions.IgnoreCase);
if (rxPos is null) return false;
Regex? rxNeg = string.IsNullOrWhiteSpace(neg)
? null
: Meta.RegexCache.Get(neg, RegexOptions.IgnoreCase);
int c = 0;
foreach (string name in ctx.GetItemSpellNames(itemId))
{
if (string.IsNullOrEmpty(name)) continue;
if (rxPos.IsMatch(name) && (rxNeg is null || !rxNeg.IsMatch(name)))
if (++c >= count) return true;
}
return false;
}
private static bool MatchMinDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
if (maxDamage == 0) return false;
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
double minDamage = maxDamage - (variance * maxDamage);
return minDamage >= threshold;
}
private static bool MatchSlotExactPalette(uint itemId, VTankLootContext? ctx, IList<string> d)
{
int slot = ReadInt(d, 0);
uint targetPaletteId = (uint)ReadInt(d, 1);
if (ctx is null) return true;
var (subIds, _) = ctx.GetItemPalettes(itemId);
if (subIds.Length == 0) return true;
if (slot < 0 || slot >= subIds.Length) return false;
uint actual = subIds[slot];
return (actual & 0x00FFFFFFu) == (targetPaletteId & 0x00FFFFFFu);
}
private static bool MatchCharacterBaseSkill(VTankLootContext? ctx, IList<string> d)
{
int skillId = ReadInt(d, 0);
int min = ReadInt(d, 1);
int max = ReadInt(d, 2);
if (ctx is null) return true;
var (_, baseVal) = ctx.GetSkill(unchecked((uint)skillId));
return baseVal >= min && baseVal <= max;
}
private static bool MatchBuffedMedianDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
if (maxDamage == 0) return false;
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
double minDamage = maxDamage - (variance * maxDamage);
return (minDamage + maxDamage) / 2.0 >= threshold;
}
private static bool MatchBuffedMissileDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
if (maxDamage == 0) return false;
double elemBonus = item.Values((DoubleValueKey)152, 1.0);
if (elemBonus < 1.0) elemBonus = 1.0;
return maxDamage * elemBonus >= threshold;
}
private static bool MatchTotalRatingsGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int total =
item.Values(370, 0) + item.Values(371, 0) + item.Values(372, 0) + item.Values(373, 0) +
item.Values(374, 0) + item.Values(375, 0) + item.Values(376, 0) + item.Values(379, 0);
return total >= threshold;
}
private static bool MatchDisabledRule(IList<string> d)
{
string raw = d.Count > 0 ? d[0] : "false";
bool isDisabled = string.Equals(raw.Trim(), "true", StringComparison.OrdinalIgnoreCase);
return !isDisabled;
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static int ReadInt(IList<string> d, int idx)
=> int.Parse(d[idx], NumberStyles.Integer, CultureInfo.InvariantCulture);
private static double ReadDouble(IList<string> d, int idx)
=> double.Parse(d[idx], NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
// (value, key) pair for the LongValKey* family.
private static (int Val, int Key) Long(IList<string> d) => (ReadInt(d, 0), ReadInt(d, 1));
private static (double Val, int Key) Double(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
// Buffed long/double helpers store value as double in slot 0 (matching VTank's "Read" of doubles).
private static (double Val, int Key) DoubleKey(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
}

View file

@ -0,0 +1,755 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Mag-Tools /mt command compatibility — maps /mt commands to /ra equivalents.
/// Partial class of RynthAiPlugin.
/// </summary>
public sealed partial class RynthAiPlugin
{
private Dictionary<string, int>? _spellNameToId;
/// <summary>
/// Handle a /mt command. Returns true if recognized and handled.
/// Called from OnChatBarEnter (manual typing) and MetaManager (ChatCommand actions).
/// </summary>
internal bool HandleMtCommand(string fullCommand)
{
string[] parts = fullCommand.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return false;
string cmd = parts[1].ToLower();
switch (cmd)
{
// ── Options ──────────────────────────────────────────────────────
case "opt":
return HandleMtOpt(parts);
// ── Combat state ─────────────────────────────────────────────────
case "combatstate":
return HandleMtCombatState(parts);
// ── Facing ───────────────────────────────────────────────────────
case "face":
return HandleMtFace(parts);
// ── Cast spell ───────────────────────────────────────────────────
case "cast": return HandleMtCast(parts, partial: false);
case "castp": return HandleMtCast(parts, partial: true);
// ── Use item ─────────────────────────────────────────────────────
case "use": return HandleMtUse(parts, inv: true, land: true, partial: false);
case "usep": return HandleMtUse(parts, inv: true, land: true, partial: true);
case "usei": return HandleMtUse(parts, inv: true, land: false, partial: false);
case "useip":
case "usepi": return HandleMtUse(parts, inv: true, land: false, partial: true);
case "usel": return HandleMtUse(parts, inv: false, land: true, partial: false);
case "uselp":
case "usepl": return HandleMtUse(parts, inv: false, land: true, partial: true);
// ── Select item ──────────────────────────────────────────────────
case "select": HandleSelectCommand(parts, inv: true, land: true, partial: false); return true;
case "selectp": HandleSelectCommand(parts, inv: true, land: true, partial: true); return true;
// ── Give item ────────────────────────────────────────────────────
case "give": return HandleMtGive(parts, partial: false);
case "givep": return HandleMtGive(parts, partial: true);
// ── Loot item ────────────────────────────────────────────────────
case "loot": return HandleMtLoot(parts, partial: false);
case "lootp": return HandleMtLoot(parts, partial: true);
// ── Drop item ────────────────────────────────────────────────────
case "drop": return HandleMtDrop(parts, partial: false);
case "dropp": return HandleMtDrop(parts, partial: true);
// ── Equip / unequip ──────────────────────────────────────────────
case "equip": return HandleMtEquip(parts, partial: false);
case "equipp": return HandleMtEquip(parts, partial: true);
case "dequip": return HandleMtDequip(parts, partial: false);
case "dequipp": return HandleMtDequip(parts, partial: true);
// ── Fellowship ───────────────────────────────────────────────────
case "fellow":
return HandleMtFellow(parts);
// ── Session ──────────────────────────────────────────────────────
case "logoff":
case "logout":
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/logout");
return true;
case "quit":
case "exit":
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/quit");
return true;
// ── Send a chat line / slash command (VTank /mt send) ────────────
case "send":
if (parts.Length >= 3 && Host.HasInvokeChatParser)
Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
return true;
default:
return false;
}
}
// ═════════════════════════════════════════════════════════════════════════
// /mt opt
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtOpt(string[] parts)
{
// /mt opt list
// /mt opt get <option>
// /mt opt set <option> <value>
if (parts.Length < 3) return false;
string sub = parts[2].ToLower();
if (sub == "list")
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
if (map == null) { ChatLine("[RynthAi] Settings not ready."); return true; }
ChatLine("[RynthAi] === Options ===");
foreach (var kvp in map)
ChatLine($"[RynthAi] {kvp.Key} = {kvp.Value.Get()}");
return true;
}
if (sub == "get" && parts.Length >= 4)
{
string optName = parts[3];
string? val = GetOptionValue(optName);
ChatLine(val != null
? $"[RynthAi] {optName} = {val}"
: $"[RynthAi] Unknown option: {optName}");
return true;
}
if (sub == "set" && parts.Length >= 5)
{
string optName = parts[3];
string optVal = parts[4];
SetOptionValue(optName, optVal);
return true;
}
// /mt opt remember / restore — store/recall for later
if (sub == "remember" && parts.Length >= 4)
{
string optName = parts[3];
string? val = GetOptionValue(optName);
if (val != null)
{
_rememberedOptions[optName.ToLower()] = val;
Host.Log($"[RynthAi] Remembered {optName} = {val}");
}
return true;
}
if (sub == "restore" && parts.Length >= 4)
{
string optName = parts[3];
if (_rememberedOptions.TryGetValue(optName.ToLower(), out string? saved))
{
SetOptionValue(optName, saved);
Host.Log($"[RynthAi] Restored {optName} = {saved}");
}
return true;
}
return false;
}
private readonly Dictionary<string, string> _rememberedOptions = new(StringComparer.OrdinalIgnoreCase);
// VTank/MagTools option name → RynthAi settings name
private static readonly Dictionary<string, string> MtOptionMap = new(StringComparer.OrdinalIgnoreCase)
{
["enablecombat"] = "EnableCombat",
["enablelooting"] = "EnableLooting",
["enablenav"] = "EnableNavigation",
["enablebuffing"] = "EnableBuffing",
["enablemeta"] = "EnableMeta",
["opendoors"] = "OpenDoors",
["idlepeacemode"] = "PeaceModeWhenIdle",
["idlebufftopoff"] = "RebuffWhenIdle",
["summonpets"] = "SummonPets",
["combinesalvage"] = "EnableCombineSalvage",
["attackdistance"] = "MonsterRange",
["approachdistance"] = "ApproachRange",
["navpriorityboost"] = "BoostNavPriority",
["lootpriorityboost"] = "BoostLootPriority",
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
["switchwandstodebuff"] = "UseDispelItems",
["lootonlyrarecorpses"] = "MineOnly",
// VTank-meta migration aliases (mirror of MetaManager.VtOptionMap so options
// set via /ub opt / /mt opt resolve the same as /vt opt set).
["autocram"] = "EnableAutocram",
["autostack"] = "EnableAutostack",
["usedispelitems"] = "UseDispelItems",
["castdispelself"] = "CastDispelSelf",
["opendoorrange"] = "OpenDoorRange",
["recharge-norm-hitp"] = "HealAt",
["recharge-norm-mana"] = "GetManaAt",
["recharge-norm-stam"] = "RestamAt",
["recharge-notarg-hitp"] = "TopOffHP",
["recharge-notarg-mana"] = "TopOffMana",
["recharge-notarg-stam"] = "TopOffStam",
["petmonsterdensity"] = "PetMinMonsters",
["corpseapproachrange-max"] = "CorpseApproachRangeMax",
["corpseapproachrange-min"] = "CorpseApproachRangeMin",
["manastonelootcount"] = "ManaStoneKeepCount",
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
["navclosestoprange"] = "NavCloseStopRange",
};
private string? GetOptionValue(string optName)
{
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
if (map != null && map.TryGetValue(raName, out var entry))
return entry.Get();
}
// Check generic options stored by expression engine
return _metaManager?.Expressions?.GetOption(optName);
}
private void SetOptionValue(string optName, string optVal)
{
// Normalize bool strings
string value = optVal.ToLower() switch
{
"true" => "1",
"false" => "0",
"on" => "1",
"off" => "0",
_ => optVal
};
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
if (map != null && map.TryGetValue(raName, out var entry))
{
entry.Set(value);
return;
}
}
// Store as generic option
_metaManager?.Expressions?.SetOption(optName, value);
}
// ═════════════════════════════════════════════════════════════════════════
// /mt combatstate
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtCombatState(string[] parts)
{
// /mt combatstate [magic,melee,missile,peace]
if (parts.Length < 3) return false;
if (!Host.HasChangeCombatMode) { ChatLine("[RynthAi] ChangeCombatMode not available."); return true; }
string mode = parts[2].ToLower();
int cm = mode switch
{
"peace" => CombatMode.NonCombat,
"melee" => CombatMode.Melee,
"missile" => CombatMode.Missile,
"magic" => CombatMode.Magic,
_ => 0
};
if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; }
Host.ChangeCombatMode(cm);
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt face
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtFace(string[] parts)
{
// /mt face <degrees>
if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false;
if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; }
Host.TurnToHeading(degrees);
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt cast / castp
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtCast(string[] parts, bool partial)
{
// /mt cast[p] <#|name> [on <target>]
if (parts.Length < 3) return false;
if (!Host.HasCastSpell) { ChatLine("[RynthAi] CastSpell not available."); return true; }
string argStr = string.Join(" ", parts, 2, parts.Length - 2);
// Parse "X on Y" — target is optional
uint targetId = _currentTargetId;
int onIdx = argStr.IndexOf(" on ", StringComparison.OrdinalIgnoreCase);
string spellArg;
if (onIdx >= 0)
{
spellArg = argStr[..onIdx].Trim();
string targetName = argStr[(onIdx + 4)..].Trim();
var targetObj = FindObject(targetName, inv: false, land: true, partial: true);
if (targetObj != null)
targetId = unchecked((uint)targetObj.Id);
else
{
ChatLine($"[RynthAi] Target not found: '{targetName}'");
return true;
}
}
else
{
spellArg = argStr.Trim();
}
// Try parse as spell ID first
int spellId;
if (!int.TryParse(spellArg, out spellId))
{
// Name lookup
_spellNameToId ??= SpellDatabase.BuildNameToIdMap();
if (partial)
{
// Partial match — find first spell name containing the search string
spellId = 0;
string search = spellArg.ToLower();
foreach (var kvp in _spellNameToId)
{
if (kvp.Key.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0)
{
spellId = kvp.Value;
break;
}
}
}
else
{
_spellNameToId.TryGetValue(spellArg, out spellId);
}
if (spellId == 0)
{
ChatLine($"[RynthAi] Spell not found: '{spellArg}'");
return true;
}
}
if (targetId == 0)
{
// Self-cast — use player ID
targetId = Host.GetPlayerId();
}
Host.CastSpell(targetId, spellId);
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt use (with closestnpc / closestvendor / closestportal support)
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtUse(string[] parts, bool inv, bool land, bool partial)
{
if (parts.Length < 3) return false;
string argStr = string.Join(" ", parts, 2, parts.Length - 2).Trim();
// Special targets: closestnpc, closestvendor, closestportal
string lower = argStr.ToLower();
if (lower == "closestnpc" || lower == "closestvendor" || lower == "closestportal")
{
return HandleMtUseClosest(lower);
}
// Delegate to existing /ra use handler
HandleUseCommand(parts, inv, land, partial);
return true;
}
private bool HandleMtUseClosest(string type)
{
if (_objectCache == null || _playerId == 0)
{
ChatLine("[RynthAi] Not ready.");
return true;
}
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
int playerId = (int)_playerId;
WorldObject? best = null;
double bestDist = double.MaxValue;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
bool match = type switch
{
"closestnpc" => wo.ObjectClass == AcObjectClass.Npc,
"closestvendor" => wo.ObjectClass == AcObjectClass.Vendor,
"closestportal" => wo.ObjectClass == AcObjectClass.Portal,
_ => false
};
if (!match) continue;
double dist = _objectCache.Distance(playerId, wo.Id);
if (dist < bestDist)
{
bestDist = dist;
best = wo;
}
}
if (best == null)
{
ChatLine($"[RynthAi] No {type.Replace("closest", "")} found nearby.");
return true;
}
Host.UseObject(unchecked((uint)best.Id));
Host.Log($"[RynthAi] /mt use {type}: {best.Name} (0x{(uint)best.Id:X8}) at {bestDist:F1}m");
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt give[p] <item> to <target>
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtGive(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
string argStr = string.Join(" ", parts, 2, parts.Length - 2);
int toIdx = argStr.IndexOf(" to ", StringComparison.OrdinalIgnoreCase);
if (toIdx < 0) { ChatLine("[RynthAi] Usage: /mt give[p] <item> to <target>"); return true; }
string itemName = argStr[..toIdx].Trim();
string targetName = argStr[(toIdx + 4)..].Trim();
var item = FindObject(itemName, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found: '{itemName}'"); return true; }
var target = FindObject(targetName, inv: false, land: true, partial: true);
if (target == null) { ChatLine($"[RynthAi] Target not found: '{targetName}'"); return true; }
// Giving to an NPC requires AC's give GameAction (Event_GiveObjectRequest).
// The old path used MoveItemExternal = move-to-CONTAINER, which does NOT
// give to an NPC — so /mt givep silently did nothing. Use the real give
// primitive (engine API v62+); on an older engine, say so rather than
// pretend it worked.
if (Host.HasGiveObjectTo)
{
bool ok = Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)target.Id), 0);
Host.Log($"[RynthAi] /mt give: {item.Name} → {target.Name} (give ok={ok})");
}
else
{
ChatLine("[RynthAi] Give requires engine API v62+ — update the RynthCore engine.");
}
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt loot[p] <item>
// ═════════════════════════════════════════════════════════════════════════
// Deferred loot state — when the meta fires /mt loot in the same tick as
// UseObject on the corpse, _openedContainerId is still 0. We queue the
// request here and retry each heartbeat until the corpse opens (or timeout).
private string? _pendingMtLootName;
private bool _pendingMtLootPartial;
private long _pendingMtLootExpiryMs;
private const long PendingMtLootTimeoutMs = 8_000;
/// <summary>
/// Resolve the container /mt loot should pull from. Prefer the auto-looter's
/// tracked open corpse (<see cref="_openedContainerId"/>), but fall back to
/// whatever the client currently has open (GetGroundContainerId). The fallback
/// is what lets /mt loot work on a corpse RynthAi already finished + marked
/// completed (so SyncCorpseContainerState refuses to re-register it), or one
/// opened manually / by the meta with auto-looting disabled.
/// </summary>
private int ResolveOpenLootContainer()
{
if (_openedContainerId != 0)
return _openedContainerId;
if (Host.HasGetGroundContainerId)
{
int raw = unchecked((int)Host.GetGroundContainerId());
if (raw != 0)
return raw;
}
return 0;
}
/// <summary>
/// Enumerate a container's contents as (id, name) pairs. Prefers AC's live
/// container query (GetContainerContents), which reads the actual client
/// container object and is immune to the passive cache-population timing that
/// leaves GetContainedItems empty for a freshly-opened corpse. Falls back to
/// the ownership-probe cache scan only when the direct API isn't available or
/// returns nothing.
/// </summary>
private List<(uint Id, string Name)> EnumerateContainer(int containerId)
{
var result = new List<(uint, string)>();
if (containerId == 0) return result;
if (Host.HasGetContainerContents)
{
uint[] buf = new uint[256];
int count = Host.GetContainerContents(unchecked((uint)containerId), buf);
for (int i = 0; i < count && i < buf.Length; i++)
{
uint id = buf[i];
if (id == 0) continue;
Host.TryGetObjectName(id, out string name);
result.Add((id, name ?? string.Empty));
}
if (result.Count > 0) return result;
}
// Fallback: passive cache ownership scan.
if (_objectCache != null)
foreach (WorldObject wo in _objectCache.GetContainedItems(containerId))
result.Add((unchecked((uint)wo.Id), wo.Name));
return result;
}
/// <summary>
/// Find a named item inside a container. An exact (case-insensitive) match
/// wins; when no exact match exists we fall back to a substring match so a
/// meta written as "/mt loot Acid" still grabs "Olthoi Acid Larva". Passing
/// partial:true skips straight to substring matching.
/// </summary>
private (uint Id, string Name)? FindContainedItem(int containerId, string name, bool partial)
{
if (containerId == 0 || string.IsNullOrEmpty(name))
return null;
(uint Id, string Name)? substringHit = null;
foreach (var item in EnumerateContainer(containerId))
{
if (!partial && string.Equals(item.Name, name, StringComparison.OrdinalIgnoreCase))
return item; // exact match preferred
if (substringHit == null &&
item.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0)
substringHit = item;
}
return substringHit; // substring fallback (or the only mode when partial)
}
internal void TickPendingMtLoot()
{
if (_pendingMtLootName == null) return;
int container = ResolveOpenLootContainer();
if (container == 0) return; // still waiting for a container to open
if (CorpseNowMs > _pendingMtLootExpiryMs)
{
ChatLine($"[RynthAi] /mt loot: timed out waiting for '{_pendingMtLootName}'.");
_pendingMtLootName = null;
return;
}
var found = FindContainedItem(container, _pendingMtLootName, _pendingMtLootPartial);
if (found == null) return; // items may not be available yet — try again next tick
Host.SelectItem(found.Value.Id);
Host.UseObject(found.Value.Id);
Host.Log($"[RynthAi] /mt loot (deferred): {found.Value.Name} (0x{found.Value.Id:X8}) from container 0x{(uint)container:X8}");
_pendingMtLootName = null;
}
private bool HandleMtLoot(string[] parts, bool partial)
{
// Pick a named item from the currently opened corpse/container.
if (parts.Length < 3) return false;
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
int container = ResolveOpenLootContainer();
// If a container is open, try immediately.
if (container != 0)
{
var found = FindContainedItem(container, name, partial);
if (found != null)
{
Host.SelectItem(found.Value.Id);
Host.UseObject(found.Value.Id);
Host.Log($"[RynthAi] /mt loot: {found.Value.Name} (0x{found.Value.Id:X8}) from container 0x{(uint)container:X8}");
_pendingMtLootName = null;
return true;
}
// Item not found — list what IS in the container so names can be checked.
var itemNames = new System.Text.StringBuilder();
foreach (var item in EnumerateContainer(container))
{
if (itemNames.Length > 0) itemNames.Append(", ");
itemNames.Append(item.Name);
}
if (itemNames.Length > 0)
ChatLine($"[RynthAi] /mt loot: '{name}' not found. Container 0x{(uint)container:X8} contains: {itemNames}");
else
ChatLine($"[RynthAi] /mt loot: '{name}' not found (container 0x{(uint)container:X8} appears empty or still loading — queuing)");
}
// Container not open yet, or items not in cache — queue for deferred retry.
_pendingMtLootName = name;
_pendingMtLootPartial = partial;
_pendingMtLootExpiryMs = CorpseNowMs + PendingMtLootTimeoutMs;
Host.Log($"[RynthAi] /mt loot: '{name}' queued (container=0x{(uint)container:X8})");
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt drop[p] <item>
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtDrop(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasMoveItemExternal) { ChatLine("[RynthAi] MoveItemExternal not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var item = FindObject(name, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found in inventory: '{name}'"); return true; }
// Drop = move to the ground (container 0)
Host.MoveItemExternal(unchecked((uint)item.Id), 0, 0);
Host.Log($"[RynthAi] /mt drop: {item.Name} (0x{(uint)item.Id:X8})");
return true;
}
// ═════════════════════════════════════════════════════════════════════════
// /mt equip[p] / dequip[p]
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtEquip(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var item = FindObject(name, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
Host.UseObject(unchecked((uint)item.Id));
Host.Log($"[RynthAi] /mt equip: {item.Name} (0x{(uint)item.Id:X8})");
return true;
}
private bool HandleMtDequip(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasMoveItemInternal) { ChatLine("[RynthAi] MoveItemInternal not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
// Find a wielded item matching the name
if (_objectCache == null) { ChatLine("[RynthAi] Cache not ready."); return true; }
WorldObject? found = null;
foreach (var wo in _objectCache.GetInventory())
{
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) <= 0) continue;
bool match = partial
? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase);
if (match) { found = wo; break; }
}
if (found == null) { ChatLine($"[RynthAi] Wielded item not found: '{name}'"); return true; }
// FIX (2026-06-24): MoveItemInternal with amount=0 is a silent no-op — the engine
// guard (ClientHelperHooks.cs:431 `if (amount <= 0) return false;`) rejects it, so
// the old amount=0 call dequipped nothing. Must pass amount>=1. Also target a
// capacity-verified open pack (not the main pack blindly) — moving into a FULL pack
// CRASHES the client via the native PutItemInContainer path.
int dest = WorldObjectCache.FindPackFor(Host, _objectCache, includeMainPack: true, requireFree: 1);
if (dest == 0)
{
ChatLine($"[RynthAi] /mt dequip: no open pack for '{found.Name}' — inventory full.");
return true;
}
Host.MoveItemInternal(unchecked((uint)found.Id), unchecked((uint)dest), 0, 1);
Host.Log($"[RynthAi] /mt dequip: {found.Name} (0x{(uint)found.Id:X8}) → pack 0x{(uint)dest:X8}");
return true;
}
// FindOpenPackForDequip DELETED (P2a) — replaced by shared
// WorldObjectCache.FindPackFor(host, cache, includeMainPack:true, requireFree:1).
// User-driven /mt dequip: requireFree:1 so a single genuinely-free slot still
// counts (do not report 'full' when 1 slot exists).
// ═════════════════════════════════════════════════════════════════════════
// /mt fellow
// ═════════════════════════════════════════════════════════════════════════
private bool HandleMtFellow(string[] parts)
{
// /mt fellow create <name>
// /mt fellow open|close|disband|quit
// /mt fellow recruit <name>
// Route through chat parser since AC handles these natively
if (parts.Length < 3) return false;
if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] ChatParser not available."); return true; }
string sub = parts[2].ToLower();
switch (sub)
{
case "create":
if (parts.Length >= 4)
{
string fellowName = string.Join(" ", parts, 3, parts.Length - 3);
Host.InvokeChatParser($"/fellowship create {fellowName}");
}
return true;
case "open":
Host.InvokeChatParser("/fellowship open");
return true;
case "close":
Host.InvokeChatParser("/fellowship close");
return true;
case "disband":
Host.InvokeChatParser("/fellowship disband");
return true;
case "quit":
Host.InvokeChatParser("/fellowship quit");
return true;
case "recruit":
if (parts.Length >= 4)
{
string playerName = string.Join(" ", parts, 3, parts.Length - 3);
Host.InvokeChatParser($"/fellowship recruit {playerName}");
}
return true;
default:
return false;
}
}
}

View file

@ -0,0 +1,583 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Mana stone tapping state machine.
///
/// Each think tick from Idle picks one of two actions:
/// 1. If any worn item has CurrentMana below the threshold AND we have a
/// charged stone in inventory, use the stone on the player.
/// 2. Otherwise, if we have an empty stone and an inventory item with at
/// least the threshold of CurrentMana, drain it.
///
/// Single-shot semantics:
/// - Using an empty stone on an item destroys the item and charges the stone.
/// - Using a charged stone on the player may also destroy the stone — if so
/// we just loot another next corpse.
/// </summary>
internal sealed class ManaStoneManager
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache _objectCache;
private enum TapState { Idle, TappingItem, UsingOnPlayer }
private TapState _state = TapState.Idle;
private int _activeStoneId;
private int _activeItemId;
private long _actionIssuedAt;
private long _lastThinkAt;
// After a use-on-player times out we blacklist the offending stone
// for a while so we don't re-select it next tick and loop forever.
private readonly Dictionary<int, long> _stoneUseOnPlayerCooldownUntil = new();
private const long StoneUseOnPlayerCooldownMs = 5 * 60 * 1000;
// Same idea for tap targets: an item that won't drain (wielded server-side,
// already at 0 mana, etc.) gets shelved for 5 minutes so we move on.
private readonly Dictionary<int, long> _tapTargetCooldownUntil = new();
private const long TapTargetCooldownMs = 5 * 60 * 1000;
// And for the stone half of the pair: a "stone" that AC silently refuses
// to use (often because it's actually charged but our cache reads its
// CurrentMana as 0/unreadable) gets parked so FindEmptyStone moves on.
// Short cooldown — most failures are transient (server lag, mid-action),
// and a genuinely-charged stone is filtered by the cur>0 check anyway.
private readonly Dictionary<int, long> _stoneTapCooldownUntil = new();
private const long StoneTapCooldownMs = 30 * 1000;
// Stones we've positively confirmed are charged via AC chat ("is already
// full of mana"). Distinct from the cooldown so the cache's stale CurrentMana
// reading doesn't auto-clear them. Only cleared when the stone disappears
// from cache (consumed via use-on-player).
private readonly HashSet<int> _stoneKnownCharged = new();
// Worn equipment is only treated as "needs refill" when current mana drops
// below this fraction of its MaxMana. Prevents the bot from continually
// dumping stones on the player just because an item dipped slightly.
private const double WornRefillPctOfMax = 0.25;
private const long ThinkIntervalMs = 600;
private const long ActionTimeoutMs = 8000;
private static long NowMs => Environment.TickCount64;
public ManaStoneManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache objectCache)
{
_host = host;
_settings = settings;
_objectCache = objectCache;
}
// ── Public API ────────────────────────────────────────────────────────────
public void OnHeartbeat(int busyCount)
{
if (!_settings.EnableManaTapping) { Reset(); return; }
if (!_settings.IsMacroRunning) { Reset(); return; }
long now = NowMs;
// Positive completion check: if the stone or target item is no longer
// in the cache, the action effectively completed (stone was destroyed
// mid-use, item drained and destroyed). Don't wait for chat — clear
// the state so we can issue the next action.
if (_state == TapState.TappingItem)
{
bool itemGone = _activeItemId != 0 && _objectCache[_activeItemId] == null;
bool stoneGone = _activeStoneId != 0 && _objectCache[_activeStoneId] == null;
if (itemGone || stoneGone)
{
_host.Log($"[RynthAi] ManaStone: tap completion detected (itemGone={itemGone} stoneGone={stoneGone}).");
GoIdle();
}
}
else if (_state == TapState.UsingOnPlayer)
{
if (_activeStoneId != 0 && _objectCache[_activeStoneId] == null)
{
_host.Log($"[RynthAi] ManaStone: use-on-player completion detected (stone destroyed).");
Reset();
}
}
// Check the action timeout BEFORE the busy-count gate. busyCount can get
// stuck > 0 (a server-side decrement that never lands), and if we waited
// for it we'd never recover. Without this, a single stuck use-on-player
// blocks the entire mana stone subsystem indefinitely.
if (_state != TapState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
_host.Log($"[RynthAi] ManaStone: action timeout in state {_state} after {now - _actionIssuedAt}ms (stone=0x{(uint)_activeStoneId:X8} item=0x{(uint)_activeItemId:X8}), resetting.");
// If a use-on-player keeps timing out with the same stone, blacklist
// the stone so subsequent ticks don't pick it again. Otherwise we'd
// re-select it every tick and never get to Priority 2 (drain looted).
if (_state == TapState.UsingOnPlayer && _activeStoneId != 0)
{
_stoneUseOnPlayerCooldownUntil[_activeStoneId] = now + StoneUseOnPlayerCooldownMs;
_host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for use-on-player ({StoneUseOnPlayerCooldownMs / 1000}s cooldown).");
}
// For the tap path, the STONE is the more likely culprit when an
// action silently fails — AC won't drain into a charged stone, so
// a "looks empty in cache" stone that's really charged keeps
// failing on every tap target. Park the stone, not the item.
if (_state == TapState.TappingItem && _activeStoneId != 0)
{
_stoneTapCooldownUntil[_activeStoneId] = now + StoneTapCooldownMs;
_host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for tap ({StoneTapCooldownMs / 1000}s cooldown).");
}
// ALSO shelve the TARGET item. A target that never completes a drain
// (server can't resolve the stone guid, item is retained/undrainable,
// it's a casting wand, etc.) is otherwise re-paired with the next
// empty stone on the very next think tick and loops forever — and
// every attempt issues UseObjectOn, which cancels the player's
// move-to chains and bumps m_cBusy, locking the character (and the
// bot's own casts) out of movement/combat. Shelving only the stone
// (above) does NOT break this loop because the WAND keeps getting
// selected. See [rynthai_respawn_blind_wedge] / 2026-06-22 wedge.
if (_state == TapState.TappingItem && _activeItemId != 0)
{
_tapTargetCooldownUntil[_activeItemId] = now + TapTargetCooldownMs;
_host.Log($"[RynthAi] ManaStone: shelving tap target 0x{(uint)_activeItemId:X8} for {TapTargetCooldownMs / 1000}s (drain never completed).");
}
Reset();
return; // let things settle before starting a new action this tick
}
if (!_host.HasUseObjectOn) return;
if (busyCount > 0) return;
if (now - _lastThinkAt < ThinkIntervalMs) return;
_lastThinkAt = now;
if (_state == TapState.Idle)
TryBeginAction();
}
public void OnChatWindowText(string? text)
{
if (string.IsNullOrEmpty(text)) return;
if (_state == TapState.TappingItem)
{
// "The Mana Stone drains X points of mana from the ..." — single drain,
// item is destroyed, stone is now charged. Back to idle so the next think
// tick can decide whether worn gear needs the charge yet.
if (text.Contains("The Mana Stone drains")
|| text.Contains("is destroyed")
|| text.Contains("has been destroyed"))
{
GoIdle();
return;
}
// "The X is already full of mana." — AC's response when we used a
// CHARGED stone on a non-equipped item (or a fully-loaded item). Our
// cache mis-read this stone as empty. Blacklist it for the tap path
// immediately so the next think tick picks a different stone.
if (text.Contains("is already full of mana") && _activeStoneId != 0)
{
_stoneKnownCharged.Add(_activeStoneId);
_stoneTapCooldownUntil.Remove(_activeStoneId); // supersede cooldown
_host.Log($"[RynthAi] ManaStone: stone 0x{(uint)_activeStoneId:X8} is actually charged (server: 'already full') — marking known-charged.");
GoIdle();
return;
}
return;
}
if (_state == TapState.UsingOnPlayer)
{
// "The Mana Stone gives X points of mana to ..." — transfer complete.
// The stone may also have been destroyed in the process; either way
// reset and let the next tick pick a fresh stone.
if (text.Contains("The Mana Stone gives")
|| text.Contains("The Mana Stone is destroyed"))
{
Reset();
}
}
}
// ── Private helpers ───────────────────────────────────────────────────────
private void TryBeginAction()
{
int threshold = _settings.ManaTapMinMana;
// Priority 1 (was 2): drain a tappable looted item into an empty stone.
// This wins over refilling worn gear because:
// * draining is the user's primary goal (loot-for-tap behavior),
// * the use-on-player path only accepts certain equipment slots and
// can loop forever on items like wielded weapons that AC won't
// refill via stone — that loop blacklists stones one by one and
// starves the drain path entirely.
int stoneId = FindEmptyStone();
int targetId = stoneId != 0 ? FindTapTarget(threshold) : 0;
if (stoneId != 0 && targetId != 0)
{
_activeStoneId = stoneId;
_activeItemId = targetId;
_host.Log($"[RynthAi] ManaStone: draining 0x{(uint)targetId:X8} with stone 0x{(uint)stoneId:X8}");
IssueTapItem(stoneId, targetId);
return;
}
// Priority 2 (was 1): refill worn gear with a charged stone, but only
// when there is nothing to drain right now.
if (WornEquipmentNeedsMana(threshold))
{
int chargedStone = FindChargedStone();
if (chargedStone != 0)
{
_activeStoneId = chargedStone;
_activeItemId = 0;
IssueUseOnPlayer();
return;
}
}
}
private void IssueTapItem(int stoneId, int itemId)
{
_state = TapState.TappingItem;
_actionIssuedAt = NowMs;
_host.UseObjectOn(unchecked((uint)stoneId), unchecked((uint)itemId));
}
private void IssueUseOnPlayer()
{
uint playerId = _host.GetPlayerId();
if (playerId == 0) { Reset(); return; }
// Confirm the stone still exists in inventory
if (_objectCache[_activeStoneId] == null) { Reset(); return; }
_host.Log($"[RynthAi] ManaStone: using charged stone 0x{(uint)_activeStoneId:X8} on player");
_state = TapState.UsingOnPlayer;
_actionIssuedAt = NowMs;
_host.UseObjectOn(unchecked((uint)_activeStoneId), playerId);
}
private void GoIdle()
{
_state = TapState.Idle;
_actionIssuedAt = 0;
}
private void Reset()
{
_state = TapState.Idle;
_activeStoneId = 0;
_activeItemId = 0;
_actionIssuedAt = 0;
}
/// <summary>
/// True if at least one configured mana stone in the player's inventory has zero charge.
/// CorpseOpenController uses this to decide whether to loot mana-bearing items for draining.
/// </summary>
public bool HasEmptyManaStone() => FindEmptyStone() != 0;
/// <summary>
/// Number of empty (zero-charge) configured mana stones currently in inventory.
/// </summary>
public int CountEmptyStones()
{
if (!_host.HasGetObjectIntProperty) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
int count = 0;
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (_stoneKnownCharged.Contains(item.Id)) continue;
bool readMana = _host.TryGetObjectIntProperty(unchecked((uint)item.Id),
(uint)AcIntProperty.CurrentMana, out int cur);
if (readMana && cur == 0)
_stoneTapCooldownUntil.Remove(item.Id);
if (_stoneTapCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
if (readMana && cur > 0) continue;
count++;
}
return count;
}
/// <summary>
/// Items already in the player's inventory that match the tap-target criteria
/// (mana ≥ threshold, not equipped, not loot-kept, not blacklisted). Each one
/// will eventually consume one empty stone, so they count against the
/// "free slots" quota that CorpseOpenController uses for ManaTap pickup.
/// </summary>
public int CountPendingDrainItems()
{
if (!_host.HasGetObjectIntProperty) return 0;
int threshold = _settings.ManaTapMinMana;
if (threshold <= 0) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
int count = 0;
foreach (var item in _objectCache.AllKnownObjects())
{
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
&& wield != 0) continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana)
|| curMana < threshold) continue;
count++;
}
return count;
}
/// <summary>
/// Free empty-stone slots = empty stones in inventory minus drain candidates
/// already in inventory waiting to be tapped. CorpseOpenController only
/// looks for new ManaTap pickups when this is &gt; 0.
/// </summary>
public int FreeEmptyStoneSlots() => Math.Max(0, CountEmptyStones() - CountPendingDrainItems());
/// <summary>
/// True when the item is a mana stone.
/// * If the user configured one or more ManaStone consumable rules, only
/// stones whose name matches a rule qualify (explicit opt-in to specific
/// stones — the user narrowed it on purpose).
/// * If there are no ManaStone rules and tapping is enabled, an item
/// qualifies if it's classified ObjectClass.ManaStone OR named
/// "Mana Stone" — so looting and tapping work with zero configuration.
/// The name fallback is load-bearing: items still on a corpse are
/// usually unappraised, AC hasn't sent ITEM_TYPE, so the cache can only
/// classify them Unknown. Name survives where ITEM_TYPE doesn't.
/// CorpseOpenController shares this predicate for both the loot gate and the
/// KeepCount inventory tally — they must agree or the cap stops working.
/// </summary>
public bool IsManaStone(WorldObject item)
{
bool hasRule = false;
foreach (var rule in _settings.ConsumableRules)
{
if (!rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase)) continue;
if (string.IsNullOrWhiteSpace(rule.Name)) continue;
hasRule = true;
if (rule.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
return true;
}
if (hasRule) return false; // explicit rules → match by name only
if (!_settings.EnableManaTapping) return false; // no rules → auto-detect only when tapping is on
if (item.ObjectClass == AcObjectClass.ManaStone) return true;
return !string.IsNullOrEmpty(item.Name)
&& item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase);
}
/// <summary>True if the item's container chain roots at the player's pack.</summary>
private bool IsOwnedByPlayer(WorldObject item, int playerId)
{
if (item.ObjectClass == AcObjectClass.Corpse) return false;
if (item.Wielder != 0 && playerId != 0 && item.Wielder != playerId) return false;
if (item.Container != 0 && playerId != 0 && item.Container != playerId)
{
var owner = _objectCache[item.Container];
if (owner == null || owner.ObjectClass == AcObjectClass.Corpse) return false;
if (owner.Wielder != playerId && owner.Container != playerId) return false;
}
return true;
}
/// <summary>Find a stone with no charge (CurrentMana == 0) — only those can drain an item.</summary>
private int FindEmptyStone()
{
if (!_host.HasGetObjectIntProperty) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Stones AC has explicitly told us are charged ("already full of
// mana") are never empty until they're consumed/destroyed.
if (_stoneKnownCharged.Contains(item.Id)) continue;
bool readMana = _host.TryGetObjectIntProperty(unchecked((uint)item.Id),
(uint)AcIntProperty.CurrentMana, out int curMana);
// If we can read CurrentMana and it's truly 0, the stone IS empty —
// clear any stale blacklist entry. This makes the cooldown self-heal
// once the cache catches up to the actual state.
if (readMana && curMana == 0)
_stoneTapCooldownUntil.Remove(item.Id);
// Skip stones that recently failed a tap so we don't loop on the
// same broken pair. The auto-clear above lets a stone return as
// soon as its real state is known.
if (_stoneTapCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
continue;
// Treat the stone as empty if CurrentMana is 0 OR unreadable.
// Unreadable happens for stones whose CBaseQualities InqInt isn't
// populated yet (cache race, partial classification). Being too
// strict here makes us blind to real empty stones; the stone-tap
// blacklist handles the misfires when an "empty-looking" stone
// is actually charged server-side.
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur)
&& cur > 0)
continue;
return item.Id;
}
return 0;
}
/// <summary>Find the most-charged mana stone in inventory (any positive charge).</summary>
private int FindChargedStone()
{
if (!_host.HasGetObjectIntProperty) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
int bestId = 0;
int bestMana = 0;
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Skip stones that timed out on use-on-player recently.
if (_stoneUseOnPlayerCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
continue;
if (cur <= 0) continue;
if (cur > bestMana) { bestMana = cur; bestId = item.Id; }
}
return bestId;
}
private int FindTapTarget(int threshold)
{
if (!_host.HasGetObjectIntProperty) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
foreach (var item in _objectCache.AllKnownObjects())
{
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Never tap a casting implement (wand/staff/orb). ACE refuses to
// drain mana out of these into a stone, so the tap can never complete
// and the loop spins forever (each attempt cancels movement + bumps
// busy). This is most often the character's OWN casting wand mis-read
// as a loose item — WieldedSlot can read 0 from a stale cache, so the
// equipped-skip below misses it. Mirrors CombatManager.IsWandObject.
if (IsWandLike(item)) continue;
// Skip items that recently failed to drain.
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
continue;
// Skip equipped items
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
&& wield != 0)
continue;
// Must currently hold at least the threshold worth of mana to be worth a drain
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana)
|| curMana < threshold)
continue;
return item.Id;
}
return 0;
}
/// <summary>
/// True for casting implements (wand/staff/orb). ACE will not drain mana out
/// of these into a mana stone, so they must never be selected as a tap target
/// — otherwise the tap can never complete and loops forever. ObjectClass alone
/// is unreliable for unappraised items, so we fall back to the name, matching
/// CombatManager/BuffManager.IsWandObject.
/// </summary>
private static bool IsWandLike(WorldObject item)
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);
private static bool IsWandName(string name)
{
if (string.IsNullOrEmpty(name)) return false;
return name.IndexOf("Orb", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Staff", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Wand", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Scepter", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Sceptre", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Baton", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Crozier", StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// True when at least one currently-worn item is BELOW its MaxMana AND
/// its CurrentMana sits under the configured refill threshold. The
/// MaxMana floor matters: an item with MaxMana=500 and CurrentMana=500
/// is full — refilling it is impossible, so it must not register as
/// "needs mana" or we get an infinite Priority-1 loop that blocks
/// Priority-2 looted-item draining.
/// </summary>
private bool WornEquipmentNeedsMana(int threshold)
{
if (!_host.HasGetObjectIntProperty) return false;
int playerId = unchecked((int)_host.GetPlayerId());
foreach (var item in _objectCache.AllKnownObjects())
{
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
|| wield == 0)
continue;
// Only items that actually consume mana matter
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.MaxMana, out int maxMana)
|| maxMana <= 0)
continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana))
continue;
// Refill only when an item has dropped to a small fraction of its
// MaxMana. The configured threshold is for *draining* loose items,
// not for "the player's robe is at 88% of full" — using min(threshold,
// maxMana) caused the bot to dump charged stones constantly on
// near-full equipment.
int floor = (int)(maxMana * WornRefillPctOfMax);
if (curMana < floor)
return true;
}
return false;
}
}

View file

@ -0,0 +1,236 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Maps;
/// <summary>
/// One D3D9 POOL_MANAGED A8R8G8B8 texture baked from a single Z-layer's floor cells.
/// Each texel covers one GridCell (0.5 AC units). Edge cells (cells bordering empty space)
/// use the bright wall colour; interior cells use the semi-transparent fill colour;
/// empty cells are fully transparent (alpha=0).
///
/// Displayed via dl.AddImageQuad — O(1) vertices per layer vs O(strips + edges) otherwise.
/// Disk-cached to C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layerIdx}.bin so
/// re-entering a dungeon skips the rasterise step.
/// </summary>
internal sealed class DungeonMapTexture : IDisposable
{
private const float GridCell = 0.5f;
private const string CacheDir = @"C:\Games\RynthSuite\RynthAi\Maps";
private const uint Magic = 0x524D5458u; // "XTMR"
// D3D9 vtable indices on IDirect3DDevice9 / IDirect3DTexture9
private const int VtCreateTexture = 23;
private const int VtLockRect = 19;
private const int VtUnlockRect = 20;
private const int VtRelease = 2;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_MANAGED = 1;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr shared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr pRect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr tex, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr obj);
[StructLayout(LayoutKind.Sequential)]
private struct D3DLockedRect { public int Pitch; public IntPtr pBits; }
// ── D3D9 A8R8G8B8 colour helpers (ARGB uint: A<<24|R<<16|G<<8|B) ─────
private static uint Argb(float r, float g, float b, float a) =>
((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f);
// Match DungeonMapUi colour definitions
private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f);
private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f);
private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f);
private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f);
private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f);
private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f);
// World bounds of the baked area
public float WorldX0, WorldY0, WorldX1, WorldY1;
public IntPtr TexId => _tex;
private IntPtr _tex;
private DungeonMapTexture() {}
/// <summary>
/// Returns a texture for the given floor-cell grid. Checks the disk cache first;
/// if absent, rasterises, uploads to D3D9, and saves to disk.
/// Returns null if device is invalid or texture upload fails.
/// </summary>
public static DungeonMapTexture? GetOrBuild(
IntPtr device,
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
uint landblock, int layerIdx)
{
if (device == IntPtr.Zero || cells.Count == 0) return null;
// Bounding box
int xMin = int.MaxValue, xMax = int.MinValue;
int yMin = int.MaxValue, yMax = int.MinValue;
foreach (var (gx, gy) in cells.Keys)
{
if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx;
if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy;
}
int w = xMax - xMin + 1, h = yMax - yMin + 1;
if (w <= 0 || h <= 0 || w > 8192 || h > 8192) return null;
// Try disk cache first (only valid when dimensions match the dat-computed bounds)
var cached = TryLoadFromDisk(device, landblock, layerIdx, xMin, yMin, w, h);
if (cached != null) return cached;
// Rasterise → upload → cache
var pixels = Rasterise(cells, xMin, yMax, w, h);
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
SaveToDisk(landblock, layerIdx, xMin, yMin, w, h, pixels);
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMax + 1) * GridCell,
WorldY1 = (yMax + 1) * GridCell,
};
}
public void Dispose()
{
if (_tex == IntPtr.Zero) return;
try { GetVtFunc<ReleaseD>(_tex, VtRelease)(_tex); } catch { }
_tex = IntPtr.Zero;
}
// ── Rasterisation ─────────────────────────────────────────────────────
private static uint[] Rasterise(
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
int xMin, int yMax, int w, int h)
{
var pixels = new uint[w * h]; // 0 = transparent
foreach (var ((gx, gy), ctype) in cells)
{
bool isEdge = !cells.ContainsKey((gx + 1, gy))
|| !cells.ContainsKey((gx - 1, gy))
|| !cells.ContainsKey((gx, gy + 1))
|| !cells.ContainsKey((gx, gy - 1));
uint col = isEdge
? ctype switch
{
DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp,
DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown,
_ => EdgeFlat,
}
: ctype switch
{
DungeonMapUi.CellType.SlopeUp => FillSlopeUp,
DungeonMapUi.CellType.SlopeDown => FillSlopeDown,
_ => FillFlat,
};
// Row 0 = northernmost cells (highest gy), so flip Y
pixels[(yMax - gy) * w + (gx - xMin)] = col;
}
return pixels;
}
// ── D3D9 upload ───────────────────────────────────────────────────────
private static unsafe IntPtr Upload(IntPtr device, int w, int h, uint[] pixels)
{
try
{
int hr = GetVtFunc<CreateTextureD>(device, VtCreateTexture)(
device, (uint)w, (uint)h, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
var locked = new D3DLockedRect();
hr = GetVtFunc<LockRectD>(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0);
if (hr < 0) { GetVtFunc<ReleaseD>(tex, VtRelease)(tex); return IntPtr.Zero; }
// Copy row by row — pitch may be wider than w*4
for (int row = 0; row < h; row++)
{
IntPtr dst = IntPtr.Add(locked.pBits, row * locked.Pitch);
fixed (uint* src = &pixels[row * w])
Buffer.MemoryCopy(src, (void*)dst, (nuint)(w * 4), (nuint)(w * 4));
}
GetVtFunc<UnlockRectD>(tex, VtUnlockRect)(tex, 0);
return tex;
}
catch { return IntPtr.Zero; }
}
// ── Disk cache ────────────────────────────────────────────────────────
private static DungeonMapTexture? TryLoadFromDisk(
IntPtr device, uint lb, int layerIdx,
int expXMin, int expYMin, int expW, int expH)
{
try
{
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
if (!File.Exists(path)) return null;
using var br = new BinaryReader(File.OpenRead(path));
if (br.ReadUInt32() != Magic) return null;
int xMin = br.ReadInt32(), yMin = br.ReadInt32();
int w = br.ReadInt32(), h = br.ReadInt32();
// Invalidate if bounds no longer match the dat
if (w != expW || h != expH || xMin != expXMin || yMin != expYMin) return null;
if (br.BaseStream.Length < 20L + (long)w * h * 4) return null;
var pixels = new uint[w * h];
for (int i = 0; i < pixels.Length; i++) pixels[i] = br.ReadUInt32();
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMin + w) * GridCell,
WorldY1 = (yMin + h) * GridCell,
};
}
catch { return null; }
}
private static void SaveToDisk(uint lb, int layerIdx, int xMin, int yMin, int w, int h, uint[] pixels)
{
try
{
Directory.CreateDirectory(CacheDir);
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
using var bw = new BinaryWriter(File.Open(path, FileMode.Create));
bw.Write(Magic); bw.Write(xMin); bw.Write(yMin); bw.Write(w); bw.Write(h);
foreach (uint px in pixels) bw.Write(px);
}
catch { }
}
// ── VTable helper ─────────────────────────────────────────────────────
private static unsafe TDelegate GetVtFunc<TDelegate>(IntPtr obj, int idx) where TDelegate : Delegate
{
void** vt = *(void***)obj;
return Marshal.GetDelegateForFunctionPointer<TDelegate>((IntPtr)vt[idx]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,337 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Saves MetaRules to .af (metaf) format.
/// </summary>
internal static class AfFileWriter
{
// .af keyword ↔ type now lives in MetaSchema (§3.3 single source of truth).
// ── Public API ──────────────────────────────────────────────────────────
public static string SaveToString(List<MetaRule> rules,
IReadOnlyDictionary<string, List<string>> embeddedNavs)
{
var sb = new System.Text.StringBuilder();
using var writer = new StringWriter(sb);
WriteContent(writer, rules, embeddedNavs);
return sb.ToString();
}
public static void Save(string filePath, List<MetaRule> rules,
IReadOnlyDictionary<string, List<string>> embeddedNavs)
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath) ?? ".");
using var writer = new StreamWriter(filePath, false);
WriteContent(writer, rules, embeddedNavs);
}
private static void WriteContent(TextWriter writer, List<MetaRule> rules,
IReadOnlyDictionary<string, List<string>> embeddedNavs)
{
// Group rules by state
var grouped = rules
.GroupBy(r => r.State)
.OrderBy(g => g.Key)
.ToList();
// Collect embedded nav routes referenced by rules
var navNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
CollectNavNames(rules, navNames);
// Write states
foreach (var group in grouped)
{
writer.WriteLine($"STATE: {{{group.Key}}} ~~ {{");
foreach (var rule in group)
WriteRule(writer, rule);
writer.WriteLine("~~ }");
}
// Write NAV sections for referenced nav routes (in-memory only)
foreach (string navName in navNames)
{
if (embeddedNavs.TryGetValue(navName, out var content))
WriteNavSection(writer, navName, content);
}
}
// ── Rule writing ────────────────────────────────────────────────────────
private static void WriteRule(TextWriter writer, MetaRule rule)
{
// Disabled marker (backward-compatible: a plain ~~ comment to old
// parsers, recognised by AfFileParser to set Enabled=false).
if (!rule.Enabled)
writer.WriteLine("\t~~ @disabled");
// Write IF: line
writer.Write("\tIF:\t");
WriteCondition(writer, rule, "\t\t\t\t");
writer.WriteLine();
// Write DO: line
writer.Write("\t\tDO:\t");
WriteAction(writer, rule, "\t\t\t\t\t");
writer.WriteLine();
}
private static void WriteCondition(TextWriter writer, MetaRule rule, string childIndent)
{
string keyword = MetaSchema.ConditionKeyword(rule.Condition);
// §2.6: typed vitals (MainHealthLE…VitaePHE) used to be written as
// Expr{…} here and reloaded as a generic Expression (lossy + slow).
// They now have real keywords in MetaSchema and fall through to the
// bare-numeric writer below, so they round-trip to the typed enum.
if (rule.Condition == MetaConditionType.All ||
rule.Condition == MetaConditionType.Any ||
rule.Condition == MetaConditionType.Not)
{
writer.Write(keyword);
if (rule.Children != null)
{
foreach (var child in rule.Children)
{
writer.WriteLine();
writer.Write(childIndent);
WriteCondition(writer, child, childIndent + "\t");
}
}
return;
}
// Simple conditions
string data = rule.ConditionData ?? "";
switch (rule.Condition)
{
case MetaConditionType.ChatMessage:
case MetaConditionType.Expression:
case MetaConditionType.PackSlots_LE:
case MetaConditionType.SecondsInState_GE:
case MetaConditionType.SecondsInStateP_GE:
case MetaConditionType.BurdenPercentage_GE:
case MetaConditionType.DistAnyRoutePT_GE:
case MetaConditionType.NoMonstersWithinDistance:
case MetaConditionType.Landblock_EQ:
case MetaConditionType.Landcell_EQ:
case MetaConditionType.MainHealthLE:
case MetaConditionType.MainHealthPHE:
case MetaConditionType.MainManaLE:
case MetaConditionType.MainManaPHE:
case MetaConditionType.MainStamLE:
case MetaConditionType.VitaePHE:
// Bare values (no braces): MainSlotsLE 4, MainHealthLE 50
writer.Write($"{keyword} {data}");
break;
case MetaConditionType.ChatMessageCapture:
writer.Write($"{keyword} {{{data}}} {{}}");
break;
case MetaConditionType.InventoryItemCount_LE:
case MetaConditionType.InventoryItemCount_GE:
{
// Format: ItemCountLE <count> {<name>}
var parts = data.Split(',');
string name = parts.Length > 0 ? parts[0] : "";
string count = parts.Length > 1 ? parts[1] : "0";
writer.Write($"{keyword} {count} {{{name}}}");
break;
}
case MetaConditionType.MonsterNameCountWithinDistance:
{
// Format: MobsInDist_Name <count> <distance> {<name>}
var parts = data.Split(',');
string name = parts.Length > 0 ? parts[0] : "";
string dist = parts.Length > 1 ? parts[1] : "0";
string count = parts.Length > 2 ? parts[2] : "0";
writer.Write($"{keyword} {count} {dist} {{{name}}}");
break;
}
case MetaConditionType.MonsterPriorityCountWithinDistance:
{
// Format: MobsInDist_Priority <count> <distance>
var parts = data.Split(',');
string count = parts.Length > 0 ? parts[0] : "0";
string dist = parts.Length > 1 ? parts[1] : "0";
writer.Write($"{keyword} {count} {dist}");
break;
}
case MetaConditionType.TimeLeftOnSpell_GE:
case MetaConditionType.TimeLeftOnSpell_LE:
{
// Format: SecsOnSpellGE <spell_id> <seconds>
var parts = data.Split(',');
string spellId = parts.Length > 0 ? parts[0] : "0";
string secs = parts.Length > 1 ? parts[1] : "0";
writer.Write($"{keyword} {spellId} {secs}");
break;
}
default:
// No-data conditions
writer.Write(keyword);
break;
}
}
private static void WriteAction(TextWriter writer, MetaRule rule, string childIndent)
{
string keyword = MetaSchema.ActionKeyword(rule.Action);
if (rule.Action == MetaActionType.All)
{
writer.Write(keyword);
var children = rule.ActionChildren ?? rule.Children ?? new List<MetaRule>();
foreach (var child in children)
{
writer.WriteLine();
writer.Write(childIndent);
WriteAction(writer, child, childIndent + "\t");
}
return;
}
string data = rule.ActionData ?? "";
switch (rule.Action)
{
case MetaActionType.SetMetaState:
case MetaActionType.ChatCommand:
case MetaActionType.ExpressionAction:
case MetaActionType.ChatExpression:
case MetaActionType.DestroyView:
writer.Write($"{keyword} {{{data}}}");
break;
case MetaActionType.CallMetaState:
// Format: CallState {<target>} {<return>}
writer.Write($"{keyword} {{{data}}} {{{rule.State}}}");
break;
case MetaActionType.EmbeddedNavRoute:
{
string navName = string.IsNullOrEmpty(data) ? "empty" : data.Split(';')[0];
writer.Write($"{keyword} {navName} {{[none]}}");
break;
}
case MetaActionType.SetWatchdog:
{
// Format: SetWatchdog <distance> <seconds> {<state>}
var parts = data.Split(';');
string state = parts.Length > 0 ? parts[0] : "Default";
string range = parts.Length > 1 ? parts[1] : "10";
string time = parts.Length > 2 ? parts[2] : "60";
writer.Write($"{keyword} {range} {time} {{{state}}}");
break;
}
case MetaActionType.SetRAOption:
{
var parts = data.Split(';');
string option = parts.Length > 0 ? parts[0] : "";
string value = parts.Length > 1 ? parts[1] : "";
writer.Write($"{keyword} {{{option}}} {{{value}}}");
break;
}
case MetaActionType.GetRAOption:
{
var parts = data.Split(';');
string variable = parts.Length > 0 ? parts[0] : "";
string option = parts.Length > 1 ? parts[1] : "";
writer.Write($"{keyword} {{{variable}}} {{{option}}}");
break;
}
case MetaActionType.CreateView:
{
int semi = data.IndexOf(';');
string name = semi >= 0 ? data.Substring(0, semi) : data;
string xml = semi >= 0 ? data.Substring(semi + 1) : "";
writer.Write($"{keyword} {{{name}}} {{{xml}}}");
break;
}
default:
// No-data actions
writer.Write(keyword);
break;
}
}
// ── NAV section writing ─────────────────────────────────────────────────
private static void WriteNavSection(TextWriter writer, string navName, IReadOnlyList<string> lines)
{
if (lines.Count < 3) return;
// Verbatim, count-prefixed passthrough of the canonical uTank2 nav lines
// (the same representation MetFileParser/NavRouteParser use). Lossless for
// EVERY waypoint type. The previous per-token writer assumed an 11-line
// type-6 trailer (vs the canonical 6: name,class,tie,exitEW,exitNS,exitZ)
// and had no case for type 5 (Vendor) / 7 (NPC) at all, so it desynced and
// truncated every .met-sourced route at its first Portal/Vendor/NPC point.
// Count prefix means a waypoint string that happens to contain "~~ }"
// cannot terminate the block early. Legacy human-readable NAV: sections are
// still parsed on read for metaf-file compatibility.
writer.WriteLine($"NAVDATA: {navName} {lines.Count} ~~ {{");
foreach (string l in lines) writer.WriteLine(l);
writer.WriteLine("~~ }");
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static void CollectNavNames(List<MetaRule> rules, HashSet<string> navNames)
{
foreach (var rule in rules)
{
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
!string.IsNullOrEmpty(rule.ActionData))
{
navNames.Add(rule.ActionData.Split(';')[0]);
}
if (rule.ActionChildren != null)
CollectNavNames(rule.ActionChildren, navNames);
if (rule.Children != null)
CollectNavNames(rule.Children, navNames);
}
}
private static string SpellIdToRecallName(int spellId)
{
return spellId switch
{
2931 => "Recall Aphus Lassel",
1635 => "Lifestone Recall",
48 => "Primary Portal Recall",
2647 => "Secondary Portal Recall",
2645 => "Portal Recall",
2023 => "Recall the Sanctuary",
4213 => "Call of the Mhoire Forge",
3865 => "Glenden Wood Recall",
2041 => "Aerlinthe Recall",
4084 => "Colosseum Recall",
5541 => "Facility Hub Recall",
5542 => "Gear Knight Recall",
5543 => "Neftet Recall",
6321 => "Rynthid Recall",
6322 => "Viridian Rise Recall",
_ => $"Spell {spellId}"
};
}
}

View file

@ -0,0 +1,180 @@
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RynthAi Chat Commands — /ra <command>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
All commands are entered in the AC chat window prefixed with /ra.
Commands are case-insensitive.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GENERAL
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/ra help
Show the in-game command list.
/ra power [0-100|auto]
Get or set melee/missile attack power percentage.
"auto" = recklessness-aware automatic power selection.
Example: /ra power 90
Example: /ra power auto
/ra buffs
Show active buff timers for the player.
/ra cast <spellId>
Cast a spell by ID on the current target.
Example: /ra cast 2648
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
OBJECT INTERACTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Object search flags (suffix on use/select commands):
(none) search both inventory and landscape, exact name match
i inventory only, exact match
l landscape only, exact match
p both, partial (contains) match
pi inventory only, partial match
lp landscape only, partial match
/ra use <name>
Use the object with the exact given name.
Searches inventory first, then landscape.
Example: /ra use Mana Elixir
/ra usei <name>
Use an inventory item by exact name.
Example: /ra usei Stamina Elixir
/ra usel <name>
Use a landscape object by exact name.
Example: /ra usel Forge
/ra usep <name>
Use the first object whose name contains the given string (inventory + landscape).
Example: /ra usep elixir
/ra usepi <name>
Use the first inventory item whose name contains the given string.
Example: /ra usepi mana
/ra uselp <name>
Use the first landscape object whose name contains the given string.
Example: /ra uselp plant
/ra use <name1> on <name2>
Use one object on another. Both names use the same search scope as the variant.
Example: /ra use Salvage Tool on Gold Ore
Example: /ra usepi split on gold
/ra select <name>
Target/select the object with the exact given name.
Searches inventory first, then landscape.
Example: /ra select Mana Elixir
/ra selecti <name>
Select an inventory item by exact name.
Example: /ra selecti Stamina Elixir
/ra selectl <name>
Select a landscape object by exact name.
Example: /ra selectl Chest
/ra selectp <name>
Select the first object whose name contains the given string (inventory + landscape).
Example: /ra selectp elixir
/ra selectpi <name>
Select the first inventory item whose name contains the given string.
Example: /ra selectpi mana
/ra selectlp <name>
Select the first landscape object whose name contains the given string.
Example: /ra selectlp chest
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
META / SCRIPTING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/ra mexec <expression>
Evaluate a meta expression and print the result.
Type annotation ([number], [string], [List]) shown before the result.
Example: /ra mexec sqrt[2]
Example: /ra mexec listcreate[1,2,3]
Example: /ra mexec wobjectgetname[wobjectgetselection[]]
See ExpressionReference.txt for the full expression function reference.
/ra listvars
Show all currently set meta variables with their type and value.
Output format: <name> (<type>) = <value>
Example output:
myList (List) = [a,b,c]
myCount (number) = 5
myName (string) = Aluvian Warrior
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DIAGNOSTICS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/ra scan
Show all nearby monsters from the object cache with their IDs.
/ra attackable
Check whether the current target is flagged as attackable.
/ra wielded
Show all currently wielded/equipped items.
/ra dumpprops
Dump all known integer, float, bool, and string properties for the player.
/ra dumpinv
Dump all inventory items from both the cache and the direct container scan.
/ra cache
Show a summary of the object cache (creature/inventory/landscape counts).
/ra cache2
Show raw object IDs currently tracked in the object cache.
/ra corpseinfo
Show corpse looting range and open diagnostics for nearby corpses.
/ra corpsecheck
Explain whether the nearest corpse would be looted by the current loot profile.
/ra corpseopen
Force the nearest corpse open flow (bypasses normal loot logic).
/ra lootparse
Inspect and parse the currently selected loot profile, showing rule breakdown.
/ra lootcheckinv
Test the active loot profile against every item in inventory and report results.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NAVIGATION / GEOMETRY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/ra navdebug
Show current player coordinates, heading, cell ID, and nav debug info.
/ra buildinfo
Show geometry and building mesh info for the current landblock.
/ra raycast
Show raycast system status (whether the DAT database is loaded, etc.).
/ra lostest
Run a line-of-sight raycast test from the player to the current target.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FELLOWSHIP
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/ra fellow [subcommand]
/ra fellowship [subcommand]
Fellowship diagnostics and queries.
/ra fellowinfo
Show fellowship tracker state (members, XP sharing status, etc.).

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Result of loading a .af or .met file: rules plus any embedded NAV routes
/// that ship inside the macro. Embedded navs stay in memory — they are never
/// extracted to the NavProfiles folder.
/// </summary>
internal sealed class LoadedMeta
{
public List<MetaRule> Rules { get; set; } = new();
public Dictionary<string, List<string>> EmbeddedNavs { get; } =
new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Non-fatal parse problems (unknown keywords, parse exception). Surfaced
/// to the user on load so a typo'd / unsupported meta is visible instead of
/// silently producing zero or partial rules.
/// </summary>
public List<string> Warnings { get; } = new();
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Single source of truth for the meta condition/action vocabulary (§3.3).
///
/// Replaces the hand-synced pairs that used to drift apart:
/// • AfFileParser.ConditionKeywords / ActionKeywords (.af read)
/// • AfFileWriter.ConditionKeywordMap / ActionKeywordMap (.af write)
/// • LegacyMetaUi._metaConditionNames / _metaActionNames (ImGui labels)
/// (the §2.6 SecsOnSpell _LE→_GE data-loss bug was exactly a read/write map
/// desync). The arrays here are ordered by the enum int value, which is the
/// real wire contract (JSON bridge sends (int)Condition; the engine-side
/// MetaPanel label array and the .met VTank map all key off it). A static
/// self-check flags drift instead of letting it corrupt saves silently.
///
/// NOT folded in: MetFileParser's VTankCType/AType maps — those translate
/// VTank's *own* binary protocol numbering to our enum and are a separate
/// concern (an adapter, not a duplicate). And the engine-repo MetaPanel label
/// array can't be referenced from the plugin; the drift-check at least catches
/// an enum reorder that would silently break that contract.
///
/// No reflection / no custom attributes — explicit arrays are NativeAOT-safe
/// and deterministic (the review's "reflection at startup" suggestion would be
/// trim-fragile here).
/// </summary>
internal static class MetaSchema
{
internal readonly record struct CondInfo(MetaConditionType Type, string Keyword, string Label);
internal readonly record struct ActInfo(MetaActionType Type, string Keyword, string Label);
// Index == (int)MetaConditionType. Keyword is the .af token (W2b gives the
// typed-vital rows real keywords so they round-trip instead of being
// written as Expr{…} and reloaded as a generic Expression).
internal static readonly CondInfo[] Conditions =
{
new(MetaConditionType.Never, "Never", "Never"),
new(MetaConditionType.Always, "Always", "Always"),
new(MetaConditionType.All, "All", "All"),
new(MetaConditionType.Any, "Any", "Any"),
new(MetaConditionType.ChatMessage, "ChatMatch", "Chat Message"),
new(MetaConditionType.PackSlots_LE, "MainSlotsLE", "Pack Slots <="),
new(MetaConditionType.SecondsInState_GE, "SecsInStateGE", "Seconds in State >="),
new(MetaConditionType.CharacterDeath, "Death", "Character Death"),
new(MetaConditionType.AnyVendorOpen, "VendorOpen", "Any Vendor Open"),
new(MetaConditionType.VendorClosed, "VendorClosed", "Vendor Closed"),
new(MetaConditionType.InventoryItemCount_LE, "ItemCountLE", "Inventory Item Count <="),
new(MetaConditionType.InventoryItemCount_GE, "ItemCountGE", "Inventory Item Count >="),
new(MetaConditionType.MonsterNameCountWithinDistance, "MobsInDist_Name", "Monster Name Count Within Distance"),
new(MetaConditionType.MonsterPriorityCountWithinDistance, "MobsInDist_Priority", "Monster Priority Count Within Distance"),
new(MetaConditionType.NeedToBuff, "NeedToBuff", "Need To Buff"),
new(MetaConditionType.NoMonstersWithinDistance, "NoMobsInDist", "No Monsters Within Distance"),
new(MetaConditionType.Landblock_EQ, "BlockE", "Landblock =="),
new(MetaConditionType.Landcell_EQ, "CellE", "Landcell =="),
new(MetaConditionType.PortalspaceEntered, "IntoPortal", "Portalspace Entered"),
new(MetaConditionType.PortalspaceExited, "ExitPortal", "Portalspace Exited"),
new(MetaConditionType.Not, "Not", "Not"),
new(MetaConditionType.SecondsInStateP_GE, "PSecsInStateGE", "Seconds in State (P) >="),
new(MetaConditionType.TimeLeftOnSpell_GE, "SecsOnSpellGE", "Time Left On Spell >="),
new(MetaConditionType.TimeLeftOnSpell_LE, "SecsOnSpellLE", "Time Left On Spell <="),
new(MetaConditionType.BurdenPercentage_GE, "BuPercentGE", "Burden Percentage >="),
new(MetaConditionType.DistAnyRoutePT_GE, "DistToRteGE", "Dist Any Route PT >="),
new(MetaConditionType.Expression, "Expr", "Expression"),
new(MetaConditionType.ChatMessageCapture, "ChatCapture", "Chat Message Capture"),
new(MetaConditionType.NavrouteEmpty, "NavEmpty", "Navroute Empty"),
new(MetaConditionType.MainHealthLE, "MainHealthLE", "Main Health <="),
new(MetaConditionType.MainHealthPHE, "MainHealthPHE", "Main Health % >="),
new(MetaConditionType.MainManaLE, "MainManaLE", "Main Mana <="),
new(MetaConditionType.MainManaPHE, "MainManaPHE", "Main Mana % >="),
new(MetaConditionType.MainStamLE, "MainStamLE", "Main Stam <="),
new(MetaConditionType.VitaePHE, "VitaePHE", "Vitae % >="),
};
// Index == (int)MetaActionType.
internal static readonly ActInfo[] Actions =
{
new(MetaActionType.None, "None", "None"),
new(MetaActionType.ChatCommand, "Chat", "Chat Command"),
new(MetaActionType.SetMetaState, "SetState", "Set Meta State"),
new(MetaActionType.EmbeddedNavRoute, "EmbedNav", "Embedded Nav Route"),
new(MetaActionType.All, "DoAll", "All"),
new(MetaActionType.CallMetaState, "CallState", "Call Meta State"),
new(MetaActionType.ReturnFromCall, "Return", "Return From Call"),
new(MetaActionType.ExpressionAction, "DoExpr", "Expression Action"),
new(MetaActionType.ChatExpression, "ChatExpr", "Chat Expression"),
new(MetaActionType.SetWatchdog, "SetWatchdog", "Set Watchdog"),
new(MetaActionType.ClearWatchdog, "ClearWatchdog", "Clear Watchdog"),
new(MetaActionType.GetRAOption, "GetOpt", "Get RA Option"),
new(MetaActionType.SetRAOption, "SetOpt", "Set RA Option"),
new(MetaActionType.CreateView, "CreateView", "Create View"),
new(MetaActionType.DestroyView, "DestroyView", "Destroy View"),
new(MetaActionType.DestroyAllViews, "DestroyAllViews", "Destroy All Views"),
};
private static readonly Dictionary<string, MetaConditionType> _condByKeyword =
new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, MetaActionType> _actByKeyword =
new(StringComparer.OrdinalIgnoreCase);
private static readonly string[] _condLabels;
private static readonly string[] _actLabels;
/// <summary>Non-null if the schema arrays drifted from the enums. Logged
/// once by MetaManager rather than thrown (a broken meta UI beats a dead
/// plugin).</summary>
internal static string? DriftError { get; }
static MetaSchema()
{
foreach (var c in Conditions) _condByKeyword[c.Keyword] = c.Type;
foreach (var a in Actions) _actByKeyword[a.Keyword] = a.Type;
_condLabels = Array.ConvertAll(Conditions, c => c.Label);
_actLabels = Array.ConvertAll(Actions, a => a.Label);
var errs = new List<string>();
var condVals = Enum.GetValues<MetaConditionType>();
if (Conditions.Length != condVals.Length)
errs.Add($"condition count {Conditions.Length} != enum {condVals.Length}");
else
for (int i = 0; i < Conditions.Length; i++)
if ((int)Conditions[i].Type != i)
errs.Add($"condition[{i}] is {Conditions[i].Type} (={(int)Conditions[i].Type}), expected enum value {i}");
var actVals = Enum.GetValues<MetaActionType>();
if (Actions.Length != actVals.Length)
errs.Add($"action count {Actions.Length} != enum {actVals.Length}");
else
for (int i = 0; i < Actions.Length; i++)
if ((int)Actions[i].Type != i)
errs.Add($"action[{i}] is {Actions[i].Type} (={(int)Actions[i].Type}), expected enum value {i}");
DriftError = errs.Count == 0 ? null : string.Join("; ", errs);
}
// ── Lookups ───────────────────────────────────────────────────────────────
public static bool TryCondition(string keyword, out MetaConditionType type)
=> _condByKeyword.TryGetValue(keyword, out type);
public static bool TryAction(string keyword, out MetaActionType type)
=> _actByKeyword.TryGetValue(keyword, out type);
public static string ConditionKeyword(MetaConditionType t)
=> (int)t >= 0 && (int)t < Conditions.Length ? Conditions[(int)t].Keyword : "Never";
public static string ActionKeyword(MetaActionType t)
=> (int)t >= 0 && (int)t < Actions.Length ? Actions[(int)t].Keyword : "None";
/// <summary>Display labels indexed by enum int — for the ImGui combos.</summary>
public static string[] ConditionLabels => _condLabels;
public static string[] ActionLabels => _actLabels;
}

View file

@ -0,0 +1,643 @@
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// AC property-id → name, generated from ACE's PropertyInt/PropertyBool/
/// PropertyString enums. SPARSE on purpose: the real AC enums have gaps, so the
/// old dense position-indexed string[] mislabelled every property after the
/// first gap (the bug the SalvageManager STypes constants worked around).
/// Used by the dumpprops diagnostic. Returns null for unknown ids.
/// </summary>
internal static class PropertyNames
{
private static readonly Dictionary<uint, string> IntNames = new()
{
{ 0, "Undef" },
{ 1, "ItemType" },
{ 2, "CreatureType" },
{ 3, "PaletteTemplate" },
{ 4, "ClothingPriority" },
{ 5, "EncumbranceVal" },
{ 6, "ItemsCapacity" },
{ 7, "ContainersCapacity" },
{ 8, "Mass" },
{ 9, "ValidLocations" },
{ 10, "CurrentWieldedLocation" },
{ 11, "MaxStackSize" },
{ 12, "StackSize" },
{ 13, "StackUnitEncumbrance" },
{ 14, "StackUnitMass" },
{ 15, "StackUnitValue" },
{ 16, "ItemUseable" },
{ 17, "RareId" },
{ 18, "UiEffects" },
{ 19, "Value" },
{ 20, "CoinValue" },
{ 21, "TotalExperience" },
{ 22, "AvailableCharacter" },
{ 23, "TotalSkillCredits" },
{ 24, "AvailableSkillCredits" },
{ 25, "Level" },
{ 26, "AccountRequirements" },
{ 27, "ArmorType" },
{ 28, "ArmorLevel" },
{ 29, "AllegianceCpPool" },
{ 30, "AllegianceRank" },
{ 31, "ChannelsAllowed" },
{ 32, "ChannelsActive" },
{ 33, "Bonded" },
{ 34, "MonarchsRank" },
{ 35, "AllegianceFollowers" },
{ 36, "ResistMagic" },
{ 37, "ResistItemAppraisal" },
{ 38, "ResistLockpick" },
{ 39, "DeprecatedResistRepair" },
{ 40, "CombatMode" },
{ 41, "CurrentAttackHeight" },
{ 42, "CombatCollisions" },
{ 43, "NumDeaths" },
{ 44, "Damage" },
{ 45, "DamageType" },
{ 46, "DefaultCombatStyle" },
{ 47, "AttackType" },
{ 48, "WeaponSkill" },
{ 49, "WeaponTime" },
{ 50, "AmmoType" },
{ 51, "CombatUse" },
{ 52, "ParentLocation" },
{ 53, "PlacementPosition" },
{ 54, "WeaponEncumbrance" },
{ 55, "WeaponMass" },
{ 56, "ShieldValue" },
{ 57, "ShieldEncumbrance" },
{ 58, "MissileInventoryLocation" },
{ 59, "FullDamageType" },
{ 60, "WeaponRange" },
{ 61, "AttackersSkill" },
{ 62, "DefendersSkill" },
{ 63, "AttackersSkillValue" },
{ 64, "AttackersClass" },
{ 65, "Placement" },
{ 66, "CheckpointStatus" },
{ 67, "Tolerance" },
{ 68, "TargetingTactic" },
{ 69, "CombatTactic" },
{ 70, "HomesickTargetingTactic" },
{ 71, "NumFollowFailures" },
{ 72, "FriendType" },
{ 73, "FoeType" },
{ 74, "MerchandiseItemTypes" },
{ 75, "MerchandiseMinValue" },
{ 76, "MerchandiseMaxValue" },
{ 77, "NumItemsSold" },
{ 78, "NumItemsBought" },
{ 79, "MoneyIncome" },
{ 80, "MoneyOutflow" },
{ 81, "MaxGeneratedObjects" },
{ 82, "InitGeneratedObjects" },
{ 83, "ActivationResponse" },
{ 84, "OriginalValue" },
{ 85, "NumMoveFailures" },
{ 86, "MinLevel" },
{ 87, "MaxLevel" },
{ 88, "LockpickMod" },
{ 89, "BoosterEnum" },
{ 90, "BoostValue" },
{ 91, "MaxStructure" },
{ 92, "Structure" },
{ 93, "PhysicsState" },
{ 94, "TargetType" },
{ 95, "RadarBlipColor" },
{ 96, "EncumbranceCapacity" },
{ 97, "LoginTimestamp" },
{ 98, "CreationTimestamp" },
{ 99, "PkLevelModifier" },
{ 100, "GeneratorType" },
{ 101, "AiAllowedCombatStyle" },
{ 102, "LogoffTimestamp" },
{ 103, "GeneratorDestructionType" },
{ 104, "ActivationCreateClass" },
{ 105, "ItemWorkmanship" },
{ 106, "ItemSpellcraft" },
{ 107, "ItemCurMana" },
{ 108, "ItemMaxMana" },
{ 109, "ItemDifficulty" },
{ 110, "ItemAllegianceRankLimit" },
{ 111, "PortalBitmask" },
{ 112, "AdvocateLevel" },
{ 113, "Gender" },
{ 114, "Attuned" },
{ 115, "ItemSkillLevelLimit" },
{ 116, "GateLogic" },
{ 117, "ItemManaCost" },
{ 118, "Logoff" },
{ 119, "Active" },
{ 120, "AttackHeight" },
{ 121, "NumAttackFailures" },
{ 122, "AiCpThreshold" },
{ 123, "AiAdvancementStrategy" },
{ 124, "Version" },
{ 125, "Age" },
{ 126, "VendorHappyMean" },
{ 127, "VendorHappyVariance" },
{ 128, "CloakStatus" },
{ 129, "VitaeCpPool" },
{ 130, "NumServicesSold" },
{ 131, "MaterialType" },
{ 132, "NumAllegianceBreaks" },
{ 133, "ShowableOnRadar" },
{ 134, "PlayerKillerStatus" },
{ 135, "VendorHappyMaxItems" },
{ 136, "ScorePageNum" },
{ 137, "ScoreConfigNum" },
{ 138, "ScoreNumScores" },
{ 139, "DeathLevel" },
{ 140, "AiOptions" },
{ 141, "OpenToEveryone" },
{ 142, "GeneratorTimeType" },
{ 143, "GeneratorStartTime" },
{ 144, "GeneratorEndTime" },
{ 145, "GeneratorEndDestructionType" },
{ 146, "XpOverride" },
{ 147, "NumCrashAndTurns" },
{ 148, "ComponentWarningThreshold" },
{ 149, "HouseStatus" },
{ 150, "HookPlacement" },
{ 151, "HookType" },
{ 152, "HookItemType" },
{ 153, "AiPpThreshold" },
{ 154, "GeneratorVersion" },
{ 155, "HouseType" },
{ 156, "PickupEmoteOffset" },
{ 157, "WeenieIteration" },
{ 158, "WieldRequirements" },
{ 159, "WieldSkillType" },
{ 160, "WieldDifficulty" },
{ 161, "HouseMaxHooksUsable" },
{ 162, "HouseCurrentHooksUsable" },
{ 163, "AllegianceMinLevel" },
{ 164, "AllegianceMaxLevel" },
{ 165, "HouseRelinkHookCount" },
{ 166, "SlayerCreatureType" },
{ 167, "ConfirmationInProgress" },
{ 168, "ConfirmationTypeInProgress" },
{ 169, "TsysMutationData" },
{ 170, "NumItemsInMaterial" },
{ 171, "NumTimesTinkered" },
{ 172, "AppraisalLongDescDecoration" },
{ 173, "AppraisalLockpickSuccessPercent" },
{ 174, "AppraisalPages" },
{ 175, "AppraisalMaxPages" },
{ 176, "AppraisalItemSkill" },
{ 177, "GemCount" },
{ 178, "GemType" },
{ 179, "ImbuedEffect" },
{ 180, "AttackersRawSkillValue" },
{ 181, "ChessRank" },
{ 182, "ChessTotalGames" },
{ 183, "ChessGamesWon" },
{ 184, "ChessGamesLost" },
{ 185, "TypeOfAlteration" },
{ 186, "SkillToBeAltered" },
{ 187, "SkillAlterationCount" },
{ 188, "HeritageGroup" },
{ 189, "TransferFromAttribute" },
{ 190, "TransferToAttribute" },
{ 191, "AttributeTransferCount" },
{ 192, "FakeFishingSkill" },
{ 193, "NumKeys" },
{ 194, "DeathTimestamp" },
{ 195, "PkTimestamp" },
{ 196, "VictimTimestamp" },
{ 197, "HookGroup" },
{ 198, "AllegianceSwearTimestamp" },
{ 199, "HousePurchaseTimestamp" },
{ 200, "RedirectableEquippedArmorCount" },
{ 201, "MeleeDefenseImbuedEffectTypeCache" },
{ 202, "MissileDefenseImbuedEffectTypeCache" },
{ 203, "MagicDefenseImbuedEffectTypeCache" },
{ 204, "ElementalDamageBonus" },
{ 205, "ImbueAttempts" },
{ 206, "ImbueSuccesses" },
{ 207, "CreatureKills" },
{ 208, "PlayerKillsPk" },
{ 209, "PlayerKillsPkl" },
{ 210, "RaresTierOne" },
{ 211, "RaresTierTwo" },
{ 212, "RaresTierThree" },
{ 213, "RaresTierFour" },
{ 214, "RaresTierFive" },
{ 215, "AugmentationStat" },
{ 216, "AugmentationFamilyStat" },
{ 217, "AugmentationInnateFamily" },
{ 218, "AugmentationInnateStrength" },
{ 219, "AugmentationInnateEndurance" },
{ 220, "AugmentationInnateCoordination" },
{ 221, "AugmentationInnateQuickness" },
{ 222, "AugmentationInnateFocus" },
{ 223, "AugmentationInnateSelf" },
{ 224, "AugmentationSpecializeSalvaging" },
{ 225, "AugmentationSpecializeItemTinkering" },
{ 226, "AugmentationSpecializeArmorTinkering" },
{ 227, "AugmentationSpecializeMagicItemTinkering" },
{ 228, "AugmentationSpecializeWeaponTinkering" },
{ 229, "AugmentationExtraPackSlot" },
{ 230, "AugmentationIncreasedCarryingCapacity" },
{ 231, "AugmentationLessDeathItemLoss" },
{ 232, "AugmentationSpellsRemainPastDeath" },
{ 233, "AugmentationCriticalDefense" },
{ 234, "AugmentationBonusXp" },
{ 235, "AugmentationBonusSalvage" },
{ 236, "AugmentationBonusImbueChance" },
{ 237, "AugmentationFasterRegen" },
{ 238, "AugmentationIncreasedSpellDuration" },
{ 239, "AugmentationResistanceFamily" },
{ 240, "AugmentationResistanceSlash" },
{ 241, "AugmentationResistancePierce" },
{ 242, "AugmentationResistanceBlunt" },
{ 243, "AugmentationResistanceAcid" },
{ 244, "AugmentationResistanceFire" },
{ 245, "AugmentationResistanceFrost" },
{ 246, "AugmentationResistanceLightning" },
{ 247, "RaresTierOneLogin" },
{ 248, "RaresTierTwoLogin" },
{ 249, "RaresTierThreeLogin" },
{ 250, "RaresTierFourLogin" },
{ 251, "RaresTierFiveLogin" },
{ 252, "RaresLoginTimestamp" },
{ 253, "RaresTierSix" },
{ 254, "RaresTierSeven" },
{ 255, "RaresTierSixLogin" },
{ 256, "RaresTierSevenLogin" },
{ 257, "ItemAttributeLimit" },
{ 258, "ItemAttributeLevelLimit" },
{ 259, "ItemAttribute2ndLimit" },
{ 260, "ItemAttribute2ndLevelLimit" },
{ 261, "CharacterTitleId" },
{ 262, "NumCharacterTitles" },
{ 263, "ResistanceModifierType" },
{ 264, "FreeTinkersBitfield" },
{ 265, "EquipmentSetId" },
{ 266, "PetClass" },
{ 267, "Lifespan" },
{ 268, "RemainingLifespan" },
{ 269, "UseCreateQuantity" },
{ 270, "WieldRequirements2" },
{ 271, "WieldSkillType2" },
{ 272, "WieldDifficulty2" },
{ 273, "WieldRequirements3" },
{ 274, "WieldSkillType3" },
{ 275, "WieldDifficulty3" },
{ 276, "WieldRequirements4" },
{ 277, "WieldSkillType4" },
{ 278, "WieldDifficulty4" },
{ 279, "Unique" },
{ 280, "SharedCooldown" },
{ 281, "Faction1Bits" },
{ 282, "Faction2Bits" },
{ 283, "Faction3Bits" },
{ 284, "Hatred1Bits" },
{ 285, "Hatred2Bits" },
{ 286, "Hatred3Bits" },
{ 287, "SocietyRankCelhan" },
{ 288, "SocietyRankEldweb" },
{ 289, "SocietyRankRadblo" },
{ 290, "HearLocalSignals" },
{ 291, "HearLocalSignalsRadius" },
{ 292, "Cleaving" },
{ 293, "AugmentationSpecializeGearcraft" },
{ 294, "AugmentationInfusedCreatureMagic" },
{ 295, "AugmentationInfusedItemMagic" },
{ 296, "AugmentationInfusedLifeMagic" },
{ 297, "AugmentationInfusedWarMagic" },
{ 298, "AugmentationCriticalExpertise" },
{ 299, "AugmentationCriticalPower" },
{ 300, "AugmentationSkilledMelee" },
{ 301, "AugmentationSkilledMissile" },
{ 302, "AugmentationSkilledMagic" },
{ 303, "ImbuedEffect2" },
{ 304, "ImbuedEffect3" },
{ 305, "ImbuedEffect4" },
{ 306, "ImbuedEffect5" },
{ 307, "DamageRating" },
{ 308, "DamageResistRating" },
{ 309, "AugmentationDamageBonus" },
{ 310, "AugmentationDamageReduction" },
{ 311, "ImbueStackingBits" },
{ 312, "HealOverTime" },
{ 313, "CritRating" },
{ 314, "CritDamageRating" },
{ 315, "CritResistRating" },
{ 316, "CritDamageResistRating" },
{ 317, "HealingResistRating" },
{ 318, "DamageOverTime" },
{ 319, "ItemMaxLevel" },
{ 320, "ItemXpStyle" },
{ 321, "EquipmentSetExtra" },
{ 322, "AetheriaBitfield" },
{ 323, "HealingBoostRating" },
{ 324, "HeritageSpecificArmor" },
{ 325, "AlternateRacialSkills" },
{ 326, "AugmentationJackOfAllTrades" },
{ 327, "AugmentationResistanceNether" },
{ 328, "AugmentationInfusedVoidMagic" },
{ 329, "WeaknessRating" },
{ 330, "NetherOverTime" },
{ 331, "NetherResistRating" },
{ 332, "LuminanceAward" },
{ 333, "LumAugDamageRating" },
{ 334, "LumAugDamageReductionRating" },
{ 335, "LumAugCritDamageRating" },
{ 336, "LumAugCritReductionRating" },
{ 337, "LumAugSurgeEffectRating" },
{ 338, "LumAugSurgeChanceRating" },
{ 339, "LumAugItemManaUsage" },
{ 340, "LumAugItemManaGain" },
{ 341, "LumAugVitality" },
{ 342, "LumAugHealingRating" },
{ 343, "LumAugSkilledCraft" },
{ 344, "LumAugSkilledSpec" },
{ 345, "LumAugNoDestroyCraft" },
{ 346, "RestrictInteraction" },
{ 347, "OlthoiLootTimestamp" },
{ 348, "OlthoiLootStep" },
{ 349, "UseCreatesContractId" },
{ 350, "DotResistRating" },
{ 351, "LifeResistRating" },
{ 352, "CloakWeaveProc" },
{ 353, "WeaponType" },
{ 354, "MeleeMastery" },
{ 355, "RangedMastery" },
{ 356, "SneakAttackRating" },
{ 357, "RecklessnessRating" },
{ 358, "DeceptionRating" },
{ 359, "CombatPetRange" },
{ 360, "WeaponAuraDamage" },
{ 361, "WeaponAuraSpeed" },
{ 362, "SummoningMastery" },
{ 363, "HeartbeatLifespan" },
{ 364, "UseLevelRequirement" },
{ 365, "LumAugAllSkills" },
{ 366, "UseRequiresSkill" },
{ 367, "UseRequiresSkillLevel" },
{ 368, "UseRequiresSkillSpec" },
{ 369, "UseRequiresLevel" },
{ 370, "GearDamage" },
{ 371, "GearDamageResist" },
{ 372, "GearCrit" },
{ 373, "GearCritResist" },
{ 374, "GearCritDamage" },
{ 375, "GearCritDamageResist" },
{ 376, "GearHealingBoost" },
{ 377, "GearNetherResist" },
{ 378, "GearLifeResist" },
{ 379, "GearMaxHealth" },
{ 380, "Unknown380" },
{ 381, "PKDamageRating" },
{ 382, "PKDamageResistRating" },
{ 383, "GearPKDamageRating" },
{ 384, "GearPKDamageResistRating" },
{ 385, "Unknown385" },
{ 386, "Overpower" },
{ 387, "OverpowerResist" },
{ 388, "GearOverpower" },
{ 389, "GearOverpowerResist" },
{ 390, "Enlightenment" },
{ 8007, "PCAPRecordedAutonomousMovement" },
{ 8030, "PCAPRecordedMaxVelocityEstimated" },
{ 8041, "PCAPRecordedPlacement" },
{ 8042, "PCAPRecordedAppraisalPages" },
{ 8043, "PCAPRecordedAppraisalMaxPages" },
{ 9001, "TotalLogins" },
{ 9002, "DeletionTimestamp" },
{ 9003, "CharacterOptions1" },
{ 9004, "CharacterOptions2" },
{ 9005, "LootTier" },
{ 9006, "GeneratorProbability" },
{ 9008, "CurrentLoyaltyAtLastLogoff" },
{ 9009, "CurrentLeadershipAtLastLogoff" },
{ 9010, "AllegianceOfficerRank" },
{ 9011, "HouseRentTimestamp" },
{ 9012, "Hairstyle" },
{ 9013, "VisualClothingPriority" },
{ 9014, "SquelchGlobal" },
{ 9015, "InventoryOrder" },
};
private static readonly Dictionary<uint, string> BoolNames = new()
{
{ 0, "Undef" },
{ 1, "Stuck" },
{ 2, "Open" },
{ 3, "Locked" },
{ 4, "RotProof" },
{ 5, "AllegianceUpdateRequest" },
{ 6, "AiUsesMana" },
{ 7, "AiUseHumanMagicAnimations" },
{ 8, "AllowGive" },
{ 9, "CurrentlyAttacking" },
{ 10, "AttackerAi" },
{ 11, "IgnoreCollisions" },
{ 12, "ReportCollisions" },
{ 13, "Ethereal" },
{ 14, "GravityStatus" },
{ 15, "LightsStatus" },
{ 16, "ScriptedCollision" },
{ 17, "Inelastic" },
{ 18, "Visibility" },
{ 19, "Attackable" },
{ 20, "SafeSpellComponents" },
{ 21, "AdvocateState" },
{ 22, "Inscribable" },
{ 23, "DestroyOnSell" },
{ 24, "UiHidden" },
{ 25, "IgnoreHouseBarriers" },
{ 26, "HiddenAdmin" },
{ 27, "PkWounder" },
{ 28, "PkKiller" },
{ 29, "NoCorpse" },
{ 30, "UnderLifestoneProtection" },
{ 31, "ItemManaUpdatePending" },
{ 32, "GeneratorStatus" },
{ 33, "ResetMessagePending" },
{ 34, "DefaultOpen" },
{ 35, "DefaultLocked" },
{ 36, "DefaultOn" },
{ 37, "OpenForBusiness" },
{ 38, "IsFrozen" },
{ 39, "DealMagicalItems" },
{ 40, "LogoffImDead" },
{ 41, "ReportCollisionsAsEnvironment" },
{ 42, "AllowEdgeSlide" },
{ 43, "AdvocateQuest" },
{ 44, "IsAdmin" },
{ 45, "IsArch" },
{ 46, "IsSentinel" },
{ 47, "IsAdvocate" },
{ 48, "CurrentlyPoweringUp" },
{ 49, "GeneratorEnteredWorld" },
{ 50, "NeverFailCasting" },
{ 51, "VendorService" },
{ 52, "AiImmobile" },
{ 53, "DamagedByCollisions" },
{ 54, "IsDynamic" },
{ 55, "IsHot" },
{ 56, "IsAffecting" },
{ 57, "AffectsAis" },
{ 58, "SpellQueueActive" },
{ 59, "GeneratorDisabled" },
{ 60, "IsAcceptingTells" },
{ 61, "LoggingChannel" },
{ 62, "OpensAnyLock" },
{ 63, "UnlimitedUse" },
{ 64, "GeneratedTreasureItem" },
{ 65, "IgnoreMagicResist" },
{ 66, "IgnoreMagicArmor" },
{ 67, "AiAllowTrade" },
{ 68, "SpellComponentsRequired" },
{ 69, "IsSellable" },
{ 70, "IgnoreShieldsBySkill" },
{ 71, "NoDraw" },
{ 72, "ActivationUntargeted" },
{ 73, "HouseHasGottenPriorityBootPos" },
{ 74, "GeneratorAutomaticDestruction" },
{ 75, "HouseHooksVisible" },
{ 76, "HouseRequiresMonarch" },
{ 77, "HouseHooksEnabled" },
{ 78, "HouseNotifiedHudOfHookCount" },
{ 79, "AiAcceptEverything" },
{ 80, "IgnorePortalRestrictions" },
{ 81, "RequiresBackpackSlot" },
{ 82, "DontTurnOrMoveWhenGiving" },
{ 83, "NpcLooksLikeObject" },
{ 84, "IgnoreCloIcons" },
{ 85, "AppraisalHasAllowedWielder" },
{ 86, "ChestRegenOnClose" },
{ 87, "LogoffInMinigame" },
{ 88, "PortalShowDestination" },
{ 89, "PortalIgnoresPkAttackTimer" },
{ 90, "NpcInteractsSilently" },
{ 91, "Retained" },
{ 92, "IgnoreAuthor" },
{ 93, "Limbo" },
{ 94, "AppraisalHasAllowedActivator" },
{ 95, "ExistedBeforeAllegianceXpChanges" },
{ 96, "IsDeaf" },
{ 97, "IsPsr" },
{ 98, "Invincible" },
{ 99, "Ivoryable" },
{ 100, "Dyable" },
{ 101, "CanGenerateRare" },
{ 102, "CorpseGeneratedRare" },
{ 103, "NonProjectileMagicImmune" },
{ 104, "ActdReceivedItems" },
{ 105, "Unknown105" },
{ 106, "FirstEnterWorldDone" },
{ 107, "RecallsDisabled" },
{ 108, "RareUsesTimer" },
{ 109, "ActdPreorderReceivedItems" },
{ 110, "Afk" },
{ 111, "IsGagged" },
{ 112, "ProcSpellSelfTargeted" },
{ 113, "IsAllegianceGagged" },
{ 114, "EquipmentSetTriggerPiece" },
{ 115, "Uninscribe" },
{ 116, "WieldOnUse" },
{ 117, "ChestClearedWhenClosed" },
{ 118, "NeverAttack" },
{ 119, "SuppressGenerateEffect" },
{ 120, "TreasureCorpse" },
{ 121, "EquipmentSetAddLevel" },
{ 122, "BarberActive" },
{ 123, "TopLayerPriority" },
{ 124, "NoHeldItemShown" },
{ 125, "LoginAtLifestone" },
{ 126, "OlthoiPk" },
{ 127, "Account15Days" },
{ 128, "HadNoVitae" },
{ 129, "NoOlthoiTalk" },
{ 130, "AutowieldLeft" },
{ 9001, "LinkedPortalOneSummon" },
{ 9002, "LinkedPortalTwoSummon" },
{ 9003, "HouseEvicted" },
{ 9004, "UntrainedSkills" },
{ 9005, "IsEnvoy" },
{ 9006, "UnspecializedSkills" },
{ 9007, "FreeSkillResetRenewed" },
{ 9008, "FreeAttributeResetRenewed" },
{ 9009, "SkillTemplesTimerReset" },
{ 9010, "FreeMasteryResetRenewed" },
};
private static readonly Dictionary<uint, string> StringNames = new()
{
{ 0, "Undef" },
{ 1, "Name" },
{ 2, "Title" },
{ 3, "Sex" },
{ 4, "HeritageGroup" },
{ 5, "Template" },
{ 6, "AttackersName" },
{ 7, "Inscription" },
{ 8, "ScribeName" },
{ 9, "VendorsName" },
{ 10, "Fellowship" },
{ 11, "MonarchsName" },
{ 12, "LockCode" },
{ 13, "KeyCode" },
{ 14, "Use" },
{ 15, "ShortDesc" },
{ 16, "LongDesc" },
{ 17, "ActivationTalk" },
{ 18, "UseMessage" },
{ 19, "ItemHeritageGroupRestriction" },
{ 20, "PluralName" },
{ 21, "MonarchsTitle" },
{ 22, "ActivationFailure" },
{ 23, "ScribeAccount" },
{ 24, "TownName" },
{ 25, "CraftsmanName" },
{ 26, "UsePkServerError" },
{ 27, "ScoreCachedText" },
{ 28, "ScoreDefaultEntryFormat" },
{ 29, "ScoreFirstEntryFormat" },
{ 30, "ScoreLastEntryFormat" },
{ 31, "ScoreOnlyEntryFormat" },
{ 32, "ScoreNoEntry" },
{ 33, "Quest" },
{ 34, "GeneratorEvent" },
{ 35, "PatronsTitle" },
{ 36, "HouseOwnerName" },
{ 37, "QuestRestriction" },
{ 38, "AppraisalPortalDestination" },
{ 39, "TinkerName" },
{ 40, "ImbuerName" },
{ 41, "HouseOwnerAccount" },
{ 42, "DisplayName" },
{ 43, "DateOfBirth" },
{ 44, "ThirdPartyApi" },
{ 45, "KillQuest" },
{ 46, "Afk" },
{ 47, "AllegianceName" },
{ 48, "AugmentationAddQuest" },
{ 49, "KillQuest2" },
{ 50, "KillQuest3" },
{ 51, "UseSendsSignal" },
{ 52, "GearPlatingName" },
{ 8006, "PCAPRecordedCurrentMotionState" },
{ 8031, "PCAPRecordedServerName" },
{ 8032, "PCAPRecordedCharacterName" },
{ 9001, "AllegianceMotd" },
{ 9002, "AllegianceMotdSetBy" },
{ 9003, "AllegianceSpeakerTitle" },
{ 9004, "AllegianceSeneschalTitle" },
{ 9005, "AllegianceCastellanTitle" },
{ 9006, "GodState" },
{ 9007, "TinkerLog" },
};
public static string? GetIntName(uint id) => IntNames.TryGetValue(id, out var n) ? n : null;
public static string? GetBoolName(uint id) => BoolNames.TryGetValue(id, out var n) ? n : null;
public static string? GetStringName(uint id) => StringNames.TryGetValue(id, out var n) ? n : null;
}

View file

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Meta;
internal sealed class QuestRecord
{
public string Key = "";
public int Solves;
public int MaxSolves;
public DateTime CompletedOn = DateTime.MinValue;
public TimeSpan RepeatTime = TimeSpan.Zero;
/// <summary>
/// Returns true if the quest can be done again now.
/// Mirrors UB QuestFlag.IsReady(): timer expired AND not a once-only flag.
/// Once-only: MaxSolves==1 &amp;&amp; Solves&lt;=1 — never ready again.
/// </summary>
public bool IsReady()
{
if ((CompletedOn + RepeatTime) > DateTime.UtcNow)
return false;
return !(MaxSolves == 1 && Solves <= 1);
}
}
/// <summary>
/// Fires /myquests, parses the resulting chat lines into a per-session quest flag cache,
/// and exposes UB-compatible query methods used by ExpressionEngine.
/// </summary>
internal sealed class QuestTracker
{
// Matches lines produced by the AC /myquests command.
// Format: key - N solves (unixTimestamp)"description" maxSolves repeatSeconds
// Example: blankaug - 1 solves (1609459200)"Blank Aug" 1 0
private static readonly Regex QuestLineRegex = new Regex(
@"(?<key>\S+) \- (?<solves>\d+) solves \((?<completedOn>\d{0,11})\)""?((?<description>.*)"" (?<maxSolves>.*) (?<repeatTime>\d{0,11}))?.*$",
RegexOptions.Compiled);
private readonly RynthCoreHost _host;
private readonly Dictionary<string, QuestRecord> _flags = new(StringComparer.OrdinalIgnoreCase);
private bool _refreshing;
private bool _gotFirstQuest;
private DateTime _lastLineTime;
private DateTime _refreshStarted;
public bool IsRefreshing => _refreshing;
public QuestTracker(RynthCoreHost host) => _host = host;
/// <summary>
/// Issues /myquests to the server to populate the quest flag cache.
/// No-ops if already refreshing or InvokeChatParser is not available.
/// </summary>
public void Refresh()
{
if (_refreshing || !_host.HasInvokeChatParser)
return;
_refreshing = true;
_gotFirstQuest = false;
_lastLineTime = DateTime.UtcNow;
_refreshStarted = DateTime.UtcNow;
_host.InvokeChatParser("/myquests");
}
/// <summary>
/// Feed every incoming chat line here. Quest lines are parsed and cached;
/// terminal lines (empty list, rate limit, etc.) end the refresh early.
/// </summary>
public void OnChatLine(string text)
{
if (!_refreshing)
return;
if (text.Contains("Quest list is empty") ||
text.Contains("The command \"myquests\" is not currently enabled"))
{
_refreshing = false;
return;
}
if (text.Contains("This command may only be run once every"))
{
_refreshing = false;
return;
}
var m = QuestLineRegex.Match(text);
if (!m.Success)
return;
_gotFirstQuest = true;
_lastLineTime = DateTime.UtcNow;
var rec = new QuestRecord();
rec.Key = m.Groups["key"].Value.ToLowerInvariant();
int.TryParse(m.Groups["solves"].Value, out rec.Solves);
int.TryParse(m.Groups["maxSolves"].Value, out rec.MaxSolves);
if (double.TryParse(m.Groups["completedOn"].Value,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out double ts) && ts > 0)
rec.CompletedOn = DateTimeOffset.FromUnixTimeSeconds((long)ts).UtcDateTime;
if (double.TryParse(m.Groups["repeatTime"].Value,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out double rt) && rt > 0)
rec.RepeatTime = TimeSpan.FromSeconds(rt);
_flags[rec.Key] = rec;
}
/// <summary>
/// Call once per game tick. Detects end-of-list by silence:
/// 1 second after the last quest line received → done.
/// 15 second global timeout if no quest lines ever arrive → done.
/// </summary>
public void Tick()
{
if (!_refreshing)
return;
var now = DateTime.UtcNow;
if (_gotFirstQuest)
{
if ((now - _lastLineTime).TotalSeconds >= 1.0)
_refreshing = false;
}
else
{
if ((now - _refreshStarted).TotalSeconds >= 15.0)
_refreshing = false;
}
}
/// <summary>Returns true if the key exists in the cached quest flag list.</summary>
public bool HasFlag(string key) => _flags.ContainsKey(key.ToLowerInvariant());
/// <summary>Returns the cached record for the given key, or false if not found.</summary>
public bool TryGetFlag(string key, out QuestRecord rec)
=> _flags.TryGetValue(key.ToLowerInvariant(), out rec!);
}

View file

@ -0,0 +1,58 @@
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Process-wide cache of constructed <see cref="Regex"/> instances keyed by
/// (pattern, options). Meta conditions and the expression engine compile the
/// same user pattern every tick / every eval; constructing a Regex parses the
/// pattern each time. Caching the instance removes that per-tick cost.
///
/// Note: deliberately NOT <see cref="RegexOptions.Compiled"/> — that path uses
/// reflection-emit which NativeAOT can't honour (it silently falls back to the
/// interpreter anyway). We cache the interpreter instance instead, which is the
/// real win here. A bad pattern is cached as null so we don't re-throw on it
/// every tick; callers treat a miss/null as "no match".
/// </summary>
internal static class RegexCache
{
// Sized to hold every distinct pattern in a large VTank loot-snob profile
// (1600+ rules, many with spell-name / string regexes) so the loot evaluator
// never thrashes the cache mid-corpse. Interpreter Regex instances are small.
private const int MaxEntries = 2048;
private static readonly ConcurrentDictionary<(string Pattern, RegexOptions Options), Regex?> _cache = new();
public static Regex? Get(string pattern, RegexOptions options = RegexOptions.None)
{
if (string.IsNullOrEmpty(pattern)) return null;
var key = (pattern, options);
if (_cache.TryGetValue(key, out var rx)) return rx;
// Unbounded user patterns: cap the cache so a meta that builds patterns
// dynamically can't grow it without limit. Coarse reset is fine — the
// hot patterns just get rebuilt once.
if (_cache.Count >= MaxEntries) _cache.Clear();
try { rx = new Regex(pattern, options | RegexOptions.CultureInvariant); }
catch { rx = null; }
_cache[key] = rx;
return rx;
}
public static bool IsMatch(string input, string pattern, RegexOptions options = RegexOptions.None)
{
var rx = Get(pattern, options);
if (rx == null) return false;
try { return rx.IsMatch(input ?? ""); }
catch { return false; }
}
public static Match Match(string input, string pattern, RegexOptions options = RegexOptions.None)
{
var rx = Get(pattern, options);
if (rx == null) return System.Text.RegularExpressions.Match.Empty;
try { return rx.Match(input ?? ""); }
catch { return System.Text.RegularExpressions.Match.Empty; }
}
}

View file

@ -0,0 +1,477 @@
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Draws navigation route markers using the engine's 3D rendering API.
/// Rings are real D3D9 geometry (flat annuli on the ground) with natural
/// perspective distortion — they look 3D like Utility Belt's D3DObj.
/// Connecting lines are also 3D quads lying on the ground.
///
/// Falls back to ImGui 2D line rendering if the 3D API is unavailable.
/// </summary>
internal sealed class NavMarkerRenderer
{
// Colors — ARGB format for D3D9 (0xAARRGGBB)
private const uint ColorCyan3D = 0xFF00FFFF;
private const uint ColorRed3D = 0xFFFF4444;
private const uint ColorLine3D = 0xFF0088FF;
private const uint ColorPortal3D = 0xFFFF44FF; // magenta — live portal target
// Colors — ABGR format for ImGui fallback
private const uint ColorCyanImGui = 0xFFFFFF00;
private const uint ColorRedImGui = 0xFF4444FF;
private const uint ColorLineImGui = 0xFFFF8800;
// Ring geometry for ImGui fallback
private const int RingSegments = 32;
private static readonly float[] _cos = new float[RingSegments];
private static readonly float[] _sin = new float[RingSegments];
static NavMarkerRenderer()
{
for (int i = 0; i < RingSegments; i++)
{
double a = 2.0 * Math.PI * i / RingSegments;
_cos[i] = (float)Math.Cos(a);
_sin[i] = (float)Math.Sin(a);
}
}
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private int _frameCount;
public NavMarkerRenderer(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
_settings = settings;
}
// Pre-allocated arrays for ImGui fallback
private const int MaxMarkers = 128;
private readonly Vector2[] _centerScreen = new Vector2[MaxMarkers];
private readonly bool[] _centerVis = new bool[MaxMarkers];
private readonly float[] _centerDepth = new float[MaxMarkers];
/// <summary>
/// Submits 3D ring + line geometry to the engine's Nav3D buffer.
/// Safe to call from OnTick — does not touch ImGui state. No-op when
/// the engine doesn't expose the 3D nav API.
/// </summary>
public void SubmitNav3D()
{
if (!_host.HasNav3D)
return;
try
{
if (!TryPrepareFrame(out var route, out int winStart, out int count, out float px, out float py, out float pz,
out double playerNS, out double playerEW, out float ringRadius, out float heightOffset))
return;
Render3D(route, winStart, count, px, py, pz, playerNS, playerEW, ringRadius, heightOffset);
}
catch (Exception ex) { _host.Log($"NavMarkers(3D): {ex.Message}"); }
}
/// <summary>
/// Draws the ImGui-projected fallback (2D rings + lines). Only used
/// when the engine doesn't expose the 3D nav API. Must be called from
/// inside an ImGui frame.
/// </summary>
public void RenderImGuiFallback()
{
if (_host.HasNav3D)
return;
try
{
if (!TryPrepareFrame(out var route, out int winStart, out int count, out float px, out float py, out float pz,
out double playerNS, out double playerEW, out float ringRadius, out float heightOffset))
return;
RenderImGuiFallback(route, winStart, count, px, py, pz, playerNS, playerEW, ringRadius, heightOffset);
}
catch (Exception ex) { _host.Log($"NavMarkers(ImGui): {ex.Message}"); }
}
private bool TryPrepareFrame(out NavRouteParser route, out int winStart, out int count,
out float px, out float py, out float pz,
out double playerNS, out double playerEW,
out float ringRadius, out float heightOffset)
{
_frameCount++;
route = null!; winStart = 0; count = 0;
px = py = pz = 0f;
playerNS = playerEW = 0.0;
ringRadius = 0f; heightOffset = 0f;
var r = _settings.CurrentRoute;
if (r?.Points == null || r.Points.Count == 0)
return false;
if (!NavCoordinateHelper.TryGetNavCoords(_host, out playerNS, out playerEW))
return false;
if (!_host.TryGetPlayerPose(out uint cellId, out px, out py, out pz,
out _, out _, out _, out _))
return false;
// Don't paint during portal animation — portalspace has landblock 0x0000,
// but also check IsPortaling() for the brief window before cellId zeroes out.
if ((cellId >> 16) == 0)
return false;
if (_host.HasIsPortaling && _host.IsPortaling())
return false;
route = r;
ringRadius = Math.Max(0.1f, _settings.FollowNavMin);
heightOffset = _settings.NavHeightOffset;
// Render a contiguous window of the route centered on the active
// waypoint rather than the first MaxMarkers points. Rings and lines are
// per-primitive D3D9 draw calls (not batched), so an unbounded route
// would flood EndScene — but a player-centered window keeps the markers
// visible wherever you patrol while the draw-call count stays bounded.
// (Was: first-MaxMarkers truncation, which left long stretches of a
// 300+ waypoint dungeon route — ordered by DFS, so visually patchy —
// with no markers at all.)
int n = r.Points.Count;
count = Math.Min(n, MaxMarkers);
if (n <= count)
{
winStart = 0;
}
else
{
int active = _settings.ActiveNavIndex;
if (active < 0 || active >= n) active = 0;
int half = count / 2;
if (r.RouteType == NavRouteType.Circular)
winStart = ((active - half) % n + n) % n;
else
winStart = Math.Clamp(active - half, 0, n - count);
}
return true;
}
// Absolute route index of the k-th point in the render window. The modulo
// wraps circular routes; for non-circular routes winStart is clamped so the
// window never runs off the end and the modulo is a no-op.
private static int WindowAbsIdx(int winStart, int k, int n) => (winStart + k) % n;
// Next window slot to connect a line to. Stays within the window (contiguous
// route points), and only wraps to slot 0 when the window IS the whole route
// (small circular route) — never draws a long wrap line across a partial
// window.
private static int NextInWindow(int k, int count, int n, bool circular)
{
if (k + 1 < count) return k + 1;
if (count == n && circular) return 0;
return -1;
}
// ═══════════════════════════════════════════════════════════════════
// 3D rendering path — real D3D9 geometry via engine API
// ═══════════════════════════════════════════════════════════════════
private void Render3D(NavRouteParser route, int winStart, int count, float px, float py, float pz,
double playerNS, double playerEW, float ringRadius, float heightOffset)
{
// Ring thickness in world units (the band width of the annulus)
float ringThick = _settings.NavRingThickness * 0.02f; // Scale from UI units to world units
float lineThick = _settings.NavLineThickness * 0.01f;
int n = route.Points.Count;
bool circular = route.RouteType == NavRouteType.Circular;
// ── Pass 1: Submit rings ─────────────────────────────────────
// Arrays are indexed by window slot k (0..count), not absolute route
// index — the absolute index can run far past count on a long route.
float[] wxArr = new float[count];
float[] wyArr = new float[count];
float[] wzArr = new float[count];
bool[] validArr = new bool[count];
for (int k = 0; k < count; k++)
{
int i = WindowAbsIdx(winStart, k, n);
var pt = route.Points[i];
// Only draw markers at real travel Points. Action waypoints
// (PortalNPC / Recall / Chat / Pause) fire in place and carry
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
continue;
// D3D coords: X=EW, Y=height(up), Z=NS
float wx = px + (float)((pt.EW - playerEW) * 240.0);
float wy = ResolveMarkerWorldY(route, i, heightOffset);
float wz = py + (float)((pt.NS - playerNS) * 240.0);
wxArr[k] = wx; wyArr[k] = wy; wzArr[k] = wz;
validArr[k] = true;
bool isActive = (i == _settings.ActiveNavIndex);
uint color = isActive ? ColorRed3D : ColorCyan3D;
float thick = isActive ? ringThick * 1.3f : ringThick;
_host.Nav3DAddRing(wx, wy, wz, ringRadius, thick, color);
}
// ── Pass 2: Submit connecting lines (consecutive Points only) ──
// validArr is true only for Point waypoints, so a non-Point between two
// Points (portal / recall / chat / pause) leaves the next slot invalid
// and BREAKS the line there. That is correct: you teleport across a
// portal, you don't walk — so no segment should span it (this is what
// produced the "line to the abyss", whether to the portal's placeholder
// coord or onward to the post-teleport destination point).
for (int k = 0; k < count; k++)
{
if (!validArr[k]) continue;
int nk = NextInWindow(k, count, n, circular);
if (nk < 0 || nk >= count || !validArr[nk]) continue;
_host.Nav3DAddLine(wxArr[k], wyArr[k], wzArr[k],
wxArr[nk], wyArr[nk], wzArr[nk],
lineThick, ColorLine3D);
}
// ── Pass 3: live portal marker + line ────────────────────────
// While the engine is actively using a portal/NPC it publishes the
// resolved object id (the waypoint's own coord is a placeholder, so we
// can't use it). Draw a distinct magenta ring at the portal's REAL
// position plus a line from the player to it — a visible "walk in here".
uint portalId = _settings.ActivePortalObjId;
if (portalId != 0 &&
_host.HasGetObjectPosition &&
_host.TryGetObjectPosition(portalId, out uint pcell, out float ppx, out float ppy, out float ppz) &&
NavCoordinateHelper.TryConvertPoseToCoords(pcell, ppx, ppy, out double portNS, out double portEW))
{
float pwx = px + (float)((portEW - playerEW) * 240.0);
float pwz = py + (float)((portNS - playerNS) * 240.0);
float pwy = ppz + heightOffset; // portal ground height (same frame as marker Z)
_host.Nav3DAddRing(pwx, pwy, pwz, ringRadius, ringThick * 1.4f, ColorPortal3D);
_host.Nav3DAddLine(px, pwy, py, pwx, pwy, pwz, lineThick, ColorPortal3D);
}
}
// ═══════════════════════════════════════════════════════════════════
// ImGui fallback path — 2D projected lines (original implementation)
// ═══════════════════════════════════════════════════════════════════
private void RenderImGuiFallback(NavRouteParser route, int winStart, int count, float px, float py, float pz,
double playerNS, double playerEW, float ringRadius, float heightOffset)
{
if (!_host.HasWorldToScreen || !_host.HasGetViewportSize)
return;
if (!_host.TryGetViewportSize(out uint vpW, out uint vpH) || vpW == 0 || vpH == 0)
return;
// Fullscreen transparent overlay window
ImGui.SetNextWindowPos(Vector2.Zero);
ImGui.SetNextWindowSize(new Vector2(vpW, vpH));
ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u);
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = true;
if (!ImGui.Begin("##NavOverlay", ref open,
ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize |
ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar |
ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.NoBackground |
ImGuiWindowFlags.NoBringToFrontOnFocus | ImGuiWindowFlags.NoFocusOnAppearing |
ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoSavedSettings))
{
ImGui.End();
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
return;
}
var drawList = ImGui.GetWindowDrawList();
int n = route.Points.Count;
bool circular = route.RouteType == NavRouteType.Circular;
// ── Pass 1: project waypoint centers ─────────────────────────
// Per-frame arrays are indexed by window slot k (0..count); the active
// waypoint's absolute route index i is used only for route lookups and
// the on-screen index label.
int projected = 0;
for (int k = 0; k < count; k++)
{
int i = WindowAbsIdx(winStart, k, n);
var pt = route.Points[i];
_centerVis[k] = false;
// Only draw markers at real travel Points. Action waypoints
// (PortalNPC / Recall / Chat / Pause) fire in place and carry
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
continue;
float wx = px + (float)((pt.EW - playerEW) * 240.0);
float wy = ResolveMarkerWorldY(route, i, heightOffset);
float wz = py + (float)((pt.NS - playerNS) * 240.0);
if (_host.WorldToScreen(wx, wy, wz, out float sx, out float sy))
{
_centerScreen[k] = new Vector2(sx, sy);
_centerVis[k] = true;
float dx = wx - px, dy = wy - pz, dz = wz - py;
_centerDepth[k] = (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);
projected++;
}
}
// ── Pass 2: connecting lines (consecutive Points only) ───────
// _centerVis is set only for Point waypoints, so a non-Point between two
// Points breaks the line there (no segment spans a teleport).
float baseLineThick = Math.Max(1f, _settings.NavLineThickness);
for (int k = 0; k < count; k++)
{
if (!_centerVis[k]) continue;
int nk = NextInWindow(k, count, n, circular);
if (nk < 0 || nk >= count || !_centerVis[nk]) continue;
float avgD = (_centerDepth[k] + _centerDepth[nk]) * 0.5f;
float thick = Math.Clamp(baseLineThick * 60f / Math.Max(avgD, 1f), baseLineThick * 0.5f, baseLineThick * 2f);
drawList.AddLine(_centerScreen[k], _centerScreen[nk], ColorLineImGui, thick);
}
// ── Pass 3: 3D ground rings at each waypoint ────────────────
float[] rsx = new float[RingSegments];
float[] rsy = new float[RingSegments];
bool[] rvis = new bool[RingSegments];
float baseRingThick = Math.Max(1f, _settings.NavRingThickness);
for (int k = 0; k < count; k++)
{
int i = WindowAbsIdx(winStart, k, n);
var pt = route.Points[i];
// Only draw markers at real travel Points. Action waypoints
// (PortalNPC / Recall / Chat / Pause) fire in place and carry
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
continue;
float cx = px + (float)((pt.EW - playerEW) * 240.0);
float cy = ResolveMarkerWorldY(route, i, heightOffset);
float cz = py + (float)((pt.NS - playerNS) * 240.0);
int visCount = 0;
for (int s = 0; s < RingSegments; s++)
{
float rwx = cx + _cos[s] * ringRadius;
float rwz = cz + _sin[s] * ringRadius;
rvis[s] = _host.WorldToScreen(rwx, cy, rwz, out rsx[s], out rsy[s]);
if (rvis[s]) visCount++;
}
if (visCount < 2) continue;
bool isActive = (i == _settings.ActiveNavIndex);
uint color = isActive ? ColorRedImGui : ColorCyanImGui;
float ringThick = isActive ? baseRingThick * 1.3f : baseRingThick;
for (int s = 0; s < RingSegments; s++)
{
int next = (s + 1) % RingSegments;
if (rvis[s] && rvis[next])
{
drawList.AddLine(
new Vector2(rsx[s], rsy[s]),
new Vector2(rsx[next], rsy[next]),
color, ringThick);
}
}
// Index label above the ring (absolute route index)
if (_centerVis[k])
{
string label = i.ToString();
var sz = ImGui.CalcTextSize(label);
drawList.AddText(_centerScreen[k] - new Vector2(sz.X * 0.5f, 16f), color, label);
}
}
ImGui.End();
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
}
// Nav-coord → AC world-metre scale. The horizontal render math (proven
// correct) is `wx = px + (pt.EW − playerEW) * 240`, i.e. a *relative*
// delta from the player scaled by 240. We reuse exactly that delta and
// anchor it to the player's known world metres, so this is unit-safe for
// whatever frame the uTank2 .nav stores (NOT the /loc frame).
private const double NavToMetres = 240.0;
/// <summary>
/// World-Y for a nav marker. Base height is the recorded path Z — the
/// original, known-good behaviour. A flat ring floats above the downhill
/// ground on a slope; we estimate the local grade purely from the route's
/// own neighbouring points (rise/run in nav units — no terrain lookup and
/// no shared raycast state, so it is thread-safe and works in structure
/// cells) and sink the marker by NavSlopeSink x grade. Flat route =&gt;
/// grade 0 =&gt; identical to the original behaviour.
/// </summary>
private float ResolveMarkerWorldY(NavRouteParser route, int i, float heightOffset)
{
var pt = route.Points[i];
float baseY = (float)(pt.Z * NavToMetres) + heightOffset;
float sink = _settings.NavSlopeSink;
if (sink <= 0f)
return baseY;
// Steeper of the two route segments meeting at this point. Delta-Z and
// the horizontal run are both in nav units, so grade is a unitless
// rise/run (= tan slope) and the 240 scale cancels out.
double grade = Math.Max(SegmentGrade(route, i, -1), SegmentGrade(route, i, +1));
if (grade <= 0.0)
return baseY;
if (grade > 2.0) grade = 2.0; // bound garbage/cliff segments
return baseY - sink * (float)grade;
}
/// <summary>
/// |Delta-Z| / horizontal-run between route point i and the neighbour
/// i+step (honouring circular wrap). 0 when the neighbour is missing or
/// coincident.
/// </summary>
private static double SegmentGrade(NavRouteParser route, int i, int step)
{
int n = route.Points.Count;
int j = i + step;
if (j < 0 || j >= n)
{
if (route.RouteType != NavRouteType.Circular || n < 2)
return 0.0;
j = ((j % n) + n) % n;
}
var a = route.Points[i];
var b = route.Points[j];
double dE = b.EW - a.EW;
double dN = b.NS - a.NS;
double run = Math.Sqrt(dE * dE + dN * dN);
if (run < 1e-6)
return 0.0;
return Math.Abs(b.Z - a.Z) / run;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,581 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUIInitialized() => Runtime.OnUIInitialized();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBarAction() => Runtime.OnBarAction();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthAiPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthAiPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorOpen", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorOpen(uint vendorId) => Runtime.OnVendorOpen(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountIncremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountIncremented() => Runtime.OnBusyCountIncremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountDecremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountDecremented() => Runtime.OnBusyCountDecremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSmartBoxEvent", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSmartBoxEvent(uint opcode, uint blobSize, uint status) => Runtime.OnSmartBoxEvent(opcode, blobSize, status);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) => Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker) => Runtime.OnCombatDamage(damage, damageType, crit, isAttacker);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => Runtime.OnEnchantmentAdded(spellId, durationSeconds);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
// ── Snapshot bridge for the engine-side Avalonia RynthAi panel ──────────
// The panel polls these exports every ~250ms to mirror the live dashboard.
// The returned ANSI buffer is freed on the next call; the caller MUST copy
// its string before calling any of these again.
// [ThreadStatic]: this snapshot is polled concurrently from MULTIPLE threads — the engine's Avalonia
// RynthAiPanel (~Hz), the heartbeat status-export (1/s), and (Phase C) the RynthRemote plugin via the
// engine's GetPluginSnapshotJson broker. With a single shared pointer the alloc-new→swap→free-old below
// races: one caller frees the buffer another is mid-read → garbage ('0x18' JsonException) / use-after-free.
// Per-thread storage gives each caller its own buffer (same discipline as the engine's account-name
// scratch), so no caller ever frees another thread's pointer. (No initializer — [ThreadStatic] defaults
// to IntPtr.Zero on every thread.)
[ThreadStatic] private static IntPtr _snapshotPtr;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSnapshotJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSnapshotJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildSnapshotJson() ?? "{}";
// Allocate the new buffer FIRST, then swap, then free the old.
// The Avalonia panel polls this from a different thread; if we
// freed before allocating, a poll mid-call would read freed
// memory — which on .NET 10 NativeAOT silently returns garbage,
// making the panel appear to "freeze" intermittently.
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _snapshotPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Full-inventory bridge (read-only remote inventory viewer, P1) ───────────
// Dedicated export (NOT folded into the 150ms status snapshot) so 100s of items never ride the
// hot path. The RynthRemote plugin polls this on its own slower cadence (P2). Per-thread buffer
// (same reasoning as _snapshotPtr): polled from multiple threads; never free another's pointer.
[ThreadStatic] private static IntPtr _inventoryPtr;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetInventoryJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetInventoryJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildInventoryJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _inventoryPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Remote-command bridge (engine SendPluginCommand broker → this plugin) ──
// When RynthRemote owns the command drain, the engine forwards each phone-issued
// (action,value) command here. We COPY the ANSI args (the caller frees them right
// after this returns) and enqueue them for the pump thread (RynthAiPlugin.OnTick →
// ApplyRemoteCommand); we NEVER apply on the caller's thread. The whole body is
// guarded — a managed exception must not cross the native boundary.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0) return;
Runtime.Plugin?.EnqueueRemoteCommand(action, value);
}
catch { /* never let a managed exception cross the native boundary */ }
}
// Every void action export below is a reverse-P/Invoke (UnmanagedCallersOnly)
// boundary: a managed exception escaping one fail-fasts the NativeAOT runtime
// (no dump, no log — the "illegal exception" crash class). Funnel them through
// this guard so a UI click that races plugin state (e.g. SelectProfile indexing
// a profile list mid-Refresh) can never kill the AC client.
private static void SafeInvoke(Action action)
{
try { action(); }
catch { /* never let a managed exception cross the native boundary */ }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginToggleMacro", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ToggleMacro() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.TogglePanelMacro());
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetSubsystemEnabled", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetSubsystemEnabled(int subsystemId, int enabled)
=> SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.SetSubsystemEnabled(subsystemId, enabled != 0));
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSelectProfile", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SelectProfile(int kind, int index)
=> SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.SelectProfileAtIndex(kind, index));
[UnmanagedCallersOnly(EntryPoint = "RynthPluginForceRebuff", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ForceRebuff() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.RequestForceRebuff());
[UnmanagedCallersOnly(EntryPoint = "RynthPluginCancelForceRebuff", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void CancelForceRebuff() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.RequestCancelForceRebuff());
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAdjustOpacity", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AdjustOpacity(float delta) => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.AdjustOpacity(delta));
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTogglePanelLock", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void TogglePanelLock() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.TogglePanelLock());
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTogglePanelMinimize", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void TogglePanelMinimize() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.TogglePanelMinimize());
// ── Radar bridge (engine-side Avalonia radar panel) ─────────────────────
// Engine passes the MapVersion it has cached (0 on first call). When the
// live landblock matches, walls/fills are omitted from the payload.
private static IntPtr _radarPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetRadarSnapshot", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetRadarSnapshot(uint engineKnownMapVersion)
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildRadarJson(engineKnownMapVersion) ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _radarPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Monsters bridge (engine-side Avalonia MonstersPanel) ────────────────
private static IntPtr _monstersPtr = IntPtr.Zero;
private static IntPtr _monsterDamagePtr = IntPtr.Zero;
// Live per-monster casts-to-kill table (engine MonsterDamagePanel polls this).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMonsterDamageText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetMonsterDamageText()
{
try
{
string text = Runtime.Plugin?.BuildMonsterDamageText() ?? "";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(text);
IntPtr oldPtr = Interlocked.Exchange(ref _monsterDamagePtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
private static IntPtr _monsterDamageJsonPtr = IntPtr.Zero;
// Structured per-monster rows for the interactive Damage panel (UTF-8/ANSI JSON).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMonsterDamageJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetMonsterDamageJson()
{
try
{
string json = Runtime.Plugin?.BuildMonsterDamageJson() ?? "[]";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _monsterDamageJsonPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// Manual HP override from the Damage panel (hp <= 0 clears it).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonsterHp", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonsterHp(uint wcid, int hp)
{
try { Runtime.Plugin?.SetMonsterHp(wcid, hp); } catch { }
}
// Delete one learned row. keyUtf8 = ANSI "wcid:weaponId:element:tier". Returns 1 on success.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginDeleteMonsterRow", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int DeleteMonsterRow(IntPtr keyUtf8)
{
try
{
string? key = Marshal.PtrToStringAnsi(keyUtf8);
return (Runtime.Plugin?.DeleteMonsterRow(key ?? "") ?? false) ? 1 : 0;
}
catch
{
return 0;
}
}
private static IntPtr _combatWeaponsPtr = IntPtr.Zero;
// Selectable weapons for the Damage-panel weapon/offhand pickers (ANSI JSON array [{id,name}]).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetCombatWeaponsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetCombatWeaponsJson()
{
try
{
string json = Runtime.Plugin?.BuildCombatWeaponsJson() ?? "[]";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _combatWeaponsPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// Per-monster weapon override from the Damage panel (weaponId == 0 clears → use learned best).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonsterWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonsterWeapon(uint wcid, uint weaponId)
{
try { Runtime.Plugin?.SetMonsterWeapon(wcid, weaponId); } catch { }
}
// Per-monster offhand override from the Damage panel (offhandId == 0 clears). Stored only.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonsterOffhand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonsterOffhand(uint wcid, uint offhandId)
{
try { Runtime.Plugin?.SetMonsterOffhand(wcid, offhandId); } catch { }
}
// Per-character DEFAULT weapon from the Damage panel's Default line (weaponId == 0 clears →
// monsters on Default fall through to learned-best). Sweeping fallback for all Default monsters.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetDefaultWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetDefaultWeapon(uint weaponId)
{
try { Runtime.Plugin?.SetDefaultWeapon(weaponId); } catch { }
}
// Master reset: zero all learned damage stats, keep monster names + manual overrides.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginClearMonsterStats", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ClearMonsterStats()
{
try { Runtime.Plugin?.ClearMonsterStats(); } catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMonstersJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetMonstersJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildMonstersJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _monstersPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
/// <summary>
/// Engine sends an ANSI null-terminated JSON string. Plugin replaces
/// MonsterRules in-memory and writes monsters.json.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonstersJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonstersJson(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (string.IsNullOrEmpty(json)) return;
Runtime.Plugin?.DashboardRenderer?.ApplyMonstersJson(json);
}
catch { }
}
// ── Settings bridge (engine-side Avalonia SettingsPanel) ────────────────
private static IntPtr _settingsPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSettingsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSettingsJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildSettingsJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _settingsPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetSettingsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetSettingsJson(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (string.IsNullOrEmpty(json)) return;
Runtime.Plugin?.DashboardRenderer?.ApplySettingsJson(json);
}
catch { }
}
// ── Nav bridge (engine-side Avalonia NavPanel) ──────────────────────────
private static IntPtr _navPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetNavJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetNavJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildNavJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _navPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSendNavCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendNavCommand(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (string.IsNullOrEmpty(json)) return;
var cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.NavCommand);
switch (cmd?.Cmd)
{
case "dunPatrol": Runtime.Plugin?.HandleDungeonNavPatrol(); break;
case "clearHazards": Runtime.Plugin?.ClearDungeonHazards(cmd.NavName); break;
case "clearHazardsAll": Runtime.Plugin?.ClearAllDungeonHazards(); break;
case "markHazardHere": Runtime.Plugin?.MarkCurrentCellHazardFromUi(); break;
case "unmarkHazardHere":Runtime.Plugin?.UnmarkCurrentCellHazardFromUi(); break;
default: Runtime.Plugin?.DashboardRenderer?.HandleNavCommand(json); break;
}
}
catch { }
}
private static IntPtr _patrolInfoPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetPatrolInfoJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetPatrolInfoJson()
{
try
{
string json = Runtime.Plugin?.BuildPatrolInfoJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _patrolInfoPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Items bridge (engine-side Avalonia ItemsPanel) ──────────────────────
private static IntPtr _itemsPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetItemsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetItemsJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildItemsJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _itemsPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetItemsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetItemsJson(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (string.IsNullOrEmpty(json)) return;
Runtime.Plugin?.DashboardRenderer?.ApplyItemsJson(json);
}
catch { }
}
// ── Meta bridge (engine-side Avalonia MetaPanel) ────────────────────────
private static IntPtr _metaPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMetaJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetMetaJson()
{
try
{
string json = Runtime.Plugin?.DashboardRenderer?.BuildMetaJson() ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _metaPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSendMetaCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendMetaCommand(IntPtr ansiJson)
{
try
{
if (ansiJson == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ansiJson);
if (string.IsNullOrEmpty(json)) return;
Runtime.Plugin?.DashboardRenderer?.HandleMetaCommand(json);
}
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AddSelectedWeapon()
{
try { Runtime.Plugin?.DashboardRenderer?.AddSelectedWeapon(); }
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedConsumable", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AddSelectedConsumable()
{
try { Runtime.Plugin?.DashboardRenderer?.AddSelectedConsumable(); }
catch { }
}
}

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\Publish</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,325 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Paints dungeon walls on the retail AC radar. Walls the player has walked
/// past render blue; unvisited walls render white. Portals (doorways) are
/// skipped so openings read as gaps. Current Z-layer only — multi-floor
/// dungeons stack would be unreadable otherwise.
///
/// Explored state is per-EnvCell and persisted per-landblock under
/// C:\Games\RynthSuite\RynthAi\ExploredDungeons\XXYY0000.json.
/// </summary>
internal sealed class RadarWallRenderer
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private MainLogic? _raycast;
// Colours (ABGR for ImGui).
private const uint ColorWall = 0xFFFFFFFF; // white — unvisited
private const uint ColorWallSeen = 0xFFFF6A2A; // blue-ish (RGB 0x2A6AFF → ABGR 0xFFFF6A2A)
private const uint ColorButtonBg = 0x80202020;
private const uint ColorButtonFg = 0xFFCCCCCC;
// Explored state (in-memory; flushed to disk).
private uint _currentLandblock;
private readonly HashSet<uint> _visitedCells = new();
private bool _visitedDirty;
private DateTime _lastSaveAt = DateTime.MinValue;
private uint _lastPlayerCellId;
// Z-layer filter: polygons whose cell Z is within this many world units of
// the player's Z are considered "same floor". AC dungeon floors are ~5u apart.
private const float FloorZTolerance = 2.5f;
// Reusable per-frame scratch for polygon vertex projection. Dungeon
// polygons are almost always ≤4 verts; 16 is ample headroom.
private const int MaxPolyVerts = 16;
private readonly Vector2[] _pts = new Vector2[MaxPolyVerts];
private readonly bool[] _inside = new bool[MaxPolyVerts];
private static readonly string ExploredDir =
@"C:\Games\RynthSuite\RynthAi\ExploredDungeons";
public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
_settings = settings;
}
public void SetRaycast(MainLogic raycast) => _raycast = raycast;
public void Render()
{
try { RenderCore(); }
catch (Exception ex) { _host.Log($"RadarWalls: {ex.Message}"); }
}
private void RenderCore()
{
if (!_settings.ShowRadarWalls)
return;
if (!_host.HasGetRadarRect)
return;
var los = _raycast?.GeometryLoader?.DungeonLOS;
if (los == null) return;
// ── Player state ─────────────────────────────────────────────
if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out float pz,
out _, out _, out _, out _))
return;
if ((cellId >> 16) == 0) return; // portalspace
if (_host.HasIsPortaling && _host.IsPortaling()) return;
uint landblock = cellId >> 16;
// Outdoor cells (0x0000–0x00FF in the low word) have no EnvCell geometry.
if ((cellId & 0xFFFF) < 0x0100)
return;
// ── Landblock transition — load explored state, flush previous ─
if (landblock != _currentLandblock)
{
if (_currentLandblock != 0 && _visitedDirty)
Save(_currentLandblock);
_currentLandblock = landblock;
_visitedCells.Clear();
Load(landblock);
_visitedDirty = false;
_lastPlayerCellId = 0;
}
// ── Mark visited when player cellId changes ──────────────────
if (cellId != _lastPlayerCellId)
{
_lastPlayerCellId = cellId;
if (_visitedCells.Add(cellId))
_visitedDirty = true;
}
// Debounced persist (save at most every 3s while moving).
if (_visitedDirty && (DateTime.UtcNow - _lastSaveAt).TotalSeconds > 3.0)
{
Save(landblock);
_lastSaveAt = DateTime.UtcNow;
_visitedDirty = false;
}
// ── Radar geometry ────────────────────────────────────────────
if (!_host.TryGetRadarRect(out int rx0, out int ry0, out int rx1, out int ry1))
return;
float centerX = (rx0 + rx1) * 0.5f;
float centerY = (ry0 + ry1) * 0.5f;
float radius = MathF.Min(rx1 - rx0, ry1 - ry0) * 0.5f - 2f;
if (radius < 10f) return;
float heading = 0f;
_host.TryGetPlayerHeading(out heading);
float hRad = heading * (MathF.PI / 180f);
float sinH = MathF.Sin(hRad);
float cosH = MathF.Cos(hRad);
float worldRange = MathF.Max(5f, _settings.RadarWallWorldRange);
float pxPerWorld = radius / worldRange;
// ── Polygon fetch ─────────────────────────────────────────────
var polys = los.GetDungeonMapPolygons(landblock);
if (polys == null || polys.Count == 0) return;
// ── Fullscreen transparent ImGui window ──────────────────────
if (!_host.TryGetViewportSize(out uint vpW, out uint vpH) || vpW == 0 || vpH == 0)
return;
ImGui.SetNextWindowPos(Vector2.Zero);
ImGui.SetNextWindowSize(new Vector2(vpW, vpH));
ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u);
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = true;
if (!ImGui.Begin("##RadarWalls", ref open,
ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize |
ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar |
ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoBringToFrontOnFocus |
ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav |
ImGuiWindowFlags.NoSavedSettings))
{
ImGui.End();
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
return;
}
var dl = ImGui.GetWindowDrawList();
var clipMin = new Vector2(rx0, ry0);
var clipMax = new Vector2(rx1, ry1);
dl.PushClipRect(clipMin, clipMax, intersect_with_current_clip_rect: true);
float r2 = radius * radius;
foreach (var poly in polys)
{
if (poly.IsPortal) continue;
if (MathF.Abs(poly.CellZ - pz) > FloorZTolerance) continue;
uint color = _visitedCells.Contains(poly.CellId) ? ColorWallSeen : ColorWall;
var verts = poly.Vertices;
int n = verts.Length;
if (n < 2 || n > MaxPolyVerts) continue;
// Project vertices to radar space once.
for (int i = 0; i < n; i++)
{
float wdx = verts[i].X - px; // east offset
float wdy = verts[i].Y - py; // north offset
// Rotate by -heading so player facing points "up" (screen -Y).
// forward = wx*sin(h) + wy*cos(h)
// right = wx*cos(h) - wy*sin(h)
float radarRight = wdx * cosH - wdy * sinH;
float radarForward = wdx * sinH + wdy * cosH;
float sx = centerX + radarRight * pxPerWorld;
float sy = centerY - radarForward * pxPerWorld;
_pts[i] = new Vector2(sx, sy);
float ddx = sx - centerX;
float ddy = sy - centerY;
_inside[i] = (ddx * ddx + ddy * ddy) <= r2;
}
// Draw each edge. Clip segments that stray fully outside the radar
// circle (PushClipRect handles the square bounds; circle clipping
// would need per-edge trimming we skip for MVP).
for (int i = 0; i < n - 1; i++)
{
if (!_inside[i] && !_inside[i + 1]) continue;
dl.AddLine(_pts[i], _pts[i + 1], color, 1.0f);
}
}
dl.PopClipRect();
// ── +/- zoom buttons at bottom-right of the radar ────────────
DrawZoomButtons(dl, rx1, ry1);
ImGui.End();
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
}
private void DrawZoomButtons(ImDrawListPtr dl, int rx1, int ry1)
{
const float btnW = 14f;
const float btnH = 14f;
const float gap = 2f;
float minusX = rx1 - btnW - 1f;
float plusX = rx1 - btnW * 2f - gap - 1f;
float btnY = ry1 - btnH - 1f;
var plusMin = new Vector2(plusX, btnY);
var plusMax = new Vector2(plusX + btnW, btnY + btnH);
var minusMin = new Vector2(minusX, btnY);
var minusMax = new Vector2(minusX + btnW, btnY + btnH);
Vector2 mouse = ImGui.GetIO().MousePos;
bool plusHover = mouse.X >= plusMin.X && mouse.X <= plusMax.X && mouse.Y >= plusMin.Y && mouse.Y <= plusMax.Y;
bool minusHover = mouse.X >= minusMin.X && mouse.X <= minusMax.X && mouse.Y >= minusMin.Y && mouse.Y <= minusMax.Y;
dl.AddRectFilled(plusMin, plusMax, plusHover ? 0xC0404040 : ColorButtonBg, 2f);
dl.AddRectFilled(minusMin, minusMax, minusHover ? 0xC0404040 : ColorButtonBg, 2f);
dl.AddRect(plusMin, plusMax, ColorButtonFg, 2f);
dl.AddRect(minusMin, minusMax, ColorButtonFg, 2f);
var plusCenter = (plusMin + plusMax) * 0.5f;
var minusCenter = (minusMin + minusMax) * 0.5f;
dl.AddLine(new Vector2(plusCenter.X - 4f, plusCenter.Y),
new Vector2(plusCenter.X + 4f, plusCenter.Y), ColorButtonFg, 1.5f);
dl.AddLine(new Vector2(plusCenter.X, plusCenter.Y - 4f),
new Vector2(plusCenter.X, plusCenter.Y + 4f), ColorButtonFg, 1.5f);
dl.AddLine(new Vector2(minusCenter.X - 4f, minusCenter.Y),
new Vector2(minusCenter.X + 4f, minusCenter.Y), ColorButtonFg, 1.5f);
if (ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
if (plusHover) _settings.RadarWallWorldRange = MathF.Max(10f, _settings.RadarWallWorldRange - 5f);
if (minusHover) _settings.RadarWallWorldRange = MathF.Min(150f, _settings.RadarWallWorldRange + 5f);
}
}
// ── Persistence ─────────────────────────────────────────────────
// File format: raw little-endian uint32 cell ids, back-to-back. No header —
// filename implies the landblock. Plain binary keeps this AOT-trivial (no
// JSON reflection) and stays tiny.
private static string PathFor(uint landblock)
=> Path.Combine(ExploredDir, $"{landblock:X4}0000.bin");
private void Load(uint landblock)
{
string path = PathFor(landblock);
if (!File.Exists(path)) return;
try
{
byte[] bytes = File.ReadAllBytes(path);
int count = bytes.Length / sizeof(uint);
for (int i = 0; i < count; i++)
{
uint id = BinaryPrimitives.ReadUInt32LittleEndian(
bytes.AsSpan(i * sizeof(uint), sizeof(uint)));
_visitedCells.Add(id);
}
}
catch (Exception ex)
{
_host.Log($"RadarWalls: load {path} failed: {ex.Message}");
}
}
private void Save(uint landblock)
{
try
{
Directory.CreateDirectory(ExploredDir);
byte[] bytes = new byte[_visitedCells.Count * sizeof(uint)];
int i = 0;
foreach (uint id in _visitedCells)
{
BinaryPrimitives.WriteUInt32LittleEndian(
bytes.AsSpan(i * sizeof(uint), sizeof(uint)), id);
i++;
}
File.WriteAllBytes(PathFor(landblock), bytes);
}
catch (Exception ex)
{
_host.Log($"RadarWalls: save failed: {ex.Message}");
}
}
/// <summary>Flush any unsaved state — call on shutdown or logout.</summary>
public void Flush()
{
if (_visitedDirty && _currentLandblock != 0)
{
Save(_currentLandblock);
_visitedDirty = false;
}
}
}

View file

@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
public class BlacklistManager
{
/// <summary>
/// Tracks consecutive failures for specific WorldObjects.
/// Incremented when an attack on a target produces no server feedback.
/// </summary>
private readonly Dictionary<int, int> _failureCounts = new Dictionary<int, int>();
/// <summary>
/// Tracks the expiration time for blacklisted targets.
/// Targets are temporarily ignored if they're stuck in walls or ghosts.
/// </summary>
private readonly Dictionary<int, DateTime> _blacklistExpirations = new Dictionary<int, DateTime>();
/// <summary>Optional diagnostic sink — invoked whenever a target is blacklisted.</summary>
public Action<string>? Log;
/// <summary>
/// Number of consecutive attack failures before a target is blacklisted.
/// Default: 1 — CombatManager sets this explicitly (CombatManager.cs:1711)
/// because the "give it N casts before giving up" counting lives in
/// JudgePendingCast; one report reaching here already means judged-failed.
/// (The stale "Default: 3" comment here drove a 2026-06-03 audit finding
/// that read the 1 as a bug — it isn't.)
/// </summary>
public int AttemptThreshold { get; set; } = 1;
/// <summary>
/// Duration in seconds that a target remains blacklisted after threshold is breached.
/// Default: 300 seconds — long enough that non-attackable objects stay gone for the session.
/// </summary>
public int TimeoutSeconds { get; set; } = 300;
/// <summary>
/// Increments the failure count for a target.
/// Call this if an attack is launched but yields no server feedback (damage, XP, etc.).
/// If the failure count reaches the threshold, the target is automatically blacklisted.
/// </summary>
public void ReportFailure(int targetId)
{
if (!_failureCounts.ContainsKey(targetId))
_failureCounts[targetId] = 0;
_failureCounts[targetId]++;
// Log the failure for debugging
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure count: {_failureCounts[targetId]}/{AttemptThreshold}");
// If the threshold is breached, blacklist the target
if (_failureCounts[targetId] >= AttemptThreshold)
{
BlacklistTarget(targetId);
}
}
/// <summary>
/// Immediately blacklists a target for the configured timeout duration.
/// </summary>
private void BlacklistTarget(int targetId)
{
DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds);
_blacklistExpirations[targetId] = expirationTime;
int fc = _failureCounts.TryGetValue(targetId, out var c) ? c : 0;
Log?.Invoke($"0x{(uint)targetId:X8} blacklisted {TimeoutSeconds}s (failures={fc})");
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklisted until {expirationTime:HH:mm:ss}");
}
/// <summary>
/// Checks if a target should be ignored by the targeting system.
/// Returns true if the target is currently blacklisted (timeout not expired).
/// Returns false if the target is not blacklisted or if its timeout has expired.
/// </summary>
public bool IsBlacklisted(int targetId)
{
if (!_blacklistExpirations.TryGetValue(targetId, out var expiration))
return false; // Target not in blacklist
// Check if blacklist timeout has expired
if (DateTime.Now >= expiration)
{
// Timeout expired - remove from blacklist and allow re-evaluation
_blacklistExpirations.Remove(targetId);
_failureCounts.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklist expired, re-evaluating");
return false;
}
// Target still blacklisted
return true;
}
/// <summary>Forget a target entirely (D8): drop its failure count and any blacklist entry.
/// Called when the object is deleted so a respawn reusing the GUID starts from a clean slate
/// instead of inheriting the despawned object's 300s blacklist timeout.</summary>
public void ForgetTarget(int targetId)
{
_failureCounts.Remove(targetId);
_blacklistExpirations.Remove(targetId);
}
/// <summary>
/// Clears the failure count and blacklist status for a target.
/// Call this when a target successfully takes damage or shows other server feedback.
/// This allows the target to be re-engaged if it becomes blocked again later.
/// </summary>
public void ClearFailure(int targetId)
{
_failureCounts.Remove(targetId);
_blacklistExpirations.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure cleared");
}
/// <summary>
/// Completely clears all blacklist and failure tracking data.
/// Useful when transitioning between combat zones or resetting the bot state.
/// </summary>
public void ClearAll()
{
_failureCounts.Clear();
_blacklistExpirations.Clear();
System.Diagnostics.Debug.WriteLine("All blacklist data cleared");
}
/// <summary>
/// Returns the number of currently blacklisted targets.
/// Useful for debugging and monitoring bot behavior.
/// </summary>
public int GetBlacklistCount()
{
int count = 0;
var expiredKeys = new List<int>();
foreach (var kvp in _blacklistExpirations)
{
if (DateTime.Now < kvp.Value)
{
count++;
}
else
{
expiredKeys.Add(kvp.Key);
}
}
// Clean up expired entries while we're here
foreach (var key in expiredKeys)
{
_blacklistExpirations.Remove(key);
_failureCounts.Remove(key);
}
return count;
}
}
}

View file

@ -0,0 +1,385 @@
using System;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Bounding volume for collision detection
/// Supports ray-volume intersection testing for raycasting
/// </summary>
public class BoundingVolume
{
public enum VolumeType
{
Sphere = 1,
Cylinder = 2,
Ellipsoid = 3,
Polygon = 4,
AxisAlignedBox = 5,
Torus = 6,
TriangleMesh = 7
}
public VolumeType Type { get; set; }
public Vector3 Center { get; set; } // X, Y, Z
public Vector3 Dimensions { get; set; } // Radius, Height, etc
public Vector3[] Vertices { get; set; } // For polygons
/// <summary>
/// Triangle mesh data — groups of 3 consecutive Vector3 vertices.
/// Used by TriangleMesh type for precise building collision.
/// AABB (Min/Max) is used as a pre-filter before testing triangles.
/// </summary>
public Vector3[] MeshTriangles { get; set; }
// Additional properties for geometry loading
public Vector3 Min { get; set; } // Minimum bounds
public Vector3 Max { get; set; } // Maximum bounds
public bool IsDoor { get; set; } // Whether this is a door (passable)
public bool NoAabbFallback { get; set; } // If true, only count actual triangle hits (no AABB fallback)
public BoundingVolume()
{
Center = new Vector3(0, 0, 0);
Dimensions = new Vector3(0, 0, 0);
Min = new Vector3(0, 0, 0);
Max = new Vector3(0, 0, 0);
IsDoor = false;
}
/// <summary>
/// Test if a ray intersects this volume
/// Returns true if collision detected
/// </summary>
public bool RayIntersect(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
try
{
switch (Type)
{
case VolumeType.Sphere:
return RayIntersectSphere(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Cylinder:
return RayIntersectCylinder(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.AxisAlignedBox:
return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Polygon:
return RayIntersectPolygon(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.TriangleMesh:
if (MeshTriangles != null && MeshTriangles.Length >= 3)
return RayIntersectTriangleMesh(rayStart, rayDir, maxDist, out hitDist);
return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist);
default:
return false;
}
}
catch
{
return false;
}
}
/// <summary>
/// Overload to accept float arrays for backwards compatibility
/// </summary>
public bool RayIntersect(float[] rayStart, float[] rayDir, float maxDist, out float hitDist)
{
return RayIntersect(
Vector3.FromArray(rayStart),
Vector3.FromArray(rayDir),
maxDist,
out hitDist
);
}
/// <summary>
/// Ray-Sphere intersection
/// </summary>
private bool RayIntersectSphere(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
Vector3 oc = rayStart - Center;
float a = Vector3.Dot(rayDir, rayDir);
float b = 2.0f * Vector3.Dot(oc, rayDir);
float c = Vector3.Dot(oc, oc) - (Dimensions.X * Dimensions.X);
float discriminant = b * b - 4 * a * c;
if (discriminant < 0)
return false;
float sqrt_disc = (float)Math.Sqrt(discriminant);
float t1 = (-b - sqrt_disc) / (2 * a);
float t2 = (-b + sqrt_disc) / (2 * a);
if (t1 > 0 && t1 < maxDist)
{
hitDist = t1;
return true;
}
// Ray starts inside sphere (t1 < 0, t2 > 0)
if (t1 <= 0 && t2 > 0 && t2 < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Cylinder intersection (vertical cylinder along Z axis).
/// Tests the curved surface and top/bottom caps.
/// </summary>
private bool RayIntersectCylinder(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
float radius = Dimensions.X;
float bottomZ = Min.Z;
float topZ = Max.Z;
// Project onto XY plane for infinite cylinder test
float dx = rayStart.X - Center.X;
float dy = rayStart.Y - Center.Y;
float a = rayDir.X * rayDir.X + rayDir.Y * rayDir.Y;
float b = 2.0f * (dx * rayDir.X + dy * rayDir.Y);
float c = dx * dx + dy * dy - radius * radius;
// Nearly vertical ray — check if inside cylinder radius, then test caps
if (a < 1e-6f)
{
if (c > 0) return false; // Outside cylinder radius
if (Math.Abs(rayDir.Z) < 1e-6f) { hitDist = 0; return true; } // Inside, horizontal
float tBot = (bottomZ - rayStart.Z) / rayDir.Z;
float tTop = (topZ - rayStart.Z) / rayDir.Z;
float tNear = Math.Min(tBot, tTop);
float tFar = Math.Max(tBot, tTop);
if (tNear > maxDist || tFar < 0) return false;
hitDist = tNear > 0 ? tNear : 0;
return true;
}
float disc = b * b - 4 * a * c;
if (disc < 0)
{
// No side hit — but caps may still intersect if ray enters from top/bottom
goto CheckCaps;
}
float sqrtDisc = (float)Math.Sqrt(disc);
float t1 = (-b - sqrtDisc) / (2 * a);
float t2 = (-b + sqrtDisc) / (2 * a);
// Check side hits against height bounds
float z1 = rayStart.Z + t1 * rayDir.Z;
if (t1 > 0 && t1 < maxDist && z1 >= bottomZ && z1 <= topZ)
{
hitDist = t1;
return true;
}
float z2 = rayStart.Z + t2 * rayDir.Z;
if (t2 > 0 && t2 < maxDist && z2 >= bottomZ && z2 <= topZ)
{
hitDist = t2;
return true;
}
// Ray starts inside cylinder
if (t1 <= 0 && t2 > 0 && rayStart.Z >= bottomZ && rayStart.Z <= topZ)
{
hitDist = 0;
return true;
}
CheckCaps:
// Test top and bottom cap discs
if (Math.Abs(rayDir.Z) > 1e-6f)
{
float tBot = (bottomZ - rayStart.Z) / rayDir.Z;
if (tBot > 0 && tBot < maxDist)
{
float hx = rayStart.X + tBot * rayDir.X - Center.X;
float hy = rayStart.Y + tBot * rayDir.Y - Center.Y;
if (hx * hx + hy * hy <= radius * radius)
{
hitDist = tBot;
return true;
}
}
float tTop = (topZ - rayStart.Z) / rayDir.Z;
if (tTop > 0 && tTop < maxDist)
{
float hx = rayStart.X + tTop * rayDir.X - Center.X;
float hy = rayStart.Y + tTop * rayDir.Y - Center.Y;
if (hx * hx + hy * hy <= radius * radius)
{
hitDist = tTop;
return true;
}
}
}
return false;
}
/// <summary>
/// Ray-AABB intersection
/// </summary>
private bool RayIntersectAABB(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
float tmin = 0, tmax = maxDist;
for (int i = 0; i < 3; i++)
{
float rayStartCoord = i == 0 ? rayStart.X : (i == 1 ? rayStart.Y : rayStart.Z);
float rayDirCoord = i == 0 ? rayDir.X : (i == 1 ? rayDir.Y : rayDir.Z);
float minCoord = i == 0 ? Min.X : (i == 1 ? Min.Y : Min.Z);
float maxCoord = i == 0 ? Max.X : (i == 1 ? Max.Y : Max.Z);
if (Math.Abs(rayDirCoord) < 0.00001f)
{
if (rayStartCoord < minCoord || rayStartCoord > maxCoord)
return false;
}
else
{
float t1 = (minCoord - rayStartCoord) / rayDirCoord;
float t2 = (maxCoord - rayStartCoord) / rayDirCoord;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = Math.Max(tmin, t1);
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
}
}
if (tmin > 0 && tmin < maxDist)
{
hitDist = tmin;
return true;
}
// Ray starts inside the box (tmin <= 0 but tmax > 0)
// This means the player is inside/overlapping the obstacle
if (tmin <= 0 && tmax > 0 && tmax < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Polygon intersection
/// </summary>
private bool RayIntersectPolygon(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
if (Vertices == null || Vertices.Length < 3)
return false;
for (int i = 0; i < Vertices.Length - 2; i++)
{
if (RayIntersectTriangle(rayStart, rayDir, Vertices[0], Vertices[i + 1], Vertices[i + 2], out float t))
{
if (t >= 0 && t < maxDist && t < hitDist)
{
hitDist = t;
return true;
}
}
}
return false;
}
/// <summary>
/// Ray-TriangleMesh intersection.
/// Uses AABB as a pre-filter, then tests each triangle (Möller-Trumbore).
/// MeshTriangles stores groups of 3 consecutive vertices per triangle.
/// </summary>
private bool RayIntersectTriangleMesh(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
// AABB test — the AABB covers the full building extent (all vertices, not just physics)
if (!RayIntersectAABB(rayStart, rayDir, maxDist, out float aabbDist))
return false;
// Test physics triangles for precise hit
for (int i = 0; i + 2 < MeshTriangles.Length; i += 3)
{
if (RayIntersectTriangle(rayStart, rayDir, MeshTriangles[i], MeshTriangles[i + 1], MeshTriangles[i + 2], out float t))
{
if (t >= 0 && t < maxDist && t < hitDist)
hitDist = t;
}
}
if (hitDist < float.MaxValue)
return true;
// No triangle hit but AABB hit — for buildings with incomplete physics mesh,
// fall back to AABB. For dungeon physics polygons (NoAabbFallback=true),
// no triangle hit means the ray passed through an opening (doorway/corridor).
if (NoAabbFallback)
return false;
hitDist = aabbDist;
return true;
}
/// <summary>
/// Ray-Triangle intersection (Möller-Trumbore algorithm)
/// </summary>
private bool RayIntersectTriangle(Vector3 rayStart, Vector3 rayDir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = float.MaxValue;
const float EPSILON = 0.0000001f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(rayDir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -EPSILON && a < EPSILON)
return false;
float f = 1.0f / a;
Vector3 s = rayStart - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0 || u > 1)
return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(rayDir, q);
if (v < 0 || u + v > 1)
return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0;
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,779 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// A position + rotation in AC's 3D world.
/// Position is in local landblock meters (0-192 for outdoors).
/// Rotation is a quaternion (W, X, Y, Z).
/// </summary>
public class Frame
{
public float OriginX, OriginY, OriginZ;
public float RotW, RotX, RotY, RotZ;
public Frame()
{
RotW = 1.0f; // Identity quaternion
}
public void Unpack(BinaryReader reader)
{
OriginX = reader.ReadSingle();
OriginY = reader.ReadSingle();
OriginZ = reader.ReadSingle();
RotW = reader.ReadSingle();
RotX = reader.ReadSingle();
RotY = reader.ReadSingle();
RotZ = reader.ReadSingle();
}
/// <summary>
/// Rotates a point by this frame's quaternion.
/// q * v * q^-1 (for unit quaternion, q^-1 = conjugate)
/// </summary>
public Vector3 RotatePoint(Vector3 point)
{
// Quaternion rotation: v' = q * v * q*
float qw = RotW, qx = RotX, qy = RotY, qz = RotZ;
// Cross product of quaternion xyz with point
float cx = qy * point.Z - qz * point.Y;
float cy = qz * point.X - qx * point.Z;
float cz = qx * point.Y - qy * point.X;
// Result = point + 2 * (qw * cross + qxyz x cross)
float cx2 = qy * cz - qz * cy;
float cy2 = qz * cx - qx * cz;
float cz2 = qx * cy - qy * cx;
return new Vector3(
point.X + 2.0f * (qw * cx + cx2),
point.Y + 2.0f * (qw * cy + cy2),
point.Z + 2.0f * (qw * cz + cz2)
);
}
/// <summary>
/// Transforms a point: rotate then translate.
/// </summary>
public Vector3 TransformPoint(Vector3 localPoint)
{
Vector3 rotated = RotatePoint(localPoint);
return new Vector3(
rotated.X + OriginX,
rotated.Y + OriginY,
rotated.Z + OriginZ
);
}
public override string ToString()
{
return $"Pos({OriginX:F2}, {OriginY:F2}, {OriginZ:F2}) Rot({RotW:F3}, {RotX:F3}, {RotY:F3}, {RotZ:F3})";
}
}
/// <summary>
/// A static object placed on a landblock (building, tree, rock, structure, etc.)
/// </summary>
public class StaticObject
{
public uint InstanceId; // Unique placement ID
public uint SetupId; // Reference to 0x02xxxxxx Setup in portal.dat
public Frame Placement; // Position and rotation in landblock space
public StaticObject()
{
Placement = new Frame();
}
}
/// <summary>
/// Parsed landblock info from cell.dat (file ID = 0xXXYYFFFE).
/// Contains static object placements (Stabs) and building info for an outdoor landblock.
///
/// Format (from ACE.DatLoader.FileTypes.LandblockInfo):
/// uint32 Id
/// uint32 NumCells
/// uint32 NumObjects (List&lt;Stab&gt; count)
/// Stab[NumObjects]:
/// uint32 Id (model/setup reference, 0x01xx or 0x02xx)
/// Frame (7 floats: pos.xyz + rot.wxyz = 28 bytes)
/// ushort NumBuildings
/// ushort PackMask
/// BuildInfo[NumBuildings]:
/// uint32 ModelId
/// Frame (28 bytes)
/// uint32 NumLeaves
/// List&lt;CBldPortal&gt; Portals
/// if (PackMask &amp; 1):
/// PackedHashTable RestrictionTables
/// </summary>
public class LandblockInfo
{
public uint Id;
public uint NumCells;
public List<StaticObject> StaticObjects = new List<StaticObject>();
public bool HasObjects;
/// <summary>
/// Parse landblock info from raw .dat file data using the ACE format.
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
NumCells = reader.ReadUInt32();
// Read List<Stab> — uint32 count + count × Stab entries
uint numObjects = reader.ReadUInt32();
if (numObjects > 5000) numObjects = 5000; // Sanity
for (uint i = 0; i < numObjects; i++)
{
if (ms.Position + 32 > ms.Length) break; // Need 4 (Id) + 28 (Frame)
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
HasObjects = StaticObjects.Count > 0;
Log($"Landblock 0x{Id:X8}: {StaticObjects.Count} static objects");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing landblock 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}");
}
}
/// <summary>
/// Parsed environment cell from cell.dat (file ID = 0xXXYY0001 to 0xXXYYFFFE).
/// Represents an indoor dungeon room with walls, portals, and static objects.
/// </summary>
public class EnvCellInfo
{
public uint Id;
public uint Flags;
public List<Vector3> Vertices = new List<Vector3>();
public List<CellPolygon> Polygons = new List<CellPolygon>();
public List<ushort> PortalPolygonIndices = new List<ushort>();
public List<StaticObject> StaticObjects = new List<StaticObject>();
public List<uint> ConnectedCells = new List<uint>();
public uint EnvironmentId; // Reference to portal.dat environment
public uint StructureId; // Reference to portal.dat cell structure
/// <summary>
/// Parse environment cell from raw data.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// uint32 environmentId (0x0Dxxxxxx)
/// uint16 cellStructId
/// uint16 position (index into structure)
/// Frame placement
/// uint32 numPortals
/// for each portal:
/// uint16 polygonId (portal polygon index)
/// uint16 flags
/// uint32 connectedCell
/// uint32 numStaticObjects
/// for each static object:
/// uint32 setupId
/// Frame placement
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Read environment/structure references
if (ms.Position + 8 > ms.Length) return false;
// The exact format depends on flags, but typically:
EnvironmentId = reader.ReadUInt32();
if (ms.Position + 4 > ms.Length) return false;
StructureId = reader.ReadUInt32();
// Read cell frame (position + rotation)
if ((Flags & 0x02) != 0 && ms.Position + 28 <= ms.Length)
{
var frame = new Frame();
frame.Unpack(reader);
}
// Read portals
if ((Flags & 0x04) != 0 || ms.Position + 4 <= ms.Length)
{
if (ms.Position + 4 <= ms.Length)
{
uint numPortals = reader.ReadUInt32();
if (numPortals > 1000) numPortals = 0; // Sanity
for (uint i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++)
{
ushort polyId = reader.ReadUInt16();
ushort portalFlags = reader.ReadUInt16();
uint connCell = reader.ReadUInt32();
PortalPolygonIndices.Add(polyId);
ConnectedCells.Add(connCell);
}
}
}
// Read static objects
if (ms.Position + 4 <= ms.Length)
{
uint numObjects = reader.ReadUInt32();
if (numObjects > 10000) numObjects = 0;
for (uint i = 0; i < numObjects && ms.Position + 32 <= ms.Length; i++)
{
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
}
Log($"EnvCell 0x{Id:X8}: {StaticObjects.Count} objects, " +
$"{PortalPolygonIndices.Count} portals");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing EnvCell 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}");
}
}
/// <summary>
/// A polygon in a cell structure (wall, floor, ceiling).
/// </summary>
public class CellPolygon
{
public ushort[] VertexIndices;
public bool IsPortal; // Portal polygons are openings, not solid walls
}
/// <summary>
/// Parsed Setup file from portal.dat (file ID = 0x02xxxxxx).
/// Matches ACE.DatLoader.FileTypes.SetupModel.Unpack() exactly.
///
/// Format:
/// uint32 Id
/// uint32 Flags (SetupFlags)
/// uint32 numParts
/// uint32[numParts] Parts (GfxObj references, 0x01xxxxxx)
/// if (Flags & 0x01): uint32[numParts] ParentIndex
/// if (Flags & 0x02): Vector3[numParts] DefaultScale
/// Dictionary&lt;int,LocationType&gt; HoldingLocations (uint32 count + entries)
/// Dictionary&lt;int,LocationType&gt; ConnectionPoints (uint32 count + entries)
/// int32 placementsCount
/// PlacementType[placementsCount]: key(int32) + AnimFrame(numParts × Frame(28) + uint32 numHooks + hooks)
/// List&lt;CylSphere&gt; CylSpheres (uint32 count + count × 20 bytes)
/// List&lt;Sphere&gt; Spheres (uint32 count + count × 16 bytes)
/// float Height, Radius, StepUpHeight, StepDownHeight
/// Sphere SortingSphere (Vector3 + float = 16 bytes)
/// Sphere SelectionSphere (16 bytes)
/// Dictionary&lt;int,LightInfo&gt; Lights
/// uint32 × 5 defaults
/// </summary>
public class SetupInfo
{
public uint Id;
public uint Flags;
public int NumParts;
public uint[] PartIds;
// Bounding sphere (from SortingSphere)
public float BoundingSphereRadius;
public Vector3 BoundingSphereCenter;
// Physics dimensions
public float Height;
public float Radius; // Physics collision radius
// Collision spheres
public List<CollisionSphere> Spheres = new List<CollisionSphere>();
// Collision cylinders
public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>();
// Default pose part frames (from first placement in Setup)
// Used to compute composite building bounding volumes.
public Frame[] PartFrames;
public bool HasBounds;
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 16)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
// --- Header ---
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
uint numParts = reader.ReadUInt32();
if (numParts > 500) return false;
NumParts = (int)numParts;
PartIds = new uint[numParts];
for (int i = 0; i < numParts; i++)
PartIds[i] = reader.ReadUInt32();
// --- Optional arrays based on flags ---
// HasParent = 0x01
if ((Flags & 0x01) != 0)
ms.Seek(numParts * 4, SeekOrigin.Current);
// HasDefaultScale = 0x02
if ((Flags & 0x02) != 0)
ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes
// --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip ConnectionPoints: same format ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip PlacementFrames ---
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
int placementsCount = reader.ReadInt32();
if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data);
for (int p = 0; p < placementsCount; p++)
{
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
reader.ReadInt32(); // key
// AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks
for (int part = 0; part < numParts; part++)
{
if (ms.Position + 28 > ms.Length) return TryFallbackParse(data);
if (p == 0) // Store default pose part frames for composite bounds
{
if (PartFrames == null) PartFrames = new Frame[numParts];
PartFrames[part] = new Frame();
PartFrames[part].Unpack(reader);
}
else
{
ms.Seek(28, SeekOrigin.Current);
}
}
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
uint numHooks = reader.ReadUInt32();
if (numHooks > 0)
{
// AnimationHooks are variable-size; can't easily skip
// But we already stored PartFrames from the default placement above
return TryFallbackParse(data);
}
}
// --- NOW we're at the good stuff! ---
return ReadBoundsData(reader, ms, data);
}
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Reads CylSpheres, Spheres, Height, Radius, SortingSphere from current position.
/// </summary>
private bool ReadBoundsData(BinaryReader reader, MemoryStream ms, byte[] data)
{
try
{
// CylSpheres: uint32 count + count × (Vector3 origin(12) + float radius(4) + float height(4) = 20)
if (ms.Position + 4 > ms.Length) return false;
uint numCylSpheres = reader.ReadUInt32();
if (numCylSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numCylSpheres; i++)
{
if (ms.Position + 20 > ms.Length) break;
var cyl = new CollisionCylinder();
cyl.BottomCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
cyl.Radius = reader.ReadSingle();
cyl.Height = reader.ReadSingle();
if (cyl.Radius > 0 && cyl.Height > 0 && !float.IsNaN(cyl.Radius))
Cylinders.Add(cyl);
}
// Spheres: uint32 count + count × (Vector3 origin(12) + float radius(4) = 16)
if (ms.Position + 4 > ms.Length) return false;
uint numSpheres = reader.ReadUInt32();
if (numSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numSpheres; i++)
{
if (ms.Position + 16 > ms.Length) break;
var sphere = new CollisionSphere();
sphere.Center = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
sphere.Radius = reader.ReadSingle();
if (sphere.Radius > 0 && !float.IsNaN(sphere.Radius))
Spheres.Add(sphere);
}
// Height, Radius, StepUpHeight, StepDownHeight
if (ms.Position + 16 > ms.Length) return false;
Height = reader.ReadSingle();
Radius = reader.ReadSingle();
float stepUp = reader.ReadSingle();
float stepDown = reader.ReadSingle();
// SortingSphere: Vector3 center + float radius
if (ms.Position + 16 > ms.Length) return false;
float sx = reader.ReadSingle(), sy = reader.ReadSingle(), sz = reader.ReadSingle();
float sr = reader.ReadSingle();
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = sr > 0.001f || Radius > 0.001f;
// If SortingSphere radius is 0, use the physics Radius
if (BoundingSphereRadius < 0.001f && Radius > 0.001f)
BoundingSphereRadius = Radius;
Log($"Setup 0x{Id:X8}: bounds OK — radius={BoundingSphereRadius:F2}, height={Height:F2}, " +
$"{Cylinders.Count} cyls, {Spheres.Count} spheres");
return true;
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Skip a hash table: uint32 count + count × entries of entrySize bytes.
/// </summary>
private bool SkipHashTable(BinaryReader reader, MemoryStream ms, int entrySize)
{
if (ms.Position + 4 > ms.Length) return false;
uint count = reader.ReadUInt32();
if (count > 1000) return false;
long skip = (long)count * entrySize;
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
return true;
}
/// <summary>
/// Fallback: scan from the end of the file for the known tail structure.
/// The tail is always:
/// ... SortingSphere(16) + SelectionSphere(16) + Lights(uint32 count + entries) + 5×uint32(20)
/// If Lights is empty (count=0 → 4 bytes), tail is 56 bytes from end.
/// </summary>
private bool TryFallbackParse(byte[] data)
{
try
{
// Read header to get PartIds at minimum
if (PartIds == null && data.Length >= 16)
{
using (var ms2 = new MemoryStream(data))
using (var r2 = new BinaryReader(ms2))
{
Id = r2.ReadUInt32();
Flags = r2.ReadUInt32();
uint np = r2.ReadUInt32();
if (np <= 500)
{
NumParts = (int)np;
PartIds = new uint[np];
for (int i = 0; i < np && ms2.Position + 4 <= ms2.Length; i++)
PartIds[i] = r2.ReadUInt32();
}
}
}
// Try to find SortingSphere by scanning from end
// Known tail (if Lights empty): 5×uint32(20) + Lights(4) + SelectionSphere(16) + SortingSphere(16) + 4×float(16)
// = 72 bytes from end for start of Height/Radius/StepUp/StepDown
int[] tailOffsets = { 72, 78, 84 }; // Try different Lights sizes (4, 10, 16 bytes)
foreach (int tailOff in tailOffsets)
{
int offset = data.Length - tailOff;
if (offset < 16 || offset + 48 > data.Length) continue;
float h = BitConverter.ToSingle(data, offset);
float r = BitConverter.ToSingle(data, offset + 4);
float sx = BitConverter.ToSingle(data, offset + 16);
float sy = BitConverter.ToSingle(data, offset + 20);
float sz = BitConverter.ToSingle(data, offset + 24);
float sr = BitConverter.ToSingle(data, offset + 28);
// Validate: Height and Radius should be positive, sphere radius positive, center reasonable
if (h >= 0 && h < 100 && r > 0 && r < 200 &&
sr > 0 && sr < 500 &&
!float.IsNaN(h) && !float.IsNaN(r) && !float.IsNaN(sr) &&
Math.Abs(sx) < 1000 && Math.Abs(sy) < 1000 && Math.Abs(sz) < 1000)
{
Height = h;
Radius = r;
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = true;
Log($"Setup 0x{Id:X8}: FALLBACK found bounds at tailOff={tailOff} — radius={sr:F2}, height={h:F2}");
return true;
}
}
Log($"Setup 0x{Id:X8}: FALLBACK failed, no valid bounds found");
return false;
}
catch
{
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[Setup] {msg}");
}
}
/// <summary>
/// Parsed GfxObj from portal.dat (file ID = 0x01xxxxxx).
/// Contains 3D mesh data. We extract the bounding sphere and AABB.
/// </summary>
public class GfxObjInfo
{
public uint Id;
public uint Flags;
// Bounding data (what we need for raycasting)
public Vector3 SortingCenter;
public float SortingRadius;
public Vector3 BoundsMin;
public Vector3 BoundsMax;
public bool HasBounds;
// Vertex data (for precise bounds calculation)
public List<Vector3> Vertices = new List<Vector3>();
/// <summary>
/// Parse GfxObj to extract bounding information.
/// We don't need the full mesh/texture data for raycasting.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// -- surface data (skip) --
/// uint32 numVertices
/// for each vertex:
/// float3 position
/// float3 normal
/// (optional UV data based on flags)
/// -- polygon data (skip) --
/// -- BSP data (skip for now) --
/// float3 sortingCenter
/// float sortingRadius
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Surfaces use SmartArray: compressed uint32 count + uint32[] IDs
if (ms.Position + 1 > ms.Length) return false;
uint numSurfaces = ReadCompressedUInt32(reader);
if (numSurfaces > 10000) return false;
ms.Seek(numSurfaces * 4, SeekOrigin.Current);
// CVertexArray: int32 vertexType + uint32 numVertices
if (ms.Position + 8 > ms.Length) return false;
int vertexType = reader.ReadInt32();
uint numVertices = reader.ReadUInt32();
if (numVertices > 100000 || vertexType != 1) return false;
// Read vertices and compute AABB
float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue;
float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue;
for (uint i = 0; i < numVertices; i++)
{
// Per vertex: ushort key, ushort numUVs, float3 pos, float3 normal, numUVs*float2 UVs
if (ms.Position + 28 > ms.Length) break;
reader.ReadUInt16(); // vertex key
ushort numUVs = reader.ReadUInt16();
float x = reader.ReadSingle();
float y = reader.ReadSingle();
float z = reader.ReadSingle();
if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)) continue;
Vertices.Add(new Vector3(x, y, z));
minX = Math.Min(minX, x); maxX = Math.Max(maxX, x);
minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
minZ = Math.Min(minZ, z); maxZ = Math.Max(maxZ, z);
// Skip normal (3 floats) + UV data (numUVs * 2 floats)
long skip = 12 + (long)numUVs * 8;
if (ms.Position + skip > ms.Length) break;
ms.Seek(skip, SeekOrigin.Current);
}
if (Vertices.Count > 0)
{
BoundsMin = new Vector3(minX, minY, minZ);
BoundsMax = new Vector3(maxX, maxY, maxZ);
HasBounds = true;
// Compute bounding sphere from AABB
SortingCenter = new Vector3(
(minX + maxX) * 0.5f,
(minY + maxY) * 0.5f,
(minZ + maxZ) * 0.5f
);
SortingRadius = (BoundsMax - SortingCenter).Length();
}
// Also try to find the explicit sorting sphere at the end of file
TryReadSortingSphere(data);
Log($"GfxObj 0x{Id:X8}: {Vertices.Count} verts, radius={SortingRadius:F2}");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing GfxObj 0x{Id:X8}: {ex.Message}");
return false;
}
}
/// <summary>
/// Reads a variable-length compressed uint32 (AC SmartArray count format).
/// </summary>
private static uint ReadCompressedUInt32(BinaryReader reader)
{
byte b0 = reader.ReadByte();
if ((b0 & 0x80) == 0) return b0;
byte b1 = reader.ReadByte();
if ((b0 & 0x40) == 0) return (uint)(((b0 & 0x7F) << 8) | b1);
ushort s = reader.ReadUInt16();
return (uint)((((b0 & 0x3F) << 8) | b1) << 16 | s);
}
/// <summary>
/// Scans the end of the file for the sorting sphere data.
/// The sorting center + radius are typically near the end of the GfxObj.
/// </summary>
private void TryReadSortingSphere(byte[] data)
{
// The last 16 bytes before any trailing data often contain the sorting sphere
if (data.Length < 20) return;
// Try reading from the last 16 bytes
for (int offset = data.Length - 16; offset >= Math.Max(0, data.Length - 64); offset -= 4)
{
if (offset + 16 > data.Length) continue;
float cx = BitConverter.ToSingle(data, offset);
float cy = BitConverter.ToSingle(data, offset + 4);
float cz = BitConverter.ToSingle(data, offset + 8);
float r = BitConverter.ToSingle(data, offset + 12);
if (r > 0.01f && r < 500f && !float.IsNaN(r) && !float.IsInfinity(r) &&
!float.IsNaN(cx) && !float.IsNaN(cy) && !float.IsNaN(cz) &&
Math.Abs(cx) < 1000 && Math.Abs(cy) < 1000 && Math.Abs(cz) < 1000)
{
SortingCenter = new Vector3(cx, cy, cz);
SortingRadius = r;
break;
}
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}");
}
}
/// <summary>
/// A spherical collision volume from a Setup file.
/// </summary>
public class CollisionSphere
{
public Vector3 Center;
public float Radius;
}
/// <summary>
/// A cylindrical collision volume from a Setup file.
/// </summary>
public class CollisionCylinder
{
public Vector3 BottomCenter;
public float Radius;
public float Height;
}
}

View file

@ -0,0 +1,98 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Main integration point for the raycasting system.
/// Initializes the .dat file parsers, geometry loader, and targeting FSM.
///
/// Usage:
/// var raycast = new MainLogic();
/// raycast.Initialize(acFolderPath); // Call once at startup
///
/// // During combat:
/// bool blocked = raycast.IsTargetBlocked(host, targetId, attackType);
/// </summary>
public class MainLogic : IDisposable
{
private GeometryLoader _geoLoader;
private BlacklistManager _blacklist;
private TargetingFSM _targetingFSM;
private bool _disposed;
public GeometryLoader GeometryLoader => _geoLoader;
public BlacklistManager Blacklist => _blacklist;
public TargetingFSM TargetingFSM => _targetingFSM;
public bool IsInitialized => _geoLoader?.IsInitialized ?? false;
public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created";
public MainLogic()
{
_geoLoader = new GeometryLoader();
_blacklist = new BlacklistManager();
_targetingFSM = new TargetingFSM(_geoLoader, _blacklist);
}
/// <summary>
/// Initializes the raycasting system by loading portal.dat and cell.dat.
///
/// acFolderPath: Optional explicit path to AC installation folder.
/// If null, will search common installation paths automatically.
///
/// Returns true if initialization succeeded (both .dat files loaded).
/// </summary>
public bool Initialize(string? acFolderPath = null)
{
try
{
bool result = _geoLoader.Initialize(acFolderPath);
if (result)
{
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic initialized successfully");
}
else
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init failed: {_geoLoader.StatusMessage}");
return result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init error: {ex.Message}");
return false;
}
}
/// <summary>
/// Quick check: is a specific target blocked by geometry?
/// Call this from CombatManager before engaging a target.
/// </summary>
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, TargetingFSM.AttackType attackType)
{
if (!IsInitialized || _targetingFSM == null)
return false;
return _targetingFSM.IsTargetBlocked(host, targetId, attackType);
}
/// <summary>
/// Determines the attack type from the current combat mode and weapon name.
/// </summary>
public TargetingFSM.AttackType GetAttackType(int currentCombatMode, string wieldedWeaponName)
{
return _targetingFSM?.DetermineAttackType(currentCombatMode, wieldedWeaponName)
?? TargetingFSM.AttackType.Linear;
}
public void Dispose()
{
if (_disposed) return;
_geoLoader?.Dispose();
_blacklist?.ClearAll();
_disposed = true;
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic disposed");
}
}
}

View file

@ -0,0 +1,285 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Core raycasting engine for line-of-sight checks.
/// Tests linear (spell/bolt) and parabolic (bow/thrown) trajectories
/// against the loaded collision geometry.
///
/// NOTE: Uses custom Vector3 from this namespace, NOT System.Numerics.
/// </summary>
public static class RaycastEngine
{
/// <summary>
/// Gravity constant for parabolic trajectory calculations.
/// AC's gravity is approximately 9.81 m/s² but may need empirical tuning.
/// </summary>
private const float GRAVITY = 9.81f;
/// <summary>
/// Number of sample points along an arc trajectory for collision testing.
/// Higher = more accurate but slower. 10 is a good balance.
/// </summary>
private const int ARC_SAMPLE_COUNT = 10;
// Shoulder / height offsets used for multi-ray dungeon LOS checks.
// Covers the approximate silhouette of a standing player character.
private const float RayLateralOffset = 0.35f; // left/right shoulder spread (meters)
private const float RayVerticalOffset = 0.30f; // up/down spread (meters)
/// <summary>
/// Tests if a straight-line path (magic spells, crossbow bolts) is blocked
/// by any collision geometry.
///
/// In dungeon mode (multiRay=true) casts 5 rays — center plus left/right/up/down
/// offsets covering the player silhouette. Any single blocked ray returns blocked.
/// This catches thin corner geometry that a single center ray slips through.
///
/// Returns true if the path IS blocked (an obstacle exists between origin and target).
/// Returns false if the path is clear.
/// </summary>
public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target,
List<BoundingVolume> geometry,
bool multiRay = false)
{
if (geometry == null || geometry.Count == 0)
return false;
if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) ||
float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z))
return false;
if (multiRay)
{
// Build perpendicular axes for offset rays.
// Lateral = direction × world-up, then re-derive true up from lateral × direction.
Vector3 dir = (target - origin);
float len = dir.Length();
if (len < 1e-4f) return false;
dir = dir / len;
Vector3 worldUp = new Vector3(0, 0, 1);
Vector3 lateral = Vector3.Cross(dir, worldUp);
float latLen = lateral.Length();
if (latLen < 1e-4f) lateral = new Vector3(1, 0, 0); // dir is vertical — use arbitrary lateral
else lateral = lateral / latLen;
Vector3 up = Vector3.Cross(lateral, dir);
float upLen = up.Length();
if (upLen > 1e-4f) up = up / upLen;
Vector3 L = lateral * RayLateralOffset;
Vector3 U = up * RayVerticalOffset;
// 5 rays: center, left shoulder, right shoulder, slightly up, slightly down
if (IsSingleRayBlocked(origin, target, geometry)) return true;
if (IsSingleRayBlocked(origin - L, target - L, geometry)) return true;
if (IsSingleRayBlocked(origin + L, target + L, geometry)) return true;
if (IsSingleRayBlocked(origin + U, target + U, geometry)) return true;
if (IsSingleRayBlocked(origin - U, target - U, geometry)) return true;
return false;
}
return IsSingleRayBlocked(origin, target, geometry);
}
private static bool IsSingleRayBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry)
{
Vector3 delta = target - origin;
float distanceToTarget = delta.Length();
if (distanceToTarget < 1e-4f) return false;
Vector3 direction = delta / distanceToTarget;
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
float hitDist;
if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist))
{
// Ignore self-intersection at origin and hits within 0.3m of target
// (reduced from 1.0m — the old 1m zone was hiding corner walls next to mobs).
if (hitDist > 0.5f && hitDist < distanceToTarget - 0.3f)
return true;
}
}
return false;
}
/// <summary>
/// Tests if a parabolic arc path (bows, thrown weapons) is blocked by geometry.
///
/// This allows attacks to arc over low obstacles like walls and rocks.
/// The arc is sampled at discrete points and each segment is tested for
/// intersection with geometry.
///
/// Returns true if the arc IS blocked.
/// Returns false if the arc clears all obstacles.
/// </summary>
public static bool IsArcPathBlocked(Vector3 origin, Vector3 target, float initialVelocity,
List<BoundingVolume> geometry)
{
if (geometry == null || geometry.Count == 0)
return false;
if (initialVelocity <= 0)
return true; // Can't fire with no velocity
// Validate inputs
if (float.IsNaN(origin.X) || float.IsNaN(target.X))
return true;
Vector3 delta = target - origin;
float horizontalDist = delta.Length2D();
float verticalDist = delta.Z;
// Check maximum range: v² / g
float maxRange = (initialVelocity * initialVelocity) / GRAVITY;
if (horizontalDist > maxRange)
return true; // Out of range
if (horizontalDist < 0.1f)
return false; // Basically on top of target
// Calculate launch angle for the desired range
// Using the optimal angle that clears obstacles
// θ = 0.5 * arcsin(g * d / v²) for flat terrain
float sinArg = (GRAVITY * horizontalDist) / (initialVelocity * initialVelocity);
sinArg = Math.Min(sinArg, 1.0f); // Clamp for float precision
// Use the high arc (π/2 - θ) for better obstacle clearance
float launchAngle = (float)(0.5 * Math.Asin(sinArg));
if (launchAngle < 0.1f)
launchAngle = (float)(Math.PI / 4); // Default to 45° if calculation fails
float cosAngle = (float)Math.Cos(launchAngle);
float sinAngle = (float)Math.Sin(launchAngle);
// Calculate time of flight
float vHorizontal = initialVelocity * cosAngle;
float vVertical = initialVelocity * sinAngle;
if (vHorizontal < 0.01f)
return true; // Basically firing straight up
float totalTime = horizontalDist / vHorizontal;
// Horizontal direction (unit vector in XY plane)
float hdx = delta.X / horizontalDist;
float hdy = delta.Y / horizontalDist;
// Sample the arc at discrete points and test each segment
Vector3 prevPoint = origin;
for (int i = 1; i <= ARC_SAMPLE_COUNT; i++)
{
float t = (float)i / ARC_SAMPLE_COUNT;
float time = t * totalTime;
// Kinematic equations.
// Deep-audit finding #31 (2026-06-18): the old code computed
// the flat-range parabola (assumes origin.Z == target.Z) as
// `height`, then bolted on a SEPARATE `heightAdjust*(1-t)`
// blend for the actual elevation difference — double-applying
// the vertical offset. Neither the true ballistic curve nor a
// straight line resulted; at t=1 the arc's own height term
// (origin.Z + vVertical*totalTime - 0.5g*totalTime²) is
// exactly origin.Z (that's what makes totalTime =
// horizontalDist/vHorizontal the correct equal-height
// time-of-flight), so the sample landed at origin.Z instead
// of target.Z — biasing the LOS verdict for sloped shots.
//
// Fix: `parabolicSag` is that SAME flat-range height term
// relative to origin.Z — by construction it is exactly 0 at
// t=0 AND at t=1 (proven via the time-of-flight identity
// above), so adding it to a straight lerp(origin.Z, target.Z)
// never disturbs either endpoint, while still producing a
// real parabolic bump in between. This anchors t=1 at
// target.Z exactly (the final explicit segment below no
// longer has to patch just the endpoint).
float hDist = vHorizontal * time;
float parabolicSag = vVertical * time - 0.5f * GRAVITY * time * time;
Vector3 arcPoint = new Vector3(
origin.X + hdx * hDist,
origin.Y + hdy * hDist,
origin.Z + verticalDist * t + parabolicSag
);
// Test this segment for collisions
if (IsSegmentBlocked(prevPoint, arcPoint, geometry))
return true;
prevPoint = arcPoint;
}
// Test final segment to target
if (IsSegmentBlocked(prevPoint, target, geometry))
return true;
return false; // Arc clears all obstacles
}
/// <summary>
/// Tests if a line segment between two points intersects any geometry.
/// Used internally for arc sampling.
/// </summary>
private static bool IsSegmentBlocked(Vector3 start, Vector3 end, List<BoundingVolume> geometry)
{
Vector3 delta = end - start;
float dist = delta.Length();
if (dist < 0.01f) return false;
Vector3 dir = delta / dist;
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
float hitDist;
if (volume.RayIntersect(start, dir, dist, out hitDist))
{
if (hitDist > 0.05f && hitDist < dist - 0.05f)
return true;
}
}
return false;
}
/// <summary>
/// Quick distance-based pre-filter: checks if ANY geometry exists near the line
/// between origin and target. Used to skip the full raycast for wide-open areas.
/// Returns true if there is nearby geometry worth testing.
/// </summary>
public static bool HasNearbyGeometry(Vector3 origin, Vector3 target, List<BoundingVolume> geometry, float margin = 5.0f)
{
if (geometry == null || geometry.Count == 0)
return false;
// Compute a rough bounding box for the path
Vector3 pathMin = Vector3.Min(origin, target) - new Vector3(margin, margin, margin);
Vector3 pathMax = Vector3.Max(origin, target) + new Vector3(margin, margin, margin);
foreach (var vol in geometry)
{
if (vol.IsDoor) continue;
// Quick AABB overlap test
if (vol.Max.X >= pathMin.X && vol.Min.X <= pathMax.X &&
vol.Max.Y >= pathMin.Y && vol.Min.Y <= pathMax.Y &&
vol.Max.Z >= pathMin.Z && vol.Min.Z <= pathMax.Z)
{
return true;
}
}
return false;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,321 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Provides line-of-sight checking for the combat system.
/// Converts AC client coordinates to global meter space and
/// performs raycasting against loaded landblock geometry.
///
/// Coordinate system:
/// AC uses a landblock grid where each block is 192x192 meters.
/// Landcell ID format: 0xXXYYnnnn where XX=east-west block, YY=north-south block.
/// LocationX/Y are local offsets within the landblock (0-192 meters).
///
/// We convert everything to "global meters" for raycasting:
/// GlobalX = (XX * 192) + LocationX
/// GlobalY = (YY * 192) + LocationY
/// GlobalZ = LocationZ (altitude, 0 = sea level)
/// </summary>
public class TargetingFSM
{
private readonly GeometryLoader _geoLoader;
private readonly BlacklistManager _blacklist;
// Attack type determines which raycast to use
public enum AttackType
{
Linear, // Melee, peace, or arcs-disabled missiles
BowArc, // Bows — moderate arc, arrows go higher than you'd think
CrossbowArc, // Crossbows — fastest projectile, flattest arc
AtlatlArc, // Atlatls, thrown weapons, darts — similar arc to bows
MagicArc // War/Void magic Arc spells — same trajectory as missile weapons
}
// Lower velocity = higher arc. Defaults tuned against in-game trajectories;
// CombatManager overrides these from LegacyUiSettings each tick so the user
// can fine-tune per-weapon in the Misc advanced-settings tab.
public float BowArcVelocity { get; set; } = 25.0f;
public float CrossbowArcVelocity { get; set; } = 40.0f;
public float AtlatlArcVelocity { get; set; } = 22.0f;
public float MagicArcVelocity { get; set; } = 25.0f;
// If true, use arc checks for missile weapons. If false, treat all as linear.
public bool UseArcs { get; set; } = true;
// Max scan distance in meters. Only check LOS for targets within this range.
// Set from CombatManager based on MonsterRange + buffer.
public float MaxScanDistanceMeters { get; set; } = 120.0f;
public TargetingFSM(GeometryLoader geoLoader, BlacklistManager blacklist)
{
_geoLoader = geoLoader ?? throw new ArgumentNullException(nameof(geoLoader));
_blacklist = blacklist ?? throw new ArgumentNullException(nameof(blacklist));
}
/// <summary>
/// Checks if line-of-sight to a target is blocked by geometry.
///
/// Returns true if the target IS blocked (should skip this target).
/// Returns false if the target is clear to attack.
/// </summary>
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType)
{
if (!_geoLoader.IsInitialized)
return false;
try
{
Vector3 origin = GetPlayerPosition(host);
if (origin == Vector3.Zero)
return false;
Vector3 targetPos = GetObjectPosition(host, targetId);
if (targetPos == Vector3.Zero)
return false;
// Early-out: skip raycast if target is beyond scan distance
float dx = targetPos.X - origin.X;
float dy = targetPos.Y - origin.Y;
float flatDist = (float)Math.Sqrt(dx * dx + dy * dy);
if (flatDist > MaxScanDistanceMeters)
return false; // Too far to bother checking, let combat handle range
// Offset to chest height
origin.Z += 1.0f;
targetPos.Z += 1.0f;
uint landcell = GetPlayerLandcell(host);
uint cellPart = landcell & 0xFFFF;
bool isDungeon = cellPart >= 0x0100;
// Force linear checks indoors — arc trajectories hit ceilings
if (isDungeon)
attackType = AttackType.Linear;
var geometry = _geoLoader.GetLandblockGeometry(landcell);
if (geometry == null || geometry.Count == 0)
return false;
// Pre-filter: skip full ray test if no geometry near the path
float margin = Math.Min(flatDist * 0.3f, 15.0f);
margin = Math.Max(margin, 3.0f);
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
return false;
// In dungeons use multi-ray checks — 5 rays covering the player silhouette
// catch thin corner geometry that a single center ray slips through.
switch (attackType)
{
case AttackType.Linear:
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.BowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.CrossbowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, CrossbowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.AtlatlArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, AtlatlArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.MagicArc:
if (UseArcs && !isDungeon)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: false);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
default:
return false;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}");
return false;
}
}
/// <summary>
/// Finds the best unblocked target from a list of candidates.
/// Returns the target ID, or 0 if no clear target is found.
/// </summary>
public uint FindBestTarget(RynthCoreHost host, List<uint> candidateIds, AttackType attackType)
{
if (candidateIds == null || candidateIds.Count == 0)
return 0;
foreach (uint id in candidateIds)
{
try
{
// Skip blacklisted targets
if (_blacklist.IsBlacklisted((int)id))
continue;
// Skip blocked targets
if (IsTargetBlocked(host, id, attackType))
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Target 0x{id:X8} blocked by geometry, skipping");
continue;
}
return id; // Found a clear target
}
catch
{
continue;
}
}
return 0; // No clear targets
}
/// <summary>
/// Gets the player's position in global meter coordinates.
/// Uses RynthCoreHost.TryGetPlayerPose for landcell + local position.
/// </summary>
private Vector3 GetPlayerPosition(RynthCoreHost host)
{
try
{
if (!host.TryGetPlayerPose(out uint objCellId, out float localX, out float localY, out float localZ,
out _, out _, out _, out _))
return Vector3.Zero;
uint blockX = (objCellId >> 24) & 0xFF;
uint blockY = (objCellId >> 16) & 0xFF;
float globalX = blockX * 192.0f + localX;
float globalY = blockY * 192.0f + localY;
return new Vector3(globalX, globalY, localZ);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error getting player pos: {ex.Message}");
return Vector3.Zero;
}
}
/// <summary>
/// Gets an object's position in global meter coordinates.
/// Uses RynthCoreHost.TryGetObjectPosition for landcell + local position.
/// </summary>
private Vector3 GetObjectPosition(RynthCoreHost host, uint objectId)
{
try
{
if (!host.TryGetObjectPosition(objectId, out uint objCellId, out float localX, out float localY, out float localZ))
return Vector3.Zero;
uint blockX = (objCellId >> 24) & 0xFF;
uint blockY = (objCellId >> 16) & 0xFF;
float globalX = blockX * 192.0f + localX;
float globalY = blockY * 192.0f + localY;
return new Vector3(globalX, globalY, localZ);
}
catch
{
return Vector3.Zero;
}
}
/// <summary>
/// Gets the player's current Landcell value for geometry lookup.
/// </summary>
private uint GetPlayerLandcell(RynthCoreHost host)
{
try
{
if (host.TryGetPlayerPose(out uint objCellId, out _, out _, out _, out _, out _, out _, out _))
return objCellId;
return 0;
}
catch
{
return 0;
}
}
/// <summary>
/// Determines the attack type based on combat mode and wielded weapon name.
/// Magic mode ALWAYS returns Linear (spells travel straight).
/// Missile weapons each get their own arc when UseArcs is true: bow, crossbow,
/// or atlatl. Melee and peace modes are Linear.
///
/// Combat modes: 1=noncombat, 2=melee, 4=missile, 8=magic
/// </summary>
public AttackType DetermineAttackType(int currentCombatMode, string wieldedWeaponName)
{
try
{
// MAGIC MODE: Always linear — spells (bolts, streaks, arcs, rings)
// all use straight-line LOS in AC, regardless of equipped weapon
if (currentCombatMode == 8)
return AttackType.Linear;
// PEACE MODE: Default to linear
if (currentCombatMode == 1)
return AttackType.Linear;
// MELEE MODE: Linear (range check only, no projectile arc)
if (currentCombatMode == 2)
return AttackType.Linear;
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown
if (currentCombatMode == 4 && !string.IsNullOrEmpty(wieldedWeaponName))
{
string name = wieldedWeaponName.ToLower();
// Crossbows — flattest arc, high velocity
if (name.Contains("crossbow"))
return UseArcs ? AttackType.CrossbowArc : AttackType.Linear;
// Atlatls and thrown weapons arc more
if (name.Contains("atlatl") || name.Contains("thrown") || name.Contains("dart"))
return UseArcs ? AttackType.AtlatlArc : AttackType.Linear;
// Regular bows — fast, flat arc
if (name.Contains("bow"))
return UseArcs ? AttackType.BowArc : AttackType.Linear;
// Unknown missile weapon — treat as bow arc
return UseArcs ? AttackType.BowArc : AttackType.Linear;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error determining attack type: {ex.Message}");
}
return AttackType.Linear; // Default to linear
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,59 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Combat\SpellData.txt" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
</ItemGroup>
<!--
Historically this target auto-copied the published plugin DLL into the
RynthCore engine's bin\Plugins\ folder so a fresh engine build would pick
up the plugin without manual intervention. That behaviour conflicts with
the launcher's plugin-discovery model (users opt-in via "Add Plugin DLL"
in the launcher UI, persisted to %APPDATA%\RynthCore\engine.json).
Auto-copy removed intentionally — deploy plugin DLLs to their canonical
home (e.g. C:\Games\RynthSuite\RynthAi\) and add the path in the launcher.
-->
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,118 @@
using System;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Renders a filled highlight over impassable (too-steep) terrain triangles
/// using the engine's 3D line API. Each 24m cell is split into its two triangles;
/// only the steep halves are highlighted, matching how AC treats passability.
/// Iterates outward from the player so the nearest cells always render first.
/// </summary>
internal sealed class TerrainPassabilityOverlay
{
// Triangle 1 (SE): vertices (cx,cy),(cx+1,cy),(cx+1,cy+1)
// Triangle 2 (NW): vertices (cx,cy),(cx+1,cy+1),(cx,cy+1)
private const uint FillColor = 0x60FF2020; // semi-transparent red ARGB
private const float FillThick = 4.0f;
private const float HeightBias = 0.5f;
private const int RenderRadius = 4;
private const int FillSteps = 3; // strips per triangle; 81 cells×2tri×3=486 ≤ MaxLines(512)
private readonly RynthCoreHost _host;
private MainLogic? _raycast;
public TerrainPassabilityOverlay(RynthCoreHost host)
{
_host = host;
}
public void SetRaycast(MainLogic raycast) => _raycast = raycast;
private static float Lerp(float a, float b, float t) => a + (b - a) * t;
public void Render()
{
if (_raycast == null || !_host.HasNav3D)
return;
if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out _,
out _, out _, out _, out _))
return;
if ((cellId & 0xFFFF) >= 0x100) return; // indoor
if ((cellId >> 16) == 0) return; // portalspace
var geo = _raycast.GeometryLoader;
if (geo == null) return;
uint landblockKey = cellId >> 16;
byte[]? heights = geo.GetTerrainHeightGrid(landblockKey);
if (heights == null) return;
int playerCX = Math.Clamp((int)(px / 24f), 0, 7);
int playerCY = Math.Clamp((int)(py / 24f), 0, 7);
// Expand outward from player — nearest cells always submitted first
for (int r = 0; r <= RenderRadius; r++)
{
for (int dx = -r; dx <= r; dx++)
{
for (int dy = -r; dy <= r; dy++)
{
if (Math.Abs(dx) < r && Math.Abs(dy) < r) continue;
int cx = playerCX + dx;
int cy = playerCY + dy;
if (cx < 0 || cx > 7 || cy < 0 || cy > 7) continue;
geo.GetTerrainTrianglePassability(landblockKey, cx, cy,
out bool t1ok, out bool t2ok);
if (t1ok && t2ok) continue;
float x0 = cx * 24f, x1 = (cx + 1) * 24f;
float z0 = cy * 24f, z1 = (cy + 1) * 24f;
float h00 = geo.GetTerrainVertexHeight(landblockKey, cx, cy ) + HeightBias;
float h10 = geo.GetTerrainVertexHeight(landblockKey, cx + 1, cy ) + HeightBias;
float h01 = geo.GetTerrainVertexHeight(landblockKey, cx, cy + 1) + HeightBias;
float h11 = geo.GetTerrainVertexHeight(landblockKey, cx + 1, cy + 1) + HeightBias;
if (!t1ok)
{
// SE triangle: SW(x0,h00,z0) → SE(x1,h10,z0) → NE(x1,h11,z1)
// Horizontal strips at z-step t; left on hypotenuse (SW→NE), right on east edge (SE→NE)
for (int s = 0; s < FillSteps; s++)
{
float t = (s + 0.5f) / FillSteps;
float sz = z0 + t * 24f;
float lx = x0 + t * 24f;
float rx = x1;
float ly = Lerp(h00, h11, t); // plane height along SW→NE
float ry = Lerp(h10, h11, t); // plane height along SE→NE
_host.Nav3DAddLine(lx, ly, sz, rx, ry, sz, FillThick, FillColor);
}
}
if (!t2ok)
{
// NW triangle: SW(x0,h00,z0) → NE(x1,h11,z1) → NW(x0,h01,z1)
// Horizontal strips at z-step t; left on west edge (SW→NW), right on hypotenuse (SW→NE)
for (int s = 0; s < FillSteps; s++)
{
float t = (s + 0.5f) / FillSteps;
float sz = z0 + t * 24f;
float lx = x0;
float rx = x0 + t * 24f;
float ly = Lerp(h00, h01, t); // plane height along SW→NW
float ry = Lerp(h00, h11, t); // plane height along SW→NE
_host.Nav3DAddLine(lx, ly, sz, rx, ry, sz, FillThick, FillColor);
}
}
}
}
}
}
}

View file

@ -0,0 +1,63 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// UtilityBelt /ub command compatibility — thin shim that forwards to the
/// matching /ra handlers. Partial class of RynthAiPlugin.
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>
/// Handle a /ub command. Returns true if recognized and handled.
/// </summary>
internal bool HandleUbCommand(string fullCommand)
{
string[] parts = fullCommand.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return false;
string cmd = parts[1].ToLower();
// /ub jump[swzxc] [heading] [holdtime] — see Jumper.cs
if (cmd.StartsWith("jump", StringComparison.Ordinal))
{
HandleJumpCommand(cmd, parts);
return true;
}
// Most remaining /ub verbs (use / usep / uselp / useip / face / give /
// givep / combatstate / cast …) share semantics with the natively
// implemented /mt verbs, which talk to host primitives (UseObject /
// TurnToHeading / settings) — NOT to Mag-Tools or Decal. Translate the
// prefix and reuse that handler so the command works with no external
// plugin loaded. Verbs /mt doesn't know (mexec, ig, prepclick, …) fall
// through to HandleMtCommand returning false → "Unrecognized /ub".
int sp = fullCommand.IndexOf(' ');
// Verbs /mt doesn't implement but /ra does — route to the /ra dispatcher
// (VTank-meta migration). "/ub follow X" → "/ra follow X"; myquests → /ra
// quest-flag refresh.
if (sp > 0 && cmd is "follow" or "ig" or "mexec" or "myquests")
{
HandleRaCommand("/ra" + fullCommand.Substring(sp));
return true;
}
// /ub clearbugged is RynthAi's clearbusy (force-reset busy state) under a
// different name.
if (cmd == "clearbugged")
{
HandleRaCommand("/ra clearbusy");
return true;
}
if (sp > 0)
{
string translated = "/mt" + fullCommand.Substring(sp); // "/ub use X" → "/mt use X"
if (HandleMtCommand(translated))
return true;
}
return false;
}
}

View file

@ -0,0 +1,115 @@
using System;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.RynthChat;
internal sealed class ChatBuffer
{
private const int Capacity = 500;
private readonly ChatLine[] _ring = new ChatLine[Capacity];
private readonly object _lock = new();
private int _head; // next write index (mod Capacity)
private int _count; // total items stored (≤ Capacity)
private ulong _nextSeq = 1;
internal void Add(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return;
string channel = ChatClassifier.IsRynthOutput(text)
? ChatClassifier.Rynth
: ChatClassifier.ChannelFor(chatType);
string? sender = ChatClassifier.SenderFor(text, chatType);
string ts = DateTime.Now.ToString("HH:mm:ss");
var line = new ChatLine
{
Seq = Interlocked.Increment(ref _nextSeq) - 1,
Timestamp = ts,
Channel = channel,
Sender = sender,
Text = text,
};
lock (_lock)
{
_ring[_head % Capacity] = line;
_head = (_head + 1) % Capacity;
if (_count < Capacity) _count++;
}
}
// Returns JSON array of lines with Seq > sinceSeq, oldest-first.
internal string BuildJson(ulong sinceSeq)
{
ChatLine[] snapshot;
int count;
int head;
lock (_lock)
{
snapshot = (ChatLine[])_ring.Clone();
count = _count;
head = _head;
}
var sb = new StringBuilder(256);
sb.Append('[');
bool first = true;
// Iterate oldest→newest. Oldest entry is at (head - count + Capacity) % Capacity.
int start = (head - count + Capacity) % Capacity;
for (int i = 0; i < count; i++)
{
var line = snapshot[(start + i) % Capacity];
if (line == null || line.Seq <= sinceSeq) continue;
if (!first) sb.Append(',');
first = false;
sb.Append("{\"seq\":");
sb.Append(line.Seq);
sb.Append(",\"ts\":\"");
sb.Append(line.Timestamp);
sb.Append("\",\"chan\":\"");
AppendEscaped(sb, line.Channel);
sb.Append("\",\"sender\":");
if (line.Sender != null)
{
sb.Append('"');
AppendEscaped(sb, line.Sender);
sb.Append('"');
}
else
{
sb.Append("null");
}
sb.Append(",\"text\":\"");
AppendEscaped(sb, line.Text);
sb.Append("\"}");
}
sb.Append(']');
return sb.ToString();
}
private static void AppendEscaped(StringBuilder sb, string s)
{
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20)
sb.Append($"\\u{(int)c:X4}");
else
sb.Append(c);
break;
}
}
}
}

View file

@ -0,0 +1,84 @@
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthChat;
// ChatMessageType values from ACE.Entity.Enum.ChatMessageType (ACE binary is
// byte-identical to retail, so these are authoritative for retail acclient.exe too).
internal static class ChatClassifier
{
internal const string Chat = "Chat"; // Local/Tell/Allegiance/Fellow — all player-to-player
internal const string Channels = "Channels"; // General/Trade/LFG/Roleplay/Society/Admin — all 0x08/0x09
internal const string System = "System";
internal const string Combat = "Combat";
internal const string Rynth = "Rynth"; // Any RynthCore/RynthAi/RynthChat plugin output ("[Rynth…]")
internal const string Other = "Other";
internal static readonly string[] AllChannels =
{ Chat, Channels, System, Combat, Rynth, Other };
/// <summary>
/// True for output emitted by the Rynth stack itself — every Rynth plugin tags
/// its chat lines with a "[Rynth…]" prefix (e.g. "[RynthAi]", "[RynthChat]",
/// "[RynthAi Craft]"). These are routed to the dedicated Rynth tab regardless of
/// the chatType the plugin happened to write them with, so nothing gets scattered
/// across System/Other/Chat and lost.
/// </summary>
internal static bool IsRynthOutput(string text) =>
text.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase);
// ── Channel classification ─────────────────────────────────────────────
internal static string ChannelFor(int chatType) => (uint)chatType switch
{
0x02 or 0x03 or 0x04 or 0x0A or 0x0B
or 0x0C or 0x12 or 0x13 => Chat,
0x08 or 0x09 => Channels,
0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18
or 0x19 or 0x1F => System,
0x06 or 0x07 or 0x11 or 0x15 or 0x16 => Combat,
_ => Other,
};
internal static uint ColorFor(string channel) => channel switch
{
Chat => 0xFFE0E0E0,
Channels => 0xFF7AB8F5,
System => 0xFF8CA6BF,
Combat => 0xFFD93333,
_ => 0xFFAAAAAA,
};
// ── Sender extraction ──────────────────────────────────────────────────
private static readonly Regex _sayRe = new(@"^(.+?) says, """, RegexOptions.Compiled);
private static readonly Regex _tellInRe = new(@"^(.+?) tells you, """, RegexOptions.Compiled);
private static readonly Regex _tellOutRe = new(@"^You tell (.+?), """, RegexOptions.Compiled);
private static readonly Regex _allegianceRe = new(@"^(.+?) says on the Allegiance channel, """, RegexOptions.Compiled);
private static readonly Regex _fellowRe = new(@"^(.+?) says on the Fellowship channel, """, RegexOptions.Compiled);
private static readonly Regex _chanSenderRe = new(@"^(.+?) says on the .+? channel, """, RegexOptions.Compiled);
internal static string? SenderFor(string text, int chatType) => (uint)chatType switch
{
0x02 => Match(_sayRe, text),
0x03 => Match(_tellInRe, text),
0x04 => TellOutSender(text),
0x12 => Match(_allegianceRe, text) ?? Match(_sayRe, text),
0x13 => Match(_fellowRe, text) ?? Match(_sayRe, text),
0x0A => Match(_sayRe, text),
0x08 => Match(_chanSenderRe, text),
_ => null,
};
private static string? Match(Regex re, string text)
{
var m = re.Match(text);
return m.Success ? m.Groups[1].Value : null;
}
private static string? TellOutSender(string text)
{
var m = _tellOutRe.Match(text);
return m.Success ? $"→{m.Groups[1].Value}" : null;
}
}

View file

@ -0,0 +1,10 @@
namespace RynthCore.Plugin.RynthChat;
internal sealed class ChatLine
{
internal ulong Seq { get; init; }
internal string Timestamp { get; init; } = "";
internal string Channel { get; init; } = "";
internal string? Sender { get; init; }
internal string Text { get; init; } = "";
}

View file

@ -0,0 +1,82 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthChat;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthChatPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthChatPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthChatPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// ── Chat scrollback bridge for the engine-side RynthChatPanel ──────────
// Panel polls RynthChatGetScrollbackJson (~10 Hz) to receive new lines.
// Panel calls RynthChatSendLine to submit a message via InvokeChatParser.
// Buffer swap pattern from RynthAi: alloc-new → swap → free-old keeps the
// polling thread safe without a lock.
private static IntPtr _scrollbackPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthChatGetScrollbackJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetScrollbackJson(ulong sinceSeq)
{
try
{
string json = Runtime.Plugin?.BuildScrollbackJson(sinceSeq) ?? "[]";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _scrollbackPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLine(IntPtr ansiText)
{
try
{
if (ansiText == IntPtr.Zero) return;
string? text = Marshal.PtrToStringAnsi(ansiText);
if (string.IsNullOrEmpty(text)) return;
Runtime.Plugin?.SendLine(text);
}
catch { }
}
}

View file

@ -0,0 +1,50 @@
using System;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthChat;
public sealed class RynthChatPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthChat");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
private readonly ChatBuffer _buffer = new();
public override int Initialize()
{
Host.Log("[RynthChat] Plugin initialized.");
return 0;
}
public override void OnLoginComplete()
{
Host.Log("[RynthChat] Login complete.");
}
public override void OnLogout()
{
Host.Log("[RynthChat] Logout.");
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
_buffer.Add(text, chatType);
}
public override void OnChatBarEnter(string? text, ref int eat)
{
// Phase 5: intercept + own outgoing chat.
}
internal string BuildScrollbackJson(ulong sinceSeq) => _buffer.BuildJson(sinceSeq);
// Called on the game thread from the engine's deferred chat dispatch
// (Win32Backend posts WM_RYNTHCORE_CHAT so this runs on a fresh, non-reentrant
// message dispatch rather than inline inside the Enter keystroke handler).
internal void SendLine(string text)
{
if (!Host.HasInvokeChatParser || string.IsNullOrWhiteSpace(text)) return;
Host.InvokeChatParser(text);
}
}

View file

@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthChat</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthChat</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting; // DatDatabase lives in the RynthCore.TerrainData assembly under this namespace
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Converts an INDOOR (dungeon) object's CELL-LOCAL origin into LANDBLOCK-RELATIVE
/// coordinates by reading the object's EnvCell transform (position + rotation)
/// from the client's cell.dat. The engine builds its view matrix in landblock
/// space even indoors (GameMatrixCapture reads AC's pre-composed viewer pose), so
/// once a mob's position is landblock-relative the existing WorldToScreen pipeline
/// projects it correctly inside dungeons.
///
/// Uses the shared TerrainData <see cref="DatDatabase"/> (the same parser
/// RynthVision uses) — this does NOT pull in RynthAi. Outdoor cells (low word
/// &lt; 0x100) pass through unchanged. cell.dat is opened lazily on first indoor
/// use, from the running client's own folder, and per-cell transforms are cached.
/// </summary>
internal sealed class EnvCellTransforms : IDisposable
{
private DatDatabase? _cellDat;
private bool _tried;
private bool _ready;
private readonly Dictionary<uint, Cell> _cache = new();
private struct Cell
{
public bool Ok;
public float Px, Py, Pz; // cell position within the landblock
public float Rw, Rx, Ry, Rz; // cell rotation quaternion
}
public bool Ready => _ready;
public string Status { get; private set; } = "uninitialized";
/// <summary>
/// If <paramref name="cellId"/> is indoor, rewrites (e,n,u) from cell-local to
/// landblock-relative and returns true; returns false if the transform can't be
/// resolved (no cell.dat / no record). Outdoor cells return true unchanged.
/// </summary>
public bool ToLandblockRelative(uint cellId, ref float e, ref float n, ref float u)
{
if ((cellId & 0xFFFF) < 0x100)
return true; // outdoor: origin is already landblock-local
if (!EnsureOpen())
return false;
if (!TryGetCell(cellId, out Cell c) || !c.Ok)
return false;
// world_landblock = rotate(local, quat) + cellPos (matches DungeonLOS.TransformVertex)
float lx = e, ly = n, lz = u;
float cx = c.Ry * lz - c.Rz * ly;
float cy = c.Rz * lx - c.Rx * lz;
float cz = c.Rx * ly - c.Ry * lx;
float cx2 = c.Ry * cz - c.Rz * cy;
float cy2 = c.Rz * cx - c.Rx * cz;
float cz2 = c.Rx * cy - c.Ry * cx;
e = lx + 2f * (c.Rw * cx + cx2) + c.Px;
n = ly + 2f * (c.Rw * cy + cy2) + c.Py;
u = lz + 2f * (c.Rw * cz + cz2) + c.Pz;
return true;
}
private bool EnsureOpen()
{
if (_tried) return _ready;
_tried = true;
// The running client's own folder may hold cell.dat with an exclusive lock
// (AC opened it first, before our share-hook, when launched by another tool).
// cell.dat is identical across installs, so fall back to any other AC copy
// whose handle isn't locked. Surface the exact per-path failure for diag.
var tried = new List<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string folder in CandidateFolders())
{
try
{
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
string? path = FindDat(folder, "client_cell_1.dat", "cell.dat");
if (path == null) { tried.Add($"{folder}=no-dat"); continue; }
if (!seen.Add(Path.GetFullPath(path))) continue; // don't retry the same file
var db = new DatDatabase();
if (db.Open(path))
{
_cellDat = db;
_ready = true;
Status = $"ready: {path}";
return true;
}
string err = db.DiagLog.Count > 0 ? db.DiagLog[db.DiagLog.Count - 1] : "open=false";
tried.Add($"{path} -> {err}");
try { db.Dispose(); } catch { }
}
catch (Exception ex) { tried.Add($"{folder} -> {ex.Message}"); }
}
Status = "cell.dat open failed; tried: " + (tried.Count > 0 ? string.Join(" | ", tried) : "(no candidates)");
return false;
}
// cell.dat search locations, in priority order: the running client's folder
// first, then well-known AC installs. Identical data in each, so any that
// opens works.
private static IEnumerable<string> CandidateFolders()
{
string? exe = Environment.ProcessPath;
string? exeDir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
if (!string.IsNullOrEmpty(exeDir)) yield return exeDir!;
yield return @"C:\Games\RynthCore\AcClient";
yield return @"C:\Turbine\Asheron's Call";
yield return @"C:\Games\Asheron's Call";
yield return @"C:\Program Files (x86)\Turbine\Asheron's Call";
yield return @"C:\Program Files\Turbine\Asheron's Call";
}
private bool TryGetCell(uint cellId, out Cell c)
{
if (_cache.TryGetValue(cellId, out c))
return true;
c = default;
try
{
byte[]? data = _cellDat!.GetFileData(cellId);
if (data != null && data.Length >= 0x30)
ParseEnvCell(data, ref c);
}
catch { c.Ok = false; }
_cache[cellId] = c; // cache failures too (avoid re-reading missing cells)
return true;
}
// EnvCell header (matches RynthAi DungeonLOS.ParseEnvCellHeader exactly):
// u32 id, u32 flags, u32 cellId, u8 numSurfaces, u8 numPortals,
// u16 numVisibleCells, [numSurfaces × u16], u16 envId, u16 cellStruct,
// f32 PosX, PosY, PosZ, RotW, RotX, RotY, RotZ
private static void ParseEnvCell(byte[] data, ref Cell c)
{
try
{
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32();
byte numSurfaces = r.ReadByte();
r.ReadByte(); // numPortals
r.ReadUInt16(); // numVisibleCells
ms.Seek(numSurfaces * 2, SeekOrigin.Current);
r.ReadUInt16(); // envId
r.ReadUInt16(); // cellStruct
c.Px = r.ReadSingle(); c.Py = r.ReadSingle(); c.Pz = r.ReadSingle();
c.Rw = r.ReadSingle(); c.Rx = r.ReadSingle(); c.Ry = r.ReadSingle(); c.Rz = r.ReadSingle();
c.Ok = true;
}
catch { c.Ok = false; }
}
private static string? FindDat(string folder, params string[] names)
{
foreach (string nm in names)
{
string p = Path.Combine(folder, nm);
if (File.Exists(p)) return p;
}
return null;
}
public void Dispose()
{
try { _cellDat?.Dispose(); } catch { }
_cellDat = null;
_ready = false;
}
}

View file

@ -0,0 +1,419 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Owns the live combat-juice effects and renders them every tick through the
/// engine's Nav3D world-space API. Floating numbers are drawn as billboarded
/// vector-digit glyphs (quads built from <see cref="RynthCoreHost.Nav3DAddTriangle"/>);
/// kill bursts are expanding rings.
///
/// Coordinate frames (see GameMatrixCapture / RadarRingOverlay):
/// • Object/player positions are AC convention: x=EW(east), y=NS(north), z=height(up),
/// local to that object's LANDBLOCK (0–192), outdoors only.
/// • Nav3D and WorldToScreen want a Y-up player-landblock-local frame: (east, up, north).
/// • A target in a different landblock than the player is shifted by
/// (Δlandblock × 192) per axis before projecting — mirroring the engine's own
/// camera re-anchor in GameMatrixCapture.
/// </summary>
internal sealed class JuiceEffects
{
public enum Kind { MobDamage, Heal, PlayerDamage }
private sealed class Effect
{
public bool IsBurst;
public uint CellId;
public float E0, N0, U0; // anchor in the effect's own landblock-local frame (AC: E,N,U)
public string Text = "";
public uint Color;
public bool Crit;
public Kind Kind;
public long BirthMs;
public float Life; // seconds
}
private readonly List<Effect> _fx = new();
private readonly object _lock = new();
private EnvCellTransforms? _cells;
private const int MaxEffects = 48;
private const float CritScale = 1.5f;
/// <summary>Wires the dungeon EnvCell transform reader (enables indoor numbers).</summary>
public void SetCells(EnvCellTransforms cells) => _cells = cells;
// Diagnostics (read by /juice diag): why Render last bailed + what it emitted.
public string LastRenderStatus { get; private set; } = "(not ticked yet)";
public int LastDrawnEffects { get; private set; }
public int LastTriangles { get; private set; }
private int _frameDrawn, _frameTris;
// ── Spawning (called from event handlers) ────────────────────────────────
public void SpawnDamage(uint cellId, float e, float n, float u, int amount, bool crit)
=> Add(cellId, e, n, u, FormatAmount(amount, crit), crit ? Gold : DamageColor(amount), crit, Kind.MobDamage);
public void SpawnHeal(uint cellId, float e, float n, float u, int amount)
=> Add(cellId, e, n, u, "+" + amount.ToString(), Green, false, Kind.Heal);
public void SpawnPlayerDamage(uint cellId, float e, float n, float u, int amount, bool crit)
=> Add(cellId, e, n, u, FormatAmount(amount, crit), crit ? Gold : PlayerRed, crit, Kind.PlayerDamage);
public void SpawnKillBurst(uint cellId, float e, float n, float u, bool crit, long nowMs)
{
if (!Resolve(cellId, ref e, ref n, ref u)) return;
lock (_lock)
{
TrimLocked();
_fx.Add(new Effect
{
IsBurst = true,
CellId = cellId, E0 = e, N0 = n, U0 = u,
Color = 0xFF60FFFF, // bright cyan — max visibility for the "is it working?" test
BirthMs = nowMs,
Life = 1.6f,
});
}
}
/// <summary>Upgrade the most recent damage number to a crit (handles crit chat
/// arriving just after the health packet). Returns true if one was upgraded.</summary>
public bool UpgradeRecentToCrit(long nowMs, int windowMs)
{
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
if (f.IsBurst || f.Kind == Kind.Heal || f.Crit) continue;
if (nowMs - f.BirthMs > windowMs) break; // list is append-ordered; older beyond window
f.Crit = true;
f.Color = Gold;
f.Text = EnsureBang(f.Text);
f.Life = MathF.Max(f.Life, 1.7f);
return true;
}
}
return false;
}
/// <summary>Overwrite the most recent matching damage number with the exact
/// amount parsed from the combat log (the health-packet anchor stays). Returns
/// true if one was updated within the window.</summary>
public bool ApplyExactToRecent(long nowMs, int windowMs, Kind kind, int amount, bool crit)
{
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
if (nowMs - f.BirthMs > windowMs) break; // append-ordered → all earlier are older
if (f.IsBurst || f.Kind != kind) continue;
f.Crit = f.Crit || crit;
f.Text = FormatAmount(amount, f.Crit);
f.Color = f.Crit ? Gold : (kind == Kind.PlayerDamage ? PlayerRed : DamageColor(amount));
if (f.Crit) f.Life = MathF.Max(f.Life, 1.7f);
return true;
}
}
return false;
}
public void Clear() { lock (_lock) _fx.Clear(); }
public int Count { get { lock (_lock) return _fx.Count; } }
private void Add(uint cellId, float e, float n, float u, string text, uint color, bool crit, Kind kind)
{
if (string.IsNullOrEmpty(text)) return;
if (!Resolve(cellId, ref e, ref n, ref u)) return; // indoor w/o cell transform → skip
lock (_lock)
{
TrimLocked();
_fx.Add(new Effect
{
CellId = cellId, E0 = e, N0 = n, U0 = u,
Text = text, Color = color, Crit = crit, Kind = kind,
BirthMs = Environment.TickCount64,
Life = crit ? 1.7f : (kind == Kind.Heal ? 1.15f : 1.35f),
});
}
}
private void TrimLocked()
{
// Drop the oldest non-burst effect if we're at the cap (keep bursts; they're brief).
while (_fx.Count >= MaxEffects)
{
int idx = _fx.FindIndex(f => !f.IsBurst);
_fx.RemoveAt(idx >= 0 ? idx : 0);
}
}
// ── Rendering (called from OnTick) ───────────────────────────────────────
public void Render(RynthCoreHost host, JuiceSettings cfg, long nowMs)
{
if (!host.HasNav3D || !host.HasNav3DTriangle)
{ LastRenderStatus = $"no-nav3d (nav={host.HasNav3D} tri={host.HasNav3DTriangle})"; return; }
if (!host.TryGetPlayerPose(out uint pCell, out float pE, out float pN, out float pU,
out _, out _, out _, out _))
{ LastRenderStatus = "no-pose"; return; }
if ((pCell >> 16) == 0)
{ LastRenderStatus = "portalspace"; return; }
// Indoors, convert the player's cell-local pose to landblock-relative so
// distance math agrees with the (already landblock-relative) anchors.
if (!Resolve(pCell, ref pE, ref pN, ref pU))
{ LastRenderStatus = "player-resolve-fail (indoor cell.dat unavailable?)"; return; }
uint playerLb = pCell >> 16;
_frameDrawn = 0; _frameTris = 0;
int culFar = 0, culDist = 0;
lock (_lock)
{
for (int i = _fx.Count - 1; i >= 0; i--)
{
var f = _fx[i];
float age = (nowMs - f.BirthMs) / 1000f;
if (age >= f.Life) { _fx.RemoveAt(i); continue; }
if (f.CellId >> 16 == 0) { _fx.RemoveAt(i); continue; }
// Shift the effect's own-landblock anchor into the player's frame.
int dXb = (int)(((f.CellId >> 16 >> 8) & 0xFF)) - (int)((playerLb >> 8) & 0xFF);
int dYb = (int)(((f.CellId >> 16) & 0xFF)) - (int)(playerLb & 0xFF);
if (Math.Abs(dXb) > 3 || Math.Abs(dYb) > 3) { culFar++; continue; } // too far / region junk
float aE = f.E0 + dXb * 192f;
float aN = f.N0 + dYb * 192f;
// Distance cull (horizontal).
float dE = aE - pE, dN = aN - pN;
if (dE * dE + dN * dN > cfg.MaxDistance * cfg.MaxDistance) { culDist++; continue; }
if (f.IsBurst) { RenderBurst(host, f, aE, aN, age); _frameDrawn++; }
else RenderNumber(host, cfg, f, aE, aN, age); // self-counts _frameDrawn on success
}
}
LastDrawnEffects = _frameDrawn;
LastTriangles = _frameTris;
LastRenderStatus = $"ok fx={_fx.Count} drawn={_frameDrawn} tris={_frameTris} culFar={culFar} culDist={culDist}";
}
private static void RenderBurst(RynthCoreHost host, Effect f, float aE, float aN, float age)
{
float t = age / f.Life; // 0→1
float alpha = 1f - t;
uint col = WithAlpha(f.Color, alpha);
float baseU = f.U0 + 0.3f;
// Big expanding ground ring.
float groundR = 0.6f + 8f * t;
host.Nav3DAddRingEx(aE, baseU, aN, groundR, 0.6f, 0.5f, col);
// A tall bright PILLAR of stacked rings (~10 m), so a kill is unmistakable
// even if the subtle stuff isn't landing yet. Tapers toward the top.
const int rings = 11;
for (int i = 0; i < rings; i++)
{
float h = baseU + i * 1.0f;
float pr = 2.0f * (1f - i / (float)rings) + 0.4f;
host.Nav3DAddRingEx(aE, h, aN, pr, 0.35f, 0.3f, col);
}
}
private void RenderNumber(RynthCoreHost host, JuiceSettings cfg, Effect f, float aE, float aN, float age)
{
// Animation: rise in world-up, pop-scale early, fade late.
float rise = 1.15f * age;
float aU = f.U0 + cfg.HeightOffset + rise;
float pop = 1f + (f.Crit ? 0.6f : 0.35f) * MathF.Max(0f, 1f - age / (f.Crit ? 0.14f : 0.10f));
float kindScale = f.Kind == Kind.PlayerDamage ? 1.15f : 1f;
float critScale = f.Crit ? CritScale : 1f;
float alpha = 1f;
float fadeStart = 0.55f * f.Life;
if (age > fadeStart) alpha = MathF.Max(0f, 1f - (age - fadeStart) / (f.Life - fadeStart));
alpha *= MathF.Min(1f, age / 0.06f); // quick fade-in
uint col = WithAlpha(f.Color, alpha);
// Size, then draw via the shared glyph routine.
float heightPx = 22f * cfg.Scale * pop * kindScale * critScale;
DrawGlyphs(host, aE, aU, aN, f.Text, heightPx, col);
}
/// <summary>Live monster-health readout: a "NN" percentage floating over each
/// actively-damaged mob, green→red by ratio. Persistent (re-drawn every tick so
/// it tracks the mob and updates as it's hit), unlike the transient numbers.</summary>
public void RenderMobHealth(RynthCoreHost host, JuiceSettings cfg, List<MobHp> mobs)
{
if (mobs.Count == 0 || !host.HasNav3D || !host.HasNav3DTriangle) return;
if (!host.TryGetPlayerPose(out uint pCell, out float pE, out float pN, out float pU, out _, out _, out _, out _)) return;
if ((pCell >> 16) == 0) return;
if (!Resolve(pCell, ref pE, ref pN, ref pU)) return;
uint playerLb = pCell >> 16;
foreach (MobHp m in mobs)
{
if ((m.CellId >> 16) == 0) continue;
int dXb = (int)(((m.CellId >> 16 >> 8) & 0xFF)) - (int)((playerLb >> 8) & 0xFF);
int dYb = (int)(((m.CellId >> 16) & 0xFF)) - (int)(playerLb & 0xFF);
if (Math.Abs(dXb) > 3 || Math.Abs(dYb) > 3) continue;
float aE = m.E0 + dXb * 192f;
float aN = m.N0 + dYb * 192f;
float dE = aE - pE, dN = aN - pN;
if (dE * dE + dN * dN > cfg.MaxDistance * cfg.MaxDistance) continue;
int pct = (int)MathF.Round(Math.Clamp(m.Ratio, 0f, 1f) * 100f);
float aU = m.U0 + cfg.HeightOffset + 0.9f; // just above the damage-number lane
DrawGlyphs(host, aE, aU, aN, pct.ToString(), 15f * cfg.Scale, HealthColor(m.Ratio));
}
}
/// <summary>Billboarded vector-glyph text at a world anchor — shared by the
/// damage numbers and the live monster-health %. False if it couldn't project.</summary>
private bool DrawGlyphs(RynthCoreHost host, float aE, float aU, float aN, string text, float heightPx, uint col)
{
if (!ComputeBillboard(host, aE, aU, aN, out Vector3 uVec, out Vector3 vVec, out _, out _))
return false;
_frameDrawn++;
float cell = heightPx / VectorFont.GlyphHeight; // px per grid unit
float halfW = MathF.Max(1.0f, cell * 0.16f); // stroke half-thickness, px
float startGridX = -VectorFont.MeasureWidth(text) / 2f;
for (int ci = 0; ci < text.Length; ci++)
{
var strokes = VectorFont.Strokes(text[ci]);
float charX = startGridX + ci * VectorFont.Advance;
foreach (var s in strokes)
{
var p1 = new Vector2((charX + s.X) * cell, (s.Y - VectorFont.GlyphHeight / 2f) * cell);
var p2 = new Vector2((charX + s.Z) * cell, (s.W - VectorFont.GlyphHeight / 2f) * cell);
EmitStrokeQuad(host, aE, aU, aN, uVec, vVec, p1, p2, halfW, col);
_frameTris += 2;
}
}
return true;
}
public readonly record struct MobHp(uint CellId, float E0, float N0, float U0, float Ratio);
private static uint HealthColor(float ratio)
{
if (ratio > 0.6f) return 0xFF40FF40; // green
if (ratio > 0.3f) return 0xFFFFF040; // yellow
if (ratio > 0.12f) return 0xFFFFA030; // orange
return 0xFFFF3030; // red
}
/// <summary>Builds one rounded-cap stroke as two world-space triangles.</summary>
private static void EmitStrokeQuad(RynthCoreHost host, float aE, float aU, float aN,
Vector3 u, Vector3 v, Vector2 p1, Vector2 p2, float halfW, uint col)
{
Vector2 d = p2 - p1;
float len = d.Length();
if (len < 0.0001f) return;
d /= len;
Vector2 perp = new(-d.Y, d.X);
Vector2 ext = d * halfW; // extend ends so segments overlap at joints
perp *= halfW;
Vector2 c0 = p1 - ext + perp;
Vector2 c1 = p2 + ext + perp;
Vector2 c2 = p2 + ext - perp;
Vector2 c3 = p1 - ext - perp;
// px-offset → world (Nav3D frame x=E, y=U, z=N)
(float, float, float) W(Vector2 px) =>
(aE + px.X * u.X + px.Y * v.X,
aU + px.X * u.Y + px.Y * v.Y,
aN + px.X * u.Z + px.Y * v.Z);
var (w0e, w0u, w0n) = W(c0);
var (w1e, w1u, w1n) = W(c1);
var (w2e, w2u, w2n) = W(c2);
var (w3e, w3u, w3n) = W(c3);
host.Nav3DAddTriangle(w0e, w0u, w0n, w1e, w1u, w1n, w2e, w2u, w2n, col);
host.Nav3DAddTriangle(w0e, w0u, w0n, w2e, w2u, w2n, w3e, w3u, w3n, col);
}
/// <summary>
/// Finite-difference Jacobian of WorldToScreen at the anchor, then its
/// 2×3 pseudo-inverse, giving world vectors u,v that move the projection by
/// exactly +1px in screen x and y respectively. Constant on-screen size +
/// automatic camera-facing billboard, with no engine-side camera basis.
/// </summary>
private static bool ComputeBillboard(RynthCoreHost host, float aE, float aU, float aN,
out Vector3 u, out Vector3 v, out float sx, out float sy)
{
u = default; v = default; sx = sy = 0f;
if (!host.HasWorldToScreen) return false;
const float h = 0.1f;
if (!host.WorldToScreen(aE, aU, aN, out float s0x, out float s0y)) return false;
if (!host.WorldToScreen(aE + h, aU, aN, out float eX, out float eY)) return false;
if (!host.WorldToScreen(aE, aU + h, aN, out float uX, out float uY)) return false;
if (!host.WorldToScreen(aE, aU, aN + h, out float nX, out float nY)) return false;
sx = s0x; sy = s0y;
// Jacobian columns (screen px / metre) for the E, U, N axes.
float jEx = (eX - s0x) / h, jEy = (eY - s0y) / h;
float jUx = (uX - s0x) / h, jUy = (uY - s0y) / h;
float jNx = (nX - s0x) / h, jNy = (nY - s0y) / h;
// J Jᵀ (2×2, symmetric) and its inverse.
float a = jEx * jEx + jUx * jUx + jNx * jNx;
float b = jEx * jEy + jUx * jUy + jNx * jNy;
float dd = jEy * jEy + jUy * jUy + jNy * jNy;
float det = a * dd - b * b;
if (MathF.Abs(det) < 1e-7f) return false;
float i00 = dd / det, i01 = -b / det, i11 = a / det;
// u = Jᵀ·(i00,i01) (screen +x); v = Jᵀ·(i01,i11) (screen +y)
u = new Vector3(jEx * i00 + jEy * i01, jUx * i00 + jUy * i01, jNx * i00 + jNy * i01);
v = new Vector3(jEx * i01 + jEy * i11, jUx * i01 + jUy * i11, jNx * i01 + jNy * i11);
return true;
}
// ── Helpers ──────────────────────────────────────────────────────────────
// Anchor coords pass through unchanged. The diag PROVED the indoor camera/view
// matrix is CELL-LOCAL (the player's own raw cell-local pos projects to screen
// centre @799/1598), so RAW object coords project correctly for objects in the
// player's cell — the EnvCell→landblock transform actually moved them OFF
// (projXform was wrong, projRaw was right). Outdoor coords are landblock-local
// and the per-landblock shift in Render handles cross-landblock. Indoor
// cross-cell mobs (a different EnvCell than the player) land far away in raw
// coords and get distance-culled rather than mis-drawn — acceptable for v1.
private bool Resolve(uint cellId, ref float e, ref float n, ref float u) => true;
private const uint Gold = 0xFFFFD700;
private const uint Green = 0xFF50FF50;
private const uint PlayerRed = 0xFFFF2828;
private const uint BurstOrange = 0xFFFF8C20;
private static uint DamageColor(int amt)
{
if (amt < 25) return 0xFFFFFFFF; // white
if (amt < 60) return 0xFFFFF080; // pale yellow
if (amt < 120) return 0xFFFFA030; // orange
return 0xFFFF3828; // red
}
private static uint WithAlpha(uint argb, float a)
{
uint aa = (uint)Math.Clamp(a * 255f, 0f, 255f);
return (argb & 0x00FFFFFF) | (aa << 24);
}
private static string FormatAmount(int amount, bool crit) =>
crit ? amount.ToString() + "!" : amount.ToString();
private static string EnsureBang(string s) =>
s.EndsWith("!", StringComparison.Ordinal) ? s : s + "!";
}

View file

@ -0,0 +1,85 @@
using System;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// RynthJuice tunables, persisted as a tiny key=value file at
/// %APPDATA%\RynthCore\rynthjuice.cfg. Plain text (no JSON serializer) to stay
/// trivially NativeAOT-safe and hand-editable.
/// </summary>
internal sealed class JuiceSettings
{
public bool Enabled = true;
public bool ShowHeals = true; // green "+N" when a target's health rises
public bool ShowPlayerDamage = true; // red numbers over your own character when hit
public float Scale = 1.0f; // global size multiplier for numbers
public float HeightOffset = 1.8f; // metres above the target origin to anchor numbers
public float MaxDistance = 55f; // metres; skip numbers for targets farther than this
public int MinDamage = 1; // ignore deltas below this (filters regen ticks)
private string _path = "";
public void Load()
{
try
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
_path = Path.Combine(dir, "rynthjuice.cfg");
if (!File.Exists(_path))
return;
foreach (string raw in File.ReadAllLines(_path))
{
string line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line.Substring(0, eq).Trim().ToLowerInvariant();
string val = line.Substring(eq + 1).Trim();
Apply(key, val);
}
}
catch { /* defaults stand */ }
}
public void Save()
{
try
{
if (string.IsNullOrEmpty(_path))
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
Directory.CreateDirectory(dir);
_path = Path.Combine(dir, "rynthjuice.cfg");
}
var ic = CultureInfo.InvariantCulture;
File.WriteAllText(_path,
"# RynthCore RynthJuice settings\n" +
$"enabled={(Enabled ? 1 : 0)}\n" +
$"heals={(ShowHeals ? 1 : 0)}\n" +
$"playerdamage={(ShowPlayerDamage ? 1 : 0)}\n" +
$"scale={Scale.ToString("0.##", ic)}\n" +
$"height={HeightOffset.ToString("0.##", ic)}\n" +
$"maxdist={MaxDistance.ToString("0.##", ic)}\n" +
$"mindamage={MinDamage}\n");
}
catch { /* non-fatal */ }
}
private void Apply(string key, string val)
{
var ic = CultureInfo.InvariantCulture;
switch (key)
{
case "enabled": Enabled = val is "1" or "true"; break;
case "heals": ShowHeals = val is "1" or "true"; break;
case "playerdamage": ShowPlayerDamage = val is "1" or "true"; break;
case "scale": if (float.TryParse(val, NumberStyles.Float, ic, out var s)) Scale = Math.Clamp(s, 0.3f, 4f); break;
case "height": if (float.TryParse(val, NumberStyles.Float, ic, out var h)) HeightOffset = Math.Clamp(h, 0f, 8f); break;
case "maxdist": if (float.TryParse(val, NumberStyles.Float, ic, out var m)) MaxDistance = Math.Clamp(m, 5f, 200f); break;
case "mindamage": if (int.TryParse(val, NumberStyles.Integer, ic, out var d)) MinDamage = Math.Max(0, d); break;
}
}
}

View file

@ -0,0 +1,62 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// C ABI exports the engine's PluginLoader resolves by name (GetProcAddress).
/// Note there is intentionally NO RynthPluginRender export: that drives plugin
/// ImGui drawing, which RynthJuice doesn't use. All geometry is submitted from
/// the tick (RynthPluginTick) through the engine's Nav3D renderer, which has its
/// own draw hook and runs regardless of the ImGui shell.
/// </summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthJuicePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthJuicePlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthJuicePlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker)
=> Runtime.OnCombatDamage(damage, damageType, crit, isAttacker);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag)
=> Runtime.OnChatBarEnter(textUtf16, eatFlag);
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthJuice</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthJuice</AssemblyName>
<Platforms>x86</Platforms>
<!-- Publish straight into the launcher-registered deploy home so a bare
`dotnet publish` lands where the engine hot-reloads it (mirrors
RynthVision). Deploy-RynthCore.ps1 points its copy step here too and
detects source == dest to skip the redundant self-copy. -->
<PublishDir>C:\Games\RynthSuite\RynthJuice\</PublishDir>
</PropertyGroup>
<!-- No ImGui.NET: RynthJuice draws purely through the engine's Nav3D world-
space renderer (lines/rings/triangles), which has its own
DrawIndexedPrimitive hook independent of the ImGui shell. That keeps the
plugin alive in EnableImGuiShell=false mode and off the fragile ImGui
path entirely. -->
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- Shared DAT reader (same lib RynthVision uses; carries NO RynthAi
dependency) — used to read per-EnvCell transforms from cell.dat for
dungeon (indoor) damage-number placement. -->
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,551 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// Combat "juice" for RynthCore: floating vector-digit damage numbers over
/// monsters (white→orange→red by size, GOLD + bigger on crit), green heal
/// numbers, red numbers over your own character when hit, and an expanding ring
/// burst when a damaged monster dies. Pure Nav3D — no ImGui — so it runs in
/// EnableImGuiShell=false mode and stays fully isolated from RynthAi. Outdoor
/// only in v1 (dungeon coords are cell-local). Toggle with /juice.
/// </summary>
public sealed class RynthJuicePlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthJuice");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
private sealed class HState
{
public bool HasCurrent;
public uint LastCurrent;
public uint KnownMax;
public float LastRatio;
public uint Cell;
public float E, N, U; // last known position (own-landblock frame)
public long LastDmgMs;
public long LastSeenMs;
}
private readonly JuiceSettings _cfg = new();
private readonly JuiceEffects _fx = new();
private readonly EnvCellTransforms _cells = new();
private readonly Dictionary<uint, HState> _health = new();
private readonly HashSet<uint> _killedIds = new();
private readonly List<JuiceEffects.MobHp> _mobHpScratch = new();
private readonly HashSet<uint> _tracked = new(); // candidate mob ids (from OnCreateObject) to poll
private readonly List<uint> _pollScratch = new();
private int _pollLogCount;
private int _createLogCount;
private readonly Random _rng = new();
private uint _playerId;
private bool _loginComplete;
private long _lastCritMs = long.MinValue;
private int _tick;
private bool _debugChat;
private bool _autoDiagDone;
private PendingExact _pending;
private const int CritWindowMs = 450;
private const int ExactWindowMs = 600; // pair a combat-log amount with its health packet
private const int HealMinDelta = 8; // filters small regen ticks
private const long DeleteKillRecentDamageMs = 8_000; // delete counts as a kill only if we hit it this recently
private const long ForgetMs = 60_000; // prune untouched health entries
// An exact combat-log amount whose health packet hasn't arrived yet (reverse order).
private struct PendingExact { public bool Has; public int Amount; public bool Crit; public bool Incoming; public long Ts; }
public override int Initialize()
{
_cfg.Load();
_fx.SetCells(_cells);
Host.Log("[RynthJuice] Initialized. /juice [on|off|test|heals|playerdmg|scale N|height N|help]. " +
"Needs a clean (no-Decal) client; works with the ImGui shell on or off; outdoors + dungeons.");
return 0;
}
public override void OnLoginComplete()
{
_playerId = Host.GetPlayerId();
_loginComplete = true;
_autoDiagDone = false;
_health.Clear();
_fx.Clear();
if (!Host.HasNav3DTriangle)
Host.Log("[RynthJuice] WARNING: engine has no Nav3D triangle API — numbers can't draw. Update the engine.");
Host.Log($"[RynthJuice] Ready (enabled={_cfg.Enabled}).");
}
public override void OnLogout()
{
_loginComplete = false;
_health.Clear();
_killedIds.Clear();
_tracked.Clear();
_fx.Clear();
}
public override void Shutdown() { _fx.Clear(); _cells.Dispose(); }
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (!_loginComplete || !_cfg.Enabled) return;
long now = Environment.TickCount64;
bool isPlayer = targetId == _playerId;
if (!_health.TryGetValue(targetId, out var st))
{
st = new HState();
_health[targetId] = st;
}
uint prevCur = st.LastCurrent;
float prevRatio = st.LastRatio;
bool hadPrev = st.HasCurrent;
// Update tracked state.
if (maxHealth > 0 && maxHealth > st.KnownMax) st.KnownMax = maxHealth;
st.LastRatio = healthRatio;
st.LastCurrent = currentHealth;
st.HasCurrent = true;
st.LastSeenMs = now;
// Cache the mob's current position every update — the live health readout and
// the kill effect both need a spot, and the position cache can be empty by the
// time the object is deleted.
if (!isPlayer && Host.TryGetObjectPosition(targetId, out uint upCell, out float upE, out float upN, out float upU))
{ st.Cell = upCell; st.E = upE; st.N = upN; st.U = upU; }
// Kill detection by HEALTH RATIO → 0. Fires at the killing blow (no
// OnDeleteObject corpse-removal delay) and works for ALL mobs — ratio is the
// reliable signal; absolute currentHealth reads 0 for unappraised mobs.
// _killedIds dedups (fires once); OnDeleteObject stays as a fallback.
if (!isPlayer && healthRatio < 0.001f)
{
if (_killedIds.Add(targetId))
{
int killAmt = (maxHealth > 0) ? (int)Math.Round(prevRatio * maxHealth) : 0;
bool kcrit = (now - _lastCritMs) <= CritWindowMs;
if (_pending.Has && (now - _pending.Ts) <= ExactWindowMs && !_pending.Incoming)
{
killAmt = _pending.Amount;
kcrit = kcrit || _pending.Crit;
_pending.Has = false;
}
// Verification scaffolding — chat only in debug mode, or every
// kill spams the chat window once this goes live.
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
// Anchor: live position → last cached → player (so it ALWAYS fires).
uint kc; float ke, kn, ku;
bool gotPos = Host.TryGetObjectPosition(targetId, out kc, out ke, out kn, out ku);
if (!gotPos && (st.Cell >> 16) != 0) { kc = st.Cell; ke = st.E; kn = st.N; ku = st.U; gotPos = true; }
if (!gotPos) gotPos = Host.TryGetPlayerPose(out kc, out ke, out kn, out ku, out _, out _, out _, out _);
if (gotPos)
{
if (killAmt >= _cfg.MinDamage) _fx.SpawnDamage(kc, ke, kn, ku, killAmt, kcrit);
_fx.SpawnKillBurst(kc, ke, kn, ku, kcrit, now);
Host.Log($"[RynthJuice] KILL tgt=0x{targetId:X8} amt={killAmt} cell=0x{kc:X8} fx={_fx.Count}");
}
}
_health.Remove(targetId);
return;
}
if (!hadPrev) return; // first non-death packet — establish baseline only
// Resolve a damage/heal amount, preferring absolute HP when the server
// gave us real numbers, falling back to ratio × best-known max.
int delta;
bool isDamage;
if (maxHealth > 0 && (currentHealth > 0 || prevCur > 0))
{
long ad = (long)prevCur - currentHealth;
isDamage = ad > 0;
delta = (int)Math.Abs(ad);
}
else
{
float rd = prevRatio - healthRatio;
float baseMax = st.KnownMax > 0 ? st.KnownMax : 100f;
isDamage = rd > 0;
delta = (int)MathF.Round(Math.Abs(rd) * baseMax);
}
if (delta <= 0) return;
// Capture anchor position (mob via object cache, player via pose).
uint cell; float e, n, u;
if (isPlayer)
{
if (!Host.TryGetPlayerPose(out cell, out e, out n, out u, out _, out _, out _, out _))
return;
}
else if (!Host.TryGetObjectPosition(targetId, out cell, out e, out n, out u))
{
if (_debugChat) Host.Log($"[RynthJuice] dmg tgt=0x{targetId:X8} delta={delta} POS-FAIL (no anchor — skipped)");
return;
}
st.Cell = cell; st.E = e; st.N = n; st.U = u;
if (isDamage)
{
if (delta < _cfg.MinDamage) return;
st.LastDmgMs = now;
int amount = delta;
bool crit = (now - _lastCritMs) <= CritWindowMs;
// Prefer the exact combat-log value if its line already arrived (reverse order).
if (_pending.Has && (now - _pending.Ts) <= ExactWindowMs && _pending.Incoming == isPlayer)
{
amount = _pending.Amount;
crit = crit || _pending.Crit;
_pending.Has = false;
}
if (isPlayer)
{
if (_cfg.ShowPlayerDamage) _fx.SpawnPlayerDamage(cell, e, n, u, amount, crit);
}
else
{
_fx.SpawnDamage(cell, e, n, u, amount, crit);
}
if (_debugChat) Host.Log($"[RynthJuice] dmg tgt=0x{targetId:X8} amt={amount} crit={crit} isPlayer={isPlayer} cell=0x{cell:X8} indoor={(cell & 0xFFFF) >= 0x100} fx={_fx.Count}");
}
else if (_cfg.ShowHeals && delta >= HealMinDelta)
{
_fx.SpawnHeal(cell, e, n, u, delta);
}
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (!_loginComplete || !_cfg.Enabled || string.IsNullOrEmpty(text)) return;
if (_debugChat) Host.Log($"[RynthJuice] chat[{chatType}]: {text}");
long now = Environment.TickCount64;
bool isCrit = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0;
// Exact damage from the combat log: "... for N points of <type> damage".
// The health packet anchors it to the right object; this overwrites the
// estimate with the true value. Requires "damage" so heal/mana/stamina
// "points of" lines are ignored.
if (TryParseDamage(text, out int amount, out bool incoming))
{
bool crit = isCrit || (now - _lastCritMs) <= CritWindowMs;
if (isCrit) _lastCritMs = now;
var kind = incoming ? JuiceEffects.Kind.PlayerDamage : JuiceEffects.Kind.MobDamage;
// Correct an already-spawned number, else stash for the health packet.
if (!_fx.ApplyExactToRecent(now, ExactWindowMs, kind, amount, crit))
_pending = new PendingExact { Has = true, Amount = amount, Crit = crit, Incoming = incoming, Ts = now };
return;
}
// A standalone crit line (no parsable amount): mark window + retro-upgrade.
if (isCrit)
{
_lastCritMs = now;
_fx.UpgradeRecentToCrit(now, CritWindowMs);
}
}
// Parses AC combat-log damage lines, e.g.:
// "You slash the Drudge for 47 points of slashing damage!" (outgoing)
// "The Drudge Slinker hits you for 12 points of bludgeoning damage!" (incoming)
// Extracts the integer before "points" and the direction. Returns false for
// non-damage "points of" lines (heals/mana/stamina lack "damage").
private static bool TryParseDamage(string text, out int amount, out bool incoming)
{
amount = 0; incoming = false;
int pts = text.IndexOf("points of", StringComparison.OrdinalIgnoreCase);
if (pts < 0) return false;
if (text.IndexOf("damage", pts, StringComparison.OrdinalIgnoreCase) < 0) return false;
int i = pts - 1;
while (i >= 0 && text[i] == ' ') i--;
long val = 0, mult = 1; bool any = false;
while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ','))
{
if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; }
i--;
}
if (!any || val <= 0 || val > 1_000_000) return false;
amount = (int)val;
// Defender (incoming) lines target "you for"; attacker lines start "You ".
incoming = text.IndexOf("you for", StringComparison.OrdinalIgnoreCase) >= 0;
return true;
}
// Exact per-hit damage from the structured AC packet (AttackerNotification /
// DefenderNotification), surfaced by the engine. This is the real damage value
// even for one-shots/overkill. It carries no object id (the packet identifies
// the target by name), so correlate it to the health packet — which has the id
// + position — by recency, reusing the same _pending mechanism.
public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker)
{
if (!_loginComplete || !_cfg.Enabled || damage == 0) return;
long now = Environment.TickCount64;
if (crit) _lastCritMs = now;
var kind = isAttacker ? JuiceEffects.Kind.MobDamage : JuiceEffects.Kind.PlayerDamage;
// Overwrite a number that already spawned from the health packet, else stash
// the exact value for the imminent health update / kill to pick up.
if (!_fx.ApplyExactToRecent(now, ExactWindowMs, kind, (int)damage, crit))
_pending = new PendingExact { Has = true, Amount = (int)damage, Crit = crit, Incoming = !isAttacker, Ts = now };
if (_debugChat) Host.Log($"[RynthJuice] COMBATDMG dmg={damage} type={damageType} crit={crit} atk={isAttacker}");
}
// Track dynamic objects (mobs/items) so we can poll their health each tick —
// the streaming-health hook is dead on this client, so polling is how we read
// monster HP. ObjectIsAttackable (in the poll) filters out non-creatures.
public override void OnCreateObject(uint objectId)
{
// No login/enabled gate: the engine REPLAYS creates for pre-existing objects
// at plugin init (possibly before OnLoginComplete), and mobs already in the
// room must be tracked. Polling itself is gated by login/enabled in OnTick.
if ((objectId & 0x80000000u) == 0) return; // dynamic objects only
if (_tracked.Count >= 800 || !_tracked.Add(objectId)) return;
if (_createLogCount < 8) { _createLogCount++; Host.Log($"[RynthJuice] create 0x{objectId:X8} tracked={_tracked.Count}"); }
}
public override void OnDeleteObject(uint objectId)
{
_tracked.Remove(objectId);
// Capture state BEFORE removing it — LastDmgMs is the recent-damage
// gate below; the old order destroyed it first.
bool hadState = _health.TryGetValue(objectId, out HState? st);
_health.Remove(objectId);
if (!_loginComplete || !_cfg.Enabled) return;
// An appraised mob already got its effect from the health=0 path — don't double.
if (_killedIds.Remove(objectId)) return;
if (_killedIds.Count > 1024) _killedIds.Clear();
// AC sends deletes for range-out / teleport / despawn too — only treat
// a delete as a DEATH if we damaged the creature recently. Without this
// gate, walking out of a spawn field or portaling fired a burst per
// nearby mob (anchored at the PLAYER via the old pose fallback, since
// the position cache was already empty).
long now = Environment.TickCount64;
if (!hadState || st!.LastDmgMs == 0 || now - st.LastDmgMs > DeleteKillRecentDamageMs)
return;
if (!Host.ObjectIsAttackable(objectId)) return;
// Anchor at the mob's live or last-cached position only — never the
// player. A delete with no known position gives a wrong-place burst.
uint kc; float ke, kn, ku;
if (!Host.TryGetObjectPosition(objectId, out kc, out ke, out kn, out ku))
{
if ((st.Cell >> 16) == 0) return;
kc = st.Cell; ke = st.E; kn = st.N; ku = st.U;
}
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
_fx.SpawnKillBurst(kc, ke, kn, ku, crit: false, now);
}
public override void OnTick()
{
if (!_loginComplete) return;
_tick++;
// Auto-diagnostic: ~150 ticks after login, log the full pipeline state once
// (no command / on-screen output needed). Fires even when disabled so the
// log shows enabled=False if that's the cause.
if (!_autoDiagDone && _tick >= 150) { _autoDiagDone = true; RunDiag(); }
if (!_cfg.Enabled) return;
long now = Environment.TickCount64;
_fx.Render(Host, _cfg, now);
if ((_tick & 1) == 0) PollMobHealth(now); // poll mob vitals every other tick
if ((_tick & 0xFF) == 0) PruneHealth(now); // ~every 256 ticks
}
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith("/juice", StringComparison.OrdinalIgnoreCase))
return;
eat = 1; // consume — never send to the server as chat
string rest = text.Length > 6 ? text.Substring(6).Trim() : "";
string[] parts = rest.Length == 0 ? Array.Empty<string>() : rest.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string cmd = parts.Length > 0 ? parts[0].ToLowerInvariant() : "";
switch (cmd)
{
case "":
case "toggle":
_cfg.Enabled = !_cfg.Enabled;
if (!_cfg.Enabled) _fx.Clear();
_cfg.Save();
Reply($"[RynthJuice] {(_cfg.Enabled ? "ON" : "OFF")}.");
break;
case "on": _cfg.Enabled = true; _cfg.Save(); Reply("[RynthJuice] ON."); break;
case "off": _cfg.Enabled = false; _fx.Clear(); _cfg.Save(); Reply("[RynthJuice] OFF."); break;
case "heals":
_cfg.ShowHeals = !_cfg.ShowHeals; _cfg.Save();
Host.Log($"[RynthJuice] heal numbers {(_cfg.ShowHeals ? "on" : "off")}.");
break;
case "playerdmg":
_cfg.ShowPlayerDamage = !_cfg.ShowPlayerDamage; _cfg.Save();
Host.Log($"[RynthJuice] player-damage numbers {(_cfg.ShowPlayerDamage ? "on" : "off")}.");
break;
case "scale":
if (parts.Length > 1 && float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float sc))
{ _cfg.Scale = Math.Clamp(sc, 0.3f, 4f); _cfg.Save(); Host.Log($"[RynthJuice] scale = {_cfg.Scale:0.##}."); }
else Host.Log("[RynthJuice] usage: /juice scale 1.5");
break;
case "height":
if (parts.Length > 1 && float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float hh))
{ _cfg.HeightOffset = Math.Clamp(hh, 0f, 8f); _cfg.Save(); Host.Log($"[RynthJuice] height = {_cfg.HeightOffset:0.##} m."); }
else Host.Log("[RynthJuice] usage: /juice height 1.8");
break;
case "test": SpawnTest(); break;
case "debug":
_debugChat = !_debugChat;
Host.Log($"[RynthJuice] combat-log debug {(_debugChat ? "ON" : "OFF")} (logs chat lines to RynthCore.log so we can verify the damage-text format).");
break;
case "help":
default:
Host.Log("[RynthJuice] /juice [on|off|toggle|test|heals|playerdmg|scale N|height N|debug|help]");
break;
}
}
// Command feedback to BOTH the unified log and the in-game chat window.
private void Reply(string msg)
{
Host.Log(msg);
if (Host.HasWriteToChat) Host.WriteToChat(msg, 1);
}
/// <summary>/juice diag — dumps the full render-pipeline state to chat + log so
/// we can pinpoint why numbers aren't appearing (especially indoors). Run it
/// outdoors AND inside a dungeon and compare.</summary>
private void RunDiag()
{
bool nav = Host.HasNav3D, tri = Host.HasNav3DTriangle, w2s = Host.HasWorldToScreen;
bool poseOk = Host.TryGetPlayerPose(out uint cell, out float e, out float n, out float u, out _, out _, out _, out _);
Host.TryGetViewportSize(out uint vpw, out uint vph);
bool indoor = poseOk && (cell & 0xFFFF) >= 0x100;
// Project a point ~2m ABOVE the player (where numbers anchor — not the
// player's feet, which sit at the camera and never project). Test BOTH the
// raw cell-local coords and the EnvCell-transformed landblock-relative
// coords; whichever projects tells us the frame the indoor camera uses.
float upU = u + 2f;
float rrx = 0, rry = 0, xsx = 0, xsy = 0;
bool projRaw = poseOk && w2s && Host.WorldToScreen(e, upU, n, out rrx, out rry);
float xe = e, xn = n, xu = upU;
bool resolveOk = poseOk && _cells.ToLandblockRelative(cell, ref xe, ref xn, ref xu);
bool projXform = resolveOk && w2s && Host.WorldToScreen(xe, xu, xn, out xsx, out xsy);
Reply($"[RynthJuice] DIAG enabled={_cfg.Enabled} tick={_tick} fx={_fx.Count} nav={nav} tri={tri} w2s={w2s} vp={vpw}x{vph}");
Reply($"[RynthJuice] DIAG pose={poseOk} cell=0x{cell:X8} indoor={indoor} cellsReady={_cells.Ready} resolve={resolveOk}");
Reply($"[RynthJuice] DIAG raw=({e:F1},{n:F1},{u:F1}) projRaw={projRaw}@({rrx:F0},{rry:F0}) | xform=({xe:F1},{xn:F1},{xu:F1}) projXform={projXform}@({xsx:F0},{xsy:F0})");
Reply($"[RynthJuice] DIAG render: {_fx.LastRenderStatus} | lastDrawn={_fx.LastDrawnEffects} lastTris={_fx.LastTriangles} writeToChat={Host.HasWriteToChat}");
if (indoor && !_cells.Ready) Reply($"[RynthJuice] DIAG cell.dat status: {_cells.Status}");
}
// Polls each tracked mob's vitals directly (TryGetTargetVitals) — the streaming
// health hook doesn't install on this client, so polling is how we read monster
// HP. Drives both the live health % and instant (no-delay) death detection.
private void PollMobHealth(long now)
{
if (_tracked.Count == 0)
{
if ((_tick & 0x7F) == 0) Host.Log("[RynthJuice] pollcycle tracked=0 (OnCreateObject delivered no ids)");
return;
}
_mobHpScratch.Clear();
_pollScratch.Clear();
_pollScratch.AddRange(_tracked); // snapshot so we can remove during the walk
int budget = 80, atk = 0, vit = 0;
foreach (uint id in _pollScratch)
{
if (budget-- <= 0) break;
if (id == _playerId) { _tracked.Remove(id); continue; }
if (!Host.ObjectIsAttackable(id)) continue; // KEEP tracked — classification lags several ticks
atk++;
if (!Host.TryGetTargetVitals(id, out uint h, out uint mx, out _, out _, out _, out _) || (h == 0 && mx == 0))
continue; // can't read this tick
vit++;
if (_pollLogCount < 12)
{
_pollLogCount++;
Host.Log($"[RynthJuice] poll 0x{id:X8} h={h} mx={mx}");
}
if (!Host.TryGetObjectPosition(id, out uint cell, out float e, out float n, out float u))
continue;
// Death by poll: HP hit 0 — instant, no OnDeleteObject corpse-removal delay.
if (mx > 0 && h == 0)
{
if (_killedIds.Add(id))
{
if (_debugChat) Reply("[RynthJuice] *** KILL ***");
_fx.SpawnKillBurst(cell, e, n, u, crit: false, now);
Host.Log($"[RynthJuice] KILL(poll) tgt=0x{id:X8} cell=0x{cell:X8}");
}
_tracked.Remove(id);
continue;
}
float ratio = mx > 0 ? Math.Clamp((float)h / mx, 0f, 1f) : 1f;
_mobHpScratch.Add(new JuiceEffects.MobHp(cell, e, n, u, ratio));
}
if ((_tick & 0x3F) == 0)
Host.Log($"[RynthJuice] pollcycle tracked={_tracked.Count} attackable={atk} vitals={vit} bars={_mobHpScratch.Count}");
if (_mobHpScratch.Count > 0) _fx.RenderMobHealth(Host, _cfg, _mobHpScratch);
}
private void PruneHealth(long now)
{
// Allocation-light prune of stale targets.
List<uint>? dead = null;
foreach (var kv in _health)
if (now - kv.Value.LastSeenMs > ForgetMs)
(dead ??= new List<uint>()).Add(kv.Key);
if (dead != null)
foreach (uint id in dead) _health.Remove(id);
}
/// <summary>/juice test — spawn a spread of demo numbers + a burst at the
/// player so the render path can be verified without combat.</summary>
private void SpawnTest()
{
if (!Host.TryGetPlayerPose(out uint cell, out float e, out float n, out float u, out _, out _, out _, out _))
{
Host.Log("[RynthJuice] test: player pose unavailable (are you in the world, outdoors?).");
return;
}
if ((cell >> 16) == 0)
{
Host.Log("[RynthJuice] test: not in the world yet.");
return;
}
long now = Environment.TickCount64;
_lastCritMs = long.MinValue; // don't accidentally crit the demo numbers
_fx.SpawnDamage(cell, e + 2f, n + 2f, u, 18, crit: false);
_fx.SpawnDamage(cell, e - 2f, n + 1f, u, 73, crit: false);
_fx.SpawnDamage(cell, e + 1f, n - 2f, u, 142, crit: false);
_fx.SpawnDamage(cell, e - 1f, n - 1f, u, 891, crit: true);
if (_cfg.ShowHeals) _fx.SpawnHeal(cell, e + 3f, n, u, 64);
_fx.SpawnKillBurst(cell, e, n + 3f, u, crit: true, now);
Host.Log("[RynthJuice] test numbers spawned around you.");
}
}

View file

@ -0,0 +1,74 @@
using System.Numerics;
namespace RynthCore.Plugin.RynthJuice;
/// <summary>
/// A tiny stroke-based vector font. Nav3D has no text primitive, so each glyph
/// is defined as a set of line segments on a normalized 2×4 grid (x ∈ [0,2],
/// y ∈ [0,4], y increasing DOWNWARD to match screen space). The renderer
/// (<see cref="JuiceEffects"/>) turns every stroke into a thin billboarded quad.
///
/// Only the characters combat juice needs are defined: digits 0-9, '+' (heals),
/// '!' and the letters C R I T (for the "CRIT!" tag). Unknown chars render as a
/// blank advance.
/// </summary>
internal static class VectorFont
{
public const float GlyphWidth = 2f; // max x in grid units
public const float GlyphHeight = 4f; // max y in grid units
public const float Advance = 3f; // per-char horizontal step (glyph + gap)
// Seven-segment grid points:
// (0,0)──A──(2,0)
// │ │
// F B
// │ │
// (0,2)──G──(2,2)
// │ │
// E C
// │ │
// (0,4)──D──(2,4)
private static readonly Vector4 A = new(0, 0, 2, 0); // top
private static readonly Vector4 B = new(2, 0, 2, 2); // upper-right
private static readonly Vector4 C = new(2, 2, 2, 4); // lower-right
private static readonly Vector4 D = new(0, 4, 2, 4); // bottom
private static readonly Vector4 E = new(0, 2, 0, 4); // lower-left
private static readonly Vector4 F = new(0, 0, 0, 2); // upper-left
private static readonly Vector4 G = new(0, 2, 2, 2); // middle
private static readonly Vector4[] Zero = { A, B, C, D, E, F };
private static readonly Vector4[] One = { B, C };
private static readonly Vector4[] Two = { A, B, G, E, D };
private static readonly Vector4[] Three = { A, B, G, C, D };
private static readonly Vector4[] Four = { F, G, B, C };
private static readonly Vector4[] Five = { A, F, G, C, D };
private static readonly Vector4[] Six = { A, F, G, E, C, D };
private static readonly Vector4[] Seven = { A, B, C };
private static readonly Vector4[] Eight = { A, B, C, D, E, F, G };
private static readonly Vector4[] Nine = { A, B, C, D, F, G };
private static readonly Vector4[] Plus = { new(0, 2, 2, 2), new(1, 1, 1, 3) };
private static readonly Vector4[] Bang = { new(1, 0, 1, 2.6f), new(1, 3.4f, 1, 4f) };
private static readonly Vector4[] LetterC = { A, F, E, D };
// R: left bar + top + upper-right + middle + diagonal leg
private static readonly Vector4[] LetterR = { F, E, A, B, G, new(1, 2, 2, 4) };
private static readonly Vector4[] LetterI = { new(1, 0, 1, 4) };
private static readonly Vector4[] LetterT = { A, new(1, 0, 1, 4) };
private static readonly Vector4[] Empty = System.Array.Empty<Vector4>();
/// <summary>Strokes for a glyph, in grid units. Empty array = blank advance.</summary>
public static Vector4[] Strokes(char c) => c switch
{
'0' => Zero, '1' => One, '2' => Two, '3' => Three, '4' => Four,
'5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine,
'+' => Plus, '!' => Bang,
'C' => LetterC, 'R' => LetterR, 'I' => LetterI, 'T' => LetterT,
_ => Empty,
};
/// <summary>Total grid width of a string (for centering): N chars × Advance, trimmed of the trailing gap.</summary>
public static float MeasureWidth(string s) =>
s.Length == 0 ? 0f : s.Length * Advance - (Advance - GlyphWidth);
}

View file

@ -0,0 +1,84 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthNav;
// Native C-ABI exports the RynthCore engine probes by name (GetProcAddress).
// Mirrors RynthVision's PluginExports; RynthPluginRuntime<T> bridges to the
// managed RynthNavPlugin instance.
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthNavPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthNavPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthNavPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// ── RynthNav panel bridge (engine RynthNavPanel reads/drives via these) ───────
// GetStatusJson uses the alloc-new → swap → free-old pointer pattern (matches
// RynthVision) so the UI-thread caller never races a free.
private static IntPtr _statusPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthNavGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetStatusJson()
{
try
{
string json = Runtime.Plugin?.BuildStatusJson() ?? "{}";
IntPtr nw = Marshal.StringToHGlobalAnsi(json);
IntPtr old = Interlocked.Exchange(ref _statusPtr, nw);
if (old != IntPtr.Zero) Marshal.FreeHGlobal(old);
return nw;
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthNavLoadTile", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void LoadTile() { try { Runtime.Plugin?.DoLoadTile(); } catch { } }
[UnmanagedCallersOnly(EntryPoint = "RynthNavTestQuery", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void TestQuery() { try { Runtime.Plugin?.DoTestQuery(); } catch { } }
[UnmanagedCallersOnly(EntryPoint = "RynthNavPreviewPath", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void PreviewPath(IntPtr ansiCoord)
{
try { Runtime.Plugin?.DoPreviewPath(Marshal.PtrToStringAnsi(ansiCoord)); } catch { }
}
// Manual movement from the panel d-pad. cmd: 1=fwd 2=back 3=left 4=right 5=stop.
// The plugin only records the request here; OnTick issues the AC movement call.
[UnmanagedCallersOnly(EntryPoint = "RynthNavMove", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Move(int cmd) { try { Runtime.Plugin?.DoMove(cmd); } catch { } }
// Auto-walk to a /loc coordinate (computes the navmesh path + steers).
[UnmanagedCallersOnly(EntryPoint = "RynthNavGoto", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Goto(IntPtr ansiCoord)
{
try { Runtime.Plugin?.DoGoto(Marshal.PtrToStringAnsi(ansiCoord)); } catch { }
}
}

View file

@ -0,0 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthNav</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthNav</AssemblyName>
<Platforms>x86</Platforms>
<!-- Publish straight to the launcher-registered home (mirrors RynthVision). -->
<PublishDir>C:\Games\RynthSuite\RynthNav\</PublishDir>
</PropertyGroup>
<ItemGroup>
<!-- Detour query side only (Recast baking stays in the offline RynthNav.Baker). -->
<PackageReference Include="DotRecast.Core" Version="2026.1.3" />
<PackageReference Include="DotRecast.Detour" Version="2026.1.3" />
</ItemGroup>
<ItemGroup>
<!-- Keep the AOT trimmer from stripping DotRecast (reached partly via patterns it can't see). -->
<TrimmerRootAssembly Include="DotRecast.Core" />
<TrimmerRootAssembly Include="DotRecast.Detour" />
</ItemGroup>
<ItemGroup>
<!-- Shared travel-route planner (same source the offline RynthNav.PortalGraph tool validates). -->
<Compile Include="..\..\Tools\RynthNav.PortalGraph\PortalRoute.cs" Link="PortalRoute.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

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