From 0a4b611a909fea42d15f50e0465d99a7aee0a892 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Fri, 25 Sep 2026 21:23:05 -0400 Subject: [PATCH] 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 --- .github/workflows/release.yml | 155 + .gitignore | 38 + BUILD.md | 87 + LICENSE | 21 + .../ACTIVITY_ARBITER_PLAN.md | 166 + .../ActivityArbiter.cs | 211 + .../Combat/AcStubs.cs | 485 + .../Combat/BuffManager.cs | 2555 + .../Combat/CastGateWatchdog.cs | 68 + .../Combat/CombatManager.cs | 3728 + .../Combat/ComponentDatabase.cs | 508 + .../Combat/FellowshipTracker.cs | 356 + .../Combat/MissileCraftingManager.cs | 562 + .../Combat/MonsterMatchEvaluator.cs | 290 + .../Combat/PetManager.cs | 399 + .../Combat/SpellData.txt | Bin 0 -> 912312 bytes .../Combat/SpellDatabase.cs | 118 + .../Combat/SpellManager.cs | 362 + .../Combat/WeaponSwapGate.cs | 62 + .../Combat/WorldObjectCache.cs | 1673 + .../CorpseOpenController.cs | 2332 + .../CreatureData/CreatureProfile.cs | 38 + .../CreatureData/CreatureProfileStore.cs | 223 + .../CreatureData/MonsterDamageStore.cs | 661 + .../DoorInteractionController.cs | 310 + .../DungeonHazardStore.cs | 147 + .../DungeonHazardSurfaces.cs | 285 + .../DungeonPathfinder.cs | 741 + .../RynthCore.Plugin.RynthAi/GlobalUsings.cs | 3 + Plugins/RynthCore.Plugin.RynthAi/Jumper.cs | 231 + .../LegacyUi/DungeonMapUi.cs | 1304 + .../LegacyUi/LegacuLuaUi.cs | 184 + .../LegacyUi/LegacyAdvancedSettingsUi.cs | 675 + .../LegacyUi/LegacyDashboardDrawing.cs | 158 + .../LegacyUi/LegacyDashboardRenderer.cs | 3112 + .../LegacyUi/LegacyMetaUi.cs | 1252 + .../LegacyUi/LegacyMonstersUi.cs | 460 + .../LegacyUi/LegacyNavigationUi.cs | 275 + .../LegacyUi/LegacyUiSettings.cs | 776 + .../LegacyUi/LegacyWeaponsUi.cs | 323 + .../LegacyUi/MetaBridgeTypes.cs | 25 + .../LegacyUi/NavCoordinateHelper.cs | 42 + .../LegacyUi/NavRouteParser.cs | 262 + .../LegacyUi/RadarSnapshot.cs | 83 + .../LegacyUi/RynthAiJsonContext.cs | 23 + .../LegacyUi/RynthChatUi.cs | 395 + .../LegacyUi/RynthRadarUi.cs | 1230 + .../Loot/InventoryManager.cs | 415 + .../Loot/LootEvaluator.cs | 75 + .../Loot/SalvageManager.cs | 1084 + .../Loot/VTankLootEvaluator.cs | 332 + .../MagToolsCommands.cs | 755 + .../ManaStoneManager.cs | 583 + .../Maps/DungeonMapTexture.cs | 236 + .../Meta/AfFileParser.cs | 1011 + .../Meta/AfFileWriter.cs | 337 + .../Meta/CommandReference.txt | 180 + .../Meta/ExpressionEngine.cs | 3801 + .../Meta/ExpressionReference.txt | 2116 + .../Meta/LoadedMeta.cs | 25 + .../Meta/MetFileParser.cs | 1007 + .../Meta/MetaManager.cs | 1220 + .../Meta/MetaSchema.cs | 154 + .../Meta/PropertyNames.cs | 643 + .../Meta/QuestTracker.cs | 147 + .../Meta/RegexCache.cs | 58 + .../NavMarkerRenderer.cs | 477 + .../NavigationEngine.cs | 1746 + .../RynthCore.Plugin.RynthAi/PluginExports.cs | 581 + .../PublishProfiles/FolderProfile.pubxml | 11 + .../RadarWallRenderer.cs | 325 + .../Raycasting/BlacklistManager.cs | 161 + .../Raycasting/BoundingVolume.cs | 385 + .../Raycasting/DungeonLOS.cs | 1073 + .../Raycasting/GeometryLoader.cs | 1794 + .../Raycasting/LandblockStructs.cs | 779 + .../Raycasting/MainLogic.cs | 98 + .../Raycasting/RaycastEngine.cs | 285 + .../Raycasting/ScatterSystem.cs | 1061 + .../Raycasting/TargetingFSM.cs | 321 + .../RynthAiCommands.cs | 2754 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 2307 + .../RynthCore.Plugin.RynthAi.csproj | 59 + .../TerrainPassabilityOverlay.cs | 118 + .../UtilityBeltCommands.cs | 63 + .../RynthCore.Plugin.RynthChat/ChatBuffer.cs | 115 + .../ChatClassifier.cs | 84 + .../RynthCore.Plugin.RynthChat/ChatLine.cs | 10 + .../PluginExports.cs | 82 + .../RynthChatPlugin.cs | 50 + .../RynthCore.Plugin.RynthChat.csproj | 41 + .../EnvCellTransforms.cs | 177 + .../JuiceEffects.cs | 419 + .../JuiceSettings.cs | 85 + .../PluginExports.cs | 62 + .../RynthCore.Plugin.RynthJuice.csproj | 39 + .../RynthJuicePlugin.cs | 551 + .../RynthCore.Plugin.RynthJuice/VectorFont.cs | 74 + .../PluginExports.cs | 84 + .../RynthCore.Plugin.RynthNav.csproj | 44 + .../RynthNavPlugin.cs | 768 + .../PluginExports.cs | 79 + .../RynthCore.Plugin.RynthTracker.csproj | 25 + .../RynthTrackerPlugin.cs | 185 + .../Overlays/RadarRingOverlay.cs | 78 + .../Overlays/SlopeOverlay.cs | 159 + .../Overlays/WaterOverlay.cs | 222 + .../PluginExports.cs | 82 + .../RynthCore.Plugin.RynthVision.csproj | 47 + .../RynthVisionPlugin.cs | 175 + .../VisionSettings.cs | 174 + README.md | 112 + RynthSuite.slnx | 15 + Shared/RynthCore.LootSdk/AcGameEnums.cs | 199 + Shared/RynthCore.LootSdk/LootModel.cs | 157 + Shared/RynthCore.LootSdk/MaterialTypes.cs | 45 + .../RynthCore.LootSdk.csproj | 10 + .../SalvageCombineSettings.cs | 70 + .../VTank/VTankLootParser.cs | 184 + .../VTank/VTankLootProfile.cs | 118 + .../VTank/VTankLootWriter.cs | 84 + .../RynthCore.LootSdk/VTank/VTankNodeTypes.cs | 132 + Shared/RynthCore.TerrainData/DatDatabase.cs | 357 + Shared/RynthCore.TerrainData/LandblockData.cs | 336 + .../RynthCore.TerrainData.csproj | 11 + .../RynthCore.TerrainData/TerrainSampler.cs | 273 + Shared/RynthCore.TerrainData/Vector3Helper.cs | 143 + Tools/RynthCore.CreatureSeed/Program.cs | 265 + .../RynthCore.CreatureSeed.csproj | 23 + Tools/RynthCore.LootEditor/App.axaml | 10 + Tools/RynthCore.LootEditor/App.axaml.cs | 24 + Tools/RynthCore.LootEditor/ConfirmDialog.cs | 47 + Tools/RynthCore.LootEditor/MainViewModel.cs | 700 + Tools/RynthCore.LootEditor/MainWindow.axaml | 372 + .../RynthCore.LootEditor/MainWindow.axaml.cs | 21 + Tools/RynthCore.LootEditor/Program.cs | 39 + Tools/RynthCore.LootEditor/RelayCommand.cs | 23 + .../RynthCore.LootEditor.csproj | 25 + Tools/RynthCore.LootEditor/SalvageVMs.cs | 51 + Tools/RynthCore.LootEditor/Styles.axaml | 139 + Tools/RynthCore.LootEditor/TypedEditors.cs | 435 + .../VTankConditionEditorView.cs | 201 + Tools/RynthCore.LootEditor/VTankRuleVm.cs | 292 + Tools/RynthCore.LootSdkTests/Program.cs | 268 + .../RynthCore.LootSdkTests.csproj | 14 + Tools/RynthCore.MonsterEditor/App.axaml | 10 + Tools/RynthCore.MonsterEditor/App.axaml.cs | 25 + Tools/RynthCore.MonsterEditor/JsonContext.cs | 9 + .../RynthCore.MonsterEditor/MainWindow.axaml | 227 + .../MainWindow.axaml.cs | 326 + Tools/RynthCore.MonsterEditor/Models.cs | 68 + Tools/RynthCore.MonsterEditor/Program.cs | 39 + .../RynthCore.MonsterEditor.csproj | 21 + Tools/RynthCore.MonsterEditor/Styles.axaml | 162 + Tools/RynthNav.Baker/ApiDump.cs | 78 + Tools/RynthNav.Baker/NavBake.cs | 213 + Tools/RynthNav.Baker/Program.cs | 151 + Tools/RynthNav.Baker/RynthNav.Baker.csproj | 29 + Tools/RynthNav.Baker/Start-NavWatcher.cmd | 8 + .../RynthNav.PortalGraph/Data/GAlocations.xml | 110468 +++++++++++++++ Tools/RynthNav.PortalGraph/Data/portals.json | 8274 ++ Tools/RynthNav.PortalGraph/Data/portals.tsv | 817 + Tools/RynthNav.PortalGraph/PortalRoute.cs | 205 + Tools/RynthNav.PortalGraph/Program.cs | 230 + Tools/RynthNav.PortalGraph/README.md | 82 + .../RynthNav.PortalGraph.csproj | 18 + 166 files changed, 186537 insertions(+) create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 BUILD.md create mode 100644 LICENSE create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ACTIVITY_ARBITER_PLAN.md create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/ComponentDatabase.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/MonsterMatchEvaluator.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/SpellData.txt create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/GlobalUsings.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Jumper.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacuLuaUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardDrawing.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMonstersUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaBridgeTypes.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RadarSnapshot.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthChatUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapTexture.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/CommandReference.txt create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/LoadedMeta.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/MetFileParser.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/MetaSchema.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/PropertyNames.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/RegexCache.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Properties/PublishProfiles/FolderProfile.pubxml create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/BlacklistManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/BoundingVolume.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/MainLogic.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/RaycastEngine.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthAi/TerrainPassabilityOverlay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/ChatLine.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/RynthChatPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthChat/RynthCore.Plugin.RynthChat.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/EnvCellTransforms.cs create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/JuiceEffects.cs create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/JuiceSettings.cs create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/RynthCore.Plugin.RynthJuice.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/RynthJuicePlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthJuice/VectorFont.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/Overlays/RadarRingOverlay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/Overlays/SlopeOverlay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/Overlays/WaterOverlay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/RynthCore.Plugin.RynthVision.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthVision/RynthVisionPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthVision/VisionSettings.cs create mode 100644 README.md create mode 100644 RynthSuite.slnx create mode 100644 Shared/RynthCore.LootSdk/AcGameEnums.cs create mode 100644 Shared/RynthCore.LootSdk/LootModel.cs create mode 100644 Shared/RynthCore.LootSdk/MaterialTypes.cs create mode 100644 Shared/RynthCore.LootSdk/RynthCore.LootSdk.csproj create mode 100644 Shared/RynthCore.LootSdk/SalvageCombineSettings.cs create mode 100644 Shared/RynthCore.LootSdk/VTank/VTankLootParser.cs create mode 100644 Shared/RynthCore.LootSdk/VTank/VTankLootProfile.cs create mode 100644 Shared/RynthCore.LootSdk/VTank/VTankLootWriter.cs create mode 100644 Shared/RynthCore.LootSdk/VTank/VTankNodeTypes.cs create mode 100644 Shared/RynthCore.TerrainData/DatDatabase.cs create mode 100644 Shared/RynthCore.TerrainData/LandblockData.cs create mode 100644 Shared/RynthCore.TerrainData/RynthCore.TerrainData.csproj create mode 100644 Shared/RynthCore.TerrainData/TerrainSampler.cs create mode 100644 Shared/RynthCore.TerrainData/Vector3Helper.cs create mode 100644 Tools/RynthCore.CreatureSeed/Program.cs create mode 100644 Tools/RynthCore.CreatureSeed/RynthCore.CreatureSeed.csproj create mode 100644 Tools/RynthCore.LootEditor/App.axaml create mode 100644 Tools/RynthCore.LootEditor/App.axaml.cs create mode 100644 Tools/RynthCore.LootEditor/ConfirmDialog.cs create mode 100644 Tools/RynthCore.LootEditor/MainViewModel.cs create mode 100644 Tools/RynthCore.LootEditor/MainWindow.axaml create mode 100644 Tools/RynthCore.LootEditor/MainWindow.axaml.cs create mode 100644 Tools/RynthCore.LootEditor/Program.cs create mode 100644 Tools/RynthCore.LootEditor/RelayCommand.cs create mode 100644 Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj create mode 100644 Tools/RynthCore.LootEditor/SalvageVMs.cs create mode 100644 Tools/RynthCore.LootEditor/Styles.axaml create mode 100644 Tools/RynthCore.LootEditor/TypedEditors.cs create mode 100644 Tools/RynthCore.LootEditor/VTankConditionEditorView.cs create mode 100644 Tools/RynthCore.LootEditor/VTankRuleVm.cs create mode 100644 Tools/RynthCore.LootSdkTests/Program.cs create mode 100644 Tools/RynthCore.LootSdkTests/RynthCore.LootSdkTests.csproj create mode 100644 Tools/RynthCore.MonsterEditor/App.axaml create mode 100644 Tools/RynthCore.MonsterEditor/App.axaml.cs create mode 100644 Tools/RynthCore.MonsterEditor/JsonContext.cs create mode 100644 Tools/RynthCore.MonsterEditor/MainWindow.axaml create mode 100644 Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs create mode 100644 Tools/RynthCore.MonsterEditor/Models.cs create mode 100644 Tools/RynthCore.MonsterEditor/Program.cs create mode 100644 Tools/RynthCore.MonsterEditor/RynthCore.MonsterEditor.csproj create mode 100644 Tools/RynthCore.MonsterEditor/Styles.axaml create mode 100644 Tools/RynthNav.Baker/ApiDump.cs create mode 100644 Tools/RynthNav.Baker/NavBake.cs create mode 100644 Tools/RynthNav.Baker/Program.cs create mode 100644 Tools/RynthNav.Baker/RynthNav.Baker.csproj create mode 100644 Tools/RynthNav.Baker/Start-NavWatcher.cmd create mode 100644 Tools/RynthNav.PortalGraph/Data/GAlocations.xml create mode 100644 Tools/RynthNav.PortalGraph/Data/portals.json create mode 100644 Tools/RynthNav.PortalGraph/Data/portals.tsv create mode 100644 Tools/RynthNav.PortalGraph/PortalRoute.cs create mode 100644 Tools/RynthNav.PortalGraph/Program.cs create mode 100644 Tools/RynthNav.PortalGraph/README.md create mode 100644 Tools/RynthNav.PortalGraph/RynthNav.PortalGraph.csproj diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..b7e665d --- /dev/null +++ b/.github/workflows/release.yml @@ -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' + 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. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..968f2f5 --- /dev/null +++ b/.gitignore @@ -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 + diff --git a/BUILD.md b/BUILD.md new file mode 100644 index 0000000..8d56ee1 --- /dev/null +++ b/BUILD.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..16bbf9c --- /dev/null +++ b/LICENSE @@ -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. diff --git a/Plugins/RynthCore.Plugin.RynthAi/ACTIVITY_ARBITER_PLAN.md b/Plugins/RynthCore.Plugin.RynthAi/ACTIVITY_ARBITER_PLAN.md new file mode 100644 index 0000000..ca1f98c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ACTIVITY_ARBITER_PLAN.md @@ -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. diff --git a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs new file mode 100644 index 0000000..d5dc6f6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs @@ -0,0 +1,211 @@ +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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 , 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 < Navigating < Salvaging < Looting < Combat < 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. +/// +internal enum BotActivity +{ + Idle = 0, + Navigating = 1, + Salvaging = 2, + Looting = 3, + Combat = 4, + Buffing = 5, +} + +/// +/// 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. +/// +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 + + /// Actively engaged (a live attack target), not merely "something is engageable". + public readonly bool CombatEngaged; + /// BoostNavPriority — navigation preempts combat and looting. + public readonly bool BoostNav; + /// BoostLootPriority — looting preempts combat. + public readonly bool BoostLoot; + /// + /// 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. + /// + 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 _log; + private string _lastShadowKey = ""; + + public ActivityArbiter(System.Action log) => _log = log; + + /// + /// Pure decision: highest-priority subsystem that wants to run. + /// Returns Idle when the macro is stopped or nobody wants to run. + /// + 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; + } + + /// + /// 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. + /// + public static string ToBotAction(BotActivity a) => a switch + { + BotActivity.Buffing => "Buffing", + BotActivity.Combat => "Combat", + BotActivity.Looting => "Looting", + BotActivity.Salvaging => "Salvaging", + BotActivity.Navigating => "Navigating", + _ => "Default", + }; + + /// + /// 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. + /// + 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}"); + } + + /// The arbiter's most recent decision. Authoritative as of Step 5. + public BotActivity Current { get; private set; } = BotActivity.Idle; + + private const System.StringComparison OIC = System.StringComparison.OrdinalIgnoreCase; + + /// + /// 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. + /// + 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}"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs new file mode 100644 index 0000000..05347ae --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -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; + +/// +/// STypeInt keys used with TryGetObjectIntProperty / WorldObjectCache.GetIntProperty. +/// Values match Chorizite STypes.cs STypeInt sequential enum. +/// +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, +} + +/// +/// STypeString keys used with TryGetObjectStringProperty / WorldObjectCache.GetStringProperty. +/// Values match Chorizite's STypeString sequential enum. +/// +public enum StringValueKey +{ + Name = 1, + ShortDesc = 15, + LongDesc = 16, + PluralName = 20, + DisplayName = 42, +} + +/// +/// STypeFloat keys used with TryGetObjectDoubleProperty / WorldObjectCache.GetDoubleProperty. +/// Values match Chorizite's STypeFloat sequential enum. +/// +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; } + + /// + /// Spell family — groups all tiers of the same spell (e.g. Strength Self I–VIII). + /// Derived by stripping tier suffixes from the spell name. + /// + public int Family { get; } + + /// 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. + 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", + }; + + /// + /// 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. + /// + private static readonly Dictionary 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 _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); + } + } + + /// + /// Maps AcSkillType to AC's internal STypeSkill sequential enum values + /// (from Chorizite STypes.cs STypeSkill enum, 0-based sequential). + /// + 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; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs new file mode 100644 index 0000000..7e37c19 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -0,0 +1,2555 @@ +using System; +using System.Collections.Generic; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public class BuffManager : IDisposable +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly SpellManager _spellManager; + private readonly PlayerVitalsCache _vitals; + + private CharacterSkills? _charSkills; + private WorldObjectCache? _worldObjectCache; + + private DateTime _lastCastAttempt = DateTime.MinValue; + // Throttles ChangeCombatMode(Magic) from EnsureMagicMode's "wand wielded but + // mode != Magic" branch. Without this, when the server rejects/silently-drops + // mode flips (e.g. wedged-target combat state), the branch fires every tick + // (~2.5Hz) and spams AC with thousands of stance-change packets, eventually + // crashing the client. 2026-05-25 AcActionTrace caught 256 consecutive + // ChangeCombatMode(Magic) calls at ~400ms intervals immediately before pid + // 39584 died. + // + // 2026-05-25 update: a fixed 1s cooldown only paced the spam at 1Hz (pid + // 16656 still crashed after ~48min on engine-side AV at 0x04F24E0 ref 0x18). + // Switched to exponential backoff that doubles wait on each consecutive + // failed flip: 1s → 2s → 4s → 8s → 16s → 30s cap. The bot KEEPS TRYING + // forever (per user requirement — bot must continue) but at a rate that + // decays as failures accumulate. Counter resets to 0 as soon as + // EnsureMagicMode is entered with mode == Magic (i.e. any successful flip + // re-enables fast cadence for the next problem). Worst-case wedge load: + // ~100 calls over 48min instead of ~2,880. + private DateTime _lastBuffStanceAttempt = DateTime.MinValue; + private int _buffStanceConsecutiveFails = 0; + private bool _isForceRebuffing = false; + private int _pendingSpellId = 0; + private Action? _onCastResolved; + + // ARMOR/ITEM enchants only: a cast that gets ZERO chat back (unknown tier / + // no comps — AC silently drops it) never resolves, so pending never clears + // and the cycle wedges. Last-resort bound: abandon after this long. Self- + // buffs do NOT use this path — they confirm via the live registry below. + private const double NoChatResolveTimeoutMs = 5000; + + // SELF-BUFFS confirm via the live player-enchantment registry, not chat + // (ReadPlayerEnchantments returns player buffs in real time; item enchants + // are NOT in it). Wait SelfBuffConfirmMs for the cast to settle server-side, + // then poll the registry; if still absent by SelfBuffGiveUpMs the tier + // didn't take (drop a tier only when the known-spell snapshot is cold). + private const double SelfBuffConfirmMs = 600; + private const double SelfBuffGiveUpMs = 2500; + private DateTime _lastSelfBuffPollAt = DateTime.MinValue; + + // Wired by RynthAiPlugin. Invoked the instant a buff cast resolves in chat + // (success / fizzle / hard-fail / too-busy) so the owner can clear the + // leaked busy-count immediately instead of waiting out the 10s watchdog — + // that post-cast stall is the entire "slow buffing" symptom. + public void SetCastResolvedCallback(Action cb) => _onCastResolved = cb; + + private class RamTimerInfo + { + public DateTime Expiration; + public int SpellLevel; + public string SpellName = ""; + // True when this is a permanent player enchantment (server reports no + // expiry). It is a presence-only marker re-derived from the live + // registry on every RefreshFromLiveMemory — NOT a synthetic timer and + // NEVER persisted (a relog after death/dispel must not resurrect it). + public bool IsPermanent; + } + + // "Never expires" sentinel for permanent player enchantments. Far enough + // from DateTime.MaxValue that IsBuffActive's Expiration.AddSeconds(-rebufferSec) + // (rebufferSec ≤ 1800) can't underflow. + private static readonly DateTime PermanentSentinel = DateTime.MaxValue.AddDays(-1); + + // Permanent-enchant families already logged this session (once-per-family + // diagnostic so the 30s refresh doesn't spam the log). + private readonly HashSet _loggedPermanentFamilies = new(); + + /// + /// Buff timer for an enchantment on a specific equipped item (armor/weapon). + /// + private class ItemBuffTimerInfo + { + public uint ObjectId; + public string ObjectName = ""; + public DateTime Expiration; + public int SpellLevel; + public string SpellName = ""; + } + + /// + /// Timer for an item spell (armor bane / Impenetrability) cast by this plugin. + /// Recorded immediately on cast — independent of chat parsing and enchantment hooks. + /// + private class ItemSpellRecord + { + public DateTime CastAt; + public DateTime ExpiresAt; + public string SpellName = ""; + public int SpellLevel; + } + + private readonly Dictionary _ramBuffTimers = new(); + // Highest tier we've actually seen LAND for a family. Incantations (nominal + // tier 8) land at a skill-capped lower tier; without this the upgrade rule + // in IsBuffActive recasts forever. Updated whenever a family's timer is + // recorded (live refresh or post-cast). Max-of-observed so it converges to + // the character's true ceiling after the first cast. + private readonly Dictionary _familyAchievedTier = new(); + /// Keyed by (objectId, spellFamily) packed as long. + private readonly Dictionary _itemBuffTimers = new(); + /// Keyed by spell family. Tracks item-enchantment casts (armor banes, Impenetrability) directly. + private readonly Dictionary _itemSpellTimers = new(); + private string _buffTimerPath = ""; + + // === Item-enchantment duration experiment (BuffManager_Review.md §headline #3) === + // Toggled via `/ra bufftest`. Stays ON until toggled OFF — captures every cast. + public bool EnableCastRegistryDiagnostic = false; + private readonly Queue _pendingDiagnostics = new(); + + // Force Rebuff cycle tracking — when set, IsBuffActive consults this instead + // of the live timer dicts so FR re-casts every spell to align all timers. + private readonly HashSet _forceRebuffCastFamilies = new(); + + // Per-family diagnostic throttle — last reason string we logged. Suppresses + // dup spam when IsBuffActive is polled every tick by NeedsAnyBuff + CheckAndCastSelfBuffs. + private readonly Dictionary _lastArmorRecastReason = new(); + + // Per-family failure cooldown. A buff the server deterministically rejects + // (no components, must specify a target, etc.) must NOT be re-picked every + // buff cycle — sustained re-cast → sustained AC AddTextToScroll re-entry → + // AC access-violation (the same AV class the cast-gate work targeted). + // Hard rejections park that family for BuffFailCooldownSec; soft random + // fizzles are NOT cooled (they should retry promptly). + private readonly Dictionary _buffFailCooldownUntil = new(); + private const double BuffFailCooldownSec = 120.0; + + // Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil + // (which catches chat-explicit hard rejects). This catches the /god case: + // skill is Trained → IsSkillUsable says yes → BuildDynamicBuffList includes + // the buff → cast is issued → AC silently does nothing because the spell + // isn't in the spellbook → no chat, no enchantment-added event, no _ramBuffTimers + // entry → IsBuffActive returns false → loop forever. The existing no-show + // branch in TickBuffing only blacklists when IsKnownSnapshotWarm == false; + // with /god the snapshot stays warm (knowledge bits exist) so retry never + // exits. This counter bounds the retry: after SilentNoShowThreshold misses + // we park the family in _buffFailCooldownUntil for SilentNoShowCooldown so + // CheckAndCastSelfBuffs skips it on subsequent cycles. Counter + cooldown + // are cleared in OnEnchantmentAdded when the family actually lands later + // (character learns the spell, components arrive, server-side fix, etc.). + private readonly Dictionary _silentNoShowCounts = new(); + private const int SilentNoShowThreshold = 2; + private static readonly TimeSpan SilentNoShowCooldown = TimeSpan.FromMinutes(30); + + // Family → the spell id we last ISSUED a buff cast for. Lets the post-batch + // audit re-check exactly what it tried instead of re-resolving the tier. + private readonly Dictionary _lastCastSpellIdByFamily = new(); + + // Per-family "cast landed but the buff STILL reads inactive" strikes. + // Distinct from both existing park mechanisms: _buffFailCooldownUntil catches + // chat-explicit hard rejects, _silentNoShowCounts catches casts that produce + // no confirmation at all. This catches the nastier third case — AC confirms + // the cast, the enchantment really is on the character, and IsBuffActive + // still returns false. Nothing in the old code bounded that: the family + // re-triggers the auto-batch on the very next tick, and since a single buff + // below threshold escalates to a FULL rebuff, one such family makes the bot + // recast all ~65 spells back-to-back forever. Two consecutive unsatisfied + // batches park the family exactly like a no-show does — time-boxed and + // self-recovering, so a genuine transient can't shelve a buff permanently. + private readonly Dictionary _unsatisfiedStrikes = new(); + private const int UnsatisfiedStrikeThreshold = 2; + + // When each family's cast was issued, and what its stored expiry was at that + // moment. The audit needs both to avoid punishing a perfectly healthy buff: + // a refresh takes time to reach the registry, so a family cast near the end + // of a batch can still read its OLD timer when the batch ends. Judging it + // there produced a false strike on 'Magic Item Tinkering Expertise Self VI' + // (observed 2026-09-02 22:34) that read active again a minute later. A family + // is only judged once AuditSettleMs has passed since its cast, and only + // counts as unsatisfied if its expiry never moved forward. A genuinely stuck + // family recurs in every batch, so it still accumulates strikes across them; + // a healthy one is simply skipped this round. + // ── "You're too busy!" backoff ─────────────────────────────────────────── + // A refusal means AC is mid-gesture and would not accept the cast. The PARK + // path clears _pendingSpellId and says it will "re-issue when the cast gate + // reopens", but nothing actually waits for the gate — the next tick re-issues + // under SpellCastIntervalMs (400ms). A cast gesture runs ~2s, so under load + // that is ~2 refusals/second for as long as the condition lasts: 675 of them + // in two episodes on 2026-09-03, with CanCastNow reporting clear and + // BusyCount 0 throughout (so neither existing gate saw it). + // + // Every refusal also pushes a chat line through AC's text pipeline, which is + // the documented AddTextToScroll re-entry AV pressure this file already + // guards against elsewhere — so a refusal storm is not merely wasted work. + // + // The refusal is authoritative: AC just told us it is busy. Back off with an + // exponential delay and reset the moment a cast is accepted, so a transient + // busy window costs a few attempts instead of thousands. + // ── Server-paced cast serialization (UseDone / GameEvent 0x01C7) ──────── + // The server sends UseDone when it FINISHES an action — completed, or refused + // with an error (0x1D = YoureTooBusy). It is the authoritative ACE + // Player.IsBusy lifecycle signal, and the engine already exposes a monotonic + // counter for it. CombatManager has serialized its casts on this since it was + // added; BuffManager never did, and paced instead on a flat + // SpellCastIntervalMs (400ms) measured from cast ISSUE. + // + // That interval is shorter than a cast actually takes. Measured over 612 + // paired buff casts on 2026-09-03, refusal rate by gap since the previous + // issue: 400-450ms → 54%, 450-600ms → 100%, 600-900ms → 33%, >900ms → 9.5%, + // with "You cast X" arriving at a median 652ms and "too busy" at 307ms. So + // the next cast was routinely issued while the previous one was still + // resolving. The local CanCastNow gate cannot catch this: it reads + // CMotionInterp's pending-motions head, which empties when the LOCAL + // animation ends, well before the server is done. + // + // Waiting for UseDone is self-tuning and needs no per-spell duration table — + // a slower tier-8 cast simply produces a later UseDone. Bounded by a timeout + // so a dropped event can't wedge buffing, and inert (never waits) on an + // engine build without UseDone observation. + private int _useDoneSeqAtCast; + private bool _awaitingCastResolution; + private DateTime _castResolutionDeadline = DateTime.MinValue; + private const double CastResolutionTimeoutMs = 2500; // covers a tier-7/8 windup+recoil + + private int _busyRefusalStreak; + private DateTime _busyBackoffUntil = DateTime.MinValue; + private const double BusyBackoffBaseMs = 500; + private const double BusyBackoffMaxMs = 8000; + + private readonly Dictionary _castIssuedAtByFamily = new(); + private readonly Dictionary _expiryAtCastByFamily = new(); + private const double AuditSettleMs = 15_000.0; + + private sealed class RegistrySnapshot + { + public uint OwnerId; + public string OwnerName = ""; + public bool IsPlayer; + public uint[] SpellIds = Array.Empty(); + public double[] ExpiryTimes = Array.Empty(); + public int Count; + public double ServerTime; + } + + private sealed class CastDiagnostic + { + public DateTime CastedAt; + public string SpellName = ""; + public int SpellId; + public int SpellFamily; + public List PreSnapshots = new(); + } + + private bool _isRechargingMana = false; + private bool _isRechargingStamina = false; + private bool _isHealingSelf = false; + + // Pre-buff combat teardown: one-shot flag set the first tick we issue + // UseObject(wand) while in a physical combat mode. Reset on reaching Magic. + // Without the teardown, AC sees the equip request while a melee/missile + // attack is still pending server-side and the resulting "you can only + // move or use one item at a time" notice can wedge all item actions + // until relog. + private bool _combatTeardownDoneForCurrentBuffCycle; + + // Wield gate: suppress duplicate UseObject(wand) calls while a prior + // equip is in flight. Cleared the moment the wielded check confirms; + // if it never does, the cooldown short-circuits further retries so we + // don't compound the same desync the missing CancelAttack causes. + private int _pendingWieldId; + private DateTime _pendingWieldAt = DateTime.MinValue; + private DateTime _wieldCooldownUntil = DateTime.MinValue; + private const double WieldResolveTimeoutMs = 2500; + private const double WieldCooldownMs = 5000; + + // FIX (2026-06-24, bow->wand buff swap): stock ACE refuses to wield a Held-slot wand + // while the bow is in the main hand and does NOT auto-dequip it (CheckWeaponCollision), + // so the bare UseObject(wand) below never confirmed -> permanent buffing coma. We must + // stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield + // the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never + // loop forever; on exhaustion the buff family is parked and the bot fights unbuffed. + private int _bowDequipPendingId; + private DateTime _bowDequipAt = DateTime.MinValue; + private int _bowDequipAttempts; + private const int BowDequipMaxAttempts = 3; + private int _wieldGateFailCount; + private const int WieldGateFailMax = 3; + private bool _wandSwapExhausted; // per-EnsureMagicMode(forBuff) signal: swap can't succeed now + + // Shared cross-subsystem weapon-swap serializer (set by RynthAiPlugin). + // Prevents the buff wand-equip from racing CombatManager's weapon equip. + private WeaponSwapGate? _weaponSwapGate; + public void SetWeaponSwapGate(WeaponSwapGate gate) => _weaponSwapGate = gate; + + // CombatManager handle (set by RynthAiPlugin after CombatManager is built). + // CheckVitals consults HasCloseThreat(MonsterRange) to pick between the + // in-combat thresholds (HealAt / RestamAt / GetManaAt) and the idle top-off + // thresholds (TopOffHP / TopOffStam / TopOffMana). Null = treat as idle. + private CombatManager? _combatManager; + public void SetCombatManager(CombatManager cm) => _combatManager = cm; + + /// Live combat mode read from AC each access — never drifts if OnCombatModeChange is missed. + public int CurrentCombatMode => + _host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat; + + /// Client busy count — when > 0, don't send any game actions. + public int BusyCount { get; set; } + + /// + /// Record-only diagnostic (D4): the reason the most recent buff-decision cycle + /// did NOT issue a self/player buff cast (or the site that yielded the tick). + /// Purely additive — set at each skip site, never read by control flow. + /// Surfaced through GetStateSnapshot()/BuffStateSnapshot for /ra why + arbiter. + /// + public string LastBuffSkipReason { get; private set; } = ""; + + private readonly List BaseCreatureBuffs = new() + { + "Strength Self", "Endurance Self", "Coordination Self", + "Quickness Self", "Focus Self", "Willpower Self", + "Magic Resistance Self", "Invulnerability Self", "Impregnability Self" + }; + + private readonly Dictionary CreatureSkillBuffs = new() + { + { AcSkillType.MeleeDefense, "Invulnerability Self" }, + { AcSkillType.MissileDefense, "Impregnability Self" }, + { AcSkillType.MagicDefense, "Magic Resistance Self" }, + { AcSkillType.HeavyWeapons, "Heavy Weapon Mastery" }, + { AcSkillType.LightWeapons, "Light Weapon Mastery" }, + { AcSkillType.FinesseWeapons, "Finesse Weapon Mastery" }, + { AcSkillType.TwoHandedCombat, "Two Handed Combat Mastery" }, + { AcSkillType.Shield, "Shield Mastery" }, + { AcSkillType.DualWield, "Dual Wield Mastery" }, + { AcSkillType.Recklessness, "Recklessness Mastery" }, + { AcSkillType.SneakAttack, "Sneak Attack Mastery" }, + { AcSkillType.DirtyFighting, "Dirty Fighting Mastery" }, + { AcSkillType.AssessCreature, "Monster Attunement" }, + { AcSkillType.AssessPerson, "Person Attunement" }, + { AcSkillType.ArcaneLore, "Arcane Enlightenment" }, + { AcSkillType.ArmorTinkering, "Armor Tinkering Expertise" }, + { AcSkillType.ItemTinkering, "Item Tinkering Expertise" }, + { AcSkillType.MagicItemTinkering, "Magic Item Tinkering Expertise" }, + { AcSkillType.WeaponTinkering, "Weapon Tinkering Expertise" }, + { AcSkillType.Salvaging, "Arcanum Salvaging" }, + { AcSkillType.Run, "Sprint" }, + { AcSkillType.Jump, "Jumping Mastery" }, + { AcSkillType.Loyalty, "Fealty" }, + { AcSkillType.Leadership, "Leadership Mastery" }, + { AcSkillType.Deception, "Deception Mastery" }, + { AcSkillType.Healing, "Healing Mastery" }, + { AcSkillType.Lockpick, "Lockpick Mastery" }, + { AcSkillType.Cooking, "Cooking Mastery" }, + { AcSkillType.Fletching, "Fletching Mastery" }, + { AcSkillType.Alchemy, "Alchemy Mastery" }, + { AcSkillType.ManaConversion, "Mana Conversion Mastery" }, + { AcSkillType.CreatureEnchantment, "Creature Enchantment Mastery" }, + { AcSkillType.ItemEnchantment, "Item Enchantment Mastery" }, + { AcSkillType.LifeMagic, "Life Magic Mastery" }, + { AcSkillType.WarMagic, "War Magic Mastery" }, + { AcSkillType.VoidMagic, "Void Magic Mastery" }, + { AcSkillType.Summoning, "Summoning Mastery" }, + }; + + public BuffManager(RynthCoreHost host, LegacyUiSettings settings, SpellManager spellManager, PlayerVitalsCache vitals) + { + _host = host; + _settings = settings; + _spellManager = spellManager; + _vitals = vitals; + } + + public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills; + public void SetWorldObjectCache(WorldObjectCache cache) => _worldObjectCache = cache; + + public void SetTimerPath(string charFolder) + { + _buffTimerPath = System.IO.Path.Combine(charFolder, "bufftimers.txt"); + LoadBuffTimers(); + } + + public void SaveBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + try + { + System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(_buffTimerPath)!); + var lines = new List(); + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + // Never persist permanent player enchants: they are a live-read + // presence cache. After a death/dispel + relog the buff is gone + // server-side, so it must be re-proven by a fresh live read, + // not restored from disk as still-active. + if (info.IsPermanent) continue; + lines.Add($"ram|{kvp.Key}|{info.Expiration.Ticks}|{info.SpellLevel}|{info.SpellName}"); + } + foreach (var kvp in _itemSpellTimers) + { + var info = kvp.Value; + lines.Add($"item|{kvp.Key}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}"); + } + // The "char doesn't know this spell" blacklist is NO LONGER persisted. + // Persisting it meant one lag-induced no-chat timeout permanently + // poisoned a KNOWN spell across all future sessions, collapsing the + // tier walk down to level 1. It is now session-only: re-proven each + // login, cleared on relog. + System.IO.File.WriteAllLines(_buffTimerPath, lines); + } + catch { } + } + + public void LoadBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + if (!System.IO.File.Exists(_buffTimerPath)) return; + try + { + _ramBuffTimers.Clear(); + _itemSpellTimers.Clear(); + foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath)) + { + string[] p = line.Split('|'); + + if (p[0] == "item" && p.Length >= 6) + { + DateTime castAt = new DateTime(long.Parse(p[2])); + DateTime expiresAt = new DateTime(long.Parse(p[3])); + int level = int.Parse(p[4]); + string name = p[5]; + if (expiresAt > DateTime.Now) + { + int family = new SpellInfo(0, name).Family; + _itemSpellTimers[family] = new ItemSpellRecord + { + CastAt = castAt, ExpiresAt = expiresAt, + SpellLevel = level, SpellName = name, + }; + } + continue; + } + + // Legacy "unknown|" blacklist lines are intentionally ignored + // (no longer restored — see SaveBuffTimers). Skip so they don't + // fall through and misparse. Existing files self-clean on next save. + if (p[0] == "unknown") continue; + + // Legacy single-prefix "family|ticks|level|name" or new "ram|family|ticks|level|name" + int offset = (p[0] == "ram") ? 1 : 0; + if (p.Length < offset + 4) continue; + { + DateTime expiration = new DateTime(long.Parse(p[offset + 1])); + int level = int.Parse(p[offset + 2]); + string name = p[offset + 3]; + int family = new SpellInfo(0, name).Family; + if (expiration > DateTime.Now) + _ramBuffTimers[family] = new RamTimerInfo { Expiration = expiration, SpellLevel = level, SpellName = name }; + } + } + int total = _ramBuffTimers.Count + _itemSpellTimers.Count; + if (total > 0) + _host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s).", 1); + } + catch { } + } + + public void Dispose() { } + + public void ForceFullRebuff() + { + _isForceRebuffing = true; + _forceRebuffCastFamilies.Clear(); + _buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns + _silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too + _unsatisfiedStrikes.Clear(); // ditto for the post-batch satisfaction audit + _castIssuedAtByFamily.Clear(); + _expiryAtCastByFamily.Clear(); + _ramBuffTimers.Clear(); + _itemSpellTimers.Clear(); + _pendingSpellId = 0; + _lastCastAttempt = DateTime.MinValue; + SaveBuffTimers(); + _host.WriteToChat("[RynthAi] Starting Force Rebuff...", 5); + + var list = BuildDynamicBuffList(); + _host.Log($"[FR] buff list ({list.Count}): {string.Join(", ", list)}"); + _host.Log($"[FR] macroRunning={_settings.IsMacroRunning} liveRefreshed={_liveBuffsRefreshed}"); + } + + public void CancelBuffing() + { + _isForceRebuffing = false; + _isRechargingMana = false; + _isRechargingStamina = false; + _isHealingSelf = false; + _pendingSpellId = 0; + _host.WriteToChat("[RynthAi] Sequence cancelled.", 5); + } + + /// + /// Spell id of a cast awaiting server confirmation, or 0. Read by the activity + /// arbiter: a cast in flight must keep Buffing winning so CombatManager can't + /// slip a peace-mode switch in mid-cast and fizzle it. + /// + public int PendingSpellId => _pendingSpellId; + + /// + /// True when the last vitals evaluation wanted a heal / restam / remana. Also + /// read by the arbiter — vital recharges run even with buffing switched off, + /// and they need the same mid-cast protection a buff gets. Side-effect free: + /// CheckVitals repopulates these flags every cycle it reaches. + /// + public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina; + + public BuffStateSnapshot GetStateSnapshot() => new() + { + EnableBuffing = _settings.EnableBuffing, + IsForceRebuffing = _isForceRebuffing, + IsRechargingMana = _isRechargingMana, + IsRechargingStamina = _isRechargingStamina, + IsHealingSelf = _isHealingSelf, + PendingSpellId = _pendingSpellId, + LastCastAttempt = _lastCastAttempt, + RamBuffTimerCount = _ramBuffTimers.Count, + ItemSpellTimerCount = _itemSpellTimers.Count, + NeedsAnyBuffNow = NeedsAnyBuff(), + LastBuffSkipReason = LastBuffSkipReason, + HealthPct = _vitals.HealthPct, + ManaPct = _vitals.ManaPct, + StaminaPct = _vitals.StaminaPct, + }; + + public struct BuffStateSnapshot + { + public bool EnableBuffing; + public bool IsForceRebuffing; + public bool IsRechargingMana; + public bool IsRechargingStamina; + public bool IsHealingSelf; + public int PendingSpellId; + public DateTime LastCastAttempt; + public int RamBuffTimerCount; + public int ItemSpellTimerCount; + public bool NeedsAnyBuffNow; + public int HealthPct; + public int ManaPct; + public int StaminaPct; + public string LastBuffSkipReason; + } + + private bool _liveBuffsRefreshed; + private DateTime _lastLiveRefreshAttempt = DateTime.MinValue; + private DateTime _lastPeriodicRefreshAt = DateTime.MinValue; + private const int PeriodicRefreshIntervalMs = 30_000; + + // Login-refresh stabilization: the server streams the active-enchantment + // registry over a few seconds after login, so an early read returns a + // partial/empty set. Opening the gate on that wipes timers → full rebuff + // every login. Wait until the count is the SAME across two consecutive 1s + // reads (registry done streaming — works for 0 buffs or 50), or a timeout. + private DateTime _loginRefreshStartAt = DateTime.MinValue; + private int _lastLoginRefreshCount = -1; + private const int LoginRefreshMaxWaitMs = 20_000; + + public void OnHeartbeat() + { + // Post-cast diffs for the bufftest experiment run unconditionally — even if the + // user toggled the macro off mid-experiment, we still want to capture and log them. + // Drain any pending diagnostics whose 2s post-cast window has elapsed. + while (_pendingDiagnostics.Count > 0 && + (DateTime.Now - _pendingDiagnostics.Peek().CastedAt).TotalSeconds >= 2.0) + { + var diag = _pendingDiagnostics.Dequeue(); + LogPostCastDiff(diag); + } + + if (!_settings.IsMacroRunning) return; + + // RefreshFromLiveMemory at OnLoginComplete fails when the server-time + // packet hasn't landed yet (GetServerTime returns 0). On those + // logins we have NO timers and would recast every buff that has + // hours left server-side. Retry every second until we get the + // live snapshot, and BLOCK any cast attempts in the meantime. + if (!_liveBuffsRefreshed) + { + if ((DateTime.Now - _lastLiveRefreshAttempt).TotalMilliseconds > 1000) + { + _lastLiveRefreshAttempt = DateTime.Now; + int n = RefreshFromLiveMemory(); + if (n >= 0) + { + if (_loginRefreshStartAt == DateTime.MinValue) _loginRefreshStartAt = DateTime.Now; + // Only trust the snapshot once the registry stops growing + // (two equal 1s reads), so we don't open the gate on a + // half-streamed set and rebuff buffs that are still landing. + bool stable = (n == _lastLoginRefreshCount); + bool timedOut = (DateTime.Now - _loginRefreshStartAt).TotalMilliseconds > LoginRefreshMaxWaitMs; + _lastLoginRefreshCount = n; + if (stable || timedOut) + { + _liveBuffsRefreshed = true; + _host.Log($"[BuffDiag] login refresh ready: {n} enchantment(s) (stable={stable} timedOut={timedOut})"); + _host.WriteToChat($"[RynthAi] Live buff timers ready ({n} loaded).", 1); + } + } + } + // Don't cast anything until we have a real snapshot — otherwise + // we'd recast over a 1-hour-old buff at the start of every login. + return; + } + + // Periodic re-sync: if the character died and lost all enchantments, the + // in-memory timers still show buffs as "active" until their timestamps + // expire normally — causing NeedsAnyBuff() to return false while the char + // is completely unbuffed. Re-read from live AC memory every 30s to detect + // this gap and clear stale timers so rebuffing resumes promptly. + if ((DateTime.Now - _lastPeriodicRefreshAt).TotalMilliseconds > PeriodicRefreshIntervalMs) + { + _lastPeriodicRefreshAt = DateTime.Now; + int n = RefreshFromLiveMemory(); + if (n >= 0) + _host.Log($"[BuffDiag] periodic sync: {n} active enchantment(s) in RAM timers."); + } + + // ── Pending-cast resolution — self-buffs and armor use DIFFERENT signals ── + // Self-buffs ARE in the live player-enchantment registry, so we confirm + // them by reading it (no chat, no no-chat blacklisting that poisons the + // tier walk). Armor/item enchants are NOT in the player registry — they + // live on the item — so they still resolve via chat + the no-chat valve. + if (_pendingSpellId != 0) + { + var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + bool pendingIsArmor = pendingSpell != null && IsItemEnchantment(pendingSpell.Name); + + if (pendingSpell != null && !pendingIsArmor) + { + // SELF-BUFF: confirm against the live registry once the cast has + // settled. (OnEnchantmentAdded usually clears pending faster; this + // poll is the authoritative fallback when the hook doesn't fire.) + double sinceCastMs = (DateTime.Now - _lastCastAttempt).TotalMilliseconds; + if (sinceCastMs > SelfBuffConfirmMs + && (DateTime.Now - _lastSelfBuffPollAt).TotalMilliseconds > 250) + { + _lastSelfBuffPollAt = DateTime.Now; + RefreshFromLiveMemory(); + bool active = _ramBuffTimers.TryGetValue(pendingSpell.Family, out RamTimerInfo? st) + && st.Expiration > DateTime.Now; + if (active) + { + // During an auto-batch / force-rebuff, IsBuffActive gates on + // _forceRebuffCastFamilies (not timers), so the family MUST be + // marked cast here or the batch respins this buff forever. + if (_isForceRebuffing) _forceRebuffCastFamilies.Add(pendingSpell.Family); + _pendingSpellId = 0; // landed — registry confirms it; advance + NoteCastAccepted(); // it went through — end any too-busy backoff + _onCastResolved?.Invoke("self-buff confirmed (registry)"); + } + else if (sinceCastMs > SelfBuffGiveUpMs) + { + // Not in the registry after settling → this tier didn't take. + // A WARM snapshot already excludes unknown tiers, so a no-show + // is lag/fizzle → retry (NO blacklist). A COLD snapshot has no + // other tier-down signal → blacklist this id to drop a tier. + bool cold = !_spellManager.IsKnownSnapshotWarm; + if (cold) _spellManager.MarkSpellUnresolvable(_pendingSpellId); + + // Per-family silent-no-show bookkeeping (the /god loop break). + // Increment regardless of warmth — even the "warm → retry" path + // needs an upper bound, otherwise a buff whose family is in the + // dynamic list but can never actually land loops forever. + int fam = pendingSpell.Family; + int noShowCount = _silentNoShowCounts.TryGetValue(fam, out int prev) ? prev + 1 : 1; + _silentNoShowCounts[fam] = noShowCount; + bool parked = false; + if (noShowCount >= SilentNoShowThreshold) + { + _buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown; + parked = true; + } + + _host.Log($"[BuffDiag] self-buff '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) absent from live registry after {sinceCastMs:0}ms — " + + (cold ? "cold snapshot → blacklisted, tier-down." : "warm snapshot → retry (lag/fizzle).") + + $" noShows={noShowCount}/{SilentNoShowThreshold}" + + (parked ? $" — family parked {SilentNoShowCooldown.TotalMinutes:0}min." : "")); + _pendingSpellId = 0; + _onCastResolved?.Invoke("self-buff no-show (registry)"); + } + } + // Yield while the self-buff cast is in flight. PendingSpellId keeps + // the arbiter on Buffing, so CombatManager can't sneak a peace-mode + // switch in mid-cast. + if (_pendingSpellId != 0) return; + } + else if (pendingIsArmor) + { + // ARMOR/ITEM: chat is authoritative. No-chat valve abandons a cast + // AC never answers so the cycle can't wedge; the chat handlers do + // the cooldown. Blacklist (unless snapshot confirms known) drops tier. + if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds > NoChatResolveTimeoutMs) + { + int stuckId = _pendingSpellId; + var stuck = SpellTableStub.GetById(stuckId); + bool confirmedKnown = _spellManager.IsKnownSnapshotWarm && _spellManager.IsKnownSpellId(stuckId); + if (!confirmedKnown) + _spellManager.MarkSpellUnresolvable(stuckId); + + // 2026-05-25 — per-family silent-no-show bookkeeping on the + // ARMOR path, mirroring the self-buff path above. + // + // Without this, an armor enchant whose target item isn't + // wielded — for example after the character died and lost + // her armor — loops forever at the 5s no-chat timeout: + // AC accepts the cast attempt ("Casting Impenetrability + // VI"), can't bind it to an item, silently drops it, never + // produces success chat. confirmedKnown=True (Impen is in + // the spellbook), so the existing path logged "NOT + // blacklisted — lag/busy" and ForceRebuff re-fired the same + // cast 12+ times/minute. Every retry pushes "Casting " + // through AC's text pipeline, feeding the documented text- + // parser singleton race + // (rynthcore_crash_investigation.md 2026-05-25 entry). + // + // Park after SilentNoShowThreshold consecutive misses; the + // selectors at lines 763/823 honour _buffFailCooldownUntil + // so the family is skipped during the cooldown window. The + // bot keeps trying eventually — just not 12×/min while + // there's no armor to bind to. + int fam = stuck?.Family ?? 0; + bool parked = false; + if (fam != 0) + { + int noShowCount = _silentNoShowCounts.TryGetValue(fam, out int prev) ? prev + 1 : 1; + _silentNoShowCounts[fam] = noShowCount; + if (noShowCount >= SilentNoShowThreshold) + { + _buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown; + parked = true; + } + } + + _host.Log($"[BuffChat] NO-CHAT TIMEOUT (armor) pending={stuckId} ('{stuck?.Name}') — no chat in " + + $"{NoChatResolveTimeoutMs:0}ms. confirmedKnown={confirmedKnown}. " + + (confirmedKnown ? "Lag/busy — NOT blacklisted." : "Blacklisted → tier-down.") + + (fam != 0 ? $" noShows={_silentNoShowCounts[fam]}/{SilentNoShowThreshold}" : "") + + (parked ? $" — family parked {SilentNoShowCooldown.TotalMinutes:0}min." : "")); + _pendingSpellId = 0; + _onCastResolved?.Invoke("no-chat timeout (armor)"); + } + // Hold the cycle until chat resolves the item cast. + if (_pendingSpellId != 0) return; + } + } + + if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs) + return; + + // Don't issue a cast while the previous cast GESTURE is still animating. + // CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast + // gate). AC refuses a cast issued mid-gesture with a server-driven + // "You're too busy!" notice; the old code gated on BusyCount (the + // ClientUISystem hourglass) which reads 0 during a cast, so it never + // blocked the retry → tight refusal loop → AddTextToScroll re-entry AV + // at 0x00460D1D. On an engine without the gate, CanCastNow defaults to + // true and the SpellCastIntervalMs throttle + parked-pending still bound + // retries. BusyCount stays as a secondary guard so we also don't queue + // casts/UseObject while the hourglass action is mid-flight. + // Buffing priority (including "hold it while our cast is in flight so + // CombatManager can't sneak in a peace-mode switch mid-cast") is the + // arbiter's call now — it reads PendingSpellId / WantsVitalRecharge / + // NeedsAnyBuff and is the sole writer of the "Buffing" string. + if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) || BusyCount > 0) + { + LastBuffSkipReason = BusyCount > 0 ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)"; + return; + } + + if (CheckVitals()) + return; + + // Too-busy backoff gates BUFFING only, and sits after CheckVitals on + // purpose: a refused heal is worth retrying hard, a refused buff is not. + // Blocking vitals here would have delayed emergency heals by up to 8s, + // and the observed refusal episode happened while the character was being + // swarmed by Olthoi — exactly when that would be most dangerous. + // Wait for the server to finish the previous cast before issuing another. + // Sits with the backoff, after CheckVitals, so it paces BUFFING only — a + // heal must never queue behind a buff's resolution. + if (IsAwaitingCastResolution()) + { + LastBuffSkipReason = "awaiting server UseDone for the previous cast"; + return; + } + + if (DateTime.Now < _busyBackoffUntil) + { + LastBuffSkipReason = $"too-busy backoff ({(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0}ms left, streak={_busyRefusalStreak})"; + return; + } + + if (_settings.EnableBuffing) + { + if (CheckAndCastSelfBuffs()) + return; + + if (_isForceRebuffing) + { + _isForceRebuffing = false; + _host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families"); + // Order matters: the flag must already be false (IsBuffActive + // short-circuits on _forceRebuffCastFamilies while it is set, so + // every family would read "active"), and the set must still be + // populated — it is what the audit iterates. + AuditBatchSatisfied(); + _forceRebuffCastFamilies.Clear(); + _host.WriteToChat("[RynthAi] Force Rebuff Complete.", 1); + } + } + } + + /// + /// Post-batch audit. Every family the batch actually CAST should read active + /// now that the batch is over. One that doesn't is not going to be fixed by + /// casting it again: the cast goes out, AC confirms it, the enchantment is + /// genuinely on the character, and IsBuffActive still says false. + /// + /// The case this was written for: a permanent item-granted lower tier living + /// in the same spell family as the tier we want, which keeps the tier-upgrade + /// rule firing no matter how many times the higher tier lands. Because ANY + /// single buff below threshold escalates to a full rebuff, one such family is + /// enough to make the bot recast every buff it owns, back-to-back, forever. + /// + /// Park the family after UnsatisfiedStrikeThreshold consecutive batches. This + /// is a backstop, not the cure — it bounds the damage from any future + /// "lands but never reads active" bug rather than one specific cause. + /// + /// Must be called with _isForceRebuffing already false: while it is set, + /// IsBuffActive answers from _forceRebuffCastFamilies and every family in + /// that set reads active by construction. + /// + /// Stored expiry for a family across BOTH timer dictionaries + /// (player buffs in _ramBuffTimers, item enchants in _itemSpellTimers), or + /// DateTime.MinValue when the family has no timer at all. + private DateTime CurrentExpiryFor(int family) + { + if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)) return t.Expiration; + if (_itemSpellTimers.TryGetValue(family, out ItemSpellRecord? i)) return i.ExpiresAt; + return DateTime.MinValue; + } + + private void AuditBatchSatisfied() + { + foreach (int family in _forceRebuffCastFamilies) + { + if (!_lastCastSpellIdByFamily.TryGetValue(family, out int spellId) || spellId == 0) + continue; + + if (IsBuffActive(spellId)) + { + _unsatisfiedStrikes.Remove(family); // satisfied — forget past strikes + continue; + } + + // Give the refresh time to reach the registry before judging. A cast + // issued seconds ago legitimately still reads its old timer. + if (!_castIssuedAtByFamily.TryGetValue(family, out DateTime castAt) + || (DateTime.Now - castAt).TotalMilliseconds < AuditSettleMs) + continue; + + // The expiry moved forward, so the cast DID land — this family is + // simply still inside the rebuff window for some other reason (a + // duration shorter than RebuffSecondsRemaining, say). Not "cast that + // never takes effect", so it must not accumulate strikes. + DateTime expiryNow = CurrentExpiryFor(family); + if (_expiryAtCastByFamily.TryGetValue(family, out DateTime expiryThen) + && expiryNow > expiryThen) + { + _unsatisfiedStrikes.Remove(family); + continue; + } + + string name = SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString(); + int strikes = _unsatisfiedStrikes.TryGetValue(family, out int prev) ? prev + 1 : 1; + _unsatisfiedStrikes[family] = strikes; + + if (strikes < UnsatisfiedStrikeThreshold) + { + _host.Log($"[BuffDiag] batch audit: '{name}' (id={spellId}, fam={family}) was cast this batch but still reads inactive — strike {strikes}/{UnsatisfiedStrikeThreshold}."); + continue; + } + + _unsatisfiedStrikes.Remove(family); + _buffFailCooldownUntil[family] = DateTime.Now + SilentNoShowCooldown; + + // Spell out the stored timer: the two causes that produce this look + // identical from the outside. Either a lower-tier enchantment is + // stuck in the family (storedLvl below the tier we cast), or + // RebuffSecondsRemaining is set above this spell's own duration, so + // it is "due for recast" the instant it lands. The numbers below + // separate them at a glance. + string stored = _ramBuffTimers.TryGetValue(family, out RamTimerInfo? t) + ? $"stored='{t.SpellName}' lvl={t.SpellLevel} remainSec={(t.IsPermanent ? "permanent" : (t.Expiration - DateTime.Now).TotalSeconds.ToString("F0"))}" + : "no timer entry"; + _host.Log($"[BuffDiag] batch audit: '{name}' (id={spellId}, fam={family}) lands but never reads active after {UnsatisfiedStrikeThreshold} batches — " + + $"parking {SilentNoShowCooldown.TotalMinutes:0}min so it can't drive continuous rebuff cycles. " + + $"{stored}, rebuffThresholdSec={_settings.RebuffSecondsRemaining}."); + } + } + + private bool CheckVitals() + { + int curHealthPct = _vitals.HealthPct; + int curManaPct = _vitals.ManaPct; + int curStamPct = _vitals.StaminaPct; + + // Reset per-tick recharge flags; they reflect "would recharge right now" + // and are repopulated from the predicates below. The /ra buff snapshot + // reads these for diagnostics. + _isHealingSelf = false; + _isRechargingMana = false; + _isRechargingStamina = false; + + // Emergency override regardless of mode: HP critical + stam available → + // burn stam for HP. Sits below the configurable thresholds so even a + // "do nothing" recharge config still saves the character. + if (curHealthPct <= 30 && curStamPct > 20) + { + _isHealingSelf = true; + return AttemptVitalCast("Stamina to Health Self"); + } + + // Pick the threshold set based on hunting state. A target within + // MonsterRange = active combat → react at the LOW (HealAt / RestamAt / + // GetManaAt) thresholds so we don't bloat cast traffic mid-fight. + // Otherwise idle → top up to the HIGH (TopOffHP / TopOffStam / + // TopOffMana) thresholds so we re-engage at full. Thresholds are + // strict "<": set a value to 0 to disable that vital in that mode. + bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true; + int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP; + int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana; + int stamThreshold = inCombat ? _settings.RestamAt : _settings.TopOffStam; + + _isHealingSelf = curHealthPct < hpThreshold; + _isRechargingMana = curManaPct < manaThreshold; + _isRechargingStamina = curStamPct < stamThreshold; + + if (_isHealingSelf) + { + if (AttemptHealthKitUse()) return true; + return AttemptVitalCast("Heal Self"); + } + if (_isRechargingMana && curStamPct > 15) return AttemptVitalCast("Stamina to Mana Self"); + if (_isRechargingStamina) return AttemptVitalCast("Revitalize Self"); + + return false; + } + + private bool AttemptVitalCast(string baseName) + { + int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic); + if (spellId == 0) return false; + if (!EnsureMagicMode()) return true; + _pendingSpellId = spellId; + _host.CastSpell((uint)_host.GetPlayerId(), spellId); + _lastCastAttempt = DateTime.Now; + NoteCastIssued(); + return true; + } + + private bool AttemptHealthKitUse() + { + if (_worldObjectCache == null) return false; + + foreach (var rule in _settings.ConsumableRules) + { + if (!rule.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)) + continue; + + if (_worldObjectCache[rule.Id] == null) + continue; + + uint playerId = _host.GetPlayerId(); + if (playerId == 0) return false; + _host.UseObjectOn(unchecked((uint)rule.Id), playerId); + _lastCastAttempt = DateTime.Now; + return true; + } + + return false; + } + + /// + /// Returns true if any self-buff in the current buff list is missing/expired, + /// without actually casting. Used by NeedToBuff meta condition. + /// + public bool NeedsAnyBuff() + { + if (!_settings.EnableBuffing) return false; + return _isForceRebuffing || AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining); + } + + // Returns true if any castable buff in the list has < thresholdSec remaining. + // Used both as the arbiter query (NeedsAnyBuff) and as the batch-rebuff trigger + // inside CheckAndCastSelfBuffs — keeps the two in sync on when buffing is needed. + // Families currently parked in _buffFailCooldownUntil are skipped so a parked + // family can't keep retriggering the batch (which would otherwise loop: + // batch starts → clears cooldown → cast again → silent no-show → re-park). + private bool AnyBuffBelowThreshold(List desiredBuffs, int thresholdSec) + { + DateTime now = DateTime.Now; + foreach (string buffBaseName in desiredBuffs) + { + AcSkillType castSkill = SkillForBuff(buffBaseName); + if (!IsSkillUsable(castSkill)) continue; + int spellId = FindBestSpellId(buffBaseName, castSkill); + if (spellId == 0) continue; + int family = SpellTableStub.GetById(spellId)?.Family ?? 0; + if (family != 0 + && _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil) + && now < coolUntil) + continue; + if (!IsBuffActive(spellId, thresholdSec)) return true; + } + return false; + } + + private bool CheckAndCastSelfBuffs() + { + // Auto batch-rebuff: when any buff drops below the configured threshold, + // trigger a full rebuff so ALL timers re-align in one session rather than + // each buff trickling in one at a time as it individually expires. + if (!_isForceRebuffing && AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining)) + { + // Batch trigger — reuse FR family-tracking but do NOT clear timers. + // ForceFullRebuff clears _ramBuffTimers, which causes an immediate + // re-trigger: any spell that can't be resolved (spellId=0) never + // gets a timer recorded, so the next AnyBuffBelowThreshold call sees + // "no timer = below threshold" and loops forever. + // Also do NOT clear _buffFailCooldownUntil here. Auto-batch must + // respect parked families (chat hard-rejects + silent no-shows); + // only an explicit ForceFullRebuff resets them. Without this, + // /god kicks off auto-batch → cooldown cleared → cast → silent + // no-show → re-park → another auto-batch → loop. Hard-reject + // cooldowns are short-lived (120s) so they expire on their own. + _isForceRebuffing = true; + _forceRebuffCastFamilies.Clear(); + } + + List desiredBuffs = BuildDynamicBuffList(); + bool diagnose = _isForceRebuffing; + + foreach (string buffBaseName in desiredBuffs) + { + AcSkillType castSkill = SkillForBuff(buffBaseName); + if (!IsSkillUsable(castSkill)) + { + LastBuffSkipReason = $"skill not usable: {buffBaseName} ({castSkill})"; + if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — skill {castSkill} not usable"); + continue; + } + + int spellId = FindBestSpellId(buffBaseName, castSkill); + if (spellId == 0) + { + LastBuffSkipReason = $"not known / unresolvable: {buffBaseName}"; + if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — FindBestSpellId returned 0"); + continue; + } + + if (IsBuffActive(spellId)) + { + LastBuffSkipReason = $"already active: {buffBaseName} (id={spellId})"; + if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — already active"); + continue; + } + + // Skip a family the server just hard-rejected (no components, etc.) + // so an uncastable buff isn't re-cast every cycle (→ AC AV). Auto- + // recovers when the cooldown expires or a cast of it later confirms. + int buffFamily = SpellTableStub.GetById(spellId)?.Family ?? 0; + if (buffFamily != 0 + && _buffFailCooldownUntil.TryGetValue(buffFamily, out DateTime coolUntil) + && DateTime.Now < coolUntil) + { + LastBuffSkipReason = $"fail-cooldown: {buffBaseName} (fam={buffFamily}, {(coolUntil - DateTime.Now).TotalSeconds:0}s)"; + if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s"); + continue; + } + + if (!EnsureMagicMode(forBuff: true)) + { + if (_wandSwapExhausted) + { + // FIX: the bow->wand swap provably can't succeed right now (no open + // pack / repeated fails). Park THIS family in the existing per-family + // cooldown so AnyBuffBelowThreshold + this selector skip it -> + // NeedsAnyBuff() goes false -> the arbiter stops picking Buffing + // -> combat runs. Buffing stays top priority; only the impossible + // family is shelved, time-boxed, and auto-retried. + if (buffFamily != 0) + _buffFailCooldownUntil[buffFamily] = DateTime.Now.AddSeconds(BuffFailCooldownSec); + LastBuffSkipReason = $"wand-swap exhausted: {buffBaseName} (fam={buffFamily})"; + _host.Log($"[WieldGate] wand-swap exhausted for '{buffBaseName}' (fam={buffFamily}) — parking {BuffFailCooldownSec:0}s, fighting unbuffed"); + continue; + } + LastBuffSkipReason = "magic-mode swap in progress (yielding tick)"; + return true; // normal in-progress swap — yield the tick (NeedsAnyBuff still holds Buffing) + } + + _pendingSpellId = spellId; + if (buffFamily != 0) + { + _lastCastSpellIdByFamily[buffFamily] = spellId; + _castIssuedAtByFamily[buffFamily] = DateTime.Now; + _expiryAtCastByFamily[buffFamily] = CurrentExpiryFor(buffFamily); + } + + var spellInfo = SpellTableStub.GetById(spellId); + if (spellInfo != null) + _host.WriteToChat($"[RynthAi] Casting: {spellInfo.Name}", 5); + // NOTE: timers are recorded ONLY on chat confirmation ("you cast X"), + // never optimistically here. An optimistic item-timer at cast time + // left a phantom 1h "active" buff whenever a cast silently failed + // (e.g. an unknown higher tier), so the bot thought armor was + // buffed when it wasn't and never retried the known tier. + + if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)"); + bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId); + _lastCastAttempt = DateTime.Now; + if (castOk) NoteCastIssued(); + if (!castOk) + { + // Local CastSpell rejected — packet never went out, so no chat + // will ever arrive. Clear the gate immediately so the cycle + // doesn't hang on this spell. (No timer to undo — we no longer + // record optimistically.) + _pendingSpellId = 0; + LastBuffSkipReason = $"local CastSpell rejected: {buffBaseName} (id={spellId})"; + if (diagnose) _host.Log($"[FR] cast '{buffBaseName}' returned false — pending cleared"); + } + return true; + } + return false; + } + + private int FindBestSpellId(string baseName, AcSkillType skill) + => _spellManager.GetDynamicSelfBuffId(baseName, skill); + + // True for enchantments that live on an ITEM (armor or weapon), NOT on the + // player. These do NOT appear in ReadPlayerEnchantments, so they must be + // confirmed via chat, stored in _itemSpellTimers, and PRESERVED across a + // RefreshFromLiveMemory (which rebuilds player buffs from the live registry + // and would otherwise wipe them → perpetual recast = "buffing in circles"). + // Matches base names AND tier-7 lore / "Aura of" forms. + private static bool IsItemEnchantment(string name) + { + string[] itemSpells = { + // Armor: Impenetrability + Brogard's, and the elemental/physical Banes + "Impenetrability", "Brogard's Defiance", "Acid Bane", "Olthoi's Bane", + "Blade Bane", "Swordsman's Bane", "Swordman's Bane", "Bludgeoning Bane", "Tusker's Bane", + "Flame Bane", "Inferno's Bane", "Frost Bane", "Gelidite's Bane", + "Lightning Bane", "Astyrrian's Bane", "Piercing Bane", "Archer's Bane", + // Weapon auras: base names cover "Aura of X Self N" / "Incantation of X Self"; + // the explicit lore names cover the tier-7 forms that drop the base word. + "Blood Drinker", "Aura of Infected Caress", + "Hermetic Link", "Aura of Mystic's Blessing", + "Heart Seeker", "Aura of Elysa's Sight", + "Spirit Drinker", "Aura of Infected Spirit Carress", "Aura of Infected Spirit Caress", + "Swift Killer", "Aura of Atlan's Alacrity", + "Defender", "Aura of Cragstone's Will", + }; + foreach (string s in itemSpells) + if (name.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + /// + /// Called immediately when CheckAndCastSelfBuffs decides to cast an item spell. + /// Records the timer optimistically — removed on fizzle. + /// + private void RecordItemSpellCast(SpellInfo spellInfo) + { + int level = GetSpellLevel(spellInfo); + double duration = GetCustomSpellDuration(level); + var now = DateTime.Now; + _itemSpellTimers[spellInfo.Family] = new ItemSpellRecord + { + CastAt = now, + ExpiresAt = now.AddSeconds(duration), + SpellName = spellInfo.Name, + SpellLevel = level, + }; + // Pair with [BuffDiag] armor-recast logs so we can match record vs lookup. + _lastArmorRecastReason.Remove(spellInfo.Family); // allow next recast to re-log + _host.Log($"[BuffDiag] RECORD '{spellInfo.Name}' (id={spellInfo.Id}, fam={spellInfo.Family}, lvl={level}, durSec={duration:F0}, expiresAt={now.AddSeconds(duration):HH:mm:ss})"); + SaveBuffTimers(); + + if (EnableCastRegistryDiagnostic) + CapturePreCastDiagnostic(spellInfo); + } + + private void CapturePreCastDiagnostic(SpellInfo spellInfo) + { + try + { + var diag = new CastDiagnostic + { + CastedAt = DateTime.Now, + SpellName = spellInfo.Name, + SpellId = spellInfo.Id, + SpellFamily = spellInfo.Family, + PreSnapshots = SnapshotRegistries(), + }; + _pendingDiagnostics.Enqueue(diag); + _host.Log($"[BuffTest] PRE-CAST '{spellInfo.Name}' (id={spellInfo.Id}, fam={spellInfo.Family}) " + + $"snapshots={diag.PreSnapshots.Count} queued={_pendingDiagnostics.Count}"); + } + catch (Exception ex) + { + _host.Log($"[BuffTest] Pre-cast snapshot failed: {ex.GetType().Name}: {ex.Message}"); + } + } + + private List SnapshotRegistries() + { + var snaps = new List(); + double serverNow = _host.HasGetServerTime ? _host.GetServerTime() : 0; + + // Player registry — known-safe path. + if (_host.HasReadPlayerEnchantments) + { + const int Max = 256; + var sids = new uint[Max]; + var exp = new double[Max]; + int n = _host.ReadPlayerEnchantments(sids, exp, Max); + snaps.Add(new RegistrySnapshot + { + OwnerId = (uint)_host.GetPlayerId(), + OwnerName = "Player", + IsPlayer = true, + SpellIds = sids, + ExpiryTimes = exp, + Count = Math.Max(0, n), + ServerTime = serverNow, + }); + } + + // Equipped-item registries — opt-in via the diagnostic flag. + // Equipped items are stable in the cache (filter avoids the freshly-arrived + // inventory items that triggered the AV in earlier RefreshEquippedItemEnchantments runs). + if (_worldObjectCache != null && _host.HasReadObjectEnchantments) + { + var equipped = new List(); + foreach (var item in _worldObjectCache.GetDirectInventory()) + { + if (item.WieldedLocation == 0) continue; + equipped.Add(item); + } + + const int Max = 64; + foreach (var item in equipped) + { + uint oid = unchecked((uint)item.Id); + var sids = new uint[Max]; + var exp = new double[Max]; + int n; + try + { + n = _host.ReadObjectEnchantments(oid, sids, exp, Max); + } + catch + { + continue; + } + snaps.Add(new RegistrySnapshot + { + OwnerId = oid, + OwnerName = item.Name, + IsPlayer = false, + SpellIds = sids, + ExpiryTimes = exp, + Count = Math.Max(0, n), + ServerTime = serverNow, + }); + } + } + + return snaps; + } + + private void LogPostCastDiff(CastDiagnostic diag) + { + try + { + var post = SnapshotRegistries(); + _host.Log($"[BuffTest] === POST-CAST DIFF for '{diag.SpellName}' (id={diag.SpellId}, fam={diag.SpellFamily}) ==="); + _host.WriteToChat($"[BuffTest] Post-cast diff captured for '{diag.SpellName}' — see RynthCore.log", 1); + + foreach (var pre in diag.PreSnapshots) + { + RegistrySnapshot? match = null; + foreach (var p in post) + if (p.OwnerId == pre.OwnerId) { match = p; break; } + + if (match == null) + { + _host.Log($"[BuffTest] {pre.OwnerName} (0x{pre.OwnerId:X8}): post-snapshot missing"); + continue; + } + + var preIds = new HashSet(); + for (int i = 0; i < pre.Count; i++) preIds.Add(pre.SpellIds[i]); + + int newCount = 0; + int matchedTargetSpell = -1; + _host.Log($"[BuffTest] {match.OwnerName} (0x{match.OwnerId:X8}): pre={pre.Count} post={match.Count} serverNow={match.ServerTime:F1}"); + + for (int i = 0; i < match.Count; i++) + { + uint sid = match.SpellIds[i]; + if (preIds.Contains(sid)) continue; + newCount++; + var sp = SpellTableStub.GetById((int)sid); + string nm = sp?.Name ?? "?"; + int fam = sp?.Family ?? -1; + double remaining = match.ExpiryTimes[i] - match.ServerTime; + _host.Log($"[BuffTest] +new spell={sid} ('{nm}') fam={fam} expiry={match.ExpiryTimes[i]:F1} remaining={remaining:F1}s"); + if (sid == (uint)diag.SpellId || fam == diag.SpellFamily) matchedTargetSpell = i; + } + + if (newCount == 0) + _host.Log($"[BuffTest] (no new entries)"); + else if (matchedTargetSpell >= 0) + { + double remaining = match.ExpiryTimes[matchedTargetSpell] - match.ServerTime; + bool hasDuration = remaining > 0.5 && remaining < (86400 * 365); + _host.Log($"[BuffTest] >>> TARGET SPELL MATCHED: remaining={remaining:F1}s hasRealDuration={hasDuration}"); + } + } + + _host.Log("[BuffTest] === END DIFF ==="); + } + catch (Exception ex) + { + _host.Log($"[BuffTest] Post-cast diff failed: {ex.GetType().Name}: {ex.Message}"); + } + } + + private bool IsBuffActive(int spellId, int? rebufferSecOverride = null) + { + var targetSpell = SpellTableStub.GetById(spellId); + if (targetSpell == null) return false; + + // Force Rebuff: ignore live timers entirely — only spells we've already + // cast THIS rebuff cycle count as "active". The whole point of FR is to + // recast every spell so all timers align to the same start time. + if (_isForceRebuffing) + return _forceRebuffCastFamilies.Contains(targetSpell.Family); + + int targetLevel = GetSpellLevel(targetSpell); + // Recast when remaining duration drops below this many seconds. + // User-configurable via Advanced Settings → Buffing; overridden during + // batch-rebuff passes (CheckAndCastSelfBuffs) to 1200s (20 min). + int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining); + + // Tier-upgrade rule (applies to both item enchantments and player buffs): + // if a better-tier spell is now available than what's currently active, + // treat the buff as inactive and recast immediately — regardless of how + // much time is left. Silent: callers like NeedsAnyBuff poll IsBuffActive + // every tick, so logging here would spam. The actual cast announces + // itself via the existing "Casting: X" line in CheckAndCastSelfBuffs. + + // Item spells (armor banes, Impenetrability) tracked in their own dictionary. + if (IsItemEnchantment(targetSpell.Name)) + { + if (_itemSpellTimers.TryGetValue(targetSpell.Family, out ItemSpellRecord? itemTimer)) + { + if (itemTimer.SpellLevel < targetLevel) + { + LogArmorRecast(targetSpell, $"tier-upgrade recordedLvl={itemTimer.SpellLevel} < targetLvl={targetLevel} (recorded='{itemTimer.SpellName}')"); + return false; + } + if (DateTime.Now < itemTimer.ExpiresAt.AddSeconds(-rebufferSec)) + { + _lastArmorRecastReason.Remove(targetSpell.Family); // clear so next recast re-logs + return true; + } + double remainSec = (itemTimer.ExpiresAt - DateTime.Now).TotalSeconds; + LogArmorRecast(targetSpell, $"expiry-window remainSec={remainSec:F0} threshold={rebufferSec} (recorded='{itemTimer.SpellName}' lvl={itemTimer.SpellLevel} expiresAt={itemTimer.ExpiresAt:HH:mm:ss})"); + } + else + { + LogArmorRecast(targetSpell, $"NO timer entry for family={targetSpell.Family} (targetLvl={targetLevel}, _itemSpellTimers.Count={_itemSpellTimers.Count})"); + } + return false; + } + + // Player buffs — use RAM timers + if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo? timer)) + { + // Tier-upgrade flap guard: many high-tier buffs are Incantations + // (nominal tier 8) that LAND at a lower, skill-capped tier — e.g. + // "Incantation of Sprint Self" (target 8) lands as "Sprint Self VI" + // (6). Comparing the landed 6 against the nominal 8 makes the + // upgrade rule fire forever → endless recast. Cap the target at the + // highest tier we've actually observed land for this family, so once + // the Incantation lands at its real ceiling we stop chasing 8. + int effectiveTarget = targetLevel; + if (_familyAchievedTier.TryGetValue(targetSpell.Family, out int achieved) && achieved < effectiveTarget) + effectiveTarget = achieved; + + if (timer.SpellLevel < effectiveTarget) + { + LogPlayerRecast(targetSpell, $"tier-upgrade storedLvl={timer.SpellLevel} < effTarget={effectiveTarget} (nominal={targetLevel}, achievedCap={(_familyAchievedTier.TryGetValue(targetSpell.Family, out int a2) ? a2 : -1)}, stored='{timer.SpellName}')"); + return false; + } + if (DateTime.Now < timer.Expiration.AddSeconds(-rebufferSec)) + { + _lastArmorRecastReason.Remove(targetSpell.Family); + return true; + } + double remainSec = (timer.Expiration - DateTime.Now).TotalSeconds; + LogPlayerRecast(targetSpell, $"expiry-window remainSec={remainSec:F0} threshold={rebufferSec} storedLvl={timer.SpellLevel} exp={timer.Expiration:HH:mm:ss} (stored='{timer.SpellName}')"); + } + else + { + LogPlayerRecast(targetSpell, $"NO ram-timer entry for family={targetSpell.Family} (targetLvl={targetLevel}, _ramBuffTimers.Count={_ramBuffTimers.Count})"); + } + + if (_isForceRebuffing) return false; + + return false; + } + + // Player-buff counterpart to LogArmorRecast — explains why a character + // self-buff (Impregnability/Aura of Deflection, masteries, etc.) is judged + // inactive. Throttled per-family (IsBuffActive is polled every tick). + private void LogPlayerRecast(SpellInfo targetSpell, string reason) + { + if (_lastArmorRecastReason.TryGetValue(targetSpell.Family, out string? prev) && prev == reason) + return; + _lastArmorRecastReason[targetSpell.Family] = reason; + _host.Log($"[BuffDiag] player-recast '{targetSpell.Name}' (id={targetSpell.Id}, fam={targetSpell.Family}): {reason}"); + } + + /// + /// Remember the highest tier a family has actually LANDED at (read from the + /// live registry, never from the cast name — an Incantation echoes its + /// nominal tier in chat but lands skill-capped). Capping the upgrade target + /// at this in IsBuffActive stops the endless "tier 6 < tier 8" recast flap. + /// + private void RecordAchievedTier(int family, int landedLevel) + { + if (landedLevel <= 0) return; + if (!_familyAchievedTier.TryGetValue(family, out int cur) || landedLevel > cur) + _familyAchievedTier[family] = landedLevel; + } + + private void LogArmorRecast(SpellInfo targetSpell, string reason) + { + // Throttle: only log when reason changes for this family — IsBuffActive + // is polled every tick, so unconditional logging would flood RynthCore.log. + if (_lastArmorRecastReason.TryGetValue(targetSpell.Family, out string? prev) && prev == reason) + return; + _lastArmorRecastReason[targetSpell.Family] = reason; + _host.Log($"[BuffDiag] armor-recast '{targetSpell.Name}' (id={targetSpell.Id}, fam={targetSpell.Family}): {reason}"); + } + + private static int GetSpellLevel(SpellInfo spell) + { + string n = spell.Name; + if (n.StartsWith("Incantation")) return 8; + if (n.Contains(" VIII")) return 8; // must precede " VII" — "X VIII".Contains(" VII") is true + if (n.Contains(" VII")) return 7; + if (n.Contains(" VI")) return 6; + if (n.Contains(" V")) return 5; + if (n.Contains(" IV")) return 4; + if (n.Contains(" III")) return 3; + if (n.Contains(" II")) return 2; + if (n.EndsWith(" I") || n.Contains(" I ")) return 1; + + if (n.Contains("Mastery") || n.Contains("Blessing") || n.Contains("Aura of") || + n.Contains("Intervention") || n.Contains("Trance") || n.Contains("Recovery") || + n.Contains("Robustify") || n.Contains("Persistence") || n.Contains("Robustification") || + n.Contains("Might of the Lugians") || n.Contains("Preservance") || n.Contains("Perseverance") || + n.Contains("Honed Control") || n.Contains("Hastening") || n.Contains("Inner Calm") || + n.Contains("Mind Blossom") || n.Contains("Infected Caress") || n.Contains("Elysa's Sight") || + n.Contains("Infected Spirit") || n.Contains("Atlan's Alacrity") || n.Contains("Cragstone's Will") || + n.Contains("Brogard's Defiance") || n.Contains("Olthoi's Bane") || n.Contains("Swordsman's Bane") || + n.Contains("Swordman's Bane") || n.Contains("Tusker's Bane") || n.Contains("Inferno's Bane") || + n.Contains("Gelidite's Bane") || n.Contains("Astyrrian's Bane") || n.Contains("Archer's Bane")) + return 7; + + return 1; + } + + private int _archmageAugs = -1; // -1 = not read yet + private long _archmageAugsReadAt; + + /// + /// Ranks of Archmage's Endurance (AUGMENTATION_INCREASED_SPELL_DURATION, 5x, + /// +20% enchantment duration each). Was hardcoded to 0, so every duration on an + /// augmented character was 20-100% short and armor banes/auras recast early + /// (2026-06-03 audit P1#3). + /// + /// Fails closed to 0 — the previous behaviour — whenever the property can't be + /// read, and clamps to the game's 5-rank cap so a bad read can't inflate a + /// duration past 2x and leave the character silently unbuffed. + /// + private int GetArchmageEnduranceCount() + { + long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + // Augs change at most once per purchase; re-read occasionally so buying one + // mid-session takes effect without paying for a property read per call. + if (_archmageAugs >= 0 && now - _archmageAugsReadAt < 60000) return _archmageAugs; + + if (!_host.HasGetObjectIntProperty) return _archmageAugs > 0 ? _archmageAugs : 0; + + uint playerId = _host.GetPlayerId(); + if (playerId == 0) return _archmageAugs > 0 ? _archmageAugs : 0; + + if (!_host.TryGetObjectIntProperty( + playerId, (uint)LongValueKey.AugmentationIncreasedSpellDuration, out int augs)) + return _archmageAugs > 0 ? _archmageAugs : 0; + + augs = Math.Clamp(augs, 0, 5); + if (augs != _archmageAugs) + _host.Log($"[Buff] Archmage's Endurance rank {augs}/5 — enchantment durations x{1.0 + augs * 0.20:0.00}"); + + _archmageAugs = augs; + _archmageAugsReadAt = now; + return augs; + } + + private double GetCustomSpellDuration(int spellLevel) + { + double baseSeconds = 1800; + if (spellLevel == 6) baseSeconds = 2700; + else if (spellLevel == 7) baseSeconds = 3600; + else if (spellLevel == 8) baseSeconds = 5400; + + int augs = GetArchmageEnduranceCount(); + return baseSeconds * (1.0 + (augs * 0.20)); + } + + /// + /// Reads active enchantments directly from client memory and refreshes _ramBuffTimers. + /// Requires both HasReadPlayerEnchantments and HasGetServerTime to be available. + /// Returns the number of timers updated, or -1 if the API is unavailable. + /// + public int RefreshFromLiveMemory() + { + if (!_host.HasReadPlayerEnchantments || !_host.HasGetServerTime) + return -1; + + double serverNow = _host.GetServerTime(); + if (serverNow <= 0) + return -1; // No time sync received yet + + const int MaxEnchantments = 512; + uint[] spellIds = new uint[MaxEnchantments]; + double[] expiryTimes = new double[MaxEnchantments]; + + int count = _host.ReadPlayerEnchantments(spellIds, expiryTimes, MaxEnchantments); + if (count < 0) + return -1; + + // Preserve item enchantment timers (armor banes, Impenetrability, etc.) + // that live on the item, not the player — ReadPlayerEnchantments won't + // return them, so clearing would lose them every login. + var preservedItemTimers = new Dictionary(); + foreach (var kvp in _ramBuffTimers) + { + if (kvp.Value.Expiration > DateTime.Now && IsItemEnchantment(kvp.Value.SpellName)) + preservedItemTimers[kvp.Key] = kvp.Value; + } + + _ramBuffTimers.Clear(); + for (int i = 0; i < count; i++) + { + var spellInfo = SpellTableStub.GetById((int)spellIds[i]); + if (spellInfo == null) + { + _host.Log($"[BuffDiag] refresh DROP: id={spellIds[i]} unresolved by SpellTableStub (no name) — would never re-add to RAM timers"); + continue; + } + + double remainingSeconds = expiryTimes[i] - serverNow; + if (remainingSeconds <= 0) + { + _host.Log($"[BuffDiag] refresh DROP: id={spellIds[i]} '{spellInfo.Name}' fam={spellInfo.Family} remainSec={remainingSeconds:F0} (expiry={expiryTimes[i]:F0} serverNow={serverNow:F0}) — treated as expired"); + continue; + } + + // A permanent player enchantment: the engine reports no expiry + // (double.MaxValue). It IS active right now — record it as a + // presence-only entry instead of dropping it (the old code + // skipped it here, so the family never recorded → IsBuffActive + // false → recast every refresh forever). This is rebuilt from the + // live registry every cycle: on death or a dispel trap the enchant + // leaves the registry, the next read won't return it, the family + // drops, and the bot rebuffs. IsPermanent keeps it out of + // SaveBuffTimers so a relog can't resurrect a stripped buff. + bool isPermanent = remainingSeconds > 86400 * 365; + + int level = GetSpellLevel(spellInfo); + var candidate = new RamTimerInfo + { + Expiration = isPermanent ? PermanentSentinel : DateTime.Now.AddSeconds(remainingSeconds), + SpellLevel = level, + SpellName = spellInfo.Name, + IsPermanent = isPermanent, + }; + + // A family can hold MORE THAN ONE live enchantment at once. The real + // case: a permanent item-granted "Armor Tinkering Expertise Self VI" + // (id=707, no expiry) sitting in the same family as the tier-7 + // "Jibril's Blessing" (id=2197) we cast. AC applies the STRONGEST, so + // that is what the timer must reflect. + // + // This used to assign unconditionally, so whichever entry the registry + // happened to return LAST won. When that was the lower permanent tier, + // the stored level (6) stayed below the target (7) forever and the + // tier-upgrade rule in IsBuffActive fired on every poll — and because + // the recast lands, confirms, and is then immediately clobbered again + // by the next refresh, nothing ever broke the cycle. One family stuck + // like this drags the whole auto-batch with it (a single buff below + // threshold escalates to a full rebuff), which is how a ~65-spell + // rebuff ended up running back-to-back indefinitely. + // + // Keep the higher tier; on a tie keep whichever lasts longer + // (PermanentSentinel naturally sorts last, so a permanent entry wins + // a tie against a timed one of the same tier). + bool keepExisting = + _ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? seen) + && (seen.SpellLevel > level + || (seen.SpellLevel == level && seen.Expiration >= candidate.Expiration)); + + if (!keepExisting) + _ramBuffTimers[spellInfo.Family] = candidate; + + // Learn the real ceiling this family lands at (Incantations cap below + // their nominal tier) so IsBuffActive stops chasing an unreachable tier. + // Recorded for EVERY entry read, including one the merge above + // discarded — the ceiling is about what this character can land, not + // about which entry currently wins the family slot. + RecordAchievedTier(spellInfo.Family, level); + + if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family)) + _host.Log($"[BuffDiag] permanent player enchant tracked: id={spellInfo.Id} '{spellInfo.Name}' (fam={spellInfo.Family}, lvl={level}) — presence-only, not persisted" + + (keepExisting + ? $" — outranked in this family by '{seen!.SpellName}' (lvl={seen.SpellLevel}), which owns the timer" + : "")); + } + + // Restore item enchantment timers that weren't covered by player enchantments + foreach (var kvp in preservedItemTimers) + _ramBuffTimers.TryAdd(kvp.Key, kvp.Value); + + SaveBuffTimers(); + // NOTE: do NOT set _liveBuffsRefreshed here. The login gate in OnHeartbeat + // owns that flag and only opens it once the enchantment count STABILIZES + // across consecutive reads. Setting it here let the first partial/empty + // login read open the gate early → timers wiped → full rebuff every login. + return _ramBuffTimers.Count; + } + + /// + /// Scans all equipped items and reads their enchantment registries. + /// Tracks item-specific buffs (Impenetrability, Banes, etc.) separately from player buffs. + /// + private void RefreshEquippedItemEnchantments(double serverNow) + { + _itemBuffTimers.Clear(); + + if (_worldObjectCache == null || !_host.HasReadObjectEnchantments) + return; + + try + { + // Snapshot the inventory to avoid iterating a changing collection + var inventorySnapshot = new List(); + foreach (var item in _worldObjectCache.GetDirectInventory()) + inventorySnapshot.Add(item); + + const int MaxEnchantments = 64; + uint[] spellIds = new uint[MaxEnchantments]; + double[] expiryTimes = new double[MaxEnchantments]; + int equippedCount = 0; + + foreach (var item in inventorySnapshot) + { + int wieldedSlot = item.WieldedLocation; + if (wieldedSlot == 0) continue; // not equipped + + equippedCount++; + uint objectId = unchecked((uint)item.Id); + int count; + try + { + count = _host.ReadObjectEnchantments(objectId, spellIds, expiryTimes, MaxEnchantments); + } + catch + { + continue; // skip items whose weenie can't be read + } + if (count <= 0) continue; + + for (int i = 0; i < count; i++) + { + var spellInfo = SpellTableStub.GetById((int)spellIds[i]); + if (spellInfo == null) continue; + + double remainingSeconds = expiryTimes[i] - serverNow; + if (remainingSeconds <= 0) continue; + if (remainingSeconds > 86400 * 365) continue; // permanent + + long key = ((long)objectId << 32) | (uint)spellInfo.Family; + _itemBuffTimers[key] = new ItemBuffTimerInfo + { + ObjectId = objectId, + ObjectName = item.Name, + Expiration = DateTime.Now.AddSeconds(remainingSeconds), + SpellLevel = GetSpellLevel(spellInfo), + SpellName = spellInfo.Name, + }; + } + } + + _host.Log($"[RynthAi] Item enchant scan: {equippedCount} equipped, {_itemBuffTimers.Count} timed buffs"); + } + catch (Exception ex) + { + _host.Log($"[RynthAi] Item enchant scan failed: {ex.GetType().Name}: {ex.Message}"); + } + } + + /// + /// Returns the number of tracked item buff timers (equipped items only). + /// + public int ItemBuffCount => _itemBuffTimers.Count; + + /// + /// Checks whether a specific equipped item has a given buff family active. + /// + public bool HasItemBuff(uint objectId, string spellBaseName) + { + int family = new SpellInfo(0, spellBaseName).Family; + long key = ((long)objectId << 32) | (uint)family; + return _itemBuffTimers.TryGetValue(key, out var info) && info.Expiration > DateTime.Now; + } + + public void PrintBuffDebug() + { + int augs = GetArchmageEnduranceCount(); + _host.WriteToChat($"[RynthAi] Archmage endurance count: {augs}", 1); + + // Try a live refresh of player enchantments + double serverNow = _host.HasGetServerTime ? _host.GetServerTime() : 0; + if (serverNow > 0 && _host.HasReadPlayerEnchantments) + { + int refreshed = RefreshFromLiveMemory(); + _host.WriteToChat($"[RynthAi] Live read: {(refreshed >= 0 ? $"{refreshed} enchantments" : "unavailable (no qualities ptr)")}", 1); + + // TODO: Item enchantment scanning disabled — crashes when reading inventory item + // memory via ReadObjectEnchantments. Needs investigation (AV in native InqInt or + // GetWeenieObject for certain inventory items). See memory note for details. + } + else + { + _host.WriteToChat($"[RynthAi] ServerTime={Math.Round(serverNow)} (no live read: serverTime=0 or API missing)", 1); + } + + if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0) + { + _host.WriteToChat("[RynthAi] No buff timers active.", 1); + return; + } + + if (_itemSpellTimers.Count > 0) + { + _host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1); + PrintItemSpellTimers(); + } + + if (_ramBuffTimers.Count > 0) + { + _host.WriteToChat($"[RynthAi] -- Player buffs ({_ramBuffTimers.Count}) --", 1); + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + double total = GetCustomSpellDuration(info.SpellLevel); + TimeSpan left = info.Expiration - DateTime.Now; + double passed = total - left.TotalSeconds; + _host.WriteToChat( + $"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(passed / 60, 1)}m passed, " + + $"{Math.Round(left.TotalMinutes, 1)}m left. Total: {total / 60}m", 1); + } + } + } + + /// + /// Diagnostic dump of buff-tier resolution. For each desired buff, shows the + /// skill, current buffed level, the max tier the threshold settings allow, + /// and the spell that actually got resolved (with its tier). Lets the user + /// see exactly why a low-tier spell is being cast — usually because the + /// higher-tier Lore spell isn't in their spellbook yet. + /// + public void PrintBuffTierDebug() + { + List desiredBuffs = BuildDynamicBuffList(); + var seen = new HashSet(); + + foreach (string baseName in desiredBuffs) + { + AcSkillType skill = SkillForBuff(baseName); + if (!IsSkillUsable(skill)) continue; + + // Skill summary line — print once per unique skill. + if (seen.Add(skill)) + { + int buffed = _charSkills != null ? _charSkills[skill].Buffed : -1; + int maxTier = _spellManager.GetHighestBuffSpellTier(skill); + _host.WriteToChat($"[RynthAi] -- {skill} (buffed={buffed}, max tier T{maxTier}) --", 1); + } + + int spellId = FindBestSpellId(baseName, skill); + if (spellId == 0) + { + _host.WriteToChat($"[RynthAi] {baseName}: no learnable spell at any tier", 1); + continue; + } + + var info = SpellTableStub.GetById(spellId); + int level = info != null ? GetSpellLevel(info) : 0; + string activeTimer = "no timer"; + if (info != null && _ramBuffTimers.TryGetValue(info.Family, out RamTimerInfo? timer)) + activeTimer = $"timer T{timer.SpellLevel}, {Math.Round((timer.Expiration - DateTime.Now).TotalMinutes, 1)}m left"; + else if (info != null && _itemSpellTimers.TryGetValue(info.Family, out ItemSpellRecord? itemTimer)) + activeTimer = $"item T{itemTimer.SpellLevel}, {Math.Round((itemTimer.ExpiresAt - DateTime.Now).TotalMinutes, 1)}m left"; + + _host.WriteToChat($"[RynthAi] {baseName} → {info?.Name ?? "?"} (T{level}, {activeTimer})", 1); + } + } + + public void PrintItemBuffDebug() + { + if (_itemSpellTimers.Count == 0) + { + _host.WriteToChat("[RynthAi] No item spell timers recorded yet.", 1); + return; + } + _host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1); + PrintItemSpellTimers(); + } + + private void PrintItemSpellTimers() + { + foreach (var kvp in _itemSpellTimers) + { + var info = kvp.Value; + TimeSpan left = info.ExpiresAt - DateTime.Now; + TimeSpan spent = DateTime.Now - info.CastAt; + double totalMin = (info.ExpiresAt - info.CastAt).TotalMinutes; + if (left.TotalSeconds <= 0) + _host.WriteToChat($"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): EXPIRED", 1); + else + _host.WriteToChat( + $"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): " + + $"{Math.Round(spent.TotalMinutes, 1)}m elapsed, {Math.Round(left.TotalMinutes, 1)}m left / {Math.Round(totalMin, 0)}m total", 1); + } + } + + private List BuildDynamicBuffList() + { + var step1_CreatureMastery = new List(); + var step2_Focus = new List(); + var step3_Willpower = new List(); + var step4_OtherCreature = new List(); + var step5_LifeAndItem = new List(); + var step6_WeaponAuras = new List(); + var step7_ArmorBanes = new List(); + + foreach (string attr in BaseCreatureBuffs) + { + if (attr == "Focus Self") step2_Focus.Add(attr); + else if (attr == "Willpower Self") step3_Willpower.Add(attr); + else step4_OtherCreature.Add(attr); + } + + foreach (var kvp in CreatureSkillBuffs) + { + if (IsSkillUsable(kvp.Key)) + { + if (kvp.Value.Contains("Creature Enchantment Mastery")) + step1_CreatureMastery.Add(kvp.Value); + else if (!BaseCreatureBuffs.Contains(kvp.Value)) + step4_OtherCreature.Add(kvp.Value); + } + } + + step5_LifeAndItem.AddRange(new List { + "Regeneration Self", "Rejuvenation Self", "Mana Renewal Self", + "Armor Self", "Acid Protection Self", "Fire Protection Self", + "Cold Protection Self", "Lightning Protection Self", + "Blade Protection Self", "Piercing Protection Self", + "Bludgeoning Protection Self" + }); + + step6_WeaponAuras.AddRange(new List { + "Blood Drinker Self", "Hermetic Link Self", "Heart Seeker Self", + "Spirit Drinker Self", "Swift Killer Self", "Defender Self" + }); + + step7_ArmorBanes.AddRange(new List { + "Impenetrability", "Acid Bane", "Blade Bane", "Bludgeoning Bane", + "Flame Bane", "Frost Bane", "Lightning Bane", "Piercing Bane" + }); + + var final = new List(); + final.AddRange(step1_CreatureMastery); + final.AddRange(step2_Focus); + final.AddRange(step3_Willpower); + final.AddRange(step4_OtherCreature); + final.AddRange(step5_LifeAndItem); + final.AddRange(step6_WeaponAuras); + final.AddRange(step7_ArmorBanes); + return final; + } + + /// + /// Called when the engine's enchantment hook fires for an enchantment applied to the player. + /// Refreshes timers from live memory when possible; falls back to the hook-supplied duration. + /// + public void OnEnchantmentAdded(uint spellId, double durationSeconds) + { + var spellInfo = SpellTableStub.GetById((int)spellId); + if (spellInfo == null) + return; + + // Only clear pending if this enchantment matches what we were casting. + // Armor/item enchantments fire on the item, not the player — clearing + // _pendingSpellId unconditionally would lose track of pending item casts + // and prevent the chat handler from recording their timers. + if (_pendingSpellId != 0) + { + var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + if (pendingSpell != null && pendingSpell.Family == spellInfo.Family) + _pendingSpellId = 0; + } + + // The family did land — clear any silent-no-show state (counter + + // cooldown park) so future expiries trigger casts normally again. + // Important for the /god case: if the user later learns the spell + // the buff system should resume casting without a manual reset. + // Also clears the chat-driven hard-reject cooldown if the family + // somehow lands despite a recent reject (server-side fix etc.). + if (_silentNoShowCounts.Remove(spellInfo.Family) || + _buffFailCooldownUntil.Remove(spellInfo.Family)) + { + // No log spam in the common case — only the rare "park-then-recover" path. + } + + // Prefer live memory read — gives accurate remaining time for all enchantments. + // But only trust it if the just-added buff actually shows up there yet. + if (RefreshFromLiveMemory() >= 0 && + _ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? liveTimer) && + liveTimer.Expiration > DateTime.Now) + { + return; + } + + RecordSpellTimer(spellInfo, durationSeconds); + } + + /// + /// Called when the engine's enchantment hook fires for an enchantment removed from the player. + /// Clears the buff timer for the corresponding spell family. + /// + public void OnEnchantmentRemoved(uint enchantmentId) + { + var spellInfo = SpellTableStub.GetById((int)enchantmentId); + if (spellInfo == null) return; + + if (_ramBuffTimers.Remove(spellInfo.Family)) + SaveBuffTimers(); + } + + /// + /// Call from RynthAiPlugin.OnChatWindowText when chat arrives. + /// Handles fizzle/fail → resets pending cast state. + /// + public void OnChatWindowText(string text, int chatType) + { + string lower = text.ToLowerInvariant(); + + // Diagnostic: log every chat seen while waiting on a cast confirmation, + // so we can see what AC is actually emitting and adjust our matchers. + if (_pendingSpellId != 0) + _host.Log($"[BuffChat] pending={_pendingSpellId} type={chatType} text='{text}'"); + + // Real failure phrases. Note: bare "component" was removed — it false-matches + // the "consumed the following components" line, which fires for both success + // AND fizzle, so it's NOT a reliable signal either direction. Ignore it + // entirely; wait for the explicit "ou cast" success or "fizzle" failure. + // "You're too busy!" is NOT a cast failure — it's AC refusing because + // the previous cast gesture is still animating. The old code lumped it + // into the fizzle/fail block below, which set _lastCastAttempt = + // DateTime.MinValue (defeating the SpellCastIntervalMs throttle) AND + // cleared _pendingSpellId, so the same cast was re-issued on the very + // next ~90ms tick → ~11 refusals/sec → AC's AddTextToScroll re-entry + // AV at 0x00460D1D. Handle it separately: roll back the optimistic + // item-spell timer (the bane genuinely didn't land) and clear pending + // so the buff loop re-evaluates — but DO NOT zero _lastCastAttempt, so + // the interval throttle stays active. The CanCastNow gesture gate is + // the primary bound; the throttle is the backstop. No tight loop by + // construction → 0x00460D1D killed regardless of gate precision. + if (lower.Contains("you're too busy") || lower.Contains("you are too busy")) + { + if (_pendingSpellId != 0) + { + var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name)) + { + _itemSpellTimers.Remove(pendingSpell.Family); + SaveBuffTimers(); + } + _host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue."); + } + _pendingSpellId = 0; + + // AC is authoritatively busy — wait, escalating, rather than retrying + // on the 400ms tick. Cleared by NoteCastAccepted on the next success. + _busyRefusalStreak++; + double backoffMs = Math.Min(BusyBackoffBaseMs * Math.Pow(2, _busyRefusalStreak - 1), BusyBackoffMaxMs); + _busyBackoffUntil = DateTime.Now.AddMilliseconds(backoffMs); + if (_busyRefusalStreak == 1 || _busyRefusalStreak % 5 == 0) + _host.Log($"[BuffChat] too-busy streak={_busyRefusalStreak} — backing off {backoffMs:0}ms before the next cast attempt."); + + _onCastResolved?.Invoke("too busy"); + return; + } + + // HARD rejection: the server can't cast this at all and the next + // attempt fails identically (missing components, no target, etc.). + // Clear pending AND park the spell's family on a cooldown so the buff + // loop stops re-picking it every cycle. Without this an uncastable buff + // (e.g. "Battlemage's Blessing" with no components) re-casts every tick + // → sustained AC AddTextToScroll re-entry → AC access-violation. + // "have all the components for this spell" is matched specifically so + // it does NOT collide with the success line "consumed the following + // components". + if (lower.Contains("missing some required") || + lower.Contains("you do not have the") || + lower.Contains("you must specify") || + lower.Contains("have all the components for this spell")) + { + if (_pendingSpellId != 0) + { + var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + if (pendingSpell != null) + { + if (IsItemEnchantment(pendingSpell.Name)) + { + _itemSpellTimers.Remove(pendingSpell.Family); + SaveBuffTimers(); + } + _buffFailCooldownUntil[pendingSpell.Family] = + DateTime.Now.AddSeconds(BuffFailCooldownSec); + } + _host.Log($"[BuffChat] CLEARED+COOLED pending={_pendingSpellId} ({BuffFailCooldownSec:0}s) — hard rejection in '{text}'"); + } + _pendingSpellId = 0; + _onCastResolved?.Invoke("hard-reject"); + return; + } + + // SOFT failure: random fizzle or transient (out of mana). Clear pending + // and allow a prompt retry — do NOT cooldown the family. + if (lower.Contains("fizzle") || + lower.Contains("your spell failed") || + lower.Contains("lack the mana")) + { + if (_pendingSpellId != 0) + { + var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name)) + { + _itemSpellTimers.Remove(pendingSpell.Family); + SaveBuffTimers(); + } + _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via soft-fail in '{text}'"); + } + _lastCastAttempt = DateTime.MinValue; + _pendingSpellId = 0; + _onCastResolved?.Invoke("soft-fail"); + return; + } + + // "You cast Incantation of Flame Bane on Gelidite Robe, refreshing ..." + // "You cast Strength Self VIII" + // The leading 'Y' is stripped by AC's chat-glyph layer before our handler + // sees it — text actually arrives as "ou cast …". IndexOf works for both. + int castIdx = lower.IndexOf("ou cast ", StringComparison.Ordinal); + if (castIdx < 0) return; + + // Extract spell name: everything after "ou cast " up to " on " or "," + string afterCast = text.Substring(castIdx + 8); // skip "ou cast " + int onIdx = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase); + int commaIdx = afterCast.IndexOf(','); + int endIdx = afterCast.Length; + if (onIdx > 0) endIdx = onIdx; + if (commaIdx > 0 && commaIdx < endIdx) endIdx = commaIdx; + string spellName = afterCast.Substring(0, endIdx).Trim(); + + // Try to find the spell by name first (authoritative — this is what was actually cast) + int spellId = SpellDatabase.GetIdByName(spellName); + SpellInfo? spellInfo = spellId > 0 ? SpellTableStub.GetById(spellId) : null; + + // Fall back to pending spell if name lookup fails + if (spellInfo == null && _pendingSpellId != 0) + spellInfo = SpellTableStub.GetById(_pendingSpellId); + + if (spellInfo != null) + { + _buffFailCooldownUntil.Remove(spellInfo.Family); // it cast — clear any stale hard-fail cooldown + NoteCastAccepted(); // AC accepted a cast — end any too-busy backoff + // Chat-authoritative record: only NOW (AC confirmed "you cast X"). + // Item/armor enchants live in _itemSpellTimers (what IsBuffActive + // checks for them); player buffs in _ramBuffTimers. + if (IsItemEnchantment(spellInfo.Name)) + RecordItemSpellCast(spellInfo); + else + RecordSpellTimer(spellInfo); + } + + if (_pendingSpellId != 0) + { + if (_isForceRebuffing) + { + var ps = SpellTableStub.GetById(_pendingSpellId); + if (ps != null) _forceRebuffCastFamilies.Add(ps.Family); + } + _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via ou-cast match name='{spellName}' resolvedId={spellId}"); + } + _pendingSpellId = 0; + _onCastResolved?.Invoke($"cast '{spellName}'"); + } + + /// Record that a cast just went out, so the next one waits for the + /// server to report the action finished rather than a blind interval. + private void NoteCastIssued() + { + if (!_host.HasUseDoneSeq) { _awaitingCastResolution = false; return; } + _useDoneSeqAtCast = _host.GetUseDoneSeq(); + _awaitingCastResolution = true; + _castResolutionDeadline = DateTime.Now.AddMilliseconds(CastResolutionTimeoutMs); + } + + /// True while the server has not yet reported finishing the last + /// cast. Self-clears on the UseDone-seq advance (completed OR refused) or on + /// the timeout, so this can never wedge the buff loop. + private bool IsAwaitingCastResolution() + { + if (!_awaitingCastResolution) return false; + if (_host.HasUseDoneSeq && _host.GetUseDoneSeq() != _useDoneSeqAtCast) + { + _awaitingCastResolution = false; + return false; + } + if (DateTime.Now >= _castResolutionDeadline) + { + _awaitingCastResolution = false; + return false; + } + return true; + } + + /// A cast was accepted by AC, so whatever it was busy with has + /// cleared — drop the too-busy backoff immediately rather than serving out a + /// stale delay. + private void NoteCastAccepted() + { + if (_busyRefusalStreak == 0 && _busyBackoffUntil == DateTime.MinValue) return; + if (_busyRefusalStreak > 0) + _host.Log($"[BuffChat] cast accepted after {_busyRefusalStreak} too-busy refusal(s) — backoff cleared."); + _busyRefusalStreak = 0; + _busyBackoffUntil = DateTime.MinValue; + } + + private void RecordSpellTimer(SpellInfo spellInfo, double durationSeconds = -1) + { + if (durationSeconds < 0) + durationSeconds = GetCustomSpellDuration(GetSpellLevel(spellInfo)); + + if (durationSeconds <= 0) + return; + + int level = GetSpellLevel(spellInfo); + _ramBuffTimers[spellInfo.Family] = new RamTimerInfo + { + Expiration = DateTime.Now.AddSeconds(durationSeconds), + SpellLevel = level, + SpellName = spellInfo.Name, + }; + SaveBuffTimers(); + } + + // TODO: Replace with real skill training lookup from AC memory + private bool IsSkillUsable(AcSkillType s) => _charSkills != null ? _charSkills[s].Training >= 2 : true; + + private static AcSkillType SkillForBuff(string name) + { + // Impregnability Self = Missile Defense (Creature Enchantment), NOT Item Enchantment. + // Impenetrability / Bane / weapon auras = Item Enchantment. + if (name.Contains("Blood Drinker") || + name.Contains("Hermetic Link") || name.Contains("Heart Seeker") || + name.Contains("Spirit Drinker") || name.Contains("Swift Killer") || + name.Contains("Defender") || name.Contains("Impenetrability") || + name.Contains("Bane")) + return AcSkillType.ItemEnchantment; + + if (name.Contains("Protection") || name.Contains("Armor") || + name.Contains("Regeneration") || name.Contains("Rejuvenation") || + name.Contains("Renewal") || name == "Harlune's Blessing" || + name.Contains("Stamina to Mana") || name.Contains("Revitalize") || + name.Contains("Stamina to Health") || name == "Heal Self") + return AcSkillType.LifeMagic; + + return AcSkillType.CreatureEnchantment; + } + + // Stance-deadlock episode state for THIS path. ⚠ EnsureMagicMode is the + // stance path that owns the bot whenever Buffing holds priority — and on + // 2026-06-12 it silently retried ChangeCombatMode for 107 MINUTES (zero + // log lines, no recovery) while the variant-2 wand/stance deadlock kept + // the character unbuffed and standing in a spawn field. CombatManager's + // capped recovery never ran because Buffing starves the combat tick. + // Mirror that recovery here: visible retries, ≤2 capped re-equips per + // episode, one-shot chat warn when wedged. + private DateTime _buffStanceStuckSince = DateTime.MinValue; + private DateTime _buffStanceLastRecoverAt = DateTime.MinValue; + private int _buffStanceReEquips; + private bool _buffStanceWedgeWarned; + private const double BuffStanceStuckRecoverMs = 8000; + private const int BuffStanceReEquipMax = 2; + + private bool EnsureMagicMode(bool forBuff = false) + { + // Per-call signal; only the buff path may set it (vitals/self-heals NEVER degrade). + _wandSwapExhausted = false; + if (CurrentCombatMode == CombatMode.Magic) + { + // Successfully reached magic mode — clear per-cycle teardown flag + // and wield gate so the next switch out of magic restarts cleanly. + _combatTeardownDoneForCurrentBuffCycle = false; + _pendingWieldId = 0; + _wieldCooldownUntil = DateTime.MinValue; + // Reset the exponential-backoff counter so the next problem starts + // at the fast 1s cadence again. See field comment for rationale. + _buffStanceConsecutiveFails = 0; + // Episode over — clear the deadlock-recovery state too. + _buffStanceStuckSince = DateTime.MinValue; + _buffStanceReEquips = 0; + _buffStanceWedgeWarned = false; + // FIX: reached Magic — clear the new swap-confirm / resilience state so a + // later recoverable episode (e.g. after a slot frees from looting) starts clean. + _bowDequipPendingId = 0; + _bowDequipAttempts = 0; + _wieldGateFailCount = 0; + return true; + } + + int wandId = FindWandInItems(); + if (wandId == 0) + { + // No wand available — try to switch mode anyway (bare-handed magic). + _host.ChangeCombatMode(CombatMode.Magic); + _lastCastAttempt = DateTime.Now; + return false; + } + + // Primary check: CurrentWieldedLocation (stype=10) — works even before the + // phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance. + bool alreadyWielded = false; + var wandObj = _worldObjectCache?[wandId]; + if (wandObj != null) + alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + + // Secondary check via API if primary didn't confirm + if (!alreadyWielded && _host.HasGetObjectWielderInfo) + { + uint playerId = _host.GetPlayerId(); + if (playerId != 0 && + _host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) && + wielder == playerId) + alreadyWielded = true; + } + + if (!alreadyWielded) + { + // Wield gate: don't spam UseObject. Hold off after the first issue + // until either the wielded check confirms (cleared on the Magic-mode + // branch above) or the resolve timeout elapses, then cool down + // before retrying. Mirrors the no-chat-timeout pattern used for + // spell casts at the top of OnHeartbeat. Checked BEFORE the shared + // swap gate so a denied attempt never claims the cross-subsystem slot. + DateTime now = DateTime.Now; + if (now < _wieldCooldownUntil) + return false; + + if (_pendingWieldId != 0) + { + if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs) + return false; + + _host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " + + $"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms"); + _pendingWieldId = 0; + _wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs); + // FIX: bound the previously-infinite wield loop. If the wand still won't + // wield after a few cooldowns (e.g. no pack to free the bow, or an + // unresolvable collision), degrade so buffing yields and combat runs. + if (++_wieldGateFailCount >= WieldGateFailMax) + return SignalSwapFailure(forBuff, FindWieldedNonWandWeapon(wandId), wandId); + return false; + } + + // Shared weapon-swap gate: if CombatManager (or anything else) swapped + // a weapon within the last few seconds, wait — two equips in flight + // collide ("you can only move or use one item at a time" / AV). + if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand")) + return false; + + // Tear down any in-flight physical combat BEFORE the UseObject. The + // transition Melee/Missile → Magic-via-wand must explicitly cancel the + // pending attack, or AC gets a UseObject while m_bAttacking is still + // set and wedges the item-action gate. Done only after we've claimed + // the swap slot above, so we don't cancel an attack then fail to swap. + if (!_combatTeardownDoneForCurrentBuffCycle && + (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) + { + if (_host.HasCancelAttack) _host.CancelAttack(); + if (_host.HasStopCompletely) _host.StopCompletely(); + _combatTeardownDoneForCurrentBuffCycle = true; + _host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})"); + } + + // FIX: stock ACE will NOT auto-dequip the bow for a Held-slot wand + // (CheckWeaponCollision refuses while mainhand != null). Stow the wielded + // non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern, + // AV-safe), then UseObject(wand) once the hand is free. Fully bounded. + int bowId = FindWieldedNonWandWeapon(wandId); + if (bowId != 0) + { + if (_bowDequipPendingId == bowId + && (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs + && IsWieldedLive(bowId)) + return false; // dequip still resolving + + if (IsWieldedLive(bowId)) + { + int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1); + if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts) + { + // No verified-open pack to receive the bow, or repeated dequip + // failures -> the swap provably can't complete now. Degrade. + _host.Log($"[WieldGate] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_bowDequipAttempts}/{BowDequipMaxAttempts}) — degrading"); + return SignalSwapFailure(forBuff, bowId, wandId); + } + _bowDequipAttempts++; + _host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0) + _bowDequipPendingId = bowId; + _bowDequipAt = now; + _lastCastAttempt = now; + _host.Log($"[WieldGate] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_bowDequipAttempts}/{BowDequipMaxAttempts}) before wand equip"); + return false; // yield until the bow is out of hand + } + _bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand + } + + _host.UseObject((uint)wandId); + _pendingWieldId = wandId; + _pendingWieldAt = now; + _lastCastAttempt = now; + return false; // Yield — let the server equip the wand + } + + // Wand is wielded — clear the gate and switch stance. + if (_pendingWieldId == wandId) + { + _pendingWieldId = 0; + _wieldCooldownUntil = DateTime.MinValue; + } + + // Deadlock episode tracking: wand wielded but mode refuses to flip. + if (_buffStanceStuckSince == DateTime.MinValue) + _buffStanceStuckSince = DateTime.Now; + double stuckMs = (DateTime.Now - _buffStanceStuckSince).TotalMilliseconds; + + // Capped re-equip recovery (mirrors CombatManager): handles the rare + // stale "wielded reads true" by resyncing the wield once or twice. + // HARD-CAPPED — UseObject on a genuinely wielded wand is a MOVE to AC, + // and unbounded re-equip jams the item-action queue permanently. + if (_buffStanceReEquips < BuffStanceReEquipMax + && stuckMs > BuffStanceStuckRecoverMs + && (DateTime.Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs + && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("buff-stance-recovery"))) + { + _buffStanceLastRecoverAt = DateTime.Now; + _buffStanceReEquips++; + _host.Log($"[BuffStance] STUCK {stuckMs:0}ms (wielded, mode={CurrentCombatMode}≠Magic) — re-equip attempt {_buffStanceReEquips}/{BuffStanceReEquipMax} 0x{(uint)wandId:X8}"); + _host.UseObject((uint)wandId); + _lastCastAttempt = DateTime.Now; + return false; + } + // Past the cap and clearly wedged: warn ONCE so a multi-hour silent + // coma can never happen again, then keep mode-change-only retries. + if (_buffStanceReEquips >= BuffStanceReEquipMax && !_buffStanceWedgeWarned + && stuckMs > BuffStanceStuckRecoverMs * 3) + { + _buffStanceWedgeWarned = true; + _host.WriteToChat($"[RynthAi] Buff stance wedged: wand wielded but AC won't enter Magic mode after {stuckMs / 1000:0}s. Buffs cannot cast. Try /ra clearbusy, or relog if it persists.", 2); + } + + // Exponential backoff: 1s → 2s → 4s → 8s → 16s → 30s cap. Counter + // increments only when this branch fires AND the previous flip didn't + // stick (we got back here with mode != Magic). Reset to 0 at the top + // of EnsureMagicMode when mode == Magic. See field comment. + int shift = _buffStanceConsecutiveFails; + if (shift > 5) shift = 5; + int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s + if (gateMs > 30000) gateMs = 30000; // cap at 30s + if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs) + { + _host.ChangeCombatMode(CombatMode.Magic); + _lastBuffStanceAttempt = DateTime.Now; + _lastCastAttempt = DateTime.Now; + if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++; + // Visible retry line (throttled by the backoff itself): the + // 2026-06-12 coma produced ZERO log output from this path. + _host.Log($"[BuffStance] ChangeCombatMode(Magic) retry #{_buffStanceConsecutiveFails} (stuck {stuckMs / 1000:0}s, next retry in {gateMs / 1000:0}s)"); + } + return false; // Yield — let stance animation finish + } + + // The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand. + private int FindWieldedNonWandWeapon(int wandId) + { + if (_worldObjectCache == null) return 0; + foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true)) + { + if (wo.Id == wandId) continue; + if (IsWandObject(wo)) continue; + if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0 + && (wo.ObjectClass == AcObjectClass.MeleeWeapon + || wo.ObjectClass == AcObjectClass.MissileWeapon)) + return wo.Id; + } + return 0; + } + + // Live (forceRefresh) wielded check — never trusts a stale cache snapshot. + private bool IsWieldedLive(int id) + { + if (id == 0 || _worldObjectCache == null) return false; + foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true)) + if (wo.Id == id) + return wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + if (_host.HasGetObjectWielderInfo) + { + uint pid = _host.GetPlayerId(); + if (pid != 0 && _host.TryGetObjectWielderInfo((uint)id, out uint wielder, out _)) + return wielder == pid; + } + return false; + } + + // FindOpenPackForDequip DELETED (P2a) — replaced by the shared + // WorldObjectCache.FindPackFor(host, cache, includeMainPack:true, requireFree:1). + // includeMainPack:true preserves the prior main-pack (cap-102) fallback so the + // just-shipped wand-swap dequip behaviour is unchanged; requireFree:1 because a + // single genuinely-free slot is enough for the bow (anti-churn is for the auto- + // loops, not the user/buff-driven swap). Call sites: EnsureMagicMode + SignalSwapFailure. + + // Bounded degrade. Re-arms the bow for combat and, for the BUFF path only, raises the + // exhaustion signal so the buff selector parks the family and the bot fights unbuffed. + // Vitals (forBuff=false) just yield/retry and never park (death-risk: heals must keep trying). + private bool SignalSwapFailure(bool forBuff, int bowId, int wandId) + { + // If the wand ended up wielded but mode never flipped, dequip it so the bow can + // re-wield (stock ACE won't auto-dequip the wand for a MissileWeapon slot). Only + // one of these two branches fires per call — no same-tick wield/unwield race. + if (wandId != 0 && IsWieldedLive(wandId)) + { + int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1); + if (openPack != 0) _host.MoveItemInternal((uint)wandId, (uint)openPack, 0, 1); + } + else if (bowId != 0 && !IsWieldedLive(bowId)) + { + _host.UseObject((uint)bowId); // re-wield the bow for missile combat + } + _pendingWieldId = 0; + _bowDequipPendingId = 0; + _bowDequipAttempts = 0; + _wieldGateFailCount = 0; + if (forBuff) _wandSwapExhausted = true; + return false; + } + + /// + /// Locates a wand to equip. Prefers a configured ItemRule classified as WandStaffOrb, + /// falling back to the first WandStaffOrb found in the inventory cache. + /// Mirrors CombatManager.FindWandInItems. + /// + private int FindWandInItems() + { + if (_worldObjectCache == null) return 0; + + // Prefer explicitly configured wand from item rules + foreach (var rule in _settings.ItemRules) + { + var wo = _worldObjectCache[rule.Id]; + if (wo != null && IsWandObject(wo)) return rule.Id; + } + + // Inventory cache scan — ObjectClass first, name fallback for unclassified items + foreach (var wo in _worldObjectCache.GetInventory()) + { + if (IsWandObject(wo)) return wo.Id; + } + + return 0; + } + + private static bool IsWandObject(WorldObject wo) => + wo.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(wo.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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs new file mode 100644 index 0000000..0cdced6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs @@ -0,0 +1,68 @@ +using System; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Stuck-state backstop for the engine's CMotionInterp cast-gesture gate +/// (_host.CanCastNow). That gate reads [CMI+0x80]; 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 (BuffManager.OnHeartbeat) and combat +/// (CombatManager magic) paths hard-return on !CanCastNow 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 SpellCastIntervalMs throttle and the "too busy" PARK path remain +/// the anti-spam guarantees, so this cannot reintroduce the 0x00460D1D +/// refusal-loop AV. +/// +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; + + /// + /// Effective "clear to cast": the raw engine gate plus a stuck backstop. + /// Call with _host.CanCastNow; optionally pass a logger for the + /// one-shot stuck/recovered transitions. + /// + public static bool CanCastNow(bool rawCanCastNow, Action? 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs new file mode 100644 index 0000000..fa21c11 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -0,0 +1,3728 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi.Combat; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.Plugin.RynthAi; + +public class CombatManager : IDisposable +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private SpellManager? _spellManager; + + private MainLogic? _raycastSystem; + public bool RaycastInitialized { get; private set; } + + // Set on the raycast-init bg thread when RaycastInitialized flips + // false→true; consumed once on the next main-thread ScanNearbyTargets to + // clear warmup-era blacklist/timer penalties (the bg thread must not touch + // combat state directly). + private volatile bool _raycastReadyResetPending; + + public int activeTargetId + { + get => _activeTargetId; + set { _activeTargetId = value; if (value == 0) _nativeAttackTargetId = 0; } + } + private int _activeTargetId; + private DateTime lastAttackCmd = DateTime.MinValue; + private DateTime lastStanceAttempt = DateTime.MinValue; + // Exponential backoff for stance flips. A persistent wedge used to re-send + // ChangeCombatMode every second forever — the 2026-05-25 stance-spam crash + // class (256 consecutive sends before the client died); BuffManager got + // backoff then, combat never did. Delay doubles every 4 failed sends, + // capped at 15s, with a one-shot warning once clearly wedged. Reset + // wherever the stance is reached or the target drops. + private int _stanceFlipAttempts; + private bool _stanceFlipWarned; + + private double StanceRetryDelayMs() + => Math.Min(15_000, 1000 * Math.Pow(2, Math.Min(4, _stanceFlipAttempts / 4))); + + private void NoteStanceFlipSent() + { + _stanceFlipAttempts++; + if (_stanceFlipAttempts == 16 && !_stanceFlipWarned) + { + _stanceFlipWarned = true; + _host.Log($"[EquipDiag] WARNING: {_stanceFlipAttempts} consecutive ChangeCombatMode sends without reaching the stance — wedge persists despite recovery; backing off to {StanceRetryDelayMs() / 1000:0}s retries."); + } + } + + private void ResetStanceFlipBackoff() + { + _stanceFlipAttempts = 0; + _stanceFlipWarned = false; + } + // Stuck-stance deadlock recovery (2026-06-10). When the wand reads as wielded + // client-side but AC refuses to complete the NonCombat→Magic stance change, the + // equip path would only re-send ChangeCombatMode forever (it never re-equips a + // "wielded" wand) — a hours-long wedge with NO m_cBusy pin so no watchdog fires. + private DateTime _stanceStuckSince = DateTime.MinValue; + private DateTime _lastStanceRecoverAt = DateTime.MinValue; + private const double StanceStuckRecoverMs = 8000; + // Re-equip attempts spent in the CURRENT deadlock episode. ⚠ UseObject on an + // ALREADY-WIELDED wand is treated by AC as an unwield/MOVE — spamming it + // every 8s for ~17 min (2026-06-11) jammed AC's item-action queue into a + // permanent "you can only move one item at a time" state (character + // unusable, no recovery but relog). The re-equip only helps the rare + // stale-wield read, so it's capped; past the cap the recovery is + // mode-change-only and warns once. + private int _stanceReEquipAttempts; + private const int StanceReEquipMaxAttempts = 2; + + // ── Combat wand wield gate ─────────────────────────────────────────────── + // The wand-equip path used to re-issue UseObject every 2s forever with no + // confirmation step and no cap. That is the exact pattern both this file and + // BuffManager already warn about: "UseObject on a genuinely wielded wand is a + // MOVE to AC, and unbounded re-equip jams the item queue." Hammering it does + // not just fail to help — it keeps the item-action queue jammed, so the wield + // that would have succeeded never lands. Observed 2026-09-02: 47 UseObject + // sends over 10 minutes, hands empty the whole time, combat never engaging. + // + // It went unnoticed because BuffManager.EnsureMagicMode also wields a wand and + // puts the character in Magic mode; while the rebuff loop was running + // constantly it re-established the stance every cycle and combat rode along on + // it. Fixing the buff loop removed that accidental cover and exposed this. + // + // Same gate as BuffManager: issue ONE UseObject, wait for the wield to + // confirm, cool down, and cap the attempts — so a wand that genuinely cannot + // be wielded degrades loudly instead of wedging the queue silently. + private int _wandPendingWieldId; + private DateTime _wandPendingWieldAt = DateTime.MinValue; + private DateTime _wandWieldCooldownUntil = DateTime.MinValue; + private int _wandWieldFailCount; + private bool _wandWieldWedgeWarned; + private const double WandWieldResolveTimeoutMs = 2500; // mirrors BuffManager.WieldResolveTimeoutMs + private const double WandWieldCooldownMs = 5000; // mirrors BuffManager.WieldCooldownMs + private const int WandWieldFailMax = 3; // mirrors BuffManager.WieldGateFailMax + private bool _stanceWedgeWarned; + private DateTime _lastPeaceAttempt = DateTime.MinValue; + + // ── Bow→wand dequip-first swap state (2026-06-27) ──────────────────── + // Stock ACE will NOT auto-dequip a main-hand bow for a Held-slot wand + // (CheckWeaponCollision refuses while mainhand != null), and it DENIES + // ChangeCombatMode(Magic) while the bow is wielded ("GetEquippedWand()==null"). + // Combat must stow the bow into an open pack FIRST, then UseObject(wand), and + // only request Magic once the wand is actually wielded (handled by the + // alreadyWielded branch). Mirrors the proven BuffManager.EnsureMagicMode path. + private int _combatBowDequipPendingId; + private int _combatBowDequipAttempts; + private DateTime _combatBowDequipAt = DateTime.MinValue; + private bool _combatSwapTeardownDone; + private const int CombatBowDequipMaxAttempts = 3; + private const double WandSwapWieldResolveMs = 4000; + + // Clear all stance-deadlock episode state. Called wherever the stance is + // reached or the target drops, so the next episode starts fresh. + private void ResetStanceRecovery() + { + _stanceStuckSince = DateTime.MinValue; + _stanceReEquipAttempts = 0; + _stanceWedgeWarned = false; + ResetWandSwapState(); + ResetStanceFlipBackoff(); + } + + // Clear the bow→wand swap episode (called once the desired stance is reached). + private void ResetCombatWandWieldGate() + { + _wandPendingWieldId = 0; + _wandPendingWieldAt = DateTime.MinValue; + _wandWieldCooldownUntil = DateTime.MinValue; + _wandWieldFailCount = 0; + _wandWieldWedgeWarned = false; + } + + private void ResetWandSwapState() + { + _combatBowDequipPendingId = 0; + _combatBowDequipAttempts = 0; + _combatSwapTeardownDone = false; + } + + // ── Face-before-attack state ───────────────────────────────────────── + // For ranged/magic attacks, face the target with smooth turn before firing. + // ── Native attack state ────────────────────────────────────── + // StartAttackRequest auto-repeats — only call once per target. + private uint _nativeAttackTargetId; + + private bool _facingTarget; + // True only on attack cycles where an OFFENSIVE damage spell was actually + // cast. The blacklist miss-counter is gated on this in magic mode so it + // counts confirmed casts, not wall-clock interval ticks (equip waits, + // cast-gate, "no spell found", tier-down learning) which used to blacklist + // a perfectly good target in ~3 ticks (~1.2s at SpellCastIntervalMs=400). + private bool _offensiveCastThisCycle; + private DateTime _faceStartTime = DateTime.MinValue; + private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and fire anyway (MISSILE only) + private const double FACE_TOLERANCE_DEG = 15.0; // heading error threshold to fire + + // ── Magic targeted-cast settle gate (root-cause fix 2026-06-19) ────────── + // On the ACE server a TARGETED (combat) cast defers its windup behind a + // turn-to-face; a turn/stop MoveToState that lands during that deferred + // windup ORPHANS the cast (DoSpellWords/CreatePlayerSpell never runs) → the + // gesture animates but 0 damage / "You're too busy!" forever. Self-buffs are + // immune (untargeted → synchronous, no turn). Fix: for MAGIC, never cast + // mid-turn — keep turning until actually within angle, then release the turn + // motions and let the stop reach the server (settle tick) BEFORE the cast. + private DateTime _faceSettledAt = DateTime.MinValue; + private const double FACE_MAX_WAIT_MS = 2500.0; // safety: heading never converges (jittery point-blank pose) → cast anyway rather than wedge + private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet + + // ── Magic cast cadence guard ──────────────────────────────────────────── + // Don't issue the next combat cast until the previous one's server windup + // has resolved (a UseDone arrived, or a hard timeout). Re-casting into the + // window makes the next cast's stop-thunk/turn orphan the prior cast. + private bool _awaitingCastResolution; + private DateTime _castResolutionDeadline = DateTime.MinValue; + private int _useDoneSeqAtCast; + private const double CAST_RESOLUTION_TIMEOUT_MS = 2500.0; // covers a tier-7/8 war windup+recoil; also the sole gate on an engine without UseDone observation + + // Smooth turn motions — same codes as NavigationEngine + private const uint MotionTurnRight = 0x6500000D; + private const uint MotionTurnLeft = 0x6500000E; + + // Grace period: keep activeTargetId alive for this long after it disappears from scan, + // so a single bad LOS result or scan gap doesn't hand control to navigation. + private DateTime _targetLostScanTime = DateTime.MinValue; + private const double TARGET_SCAN_GRACE_MS = 1500.0; + + // Target lock — once committed to a mob, hold it until confirmed dead/gone. + // Prevents spinning caused by target thrashing when world-filter has a transient null + // or when a second mob briefly becomes slightly closer between scan ticks. + private int _lockedTargetId = 0; + + private bool _wasMacroRunning; + + private DateTime _lastSpellCast = DateTime.MinValue; + private bool _lastCastWasRing = false; + private const double ATTACK_SPELL_COOLDOWN_MS = 100.0; + + private bool _returnToPhysicalCombat = false; + private int _savedWeaponId = 0; + + // Shared cross-subsystem weapon-swap serializer (set by RynthAiPlugin). + // Prevents combat weapon equips from racing the buff wand-equip, and also + // serializes CombatManager's own re-equip + EquipWeaponAndSetStance so two + // equips can't fire in one tick. + private WeaponSwapGate? _weaponSwapGate; + public void SetWeaponSwapGate(WeaponSwapGate gate) => _weaponSwapGate = gate; + + /// Current combat mode — read live from AC client each access to avoid event-drop drift. + public int CurrentCombatMode => + _host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat; + + /// Client busy count — set by plugin from OnBusyCountIncremented/Decremented. + /// When > 0, combat must not send any game actions (SelectItem, attack, cast). + public int BusyCount { get; set; } + + /// D4 (record-only): human-readable reason combat did NOT cast on the + /// most recent tick (or "cast" when it did). Set at every magic skip site; read + /// by /ra why and the status feed. Purely diagnostic — never gates behavior. + public string LastCombatSkipReason { get; private set; } = ""; + + private CharacterSkills? _charSkills; + + private readonly WorldObjectCache _worldFilter; + + private static readonly Dictionary VulnSpells = new(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Fire Vulnerability Other" } }, + { "Cold", new[] { "Cold Vulnerability Other" } }, + { "Lightning", new[] { "Lightning Vulnerability Other" } }, + { "Acid", new[] { "Acid Vulnerability Other" } }, + { "Blade", new[] { "Blade Vulnerability Other" } }, + { "Slash", new[] { "Blade Vulnerability Other" } }, + { "Pierce", new[] { "Piercing Vulnerability Other" } }, + { "Bludgeon", new[] { "Bludgeoning Vulnerability Other" } }, + }; + + private readonly BlacklistManager _blacklistManager = new(); + private int _lastAttackedTargetId = 0; + // Blacklist is driven by CONFIRMED no-damage casts, not wall-clock time. + // A cast is queued in _pendingJudge* when issued and only judged a "miss" + // after BlacklistCastSettleMs with no damage on the target (so the damage + // packet has time to arrive). BlacklistAttempts consecutive misses → drop. + private int _consecutiveCastMisses = 0; + private DateTime _pendingJudgeCastAt = DateTime.MinValue; + private int _pendingJudgeTargetId = 0; + private bool _damageSincePendingCast; + private DateTime _targetLockedAt = DateTime.MinValue; + private DateTime _lastDamageDealtAt = DateTime.MinValue; + + // Ids to skip in the scanner for a short window — both confirmed kills + // (KillerNotification 0x01AD) and predicted kill-shot swaps. Value = the + // EXPIRY time, so the longer confirmed window and the shorter predicted + // window can coexist. The death signal reaches us at the lethal hit — + // before the mob's health reads 0 or it reclassifies to a corpse (ACE + // delays CreateCorpse by the full death-animation length) — so without this + // the scanner would re-lock the dead-but-not-yet-corpse mob and burn another + // cast on it. Self-prunes at the top of ScanNearbyTargets. + private readonly Dictionary _recentlyKilled = new(); + private readonly List _killPruneScratch = new(); + private const double RECENTLY_KILLED_SUPPRESS_MS = 4000.0; // confirmed kill + private const double PREDICTED_SWAP_SUPPRESS_MS = 2000.0; // predicted kill (re-acquirable if it survived) + + // ── Kill-shot prediction (damage-based, selection-free) ────────────────── + // Combat can't read an unselected mob's live health (ACE only pushes vitals + // for the SELECTED target, and combat is selection-free). Instead we learn + // from the EXACT per-hit damage the engine pushes (AttackerNotification + // 0x01B1): accumulate damage dealt this fight, compare to the mob's HP + // (appraised MaxHealth from the shared CreatureProfileStore, else learned + // damage-to-kill per wcid), and when the cast we just fired is expected to + // finish it, swap to the next target instead of wasting the following cast + // during this projectile's flight. + private CreatureProfileStore? _creatureStore; // shared: MaxHealth + resists by wcid + private MonsterDamageStore? _damageStore; // per-character: avg damage + learned HP by wcid + private int _fightTargetId; // the id _fightDamage is being accumulated for + private uint _fightTargetWcid; // its weenie-class id (stable monster-type key) + private string _fightTargetName = ""; // its name (stored in the learning file for readability) + private double _fightTargetMaxHp; // 0 = not yet known + private double _fightDamage; // cumulative confirmed damage dealt this fight + private int _fightCastCount; // offensive casts fired this fight (for casts-to-kill learning) + private bool _fightAppraiseRequested; // one appraisal attempt per fight to fill unknown HP + + // Predicted one-shots are swapped away BEFORE their own KillerNotification + // arrives, so OnKillNotification (which keys off the CURRENT target) can't + // attribute them — they'd go uncounted and bias casts-to-kill HIGH (the + // recorded average ends up built only from the messier non-swap kills). + // Stash each predicted kill here; record it to the store only when its death + // is CONFIRMED (so a wrong prediction expires unrecorded), and consume the + // matching death-notification so it doesn't drop the (different) live target. + private readonly List _predictedKillPending = new(); + private readonly record struct PendingKill( + string Name, uint Wcid, int CastCount, uint WeaponId, string Element, int Tier, double Damage, DateTime Expiry); + + // Ring of recently-fought objects (by id). The single _lastFight* slot only credits a kill + // that lands one-back; when we've advanced PAST the dying mob (rapid multi-mob melee) its + // death message matches neither the current target nor _lastFight, and the kill is lost + // (KillDbg how=miss). This ring credits it by name across the last few fights. + private readonly List<(int Id, PendingKill Pk)> _recentFights = new(); + private const int RecentFightsCap = 12; + private const double RecentFightTtlMs = 8000.0; + + // name -> wcid for monsters seen by the scanner this session. AOE/area casts kill mobs we + // never directly fought (ACE streams health only for the selected target, so tiers 1-4 never + // saw them) — tier 5 credits those kills by matching the death message against these names. + // Same pump thread as the scanner and OnKillNotification, so no lock needed. + private readonly Dictionary _seenMonsterNameToWcid = + new(StringComparer.OrdinalIgnoreCase); + + // Persistent snapshot of the most-recently-cast-at fight — survives DropTarget + // (which zeroes _fightTarget*). When a kill arrives after the bot has already + // dropped/advanced (common when one-shotting fast: the corpse's KillerNotification + // lands a beat after we moved on), this lets the kill still be credited by name. + private uint _lastFightWcid; + private string _lastFightName = ""; + private uint _lastFightWeaponId; + private string _lastFightElement = ""; + private int _lastFightTier; + private int _lastFightCount; + private int _killDbgCount; + private string _lastCastElement = "Fire"; // element of the most recent offensive cast + private int _lastCastTier; // tier (spell level) of the most recent offensive cast + private uint _lastCastWeaponId; // weapon (wand) guid the most recent cast used — damage varies by weapon + private int _equippedWeaponId; // weapon EquipWeaponAndSetStance last wielded (any mode) — drives melee/missile damage learning + private bool _predictKillSwap; // set by AttackWithMagic, consumed in Think after the cast + // Predicted kill shot is ARMED here but only executed once the cast is + // CONFIRMED accepted (ACE: no "You're too busy!" within the refusal window). + // The old code dropped the target 1ms after issuing the cast — so a REFUSED + // cast still abandoned a live mob and advanced to the next, churning the + // swarm and pinning AC's m_cBusy (the "can't enter combat mode" wedge). + private bool _predictKillSwapArmed; + private bool _predictSwapGestureSeen; // observed the cast windup since arming (gate the swap on it) + private const double PredictKillSwapMaxWaitMs = 3000; // hard cap: a tier-8 cast fully resolves well within this + private const double KILL_CONFIDENCE = 0.80; // predict kill if remaining HP <= avg cast damage * this + private const int KILL_MIN_SAMPLES = 3; // need this many learned hits before trusting the avg + + internal void SetDamageStores(CreatureProfileStore? creatures, MonsterDamageStore? damage) + { + _creatureStore = creatures; + _damageStore = damage; + } + + public int RaycastBlockCount { get; private set; } + public int RaycastCheckCount { get; private set; } + + // D2 three-tier target telemetry, refreshed each ScanNearbyTargets() so a + // "scanned=0 vs live mobs" wedge shows WHICH stage zeroed the candidate set: + // Total>0,Ring=0 → mobs exist but all out of engage range (nav/spawn issue) + // Ring>0,Possible=0 → over-filtering (blacklist / not-attackable / LOS) + // Total=0 → genuinely blind (cache empty / respawn-blind) + // -1 = no scan has run yet this session. + public int LastScanTotalMonsters { get; private set; } = -1; // real monsters the client renders + public int LastScanInRing { get; private set; } = -1; // of those, within MonsterRange + public int LastScanPossible { get; private set; } = -1; // survive all combat filters (= candidates) + public int LastScanLosBlocked { get; private set; } = -1; // in range + attackable but wall-blocked + + // D6 offensive attack-cast counters. CastsSinceLastKill climbing while kills stay + // flat is the early signal of the "animates but 0 damage / too busy forever" orphan. + public int SessionAttackCasts { get; private set; } + public int CastsSinceLastKill { get; private set; } + + // ── Monster scanner ────────────────────────────────────────────────── + // Pre-scans nearby creatures for distance, IsAttackable, and LOS. + // Combat picks from this list — no SelectItem needed until attack time. + private readonly List _scannedTargets = new(); + private DateTime _lastScanTime = DateTime.MinValue; + private const int SCAN_INTERVAL_MS = 50; + + // Utility-AI target switching: every candidate is scored each tick. + // The currently-locked target gets this bonus so we don't flap on near-ties — + // an alternative must beat (locked_score + STICKINESS) to take over. + private const double TARGET_SWITCH_STICKINESS = 25.0; + + // Extra hold applied ON TOP of stickiness once we have actually landed damage + // on the locked target — "finish what you started". Stickiness alone only + // breaks near-ties; this is what stops combat walking away from a half-dead + // mob because something undamaged wandered closer. Cleared with the rest of + // the fight state on switch/DropTarget. See HandleCombatTrigger. + private const double DAMAGE_COMMITMENT_BONUS = 20.0; + + /// How long a cast-issue commitment arm survives without damage + /// landing. Covers a projectile's flight (Force Arc confirms at a ~650ms + /// median, damage follows) without granting open-ended immunity to a target + /// that never takes damage. See the arming block in HandleCombatTrigger. + private const double CastCommitmentWindowMs = 4000.0; + + /// Ceiling on how long a target that has never taken damage may keep + /// the commitment bonus after being locked. Past this it competes on its own + /// merits again, so an unkillable or unreachable mob cannot hold the lock + /// forever — the 2026-09-05 stall, where one Olthoi absorbed 5+ hours and + /// ~3,100 casts because commitment never expired and + /// TargetNoProgressTimeoutSec defaults to 0 (disabled). + private const double UndamagedCommitmentMaxMs = 15000.0; + + /// When the last offensive action was issued at + /// . Bounds the cast-issue commitment arm. + private DateTime _lastAttackedAt = DateTime.MinValue; + + // Distance (m) at which the melee-threat bonus reaches full value. The bonus + // ramps continuously to this range instead of switching on at a hard edge — + // as a step it was worth more than TARGET_SWITCH_STICKINESS, so a mob + // drifting across the line flipped the winner every tick. See ScoreCandidate. + private const double THREAT_RANGE_M = 5.0; + + // Incumbent continuity across scan gaps. ScanNearbyTargets drops a target on + // a single bad LOS result or a transient miss — the candidate list has been + // observed oscillating 14<->17 entries tick to tick. HandleCombatTrigger + // scores only what is in the list, so an incumbent that blinks out scores + // NOTHING and loses to any challenger. That is the "score=gone" switch, and + // it defeats TARGET_SCAN_GRACE_MS, whose stated job is that "one bad LOS + // result or scan gap shouldn't hand control to navigation" — it protected + // the target from being DROPPED but not from being OUTSCORED while absent. + // Carry the last computed score for the grace window instead. + private double _lockedLastScore = double.MinValue; + private DateTime _lockedLastSeenInScan = DateTime.MinValue; + + public struct ScannedTarget + { + public int Id; + public double Distance; + public double Angle; // absolute facing error to target, degrees (0 = directly ahead) + public string Name; + } + + /// List of nearby, attackable, LOS-clear creatures. Re-scanned every tick (≤50 ms). + /// Sorted by distance — selection itself is score-based via HandleCombatTrigger. + public IReadOnlyList ScannedTargets => _scannedTargets; + + /// True when combat has an active target or viable targets nearby. Used to block navigation. + public bool HasTargets => activeTargetId != 0 || _scannedTargets.Count > 0; + + // Monsters that passed range/attackable checks but were LOS-blocked by walls. + // Non-zero means a monster is nearby but not yet visible — nav should stop. + private int _nearbyNoLos; + + /// True when any monster is in range, regardless of LOS. Use this for nav-blocking so + /// the bot stops before walking through a portal into a room with monsters. + public bool HasNearbyMonsters => HasTargets || _nearbyNoLos > 0; + + /// True if any scanned target is within yards. Used by loot/salvage gates to decide when to yield to combat. + public bool HasCloseThreat(double yd) + { + for (int i = 0; i < _scannedTargets.Count; i++) + if (_scannedTargets[i].Distance <= yd) return true; + return false; + } + + /// True only when actively attacking a specific target. Unlike HasTargets, this is false between kills even when more monsters are scanned nearby. + public bool IsActivelyEngaged => activeTargetId != 0; + + /// Yards inside which a scanned mob counts as "on top of me". + private const double CloseAttackYards = 5.0; + + /// + /// "A fight is actually happening to me" — the arbiter's escape hatch that + /// lets Combat preempt BoostLootPriority (2026-06-03 audit P1#1). + /// + /// Deliberately NOT HasEngageableTarget: that is true for any scanned mob + /// inside MonsterRange, which would make BoostLootPriority meaningless. + /// And deliberately not IsActivelyEngaged alone: while BoostLoot holds the + /// Looting decision, canRun blocks Think(), so activeTargetId never gets + /// set — keying the escape on it would be circular (blocked → no lock → + /// still blocked → mob keeps hitting a bot that never fights back). The + /// scan always runs and has no side effects, so a close-range scanned mob + /// is the non-circular signal. + /// + public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards); + + /// + /// Pure predicate for the ActivityArbiter: should Combat claim this tick? + /// True iff we're already locked on a target, OR a scanned target (the + /// scan is already filtered to attackable + LOS-clear) is within actual + /// engage range (MonsterRange — the same distance Think() uses for its + /// attack gate). Deliberately NOT HasTargets: HasTargets is true for any + /// scanned creature including unreachable/out-of-range ones, which made + /// Combat squat on the action lock without ever attacking while nav was + /// blocked — the "stands there surrounded by far-off mobs" freeze. With + /// this predicate, far mobs → Combat doesn't claim → nav runs and closes + /// distance → once within MonsterRange this flips true → Combat takes over. + /// No side effects; safe to call from the arbiter's pure decision path. + /// + public bool HasEngageableTarget => + IsActivelyEngaged || HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)); + + /// + /// Distance at which an already-locked target is dropped / stops being + /// attacked. Larger than MonsterRange (the acquire distance) to form a + /// hysteresis deadband around the combat-mode step-back. Configurable via + /// MonsterDisengageRange; 0 or any value not exceeding MonsterRange falls + /// back to MonsterRange + 3. + /// + private double DisengageDistance => + _settings.MonsterDisengageRange > _settings.MonsterRange + ? _settings.MonsterDisengageRange + : _settings.MonsterRange + 3; + + /// Diagnostic snapshot for /ra combat — exposes the internal state machine fields. + public CombatStateSnapshot GetStateSnapshot() + { + // Pick the same weapon EquipWeaponAndSetStance would pick for the active target, + // so the dump shows which weapon combat is trying to swing/cast with. + WorldObject? targetObj = activeTargetId != 0 ? _worldFilter[activeTargetId] : null; + int pickedWeaponId = 0; + string pickedWeaponName = ""; + int pickedWeaponMode = 0; + int weaponWieldLoc = -1; + if (targetObj != null) + { + // Mirror EquipWeaponAndSetStance: per-wcid Damage-tab weapon (override > best), + // else first configured weapon, else any wand. (rule.WeaponId is no longer consulted.) + uint dwcid = 0; + if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)targetObj.Id, out uint dw)) dwcid = dw; + uint deff = (dwcid != 0 && _damageStore != null) ? _damageStore.GetEffectiveWeapon(dwcid) : 0; + if (deff != 0) + pickedWeaponId = (int)deff; + else + { + var bestWeapon = _settings.ItemRules.FirstOrDefault(); + if (bestWeapon != null) pickedWeaponId = bestWeapon.Id; + } + if (pickedWeaponId == 0) pickedWeaponId = FindWandInItems(); + + if (pickedWeaponId != 0) + { + var w = _worldFilter[pickedWeaponId]; + if (w != null) + { + pickedWeaponName = w.Name ?? ""; + weaponWieldLoc = w.Values(LongValueKey.CurrentWieldedLocation, 0); + pickedWeaponMode = IsWandObject(w) ? CombatMode.Magic + : w.ObjectClass == AcObjectClass.MissileWeapon ? CombatMode.Missile + : CombatMode.Melee; + } + } + } + + int liveMode = -1; + if (_host.HasGetCurrentCombatMode) + { + try { liveMode = _host.GetCurrentCombatMode(); } catch { liveMode = -1; } + } + + bool hasAmmo = false; + try { hasAmmo = HasWieldedAmmo(); } catch { hasAmmo = false; } + + return new() + { + ActiveTargetId = activeTargetId, + LockedTargetId = _lockedTargetId, + ScannedCount = _scannedTargets.Count, + ClosestScannedId = _scannedTargets.Count > 0 ? _scannedTargets[0].Id : 0, + ClosestScannedName = _scannedTargets.Count > 0 ? _scannedTargets[0].Name ?? "" : "", + ClosestScannedDist = _scannedTargets.Count > 0 ? _scannedTargets[0].Distance : 0.0, + BusyCount = BusyCount, + FacingTarget = _facingTarget, + TargetLostScanTime = _targetLostScanTime, + LastAttackCmd = lastAttackCmd, + LastStanceAttempt = lastStanceAttempt, + LastEquipTime = _lastEquipTime, + CurrentCombatMode = CurrentCombatMode, + LiveCombatMode = liveMode, + BotAction = _settings.BotAction ?? "", + EnableCombat = _settings.EnableCombat, + IsMacroRunning = _settings.IsMacroRunning, + PickedWeaponId = pickedWeaponId, + PickedWeaponName = pickedWeaponName, + PickedWeaponMode = pickedWeaponMode, + PickedWeaponWieldLoc = weaponWieldLoc, + HasWieldedAmmoFlag = hasAmmo, + LastCombatSkipReason = LastCombatSkipReason, + }; + } + + public struct CombatStateSnapshot + { + public int ActiveTargetId; + public int LockedTargetId; + public int ScannedCount; + public int ClosestScannedId; + public string ClosestScannedName; + public double ClosestScannedDist; + public int BusyCount; + public bool FacingTarget; + public DateTime TargetLostScanTime; + public DateTime LastAttackCmd; + public DateTime LastStanceAttempt; + public DateTime LastEquipTime; + public int CurrentCombatMode; + public int LiveCombatMode; + public string BotAction; + public bool EnableCombat; + public bool IsMacroRunning; + public int PickedWeaponId; + public string PickedWeaponName; + public int PickedWeaponMode; + public int PickedWeaponWieldLoc; + public bool HasWieldedAmmoFlag; + public string LastCombatSkipReason; + } + + /// + /// Periodic scan of all creatures. Filters: distance, self, blacklist, IsAttackable, raycast LOS. + /// Call from OnHeartbeat or Think. + /// + public void ScanNearbyTargets() + { + if ((DateTime.Now - _lastScanTime).TotalMilliseconds < SCAN_INTERVAL_MS) + return; + _lastScanTime = DateTime.Now; + + // Raycast just became ready (warmup→ready edge, flagged on the bg + // thread): one-time clean slate. Whatever got blacklisted or had its + // miss/no-progress timers run up while targeting was degraded is + // forgiven, so mobs that were present at login are re-evaluated with + // real LOS/attack-type instead of being sidelined for 5 minutes. + if (_raycastReadyResetPending) + { + _raycastReadyResetPending = false; + _blacklistManager.ClearAll(); + _consecutiveCastMisses = 0; + _pendingJudgeCastAt = DateTime.MinValue; + _lastAttackedTargetId = 0; + _targetLockedAt = DateTime.MinValue; + _lastDamageDealtAt = DateTime.MinValue; + _host.Log("[RynthAi] Raycast ready — combat clean slate (blacklist cleared, target timers reset)."); + } + + // Drop expired kill-suppression entries so the set can't grow unbounded + // over a long session (a suppressed id may never re-enter scan to be + // cleared lazily). Allocation-free: scratch list is reused. + if (_recentlyKilled.Count > 0) + { + DateTime now = DateTime.Now; + _killPruneScratch.Clear(); + foreach (var kv in _recentlyKilled) + if (now >= kv.Value) // Value = expiry time + _killPruneScratch.Add(kv.Key); + for (int i = 0; i < _killPruneScratch.Count; i++) + _recentlyKilled.Remove(_killPruneScratch[i]); + } + + _scannedTargets.Clear(); + _nearbyNoLos = 0; + int scanTotal = 0, scanRing = 0; // D2 telemetry, published after the loop + int playerId = (int)_playerId; + if (playerId == 0) return; + + // Cache player pose once for angle tiebreaker — same math as GetFacingError. + bool hasPose = _host.TryGetPlayerPose(out _, out float ppx, out float ppy, out _, + out float pqw, out _, out _, out float pqz); + double playerHeadingDeg = 0; + if (hasPose) + { + double physYaw = 2.0 * Math.Atan2(pqz, pqw) * (180.0 / Math.PI); + playerHeadingDeg = ((-physYaw) % 360.0 + 720.0) % 360.0; + } + + double maxDist = _settings.MonsterRange; + TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear; + if (RaycastInitialized && _raycastSystem?.TargetingFSM != null) + attackType = _raycastSystem.GetAttackType(CurrentCombatMode, ""); + + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.Id == playerId) continue; + if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue; + + // Never acquire our own spell projectiles (mis-classified as + // Monster, no health record). A real monster is never named + // "Flame Bolt"/"Frost Streak"/etc. + if (IsSpellProjectileName(wo.Name)) continue; + + // D2 telemetry: every real monster the client renders counts toward Total, and (by + // pure proximity) toward Ring. dist is hoisted up here from below the blacklist gate + // so Ring reflects how many mobs are physically near us regardless of the gameplay + // filters below — that's what distinguishes "out of range" from "all filtered out". + scanTotal++; + double dist = _worldFilter.Distance(playerId, wo.Id); + if (dist <= maxDist) scanRing++; + + // User-configured "never attack" list — excluded from acquisition + // entirely (an already-engaged match drops out of _scannedTargets + // here and is released by the scan-grace timer in Think). + if (IsUserBlacklistedName(wo.Name)) continue; + + // Cache name->wcid (once per type) for AOE kill attribution (tier 5): a mob wiped + // by an area cast we never directly fought is credited by matching its death message. + if (!string.IsNullOrEmpty(wo.Name) && _seenMonsterNameToWcid.Count < 256 + && !_seenMonsterNameToWcid.ContainsKey(wo.Name) + && _host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)wo.Id, out uint scanWcid) && scanWcid != 0) + _seenMonsterNameToWcid[wo.Name] = scanWcid; + + if (_blacklistManager.IsBlacklisted(wo.Id)) continue; + + // Just killed (KillerNotification) but not yet a corpse — skip so we + // don't re-lock and cast at it during its death animation. + if (_recentlyKilled.ContainsKey(wo.Id)) continue; + + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)wo.Id)) continue; + + // Dead but not yet reclassified as corpse — skip + if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; + + // Allow the currently-engaged target out to DisengageDistance: AC's + // combat-mode step-back routinely pushes the active target just past + // MonsterRange, and dropping it from the scan defeated the disengage + // hysteresis — it vanished from _scannedTargets and was dropped after + // the 1.5s scan grace despite the distance gate intending to keep + // attacking out to DisengageDistance. + bool isEngaged = wo.Id != 0 && (wo.Id == activeTargetId || wo.Id == _lockedTargetId); + if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue; + + bool losBlocked = false; + if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null) + { + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_host, (uint)wo.Id, attackType)) + { + RaycastBlockCount++; + losBlocked = true; + } + } + + // Don't blacklist from scan — just exclude from this result. + // Blacklisting only happens when an active target fails LOS during attack. + if (losBlocked) + { + _nearbyNoLos++; // in range + attackable but wall-blocked — still stops nav + continue; + } + + double angle = 180.0; + if (hasPose && _host.TryGetObjectPosition((uint)wo.Id, out _, out float tx, out float ty, out _)) + { + double desired = Math.Atan2(tx - ppx, ty - ppy) * (180.0 / Math.PI); + if (desired < 0) desired += 360.0; + double err = desired - playerHeadingDeg; + while (err > 180.0) err -= 360.0; + while (err < -180.0) err += 360.0; + angle = Math.Abs(err); + } + _scannedTargets.Add(new ScannedTarget { Id = wo.Id, Distance = dist, Angle = angle, Name = wo.Name }); + } + + // Primary: closest first. Tiebreaker within 0.5yd: smallest facing angle first. + _scannedTargets.Sort((a, b) => + { + double dd = a.Distance - b.Distance; + if (Math.Abs(dd) > 0.5) return dd < 0 ? -1 : 1; + return a.Angle.CompareTo(b.Angle); + }); + + // Publish D2 telemetry (whole-int writes are atomic; the plugin tick reads these on the + // same pump thread before pushing them to the status feed). + LastScanTotalMonsters = scanTotal; + LastScanInRing = scanRing; + LastScanPossible = _scannedTargets.Count; + LastScanLosBlocked = _nearbyNoLos; + } + + public CombatManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache worldFilter, SpellManager? spellManager = null) + { + _host = host; + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _worldFilter = worldFilter ?? throw new ArgumentNullException(nameof(worldFilter)); + _spellManager = spellManager; + // Diagnostic: surface every blacklist (any path) with id + reason so a + // single login test is conclusive instead of another guess. + _blacklistManager.Log = m => _host.Log($"[Blacklist] {m}"); + } + + public void SetSpellManager(SpellManager spellManager) => _spellManager = spellManager; + public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills; + + /// Plugin forwards every object deletion here (D7/D8). For a genuinely-despawned + /// object (a reliable engine event, unlike a transient scan gap) we: (D8) drop its stale + /// per-id state — kill-suppression + blacklist/failure entries — so a respawn reusing the GUID + /// starts clean instead of inheriting the old 300s timeout; and (D7) if it was the target we + /// were attacking or mid-cast on, clear the cast-resolution/debuff wait so we don't sit out the + /// 2.5s windup timeout casting at nothing. Writes are atomic flag/int sets — safe on any thread. + public void OnObjectDeleted(uint objectId) + { + int id = (int)objectId; + _recentlyKilled.Remove(id); + _blacklistManager.ForgetTarget(id); + + if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId) + _awaitingCastResolution = false; + if (id == _pendingDebuffTargetId) + { + _waitingForDebuffResult = false; + _pendingDebuffTargetId = 0; + } + } + public void SetPlayerId(uint playerId) + { + _playerId = playerId; + _monsterMatchEval = new MonsterMatchEvaluator(_worldFilter, playerId); + } + public void SetRaycastSystem(MainLogic raycast) + { + bool wasReady = RaycastInitialized; + _raycastSystem = raycast; + RaycastInitialized = raycast?.IsInitialized ?? false; + + // Warmup→ready edge. This runs on the raycast-init bg thread, so do + // NOT mutate combat state here — defer the clean slate to the next + // main-thread scan. Anything sidelined while targeting was degraded + // (no LOS, Linear attack-type) gets re-evaluated now it's real. + if (!wasReady && RaycastInitialized) + _raycastReadyResetPending = true; + } + + private uint _playerId; + private MonsterMatchEvaluator? _monsterMatchEval; + + private readonly HashSet _confirmedDebuffs = new(); + private int _lastDebuffTargetId = 0; + + private string? _pendingDebuffKey = null; + private int _pendingDebuffTargetId = 0; + private int _pendingDebuffTier = 0; + private bool _waitingForDebuffResult = false; + private DateTime _pendingDebuffCastTime = DateTime.MinValue; + private const double DEBUFF_RESULT_TIMEOUT_MS = 3000.0; + + // Last offensive (war/void) spell we fired and when. If AC never answers it + // (char doesn't know it, or no components) the no-chat valve in + // AttackWithMagic marks it unresolvable so FindBestOffensiveSpellId tiers + // down to an alternative the char actually has — same empirical signal the + // buff path uses (the engine IsSpellKnown oracle lies "true" for unknowns). + private int _pendingOffensiveSpellId = 0; + private DateTime _pendingOffensiveCastAt = DateTime.MinValue; + // Target id captured when the offensive cast was *issued*, so the + // chat-confirmation handler can record the cast against the right target + // for blacklist judgement — even if activeTargetId has since changed. + private int _pendingOffensiveTargetId = 0; + private const double OFFENSIVE_NOCHAT_TIMEOUT_MS = 5000.0; + // ACE doesn't emit "You cast X" chat for offensive war magic, so we infer + // a successful server cast by NEGATION: if no "You're too busy!" arrives + // within this many ms of issuance, the gesture proceeded — queue the cast + // for blacklist judgement. Server "too busy" responses arrive within + // ~100–200ms; 500ms is a comfortable margin without delaying the next + // attempt noticeably. + private const double OffensiveRefusalWindowMs = 500.0; + + // Throttled lowercased inventory-name set for the predictive component + // gate (TrySpellByName is called many times per resolution; rebuilding the + // set every call would be wasteful). _compSkipLogged dedupes the skip log + // within a cache window so a tiered-down spell doesn't spam the log. + private readonly HashSet _invNamesLower = new(); + private DateTime _invNamesBuiltAt = DateTime.MinValue; + private const double InvNameCacheMs = 1000.0; + private readonly HashSet _compSkipLogged = new(); + + // Predictive component gate is OFF: the dat formula is the full historical + // recipe, not ACE's actual (reduced) requirement, so it false-rejected + // every spell. Empirical no-components learning + persistence handles it + // reliably instead. See the long note in TrySpellByName. + private const bool EnablePredictiveComponentGate = false; + + private static readonly Dictionary DebuffSpells = new(StringComparer.OrdinalIgnoreCase) + { + { "Fester", new[] { "Fester Other", "Decrepitude's Grasp" } }, + { "Broadside", new[] { "Missile Weapon Ineptitude Other", "Broadside of a Barn" } }, + { "Gravity", new[] { "Vulnerability Other", "Gravity Well" } }, + { "Imperil", new[] { "Imperil Other", "Gossamer Flesh" } }, + { "Yield", new[] { "Magic Yield Other", "Yield" } }, + }; + + private static readonly Dictionary SpellShapes = new(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Flame Arc", "Ring of Fire", "Flame Streak", "Flame Bolt" } }, + { "Cold", new[] { "Frost Arc", "Frost Ring", "Frost Streak", "Frost Bolt" } }, + { "Lightning", new[] { "Lightning Arc", "Shock Ring", "Lightning Streak", "Shock Wave" } }, + { "Acid", new[] { "Acid Arc", "Acid Ring", "Acid Streak", "Acid Stream" } }, + { "Blade", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + { "Pierce", new[] { "Force Arc", "Force Ring", "Force Streak", "Force Bolt" } }, + { "Bludgeon", new[] { "Bludgeoning Arc", "Bludgeoning Ring", "Bludgeoning Streak", "Shock Wave" } }, + { "Slash", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + }; + + // War Streak/Bolt lines have NO "{base} VII" — their tier-7 is a + // lore-named spell (Arc uses Roman "VII"; Ring uses RingLoreNames). + // [0] = Streak VII lore, [1] = Bolt VII lore. Names verified against + // SpellData.txt skill-300 entries 2026-05-17 (e.g. Force Streak VII = + // "Outlander's Insolence" id 2133). Slash shares the Blade family. + private static readonly Dictionary WarTier7Lore = new(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Sizzling Fury", "Ilservian's Flame" } }, + { "Cold", new[] { "Sudden Frost", "Icy Torment" } }, + { "Lightning", new[] { "Lhen's Flare", "Alset's Coil" } }, + { "Acid", new[] { "Corrosive Flash", "Disintegration" } }, + { "Blade", new[] { "Rending Wind", "Evisceration" } }, + { "Slash", new[] { "Rending Wind", "Evisceration" } }, + { "Pierce", new[] { "Outlander's Insolence", "The Spike" } }, + { "Bludgeon", new[] { "Cameron's Curse", "Crushing Shame" } }, + }; + + private static readonly Dictionary RingLoreNames = new(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Cassius' Ring of Fire", "Cassius' Ring of Fire II" } }, + { "Cold", new[] { "Halo of Frost", "Halo of Frost II" } }, + { "Lightning", new[] { "Eye of the Storm", "Eye of the Storm II" } }, + { "Acid", new[] { "Searing Disc", "Searing Disc II" } }, + { "Blade", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Slash", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Pierce", new[] { "Nuhmudira's Spines", "Nuhmudira's Spines II" } }, + { "Bludgeon", new[] { "Tectonic Rifts", "Tectonic Rifts II" } }, + }; + + private static readonly Dictionary VoidSpellShapes = new(StringComparer.OrdinalIgnoreCase) + { + { "Nether", new[] { "Nether Arc", "Nether Ring", "Nether Streak", "Nether Bolt" } }, + { "Fire", new[] { "Corrosion Arc", "Corrosion Ring", "Corrosion Streak", "Nether Bolt" } }, + }; + + // In-world war/void projectiles are named exactly the spell's shape base + // (e.g. "Flame Bolt", "Frost Streak"). The object cache sometimes mis- + // classifies these transient objects as Monster and they carry no health + // record, so the combat scanner would lock onto the bot's OWN projectile, + // burn casts on it (no damage possible) and blacklist it. No real + // attackable monster is ever named one of these — they are excluded from + // target selection. Built once from the authoritative shape tables. + private static readonly HashSet ProjectileNames = BuildProjectileNames(); + + private static HashSet BuildProjectileNames() + { + var set = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var arr in SpellShapes.Values) + foreach (var n in arr) set.Add(n); + foreach (var arr in VoidSpellShapes.Values) + foreach (var n in arr) set.Add(n); + return set; + } + + private static bool IsSpellProjectileName(string? name) + => !string.IsNullOrEmpty(name) && ProjectileNames.Contains(name); + + public void InitializeRaycasting(string? acFolderPath = null) + { + try + { + _raycastSystem = new MainLogic(); + if (string.IsNullOrEmpty(acFolderPath)) acFolderPath = @"C:\Turbine\Asheron's Call"; + RaycastInitialized = _raycastSystem.Initialize(acFolderPath); + } + catch { RaycastInitialized = false; } + } + + // Crit detection: AC may send the crit indicator inline ("...critically...") + // or as a separate line just before the damage line — track the last crit + // line so a damage line arriving within the window is credited as a crit. + private DateTime _lastCritChatAt = DateTime.MinValue; + private const double CRIT_WINDOW_MS = 600; + private int _dmgDbgCount; + + /// + /// Parse OUR outgoing damage out of the combat-log chat and feed it to the + /// per-monster crit/non-crit learning. War magic sends NO AttackerNotification + /// (0x01B1), so the chat line "You blast X for N points of fire damage!" is the + /// only damage source for casters — this is what fills the Crit/NonCrit columns. + /// MAGIC-ONLY: melee/missile get the structured 0x01B1 event (OnCombatDamage), + /// so parsing chat for them too would double-count. + /// + public void HandleChatForDamage(string text) + { + if (string.IsNullOrEmpty(text) || _damageStore == null) return; + + DateTime now = DateTime.Now; + bool critLine = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0; + if (critLine) _lastCritChatAt = now; + + if (!TryParseOutgoingDamage(text, out int amount)) return; + bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS; + + // Attribute to the current fight; if it's already cleared (we one-shot and + // moved on before the damage line landed), fall back to the last-fight + // snapshot — same wcid as the bolt, so the crit/non-crit average is right. + bool cur = _fightTargetWcid != 0; + uint wcid = cur ? _fightTargetWcid : _lastFightWcid; + + if (_dmgDbgCount < 15) + { + _dmgDbgCount++; + _host.Log($"[DmgDbg] amt={amount} crit={crit} wcid={wcid} mode={CurrentCombatMode} text='{text}'"); + } + + // MAGIC-ONLY: melee/missile get the structured 0x01B1 event (OnCombatDamage), + // so parsing chat for them too would double-count. + if (CurrentCombatMode != CombatMode.Magic || wcid == 0) return; + + // Feed the kill-shot predictor. War magic gets no 0x01B1, so this chat + // line is the ONLY damage signal for casters — without accumulating it, + // _fightDamage stayed 0: EvaluateKillShot path B always saw a full-HP + // target and RecordKill(totalDamage:0) never learned HP pools. + if (cur) + _fightDamage += amount; + + uint weapon = cur ? _lastCastWeaponId : _lastFightWeaponId; + string nm = cur ? _fightTargetName : _lastFightName; + string elem = cur ? _lastCastElement : _lastFightElement; + int tier = cur ? _lastCastTier : _lastFightTier; + _damageStore.RecordHit(weapon, wcid, nm, elem, tier, amount, crit); + } + + /// + /// Extract our outgoing damage amount from a combat-log line. Two wordings reach us: + /// • Retail combat log: "You blast X for 153 points of fire damage!" + /// • ACE war/void magic: "You blast X for 153 points with Whirling Blade VII." + /// (ACEmulator's SpellProjectile.DamageTarget emits "for {amount} points with + /// {Spell.Name}" — NOT "points of damage" — so the old retail-only + /// parser matched nothing on ACE and the Crit/NonCrit columns stayed empty.) + /// Returns false for incoming ("... you for N points ...") and non-damage + /// "points of <vital>" lines (heals / mana / stamina drains). Allocation-free (hot path). + /// + private static bool TryParseOutgoingDamage(string text, out int amount) + { + amount = 0; + + // Anchor on the word "points" (shared by both wordings). The number is the run + // of digits immediately before it; the word right AFTER it disambiguates: + // "points with ..." → ACE damage cast (only the projectile msg uses this) + // "points of ... damage" → retail damage + // "points of mana/stamina/..." → vital drain/heal (no "damage") → reject + int pts = text.IndexOf("points", StringComparison.OrdinalIgnoreCase); + if (pts < 0) return false; + + int w = pts + 6; // first char after "points" + while (w < text.Length && text[w] == ' ') w++; + bool nextWith = WordAt(text, w, "with"); + bool nextOf = WordAt(text, w, "of"); + bool isDamage = nextWith + || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0); + if (!isDamage) return false; + + // Incoming (we got hit) lines read "... you for N points ..." — not our damage. + if (text.IndexOf("you for", 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; + return true; + } + + /// Case-insensitive whole-word match of (passed lowercase) + /// at in , bounded by end-of-string or a + /// non-letter. Allocation-free. + private static bool WordAt(string text, int pos, string word) + { + if (pos < 0 || pos + word.Length > text.Length) return false; + for (int k = 0; k < word.Length; k++) + if (char.ToLowerInvariant(text[pos + k]) != word[k]) return false; + int end = pos + word.Length; + return end >= text.Length || !char.IsLetter(text[end]); + } + + public void HandleChatForDebuffs(string text) + { + if (string.IsNullOrEmpty(text)) return; + + // Offensive (war/void) cast resolution — runs independent of the debuff + // gate (this handler is called for every chat line). Mirrors + // BuffManager's categorisation so a war spell the char can't actually + // cast gets marked unresolvable and FindBestOffensiveSpellId drops to + // an alternative, instead of silently re-firing the dead spell forever. + if (_pendingOffensiveSpellId != 0) + { + string lo = text.ToLowerInvariant(); + + // "You're too busy!" — server refused the cast mid-gesture (a + // previous cast is still animating). NOT a real cast: must NOT + // count toward the blacklist miss streak. Clear pending silently + // so JudgePendingOffensiveCast's 500ms no-too-busy window stays + // honest, and the next attempt can be issued under the throttle. + if (lo.Contains("you're too busy") || lo.Contains("you are too busy")) + { + _pendingOffensiveSpellId = 0; + _pendingOffensiveTargetId = 0; + // The cast was REFUSED (a prior gesture is still animating) — it + // never fired, so undo the casts-to-kill increment that issuance + // optimistically added. The blacklist counter already excludes + // refusals; without this, casts-to-kill reads >1 on pure one-shots. + if (_fightCastCount > 0) _fightCastCount--; + // Cancel any armed predicted kill-shot swap — the cast that armed + // it was refused, so the mob is still alive: keep + retry it + // instead of advancing. This is the core of the anti-wedge fix. + _predictKillSwapArmed = false; + } + // Hard reject: no components / unknown / no target. Same phrases the + // buff path treats as a hard rejection. Mark unresolvable so the + // tier loop drops down (faster than waiting out the no-chat valve). + else if (lo.Contains("missing some required") || + lo.Contains("you do not have the") || + lo.Contains("have all the components for this spell")) + { + _spellManager?.MarkSpellUnresolvable(_pendingOffensiveSpellId); + _host.Log($"[CombatCast] NO-COMPONENTS id={_pendingOffensiveSpellId} " + + $"'{SpellTableStub.GetById(_pendingOffensiveSpellId)?.Name}' — '{text.Trim()}'. " + + $"Marked unresolvable → tiering down to an alternative."); + _pendingOffensiveSpellId = 0; + } + else + { + // Success / fizzle / resisted ⇒ the char DOES know it and has + // components — clear pending, never mark. Match the cast id to + // ours so a debuff's "ou cast" can't falsely clear it; on a + // name-lookup miss, leave pending (the no-chat valve backstops). + int ci = text.IndexOf("ou cast ", StringComparison.OrdinalIgnoreCase); + if (ci >= 0) + { + string after = text.Substring(ci + 8); + int onI = after.IndexOf(" on ", StringComparison.OrdinalIgnoreCase); + int cI = after.IndexOf(','); + int e = after.Length; + if (onI > 0) e = onI; + if (cI > 0 && cI < e) e = cI; + int castId = SpellDatabase.GetIdByName(after.Substring(0, e).Trim()); + if (castId == _pendingOffensiveSpellId) + { + // ACE doesn't emit "You cast X" for offensive war + // magic, so on ACE this branch is effectively dead — + // the successful-cast detection happens via + // JudgePendingOffensiveCast (no "too busy" within + // OffensiveRefusalWindowMs of the issue). This branch + // is kept so forks/retail that DO emit chat still + // clear pending; it must NOT itself call + // RecordOffensiveCast or the cast would double-count. + _pendingOffensiveSpellId = 0; + _pendingOffensiveTargetId = 0; + } + } + else if (lo.Contains("fizzle") || lo.Contains("resists your spell")) + { + _pendingOffensiveSpellId = 0; + _predictKillSwapArmed = false; // cast didn't land — don't swap off a live mob + } + } + } + + if (!_waitingForDebuffResult) return; + + // AC strips the leading 'Y' from cast-confirmation chat — text arrives as + // "ou cast …". IndexOf matches both "You cast" and "ou cast". + if (text.IndexOf("ou cast ", StringComparison.OrdinalIgnoreCase) >= 0) + { + string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; + _confirmedDebuffs.Add(key); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + + if (text.IndexOf("fizzle", StringComparison.OrdinalIgnoreCase) >= 0) + { + _host.WriteToChat($"[RynthAi] Fizzled: {_pendingDebuffKey} — recasting", 2); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + + if (text.IndexOf("resists your spell", StringComparison.OrdinalIgnoreCase) >= 0) + { + _host.WriteToChat($"[RynthAi] Resisted: {_pendingDebuffKey} — recasting", 2); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + } + + public void ReportDamageOnTarget(int targetId) + { + // Damage / health change on the cast we're judging → that cast HIT. + if (targetId == _pendingJudgeTargetId) + _damageSincePendingCast = true; + // Immediate positive feedback on the engaged target clears the streak. + if (targetId == _lastAttackedTargetId) + _consecutiveCastMisses = 0; + _blacklistManager.ClearFailure(targetId); + if (targetId == activeTargetId || targetId == _lockedTargetId) + _lastDamageDealtAt = DateTime.Now; + } + + /// + /// True if a monster's name matches the user-configured never-attack list + /// (case-insensitive substring, so "Drudge" excludes every drudge). Blank + /// entries are ignored. This is the manual do-not-attack list and is distinct + /// from the automatic no-damage blacklist. + /// + private bool IsUserBlacklistedName(string? name) + { + if (string.IsNullOrEmpty(name)) return false; + var list = _settings.MonsterNameBlacklist; + if (list == null || list.Count == 0) return false; + for (int i = 0; i < list.Count; i++) + { + string entry = list[i]; + if (!string.IsNullOrWhiteSpace(entry) && + name.IndexOf(entry.Trim(), StringComparison.OrdinalIgnoreCase) >= 0) + return true; + } + return false; + } + + /// + /// True during the post-login window where raycasting is enabled but the + /// DAT parse hasn't finished, so combat targeting runs degraded (no LOS, + /// Linear attack-type fallback). Attacks miss for reasons unrelated to the + /// target — blacklist accrual must be suppressed here, otherwise the first + /// mobs after login get sidelined for BlacklistTimeoutSec (default 300s) + /// and nav runs the bot straight past them. + /// + private bool RaycastWarmingUp => _settings.EnableRaycasting && !RaycastInitialized; + + /// + /// Judge the cast awaiting a verdict. A cast becomes a "miss" only once + /// BlacklistCastSettleMs has elapsed with no damage on the target — so the + /// damage/health packet has time to land and blacklisting is driven by + /// confirmed no-damage casts, never wall-clock time. BlacklistAttempts + /// consecutive misses → blacklist. Called every combat cycle and before + /// recording a new cast so the last cast is still judged. + /// + private void JudgePendingCast() + { + if (_pendingJudgeCastAt == DateTime.MinValue) return; + if (RaycastWarmingUp) { _pendingJudgeCastAt = DateTime.MinValue; return; } + if ((DateTime.Now - _pendingJudgeCastAt).TotalMilliseconds < _settings.BlacklistCastSettleMs) + return; // not settled yet — give the damage/health packet time + + int tid = _pendingJudgeTargetId; + bool hit = _damageSincePendingCast; + _pendingJudgeCastAt = DateTime.MinValue; + + if (hit) { _consecutiveCastMisses = 0; return; } + + _consecutiveCastMisses++; + if (_consecutiveCastMisses >= _settings.BlacklistAttempts) + { + _blacklistManager.ReportFailure(tid); + if (_blacklistManager.IsBlacklisted(tid)) + { + string what = CurrentCombatMode == CombatMode.Magic ? "casts" : "attacks"; + _host.WriteToChat($"[RynthAi] {_consecutiveCastMisses} {what} with no damage — blacklisting 0x{(uint)tid:X8}", 2); + _consecutiveCastMisses = 0; + if (tid == activeTargetId) + DropTarget($"blacklisted after {_settings.BlacklistAttempts} no-damage {what}"); + } + } + } + + /// + /// ACE doesn't emit "You cast X" chat for offensive war magic, so the + /// offensive cast-confirmation works by NEGATION: cast issuance sets + /// _pendingOffensiveSpellId/CastAt/TargetId; if a "You're too busy!" chat + /// hits within OffensiveRefusalWindowMs the chat handler clears pending + /// silently (server refused, don't count); otherwise this method runs + /// once that window has elapsed and queues the cast for blacklist + /// judgement (the BlacklistCastSettleMs damage-wait then runs in + /// JudgePendingCast as usual). Effect: refused spam attempts never reach + /// _consecutiveCastMisses. + /// + private void JudgePendingOffensiveCast() + { + if (_pendingOffensiveSpellId == 0) return; + if (_pendingOffensiveTargetId == 0) return; + if (_pendingOffensiveCastAt == DateTime.MinValue) return; + if ((DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds < OffensiveRefusalWindowMs) + return; + + // Refusal window passed without a "too busy" — the server accepted + // the gesture. Queue this cast for blacklist judgement. + int targetId = _pendingOffensiveTargetId; + _pendingOffensiveSpellId = 0; + _pendingOffensiveTargetId = 0; + _pendingOffensiveCastAt = DateTime.MinValue; + RecordOffensiveCast(targetId); + } + + /// + /// Record that an attack (offensive spell cast / weapon swing) was just + /// issued at . The prior attack is judged first; + /// a new judgement window is then armed ONLY if none is still in flight. + /// Not clobbering an unsettled window is what makes melee/missile count at + /// all: those modes re-attack every 1000ms (attackCmdIntervalMs) while the + /// settle window is BlacklistCastSettleMs (default 1500ms), so resetting the + /// timer every cycle meant the pending attack never settled and the miss + /// streak never advanced — only magic (≥1500ms cadence) ever blacklisted. + /// Now each attack window runs to settle, so the blacklist is driven by + /// "N real attacks with no damage" for casts, missile shots, and melee + /// swings alike — never raw interval ticks. + /// + private void RecordOffensiveCast(int targetId) + { + if (_lastAttackedTargetId != targetId) + { + // New target — reset streak + drop any stale pending judgement. + _lastAttackedTargetId = targetId; + _consecutiveCastMisses = 0; + _pendingJudgeCastAt = DateTime.MinValue; + } + + // Stamped on EVERY offensive action, not just a target change, so the + // cast-issue commitment window tracks the most recent cast. Stamping only + // on change would expire commitment mid-fight while still casting at the + // same mob — reintroducing the in-flight abandonment this exists to stop. + _lastAttackedAt = DateTime.Now; + + JudgePendingCast(); // verdict on the prior attack if its settle window elapsed + + // An attack is still awaiting its verdict — let it settle instead of + // restarting the clock (the fast-cadence starvation fix). JudgePendingCast + // clears _pendingJudgeCastAt on settle, so the next attack re-arms here. + if (_pendingJudgeCastAt != DateTime.MinValue) return; + + _pendingJudgeCastAt = DateTime.Now; + _pendingJudgeTargetId = targetId; + _damageSincePendingCast = false; + } + + private void DropTarget(string reason) + { + if (activeTargetId != 0) + _host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason}"); + activeTargetId = 0; + _lockedTargetId = 0; + _facingTarget = false; + _returnToPhysicalCombat = false; + _targetLockedAt = DateTime.MinValue; + _lastDamageDealtAt = DateTime.MinValue; + _lockedLastScore = double.MinValue; + _lockedLastSeenInScan = DateTime.MinValue; + _targetLostScanTime = DateTime.MinValue; + _pendingJudgeCastAt = DateTime.MinValue; + _consecutiveCastMisses = 0; + // Reset kill-shot fight tracking — the next acquired target starts fresh. + _fightTargetId = 0; + _fightTargetWcid = 0; + _fightTargetName = ""; + _fightTargetMaxHp = 0; + _fightDamage = 0; + _fightCastCount = 0; + _fightAppraiseRequested = false; + _predictKillSwap = false; + _predictKillSwapArmed = false; + // Clear the stance-stuck timer — it arms during the normal NonCombat→Magic + // window at fight start, and if the target drops in that window a surviving + // timer makes the NEXT engagement's first equip tick see minutes of "stuck" + // and fire a spurious recovery (busy force-clear + UseObject on a wielded wand). + ResetStanceRecovery(); + // Defer the turn-stop while a targeted cast is still resolving: SetMotion(turn,false) + // here truncates the in-flight cast gesture → ACE never finishes the cast → server + // Player.IsBusy stranded (relog-only wedge). The target drop above still happens; only + // the stop-thunk waits, bounded by IsCastInFlight (UseDone-seq or 2.5s); re-issued next tick. + if (!IsCastInFlight()) ClearCombatTurnMotions(); + } + + /// + /// Execute a predicted kill-shot swap that was ARMED at cast time and is now + /// CONFIRMED accepted (ACE: refusal window elapsed with no "You're too + /// busy!"). Deferring the drop until confirmation is what stops a refused + /// cast from abandoning a live mob and churning the swarm — the behaviour + /// that pinned AC's m_cBusy and wedged combat-mode / cast input. Body is the + /// old immediate-swap path, unchanged. + /// + private void ExecuteDeferredKillSwap() + { + _predictKillSwapArmed = false; + int swapId = activeTargetId; + if (swapId == 0) return; + + _recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS); + // Queue this predicted one-shot so it's CREDITED when its death confirms — + // we may swap away before its KillerNotification. Capture the name LIVE + // from the world filter (_fightTargetName is often empty this early). + string pkName = _worldFilter[swapId]?.Name ?? _fightTargetName; + if (_fightTargetWcid != 0 && _fightCastCount > 0 && !string.IsNullOrEmpty(pkName)) + { + DateTime nowSwap = DateTime.Now; + _predictedKillPending.RemoveAll(p => p.Expiry < nowSwap); + _predictedKillPending.Add(new PendingKill( + pkName, _fightTargetWcid, _fightCastCount, + _lastCastWeaponId, _lastCastElement, _lastCastTier, _fightDamage, + DateTime.Now.AddSeconds(5))); + } + _host.Log($"[RynthAi] Predicted kill shot 0x{swapId:X8} '{_worldFilter[swapId]?.Name}' (cast#{_fightCastCount} hp~{_fightTargetMaxHp:0} dealt~{_fightDamage:0}) — confirmed accepted, swapping to next target."); + // The pending-offensive judge state belongs to the mob being dropped — + // clearing it stops JudgePendingOffensiveCast from recording this cast + // against the dead target on the next attack block. + _pendingOffensiveSpellId = 0; + _pendingOffensiveTargetId = 0; + DropTarget("predicted kill — swap (confirmed)"); + } + + /// + /// Handle ACE's KillerNotification (GameEvent 0x01AD), forwarded by the + /// engine with the formatted death message. The server sends it to the + /// killer at the lethal hit — earlier than the health=0 update and the + /// Monster→Corpse flip combat otherwise waits on (ACE delays CreateCorpse + /// by the death-animation length, so those land 1–3s later). If the death + /// message names our active target — or we can't read its name — drop it + /// now and briefly suppress re-acquiring that id, so combat advances to the + /// next target instead of firing a second full cast at a corpse-to-be. + /// The notification is sent ONLY to the killer, so receiving it means WE + /// killed something; combat engages one target at a time, so the active + /// target is the victim. A non-matching name means a different creature + /// died (AoE/DoT) — we leave the live target alone. + /// Runs on the same pump thread as Think()/ScanNearbyTargets (no locking). + /// + public void OnKillNotification(string deathMessage) + { + CastsSinceLastKill = 0; // D6: a kill landed (KillerNotification → the killer) — reset the orphan signal. + // Record EXACTLY ONE kill per death message, attributed by name (→ correct + // wcid) from the best available source, so rapid one-shots aren't lost when + // the fight state has already been cleared/advanced by the time the corpse's + // KillerNotification lands. Three tiers, most-specific first. + if (_damageStore == null) return; + DateTime nowKill = DateTime.Now; + _predictedKillPending.RemoveAll(p => p.Expiry < nowKill); + + bool recorded = false; + string how = "miss"; + + // (1) A predicted one-shot we swapped away from — captured wcid + cast count. + for (int i = 0; i < _predictedKillPending.Count; i++) + { + if (!string.IsNullOrEmpty(_predictedKillPending[i].Name) + && deathMessage.IndexOf(_predictedKillPending[i].Name, StringComparison.OrdinalIgnoreCase) >= 0) + { + PendingKill pk = _predictedKillPending[i]; + _predictedKillPending.RemoveAt(i); + _damageStore.RecordKill(pk.WeaponId, pk.Wcid, pk.Name, pk.Element, pk.Tier, pk.CastCount, pk.Damage); + recorded = true; how = "pending"; + break; + } + } + + int tid = activeTargetId; + string curName = tid != 0 ? (_worldFilter[tid]?.Name ?? "") : ""; + bool curMatches = curName.Length > 0 + && deathMessage.IndexOf(curName, StringComparison.OrdinalIgnoreCase) >= 0; + + // (2) The current target died (its name is in the message). + if (!recorded && curMatches && _fightTargetWcid != 0 && _fightCastCount > 0) + { + _damageStore.RecordKill(_lastCastWeaponId, _fightTargetWcid, curName, _lastCastElement, _lastCastTier, + _fightCastCount, _fightDamage); + recorded = true; how = "current"; + } + + // (3) A mob we cast at then moved on from (state already cleared) — credit + // it from the persistent snapshot when the name matches. This is the + // fix for the rapid-kill under-count. + if (!recorded && _lastFightWcid != 0 && _lastFightName.Length > 0 + && deathMessage.IndexOf(_lastFightName, StringComparison.OrdinalIgnoreCase) >= 0) + { + _damageStore.RecordKill(_lastFightWeaponId, _lastFightWcid, _lastFightName, _lastFightElement, _lastFightTier, + _lastFightCount > 0 ? _lastFightCount : 1, 0); + recorded = true; how = "snapshot"; + } + + // (4) A mob fought further back than one-ago (advanced past several targets) — the + // recent-fights ring credits it by name. Closes the post-advance under-count that + // the single _lastFight slot drops (KillDbg how=miss). Consumes the matched entry. + if (!recorded) + { + _recentFights.RemoveAll(e => e.Pk.Expiry < nowKill); + for (int i = _recentFights.Count - 1; i >= 0; i--) + { + PendingKill pk = _recentFights[i].Pk; + if (!string.IsNullOrEmpty(pk.Name) + && deathMessage.IndexOf(pk.Name, StringComparison.OrdinalIgnoreCase) >= 0) + { + _recentFights.RemoveAt(i); + _damageStore.RecordKill(pk.WeaponId, pk.Wcid, pk.Name, pk.Element, pk.Tier, + pk.CastCount > 0 ? pk.CastCount : 1, 0); + recorded = true; how = "recent"; + break; + } + } + } + + // (5) AOE/area kill: a mob wiped by a splash cast we never directly fought (tiers 1-4 + // have no record of it). Credit by matching its death message against the names of + // monsters the scanner has seen this session. Longest name wins (most specific), so + // "Olthoi Swarm Soldier" isn't mis-credited to a shorter overlapping name. + if (!recorded && _seenMonsterNameToWcid.Count > 0) + { + uint bestWcid = 0; string bestName = ""; int bestLen = 0; + foreach (var kv in _seenMonsterNameToWcid) + { + if (kv.Key.Length > bestLen + && deathMessage.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) >= 0) + { bestWcid = kv.Value; bestName = kv.Key; bestLen = kv.Key.Length; } + } + if (bestWcid != 0) + { + // Attribute to the last cast's shape (the AOE/ring that wiped the pack) so these + // kills group under that tier (e.g. "R2") instead of an unattributed row. Per-cast + // damage/casts-to-kill stays meaningless for AOE — we only count the kill. + _damageStore.RecordKill(_lastCastWeaponId, bestWcid, bestName, _lastCastElement, _lastCastTier, 1, 0); + recorded = true; how = "aoe"; + } + } + + if (_killDbgCount < 1000) + { + _killDbgCount++; + _host.Log($"[KillDbg] how={how} curMatch={curMatches} tid=0x{(uint)tid:X8} fightWcid={_fightTargetWcid} cnt={_fightCastCount} lastWcid={_lastFightWcid} pend={_predictedKillPending.Count} msg='{deathMessage}'"); + } + + // Drop the current target only if IT is the one that died. + if (tid != 0 && curMatches) + { + _recentlyKilled[tid] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + DropTarget("killed (KillerNotification)"); + } + } + + /// Record the just-stamped _lastFight* context into the recent-fights ring, + /// keyed by the live object id (refreshed per hit, capped, TTL-pruned). Lets a kill that + /// lands after we've advanced past the dying mob still be credited by name (tier 4). + private void StampRecentFight() + { + if (_lastFightWcid == 0) return; + int id = activeTargetId; + if (id == 0) return; + var pk = new PendingKill(_lastFightName, _lastFightWcid, _lastFightCount > 0 ? _lastFightCount : 1, + _lastFightWeaponId, _lastFightElement, _lastFightTier, 0, + DateTime.Now.AddMilliseconds(RecentFightTtlMs)); + for (int i = _recentFights.Count - 1; i >= 0; i--) + if (_recentFights[i].Id == id) _recentFights.RemoveAt(i); + _recentFights.Add((id, pk)); + if (_recentFights.Count > RecentFightsCap) _recentFights.RemoveAt(0); + } + + /// + /// Exact per-hit damage from the engine (AttackerNotification 0x01B1), + /// attributed to the active target (combat engages one mob at a time). This + /// is the only selection-free source of real damage numbers: ACE pushes + /// creature health only for the SELECTED target, so combat — which never + /// selects — otherwise can't see how hurt a mob is. Feeds kill-shot + /// prediction and doubles as reliable blacklist damage feedback. + /// + public void OnCombatDamage(double damage, uint damageType, bool crit, bool isAttacker) + { + if (!isAttacker || damage <= 0) return; + int tid = activeTargetId; + if (tid == 0 || tid != _fightTargetId) return; + + _fightDamage += damage; + + // War magic sends NO 0x01B1 (its damage comes from the chat parse), so a structured + // hit event in a NON-magic mode is a MELEE or MISSILE hit. Magic sets its cast context + // in AttackWithMagic; for melee/missile derive the per-hit context here so the Damage + // tab keys it correctly: weapon = the equipped weapon, element = the packet damage type + // (accurate per hit), tier = 0 (no spell tier). The packet crit flag is reliable too. + if (CurrentCombatMode != CombatMode.Magic) + { + _lastCastWeaponId = unchecked((uint)_equippedWeaponId); + _lastCastElement = ElementFromDamageType(damageType); + _lastCastTier = 0; + _lastCastWasRing = false; // melee/missile are single-target + _fightCastCount++; // landed hits → "casts/attacks to kill" learning + // Snapshot the fight so a kill landing after we've advanced is still credited + // (OnKillNotification path 3) with the right melee/missile weapon/element. + if (_fightTargetWcid != 0) + { + _lastFightWcid = _fightTargetWcid; + _lastFightName = _fightTargetName; + _lastFightWeaponId = _lastCastWeaponId; + _lastFightElement = _lastCastElement; + _lastFightTier = _lastCastTier; + _lastFightCount = _fightCastCount; + StampRecentFight(); + } + } + + // Don't learn per-cast damage from ring/AoE casts — they hit multiple + // mobs, so the damage can't be attributed to this single target. + if (_damageStore != null && _fightTargetWcid != 0 && !_lastCastWasRing) + _damageStore.RecordHit(_lastCastWeaponId, _fightTargetWcid, _fightTargetName, _lastCastElement, _lastCastTier, damage, crit); + + ReportDamageOnTarget(tid); // clears the blacklist miss streak + stamps last-damage time + } + + // Map an AC DAMAGE_TYPE flag (from the 0x01B1 packet) to the Damage-tab element string. + // A weapon hit carries one primary type; if multiple bits are set, prefer the physical base. + private static string ElementFromDamageType(uint dt) + { + if ((dt & 0x1) != 0) return "Slash"; + if ((dt & 0x2) != 0) return "Pierce"; + if ((dt & 0x4) != 0) return "Bludgeon"; + if ((dt & 0x10) != 0) return "Fire"; + if ((dt & 0x8) != 0) return "Cold"; + if ((dt & 0x40) != 0) return "Lightning"; // DamageType.Electric + if ((dt & 0x20) != 0) return "Acid"; + if ((dt & 0x400) != 0) return "Nether"; + return "Physical"; // Undef / vital drains + } + + /// Start tracking a fresh fight against : zero the damage tally, capture its wcid, resolve its HP. + private void BeginFight(int targetId) + { + _fightTargetId = targetId; + _fightDamage = 0; + _fightCastCount = 0; + _fightTargetWcid = 0; + _fightTargetMaxHp = 0; + _fightAppraiseRequested = false; + _predictKillSwap = false; + _fightTargetName = ""; + if (targetId == 0) return; + _fightTargetName = _worldFilter[targetId]?.Name ?? ""; + if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)targetId, out uint wcid)) + _fightTargetWcid = wcid; + ResolveFightHp(); + } + + /// + /// Resolve the active target's HP pool for prediction. Priority: + /// 1) appraised MaxHealth from the shared creature store (instant once any + /// character has assessed this monster type; persists across sessions), + /// 2) learned damage-to-kill for this wcid (per character), + /// 3) one appraisal request to populate (1) for next time (best-effort). + /// Re-called each tick until HP is known (the appraisal lands async). + /// + private void ResolveFightHp() + { + if (_fightTargetId == 0) return; + + // Once per fight, query the live target's health. The 0x01C0 response is + // handled on AC's main thread, where the engine reads the creature's REAL + // MaxHealth from its qualities (SEH-guarded) and corrects the bogus + // appraisal stub in creatures.json. Fire this EVEN when we already have a + // cached (stub) value — otherwise the stub suppresses the query and the + // real number never gets read. + if (!_fightAppraiseRequested) + { + _fightAppraiseRequested = true; + try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { } + } + + if (_fightTargetMaxHp > 0) return; + + // User-entered HP override (set in the Damage panel) is authoritative — + // it's the manual fix for ACE's skill-gated appraisal reading low. + if (_damageStore != null && _fightTargetWcid != 0) + { + double manual = _damageStore.GetManualHp(_fightTargetWcid); + if (manual > 0) { _fightTargetMaxHp = manual; return; } + } + + var obj = _worldFilter[_fightTargetId]; + string name = obj?.Name ?? ""; + + if (_creatureStore != null && !string.IsNullOrEmpty(name)) + { + CreatureProfile? prof = null; + bool found = _fightTargetWcid != 0 + ? _creatureStore.TryGet(name, _fightTargetWcid, out prof) + : _creatureStore.TryGetByName(name, out prof); + if (found && prof != null && prof.MaxHealth > 0) + { + _fightTargetMaxHp = prof.MaxHealth; + return; + } + } + + if (_damageStore != null && _fightTargetWcid != 0) + { + double hp = _damageStore.GetLearnedHp(_fightTargetWcid); + if (hp > 0) { _fightTargetMaxHp = hp; return; } + } + + // Unknown — appraise once so the shared store fills for next time. Costs + // one busy-count tick; only the first encounter of a wcid pays it. + if (!_fightAppraiseRequested) + { + _fightAppraiseRequested = true; + try { if (_host.HasRequestId) _host.RequestId((uint)_fightTargetId); } catch { } + try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { } + } + } + + /// + /// After firing an offensive cast at the active target, decide whether that + /// cast is expected to finish the mob. If so — and another target is in + /// range — flag a swap so Think drops this mob instead of wasting the next + /// cast during the projectile's flight. Ring/AoE casts are excluded (their + /// damage hits multiple mobs, so single-target accounting doesn't apply). + /// + private void EvaluateKillShot(uint weaponId, string element, int tier, bool isRing) + { + _predictKillSwap = false; + if (isRing || _damageStore == null || _fightTargetWcid == 0) return; + if (activeTargetId == 0 || activeTargetId != _fightTargetId) return; + if (!HasAlternateTarget(activeTargetId)) return; // nothing to swap to — keep casting + + // (A) Casts-to-kill: we've fired the number of casts this wcid typically + // takes to die from this weapon+spell. Catches ONE-SHOTS (avg≈1 → swap + // right after cast 1), which the damage math below can't — nothing has + // landed when we predict, so it has no remaining-HP signal yet. + double avgCasts = _damageStore.GetAvgCastsToKill(weaponId, _fightTargetWcid, element, tier, out int killSamples); + if (killSamples >= KILL_MIN_SAMPLES && avgCasts > 0 + && _fightCastCount >= (int)Math.Round(avgCasts)) + { + _predictKillSwap = true; + return; + } + + // (B) Damage-based: remaining HP is within one comfortable cast. Precise + // for multi-cast fights once some damage has landed. + if (_fightTargetMaxHp > 0) + { + double expected = _damageStore.GetAvgDamage(weaponId, _fightTargetWcid, element, tier, out int dmgSamples); + double remaining = _fightTargetMaxHp - _fightDamage; + if (dmgSamples >= KILL_MIN_SAMPLES && expected > 0 && remaining <= expected * KILL_CONFIDENCE) + _predictKillSwap = true; + } + } + + /// True if a scanned, non-suppressed target other than is available to swap to. + private bool HasAlternateTarget(int excludeId) + { + for (int i = 0; i < _scannedTargets.Count; i++) + { + int id = _scannedTargets[i].Id; + if (id == excludeId) continue; + if (_recentlyKilled.ContainsKey(id)) continue; + return true; + } + return false; + } + + public bool Think() + { + if (!_settings.EnableCombat) return false; + + double acDistanceLimit = _settings.MonsterRange; + // Hysteresis: a locked target is retained (and kept under attack) out to + // the larger disengage distance, while new targets are still only + // acquired within MonsterRange (ScanNearbyTargets). The gap absorbs the + // step-back AC applies on combat-mode entry so a mob at the edge doesn't + // oscillate engage<->peace. + double disengageLimit = DisengageDistance; + // Note: _blacklistManager self-expires entries on read (IsBlacklisted), so no + // explicit cleanup pass is needed. The old vestigial `blacklistedTargets` dict + // and its CleanupExpiredBlacklist helper were removed — they were never populated. + _blacklistManager.AttemptThreshold = 1; // one report = blacklist; the N-cast count is controlled by JudgePendingCast + _blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec; + + if (_raycastSystem?.TargetingFSM != null) + { + var fsm = _raycastSystem.TargetingFSM; + fsm.MaxScanDistanceMeters = _settings.MonsterRange + 40.0f; + fsm.UseArcs = _settings.UseArcs; + fsm.BowArcVelocity = _settings.BowArcVelocity; + fsm.CrossbowArcVelocity = _settings.CrossbowArcVelocity; + fsm.AtlatlArcVelocity = _settings.AtlatlArcVelocity; + fsm.MagicArcVelocity = _settings.MagicArcVelocity; + } + + // Deferred predicted kill-shot swap: a cast that armed it is confirmed + // accepted once OffensiveRefusalWindowMs elapses with no "You're too + // busy!" (ACE has no positive "You cast X" for war magic). Run BEFORE the + // scan so the dropped mob is suppressed this same tick and acquisition + // picks the next target — preserving the old swap cadence on real kills, + // while a REFUSED cast (which cleared the arm) now keeps + retries its + // target instead of churning the swarm and pinning AC's busy count. + if (_predictKillSwapArmed) + { + // Observe the cast WINDUP: CanCastNow goes false while the cast + // gesture animates ([CMI+0x80] non-empty), true once it releases. + bool gestureInFlight = _host.HasGetCastBusyState && !_host.CanCastNow; + if (gestureInFlight) + _predictSwapGestureSeen = true; + + if (activeTargetId == 0 || _pendingOffensiveTargetId != activeTargetId) + _predictKillSwapArmed = false; // target already advanced/dropped — stale arm + else if (_pendingOffensiveSpellId != 0 + && (DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds >= OffensiveRefusalWindowMs) + { + // ⚠ Do NOT drop the target while the cast gesture is still + // animating. A high-tier cast (Force Arc VII) winds up ~2s, + // FAR longer than the 500ms refusal window — swapping at 500ms + // dropped the target mid-windup and ABORTED the cast before it + // reached the server (full gesture + bolt played, but no + // "You cast", zero damage; two mobs ping-ponged, nothing died — + // 2026-06-13). Wait until the windup has been SEEN and then + // completed (released): then the cast has actually landed its + // damage and the predicted swap is correct. Bounded by a + // timeout so a missing/forever gesture can't arm-lock combat. + bool released = _predictSwapGestureSeen && (!_host.HasGetCastBusyState || _host.CanCastNow); + bool timedOut = (DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds >= PredictKillSwapMaxWaitMs; + if (released || timedOut) + ExecuteDeferredKillSwap(); + } + } + + // Update the pre-scanned target list (distance, attackable, LOS — no selection) + try { ScanNearbyTargets(); } catch (Exception ex) { _host.Log($"[RynthAi] ScanNearbyTargets crashed: {ex.Message}"); } + + // Validate current target — restore from lock first so transient world-filter nulls + // don't cause HandleCombatTrigger to pick a different mob on the same tick. + if (_lockedTargetId != 0 && activeTargetId == 0) + activeTargetId = _lockedTargetId; + + if (activeTargetId != 0) + { + var target = _worldFilter[activeTargetId]; + bool blacklisted = _blacklistManager.IsBlacklisted(activeTargetId); + + if (blacklisted) + DropTarget("blacklisted"); + else if (target != null && IsSpellProjectileName(target.Name)) + DropTarget("spell projectile (not a monster)"); + else if (target != null && (int)target.ObjectClass != (int)AcObjectClass.Monster) + DropTarget("became corpse"); + else if (_worldFilter.GetHealthRatio(activeTargetId) == 0f) + DropTarget("hp=0"); + else if (target != null && + _worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit) + DropTarget("out of range"); + // If target == null here it's a transient world-filter miss — keep the lock, + // the stillScanned grace period below will handle a truly dead/vanished mob. + } + + // Score every candidate every tick — handles initial pick AND switching when + // a meaningfully better target appears (stickiness bonus prevents flapping). + HandleCombatTrigger(); + + if (activeTargetId == 0) + { + // No valid target — go to Peace immediately to stop the client + // from auto-running toward a distant monster. The 500ms cooldown + // prevents ChangeCombatMode spam while idling between spawns. + if (_settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat + && _scannedTargets.Count == 0 && BusyCount == 0) + { + // Defer idle peace-swap while a cast at the just-dropped target is still + // resolving: ChangeCombatMode truncates the in-flight gesture → strands + // Player.IsBusy. Bounded by IsCastInFlight (UseDone-seq or 2.5s). + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 500 && !IsCastInFlight()) + { + _host.ChangeCombatMode(CombatMode.NonCombat); + _lastPeaceAttempt = DateTime.Now; + } + } + return true; + } + + // Verify active target is still in the scanned list (still visible + LOS clear) + bool stillScanned = false; + for (int i = 0; i < _scannedTargets.Count; i++) + { + if (_scannedTargets[i].Id == activeTargetId) { stillScanned = true; break; } + } + if (!stillScanned) + { + // Give it a grace period before dropping — one bad LOS result or scan gap shouldn't + // hand control to navigation mid-fight. + if (_targetLostScanTime == DateTime.MinValue) + _targetLostScanTime = DateTime.Now; + + if ((DateTime.Now - _targetLostScanTime).TotalMilliseconds > TARGET_SCAN_GRACE_MS) + DropTarget("scan grace expired"); + return true; + } + _targetLostScanTime = DateTime.MinValue; // back in scan — reset grace timer + + var targetObj = _worldFilter[activeTargetId]; + if (targetObj == null) return true; // transient miss — skip tick, keep lock + + // Pin kill-shot fight tracking to the active target (covers initial lock, + // target switches, and lock-restore after a transient miss), and keep + // trying to resolve its HP until known (the appraisal lands async). + if (activeTargetId != _fightTargetId) + BeginFight(activeTargetId); + else if (_fightTargetMaxHp <= 0) + ResolveFightHp(); + // Keep trying to capture the mob's name (the world filter fills it in + // asynchronously, so it's often empty at lock time) — by kill time the + // learning file then has a real name, not a blank. + if (_fightTargetName.Length == 0) + { + string? nm = _worldFilter[activeTargetId]?.Name; + if (!string.IsNullOrEmpty(nm)) _fightTargetName = nm; + } + + // Time-based blacklist: if we've been engaged with this target for longer than + // TargetNoProgressTimeoutSec without dealing any damage, give up and blacklist it. + // Uses last-damage time when available; falls back to lock time. + // Skip the no-progress blacklist while raycast is warming up — the bot + // can't deal damage with degraded targeting, so this timer would + // otherwise sideline a perfectly good target through no fault of its + // own. Warmup is sub-second to ~2s, far under TargetNoProgressTimeoutSec. + int noProgressTimeoutSec = _settings.TargetNoProgressTimeoutSec; + if (noProgressTimeoutSec > 0 && _targetLockedAt != DateTime.MinValue && !RaycastWarmingUp) + { + DateTime refTime = _lastDamageDealtAt != DateTime.MinValue ? _lastDamageDealtAt : _targetLockedAt; + if ((DateTime.Now - refTime).TotalSeconds > noProgressTimeoutSec) + { + _host.WriteToChat($"[RynthAi] No progress on {targetObj.Name} after {noProgressTimeoutSec}s — blacklisting", 2); + _blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec; + _blacklistManager.ReportFailure(activeTargetId); + DropTarget("no-progress timeout"); + return true; + } + } + + // Distance gate: don't issue any attack commands (SelectItem, attack, cast) + // when the target is beyond the disengage distance. Within the deadband + // (MonsterRange..disengage) we KEEP issuing commands so AC's auto-run + // pulls the character back into engage range after the combat-mode + // step-back — instead of dropping to peace and restarting the approach. + double currentDist = _worldFilter.Distance( + _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId); + if (currentDist > disengageLimit) + return true; + + // While a targeted combat cast is still resolving on the server, do NOT re-assert + // stance/weapon here: EquipWeaponAndSetStance can emit ChangeCombatMode/UseObject, + // motion-replacing actions that truncate the in-flight cast gesture → orphan the cast + // → strand Player.IsBusy (relog-only wedge). Magic-only (melee re-equips every tick and + // never arms the flag); bounded by IsCastInFlight (UseDone-seq or 2.5s); re-runs next tick. + if (!(CurrentCombatMode == CombatMode.Magic && IsCastInFlight())) + { + if (!EquipWeaponAndSetStance(targetObj, "Auto")) + return true; + } + + bool useNative = _settings.UseNativeAttack && _host.HasNativeAttack; + + // Melee turn motions are managed by the facing gate below (direct-attack + // path) — it clears them the moment heading is within tolerance, which + // also mops up anything navigation left running. The native path never + // sets them and lets AC turn the avatar itself. + + // Attack magic uses its OWN interval (AttackSpellIntervalMs, default + // 1500ms) so war/void combat casts can be spaced ~1-2s without slowing + // buff chains — buffs keep the faster SpellCastIntervalMs. Spacing the + // offensive casts stops back-to-back "You're too busy!" refusals that + // silently drop casts and cost kills. ≤0 (e.g. a pre-existing settings + // file saved before this field existed) falls back to 1500ms. + double attackCmdIntervalMs = CurrentCombatMode == CombatMode.Magic + ? (_settings.AttackSpellIntervalMs > 0 ? _settings.AttackSpellIntervalMs : 1500) + : 1000.0; + if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= attackCmdIntervalMs) + { + _offensiveCastThisCycle = false; + // Convert any pending offensive cast whose refusal window has + // elapsed into a queued judgement (ACE has no "You cast X" for + // war magic; this is our successful-cast detector). + JudgePendingOffensiveCast(); + JudgePendingCast(); // verdict on the last cast once its window elapses + + // Client is busy processing a previous action — don't queue more + if (BusyCount > 0) + { + LastCombatSkipReason = "busy-count"; // D4 record-only + return true; + } + + // Magic cadence guard: while a previous combat cast is still + // resolving on the ACE server, do NOT turn or issue another cast. + // A turn/stop MoveToState (or the next cast's free-hands stop-thunk) + // landing during the server's deferred targeted-cast windup orphans + // the prior cast → 0 damage. Resolves on a server UseDone (poll) or + // a hard timeout. Magic only; melee/missile are AC-paced. + if (CurrentCombatMode == CombatMode.Magic && IsAwaitingCastResolution()) + { + LastCombatSkipReason = "cast-cadence"; // D4 record-only (IsCastInFlight) + return true; + } + + // MAGIC: settle-before-cast facing gate. Never cast mid-turn and + // never let a turn-stop ride alongside the cast packet — both orphan + // the ACE server's deferred targeted-cast windup (root cause of + // "animates but 0 damage / too busy"). Makes combat behave like the + // working self-buff path. Applies regardless of UseNativeAttack + // (native attack is a physical swing; in Magic mode the bot always + // casts, so the facing race is the same with or without it). + if (CurrentCombatMode == CombatMode.Magic) + { + double facingError = GetFacingError(activeTargetId); + if (facingError > FACE_TOLERANCE_DEG) + { + FaceTarget(activeTargetId); + if (!_facingTarget) + { + _facingTarget = true; + _faceStartTime = DateTime.Now; + } + // Keep turning until actually within angle. Do NOT "fire + // anyway" while still turning (that was the bug). Only a long + // safety timeout falls through, so a jittery point-blank pose + // can't wedge combat forever. + if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_MAX_WAIT_MS) + { + LastCombatSkipReason = "facing-turning"; // D4 record-only + return true; + } + _host.Log($"[CombatCast] facing did not converge in {FACE_MAX_WAIT_MS:0}ms (err={facingError:0.0}°) — releasing turn + casting anyway"); + } + + // Within angle (or safety-timed-out). If we were turning, release + // the turn motions and give the stop ONE settle tick to reach the + // server BEFORE the cast packet. + if (_facingTarget) + { + ClearCombatTurnMotions(); + _facingTarget = false; + _faceSettledAt = DateTime.Now; + LastCombatSkipReason = "face-settle-release"; // D4 record-only + return true; // settle tick + } + if ((DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS) + { + LastCombatSkipReason = "face-settle-wait"; // D4 record-only + return true; // let the turn-stop settle on the server first + } + } + // Native attack handles facing internally — skip manual facing. + // Otherwise turn to face before swinging or firing: the direct + // MeleeAttack/MissileAttack game actions bypass the client's + // turn-to-face, so without this a non-native melee box swings at + // whatever heading nav left it on. AC paces the swing/shot itself, + // so the cast-windup orphaning that Magic guards against above + // doesn't apply — a plain servo is enough here. + else if (!useNative) + { + double facingError = GetFacingError(activeTargetId); + if (facingError > FACE_TOLERANCE_DEG) + { + FaceTarget(activeTargetId); + if (!_facingTarget) + { + _facingTarget = true; + _faceStartTime = DateTime.Now; + } + if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_TIMEOUT_MS) + return true; // not facing yet, keep waiting + } + _facingTarget = false; + ClearCombatTurnMotions(); + } + + // Don't attack in missile mode without ammo + if (CurrentCombatMode == CombatMode.Missile && !HasWieldedAmmo()) + return true; + + // SelectItem removed 2026-06-03: targeted casts now use the explicit-target + // FreeHandsAndCastSpell path and direct attacks pass targetId explicitly, so + // AC's global selection no longer needs setting here. Setting it stole the + // user's inventory selection every combat tick (AC has a single selection) and + // was an off-thread SetSelectedObject mutation (not marshalled by P1). Matches + // RC2's RynthBot, which never selects. (Native physical attack in AttackTarget + // still selects — it genuinely requires AC's selection.) + + if (CurrentCombatMode == CombatMode.Magic && _spellManager != null) + { + // Don't issue a combat spell while the previous cast GESTURE is + // still animating. AC refuses a mid-gesture cast with the + // server-driven "You're too busy!" notice; sustained refusals + // re-enter AC's AddTextToScroll → 0x00460D1D AV. CanCastNow is + // the engine's CMotionInterp gesture gate (the SAME gate + // BuffManager uses). It degrades to true on an engine without + // the gate, where the SpellCastIntervalMs attack throttle still + // bounds retries. Melee/missile (AttackTarget, below) is + // deliberately NOT gated on this — a weapon swing isn't a spell + // cast and AC paces the swing animation itself. + if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) + { + if ((DateTime.Now - lastAttackCmd).TotalMilliseconds > 5000) + _host.Log($"[CombatCast] CanCastNow=false — gesture gate blocking cast (last attack {(DateTime.Now - lastAttackCmd).TotalMilliseconds:0}ms ago, target=0x{activeTargetId:X8})"); + LastCombatSkipReason = "cast-gate"; // D4 record-only (CanCastNow=false) + return true; + } + + AttackWithMagic(targetObj); + + // Don't restore the physical weapon on top of a cast just issued this tick + // (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would + // truncate the in-flight gesture and strand Player.IsBusy. Defer one windup + // (bounded); _returnToPhysicalCombat stays true so the restore still runs after. + if (_returnToPhysicalCombat && !IsCastInFlight()) + { + var rule2 = GetRuleForTarget(targetObj); + string elem2 = GetPreferredElement(targetObj, rule2); + if (rule2 != null && !HasPendingDebuffs(rule2, elem2)) + { + _returnToPhysicalCombat = false; + if (_savedWeaponId != 0 + && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-restore"))) + { + _host.UseObject((uint)_savedWeaponId); + _savedWeaponId = 0; + } + EquipWeaponAndSetStance(targetObj, "Auto"); + } + } + } + else + { + var rule = GetRuleForTarget(targetObj); + + if (rule != null && _spellManager != null && !_returnToPhysicalCombat) + { + string elem = GetPreferredElement(targetObj, rule); + if (HasPendingDebuffs(rule, elem)) + { + int wandId = FindWandInItems(); + if (wandId != 0 + && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-debuff-wand"))) + { + // TODO: Save current equipped weapon when inventory API is available. + _savedWeaponId = 0; + _returnToPhysicalCombat = true; + _host.UseObject((uint)wandId); + _lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded + _host.ChangeCombatMode(CombatMode.Magic); + lastAttackCmd = DateTime.Now; + return true; + } + } + } + + // Physical combat always attacks — spell shape flags (UseArc/Bolt/Ring/Streak) + // are only relevant in magic mode and must not gate melee/missile attacks. + AttackTarget(); + } + + // Ring spells hit an area — no per-target damage feedback is generated, + // so they must not count toward the blacklist miss counter. + // Magic mode no longer counts from here at all: RecordOffensiveCast + // is invoked from the chat-confirmation path ("ou cast X" matching + // _pendingOffensiveSpellId) so a server-refused attempt ("too busy", + // equip waits, "no spell found" etc.) never queues a judgement. + // Melee/missile attack every cycle and get prompt damage feedback, + // so they keep per-cycle counting (the magicMode branch is false). + bool magicMode = CurrentCombatMode == CombatMode.Magic && _spellManager != null; + if (!_lastCastWasRing && (!magicMode || _offensiveCastThisCycle)) + RecordOffensiveCast(activeTargetId); + lastAttackCmd = DateTime.Now; + + // Predicted kill shot (set in AttackWithMagic): the cast we just fired + // is expected to finish this mob. DON'T swap yet — on ACE a war cast is + // only confirmed accepted ~OffensiveRefusalWindowMs later (the absence + // of "You're too busy!"). Dropping the target 1ms after issuing meant a + // REFUSED cast still abandoned a live mob and advanced to the next, + // churning the whole swarm and pinning AC's busy count (the wedge). + // Arm it; the deferred-swap check at the top of Think executes it once + // the cast is confirmed, and the "too busy"/fizzle handlers cancel it. + if (_predictKillSwap) + { + _predictKillSwap = false; + if (activeTargetId != 0) + { + _predictKillSwapArmed = true; + _predictSwapGestureSeen = false; // must observe the cast windup before swapping + } + } + } + return true; + } + + // Diagnostic: log the combat manager state when meaningful inputs change. + // We bucket msSinceAttack into Recent (<3s = "in active engagement") vs + // Stale (>=3s) so this doesn't fire on every tick — the raw ms ticks up + // continuously and would flood the log at ~30 lines/sec otherwise (which + // it did before this fix — bot lived ~64s under that load and the file- + // write contention may have helped trigger AC's idle-exit timeout). + private string _lastCombatStateKey = ""; + private void LogCombatStateIfChanged() + { + long msSinceAttack = lastAttackCmd == DateTime.MinValue + ? -1 + : (long)(DateTime.Now - lastAttackCmd).TotalMilliseconds; + string attackBucket = msSinceAttack < 0 ? "never" + : msSinceAttack < 3000 ? "recent" + : msSinceAttack < 10_000 ? "stale" + : "cold"; + string key = $"enableCombat={_settings.EnableCombat} scanned={_scannedTargets.Count} active=0x{activeTargetId:X8} busy={BusyCount} mode={CurrentCombatMode} attack={attackBucket} action='{_settings.BotAction}'"; + if (key == _lastCombatStateKey) return; + _lastCombatStateKey = key; + _host.Log($"Combat: state {key} (msSinceAttack={msSinceAttack})"); + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) + { + // Clear turn motions once on the transition from running → stopped, + // so the character doesn't spin indefinitely after a mid-turn stop. + // Do NOT clear every frame — that blocks manual keyboard turning. + if (_wasMacroRunning) + { + _wasMacroRunning = false; + ClearCombatTurnMotions(); + } + return; + } + _wasMacroRunning = true; + + LogCombatStateIfChanged(); + + // Always run the scan and BotAction state update, even when combat can't + // take actions. ScanNearbyTargets has no side-effects (no game commands) + // and must stay fresh so HasTargets is accurate for nav-blocking decisions. + // Without this, stale scan data keeps combatBlocking = true after a kill, + // preventing navigation from resuming while the bot is buffing, etc. + if (_settings.EnableCombat) + { + try { ScanNearbyTargets(); } + catch (Exception ex) { _host.Log($"[RynthAi] ScanNearbyTargets CRASH: {ex.Message}"); } + + // Only hold the "Combat" BotAction lock while actively engaging. + // "Actively engaging" = an attack command was issued recently. + // Without this, having anything visible in scan range latched + // BotAction = "Combat" and blocked NavigationEngine.Tick from + // running, even when CombatManager couldn't actually attack + // (out of range, BusyCount stuck, etc.) — symptom was bot + // standing still surrounded by far-off mobs while nav refused + // to move. By tying the lock to recent attack activity, nav + // gets to run between engagement windows and bot can chase / + // reposition. + // BotAction is no longer written here. STEP 2 (ACTIVITY_ARBITER_PLAN.md): + // the ActivityArbiter in RynthAiPlugin.OnTick is the sole writer of + // the "Combat"/"Navigating" strings, driven by the pure + // HasEngageableTarget predicate. CombatManager only reads BotAction + // (via canRun below) and acts. Removing these writes is what kills + // the squat-without-fighting freeze: Combat can no longer latch the + // lock based on broad/stale scan state. + } + + // Combat can run in Default/Combat, can interrupt navigation unless nav boost is on, + // and can interrupt looting unless loot boost is on. + // Buffing always blocks combat — if buffs drop, the character dies. + bool canRun = _settings.BotAction == "Default" + || _settings.BotAction == "Combat" + || (_settings.BotAction == "Navigating" && !_settings.BoostNavPriority) + || (_settings.BotAction == "Looting" && !_settings.BoostLootPriority); + if (!canRun) return; + + if (_settings.EnableCombat) + { + try { Think(); } + catch (Exception ex) { _host.Log($"[RynthAi] Think CRASH: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); } + + // BotAction no longer written post-Think either — the arbiter + // recomputes from HasEngageableTarget every tick (33ms lag, picks + // up activeTargetId set by the Think() above on the next pass). + // See STEP 2 note in the pre-Think branch. + } + } + + public void HandleCombatTrigger() + { + // Utility-AI selection: score every visible candidate, pick the highest. + // The locked target carries a stickiness bonus so we only switch when a + // genuinely better option appears — no flapping on near-ties. + if (_scannedTargets.Count == 0) return; + + int bestId = 0; + double bestScore = double.MinValue; + double heldScore = double.MinValue; // scored total for the incumbent, for the switch log + bool incumbentSeen = false; + foreach (var c in _scannedTargets) + { + double s = ScoreCandidate(c); + if (c.Id == _lockedTargetId) + { + s += TARGET_SWITCH_STICKINESS; + // Commitment: once we have COMMITTED to the locked target, + // finishing it outranks any small positional edge a fresh mob + // holds. Stickiness alone only settles near-ties — it loses to a + // full-health mob that simply walked closer, which is how the bot + // left a trail of half-dead mobs. + // + // Armed at cast ISSUE as well as on confirmed damage, because + // Force Arc has ~2s of travel time and keying only on damage + // landing left that window looking "untouched" — a 2.4-point + // margin could walk away from a mob with a bolt already in the + // air (observed 2026-09-03 02:22:45). + // + // The cast-issue arm MUST expire. The first version keyed on + // _lastAttackedTargetId alone, which is set at issue and never + // cleared while the lock holds — granting a permanent +20 on top + // of the +25 stickiness to a target that had never taken damage + // and might never take any. With TargetNoProgressTimeoutSec + // defaulting to 0 (disabled) nothing else breaks that loop: on + // 2026-09-05 the bot held one Olthoi for 5+ hours, ~3,100 casts, + // zero damage, zero kills, switches down from 126 to 3 per 4h. + // + // Bounded to the projectile flight window instead: long enough to + // cover a bolt in the air, short enough that a target which never + // takes damage returns to competing on its merits. + // Two bounds, and BOTH are needed: + // * since the last cast — covers the bolt currently in flight; + // * since the target was locked — caps how long we extend that + // courtesy to a target that has never actually taken damage. + // The second bound is the important one. Without it the window + // refreshes on every cast, so a target under continuous fire keeps + // the bonus indefinitely, which is the same permanent-immunity bug + // in a different guise. + // + // Once damage HAS landed, _lastDamageDealtAt grants commitment with + // no time bound — finishing a wounded mob is exactly the intent. + bool undamaged = _lastDamageDealtAt == DateTime.MinValue; + bool withinFlightWindow = + _lastAttackedTargetId == c.Id + && _lastAttackedAt != DateTime.MinValue + && (DateTime.Now - _lastAttackedAt).TotalMilliseconds <= CastCommitmentWindowMs; + bool withinUndamagedGrace = + _targetLockedAt != DateTime.MinValue + && (DateTime.Now - _targetLockedAt).TotalMilliseconds <= UndamagedCommitmentMaxMs; + + if (!undamaged || (withinFlightWindow && withinUndamagedGrace)) + s += DAMAGE_COMMITMENT_BONUS; + heldScore = s; + incumbentSeen = true; + _lockedLastScore = s; + _lockedLastSeenInScan = DateTime.Now; + } + if (s > bestScore) { bestScore = s; bestId = c.Id; } + } + + // Incumbent briefly absent from the scan: keep it in the running at its + // last known score for the grace window rather than letting it score + // nothing. Without this a transient scan gap hands the fight to whoever + // happens to be visible this tick, then the next tick hands it back — + // the A->B->A flapping seen repeatedly on 2026-09-03. + if (!incumbentSeen + && _lockedTargetId != 0 + && _lockedLastScore > double.MinValue + && _lockedLastSeenInScan != DateTime.MinValue + && (DateTime.Now - _lockedLastSeenInScan).TotalMilliseconds <= TARGET_SCAN_GRACE_MS) + { + heldScore = _lockedLastScore; + if (heldScore >= bestScore) + return; // incumbent still wins on its last known score — no switch + } + + if (bestId == 0 || bestId == _lockedTargetId) return; + + // One line per real switch. After the scoring fixes a switch should be a + // genuine event (target died, left, or something decisively better showed + // up) — if this floods the log, selection is thrashing again and the two + // scores say by how much. + if (_lockedTargetId != 0) + _host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}) " + + $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0})"); + + activeTargetId = bestId; + _lockedTargetId = bestId; + _targetLockedAt = DateTime.Now; + _lastDamageDealtAt = DateTime.MinValue; + _lockedLastScore = double.MinValue; // new incumbent — no carried score yet + _lockedLastSeenInScan = DateTime.MinValue; + _consecutiveCastMisses = 0; + _pendingJudgeCastAt = DateTime.MinValue; + _facingTarget = false; + _returnToPhysicalCombat = false; + // Target-switch turn-stop: defer while a cast at the PREVIOUS target is still resolving + // (nothing clears the in-flight flag on target acquire), else this SetMotion(turn,false) + // truncates that gesture → strands Player.IsBusy. The lock switch above still happens; + // the stop re-issues next tick. Bounded by IsCastInFlight (UseDone-seq or 2.5s). + if (!IsCastInFlight()) ClearCombatTurnMotions(); + + // Internal lock is set unconditionally so combat is ready to swing the + // moment busy clears. SelectItem during a combat-mode transition can + // wedge the client action queue, so only fire it when not busy. + // SelectItem removed 2026-06-03 (see the combat-tick note): the target lock is + // purely internal (activeTargetId / _lockedTargetId set above). Casts use the + // explicit-target FreeHandsAndCastSpell path and attacks pass targetId, so AC's + // selection needn't track the combat target. Removing it frees the user's + // inventory selection and drops an off-thread SetSelectedObject mutation. + } + + private double ScoreCandidate(in ScannedTarget c) + { + double maxDist = Math.Max(1.0, _settings.MonsterRange); + double distScore = Math.Clamp((maxDist - c.Distance) / maxDist, 0.0, 1.0) * 100.0; + + // GetHealthRatio returns -1 for "no vitals received for this mob yet". + // Combat is selection-free (SelectItem removed 2026-06-03), so ACE only + // pushes health for the mob we are actually fighting — every other + // candidate reads -1. Math.Clamp(-1, 0, 1) folded that to 0.0, i.e. "at + // death's door", so every untouched mob collected the FULL 50-point + // wounded bonus while the mob we were burning down scored its real, + // smaller one. + // + // The nastier half: a target's score COLLAPSED by up to 45 points the + // instant we hit it and its true health finally arrived. Engaging a mob + // made it a worse choice than the untouched mob standing next to it, so + // combat was pushed off whatever it had just committed to and onto the + // next one — pick, turn, hit once, re-pick, turn again. That is the spin. + // + // Unknown health means "not engaged yet", and an un-engaged mob is almost + // certainly at full health. Score it that way. + float hpRatio = _worldFilter.GetHealthRatio(c.Id); + double hpScore = hpRatio < 0f ? 0.0 : (1.0 - Math.Clamp(hpRatio, 0f, 1f)) * 50.0; + + // Continuous ramp rather than a hard step at 3.0m. As a step this was + // worth 30 points the moment a mob crossed the line — more than + // TARGET_SWITCH_STICKINESS (25) — so a mob jittering either side of 3.0m + // could flip the winner every tick regardless of our commitment. + double threatScore = Math.Clamp((THREAT_RANGE_M - c.Distance) / THREAT_RANGE_M, 0.0, 1.0) * 30.0; + + double facingScore = (1.0 - Math.Min(1.0, c.Angle / 180.0)) * 10.0; + + // Monster-rule priority: default scoring already prefers "fastest to attack" + // (close/low-hp/in-melee/in-front), which is right for normal grind dungeons. + // The user uses MonsterRules.Priority to elevate threats they want focused + // first — so only apply a bonus when Priority is *above* the default of 1. + // Priority 10 → +45 (about half a max-distance score, enough to switch + // targets unless the alternative is much closer/lower-HP). + string targetName = c.Name; + var rule = _settings.MonsterRules.FirstOrDefault( + r => !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && + targetName.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + double priorityScore = rule != null ? Math.Max(0, rule.Priority - 1) * 5.0 : 0; + + return distScore + hpScore + threatScore + facingScore + priorityScore; + } + + private DateTime _lastEquipTime = DateTime.MinValue; + private DateTime _lastStanceTime = DateTime.MinValue; + private DateTime _lastEquipDiagAt = DateTime.MinValue; + + // Returns true when the correct weapon is wielded and combat mode matches — safe to attack. + // Returns false when a weapon swap or stance change is in progress — caller should skip this tick. + private bool EquipWeaponAndSetStance(WorldObject target, string monsterWeakness = "Auto") + { + if (target == null) return true; + + int targetWeaponId = 0; + + var rule = _settings.MonsterRules.FirstOrDefault( + r => target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + if (rule == null) + rule = _settings.MonsterRules.FirstOrDefault(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + + string desired = (rule != null && rule.DamageType != "Auto") ? rule.DamageType : monsterWeakness; + + string weaponSource = "none"; + // Per-monster weapon now comes from the Damage tab (per-wcid override > learned best), + // NOT the Monsters-tab rule.WeaponId (that selection was removed — hard cut). Resolve the + // target's wcid the same way BeginFight does. + uint targetWcid = 0; + if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)target.Id, out uint tw)) targetWcid = tw; + if (targetWcid != 0 && _damageStore != null) + { + uint eff = _damageStore.GetEffectiveWeapon(targetWcid); + if (eff != 0) { targetWeaponId = (int)eff; weaponSource = "DamageTab"; } + } + if (targetWeaponId == 0) + { + // No Damage-tab choice yet → element/wand auto (element from rule.DamageType or weakness). + var bestWeapon = _settings.ItemRules.FirstOrDefault(i => i.Element.Equals(desired, StringComparison.OrdinalIgnoreCase)) + ?? _settings.ItemRules.FirstOrDefault(); + if (bestWeapon != null) { targetWeaponId = bestWeapon.Id; weaponSource = "ItemRules"; } + } + + if (targetWeaponId == 0) + { + targetWeaponId = FindWandInItems(); + if (targetWeaponId != 0) weaponSource = "FindWandInItems"; + } + if (targetWeaponId == 0) + { + if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5) + { + _lastEquipDiagAt = DateTime.Now; + _host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}') — proceeding unarmed"); + } + return true; + } + + var weaponObj = _worldFilter[targetWeaponId]; + if (weaponObj == null) + { + if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5) + { + _lastEquipDiagAt = DateTime.Now; + _host.Log($"[EquipDiag] weapon 0x{targetWeaponId:X8} not in WorldFilter (source={weaponSource}) — proceeding unarmed"); + } + return true; + } + + // Remember the weapon in hand (now confirmed in-world) so melee/missile damage + // (0x01B1) learns under the real weapon, not a resolved-but-unwielded id. + _equippedWeaponId = targetWeaponId; + + // Use IsWandObject (ObjectClass + name fallback) so wands with + // ObjectClass=Unknown (stale WorldFilter classification) still get + // Magic mode instead of falling through to the Melee default. + int desiredMode = IsWandObject(weaponObj) ? CombatMode.Magic + : weaponObj.ObjectClass == AcObjectClass.MissileWeapon ? CombatMode.Missile + : CombatMode.Melee; + + bool diagNow = (DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5; + + // Use CurrentWieldedLocation (stype=10) — has an InqInt fallback that works even + // when the phys-obj offset probe hasn't fired yet (unlike TryGetObjectWielderInfo). + bool alreadyWielded = weaponObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + + // Secondary check — BuffManager.EnsureMagicMode has always had this and this + // path never did, which is the whole reason buffing could flip the stance and + // combat could not. CurrentWieldedLocation reads 0 for a weapon that IS wielded + // whenever the cached property hasn't been refreshed, and a mage's wand is + // permanently in hand, so the primary read is exactly the one that goes stale. + // Falling through to the not-wielded branch on a wielded wand sends UseObject + // (a no-op MOVE) forever and never sends the stance flip that was the only + // thing actually missing. Confirmed live 2026-09-02: entering Magic mode by + // hand immediately unstuck combat. + if (!alreadyWielded && _host.HasGetObjectWielderInfo) + { + uint pid = _host.GetPlayerId(); + if (pid != 0 && _host.TryGetObjectWielderInfo((uint)targetWeaponId, out uint wielder, out _) + && wielder == pid) + { + alreadyWielded = true; + // Must re-arm the throttle, as every other [EquipDiag] site does. + // diagNow is computed from _lastEquipDiagAt; logging without + // updating it leaves the gate permanently open on any path that + // returns before reaching one of those sites — this logged at the + // full 30Hz tick rate, 26,410 lines in one rotation (~70% of the + // log), which churned the log every ~30min and destroyed + // diagnostic history that was needed to investigate other issues. + if (diagNow) + { + _lastEquipDiagAt = DateTime.Now; + _host.Log($"[EquipDiag] wielded via wielder-info fallback (CurrentWieldedLocation read 0) 0x{targetWeaponId:X8} '{weaponObj.Name}'"); + } + } + } + + if (alreadyWielded) + { + // Don't enter missile mode without ammo — AC rejects it and cycles stance + if (desiredMode == CombatMode.Missile && !HasWieldedAmmo()) + return false; + + // The wand read as wielded, so whatever UseObject we had in flight landed. + // Clear the gate here (not only on reaching the stance) so a slow stance + // flip doesn't leave a stale pending-wield behind it. + ResetCombatWandWieldGate(); + + if (CurrentCombatMode == desiredMode) + { + ResetStanceRecovery(); // reached the stance — clear the whole episode + return true; + } + + // Deadlock recovery: AC is refusing the stance change despite the wand + // reading as wielded. After a stuck window, STOP trusting the stale wield + // read — flush any jammed command interpreter (no m_cBusy pin → the + // watchdog won't) and RE-EQUIP the wand (UseObject resyncs the wield; on a + // truly-unwielded wand it wields it, which is the actual fix). Without this + // the bot sat in NonCombat for 5h, buffs expired, never fighting (2026-06-10). + if (_stanceStuckSince == DateTime.MinValue) + _stanceStuckSince = DateTime.Now; + double stuckMs = (DateTime.Now - _stanceStuckSince).TotalMilliseconds; + // RE-EQUIP recovery — only for the first couple of attempts in an + // episode (handles a stale "wielded reads true" on a wand that + // actually isn't wielded). Capped: UseObject on a genuinely wielded + // wand is a MOVE to AC, and unbounded re-equip jams the item queue. + if (_stanceReEquipAttempts < StanceReEquipMaxAttempts + && stuckMs > StanceStuckRecoverMs + && (DateTime.Now - _lastStanceRecoverAt).TotalMilliseconds > StanceStuckRecoverMs + // Recovery equips like any other path — must hold the swap gate or + // it can collide with a buff wand-equip inside the ±3s window. + // On refusal the && short-circuits: fall through to the throttled + // ChangeCombatMode below and retry next tick. + && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("stance-recovery"))) + { + _lastStanceRecoverAt = DateTime.Now; + _stanceReEquipAttempts++; + _host.Log($"[EquipDiag] STANCE STUCK {stuckMs:0}ms mode={CurrentCombatMode}≠{desiredMode} (wielded reads true) — re-equip attempt {_stanceReEquipAttempts}/{StanceReEquipMaxAttempts} 0x{targetWeaponId:X8}"); + if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount(); + _host.UseObject((uint)targetWeaponId); + _lastEquipTime = DateTime.Now; + lastStanceAttempt = DateTime.MinValue; // let ChangeCombatMode re-fire next tick + return false; + } + // Past the re-equip cap: the wand really is wielded and AC just + // won't flip the mode. Do NOT keep UseObject-ing (that's what jams + // the item queue) — fall through to mode-change-only, and warn once + // so a genuinely wedged stance is visible instead of silent. + if (_stanceReEquipAttempts >= StanceReEquipMaxAttempts && !_stanceWedgeWarned + && stuckMs > StanceStuckRecoverMs * 3) + { + _stanceWedgeWarned = true; + _host.WriteToChat($"[RynthAi] Stance wedged: wand wielded but AC won't enter {(desiredMode == CombatMode.Magic ? "Magic" : "combat")} mode after {stuckMs / 1000:0}s. Re-equip stopped (was jamming item actions). Try /ra clearbusy, or relog if it persists.", 2); + } + + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); } + _host.ChangeCombatMode(desiredMode); + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } + else if (diagNow) + { + _lastEquipDiagAt = DateTime.Now; + _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}≠{desiredMode} throttled (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}') — waiting for mode change"); + } + return false; + } + + // Wield-location probe hasn't confirmed this item yet. Two cases: + // + // A) Already in the correct combat mode — AC enforces "weapon wielded ↔ mode matches", + // so trust it. Calling UseObject on an already-wielded wand is a no-op in AC + // (it opens the wand's properties), so we must NOT call it here. + if (CurrentCombatMode == desiredMode) + { + _stanceStuckSince = DateTime.MinValue; ResetWandSwapState(); ResetStanceFlipBackoff(); // reached the stance — clear stuck timer + swap + flip backoff + ResetCombatWandWieldGate(); + return true; + } + + // B-wand) Held-slot wand, not yet wielded. The wand CANNOT wield while a + // melee/missile weapon occupies the main hand — stock ACE's CheckWeaponCollision + // refuses it, AND the server DENIES ChangeCombatMode(Magic) while the bow is + // wielded ("GetEquippedWand()==null"), which is the Missile↔NonCombat↔Magic flap. + // So: tear down the in-flight attack, stow the bow into an open pack FIRST, then + // UseObject(wand). Do NOT request Magic here — the alreadyWielded branch above + // flips the stance once CurrentWieldedLocation confirms the wand. Mirrors the + // proven BuffManager.EnsureMagicMode dequip-first path (the missing 4th site). + if (desiredMode == CombatMode.Magic) + { + // Claim the shared swap slot FIRST so a concurrent buff/combat equip can't + // collide; only then tear down / move items (don't cancel an attack then fail + // to claim the slot). The 3s gate interval paces the dequip→wield steps. + if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-wand-swap")) + return false; + + if (!_combatSwapTeardownDone + && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) + { + if (_host.HasCancelAttack) _host.CancelAttack(); + if (_host.HasStopCompletely) _host.StopCompletely(); + _combatSwapTeardownDone = true; + _host.Log($"[EquipDiag] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})"); + } + + // Clear the main hand. Yields (false) while a dequip is in flight or blocked; + // returns true only once the bow is confirmed out of the main hand. + if (!EnsureHandClearForWand(targetWeaponId, diagNow)) + return false; + + // Main hand is clear (no bow), so the reason this branch withheld the + // stance request — "the server DENIES ChangeCombatMode(Magic) while the bow + // is wielded" — no longer applies. Send it. If the wand is in fact already + // wielded and only the cached wield-location read is stale, this flip IS the + // entire fix and no amount of UseObject would ever have produced it. Costs + // nothing when the wand genuinely isn't wielded: ACE just denies it, and the + // gated UseObject below still does the wielding. Mirrors the non-wand branch, + // which has always sent both. + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + { + if (diagNow) _host.Log($"[EquipDiag] hand clear — ChangeCombatMode({desiredMode}) alongside wand equip (mode={CurrentCombatMode})"); + _host.ChangeCombatMode(desiredMode); + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } + + // Main hand is clear — wield the wand through the wield gate. Stance flip + // happens next tick in the alreadyWielded branch once the wand reads as + // wielded. Do NOT re-send UseObject on a fixed 2s tick: each send is an + // item MOVE to AC, and a continuous stream of them keeps the item-action + // queue jammed so the wield never resolves. Issue one, wait for it, + // cool down, cap. + DateTime wnow = DateTime.Now; + + if (wnow < _wandWieldCooldownUntil) + return false; + + if (_wandPendingWieldId != 0) + { + if ((wnow - _wandPendingWieldAt).TotalMilliseconds < WandWieldResolveTimeoutMs) + return false; // still resolving — give the server time, send nothing + + _wandWieldFailCount++; + _host.Log($"[EquipDiag] wand UseObject(0x{_wandPendingWieldId:X8}) not confirmed in {WandWieldResolveTimeoutMs:0}ms — " + + $"cooling down {WandWieldCooldownMs:0}ms (fail {_wandWieldFailCount}/{WandWieldFailMax})"); + _wandPendingWieldId = 0; + _wandWieldCooldownUntil = wnow.AddMilliseconds(WandWieldCooldownMs); + + // Past the cap the wand provably won't wield right now. Say so once, + // loudly, instead of standing in peace mode issuing item actions + // forever — that silence is what made this take an hour to spot. + if (_wandWieldFailCount >= WandWieldFailMax && !_wandWieldWedgeWarned) + { + _wandWieldWedgeWarned = true; + _host.Log($"[EquipDiag] WAND WIELD WEDGED: 0x{targetWeaponId:X8} '{weaponObj.Name}' would not wield after {WandWieldFailMax} attempts " + + $"(mode={CurrentCombatMode}, busy={BusyCount}) — combat cannot enter Magic. Retrying on the cooldown cadence."); + _host.WriteToChat($"[RynthAi] Can't wield '{weaponObj.Name}' — combat is stuck out of Magic mode. Check the wand is reachable (not in a closed pack) or re-equip it manually.", 2); + } + return false; + } + + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] hand clear — UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') wand equip"); } + _host.UseObject((uint)targetWeaponId); + _wandPendingWieldId = targetWeaponId; + _wandPendingWieldAt = wnow; + _lastEquipTime = wnow; + return false; + } + + // B) Non-wand (melee/missile) weapon not yet confirmed wielded. Either it genuinely + // isn't wielded, or CurrentCombatMode is stale (e.g. hot-reload didn't re-fire + // OnCombatModeChange). Request both a mode change and an equip — these go in the + // main hand, which AC swaps in place (no held-slot collision). ChangeCombatMode + // succeeds if already wielded (fixes hot-reload next tick); UseObject equips it if not. + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); } + _host.ChangeCombatMode(desiredMode); + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000 + && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-equip"))) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') — equip attempt"); } + _host.UseObject((uint)targetWeaponId); + _lastEquipTime = DateTime.Now; + } + return false; + } + + // Stow the wielded non-wand weapon (the bow) blocking the Held-slot wand into a + // capacity-verified open pack (AutoCram-pattern, AV-safe), fully bounded. Returns + // true only when the main hand is confirmed clear (safe to wield the wand); false + // while a dequip is resolving, blocked, or just issued — caller yields this tick. + private bool EnsureHandClearForWand(int wandId, bool diagNow) + { + int bowId = FindWieldedNonWandWeapon(wandId); + if (bowId == 0) { _combatBowDequipPendingId = 0; _combatBowDequipAttempts = 0; return true; } + + DateTime now = DateTime.Now; + if (_combatBowDequipPendingId == bowId + && (now - _combatBowDequipAt).TotalMilliseconds < WandSwapWieldResolveMs + && IsWieldedLive(bowId)) + return false; // dequip still resolving + + if (IsWieldedLive(bowId)) + { + int openPack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1); + if (openPack == 0 || _combatBowDequipAttempts >= CombatBowDequipMaxAttempts) + { + // No verified-open pack to receive the bow, or repeated failures — the swap + // can't complete now. Reset the attempt counter and yield; combat keeps + // running with the bow (missile) until a slot frees (e.g. after looting). + if (diagNow) + { + _lastEquipDiagAt = now; + _host.Log($"[EquipDiag] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_combatBowDequipAttempts}/{CombatBowDequipMaxAttempts}) — cannot swap to wand yet"); + } + _combatBowDequipPendingId = 0; + _combatBowDequipAttempts = 0; + return false; + } + _combatBowDequipAttempts++; + _host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0) + _combatBowDequipPendingId = bowId; + _combatBowDequipAt = now; + _host.Log($"[EquipDiag] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_combatBowDequipAttempts}/{CombatBowDequipMaxAttempts}) before wand equip"); + return false; // yield until the bow is out of hand + } + + _combatBowDequipPendingId = 0; + _combatBowDequipAttempts = 0; + return true; // bow confirmed unwielded — main hand clear + } + + // The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand. + private int FindWieldedNonWandWeapon(int wandId) + { + foreach (var wo in _worldFilter.GetDirectInventory(forceRefresh: true)) + { + if (wo.Id == wandId) continue; + if (IsWandObject(wo)) continue; + if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0 + && (wo.ObjectClass == AcObjectClass.MeleeWeapon + || wo.ObjectClass == AcObjectClass.MissileWeapon)) + return wo.Id; + } + return 0; + } + + // Live (forceRefresh) wielded check — never trusts a stale cache snapshot. + private bool IsWieldedLive(int id) + { + if (id == 0) return false; + foreach (var wo in _worldFilter.GetDirectInventory(forceRefresh: true)) + if (wo.Id == id) + return wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + if (_host.HasGetObjectWielderInfo) + { + uint pid = _host.GetPlayerId(); + if (pid != 0 && _host.TryGetObjectWielderInfo((uint)id, out uint wielder, out _)) + return wielder == pid; + } + return false; + } + + /// + /// Ensure a wand is wielded and the player is in Magic combat mode. + /// Used by NavigationEngine to prepare for recall casts. Returns true only when + /// ready to cast; when false, caller should re-tick (equip/stance are throttled + /// internally so calling every tick is safe). + /// + public bool EnsureMagicReady() + { + int wandId = FindWandInItems(); + if (wandId == 0) return false; + + var wand = _worldFilter[wandId]; + if (wand == null) return false; + + bool alreadyWielded = wand.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + + if (alreadyWielded) + { + if (CurrentCombatMode == CombatMode.Magic) { ResetWandSwapState(); ResetStanceFlipBackoff(); return true; } + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + { + _host.ChangeCombatMode(CombatMode.Magic); + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } + return false; + } + + if (CurrentCombatMode == CombatMode.Magic) { ResetWandSwapState(); ResetStanceFlipBackoff(); return true; } + + // Wand not wielded. Dequip the blocking bow FIRST (stock ACE won't auto-dequip a + // main-hand weapon for the Held-slot wand, and denies ChangeCombatMode(Magic) while + // it's wielded). Do NOT request Magic until the wand is wielded — the alreadyWielded + // branch above handles the stance flip. Mirrors EquipWeaponAndSetStance / BuffManager. + if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-magicready-wand")) + return false; + if (!_combatSwapTeardownDone + && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) + { + if (_host.HasCancelAttack) _host.CancelAttack(); + if (_host.HasStopCompletely) _host.StopCompletely(); + _combatSwapTeardownDone = true; + } + if (!EnsureHandClearForWand(wandId, diagNow: true)) + return false; + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000) + { + _host.UseObject((uint)wandId); + _lastEquipTime = DateTime.Now; + } + return false; + } + + public string GetRaycastStatus() + { + if (_raycastSystem == null) return "Raycasting: NOT INITIALIZED"; + string status = _settings.EnableRaycasting ? "ACTIVE" : "DISABLED"; + return $"Raycasting: {status}\n Status: {_raycastSystem.StatusMessage}\n Checks: {RaycastCheckCount}, Blocks: {RaycastBlockCount}"; + } + + public List GetRaycastDiagLog() + { + var lines = new List(); + if (_raycastSystem?.GeometryLoader?.DiagLog != null) + foreach (var line in _raycastSystem.GeometryLoader.DiagLog) lines.Add(line); + return lines; + } + + private TargetingFSM.AttackType DetermineAttackTypeForLOS() + { + if (CurrentCombatMode == CombatMode.Magic) + { + // Get rule from current target name if available + var targetObj = _worldFilter[activeTargetId]; + var rule = GetRuleForTarget(targetObj); + if (rule != null && rule.UseArc) return TargetingFSM.AttackType.MagicArc; + return TargetingFSM.AttackType.Linear; + } + + if (_raycastSystem?.TargetingFSM != null) + return _raycastSystem.GetAttackType(CurrentCombatMode, ""); + + return TargetingFSM.AttackType.Linear; + } + + private void FaceTarget(int targetId) + { + try + { + if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _, + out float qw, out _, out _, out float qz)) + return; + if (!_host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _)) + return; + + double dx = tx - px; + double dy = ty - py; + double desiredDeg = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + double currentDeg = ((-physYawDeg) % 360.0 + 720.0) % 360.0; + + double error = desiredDeg - currentDeg; + while (error > 180.0) error -= 360.0; + while (error < -180.0) error += 360.0; + + if (Math.Abs(error) <= FACE_TOLERANCE_DEG) + { + ClearCombatTurnMotions(); + } + else if (error > 0) + { + _host.SetMotion(MotionTurnRight, true); + _host.SetMotion(MotionTurnLeft, false); + } + else + { + _host.SetMotion(MotionTurnLeft, true); + _host.SetMotion(MotionTurnRight, false); + } + } + catch { } + } + + private void ClearCombatTurnMotions() + { + _host.SetMotion(MotionTurnRight, false); + _host.SetMotion(MotionTurnLeft, false); + } + + /// + /// True while a previously-issued combat cast is still resolving on the ACE + /// server. Serializes magic casts so the next cast's turn/stop motion can't + /// orphan the prior cast's deferred windup. Cleared when a server UseDone + /// (0x1C7) is observed since the cast (the server finished the action — + /// completed or refused) or a hard timeout elapses. On an engine without + /// UseDone observation (HasUseDoneSeq == false) the timeout is the sole gate. + /// + private bool IsAwaitingCastResolution() + { + if (!_awaitingCastResolution) return false; + if (_host.HasUseDoneSeq && _host.GetUseDoneSeq() != _useDoneSeqAtCast) + { + _awaitingCastResolution = false; + return false; + } + if (DateTime.Now >= _castResolutionDeadline) + { + _awaitingCastResolution = false; + return false; + } + return true; + } + + /// True while a targeted combat cast is still resolving on the server (windup + /// in flight). Shares the bounded IsAwaitingCastResolution state, so it self-clears on + /// the UseDone-seq advance or the 2.5s timeout — used to gate motion emitters that would + /// otherwise truncate the cast gesture and strand server Player.IsBusy (relog-only wedge). + private bool IsCastInFlight() => IsAwaitingCastResolution(); + + /// Record that a targeted combat cast was just issued, so the next + /// cast waits for it to resolve on the server (see IsAwaitingCastResolution). + private void MarkCombatCastIssued() + { + _awaitingCastResolution = true; + _castResolutionDeadline = DateTime.Now.AddMilliseconds(CAST_RESOLUTION_TIMEOUT_MS); + _useDoneSeqAtCast = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0; + } + + /// + /// Returns the absolute heading error (degrees) between the player's current + /// facing and the direction to the target. Used to decide whether we need to + /// wait for a heading change before firing a ranged attack. + /// + private double GetFacingError(int targetId) + { + try + { + if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _, + out float qw, out _, out _, out float qz)) + return 180.0; // can't read pose — assume worst case + + if (!_host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _)) + return 180.0; + + // Desired heading to target (0=North CW) + double dx = tx - px; + double dy = ty - py; + double desiredDeg = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + // Current heading from quaternion (same formula as NavigationEngine) + double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + double currentDeg = ((-physYawDeg) % 360.0 + 720.0) % 360.0; + + double error = desiredDeg - currentDeg; + while (error > 180.0) error -= 360.0; + while (error < -180.0) error += 360.0; + return Math.Abs(error); + } + catch { return 180.0; } + } + + private bool HasWieldedAmmo() + { + int playerId = unchecked((int)_playerId); + + // Walk via GetDirectInventory(forceRefresh:true). This is the same path + // MissileCraftingManager uses successfully — it triggers per-item + // wielder-info lookups on the cache, which populates Wielder / + // WieldedLocation. AllKnownObjects() doesn't trigger those probes, so + // arrows that arrived via OnCreateObject keep WieldedLocation=0 and + // never match. The forced refresh adds ~one InqInt call per pack item + // but is cheap and fixes detection definitively. + foreach (var item in _worldFilter.GetDirectInventory(forceRefresh: true)) + if (LooksLikeWieldedAmmo(item, playerId)) return true; + + return false; + } + + // EquipMask bit for the ammunition slot. Items wielded in this slot are ammo + // by definition — far more reliable than name or ItemType inspection because + // some servers type their arrows as MissileWeapon (0x100) rather than the + // MissileAmmo bit (0x400) that AC's vanilla data has. + private const int AmmunitionSlot = 0x00800000; + + private bool LooksLikeWieldedAmmo(WorldObject item, int playerId) + { + if (item == null) return false; + + // Authoritative: ask AC's runtime for the wielder + slot directly. + // The cached WieldedLocation/Wielder fields can be 0 forever if the + // item arrived via OnCreateObject and never went through the + // GetDirectInventory walk that probes wielder info. Querying the + // host API per-candidate side-steps that. + int loc = 0; + bool slotKnown = false; + if (_host.HasGetObjectWielderInfo && + _host.TryGetObjectWielderInfo(unchecked((uint)item.Id), out uint wielder, out uint locFromApi)) + { + if (playerId != 0 && wielder != 0 && wielder != (uint)playerId) return false; + if (locFromApi > 0) { loc = unchecked((int)locFromApi); slotKnown = true; } + } + + // Fall back to InqInt and the cache field if the wielder API didn't answer. + if (!slotKnown) + { + int locInq = item.Values(LongValueKey.CurrentWieldedLocation, 0); + int locCache = item.WieldedLocation; + loc = locInq > 0 ? locInq : locCache; + if (loc <= 0) return false; + if (playerId != 0 && item.Wielder != 0 && item.Wielder != playerId) return false; + } + + // Authoritative: ammunition slot bit. + if ((loc & AmmunitionSlot) != 0) + return true; + + // Name-based fallback for items in non-ammo slots that still match + // ammo names (rare server-custom configurations). + string n = item.Name; + if (string.IsNullOrEmpty(n)) return false; + if (n.Contains("Bundle") || n.Contains("Wrapped")) return false; + return n.Contains("Arrow") || n.Contains("Quarrel") || n.Contains("Bolt") || n.Contains("Dart"); + } + + private void AttackTarget() + { + try + { + bool isMissile = CurrentCombatMode == CombatMode.Missile; + uint targetId = (uint)activeTargetId; + + // Don't fire in missile mode without ammo — let crafting manager handle it + if (isMissile && !HasWieldedAmmo()) + return; + + float power; + int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower; + if (powerPct < 0) + { + power = 1.0f; + if (_settings.UseRecklessness && (_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2)) + power = 0.8f; + } + else + { + power = powerPct / 100f; + } + + int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight; + int acHeight = uiHeight switch { 0 => 3, 2 => 1, _ => 2 }; // Low=3, Med=2, High=1 + + // Native attack: select target, Start fills power bar, End fires the attack. + // Called each attack cycle — the client handles turn-to-face naturally. + if (_settings.UseNativeAttack && _host.HasNativeAttack) + { + _host.SelectItem(targetId); + _host.NativeAttack(acHeight, power); + return; + } + + // Direct attack: raw game action (bypasses client facing) + if (isMissile) + _host.MissileAttack(targetId, acHeight, power); + else + _host.MeleeAttack(targetId, acHeight, power); + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // MAGIC COMBAT SYSTEM + // ══════════════════════════════════════════════════════════════════════════ + + private MonsterRule? GetRuleForTarget(WorldObject? target) + { + if (target == null) return null; + + string metaState = _settings.CurrentState ?? "Default"; + + foreach (var r in _settings.MonsterRules) + { + if (r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) continue; + + bool matches; + if (!string.IsNullOrWhiteSpace(r.MatchExpression)) + { + // Expression match: eval first; if expression is true AND name is non-empty, also check name. + bool exprTrue = _monsterMatchEval?.Evaluate(r.MatchExpression, target, metaState) ?? false; + if (!string.IsNullOrWhiteSpace(r.Name)) + matches = exprTrue && target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0; + else + matches = exprTrue; + } + else + { + matches = !string.IsNullOrWhiteSpace(r.Name) && + target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0; + } + + if (matches) return r; + } + + return _settings.MonsterRules.FirstOrDefault( + m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + private void AttackWithMagic(WorldObject target) + { + if (_spellManager == null || target == null) return; + + // Hard safety veto: never cast offensive magic at something AC's combat + // system says is not attackable. AC NPCs/vendors are ItemType=Creature, + // so classification (the ItemType-flag rescue path in WorldObjectCache) + // can still promote them to "Monster" even after the engine fix cleans + // the primary attackable-gated path. The attackable check is the game's + // own authority for "can I fight this". The engine serves the REAL + // ObjectIsAttackable from a main-thread snapshot to this off-thread + // pump; if it says not-attackable, bail before any cast/select. + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)target.Id)) + return; + + // Keep the authoritative known-spell snapshot warm for the combat + // resolver even when the char isn't buffing (GetDynamicSelfBuffId is + // the only other pump). Throttled internally — cheap to call per tick. + _spellManager.RefreshKnownSpells(); + + // Combat spell selection is now purely predictive (known ∧ scarab ∧ + // skill-window tier ∧ configured shape). No empirical no-chat → + // blacklist valve: it falsely poisoned KNOWN spells whenever a cast + // didn't execute, which is what collapsed war to Force Bolt I and + // re-poisoned bufftimers.txt every few seconds. + + // Don't cast while a weapon equip is in progress — the wand may not be registered + // as wielded yet. _lastEquipTime is set whenever UseObject is called for a wand swap. + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds < 3000) + { + _host.Log($"[CombatCast] equip-gate: wand equip in progress ({(DateTime.Now - _lastEquipTime).TotalMilliseconds:0}ms < 3000ms), skipping cast"); + LastCombatSkipReason = "equip-gate"; // D4 record-only + return; + } + // Cadence is the motion-end gate (CanCastNow at the AttackWithMagic + // call site, CombatManager.cs:905) — no fixed inter-cast interval; + // fire as soon as the cast gesture completes. + + if (_waitingForDebuffResult) + { + if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS) + { + _confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}"); + _waitingForDebuffResult = false; + } + else + { + LastCombatSkipReason = "awaiting-debuff-result"; // D4 record-only + return; + } + } + + if (activeTargetId != _lastDebuffTargetId) + { + _confirmedDebuffs.Clear(); + _lastDebuffTargetId = activeTargetId; + } + + var rule = GetRuleForTarget(target); + string element = GetPreferredElement(target, rule); + + if (rule != null) + { + var pendingDebuffs = BuildDebuffList(rule, element); + foreach (var debuffKey in pendingDebuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + if (_confirmedDebuffs.Contains(key)) continue; + + int spellId = 0; + int castTier = 0; + if (debuffKey.StartsWith("Vuln:")) + spellId = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier); + else + spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier); + + if (spellId == 0) continue; + + try + { + _host.CastSpell((uint)activeTargetId, spellId); + MarkCombatCastIssued(); + _lastSpellCast = DateTime.Now; + _lastCastWasRing = false; + _pendingDebuffKey = debuffKey; + _pendingDebuffTargetId = activeTargetId; + _pendingDebuffTier = castTier; + _waitingForDebuffResult = true; + _pendingDebuffCastTime = DateTime.Now; + _host.WriteToChat($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5); + } + catch { } + return; + } + } + + if (rule != null && !rule.UseArc && !rule.UseRing && !rule.UseStreak && !rule.UseBolt) + { + _host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt all false) — no offensive cast"); + LastCombatSkipReason = "no-attack-shapes"; // D4 record-only + return; + } + + int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0; + int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0; + int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing); + if (offensiveSpellId != 0) + { + LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick + // Visibility: log exactly what war/void spell we're about to cast + // (id + resolved name + element/tier/target). Diagnostic only. + _host.Log($"[CombatCast] offensive id={offensiveSpellId} " + + $"'{SpellTableStub.GetById(offensiveSpellId)?.Name}' elem={element} " + + $"ring={isRing} warTier={warTier} voidTier={voidTier} target='{target.Name}'"); + try + { + _host.CastSpell((uint)activeTargetId, offensiveSpellId); + MarkCombatCastIssued(); + SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal + CastsSinceLastKill++; // reset in OnKillNotification when a kill lands + _lastSpellCast = DateTime.Now; + _lastCastWasRing = isRing; + // _offensiveCastThisCycle is NOT set here anymore — a cast + // attempt that the server refuses (e.g. "You're too busy!") + // must not count toward the blacklist miss streak. The + // RecordOffensiveCast trigger moved to the chat-confirmation + // path so only chat-confirmed casts queue a judgement. + _pendingOffensiveSpellId = offensiveSpellId; + _pendingOffensiveCastAt = DateTime.Now; + _pendingOffensiveTargetId = activeTargetId; + + // Tag this cast's weapon + element + tier so the pushed damage event + // can be attributed to it, count it for casts-to-kill learning, then + // decide if it's a predicted kill shot. + _lastCastWeaponId = unchecked((uint)FindWandInItems()); + _lastCastElement = element; + // Tier = the LEVEL of the spell actually cast (1-8), not the caster's highest + // castable tier (which made every magic kill record tier 8). Fall back to the + // old max-tier only if the level can't be derived, so it never regresses to blank. + int castLevel = SpellTableStub.GetById(offensiveSpellId)?.Level ?? 0; + int castTierMag = castLevel > 0 ? castLevel : Math.Max(warTier, voidTier); + // Ring spells are stored as a NEGATIVE tier so the Damage tab can render them as + // "R" (e.g. a level-2 ring = -2 -> "R2"); non-ring stays positive; 0 = none. + _lastCastTier = isRing ? -castTierMag : castTierMag; + // Record the latest tier used vs this monster so the Damage tab's collapsed row + // reflects it immediately (covers ring casts, which skip RecordHit). + if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName); + _fightCastCount++; + // Snapshot this fight so a kill that lands after we've dropped/advanced + // can still be credited by name (see OnKillNotification step 3). + if (_fightTargetWcid != 0) + { + _lastFightWcid = _fightTargetWcid; + _lastFightName = _worldFilter[activeTargetId]?.Name ?? _fightTargetName; + _lastFightWeaponId = _lastCastWeaponId; + _lastFightElement = _lastCastElement; + _lastFightTier = _lastCastTier; + _lastFightCount = _fightCastCount; + StampRecentFight(); + } + EvaluateKillShot(_lastCastWeaponId, element, _lastCastTier, isRing); + } + catch { } + } + else + { + bool snapWarm = _spellManager?.IsKnownSnapshotWarm == true; + _host.WriteToChat($"[RynthAi] No spell found: elem={element} warTier={warTier} voidTier={voidTier} snapshotWarm={snapWarm} pid={_playerId}", 2); + _host.Log($"[CombatCast] no offensive spell: elem={element} warTier={warTier} voidTier={voidTier} snapshotWarm={snapWarm} rule={rule?.Name ?? "null"} target='{target.Name}'"); + LastCombatSkipReason = "no-offensive-spell"; // D4 record-only (FindBestShapedSpell==0) + _lastSpellCast = DateTime.Now; // suppress repeated spam + } + } + + private int _autoElemDiagCount; + + private string GetPreferredElement(WorldObject? target, MonsterRule? rule) + { + if (rule != null && !string.IsNullOrEmpty(rule.DamageType) && + !rule.DamageType.Equals("Auto", StringComparison.OrdinalIgnoreCase)) + return rule.DamageType; + + // Learned-resist auto element: CreatureProfileStore has been recording + // per-creature resists all along — use the weakest one when no rule or + // static mapping names an element. Resist 1.0 = no data. Only swap when + // the configured shape actually resolves a castable spell of that + // element for this character (otherwise a learned weakness the char + // has no spells for would leave the mob unattacked — keep Fire then). + if (target != null && rule != null && _creatureStore != null && !string.IsNullOrEmpty(target.Name)) + { + CreatureProfile? prof = null; + bool got = _fightTargetWcid != 0 && target.Id == _fightTargetId + ? _creatureStore.TryGet(target.Name, _fightTargetWcid, out prof) + : _creatureStore.TryGetByName(target.Name, out prof); + if (got && prof != null) + { + var (weakType, resist) = CreatureProfileStore.GetWeakest(prof); + if (resist < 1.0 && !string.IsNullOrEmpty(weakType)) + { + string elem = char.ToUpperInvariant(weakType[0]) + weakType.Substring(1); + if (FindBestShapedSpell(elem, rule, out _) != 0) + { + if (_autoElemDiagCount < 20) + { + _autoElemDiagCount++; + _host.Log($"[CombatCast] auto-element '{target.Name}': learned weakest={elem} (resist {resist:0.00})"); + } + return elem; + } + } + } + } + + return "Fire"; + } + + private bool HasPendingDebuffs(MonsterRule rule, string element) + { + if (rule == null) return false; + foreach (var debuffKey in BuildDebuffList(rule, element)) + if (!_confirmedDebuffs.Contains($"{activeTargetId}_{debuffKey}")) return true; + return false; + } + + private int FindWandInItems() + { + // Prefer explicitly configured wand from item rules + foreach (var item in _settings.ItemRules) + { + var wo = _worldFilter[item.Id]; + if (wo != null && IsWandObject(wo)) return item.Id; + } + // Inventory cache scan — ObjectClass first, name fallback for unclassified items + foreach (var wo in _worldFilter.GetInventory()) + { + if (IsWandObject(wo)) return wo.Id; + } + return 0; + } + + private static bool IsWandObject(WorldObject wo) => + wo.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(wo.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; + } + + private static List BuildDebuffList(MonsterRule rule, string element) + { + var list = new List(); + if (rule.Imperil) list.Add("Imperil"); + if (rule.Vuln) list.Add("Vuln:" + element); + if (!string.IsNullOrEmpty(rule.ExVuln) && !rule.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) + list.Add("Vuln:" + rule.ExVuln); + if (rule.Fester) list.Add("Fester"); + if (rule.Yield) list.Add("Yield"); + if (rule.Broadside) list.Add("Broadside"); + if (rule.GravityWell) list.Add("Gravity"); + return list; + } + + private int FindBestDebuffSpellWithTier(string debuffType, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + if (!DebuffSpells.TryGetValue(debuffType, out string[]? spellInfo) || spellInfo.Length < 2) return 0; + + string tieredBase = spellInfo[0]; + string loreName = spellInfo[1]; + + int maxTier = EffectiveMaxTier(AcSkillType.CreatureEnchantment); + + if (maxTier >= 8) { int id = TrySpellByName($"Incantation of {tieredBase}"); if (id != 0) { tier = 8; return id; } } + if (maxTier >= 7 && !string.IsNullOrEmpty(loreName)) { int id = TrySpellByName(loreName); if (id != 0) { tier = 7; return id; } } + + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + int id = TrySpellByName($"{tieredBase} {GetRomanNumeral(t)}"); + if (id != 0) { tier = t; return id; } + } + return 0; + } + + private int FindBestVulnSpellWithTier(string element, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + if (!VulnSpells.TryGetValue(element, out string[]? vulnBases)) return 0; + + int maxTier = EffectiveMaxTier(AcSkillType.CreatureEnchantment); + + foreach (string baseName in vulnBases) + { + if (maxTier >= 8) { int id = TrySpellByName($"Incantation of {baseName}"); if (id != 0) { tier = 8; return id; } } + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + int id = TrySpellByName($"{baseName} {GetRomanNumeral(t)}"); + if (id != 0) { tier = t; return id; } + } + } + return 0; + } + + private int TrySpellByName(string name) + { + if (_spellManager == null) return 0; + // Single source of truth shared with the buff path: unresolvable skip + + // the engine's main-thread known-spell snapshot. Combat used to roll + // its own check that trusted the mis-bound IsSpellKnown oracle (lies + // "true" for unknown spells) and never saw _knownSpellIds, so an + // unknown tier-8 (e.g. Incantation of Flame Bolt) resolved as castable + // and never tiered down. Delegating fixes that for war/void/debuff/ring + // resolution alike. RefreshKnownSpells() is pumped on the attack path. + // Deterministic: name → id, REQUIRE the char knows it (authoritative + // warm spellbook snapshot). No empirical unresolvable blacklist, no + // mis-bound engine oracle — selection is purely predictive so nothing + // self-poisons. + if (!_spellManager.TryResolveKnownSpellId(name, out int id)) return 0; + + // Scarab gate DISABLED (EnablePredictiveComponentGate=false). Field- + // tested 2026-05-17, pid 15372: it rejected every KNOWN Force Arc + // tier ("NO-SCARAB" 2724/2723) while the char had the scarab — the + // dat-decoded SpellComponentTable scarab name does not match the ACE + // inventory item name. This is the documented predictive-components + // failure on ACE (see rynthai_predictive_components.md): only the + // server knows its real component rules. Selection therefore stays + // known ∧ skill-window tier ∧ configured shape; the player keeps + // components stocked. Code retained behind the flag for a future + // retry IF a verified scarab-name↔inventory-name mapping exists. + if (EnablePredictiveComponentGate) + { + EnsureInventoryNameCache(); + if (!ComponentDatabase.HasRequiredScarab(id, _invNamesLower)) + { + if (_compSkipLogged.Add(id)) + _host.Log($"[CombatCast] NO-SCARAB id={id} " + + $"'{SpellTableStub.GetById(id)?.Name}' — required scarab " + + $"not in inventory; tiering down."); + return 0; + } + } + return id; + } + + private void EnsureInventoryNameCache() + { + if ((DateTime.Now - _invNamesBuiltAt).TotalMilliseconds < InvNameCacheMs) return; + _invNamesBuiltAt = DateTime.Now; + _invNamesLower.Clear(); + _compSkipLogged.Clear(); + foreach (var wo in _worldFilter.GetInventory()) + if (!string.IsNullOrEmpty(wo.Name)) + _invNamesLower.Add(wo.Name.ToLowerInvariant()); + } + + private int CountMonstersInRange(double rangeYards) + { + if (_playerId == 0) return 0; + int pid = (int)_playerId; + int count = 0; + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.ObjectClass != AcObjectClass.Monster) continue; + float hp = _worldFilter.GetHealthRatio(wo.Id); + if (hp == 0f || hp < 0f) continue; + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)wo.Id)) continue; + if (_worldFilter.Distance(pid, wo.Id) <= rangeYards) + count++; + } + return count; + } + + private int FindBestShapedSpell(string element, MonsterRule? rule) => + FindBestShapedSpell(element, rule, out _); + + private int FindBestShapedSpell(string element, MonsterRule? rule, out bool isRing) + { + isRing = false; + if (_spellManager == null) return 0; + + bool useVoid = element.Equals("Nether", StringComparison.OrdinalIgnoreCase); + bool warTrained = _charSkills == null || _charSkills[AcSkillType.WarMagic].Training >= 2; + bool voidTrained = _charSkills == null || _charSkills[AcSkillType.VoidMagic].Training >= 2; + + if (useVoid && !voidTrained && warTrained) useVoid = false; + if (!useVoid && !warTrained && voidTrained) useVoid = true; + + AcSkillType skill = useVoid ? AcSkillType.VoidMagic : AcSkillType.WarMagic; + + int shapeIdx = 3; // default = Bolt + if (rule != null) + { + if (rule.UseArc) shapeIdx = 0; + else if (rule.UseStreak) shapeIdx = 2; + else if (rule.UseBolt) shapeIdx = 3; + else if (!rule.UseRing) return 0; // no shape enabled at all + } + + // Ring override: when UseRing is enabled, check if enough monsters are within + // ring range. If so, upgrade to ring; otherwise keep the base shape (bolt/arc/streak). + if (rule != null && rule.UseRing && _settings.RingRange > 0) + { + int nearbyCount = CountMonstersInRange(_settings.RingRange); + if (nearbyCount >= Math.Max(1, _settings.MinRingTargets)) + shapeIdx = 1; // ring + } + + var shapes = useVoid ? VoidSpellShapes : SpellShapes; + if (!shapes.TryGetValue(element, out string[]? elementShapes)) + { + if (useVoid) + { + // Void Magic only damages with Nether — fall back to Nether shapes for + // ANY element not in VoidSpellShapes (Cold/Lightning/Acid/Blade/Pierce/ + // Bludgeon/Slash). Previously this fell through to War Magic Fire, which + // forced War on Void-only casters whose War skill was untrained. + if (!VoidSpellShapes.TryGetValue("Nether", out elementShapes)) return 0; + } + else + { + if (!SpellShapes.TryGetValue("Fire", out elementShapes)) return 0; + skill = AcSkillType.WarMagic; + } + } + + if (shapeIdx >= elementShapes.Length) shapeIdx = elementShapes.Length - 1; + + if (shapeIdx == 1) + { + int ringId = FindBestRingSpell(element, skill); + if (ringId != 0) { isRing = true; return ringId; } + } + + // Strict TYPE adherence: cast ONLY the shape configured in the + // Monsters tab (Arc/Bolt/Streak) — plus the ring override handled + // above. No cross-shape fallthrough; that was casting Streak when + // Arc was configured but its tiers weren't resolvable. + // + // Streak (idx 2) / Bolt (idx 3) war lines have a lore-named tier-7 + // (no "{base} VII"); pass it so tier 7 resolves. Arc (idx 0) uses + // Roman "VII" (exists); Void has no lore tier-7 in this table. + string? t7 = null; + if (!useVoid && WarTier7Lore.TryGetValue(element, out string[]? w7)) + { + if (shapeIdx == 2) t7 = w7[0]; // Streak VII lore + else if (shapeIdx == 3) t7 = w7[1]; // Bolt VII lore + } + return FindBestOffensiveSpellId(elementShapes[shapeIdx], skill, t7); + } + + private int FindBestRingSpell(string element, AcSkillType skill) + { + // Void Magic doesn't have lore-named rings (Cassius'/Halo/etc. are all War + // Magic spells). Returning 0 here makes FindBestShapedSpell fall through to + // FindBestOffensiveSpellId(elementShapes[1], skill) where elementShapes comes + // from VoidSpellShapes — e.g. "Nether Ring" or "Corrosion Ring" — and the + // Void caster gets the right Void ring tier instead of an unknown War spell. + if (skill == AcSkillType.VoidMagic) + return 0; + + if (!RingLoreNames.TryGetValue(element, out string[]? loreNames) || loreNames.Length < 2) return 0; + + int maxTier = EffectiveMaxTier(skill); + + if (maxTier >= 7) + { + int id = TrySpellByName(loreNames[1]); if (id != 0) return id; + id = TrySpellByName(loreNames[1].Replace("'", "\u2019")); if (id != 0) return id; + id = TrySpellByName(loreNames[1].Replace("'", "`")); if (id != 0) return id; + } + if (maxTier >= 6) + { + int id = TrySpellByName(loreNames[0]); if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "\u2019")); if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "`")); if (id != 0) return id; + } + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {loreNames[0]}"); if (id != 0) return id; + } + + if (SpellShapes.TryGetValue(element, out string[]? genericRingBases) && genericRingBases.Length > 1) + { + string ringBase = genericRingBases[1]; + for (int t = Math.Min(maxTier, 5); t >= 1; t--) + { + int id = TrySpellByName($"{ringBase} {GetRomanNumeral(t)}"); if (id != 0) return id; + } + } + + _host.WriteToChat($"[RynthAi] Ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})", 2); + return 0; + } + + private int FindBestOffensiveSpellId(string baseName, AcSkillType skill, string? tier7Lore = null) + { + if (_spellManager == null) return 0; + int maxTier = EffectiveMaxTier(skill); + + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); if (id != 0) return id; + id = TrySpellByName(baseName + " VIII"); if (id != 0) return id; + } + + for (int tier = Math.Min(maxTier, 7); tier >= 1; tier--) + { + // Streak/Bolt war lines have no "{base} VII" — tier-7 is a lore + // name (e.g. Force Streak VII = "Outlander's Insolence"). Try it + // at the tier-7 step so the highest tier still wins; Arc falls + // through to the Roman "{base} VII" below (which exists). + if (tier == 7 && !string.IsNullOrEmpty(tier7Lore)) + { + int loreId = TrySpellByName(tier7Lore); if (loreId != 0) return loreId; + } + int id = TrySpellByName($"{baseName} {GetRomanNumeral(tier)}"); if (id != 0) return id; + } + return 0; + } + + /// + /// Combat tier ceiling. When the authoritative known-spell snapshot is + /// cold the resolver can't trust IsSpellKnown (it lies "true" for unknown + /// spells), so refuse to blind-pick the tier-8 Incantation — clamp to 7 + /// until the snapshot warms. A char who really knows L8 loses Incantations + /// only during the brief cold window; one who doesn't no longer spams an + /// uncastable L8 every fight. + /// + private int EffectiveMaxTier(AcSkillType skill) + { + if (_spellManager == null) return 0; + int t = _spellManager.GetHighestSpellTier(skill); + if (t > 7 && !_spellManager.IsKnownSnapshotWarm) t = 7; + return t; + } + + 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 void Dispose() => _raycastSystem?.Dispose(); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/ComponentDatabase.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/ComponentDatabase.cs new file mode 100644 index 0000000..98e7daa --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/ComponentDatabase.cs @@ -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; + +/// +/// 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 +/// +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 _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 _spellComps = new(); + private static bool _spellCompsLoaded; + + private static bool _loaded; + private static readonly object _lock = new(); + private static Action? _log; + + public static void SetLog(Action log) => _log = log; + + public static bool IsLoaded => _loaded; + + public static void EnsureLoaded(Action? log = null) + { + lock (_lock) + { + if (_loaded) return; + LoadFromDat(log); + } + } + + private static void LoadFromDat(Action? 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? 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; + } + + /// + /// Reads a nibble-swapped string: uint16 len, len bytes (each byte nibble-swapped), pad to 4-byte. + /// + 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. 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? 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(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 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? 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(); + 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); + } + + /// + /// Predictive component gate. Returns false ONLY when a required non-taper + /// component this spell needs is positively absent from + /// . 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. + /// + public static bool HasAllComponents(int spellId, HashSet 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; + } + + /// + /// Scarab-only predictive gate. Returns false ONLY when this spell's + /// required SCARAB (SpellComponentCategory 0) is positively absent from + /// . 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). + /// + public static bool HasRequiredScarab(int spellId, HashSet 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs new file mode 100644 index 0000000..d4f9209 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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) +/// +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()) == 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 _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 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 ""; } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs new file mode 100644 index 0000000..c70aa39 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -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; + +/// +/// 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. +/// +public class MissileCraftingManager +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private WorldObjectCache? _objectCache; + private CharacterSkills? _charSkills; + + public bool IsBusy { get; set; } = false; + /// Live combat mode — read from AC each access (1=peace, 2=melee, 4=missile, 8=magic). + 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 _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 AllRecipes = new List + { + // ── 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 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 GetInventory(bool forceRefresh = false) + => _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new(); + + private WeaponCategory ResolveWeaponCategory(IEnumerable inventory) + { + if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category)) + { + _lastWeaponCategory = category; + return category; + } + + return _lastWeaponCategory; + } + + private bool TryGetWieldedMissileCategory(IEnumerable 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 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 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 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 { } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MonsterMatchEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MonsterMatchEvaluator.cs new file mode 100644 index 0000000..edc4c3c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MonsterMatchEvaluator.cs @@ -0,0 +1,290 @@ +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthAi.Combat; + +/// +/// 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): || && == != < > <= >= # + - * / % +/// Grouping with ( ). +/// +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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs new file mode 100644 index 0000000..70d36eb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs @@ -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; + +/// +/// 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 Structure 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 "<PlayerName>'s <PetName>", +/// which is how we detect whether a pet is already up. +/// +/// Behaviour (per user spec): +/// * Summon only when mobs are near — at least PetMinMonsters scanned, +/// attackable monsters within CustomPetRange — 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 PetAutoRefill). +/// +/// Mirrors : busy-gated, chat-driven, timeout- +/// guarded, one in-flight action at a time. Entirely plugin-side; the only AC +/// actions issued are Host.UseObject (summon) and Host.UseObjectOn +/// (refill), both selection-free. +/// +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 _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) + { + // " 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 ────────────────────────────────────────────────────────────────── + + /// True once a successful summon has decremented the device's charges. + 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; + + /// Device remaining charges (Structure). -1 if unreadable. + private int ReadCharges(int deviceId) + { + if (!_host.HasGetObjectIntProperty) return -1; + return _host.TryGetObjectIntProperty(unchecked((uint)deviceId), + (uint)AcIntProperty.Structure, out int s) ? s : -1; + } + + /// At least PetMinMonsters attackable monsters within CustomPetRange. + 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; + } + + /// + /// A combat pet is up if a live creature named "<PlayerName>'s …" exists in + /// the cache — the server names summoned pets exactly that (Pet.Init). + /// + 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 ───────────────────────────────────────────────────────── + + /// + /// 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). + /// + private IEnumerable 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; + } + + /// True if the item's container chain roots at the player's pack (not a corpse). + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellData.txt b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellData.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6873ca371b9df38da60262fc761db616f634a4a GIT binary patch literal 912312 zcmd44S+iAD)~>s5JrU|N-D-7nGE*7&tqt&e!WBh;r=i`fyE*@RHyLfZ)^y1aUv-Ii5i)$DE%uvhGk1pn)|L=?c>*9L) z+i~Pa`5S*Y>$qPh-e1%AV$>UH)Nj-0#}_}R>wS9hHvKnVFWB(s>BYa(zkHs4v%TKa z^jc+{`l>PJ&FPr!m3l|KmA-2((~mA>e2j_T`yyZGi^=ufzPOwIp07ox@00EyU;L8( z{FMIoZ+~cgHD38SMm#kmwpVvbV||o<1F!qz)z^n_`XZ6ON#8f>57zimw#izDp6in_ zYANID?lj}IR~H%0t3T-HL9)9alKs6+dc1b=FkS7d^k=-BD$bRxBjr?8urWfhYyNll^6gRSr_*(qtbrmIIUh{FbD2<@i!tVIR zidzr*I9n@p@LNa*$MpLzQv7|KEF1Clar(E2$Gdq1zHTwKvJnz_KT1@~ z=z5Nug-5gCG0%bsa^U-uoVg&MA3I6Wm#$|oomp@nzpm#P;iKwhb(Cqw2Wz^Xv+=zg z!(XS@ndLAJK^};lqn_U8c=Y48?I1VT1mm@1-1Cj!S_;1VLCRpiB#(HLu4I<0F*b6m zypJ|fWDvIsd~;7Q%HZhuYYRY(x}UE5agqWe$|os?yh!#gbtk>)<76wSKi{Xn{VB%^ z#*Jqwdc03RpVulP>(LhwP46d(zfKVdWA&pl&OzdcTm7hdg|r&=Mz-L4i5R)`S{fTw z?kDMLU#I`RPoF=_Ht;G%LRQ|r9&Y7I5}p97Ep-&Ca9WQyf(j$N@J6<-n&ZpF!>`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PEM4Vi#|tsL*pH9aY>yB zVRn2(^W`QZPM7I^-ea3Z=W$y-;B&INjBXa6$MVmHS+plT@$I^9UA~X}xr1&No9Em0 z^3#fDsU~E9gzj^_s~K61`d_dO#~2(0-6fQ+jg0*ND#}@$uC0tB z!Wz!tlzlv4!{B* zeJrzR9JYf7-nnRkFV`gFa(Wa8##)+1;xhN~lvMiuQ_O`GFqrWc3?BLTy=?l3f;-nR zxlA5;^f^qks9Z*m{Pzs1;L|lpdCXQN_H`@kX>S&h$MA8#^`A=itks3|qqnhHT`T5*+)G{0?#%D%W8{PP^E(Le7_+M@x;sXGw?-h{&uIW#bmkxV+MM5+T?}{TM_xUP zXxF%*1AhM68rNmv$fq7LI4E2$j=X3Og@Xf$IT{)H%_ELr#*9upUaC^Ly<_gKoNI7% z*t_c1uDCTU##`PVMqd-T4fi3_)4?rs`PKvPU~muK>? _spellNames = new(); + private static bool _loaded = false; + + private static readonly Dictionary _builtinSpells = new Dictionary + { + { 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? 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(); + } + + /// + /// Returns true if the spell exists in the database. + /// TODO: Replace with real "is spell known" check from AC memory. + /// + public static bool IsSpellKnown(int spellId) + { + return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId); + } + + /// Builds a name→id reverse map for SpellManager initialisation. + public static Dictionary BuildNameToIdMap() + { + var map = new Dictionary(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; + } + + /// Looks up a spell ID by exact name (case-insensitive). + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs new file mode 100644 index 0000000..455355b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs @@ -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 _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 _knownSpellIds = new(); + private DateTime _lastKnownRefreshUtc = DateTime.MinValue; + private const double KnownRefreshThrottleMs = 3000; + + public Dictionary SpellDictionary { get; private set; } = + new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Map base spell names to their exact Level 7 Lore counterparts + private readonly Dictionary 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); + } + } + + /// + /// 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. + /// + public int GetHighestSpellTier(AcSkillType skill) + => ComputeTier(skill, + _settings.MinSkillLevelTier1, _settings.MinSkillLevelTier2, + _settings.MinSkillLevelTier3, _settings.MinSkillLevelTier4, + _settings.MinSkillLevelTier5, _settings.MinSkillLevelTier6, + _settings.MinSkillLevelTier7, _settings.MinSkillLevelTier8); + + /// + /// Same as 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. + /// + 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; + } + + /// + /// 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. + /// + public void MarkSpellUnresolvable(int spellId) + { + if (spellId > 0) _unresolvableSpellIds.Add(spellId); + } + + /// Persisted by BuffManager so the tier-7→6 drop is learned once + /// (first rebuff per char) then instant on every later session/RL. + public IReadOnlyCollection UnresolvableSpellIds => _unresolvableSpellIds; + + /// + /// 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 _knownSpellIds 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 + /// on the consuming path first to keep the + /// snapshot warm even when not buffing. + /// + public bool TryResolveSpellId(string exactName, out int spellId) + => TryGetId(exactName, out spellId); + + /// + /// Combat-facing resolver. Deterministic: name → id via the dictionary, + /// then REQUIRES membership in the authoritative warm spellbook snapshot. + /// Deliberately does NOT consult _unresolvableSpellIds (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). + /// + 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; + } + + /// + /// 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. + /// + public bool IsKnownSnapshotWarm => _knownSpellIds.Count > 0; + + /// + /// True if the authoritative main-thread spellbook snapshot contains this + /// id. Only meaningful when 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". + /// + public bool IsKnownSpellId(int id) => _knownSpellIds.Contains(id); + + /// + /// 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. + /// + 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 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs new file mode 100644 index 0000000..cc10f50 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs @@ -0,0 +1,62 @@ +using System; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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. +/// +public sealed class WeaponSwapGate +{ + private readonly object _lock = new(); + private long _lastSwapTickMs = long.MinValue / 4; + private string _lastSwapBy = ""; + + /// + /// 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. + /// + public int MinIntervalMs { get; set; } = 3000; + + /// + /// 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. + /// + public bool TryBeginSwap(string requestedBy) + { + long now = Environment.TickCount64; + lock (_lock) + { + if (now - _lastSwapTickMs < MinIntervalMs) + return false; + _lastSwapTickMs = now; + _lastSwapBy = requestedBy ?? ""; + return true; + } + } + + /// Milliseconds since the last successful swap (diagnostics). + public long MsSinceLastSwap + { + get { lock (_lock) { return Environment.TickCount64 - _lastSwapTickMs; } } + } + + /// Who last claimed a swap (diagnostics). + public string LastSwapBy { get { lock (_lock) { return _lastSwapBy; } } } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs new file mode 100644 index 0000000..0b2275f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -0,0 +1,1673 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Live object cache tracking AC world objects via engine events. +/// +/// Classification strategy: +/// - Creature : received OnUpdateHealth OR TryGetItemType returns TYPE_CREATURE flag +/// - Corpse : world object with a corpse-like name (e.g. "Foo's Corpse") +/// - Inventory : TryGetObjectPosition returns false (not placed in world = in a container) +/// OR item GUID (0xC0000000+) with no position +/// - Landscape : TryGetObjectPosition returns true + not a creature = static object +/// - Weapon type: TryGetItemType flags first; name-based heuristics as fallback +/// +/// THREADING: the mutating handlers (OnCreateObject/OnDeleteObject/OnUpdateHealth) and the +/// classify pump (Tick → TryClassify/ReclassifyUnknownDynamics) all run on the engine's +/// plugin pump thread — the engine queues AC's main-thread object events and dispatches them +/// (PluginManager.ProcessPendingActions) then runs TickAll, sequentially on that one thread. +/// HOWEVER the read enumerators (GetLandscape/GetLandscapeObjects/GetInventory/AllKnownObjects/ +/// GetContainedItems/GetDirectInventory) are ALSO pulled from the Avalonia panel poll thread +/// (~10 Hz) for the radar/dashboard snapshot. Enumerating a collection there while the pump +/// mutates it throws "Collection was modified"; escaping the snapshot's reverse-P/Invoke +/// boundary that fail-fasts the NativeAOT runtime (0xC0000602). So ALL collection access goes +/// through _gate: mutators lock their whole body, enumerators copy-under-lock then iterate the +/// copy outside the lock. The _host.* reads used here are non-blocking/cache-served off-thread, +/// so holding _gate across them cannot deadlock against AC's main thread. +/// +public class WorldObjectCache +{ + private readonly RynthCoreHost _host; + + // Serializes all collection access (see the THREADING note above). Single reentrant + // monitor — the indexer re-enters via EnsureInCache — and one lock means no lock-ordering + // deadlock is possible. Contended only between the pump thread and the ~10 Hz Avalonia poll. + private readonly object _gate = new(); + + private readonly Dictionary _byId = new(); + private readonly HashSet _creatures = new(); // received OnUpdateHealth or TYPE_CREATURE + private readonly HashSet _landscape = new(); // has physics position + private readonly HashSet _inventory = new(); // no physics position + private readonly Dictionary _healthRatios = new(); // last known health ratio per object (0-1) + + // OnCreateObject IDs pending classification + private readonly Queue _pending = new(); + private const int MaxClassifyPerTick = 30; + + // Retry tracking for 0x8000xxxx objects that have no weenie yet (e.g. spawning corpses) + private readonly Dictionary _classifyRetry = new(); + private const int MaxClassifyRetries = 8; + + // Slow-retry rescue. When the 8-tick fast-retry burst exhausts (all attempts + // within ~10 ms because Tick processes 30 pending entries per pass), the uid + // moves here instead of being abandoned. Every ReclassifyIntervalSec the + // entries are flushed back into _pending so the engine has fresh chances to + // populate name+position. Successful classification evicts the uid at the + // top of TryClassify; a fresh give-up re-adds it. OnDeleteObject cleans up. + // Roots out the "respawned monster invisible until clicked" bug where AC's + // weenie data lagged behind OnCreateObject by more than 10 ms. + private readonly HashSet _slowRetry = new(); + + // Objects deleted while still pending classification — skip to avoid stale-pointer AV + private readonly HashSet _deletedWhilePending = new(); + + // Periodic reclassification — rescues Unknown landscape objects that become recognisable later + private DateTime _lastReclassifyTime = DateTime.MinValue; + private const double ReclassifyIntervalSec = 2.0; + + // Diagnostic state for the "bot ignores mobs until clicked" investigation. + // Records the latest reason each Unknown landscape uid keeps failing to be promoted + // to creature so we can correlate skip ↔ HEALTHADD-RESCUE ↔ promotion in the log. + // State-change suppressed per uid; cleared on promotion / health-add rescue. + private readonly Dictionary _reclassifySkipState = new(); + private int _reclassifyDiagCount; + private int _reclassifyDiagSummaryCount; + private const int MaxReclassifyDiagLines = 500; + private const int MaxReclassifyDiagSummaries = 60; + + // Diagnostic — track every uid OnCreateObject ever saw. Lets HEALTHADD-RESCUE + // and INDEXER-RESCUE log lines flag the case where a mob enters _creatures via + // a path other than OnCreateObject → TryClassify (i.e. the engine's CreateObject + // hook never fired for this respawn — the suspected bug). No eviction: a delete + + // recreate of the same id MUST keep showing seenCreate=1 to be diagnostic-correct. + private readonly HashSet _seenCreateObject = new(); + private int _healthAddLogCount; + private int _indexerRescueLogCount; + private int _classifyGiveupLogCount; + private int _deleteWhilePendingSkipLogCount; + private int _deleteBeforeClassifyLogCount; + private const int MaxHealthAddDiagLines = 200; + private const int MaxIndexerRescueDiagLines = 200; + private const int MaxClassifyGiveupLogLines = 200; + private const int MaxDeleteWhilePendingSkipLogLines = 200; + private const int MaxDeleteBeforeClassifyLogLines = 200; + + // ItemType flag constants (AC ITEM_TYPE bitmask) + private const uint ItemTypeMeleeWeapon = 0x00000001; + private const uint ItemTypeArmor = 0x00000002; + private const uint ItemTypeClothing = 0x00000004; + private const uint ItemTypeJewelry = 0x00000008; + private const uint ItemTypeCreature = 0x00000010; + private const uint ItemTypeFood = 0x00000020; + private const uint ItemTypeMoney = 0x00000040; + private const uint ItemTypeMisc = 0x00000080; + private const uint ItemTypeMissileWeapon = 0x00000100; + private const uint ItemTypeContainer = 0x00000200; + private const uint ItemTypeGem = 0x00000800; + private const uint ItemTypeSpellComponents = 0x00001000; + private const uint ItemTypeWritable = 0x00002000; + private const uint ItemTypeKey = 0x00004000; + private const uint ItemTypeCaster = 0x00008000; + private const uint ItemTypePortal = 0x00010000; + private const uint ItemTypePromissoryNote = 0x00040000; + private const uint ItemTypeManaStone = 0x00080000; + private const uint ItemTypeService = 0x00100000; + private const uint ItemTypeCraftCookingBase = 0x00400000; + private const uint ItemTypeCraftAlchemyBase = 0x00800000; + private const uint ItemTypeCraftFletchingBase = 0x02000000; + private const uint ItemTypeCraftAlchemyIntermediate = 0x04000000; + private const uint ItemTypeCraftFletchingIntermediate = 0x08000000; + private const uint ItemTypeLifeStone = 0x10000000; + private const uint ItemTypeTinkeringTool = 0x20000000; + private const uint ItemTypeTinkeringMaterial = 0x40000000; + + private uint _playerId; // set at login; health updates for self are ignored + private DateTime _loginTime = DateTime.MinValue; // when SetPlayerId was called + + public WorldObjectCache(RynthCoreHost host) + { + _host = host; + } + + public void SetPlayerId(uint playerId) + { + lock (_gate) + { + _playerId = playerId; + _loginTime = DateTime.Now; + _deletedWhilePending.Clear(); + // Remove self if mistakenly added as creature before login completed + if (playerId == 0) return; + int sid = (int)playerId; + _creatures.Remove(sid); + _landscape.Remove(sid); + _byId.Remove(sid); + } + } + + // ── Event handlers ──────────────────────────────────────────────────── + + public void OnCreateObject(uint id) + { + // AC recycles dynamic GUIDs after delete. A fresh create on a previously-deleted + // id means the new object should classify normally — drop any stale delete mark + // before re-queueing so TryClassify doesn't skip it. + lock (_gate) + { + _deletedWhilePending.Remove(id); + _pending.Enqueue(id); + _seenCreateObject.Add(id); // diagnostic: record that the engine fired CreateObject for this uid + } + } + + public void OnDeleteObject(uint id) + { + lock (_gate) + { + int sid = (int)id; + bool wasInventory = _inventory.Remove(sid); + bool wasClassified = _byId.Remove(sid); + _creatures.Remove(sid); + _landscape.Remove(sid); + _healthRatios.Remove(sid); + _classifyRetry.Remove(id); + _slowRetry.Remove(id); + _reclassifySkipState.Remove(id); + // Only mark as "deleted while pending" when the object was never classified — + // i.e. it might still be sitting in _pending and TryClassify must skip it to + // avoid touching freed AC memory. For already-classified objects the cache + // entries above are gone cleanly and no protection is needed; marking them + // would leak forever (TryClassify is never called for them again). + if (!wasClassified) + { + _deletedWhilePending.Add(id); + // DIAG: OnDeleteObject fired BEFORE TryClassify ever processed this uid. + // Sets the delete-while-pending mark which TryClassify will use to skip + // the object. If a respawn never re-fires OnCreateObject (which would + // clear this mark), the plugin loses awareness of the uid until the + // indexer's lazy lookup is forced (typically by a user click). + if (id >= 0x80000000u && _deleteBeforeClassifyLogCount < MaxDeleteBeforeClassifyLogLines) + { + _deleteBeforeClassifyLogCount++; + bool seenCreate = _seenCreateObject.Contains(id); + _host.Log($"[ReclassifyDiag] 0x{id:X8} DELETE-BEFORE-CLASSIFY seenCreate={(seenCreate ? 1 : 0)}"); + } + } + if (wasInventory) + _inventoryDirty = true; + } + } + + /// Returns the last known health ratio (0–1) for , or -1 if no update has been received. + public float GetHealthRatio(int id) + { + lock (_gate) + return _healthRatios.TryGetValue(id, out float v) ? v : -1f; + } + + public void OnUpdateHealth(uint id, float healthRatio) + { + lock (_gate) + { + if (_playerId != 0 && id == _playerId) + return; // ignore self + + int sid = (int)id; + _healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f); + + if (!_creatures.Add(sid)) + return; // creature already known — ratio updated above, nothing more to do + + // DIAG: unconditional log for the FIRST time a dynamic uid lands in _creatures via + // OnUpdateHealth. seenCreate=0 is the smoking gun for the suspected bug — the + // engine's CreateObject hook never fired for this respawn, yet the server is + // sending vitals for it, meaning the mob exists for AC but was invisible to the + // plugin until something poked it (typically a user click → QueryHealth response). + if (id >= 0x80000000u && _healthAddLogCount < MaxHealthAddDiagLines) + { + _healthAddLogCount++; + bool wasSkipped = _reclassifySkipState.Remove(id); + bool seenCreate = _seenCreateObject.Contains(id); + bool inLandscape = _landscape.Contains(sid); + bool inById = _byId.ContainsKey(sid); + _host.Log($"[ReclassifyDiag] 0x{id:X8} HEALTHADD-RESCUE ratio={healthRatio:0.00} seenCreate={(seenCreate ? 1 : 0)} inLandscape={(inLandscape ? 1 : 0)} inById={(inById ? 1 : 0)} wasSkipped={(wasSkipped ? 1 : 0)}"); + } + else if (_reclassifySkipState.ContainsKey(id)) + { + // Past the log cap — still clean up skip state so the dict doesn't grow unbounded. + _reclassifySkipState.Remove(id); + } + + // DIAG: a creature first learned via server health update (the + // "aggressive mob self-rescues" path) — NOT via TryClassify. Lets us + // correlate a manually-selected mob's id to how/when it entered + // _creatures vs. why classification missed it earlier. + TraceClassify(id, true, true, false, 0u, $"healthAdd->creature hr={healthRatio:0.00}"); + + // If the object was already classified as a Corpse, don't promote it back to Monster. + // AC fires health=0 events during the creature→corpse transition; if TryClassify already + // reclassified it and removed it from _creatures, the Add above would re-admit it incorrectly. + if (_byId.TryGetValue(sid, out var existing)) + { + if (existing.ObjectClass == AcObjectClass.Corpse) + { + _creatures.Remove(sid); + return; + } + if (existing.ObjectClass != AcObjectClass.Monster) + _byId[sid] = Make(sid, existing.Name, AcObjectClass.Monster); + } + else + { + // Not yet classified — add with empty name; Tick() will fill in name + _byId[sid] = Make(sid, "", AcObjectClass.Monster); + } + + _landscape.Add(sid); + _inventory.Remove(sid); + } + } + + // ── Per-frame processing ────────────────────────────────────────────── + + private int _tickDiagCount; + private bool _inventoryDirty = true; // true at start so first scan runs after hooks ready + private bool _initialScanDone; + private DateTime _lastScanAttempt = DateTime.MinValue; + private const int ScanCooldownMs = 1000; + private int _initialScanRetries; + private const int MaxInitialScanRetries = 15; + private readonly List _directInventory = new(); + private readonly HashSet _directInventoryIds = new(); + private readonly Dictionary _directInventoryIndex = new(); + private DateTime _lastDirectInventoryScan = DateTime.MinValue; + private const int DirectInventoryCooldownMs = 1000; + private const int DirectInventoryForceRefreshMinMs = 250; + + /// Mark inventory as changed — triggers a full container scan on next Tick. + public void MarkInventoryDirty() => _inventoryDirty = true; + + /// Call from OnTick to classify queued objects. + public void Tick() + { + int pending0; + lock (_gate) pending0 = _pending.Count; + + int processed = 0; + while (processed < MaxClassifyPerTick) + { + uint uid; + lock (_gate) + { + if (_pending.Count == 0) break; + uid = _pending.Dequeue(); + } + TryClassify(uid); // re-enters _gate for its own body + processed++; + } + if (processed > 0 && _tickDiagCount < 3) + { + _tickDiagCount++; + int total, landscape, creatures; + lock (_gate) { total = _byId.Count; landscape = _landscape.Count; creatures = _creatures.Count; } + _host.Log($"[RynthAi] Cache.Tick classified {processed} from {pending0} pending, total now {total}, landscape={landscape}, creatures={creatures}"); + } + + // Periodically re-check Unknown landscape objects — dynamic creatures whose weenie + // wasn't ready at classify time will be promoted to _creatures here. + // Same cadence also re-queues uids parked in _slowRetry (their fast-retry burst + // exhausted in <10 ms before AC could populate their weenie), giving them a + // fresh 8-tick attempt each pass. + if ((DateTime.Now - _lastReclassifyTime).TotalSeconds >= ReclassifyIntervalSec) + { + _lastReclassifyTime = DateTime.Now; + FlushSlowRetry(); + ReclassifyUnknownDynamics(); + } + + // Full container scan disabled — causes delayed crash when 160+ items in cache + // trigger bulk property queries. MissileCraftingManager does its own lightweight scan. + if (false && _inventoryDirty && _playerId != 0 && _host.HasGetContainerContents + && (DateTime.Now - _loginTime).TotalMilliseconds >= 5000 + && (DateTime.Now - _lastScanAttempt).TotalMilliseconds >= ScanCooldownMs) + { + _lastScanAttempt = DateTime.Now; + int found = ScanFullInventory(); + // Only clear dirty once scan actually discovers items (hooks ready) + if (found > 0 || _initialScanDone) + _inventoryDirty = false; + if (!_initialScanDone) + { + _initialScanRetries++; + if (found > 0) + { + _initialScanDone = true; + _host.Log($"[RynthAi] Inventory scan: discovered {found} item(s), inventory now {_inventory.Count}"); + } + else if (_initialScanRetries >= MaxInitialScanRetries) + { + _initialScanDone = true; + _inventoryDirty = false; + _host.Log($"[RynthAi] Inventory scan: gave up after {_initialScanRetries} retries (topCount was 0)"); + } + } + } + } + + // Read-only classify trace (no AC probes added — reuses the caller's + // already-computed hasName/hasPos/TryGetItemType). Bounded so one login is + // conclusive without flooding. Dynamic (0x8000+) only — that's the + // creature/NPC/equipped range the login-mob bug lives in. + private int _classifyTrace; + // Bumped from 500 while the missing-respawn investigation needs coverage of late + // OnCreateObject events (login-burst alone blows the 500 cap in <2s, leaving the + // session blind to anything that spawned later). + private void TraceClassify(uint uid, bool hasName, bool hasPos, bool gotType, uint flags, string note) + { + if (_classifyTrace >= 5000 || uid < 0x80000000u) return; + _classifyTrace++; + int atk = -1; + try { if (_host.HasObjectIsAttackable) atk = _host.ObjectIsAttackable(uid) ? 1 : 0; } + catch { atk = -2; } + _host.Log($"[ClassifyTrace] 0x{uid:X8} name={(hasName ? 1 : 0)} pos={(hasPos ? 1 : 0)} gotType={(gotType ? 1 : 0)} flags=0x{flags:X8} creature={((flags & ItemTypeCreature) != 0 ? 1 : 0)} atk={atk} {note}"); + } + + private void TryClassify(uint uid) + { + lock (_gate) + { + // Slow-retry eviction: any uid TryClassify gets to process is by definition no + // longer "abandoned" for this pass. If we give up again below, the give-up + // branch re-adds; if we succeed or hit a clean early-return, the set is now + // correct without further bookkeeping. + _slowRetry.Remove(uid); + + // Skip objects that were deleted after being enqueued — accessing their AC memory + // would touch stale pointers and cause an AccessViolationException. + if (_deletedWhilePending.Contains(uid)) + { + _deletedWhilePending.Remove(uid); + // DIAG: TryClassify abandoned this uid because OnDeleteObject marked it + // delete-while-pending. If the mob is actually still alive (server kept + // the entity, the delete fired spuriously, or the create-delete-recreate + // sequence dropped one create), it sits invisible to the plugin until + // an indexer access rescues it. Pairs with DELETE-BEFORE-CLASSIFY. + if (uid >= 0x80000000u && _deleteWhilePendingSkipLogCount < MaxDeleteWhilePendingSkipLogLines) + { + _deleteWhilePendingSkipLogCount++; + _host.Log($"[ReclassifyDiag] 0x{uid:X8} DELETE-WHILE-PENDING-SKIP"); + } + return; + } + + // Never classify the player's own object — after portal/zone changes + // OnCreateObject fires for the player and would re-add them to _creatures. + if (_playerId != 0 && uid == _playerId) return; + + int id = (int)uid; + + // Already known as creature — just fill in name if missing + if (_creatures.Contains(id)) + { + if (_byId.TryGetValue(id, out var c) && c.Name.Length == 0 + && _host.TryGetObjectName(uid, out string cn) && cn.Length > 0) + _byId[id] = Make(id, cn, c.ObjectClass); + return; + } + + bool hasName = _host.TryGetObjectName(uid, out string name); + bool hasPos = _host.TryGetObjectPosition(uid, out _, out _, out _, out _); + bool looksLikeCorpse = hasPos && IsCorpseName(name); + + // Object not accessible yet — retry for any dynamic object (weenie may not be ready) + if (!hasName && !hasPos) + { + TraceClassify(uid, hasName, hasPos, false, 0u, "noNamePos"); + if (uid >= 0x80000000u) + { + int retries = _classifyRetry.TryGetValue(uid, out int r) ? r : 0; + if (retries < MaxClassifyRetries) + { + _classifyRetry[uid] = retries + 1; + _pending.Enqueue(uid); + } + else + { + // Fast-retry burst exhausted (8 ticks ≈ 10 ms because Tick drains + // 30 pending per pass). Hand off to slow-retry: reset the fast + // counter so the next attempt gets a fresh 8 ticks, and park the + // uid in _slowRetry. FlushSlowRetry re-enqueues it every + // ReclassifyIntervalSec until the engine populates name/position. + _classifyRetry.Remove(uid); + _slowRetry.Add(uid); + + if (_classifyGiveupLogCount < MaxClassifyGiveupLogLines) + { + _classifyGiveupLogCount++; + _host.Log($"[ReclassifyDiag] 0x{uid:X8} CLASSIFY-GIVEUP retries={retries} (name+pos unreadable across {MaxClassifyRetries} ticks; parked in slow-retry)"); + } + } + } + return; + } + + // AC GUID ranges: + // 0xC0000000–0xFFFFFFFF = pack/ground items (dynamic items) + // 0x80000000–0xBFFFFFFF = dynamic objects: creatures, NPCs, AND equipped items + // 0x50000000–0x5FFFFFFF = players (filtered by SetPlayerId) + // below = static world objects (portals, lifestones, structures) + bool isPackItemGuid = uid >= 0xC0000000u; + + AcObjectClass cls; + if (isPackItemGuid || !hasPos) + { + if (looksLikeCorpse) + { + cls = AcObjectClass.Corpse; + } + // Could be pack item, equipped item on 0x8000 range, or spawning dynamic object + // Check item type flags first + else if (_host.TryGetItemType(uid, out uint typeFlags)) + { + if ((typeFlags & ItemTypeCreature) != 0) + { + // It's a creature with no position yet. + // Add to _creatures so future health update or retry classifies it + TraceClassify(uid, hasName, hasPos, true, typeFlags, "nopos-creature"); + _creatures.Add(id); + _landscape.Add(id); + _byId[id] = Make(id, name, AcObjectClass.Monster); + return; + } + + TraceClassify(uid, hasName, hasPos, true, typeFlags, "nopos-item"); + cls = ClassifyByItemType(typeFlags); + } + else + { + // No weenie/item-type accessible yet — retry for a few ticks + int retries = _classifyRetry.TryGetValue(uid, out int r) ? r : 0; + TraceClassify(uid, hasName, hasPos, false, 0u, retries < MaxClassifyRetries ? $"nopos-retry r={retries}" : "nopos-giveup"); + if (retries < MaxClassifyRetries) + { + _classifyRetry[uid] = retries + 1; + _pending.Enqueue(uid); // re-queue + return; + } + // Gave up retrying — fall through to name heuristics + _classifyRetry.Remove(uid); + cls = ClassifyInventoryItem(name); + } + + if (cls == AcObjectClass.Corpse) + { + _creatures.Remove(id); + _inventory.Remove(id); + _landscape.Add(id); + } + else + { + _inventory.Add(id); + _landscape.Remove(id); + } + } + else + { + if (looksLikeCorpse) + { + _classifyRetry.Remove(uid); + _creatures.Remove(id); + _inventory.Remove(id); + _landscape.Add(id); + _byId[id] = Make(id, name, AcObjectClass.Corpse); + return; + } + + // Has a position — check if it's actually a creature type (equipped items have 0x8000 GUIDs with positions) + bool gotType = _host.TryGetItemType(uid, out uint typeFlags); + TraceClassify(uid, hasName, hasPos, gotType, gotType ? typeFlags : 0u, "pos"); + if (gotType) + { + if ((typeFlags & ItemTypeCreature) != 0) + { + _creatures.Add(id); + _landscape.Add(id); + _byId[id] = Make(id, name, AcObjectClass.Monster); + return; + } + + // Non-creature with a position — could be equipped item on 0x8000 range + // or static world object; classify by type flags + if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0) + { + // Item with a world position = equipped or ground-dropped + cls = ClassifyByItemType(typeFlags); + _inventory.Add(id); + _landscape.Remove(id); + _byId[id] = Make(id, name, cls); + return; + } + } + else if (uid >= 0x80000000u) + { + // TryGetItemType failed for a dynamic object with position — weenie may not be ready. + // Re-queue for retry so creatures aren't permanently misclassified as Unknown landscape. + int retries = _classifyRetry.TryGetValue(uid, out int r) ? r : 0; + if (retries < MaxClassifyRetries) + { + _classifyRetry[uid] = retries + 1; + _pending.Enqueue(uid); + return; + } + _classifyRetry.Remove(uid); + } + + // Immediate creature rescue. The qualities/appraisal ItemType that + // TryGetItemType resolves lags ~30s post-login (reports flags=0), + // so a login mob would sit here as Unknown and never be scanned — + // the "bot ignores mobs after login" bug. AC's native combat check + // (ClientCombatSystem::ObjectIsAttackable) is available the instant + // the weenie object exists (it's how the game shows the health bar + // immediately) and does NOT depend on qualities/appraisal. A + // positioned dynamic (0x8000) object the game itself says is + // attackable IS a creature; NPCs / equipped gear are not attackable + // so they are not mis-promoted. ItemType refines it later if needed. + if (uid >= 0x80000000u + && _host.HasObjectIsAttackable + && _host.ObjectIsAttackable(uid)) + { + _classifyRetry.Remove(uid); + _inventory.Remove(id); + _creatures.Add(id); + _landscape.Add(id); + _byId[id] = Make(id, name, AcObjectClass.Monster); + TraceClassify(uid, hasName, hasPos, gotType, gotType ? typeFlags : 0u, "attackable->creature"); + return; + } + + cls = AcObjectClass.Unknown; // landscape non-creature (static object, portal, etc.) + _landscape.Add(id); + MaybeRegisterHazard(uid, name); // lava/acid hotspots arrive here as Unknown landscape + } + + _classifyRetry.Remove(uid); + _byId[id] = Make(id, name, cls); + } + } + + /// + /// Re-enqueue every uid that's currently parked in . Pairs + /// with the give-up branch of : when an OnCreateObject-then- + /// fast-retry burst exhausts in <10 ms before AC populates the weenie, the uid + /// lands here. The 2 s flush hands it back to so TryClassify + /// gets another 8-tick window. Successful classification evicts the uid at the top + /// of TryClassify; persistent failure re-adds it for the next cycle. + /// + private void FlushSlowRetry() + { + lock (_gate) + { + if (_slowRetry.Count == 0) return; + foreach (uint uid in _slowRetry) + _pending.Enqueue(uid); + } + } + + /// + /// Scan landscape objects classified as Unknown with dynamic GUIDs and try to promote + /// any that are now recognised as TYPE_CREATURE. Runs every ~2 seconds from Tick(). + /// This rescues creatures whose weenie data wasn't available when they were first classified. + /// + private void ReclassifyUnknownDynamics() + { + lock (_gate) + { + List? toPromote = null; + List? toCorpse = null; + foreach (int id in _landscape) + { + uint uid = unchecked((uint)id); + if (uid < 0x80000000u) continue; // static objects never become creatures/corpses + if (!_byId.TryGetValue(id, out var wo)) continue; + if (wo.ObjectClass == AcObjectClass.Corpse) continue; // already correct + + // Corpse rescue: a dead creature whose corpse name/position wasn't + // readable at OnCreateObject gets bucketed as Monster (or Unknown). + // The loot finder (TryFindNearestCorpse) matches ObjectClass==Corpse, + // and this is the ONLY path that promotes a non-Unknown object to + // Corpse — without it those corpses are permanently invisible to + // looting (corpse exists with a valid name, but classed as Monster). + // Bounded to Monster/Unknown so we don't name-query every ground + // item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X") + // so a live mob cannot be misread as a corpse. + if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown) + && _host.TryGetObjectName(uid, out string maybeCorpse) + && IsCorpseName(maybeCorpse)) + { + toCorpse ??= new List(); + toCorpse.Add(id); + continue; + } + + if (_creatures.Contains(id)) continue; + if (wo.ObjectClass != AcObjectClass.Unknown) continue; + + // Promote if EITHER the (laggy) qualities ItemType now reports + // creature, OR AC's native combat check says it's attackable (the + // immediate signal that doesn't wait on qualities/appraisal). This + // second path is what rescues a login mob within 2s if it slipped + // to Unknown before its weenie/combat-state was readable. + bool isCreature = _host.TryGetItemType(uid, out uint typeFlags) + && (typeFlags & ItemTypeCreature) != 0; + if (!isCreature + && _host.HasObjectIsAttackable + && _host.ObjectIsAttackable(uid)) + isCreature = true; + if (!isCreature) + { + DiagLogReclassifySkip(uid, wo.Name); + continue; + } + + toPromote ??= new List(); + toPromote.Add(id); + } + + if (toCorpse != null) + { + foreach (int id in toCorpse) + { + uint uid = unchecked((uint)id); + _host.TryGetObjectName(uid, out string name); + _creatures.Remove(id); + _inventory.Remove(id); + _byId[id] = Make(id, name ?? string.Empty, AcObjectClass.Corpse); + } + _host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse"); + } + + // DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted + // this pass. Confirms ReclassifyUnknownDynamics is running and engine signals + // keep failing for the stuck uids (vs. them never reaching _landscape at all). + if (toPromote == null + && _reclassifySkipState.Count > 0 + && _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries) + { + _reclassifyDiagSummaryCount++; + _host.Log($"[ReclassifyDiag] pass: {_reclassifySkipState.Count} stuck Unknown landscape candidate(s), 0 promoted"); + } + + if (toPromote == null) return; + + foreach (int id in toPromote) + { + uint uid = unchecked((uint)id); + _host.TryGetObjectName(uid, out string name); + _creatures.Add(id); + _byId[id] = Make(id, name ?? string.Empty, AcObjectClass.Monster); + _reclassifySkipState.Remove(uid); // diagnostic state cleared on success + } + + _host.Log($"[RynthAi] ReclassifyUnknownDynamics: promoted {toPromote.Count} object(s) to Creature"); + } + } + + // Diagnostic helper for ReclassifyUnknownDynamics. Logs the live engine signals + // (name, position, item-type flags, attackable bit) for each Unknown landscape + // candidate the rescue pass keeps rejecting. Bounded + state-change suppressed so + // a stuck mob produces one log line, and only re-logs if its engine state changes. + private void DiagLogReclassifySkip(uint uid, string name) + { + if (_reclassifyDiagCount >= MaxReclassifyDiagLines) return; + + bool gotType = _host.TryGetItemType(uid, out uint flags); + bool hasAtk = _host.HasObjectIsAttackable; + int atk = -1; + if (hasAtk) + { + try { atk = _host.ObjectIsAttackable(uid) ? 1 : 0; } + catch { atk = -2; } + } + bool hasPos = _host.TryGetObjectPosition(uid, out _, out _, out _, out _); + string state = $"name='{name}' hasPos={(hasPos ? 1 : 0)} gotType={(gotType ? 1 : 0)} flags=0x{flags:X8} hasAtk={(hasAtk ? 1 : 0)} atk={atk}"; + if (_reclassifySkipState.TryGetValue(uid, out string? prev) && prev == state) + return; // state unchanged — suppress duplicate + _reclassifySkipState[uid] = state; + _reclassifyDiagCount++; + _host.Log($"[ReclassifyDiag] 0x{uid:X8} skip: {state}"); + } + + // ── WorldFilter API ─────────────────────────────────────────────────── + + public WorldObject? this[int id] + { + get + { + lock (_gate) + { + if (_byId.TryGetValue(id, out var wo)) + { + // Patch empty name on access + if (wo.Name.Length == 0 && _host.TryGetObjectName(unchecked((uint)id), out string n) && n.Length > 0) + { + wo = Make(id, n, wo.ObjectClass); + _byId[id] = wo; + } + return wo; + } + + // Lazy lookup for objects not yet in queue (e.g. user-configured weapon IDs) + uint uid = unchecked((uint)id); + bool hasName = _host.TryGetObjectName(uid, out string name); + bool hasPos = _host.TryGetObjectPosition(uid, out _, out _, out _, out _); + if (!hasName && !hasPos) + return null; + + bool isPackItemGuid = uid >= 0xC0000000u; + bool looksLikeCorpse = hasPos && IsCorpseName(name); + AcObjectClass cls; + if (looksLikeCorpse) + { + cls = AcObjectClass.Corpse; + _creatures.Remove(id); + } + else if (_creatures.Contains(id)) + cls = AcObjectClass.Monster; + else if (_host.TryGetItemType(uid, out uint typeFlags)) + { + if ((typeFlags & ItemTypeCreature) != 0) + { + cls = AcObjectClass.Monster; + _creatures.Add(id); + // DIAG: indexer's lazy-lookup side-effect just added a fresh uid to + // _creatures. This is the "click → OnSelectedTargetChange → indexer + // queries qualities → TYPE_CREATURE finally readable → bot sees the + // mob" path. seenCreate=0 here is the strongest signal that the + // engine's CreateObject hook missed this respawn entirely. + if (uid >= 0x80000000u && _indexerRescueLogCount < MaxIndexerRescueDiagLines) + { + _indexerRescueLogCount++; + bool seenCreate = _seenCreateObject.Contains(uid); + _host.Log($"[ReclassifyDiag] 0x{uid:X8} INDEXER-RESCUE name='{name}' flags=0x{typeFlags:X8} seenCreate={(seenCreate ? 1 : 0)}"); + } + } + else + cls = ClassifyByItemType(typeFlags); + } + else if (isPackItemGuid || !hasPos) + cls = ClassifyInventoryItem(name); + else + cls = AcObjectClass.Unknown; + + var obj = Make(id, name, cls); + _byId[id] = obj; + if (cls == AcObjectClass.Corpse || (!isPackItemGuid && hasPos)) + { + _inventory.Remove(id); + _landscape.Add(id); + if (cls == AcObjectClass.Unknown) + MaybeRegisterHazard(uid, name); + } + else + { + _inventory.Add(id); + } + return obj; + } + } + } + + /// + /// Read an STypeInt property from an object via CBaseQualities::InqInt. + /// Returns defaultValue if the API is unavailable or the property is not set. + /// + public int GetIntProperty(int id, uint stype, int defaultValue) + { + if (!_host.HasGetObjectIntProperty) return defaultValue; + uint uid = unchecked((uint)id); + return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue; + } + + /// + /// Read an STypeFloat property from an object via CBaseQualities::InqFloat. + /// Returns defaultValue if the API is unavailable or the property is not set. + /// + public double GetDoubleProperty(int id, uint stype, double defaultValue) + { + if (!_host.HasGetObjectDoubleProperty) return defaultValue; + uint uid = unchecked((uint)id); + return _host.TryGetObjectDoubleProperty(uid, stype, out double v) ? v : defaultValue; + } + + /// + /// Read an STypeString property from an object via CBaseQualities::InqString. + /// Returns defaultValue if the API is unavailable or the property is not set. + /// + public string GetStringProperty(int id, uint stype, string defaultValue) + { + if (!_host.HasGetObjectStringProperty) return defaultValue; + uint uid = unchecked((uint)id); + return _host.TryGetObjectStringProperty(uid, stype, out string? v) && !string.IsNullOrEmpty(v) + ? v + : defaultValue; + } + + public int GetContainerId(int id) + { + if (!TryGetOwnership(id, out int containerId, out _, out _)) + return 0; + + return containerId; + } + + public int GetWielderId(int id) + { + if (!TryGetOwnership(id, out _, out int wielderId, out _)) + return 0; + + return wielderId; + } + + public int GetWieldedLocation(int id) + { + if (!TryGetOwnership(id, out _, out _, out int location)) + return 0; + + return location; + } + + /// + /// Compute 3D distance between two objects. + /// Converts AC landblock-local coordinates to global space so cross-block distances work. + /// + public double Distance(int id1, int id2) + { + uint uid1 = unchecked((uint)id1); + uint uid2 = unchecked((uint)id2); + + if (!_host.TryGetObjectPosition(uid1, out uint cell1, out float x1, out float y1, out float z1)) + return double.MaxValue; + if (!_host.TryGetObjectPosition(uid2, out uint cell2, out float x2, out float y2, out float z2)) + return double.MaxValue; + + // Convert landblock-local to global: each landblock block is 192 meters + float gx1 = ((cell1 >> 24) & 0xFF) * 192f + x1; + float gy1 = ((cell1 >> 16) & 0xFF) * 192f + y1; + float gx2 = ((cell2 >> 24) & 0xFF) * 192f + x2; + float gy2 = ((cell2 >> 16) & 0xFF) * 192f + y2; + + float dx = gx1 - gx2; + float dy = gy1 - gy2; + float dz = z1 - z2; + return Math.Sqrt(dx * dx + dy * dy + dz * dz); + } + + /// Enumerate objects in player's inventory (no physics position). + public IEnumerable GetInventory() + { + // Copy-under-lock then iterate the copy outside the lock (the Avalonia radar/ + // dashboard poll thread enumerates this while the pump thread mutates _inventory). + lock (_gate) + { + var snapshot = new List(_inventory.Count); + foreach (int id in _inventory) + if (_byId.TryGetValue(id, out var wo)) + snapshot.Add(wo); + return snapshot; + } + } + + /// + /// Every object the cache currently knows about, indexed by id. Useful for + /// wielded-item lookups when the `_inventory` set hasn't picked them up + /// yet (the cache classifies items asynchronously and the wielderInfo probe + /// can race with consumers like HasWieldedAmmo). + /// + public IEnumerable AllKnownObjects() + { + lock (_gate) + return new List(_byId.Values); + } + + /// + /// Lightweight live inventory snapshot built from GetContainerContents. + /// This bypasses the crash-prone full cache scan and is the source of truth + /// for crafting and ammo diagnostics. + /// + public IReadOnlyList GetDirectInventory(bool forceRefresh = false) + { + // Whole-body lock: the rescan clears+rebuilds _directInventory*, and callers may + // arrive from the pump thread AND Avalonia button handlers. Each exit returns a + // snapshot copy so the caller never iterates the live list a later call will clear. + lock (_gate) + { + DateTime now = DateTime.Now; + + if (!_host.HasGetContainerContents) + { + if (forceRefresh || _directInventory.Count == 0) + { + _directInventory.Clear(); + foreach (var item in GetInventory()) + _directInventory.Add(item); + } + return _directInventory.ToList(); + } + + double scanAgeMs = (now - _lastDirectInventoryScan).TotalMilliseconds; + if (_directInventory.Count > 0) + { + if (!forceRefresh && scanAgeMs < DirectInventoryCooldownMs) + return _directInventory.ToList(); + + if (forceRefresh && scanAgeMs < DirectInventoryForceRefreshMinMs) + return _directInventory.ToList(); + } + + _lastDirectInventoryScan = now; + _directInventory.Clear(); + _directInventoryIds.Clear(); + _directInventoryIndex.Clear(); + + uint playerId = _host.GetPlayerId(); + if (playerId == 0) + return _directInventory.ToList(); + + _host.TryGetObjectPosition(playerId, out _, out _, out _, out _); + + var pendingContainers = new Queue(); + var seenContainers = new HashSet { playerId }; + pendingContainers.Enqueue(playerId); + + while (pendingContainers.Count > 0) + { + uint containerId = pendingContainers.Dequeue(); + uint[] buf = new uint[512]; + + int count; + try + { + count = _host.GetContainerContents(containerId, buf); + } + catch + { + continue; + } + + for (int i = 0; i < count; i++) + { + uint itemId = buf[i]; + // Pass the container being enumerated + the item's index as the authoritative + // parent/slot for the remote inventory view (stashed onto the WorldObject). + if (!TryAddDirectInventoryItem(itemId, playerId, containerId, i, out bool isContainer)) + continue; + + if (isContainer && seenContainers.Add(itemId)) + pendingContainers.Enqueue(itemId); + } + } + + // GetContainerContents does not include worn/wielded gear, so merge only + // the player's own cache-known equipped objects into the same live snapshot. + foreach (var cachedItem in GetInventory()) + { + if (IsPlayerWielded(cachedItem)) + UpsertDirectInventoryItem(cachedItem); + } + + return _directInventory.ToList(); + } + } + + // ── Shared AV-safe pack finder (P2a) ────────────────────────────────── + // ONE finder replacing the 4 divergent clones (InventoryManager.FindOpenPack, + // BuffManager.FindOpenPackForDequip, MagToolsCommands.FindOpenPackForDequip, + // ExpressionEngine.FindCastOpenPack). A FULL target pack CRASHES the client via + // the native PutItemInContainer path, so we ONLY ever return a sub-pack whose + // resolved free capacity (ItemsCapacity>0) is >= requireFree, picking the MOST- + // free so a single mis-count can't tip a near-full pack over. The P0 engine gate + // (ClientHelperHooks.IsFullOwnedContainer) is the hard truth; requireFree is + // purely churn tuning. + // + // includeMainPack=false -> AutoCram: cram empties the MAIN pack, so it must + // NEVER target it (would self-move and spin). + // includeMainPack=true -> wand-swap / dequip: the bow needs ONE slot; fall + // back to the main pack (top-level slots, cap 102) + // when no sub-pack qualifies. + // requireFree -> min free slots a sub-pack must have to be picked + // (2 for the auto-loops = anti-churn margin; 1 for + // user-driven /mt dequip + MetaCast wand-swap). + // + // The spec's `item` parameter is intentionally dropped: no clone ever read the + // source item when choosing a destination (vestigial). Two overloads preserve + // both snapshot disciplines: the (cache) overload force-refreshes for the AV- + // risky dequip paths (must not read stale); the (inv) overload reuses a caller- + // supplied snapshot (AutoCram's single per-tick snapshot — no double BFS). + public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache, + bool includeMainPack, int requireFree) + { + if (cache == null) return 0; + int playerId = unchecked((int)host.GetPlayerId()); + if (playerId == 0) return 0; + // forceRefresh — the dequip paths gate an AV-risky move, so must not read a + // stale cache before the move. + var inv = cache.GetDirectInventory(forceRefresh: true); + return FindPackFor(inv, playerId, includeMainPack, requireFree); + } + + // Snapshot overload — caller supplies an already-built inventory list (AutoCram + // reuses its single per-tick GetDirectInventory snapshot here; do NOT re-refresh). + public static int FindPackFor(IReadOnlyList inv, int playerId, + bool includeMainPack, int requireFree) + { + if (inv == null || playerId == 0) return 0; + if (requireFree < 1) requireFree = 1; + int bestPack = 0, bestFree = 0; + int mainUsed = 0; // loose top-level item-slot occupancy (mirrors ScanInventoryStatus 594-604) + foreach (var p in inv) + { + if (p.Container != playerId) continue; + // Main-pack item-slot tally: loose, non-equipped, non-foci, non-container + // items directly in the player pack. Sub-packs occupy the side-pack slots, + // NOT the 102 item slots, so they're excluded from this count. + if (p.ObjectClass != AcObjectClass.Container + && p.ObjectClass != AcObjectClass.Foci + && p.Values(LongValueKey.EquippedSlots, 0) == 0) + mainUsed++; + if (p.ObjectClass != AcObjectClass.Container) continue; + // Skip foci — technically containers but reserved for spell components. + if (!string.IsNullOrEmpty(p.Name) + && p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) continue; + int capacity = p.Values(LongValueKey.ItemsCapacity, 0); + if (capacity <= 0) continue; // capacity unknown — don't risk the move + int used = 0; + foreach (var it in inv) + { + if (it.Container != p.Id) continue; + if (it.ObjectClass == AcObjectClass.Container) continue; // sub-containers use CONTAINERS_CAPACITY + used++; + } + int free = capacity - used; + // requireFree margin: a pack with fewer than requireFree slots is ineligible + // so a single mis-count can't tip a near-full pack over (anti-churn). + if (free >= requireFree && free > bestFree) { bestFree = free; bestPack = p.Id; } + } + if (bestPack != 0) return bestPack; + if (!includeMainPack) return 0; // AutoCram: never target the main pack (would self-move/spin) + // Dequip fallback: the bow needs ONE free main-pack slot; a dequip into a + // non-full main pack is AV-safe (the AV is only on a genuinely FULL target). + int mainFree = 102 - mainUsed; + return mainFree > 0 ? playerId : 0; + } + + public IEnumerable GetContainedItems(int containerId) + { + if (containerId == 0) + return Array.Empty(); + + // Snapshot candidates under the lock (pure collection reads); resolve container + // ownership outside the lock — GetContainerId is a host-only read, no cache access. + List candidates; + lock (_gate) + { + candidates = new List(_inventory.Count); + foreach (int id in _inventory) + if (_byId.TryGetValue(id, out var wo)) + candidates.Add(wo); + + // Quest items and items with dynamic (0x80000000+) GUIDs are classified + // as landscape rather than inventory. Check landscape too so they appear + // as corpse contents when an open corpse is scanned. + foreach (int id in _landscape) + { + if (_inventory.Contains(id)) continue; // already added above + if (_creatures.Contains(id)) continue; // it's a live creature, not a container item + if (_byId.TryGetValue(id, out var wo)) + candidates.Add(wo); + } + } + + var result = new List(); + foreach (var wo in candidates) + if (GetContainerId(wo.Id) == containerId) + result.Add(wo); + return result; + } + + /// Enumerate landscape creatures (received health updates or TYPE_CREATURE). + public IEnumerable GetLandscape() + { + // Copy-under-lock — the Avalonia radar poll enumerates this cross-thread (see GetInventory). + lock (_gate) + { + var snapshot = new List(_creatures.Count); + foreach (int id in _creatures) + if (_byId.TryGetValue(id, out var wo)) + snapshot.Add(wo); + return snapshot; + } + } + + /// Enumerate all world objects with a valid landscape position, including corpses. + public IEnumerable GetLandscapeObjects() + { + // Copy-under-lock — the Avalonia radar poll enumerates this cross-thread (see GetInventory). + lock (_gate) + { + var snapshot = new List(_landscape.Count); + foreach (int id in _landscape) + if (_byId.TryGetValue(id, out var wo)) + snapshot.Add(wo); + return snapshot; + } + } + + // ── Hazard cells (lava / acid / fire / cold pools) ─────────────────────── + // + // Hotspot weenies in AC are server-side WorldObjects that damage on collision; + // they're not part of the EnvCell graph and so the dungeon pathfinder can't see + // them. We populate this set two ways: + // 1. WO sightings: any landscape (positioned, non-creature) object whose name + // matches a known hazard pattern marks its cellId here. + // 2. Reactive blacklist: NavigationEngine / patrol loop marks the player's + // current cell if HP drops with no nearby hostile (see MarkCellHazard). + // DungeonPathfinder consumes this set via the hazardCells parameter on + // FindPath / BuildPatrolRoute and skips edges into hazard cells the same way + // it skips drop edges. + + private static readonly string[] HazardNamePatterns = + { + "lava", "pool of acid", "acid pool", "pool of fire", "pool of cold", + "cesspool", "hot spring", "magma", + }; + + private readonly HashSet _hazardCells = new(); + + // Bumped every time a NEW hazard cell is registered. The patrol controller + // snapshots this when it builds a route and compares each tick: a change means + // a lava/acid hotspot was sighted that the current route doesn't yet avoid, so + // the route must be rebuilt around it. Cheaper than diffing the set every tick. + private int _hazardVersion; + + public int HazardVersion + { + get { lock (_gate) return _hazardVersion; } + } + + public bool IsHazardCell(uint cellId) + { + lock (_gate) + return _hazardCells.Contains(cellId); + } + + public int HazardCellCount + { + get { lock (_gate) return _hazardCells.Count; } + } + + /// Live hazard cells for a landblock (cellId >> 16 == landblockKey). + public List GetHazardCellsForLandblock(uint landblockKey) + { + lock (_gate) + { + var list = new List(); + foreach (uint c in _hazardCells) + if ((c >> 16) == landblockKey) list.Add(c); + list.Sort(); + return list; + } + } + + /// + /// Manually marks a cell as a hazard (user "this is lava" command / UI button). Adds to + /// the live set, persists it, and bumps so an active patrol + /// reroutes around it. Returns true if it was newly added. + /// + public bool AddHazardCell(uint cellId) + { + if (cellId == 0) return false; + lock (_gate) + { + if (!_hazardCells.Add(cellId)) return false; + _hazardVersion++; + DungeonHazardStore.Append(cellId >> 16, cellId); + _host.Log($"[Hazard] manually marked cell 0x{cellId:X8}"); + return true; + } + } + + /// + /// Removes a manually- or auto-marked hazard cell from the live set and the on-disk store. + /// Bumps . Returns true if it was present. + /// + public bool RemoveHazardCell(uint cellId) + { + lock (_gate) + { + bool removed = _hazardCells.Remove(cellId); + DungeonHazardStore.RemoveCell(cellId >> 16, cellId); + if (removed) _hazardVersion++; + return removed; + } + } + + /// + /// Drops live hazard cells for one landblock (cellId >> 16 == landblockKey) and + /// re-arms seeding for it, so a later patrol of that dungeon reloads from disk fresh. + /// Bumps so an active patrol there rebuilds without the + /// cleared cells. The caller is responsible for clearing the on-disk store separately. + /// + public void ClearLiveHazards(uint landblockKey) + { + lock (_gate) + { + _hazardCells.RemoveWhere(c => (c >> 16) == landblockKey); + if (_hazardsSeededLandblock == landblockKey) _hazardsSeededLandblock = 0; + _hazardVersion++; + } + } + + /// Drops every live hazard cell and re-arms seeding. Bumps HazardVersion. + public void ClearAllLiveHazards() + { + lock (_gate) + { + _hazardCells.Clear(); + _hazardsSeededLandblock = 0; + _hazardVersion++; + } + } + + public IReadOnlySet GetHazardCells() + { + // Snapshot — consumers (DungeonPathfinder) want a point-in-time set per path call. + lock (_gate) + return new HashSet(_hazardCells); + } + + // Landblock whose persisted hazards have already been merged in, so SeedHazardsFromStore + // is a cheap no-op when the patrol builder calls it every (re)build for the same dungeon. + private uint _hazardsSeededLandblock; + + /// + /// Merges the on-disk hazard cells recorded for on prior + /// visits into the live set, so a patrol route built right after entering a known dungeon + /// avoids them from the start instead of having to re-sight and reroute. Cheap no-op once + /// per landblock. Bumps if it adds anything (so an already- + /// running patrol reroutes around the loaded cells too). + /// + public void SeedHazardsFromStore(uint landblockKey) + { + lock (_gate) + { + if (_hazardsSeededLandblock == landblockKey) return; + _hazardsSeededLandblock = landblockKey; + + var persisted = DungeonHazardStore.Load(landblockKey); + int added = 0; + foreach (uint cell in persisted) + if (_hazardCells.Add(cell)) added++; + + if (added > 0) + { + _hazardVersion++; + _host.Log($"[Hazard] seeded {added} persisted hazard cell(s) for landblock 0x{landblockKey:X4}"); + } + } + } + + /// + /// Detector C: marks EnvCells flagged by their lava/acid surface texture as live hazard cells. + /// Unlike these are NOT persisted to DungeonHazardStore — they are + /// re-derived from the cell.dat surface palette + the hazard-texture set on every patrol build, + /// so the texture set stays the single source of truth (re-running with a smaller texture set + /// must drop them). Bumps if it adds anything. Never throws. + /// + public void SeedSurfaceHazards(IEnumerable cells) + { + if (cells == null) return; + lock (_gate) + { + int added = 0; + foreach (uint c in cells) + if (c != 0 && _hazardCells.Add(c)) added++; + + if (added > 0) + { + _hazardVersion++; + _host.Log($"[Hazard] Detector C: {added} EnvCell-surface hazard cell(s) seeded from floor textures"); + } + } + } + + private static bool IsHazardName(string? name) + { + if (string.IsNullOrEmpty(name)) return false; + foreach (string pat in HazardNamePatterns) + if (name.IndexOf(pat, StringComparison.OrdinalIgnoreCase) >= 0) + return true; + return false; + } + + /// + /// Inspect a freshly-classified landscape object and register it as a hazard if + /// its name matches a known hotspot pattern (lava, acid pool, etc.). + /// Safe to call repeatedly for the same uid — set membership is idempotent. + /// + private void MaybeRegisterHazard(uint uid, string name) + { + if (!IsHazardName(name)) return; + if (!_host.TryGetObjectPosition(uid, out uint cellId, out _, out _, out _)) return; + if (cellId == 0) return; + if (_hazardCells.Add(cellId)) + { + _hazardVersion++; + // Persist so future visits to this dungeon avoid the cell from the first + // waypoint. Keyed by landblock (cellId >> 16) — hazards are static world + // geometry, identical for every character. + DungeonHazardStore.Append(cellId >> 16, cellId); + _host.Log($"[Hazard] 0x{uid:X8} '{name}' → cell 0x{cellId:X8} (persisted)"); + } + } + + /// + /// Discover all inventory items via native container scan. + /// Finds items whose CreateObject events fired before the plugin loaded. + /// Call once at login after hooks are ready. + /// + public int ScanFullInventory() + { + lock (_gate) + { + if (!_host.HasGetContainerContents) return -1; + uint playerId = _host.GetPlayerId(); + if (playerId == 0) return -1; + + // Warm up engine probes before bulk scanning: + // 1. TryGetObjectPosition triggers physOffsetProbe (_weeniePhysicsObjOffset) + // needed by TryGetObjectOwnershipInfo / GetContainerContents + // 2. TryGetObjectIntProperty triggers qualitiesOffsetProbe (_weenieQualitiesOffset) + // needed by later property queries — probing now prevents crash if done after scan + _host.TryGetObjectPosition(playerId, out _, out _, out _, out _); + _host.TryGetObjectIntProperty(playerId, 1 /* STypeInt.ItemType */, out _); + + int discovered = 0; + uint[] buf = new uint[512]; + + // Scan player's direct contents + int topCount = _host.GetContainerContents(playerId, buf); + _host.Log($"[RynthAi] ScanFullInventory: topCount={topCount} for player 0x{playerId:X8}"); + for (int i = 0; i < topCount; i++) + discovered += EnsureInCache(buf[i]); + + // Scan inside each pack/container + // Collect pack IDs first to avoid modifying collection during iteration + var packIds = new List(); + for (int i = 0; i < topCount; i++) + { + if (_host.TryGetItemType(buf[i], out uint flags) && (flags & ItemTypeContainer) != 0) + packIds.Add(buf[i]); + } + + foreach (uint packId in packIds) + { + uint[] packBuf = new uint[256]; + int packCount = _host.GetContainerContents(packId, packBuf); + for (int i = 0; i < packCount; i++) + discovered += EnsureInCache(packBuf[i]); + } + + if (discovered > 0) + _host.Log($"[RynthAi] ScanFullInventory: discovered {discovered} new item(s) across {packIds.Count + 1} container(s)"); + + return discovered; + } + } + + private int EnsureInCache(uint uid) + { + lock (_gate) + { + int id = (int)uid; + // Use the indexer for lazy lookup (reads name, classifies, adds to cache) + if (_byId.ContainsKey(id) || this[id] != null) + { + // Item is known to be inside a container — force into _inventory + // even if the indexer classified it as landscape (equipped items have positions) + if (!_inventory.Contains(id)) + { + _inventory.Add(id); + _landscape.Remove(id); + } + return _byId.ContainsKey(id) ? 1 : 0; + } + return 0; + } + } + + private bool TryAddDirectInventoryItem(uint uid, uint playerId, uint containerId, int slot, out bool isContainer) + { + isContainer = false; + + int id = unchecked((int)uid); + if (!_host.TryGetObjectName(uid, out string name) || string.IsNullOrWhiteSpace(name)) + return false; + + int wieldedLocation = 0; + if (_host.HasGetObjectWielderInfo && + _host.TryGetObjectWielderInfo(uid, out uint wielderByInfo, out uint locByInfo) && + wielderByInfo == playerId && + locByInfo > 0) + { + wieldedLocation = unchecked((int)locByInfo); + } + else if (_host.HasGetObjectOwnershipInfo && + _host.TryGetObjectOwnershipInfo(uid, out _, out uint wielder, out uint loc) && + wielder == playerId && + loc > 0) + { + wieldedLocation = unchecked((int)loc); + } + + AcObjectClass cls = AcObjectClass.Unknown; + if (_host.TryGetItemType(uid, out uint flags)) + { + isContainer = (flags & ItemTypeContainer) != 0; + cls = ClassifyByItemType(flags); + } + + if (cls == AcObjectClass.Unknown) + cls = ClassifyInventoryItem(name); + + var wo = new WorldObject(id, name, cls); + wo._wieldedLocationDirect = wieldedLocation; + wo._directContainerId = unchecked((int)containerId); // authoritative parent from the BFS + wo._directSlot = slot; // position in this container's contents + wo.Cache = this; + UpsertDirectInventoryItem(wo); + return true; + } + + private void UpsertDirectInventoryItem(WorldObject item) + { + if (_directInventoryIndex.TryGetValue(item.Id, out int index)) + { + var existing = _directInventory[index]; + if (ShouldReplaceDirectInventoryItem(existing, item)) + _directInventory[index] = item; + return; + } + + _directInventoryIds.Add(item.Id); + _directInventoryIndex[item.Id] = _directInventory.Count; + _directInventory.Add(item); + } + + private static bool ShouldReplaceDirectInventoryItem(WorldObject existing, WorldObject candidate) + { + if (candidate.WieldedLocation > 0 && existing.WieldedLocation <= 0) + return true; + + if (existing.ObjectClass == AcObjectClass.Unknown && candidate.ObjectClass != AcObjectClass.Unknown) + return true; + + if (existing.Cache == null && candidate.Cache != null) + return true; + + return false; + } + + private bool IsPlayerWielded(WorldObject item) + { + if (_playerId == 0 || item.WieldedLocation <= 0) + return false; + + return item.Wielder == unchecked((int)_playerId); + } + + /// Cache statistics for diagnostics. + public (int Total, int Creatures, int Inventory, int Landscape, int Pending) GetStats() + { + lock (_gate) + return (_byId.Count, _creatures.Count, _inventory.Count, _landscape.Count, _pending.Count); + } + + // ── Factory ─────────────────────────────────────────────────────────── + + private WorldObject Make(int id, string name, AcObjectClass cls) + { + var wo = new WorldObject(id, name, cls); + wo.Cache = this; + return wo; + } + + // ── Type-flag item classification ───────────────────────────────────── + + private static AcObjectClass ClassifyByItemType(uint typeFlags) + { + // Most specific / unambiguous types first + if ((typeFlags & ItemTypePromissoryNote) != 0) return AcObjectClass.TradeNote; + if ((typeFlags & ItemTypeManaStone) != 0) return AcObjectClass.ManaStone; + if ((typeFlags & ItemTypeSpellComponents) != 0) return AcObjectClass.SpellComponent; + if ((typeFlags & ItemTypeGem) != 0) return AcObjectClass.Gem; + if ((typeFlags & ItemTypeKey) != 0) return AcObjectClass.Key; + if ((typeFlags & ItemTypeLifeStone) != 0) return AcObjectClass.Lifestone; + if ((typeFlags & ItemTypeTinkeringMaterial) != 0) return AcObjectClass.Salvage; + if ((typeFlags & ItemTypeTinkeringTool) != 0) return AcObjectClass.Ust; + if ((typeFlags & ItemTypeCraftCookingBase) != 0) return AcObjectClass.BaseCooking; + if ((typeFlags & ItemTypeCraftAlchemyBase) != 0) return AcObjectClass.BaseAlchemy; + if ((typeFlags & ItemTypeCraftFletchingBase) != 0) return AcObjectClass.BaseFletching; + if ((typeFlags & ItemTypeCraftAlchemyIntermediate) != 0) return AcObjectClass.CraftedAlchemy; + if ((typeFlags & ItemTypeCraftFletchingIntermediate)!= 0) return AcObjectClass.CraftedFletching; + if ((typeFlags & ItemTypeService) != 0) return AcObjectClass.Services; + if ((typeFlags & ItemTypePortal) != 0) return AcObjectClass.Portal; + if ((typeFlags & ItemTypeWritable) != 0) return AcObjectClass.Book; + if ((typeFlags & ItemTypeContainer) != 0) return AcObjectClass.Container; + if ((typeFlags & ItemTypeCaster) != 0) return AcObjectClass.WandStaffOrb; + if ((typeFlags & ItemTypeMissileWeapon) != 0) return AcObjectClass.MissileWeapon; + if ((typeFlags & ItemTypeArmor) != 0) return AcObjectClass.Armor; + if ((typeFlags & ItemTypeMeleeWeapon) != 0) return AcObjectClass.MeleeWeapon; + if ((typeFlags & ItemTypeClothing) != 0) return AcObjectClass.Clothing; + if ((typeFlags & ItemTypeJewelry) != 0) return AcObjectClass.Jewelry; + if ((typeFlags & ItemTypeFood) != 0) return AcObjectClass.Food; + if ((typeFlags & ItemTypeMoney) != 0) return AcObjectClass.Money; + if ((typeFlags & ItemTypeMisc) != 0) return AcObjectClass.Misc; + return AcObjectClass.Unknown; + } + + // ── Name-based item classification (fallback) ───────────────────────── + + private static AcObjectClass ClassifyInventoryItem(string name) + { + if (string.IsNullOrEmpty(name)) + return AcObjectClass.Unknown; + + if (IsWand(name)) return AcObjectClass.WandStaffOrb; + if (IsMissileWeapon(name)) return AcObjectClass.MissileWeapon; + if (IsAmmo(name)) return AcObjectClass.MissileWeapon; + if (IsClothing(name)) return AcObjectClass.Clothing; + if (IsArmor(name)) return AcObjectClass.Armor; + if (IsMeleeWeapon(name)) return AcObjectClass.MeleeWeapon; + return AcObjectClass.Unknown; + } + + private static bool IsWand(string name) => + ContainsAny(name, "Orb", "Staff", "Wand", "Scepter", "Sceptre", "Baton", "Crozier"); + + private static bool IsMissileWeapon(string name) => + ContainsAny(name, "Bow", "Crossbow", "Atlatl"); + + private static bool IsAmmo(string name) => + ContainsAny(name, "Arrow", "Quarrel", "Bolt", "Atlatl Dart"); + + private static bool IsMeleeWeapon(string name) => + ContainsAny(name, "Sword", "Falchion", "Axe", "Mace", "Spear", + "Dagger", "Katar", "Claw", "Club", "Hammer", "Blade", + "Knife", "Lance", "Rapier", "Scimitar", "Estoc", "Cleaver", + "Flail", "Maul", "Glaive", "Halberd", "Pike", "Trident"); + + private static bool IsClothing(string name) => + ContainsAny(name, "Coat", "Shirt", "Smock", "Pants", "Pantaloons", "Trousers", + "Vest", "Robe", "Over-Robe", "Cowl", "Cap", "Shoes", "Sandals", + "Slippers", "Shorts", "Tunic"); + + private static bool IsArmor(string name) => + ContainsAny(name, "Shield", "Defender", "Helm", "Armet", "Basinet", "Breastplate", + "Cuirass", "Hauberk", "Jerkin", "Leggings", "Greaves", "Tassets", + "Pauldrons", "Bracers", "Gauntlets", "Girth", "Sollerets", + "Vambraces", "Coif", "Coronet", "Crown", "Diadem", "Kabuton", + "Boots", "Mask"); + + private static bool IsCorpseName(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return false; + + return name.EndsWith(" corpse", StringComparison.OrdinalIgnoreCase) + || name.Contains("'s corpse", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("corpse of ", StringComparison.OrdinalIgnoreCase); + } + + private static bool ContainsAny(string name, params string[] keywords) + { + foreach (string kw in keywords) + if (name.IndexOf(kw, StringComparison.OrdinalIgnoreCase) >= 0) + return true; + return false; + } + + private bool TryGetOwnership(int id, out int containerId, out int wielderId, out int location) + { + containerId = 0; + wielderId = 0; + location = 0; + + uint uid = unchecked((uint)id); + bool gotAny = false; + + if (_host.HasGetObjectWielderInfo && + _host.TryGetObjectWielderInfo(uid, out uint wielderOnly, out uint wieldedOnly)) + { + wielderId = unchecked((int)wielderOnly); + location = unchecked((int)wieldedOnly); + gotAny = gotAny || wielderOnly != 0 || wieldedOnly != 0; + } + + if (_host.HasGetObjectOwnershipInfo && + _host.TryGetObjectOwnershipInfo(uid, out uint container, out uint wielder, out uint wieldedLocation)) + { + containerId = unchecked((int)container); + if (wielderId == 0) + wielderId = unchecked((int)wielder); + if (location == 0) + location = unchecked((int)wieldedLocation); + gotAny = true; + } + + return gotAny; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs new file mode 100644 index 0000000..490892d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -0,0 +1,2332 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Loot.VTank; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + private readonly struct CorpseLootDecision + { + public bool ShouldLoot { get; init; } + public string ModeName { get; init; } + public string Reason { get; init; } + public string KillerName { get; init; } + public string PlayerName { get; init; } + public string LongDesc { get; init; } + public bool InFellowship { get; init; } + public bool KillerIsFellow { get; init; } + } + + // id → completed-at ms. Authoritative "looted, do not reopen" set. Aged out + // by PruneCorpseCollections well past max AC corpse lifetime; deliberately + // never cleared by a reopen, so AC re-announcing a still-open looted corpse + // on a patrol loop cannot resurrect it. + private readonly Dictionary _completedCorpses = new(); + private readonly HashSet _processedCorpseItems = new(); + private readonly Dictionary _corpseItemAttempts = new(); + private readonly Dictionary _corpseCooldownUntil = new(); + // Never-opened abandon tally per corpse: a timeout on a corpse we never got + // open earns a retry cooldown (not the 30-min completed mark); after 3 such + // abandons the corpse is treated as unreachable and completed for real. + private readonly Dictionary _corpseAbandonCounts = new(); + private const int NeverOpenedAbandonRetryMs = 30_000; + private readonly HashSet _ownershipSkipLogged = new(); + private readonly HashSet _corpseIdRequested = new(); // corpses whose LongDesc ID was already requested + private int _busyCount; + private long _busyCountLastIncrementAt; + private long _busyCountBecamePositiveAt; // when count first went 0→positive + private const long BUSY_TIMEOUT_MS = 10_000; // safety: force-clear if stuck >10s + + // Wedge detection: when AC's item-action state locks up (server-side, e.g. + // after a corpse pile is opened too fast), EVERY corpse open times out. + // Rather than hammer a dead client for 45 min, count consecutive open + // timeouts → at the threshold, halt looting briefly, fire one reset, and + // tell the user to relog (only thing that clears a server-side lock). + private int _consecutiveLootTimeouts; + private long _lootHaltUntil; + private const int LootWedgeThreshold = 3; // consecutive open timeouts ⇒ wedged + private const long LootWedgeHaltMs = 20_000; // pause looting this long after detecting + private const uint MotionTurnRight = 0x6500000D; + private const uint MotionTurnLeft = 0x6500000E; + private int _openedContainerId; + private int _pendingLootCheckContainerId; // non-corpse container opened natively: run lootcheck on inventory arrival + private int _corpseItemsEvaluated; // items checked against loot profile this corpse session + private int _corpseItemsMatched; // items that matched a loot rule this corpse session + // Mana stones we've approved for loot but whose cache arrival hasn't landed yet. + // Added to haveCount so the KeepCount cap isn't bypassed in the window between + // MoveItemExternal confirmation and the player-inventory CreateObject event. + // HashSet (not a plain count) because ClassifyItemAgainstProfile is called for + // every item on the corpse every tick — a counter would over-count by N each + // re-evaluation pass. + private readonly HashSet _pendingManaStoneIds = new(); + + // Same idea for ManaTap candidates: tracks items approved this corpse + // session so we don't approve more than the available empty-stone slots. + private readonly HashSet _pendingManaTapIds = new(); + private int _targetCorpseId; + private int _currentLootItemId; + private long _corpseTargetSince; + private long _openedContainerAt; + private long _openedContainerInventoryObservedAt; + private long _lastCorpseOpenAttemptAt; + private long _lastCorpseApproachHeartbeatAt; + private long _lastLootActionAt; + private long _currentLootItemRequestedAt; + private long _currentLootItemMoveRequestedAt; + private bool _currentLootItemRequested; + private bool _currentLootItemMovePending; + private bool _corpseAutorunActive; + private int _currentLootItemMoveAttempts; + private string _currentLootItemActionLabel = string.Empty; + private string _currentLootItemName = string.Empty; + private bool _currentLootItemIsSalvage; + private bool _corpseIdsRequested; + private long _corpseIdsRequestedAt; + private bool _corpseApproachTurnsActive; + + private static long CorpseNowMs => Environment.TickCount64; + private void LootDiag(string message) + { + Log(message); + } + + public override void OnBusyCountIncremented() + { + if (_busyCount == 0) + _busyCountBecamePositiveAt = CorpseNowMs; // record first transition 0→positive + _busyCount++; + _busyCountLastIncrementAt = CorpseNowMs; + if (_combatManager != null) _combatManager.BusyCount = _busyCount; + if (_buffManager != null) _buffManager.BusyCount = _busyCount; + } + + public override void OnBusyCountDecremented() + { + if (_busyCount > 0) + _busyCount--; + if (_busyCount == 0) + _busyCountBecamePositiveAt = 0; // back to idle — reset the elevation timer + if (_combatManager != null) _combatManager.BusyCount = _busyCount; + if (_buffManager != null) _buffManager.BusyCount = _busyCount; + } + + /// Safety valve: if busy count has been continuously positive for too long, + /// force-reset it. Uses the "first went positive" timestamp so that a stream of + /// new increments cannot keep refreshing the window indefinitely. + /// When combat has live targets, drops to a much shorter threshold — stale busy + /// from salvage retries shouldn't lock the bot out of fighting for 10s. + // 5s, deliberately ABOVE the engine reconciler's 4s no-gesture timeout + // (BusyCountHooks.CastBusyReconcileTimeoutMs): the reconciler's clean + // deterministic decrement must win this race. At the old 2s, this clear + // fired first on every corpse open — force-clears (with their mid-flight + // busy-zero churn) paced the whole loot grind, and the 2026-06-12 09:33 + // storm of them latched the variant-2 stance/item deadlock. + private const long BUSY_TIMEOUT_COMBAT_URGENT_MS = 5_000; + private void CheckBusyTimeout() + { + if (_busyCount > 0 && _busyCountBecamePositiveAt != 0) + { + long elapsed = CorpseNowMs - _busyCountBecamePositiveAt; + bool combatUrgent = _combatManager?.HasTargets == true; + // Also treat the corpse approach/open phase as urgent: offensive/buff casts + // leak m_cBusy (off-thread CastSpell increments but never pairs a decrement), + // and a lingering phantom count makes TickCorpseOpening sit on OpenBusyWaitMaxMs + // before opening the next corpse — ~8s of dead time per corpse between kills, + // when HasTargets is false so the 10s fallback applied. Scoped to "corpse + // claimed but not yet open" so it never interrupts an in-flight item pickup + // (no pickup is pending until a container is open). + bool lootOpenUrgent = _targetCorpseId != 0 && _openedContainerId == 0; + bool urgent = combatUrgent || lootOpenUrgent; + long threshold = urgent ? BUSY_TIMEOUT_COMBAT_URGENT_MS : BUSY_TIMEOUT_MS; + + // Don't abort a legitimately in-progress cast. The explicit-target war + // cast (FreeHandsAndCastSpell readies the wand THEN casts, so m_cBusy + // often climbs to 2) holds busy for >2s on high tiers — longer than the + // combat-urgent threshold. Force-clearing at 2s aborted the cast before + // its projectile launched (dealt~0, the mob survived) and churned AC's + // action state via ForceResetBusyCount — a prime driver of the + // "can't enter combat mode" wedge. CanCastNow is the engine's + // CMotionInterp gesture gate (the SAME signal BuffManager casts on); + // while a gesture animates, the count is REAL, so extend to the 10s + // absolute backstop (a truly stuck count still self-heals). No-ops on + // an engine without the gate (HasGetCastBusyState false → unchanged). + bool castGestureInProgress = Host.HasGetCastBusyState && !Host.CanCastNow; + if (castGestureInProgress && threshold < BUSY_TIMEOUT_MS) + threshold = BUSY_TIMEOUT_MS; + + if (elapsed > threshold) + { + Log($"[RynthAi] Busy count stuck at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}) — force-clearing."); + // Reset pending loot item BEFORE zeroing AC's m_cBusy. If we have an + // in-flight UseObject, ForceResetBusyCount zeros m_cBusy under it; the + // retry in TickPendingCorpsePickup would then hit a freed AC object and crash. + ResetCurrentLootItem(); + _corpseIdsRequested = false; + _lastLootActionAt = CorpseNowMs; + _busyCount = 0; + _busyCountLastIncrementAt = 0; + _busyCountBecamePositiveAt = 0; + if (_combatManager != null) _combatManager.BusyCount = 0; + if (_buffManager != null) _buffManager.BusyCount = 0; + if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); + } + } + + PruneCorpseCollections(); + } + + // BuffManager calls this the instant a cast RESOLVES in chat: reset the + // plugin's SHADOW busy counter so the next buff isn't gated on a stale + // mirror. ⚠ This no longer touches the REAL m_cBusy: the engine's + // delta-reconciler (e70ac92/9611af8) owns the real field now, decrementing + // exactly what each direct cast/item-action added once its gesture ends. + // The old Host.ForceResetBusyCount() here fired on EVERY cast resolution — + // during the 2026-06-12 buff no-show storm that was a blind real-field + // zero every ~2.5s, which (a) beat the reconciler to the decrement so it + // never ran (rec frozen while fcl climbed), and (b) destroyed AC's own + // item-action serialization, feeding the "one item at a time" latch. The + // CheckBusyTimeout watchdog above remains the real-field backstop. + private void OnBuffCastResolved(string reason) + { + if (_busyCount <= 0) return; + int was = _busyCount; + _busyCount = 0; + _busyCountLastIncrementAt = 0; + _busyCountBecamePositiveAt = 0; + if (_combatManager != null) _combatManager.BusyCount = 0; + if (_buffManager != null) _buffManager.BusyCount = 0; + Log($"[RynthAi] shadow busy-reset on cast resolve (was {was}, {reason}) — real field left to the engine reconciler"); + } + + private long _lastCorpsePruneAt; + private const long CorpsePruneIntervalMs = 60_000; // prune once per minute + // Retain a completed-corpse mark this long. Must exceed the longest AC corpse + // lifetime by a wide margin (so an aged-out entry's corpse is provably gone and + // can never be re-looted) while staying well under server GUID-reuse timescales. + private const long CompletedCorpseRetentionMs = 30 * 60_000; // 30 min + + private void PruneCorpseCollections() + { + long now = CorpseNowMs; + if (now - _lastCorpsePruneAt < CorpsePruneIntervalMs) return; + _lastCorpsePruneAt = now; + + // _completedCorpses — authoritative "looted, do not reopen" set. Evict ONLY by + // age: an entry older than the retention window refers to a corpse that has long + // since despawned (well past max AC corpse lifetime), so it cannot be re-looted + // and its id is past realistic server GUID reuse. Presence in the render cache is + // NOT a despawn signal — an out-of-range corpse must stay marked or the bot + // re-opens it on the next patrol loop — so it is deliberately not consulted here. + if (_completedCorpses.Count > 0) + { + var stale = new List(); + foreach (var kvp in _completedCorpses) + if (now - kvp.Value >= CompletedCorpseRetentionMs) + stale.Add(kvp.Key); + if (stale.Count > 0) + { + int before = _completedCorpses.Count; + foreach (int id in stale) + _completedCorpses.Remove(id); + Log($"[RynthAi] Pruned _completedCorpses: {before} → {_completedCorpses.Count}"); + } + } + + // _ownershipSkipLogged / _corpseIdRequested — pure spam-prevention, safe to wipe periodically + if (_ownershipSkipLogged.Count > 200) + { + _ownershipSkipLogged.Clear(); + Log($"[RynthAi] Pruned _ownershipSkipLogged"); + } + if (_corpseIdRequested.Count > 200) + _corpseIdRequested.Clear(); + + // _corpseCooldownUntil — remove expired entries + var expiredCooldowns = new List(); + foreach (var kvp in _corpseCooldownUntil) + if (kvp.Value <= now) expiredCooldowns.Add(kvp.Key); + foreach (var id in expiredCooldowns) + _corpseCooldownUntil.Remove(id); + } + + public override void OnViewObjectContents(uint objectId) + { + int sid = unchecked((int)objectId); + if (!IsCorpseLikeObject(sid)) + { + // Non-corpse container (chest, bag, etc.) — queue a loot-check once inventory arrives. + _pendingLootCheckContainerId = sid; + return; + } + + // _completedCorpses is authoritative. FinalizeCorpse deliberately leaves a + // looted corpse open server-side, so AC re-announces its contents every time + // it re-streams into range on a patrol loop. Treat any reopen of a completed + // corpse as a passive re-announce: never clear the mark, never start a loot + // session. Membership alone decides — same rule the polling reconciler + // already enforces in SyncCorpseContainerState. A corpse NOT in the set + // (incl. one the user manually opens) still loots normally below. + if (_completedCorpses.ContainsKey(sid)) + { + LootDiag($"[RynthAi] Corpse loot: ignoring reopen of completed corpse 0x{objectId:X8}."); + return; + } + + _corpseCooldownUntil.Remove(sid); + bool sameCorpse = _targetCorpseId == sid; + bool switchedTarget = _targetCorpseId != 0 && _targetCorpseId != sid; + + _openedContainerId = sid; + _openedContainerAt = CorpseNowMs; + _openedContainerInventoryObservedAt = 0; + _lastLootActionAt = 0; + _corpseItemsEvaluated = 0; + _corpseItemsMatched = 0; + _corpseIdsRequested = false; + ResetCurrentLootItem(); + if (!sameCorpse) + { + _processedCorpseItems.Clear(); + _corpseItemAttempts.Clear(); + _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); + } + LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}."); + _consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again + if (switchedTarget) + LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}."); + + _targetCorpseId = sid; + _corpseTargetSince = CorpseNowMs; + _lastCorpseOpenAttemptAt = 0; + } + + public override void OnUpdateObjectInventory(uint objectId) + { + _objectCache?.MarkInventoryDirty(); + _inventoryManager?.MarkDirty(); + + int sid = unchecked((int)objectId); + if (sid == 0) + return; + + // Non-corpse container opened natively — run lootcheck on all its items. + if (_pendingLootCheckContainerId != 0 && sid == _pendingLootCheckContainerId) + { + _pendingLootCheckContainerId = 0; + if (_objectCache != null) + { + foreach (WorldObject item in _objectCache.GetContainedItems(sid)) + InspectLootRuleForItem(item.Id, quiet: true); + } + return; + } + + if (_openedContainerId != 0) + { + if (sid != _openedContainerId) + return; + } + else if (_targetCorpseId == 0 || sid != _targetCorpseId || !IsCorpseLikeObject(sid)) + { + return; + } + + bool firstObservation = _openedContainerInventoryObservedAt == 0; + _openedContainerInventoryObservedAt = CorpseNowMs; + if (firstObservation) + LootDiag($"[RynthAi] Corpse loot: inventory update observed for 0x{objectId:X8}."); + } + + public override void OnStopViewingObjectContents(uint objectId) + { + int sid = unchecked((int)objectId); + if (_pendingLootCheckContainerId == sid) + _pendingLootCheckContainerId = 0; + bool wasOpenCorpse = _openedContainerId == sid; + if (_openedContainerId == sid) + { + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + } + + if (_targetCorpseId == sid) + { + if (_completedCorpses.ContainsKey(sid)) + { + ResetCorpseTarget(); + return; + } + + if (wasOpenCorpse) + { + _lastCorpseOpenAttemptAt = 0; + _lastLootActionAt = CorpseNowMs; + LootDiag($"[RynthAi] Corpse loot: container 0x{objectId:X8} closed before completion; will retry open until timeout."); + } + } + } + + public override void OnVendorOpen(uint vendorId) + { + string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}"; + Host.WriteToChat($"[RynthAi] Vendor open: {label}", 1); + _metaManager?.OnVendorOpen(vendorId); + } + + public override void OnVendorClose(uint vendorId) + { + string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}"; + Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1); + _metaManager?.OnVendorClose(vendorId); + } + + private void TickCorpseOpening() + { + var settings = _dashboard?.Settings; + if (settings == null || _objectCache == null || _playerId == 0) + return; + + SyncCorpseContainerState(); + + // ── Macro off / looting disabled / nav-boost — full stop and reset ── + // Must come before the Buffing check so that turning off the macro always + // clears motion state (smooth turns, autorun) set during corpse approach. + if (!settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority) + { + ResetCorpseTarget(); + return; + } + + // Wedge halt: AC's item-action state is locked (consecutive open + // timeouts). Stop firing opens into a dead client until the halt window + // elapses — hammering it can't recover a server-side lock, only a relog + // can. Navigation/combat (non-item-action) still run elsewhere. + if (CorpseNowMs < _lootHaltUntil) + return; + + // ── Buffing: halt loot work but retain target so looting resumes immediately ── + if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) + { + FreezeCorpseTimeout(CorpseNowMs); + return; + } + + // ── Combat takes priority over claiming NEW corpses ─────────────── + // But if we already have an opened container, finish looting it + // (no movement, no conflict with combat). + if (settings.EnableCombat + && _combatManager?.HasTargets == true + && !settings.BoostLootPriority + && _openedContainerId == 0) + { + FreezeCorpseTimeout(CorpseNowMs); + return; // Keep our target, just wait — don't ResetCorpseTarget + } + + // Loot work is actually running this tick — the timeout clock counts again. + _corpseHoldFrozenAge = -1; + + // ── Active corpse work — pause navigation ──────────────────────── + if (_openedContainerId != 0 || _targetCorpseId != 0) + PauseNavigationForCorpse(); + + if (_openedContainerId != 0) + { + StopCorpseMovement(); + TickOpenCorpseLooting(settings); + return; + } + + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + double minMeters = GetCorpseApproachRangeMinMeters(settings, maxMeters); + if (maxMeters <= 0.25) + return; + + long now = CorpseNowMs; + if (_targetCorpseId == 0) + { + if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _)) + { + // No corpses in range. STEP 4: nothing to release. The "Looting" + // string used to be held here from a just-completed corpse and + // had to be handed back so nav could resume; now HasLootWork + // simply stops returning true and the arbiter moves on by itself + // on the next tick. + return; + } + + if (corpse == null) + return; + + _targetCorpseId = corpse.Id; + _corpseTargetSince = now; + _lastCorpseOpenAttemptAt = 0; + LootDiag($"[RynthAi] Corpse loot: claimed corpse target 0x{(uint)corpse.Id:X8}."); + PauseNavigationForCorpse(); + } + + if (HasCorpseTimedOut(settings, now)) + { + AbandonCurrentCorpse(now, "timeout"); + return; + } + + WorldObject? targetCorpse = _objectCache[_targetCorpseId]; + if (targetCorpse == null || targetCorpse.ObjectClass != AcObjectClass.Corpse) + { + MarkCorpseCooldown(_targetCorpseId, 3000); + ResetCorpseTarget(); + return; + } + + // STEP 4: BotAction is not written here any more. The arbiter already + // decided Looting this tick (HasLootWork saw this corpse in range before + // the claim), and the "don't override Buffing" special case this branch + // encoded is now just the fixed priority order in Decide(). + + double distanceMeters = _objectCache.Distance(unchecked((int)_playerId), _targetCorpseId); + if (double.IsNaN(distanceMeters) || double.IsInfinity(distanceMeters) || distanceMeters == double.MaxValue) + return; + + if (distanceMeters > Math.Max(maxMeters * 1.5, maxMeters + 2.0)) + { + MarkCorpseCooldown(_targetCorpseId, 3000); + ResetCorpseTarget(); + return; + } + + if (distanceMeters > minMeters) + { + ApproachCorpse(_targetCorpseId); + return; + } + + StopCorpseMovement(); + + // Don't stack a corpse-open on top of a still-pending item action. AC + // allows one at a time; firing the open every 500ms regardless of busy + // spikes the count to 5-6 during loot+salvage and trips "you can only + // move or use one item at a time". Wait for busy to clear — but only up + // to OpenBusyWaitMaxMs, so a leaked/desynced count (off-thread casts, + // salvage) can't stall looting forever; the cast-resolve reset and the + // busy watchdog clear the leak independently. + bool throttleOk = _lastCorpseOpenAttemptAt == 0 + || now - _lastCorpseOpenAttemptAt >= Math.Max(500, settings.LootOpenRetryMs); + if (throttleOk) + { + if (_busyCount > 0) + { + if (_corpseOpenBusyWaitSince == 0) _corpseOpenBusyWaitSince = now; + if (now - _corpseOpenBusyWaitSince < OpenBusyWaitMaxMs) + return; // busy — hold the open briefly + } + _corpseOpenBusyWaitSince = 0; + AttemptOpenCorpse(_targetCorpseId); + _lastCorpseOpenAttemptAt = now; + } + } + + private long _corpseOpenBusyWaitSince; + // Wait for busy to genuinely clear before opening the next corpse. The backstop + // only exists so a leaked/desynced count can't freeze looting — CheckBusyTimeout + // now force-clears a leak in 2s during the corpse approach/open phase (lootOpenUrgent), + // so this sits just above that: by the time we'd give up waiting, the watchdog has + // already zeroed the phantom count and the open proceeds cleanly. Was 8000ms, which + // cost ~8s of dead time per corpse whenever a cast had leaked the busy count. + private const long OpenBusyWaitMaxMs = 2500; + + private bool ShouldDriveCorpseOpening(LegacyUiSettings settings) + { + if (!settings.IsMacroRunning || !settings.EnableLooting) + return false; + + if (settings.BoostNavPriority) + return false; + + // Combat is #1 priority — block new corpse claims while combat is + // enabled and has ANY targets (scanned or actively engaged). + // If combat is disabled, targets don't matter — loot freely. + // Exception: if we already have an opened container, finish looting it + // since that involves no movement and doesn't conflict with combat. + if (settings.EnableCombat + && _combatManager?.HasTargets == true + && !settings.BoostLootPriority) + { + if (_openedContainerId == 0) + return false; + } + + return settings.BotAction == "Default" + || settings.BotAction == "Navigating" + || settings.BotAction == "Looting" + || settings.BotAction == "Combat"; + } + + private bool TryFindNearestCorpse(double maxMeters, out WorldObject? corpse, out double distanceMeters) + { + corpse = null; + distanceMeters = double.MaxValue; + if (_objectCache == null || _playerId == 0) + return false; + + long now = CorpseNowMs; + int playerId = unchecked((int)_playerId); + foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) + { + if (candidate.ObjectClass != AcObjectClass.Corpse) + continue; + + if (candidate.Id == _targetCorpseId || _completedCorpses.ContainsKey(candidate.Id)) + continue; + + if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long blockedUntil)) + { + if (blockedUntil > now) + continue; + + _corpseCooldownUntil.Remove(candidate.Id); + } + + CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate); + if (!decision.ShouldLoot) + { + if (_ownershipSkipLogged.Add(candidate.Id)) + { + LootDiag($"[RynthAi] Corpse loot: ownership skip 0x{(uint)candidate.Id:X8} name='{candidate.Name}' mode='{decision.ModeName}' killer='{decision.KillerName}' me='{decision.PlayerName}' reason='{decision.Reason}'"); + } + continue; + } + + double dist = _objectCache.Distance(playerId, candidate.Id); + if (dist > maxMeters || dist >= distanceMeters) + continue; + + corpse = candidate; + distanceMeters = dist; + } + + return corpse != null; + } + + private bool ShouldLootCorpse(WorldObject corpse) + { + return EvaluateCorpseLootDecision(corpse).ShouldLoot; + } + + private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse) + { + var settings = _dashboard?.Settings; + if (corpse == null) + { + return new CorpseLootDecision + { + ShouldLoot = false, + ModeName = "Unknown", + Reason = "Corpse is not available." + }; + } + + int lootOwnership = settings?.LootOwnership ?? 0; + string modeName = GetLootOwnershipModeName(lootOwnership); + string longDesc = corpse.Values(StringValueKey.LongDesc, string.Empty); + + // Corpse LongDesc is only available after the object is identified. + // Request ID so the killer name is populated for the next check. + if (string.IsNullOrWhiteSpace(longDesc) && Host.HasRequestId && _corpseIdRequested.Add(corpse.Id)) + Host.RequestId(unchecked((uint)corpse.Id)); + + string killerName = ExtractCorpseKillerName(longDesc) ?? string.Empty; + string myName = GetPlayerNameForLootOwnership(); + bool inFellowship = _fellowshipTracker?.IsInFellowship == true; + bool killerIsFellow = !string.IsNullOrWhiteSpace(killerName) && _fellowshipTracker?.IsMember(killerName) == true; + + if (settings == null) + { + return new CorpseLootDecision + { + ShouldLoot = false, + ModeName = modeName, + Reason = "Settings are not ready yet.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + if (lootOwnership >= 2) + { + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = modeName, + Reason = "Loot From is set to All Corpses.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + if (lootOwnership <= 0) + { + if (string.IsNullOrWhiteSpace(killerName)) + { + // LongDesc not loaded yet — ID was requested above. + // Treat as tentatively lootable so the corpse gets claimed; + // once the ID response arrives the next check will verify ownership. + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = modeName, + Reason = "Corpse not yet identified — treating as lootable pending ID response.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + bool matchesPlayer = !string.IsNullOrWhiteSpace(myName) + && NormalizeCharName(killerName).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase); + return new CorpseLootDecision + { + ShouldLoot = matchesPlayer, + ModeName = modeName, + Reason = matchesPlayer + ? "Corpse killer matches the current character." + : "Corpse killer does not match the current character.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + if (!string.IsNullOrWhiteSpace(killerName) + && !string.IsNullOrWhiteSpace(myName) + && NormalizeCharName(killerName).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase)) + { + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = modeName, + Reason = "Corpse killer matches the current character.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + if (inFellowship) + { + if (killerIsFellow) + { + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = modeName, + Reason = "Corpse killer is a tracked fellowship member.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + // When fellowship membership data lags behind the live client, allow the server + // to be the final authority instead of skipping potentially valid fellowship corpses. + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = modeName, + Reason = "In fellowship mode, RynthAi will let the server decide when killer ownership is not fully resolved yet.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + bool killerKnown = !string.IsNullOrWhiteSpace(killerName); + bool fallbackMatchesPlayer = killerKnown + && !string.IsNullOrWhiteSpace(myName) + && NormalizeCharName(killerName).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase); + bool tentative = !killerKnown; // LongDesc not loaded yet + return new CorpseLootDecision + { + ShouldLoot = fallbackMatchesPlayer || tentative, + ModeName = modeName, + Reason = tentative + ? "Corpse not yet identified — treating as lootable pending ID response." + : fallbackMatchesPlayer + ? "Not in a fellowship, so the corpse is treated as your own kill." + : "Not in a fellowship and the corpse killer does not match the current character.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + + private string GetPlayerNameForLootOwnership() + { + if (_playerId == 0) + return string.Empty; + + return Host.TryGetObjectName(_playerId, out string playerName) && !string.IsNullOrWhiteSpace(playerName) + ? playerName + : string.Empty; + } + + /// Strip GM/admin sigils (leading '+', surrounding whitespace) so admin characters + /// whose player-object name is "+Buffi" match the "Killed by Buffi." string in corpse LongDesc. + private static string NormalizeCharName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + return string.Empty; + + string trimmed = name.Trim(); + // Admin/GM sigils appear at the start of the display name (+, @, etc.) but + // are stripped out of the "Killed by X" string the server writes to LongDesc. + while (trimmed.Length > 0 && (trimmed[0] == '+' || trimmed[0] == '@' || trimmed[0] == '#')) + trimmed = trimmed.Substring(1); + return trimmed.Trim(); + } + + private static string? ExtractCorpseKillerName(string longDesc) + { + if (string.IsNullOrWhiteSpace(longDesc)) + return null; + + const string prefix = "Killed by "; + int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx < 0) + return null; + + string remainder = longDesc[(idx + prefix.Length)..]; + remainder = remainder.TrimEnd('.', ' ', '\n', '\r'); + return string.IsNullOrWhiteSpace(remainder) ? null : remainder; + } + + private static string GetLootOwnershipModeName(int lootOwnership) + { + return lootOwnership switch + { + <= 0 => "My Kills Only", + 1 => "Fellowship Kills", + _ => "All Corpses" + }; + } + + private void TickOpenCorpseLooting(LegacyUiSettings settings) + { + int corpseId = _openedContainerId; + if (corpseId == 0) + return; + + if (_targetCorpseId == 0) + { + _targetCorpseId = corpseId; + _corpseTargetSince = CorpseNowMs; + } + + if (_completedCorpses.ContainsKey(corpseId)) + { + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + ResetCorpseTarget(); + return; + } + + long now = CorpseNowMs; + if (_openedContainerAt == 0) + _openedContainerAt = now; + + if (HasCorpseTimedOut(settings, now)) + { + AbandonCurrentCorpse(now, "timeout"); + return; + } + + long openAge = now - _openedContainerAt; + + // Snapshot the corpse's contents ONCE per tick and reuse it everywhere below. + // GetContainedItems scans the entire landscape+inventory set (200+ objects) with + // a native ownership probe per object; this path used to call it up to 3× per tick + // (fast-path probe, ID-request loop, eval loop) on the shared plugin tick thread. + List containedItems = _objectCache.GetContainedItems(corpseId).ToList(); + + // Fast path: items for this corpse are already in the cache. AC's CreateObject + // burst populates the corpse's contents during the landscape sweep that precedes + // the ViewContents packet, so OnUpdateObjectInventory effectively never fires for + // corpses — leaving the settle+probe gates below as pure dead time (~400ms/corpse). + // When the cache already has contents, mark observed and proceed immediately. + if (_openedContainerInventoryObservedAt == 0 && containedItems.Count > 0) + { + _openedContainerInventoryObservedAt = now; + LootDiag($"[RynthAi] Corpse loot: cache pre-populated for 0x{(uint)corpseId:X8} at {openAge}ms; skipping inv-wait."); + } + else + { + // Brief settle after open for client to populate container + if (openAge < Math.Max(50, settings.LootContentSettleMs)) + return; + + // Wait for inventory update event from server + if (_openedContainerInventoryObservedAt == 0) + { + if (openAge < Math.Max(300, settings.LootEmptyCorpseMs)) + return; + _openedContainerInventoryObservedAt = _openedContainerAt; + LootDiag($"[RynthAi] Corpse loot: no inventory update for 0x{(uint)corpseId:X8}; probing after {openAge}ms."); + } + } + + // Handle pending pickup confirmation (don't block evaluation — just check) + if (_currentLootItemMovePending) + { + TickPendingCorpsePickup(settings); + if (_currentLootItemMovePending) + return; // Still waiting for this pickup to clear + } + + // Pre-classify items and batch-request IDs only for items that need them. + // + // Each Host.RequestId() call increments ClientUISystem::m_cBusy (busy count). + // After MarkCorpseCompleted, the _busyCount > 0 guard in TickCorpseOpening + // blocks AttemptOpenCorpse until every ID response clears the count — which + // takes 2-4 seconds for a full corpse batch. Fix: classify items whose class + // has no stat-based rules immediately (no ID needed); only request ID for items + // where the profile has numeric/spell conditions that require appraisal data. + if (!_corpseIdsRequested) + { + _corpseIdsRequested = true; + _corpseIdsRequestedAt = now; + int requested = 0; + int preClassified = 0; + + foreach (WorldObject item in containedItems) + { + if (_processedCorpseItems.Contains(item.Id)) continue; + + bool hasData = Host.HasHasAppraisalData && Host.HasAppraisalData(unchecked((uint)item.Id)); + if (hasData) continue; // Already has full appraisal — will evaluate below + + bool hasName = !string.IsNullOrWhiteSpace(item.Name); + + // Items with a name whose class has no stat-based loot rules can be + // classified immediately from name/class data — no ID request needed. + if (hasName && !ItemNeedsAppraisalForLoot(item)) + { + // Pre-classify: if no match, mark processed so we never re-evaluate. + // Items that DO match (e.g. name-only rules) stay unprocessed and will + // be picked up in the eval loop below on this same tick. + if (!ClassifyItemAgainstProfile(item, settings, out _, out _, out _)) + _processedCorpseItems.Add(item.Id); + preClassified++; + continue; // No busy-count-inflating ID request + } + + // Item needs appraisal for accurate classification — request ID. + Host.RequestId(unchecked((uint)item.Id)); + requested++; + } + + if (requested > 0) + { + LootDiag($"[RynthAi] Corpse loot: requested {requested} item ID(s) (pre-classified {preClassified}) for 0x{(uint)corpseId:X8}."); + return; // One tick for server responses to start arriving + } + if (preClassified > 0) + LootDiag($"[RynthAi] Corpse loot: pre-classified {preClassified} item(s) without ID for 0x{(uint)corpseId:X8}."); + // Fall through: all items handled without ID requests — evaluate immediately + } + + // Evaluate ALL items with data in one pass — do NOT gate evaluation on + // busy count. Only the actual UseObject pickup needs busy == 0. + // This lets us classify every item on the corpse as soon as ID data + // arrives, instead of waiting for each RequestId to fully clear. + int visibleItemCount = 0; + int pendingDataCount = 0; + bool assessTimedOut = now - _corpseIdsRequestedAt >= Math.Max(100, settings.LootAssessWindowMs); + + int firstMatchId = 0; + string matchItemName = string.Empty; + string matchActionLabel = string.Empty; + string matchRuleLabel = string.Empty; + bool matchIsSalvage = false; + + foreach (WorldObject item in containedItems) + { + visibleItemCount++; + if (_processedCorpseItems.Contains(item.Id)) + continue; + + bool hasAppraisalData = Host.HasHasAppraisalData && Host.HasAppraisalData(unchecked((uint)item.Id)); + bool hasName = !string.IsNullOrWhiteSpace(item.Name); + + // Hold an item until we can judge it correctly. Stat properties + // (ArmorLevel, damage, total ratings, spells) arrive in the appraisal/ + // RequestId response, NOT the basic create — before that, item.Values(...) + // reads 0, so a stat-gated loot-snob rule fails and the item would be marked + // processed and left on the corpse: a silent loot miss. So wait while the item + // lacks appraisal AND either has no name yet OR the profile needs appraisal to + // classify its class — bounded by the assess window, then best-effort below. + if (!hasAppraisalData && (!hasName || ItemNeedsAppraisalForLoot(item))) + { + if (!assessTimedOut) + { + pendingDataCount++; + continue; + } + if (!hasName) + { + // Timed out with nothing usable — skip this item. + _processedCorpseItems.Add(item.Id); + continue; + } + // Timed out but we have a name — fall through and classify best-effort. + } + + // Evaluate against loot profile — pure classification, no UseObject. + bool classified = ClassifyItemAgainstProfile(item, settings, out string actionLabel, out bool isSalvage, out string ruleLabel); + + // Per-item decision to the LOG, not just chat. The "Loot rule:" line + // below uses ChatLine (Host.WriteToChat), so nothing about WHY an item + // was taken has ever reached RynthCore.log — leaving "it loots things + // that don't match the profile" undiagnosable after the fact. + // + // appraised= is the key field. Stat properties (ArmorLevel, damage, + // ratings, spells) arrive in the RequestId response, not the create, + // so before that every item.Values(...) reads 0 — and a VTank + // LongValKeyLE/NE condition compares against 0 and PASSES. The + // best-effort path below deliberately classifies without appraisal + // once the assess window expires, so an unappraised item can match a + // rule it should not. If keeps correlate with appraised=False, that + // is the cause. + LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " + + (classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : "leave")); + + if (classified) + { + // First match wins — save it for pickup below + if (firstMatchId == 0) + { + firstMatchId = item.Id; + matchItemName = item.Name ?? string.Empty; + matchActionLabel = actionLabel; + matchRuleLabel = ruleLabel; + matchIsSalvage = isSalvage; + } + // Don't break — keep evaluating to mark non-matches processed + } + else + { + // No match — mark processed so we never re-evaluate + _processedCorpseItems.Add(item.Id); + } + } + + // Empty corpse check + if (visibleItemCount == 0) + { + if (openAge >= Math.Max(200, settings.LootEmptyCorpseMs)) + { + LootDiag($"[RynthAi] Corpse loot: no items on 0x{(uint)corpseId:X8} after {openAge}ms; marking complete."); + MarkCorpseCompleted(corpseId); + } + return; + } + + // Matched item — attempt pickup + if (firstMatchId != 0) + { + // Within the assess window, gate on busy count so we don't race with + // RequestId responses still in flight. After the window, items without + // data are already being skipped — items we're picking up here have their + // own ID response back (and their busy-count contribution already decremented). + // If busy gets genuinely stuck, CheckBusyTimeout / ForceResetBusyCount handles + // it; don't add a second gate here that fights the first. + if (_busyCount > 0 && !assessTimedOut) + return; + + ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); + _currentLootItemId = firstMatchId; + Host.SelectItem(unchecked((uint)firstMatchId)); + LootDiag($"[RynthAi] Corpse loot: using 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}."); + + // Jump-loot: jump before MoveItemExternal to cancel the pickup animation. + // Only jump when multiple items remain (single-item: no animation worth cancelling). + // Guards: needs both hooks, stamina > 5 to cover the cost. + bool moved; + int remainingItems = visibleItemCount - _processedCorpseItems.Count; + bool useJumpLoot = settings.LootJumpEnabled + && Host.HasJumpNonAutonomous + && Host.HasMoveItemExternal + && _vitals.CurrentStamina > 5; + + if (useJumpLoot) + { + if (remainingItems > 1) + Host.JumpNonAutonomous(Math.Clamp(settings.LootJumpHeight / 100f, 0.01f, 1f)); + moved = Host.MoveItemExternal(unchecked((uint)firstMatchId), _playerId, 0); + } + else + { + moved = Host.UseObject(unchecked((uint)firstMatchId)); + } + + if (!moved) + { + // If the game rejected the request due to its own busy state, don't + // count it as a failed attempt — just return and retry next tick. + if (_busyCount > 0) + return; + + LootDiag($"[RynthAi] Corpse loot: use request failed for 0x{(uint)firstMatchId:X8}."); + if (IncrementCorpseItemAttempt(firstMatchId) >= 3) + _processedCorpseItems.Add(firstMatchId); + ResetCurrentLootItem(); + _lastLootActionAt = now; + return; + } + _currentLootItemMovePending = true; + _currentLootItemMoveRequestedAt = now; + _currentLootItemMoveAttempts = 1; + _currentLootItemActionLabel = matchActionLabel; + _currentLootItemName = matchItemName; + _currentLootItemIsSalvage = matchIsSalvage; + _lastLootActionAt = now; + return; + } + + // All items evaluated, no matches left — mark corpse complete + if (pendingDataCount == 0) + { + LootDiag($"[RynthAi] Corpse loot: all {visibleItemCount} items on 0x{(uint)corpseId:X8} evaluated; marking complete."); + MarkCorpseCompleted(corpseId); + } + } + + private void TickPendingCorpsePickup(LegacyUiSettings settings) + { + if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0) + { + ResetCurrentLootItem(); + return; + } + + long now = CorpseNowMs; + WorldObject? currentItem = _objectCache[_currentLootItemId]; + int currentContainer = currentItem?.Container ?? 0; + bool stillVisibleOnCorpse = IsCorpseItemVisible(_openedContainerId, _currentLootItemId); + + // Check every tick — confirm immediately as soon as the item leaves the corpse. + // Don't gate this on a timer; the timer only applies to the RETRY path below. + if (currentItem == null || !stillVisibleOnCorpse || (currentContainer != 0 && currentContainer != _openedContainerId)) + { + ConfirmCurrentLootItemMoved( + now, + currentItem == null + ? "item left cache after use" + : (!stillVisibleOnCorpse + ? "item no longer listed on corpse" + : $"new container=0x{(uint)currentContainer:X8}")); + return; + } + + // Item still on corpse — wait before retrying the UseObject. + long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs); + if (now - _currentLootItemMoveRequestedAt < verifyWindowMs) + return; + + if (_currentLootItemMoveAttempts >= 3) + { + LootDiag($"[RynthAi] Corpse loot: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)."); + _processedCorpseItems.Add(_currentLootItemId); + ResetCurrentLootItem(); + _lastLootActionAt = now; + return; + } + + if (_busyCount > 0) + return; // Client is busy — don't queue retry + + Host.SelectItem(unchecked((uint)_currentLootItemId)); + bool retried = Host.UseObject(unchecked((uint)_currentLootItemId)); + _currentLootItemMoveAttempts++; + _currentLootItemMoveRequestedAt = now; + _lastLootActionAt = now; + LootDiag($"[RynthAi] Corpse loot: retrying use for 0x{(uint)_currentLootItemId:X8} attempt {_currentLootItemMoveAttempts}."); + + if (!retried && _currentLootItemMoveAttempts >= 3) + { + _processedCorpseItems.Add(_currentLootItemId); + ResetCurrentLootItem(); + } + } + + private int FindNextCorpseItem(int corpseId, out int visibleItemCount) + { + visibleItemCount = 0; + if (_objectCache == null) + return 0; + + foreach (WorldObject item in _objectCache.GetContainedItems(corpseId)) + { + visibleItemCount++; + if (item.Id == 0 || _processedCorpseItems.Contains(item.Id)) + continue; + + return item.Id; + } + + return 0; + } + + private bool IsCorpseItemVisible(int corpseId, int itemId) + { + if (_objectCache == null || corpseId == 0 || itemId == 0) + return false; + + foreach (WorldObject item in _objectCache.GetContainedItems(corpseId)) + { + if (item.Id == itemId) + return true; + } + + return false; + } + + private void ConfirmCurrentLootItemMoved(long now, string reason) + { + if (_currentLootItemId == 0) + return; + + _processedCorpseItems.Add(_currentLootItemId); + LootDiag($"[RynthAi] Corpse loot: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}."); + if (!string.IsNullOrWhiteSpace(_currentLootItemName)) + ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}"); + + if (_currentLootItemIsSalvage) + _salvageManager?.EnqueueItem(unchecked((uint)_currentLootItemId)); + + ResetCurrentLootItem(); + _lastLootActionAt = now; + } + + /// + /// WantLooting input for the ActivityArbiter (STEP 4). No game commands, no + /// state mutation — safe to call from the decision path every tick. + /// + /// This deliberately answers "is there loot work to do" rather than "have I + /// already claimed a corpse". The distinction is about tick order: the + /// arbiter runs at the top of OnTick and TickCorpseOpening (which is what + /// sets _targetCorpseId) runs near the bottom, so a claim-only predicate + /// would lag one tick behind every claim and hand nav a free step away from + /// each fresh body. Answering from what is in range makes the decision lead + /// the claim instead of trailing it. + /// + /// Caveat, deliberately kept: the in-range scan calls ShouldLootCorpse, + /// which fires one Host.RequestId per corpse to populate the killer name + /// (guarded by _corpseIdRequested, so once per corpse ever). That is a + /// memoized fetch rather than a mutation, and the old bottom-of-tick + /// IsCorpseNavigationClaimActive call already did it on the same cadence — + /// this moves it earlier in the tick, it does not add it. + /// + private bool HasLootWork(LegacyUiSettings settings, long nowMs) + { + if (!settings.IsMacroRunning || !settings.EnableLooting) + return false; + + // Already committed to a body, or mid-loot with the container open. + if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive) + return true; + + // Loot grace: combat just ended and the corpse CreateObject has not + // arrived yet. Hold Looting across that gap so nav doesn't walk away + // from a body that is about to exist. + if (_combatEndedAt != 0 && (nowMs - _combatEndedAt) < LootGraceMs) + return true; + + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + if (maxMeters <= 0.25) + return false; + + return HasUnlootedCorpsesInRange(maxMeters); + } + + // STEP 4/5: IsCorpseNavigationClaimActive is gone. It answered "should loot + // block nav?", which was only ever a question because nav and loot each + // decided for themselves whether to run. The arbiter answers it once now, + // for every subsystem, and HasLootWork above carries the parts that were + // real (claimed corpse, open container, autorun, corpses in range). Its + // BoostNavPriority early-out became the BoostNav clause in Decide(), and its + // BotAction=="Looting" gap check became unnecessary once the string stopped + // being a lock that someone had to remember to release. + + /// Returns true if at least one lootable, non-completed corpse is within range. + private bool HasUnlootedCorpsesInRange(double maxMeters) + { + if (_objectCache == null || _playerId == 0) + return false; + + long now = CorpseNowMs; + int playerId = unchecked((int)_playerId); + foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) + { + if (candidate.ObjectClass != AcObjectClass.Corpse) + continue; + if (_completedCorpses.ContainsKey(candidate.Id)) + continue; + if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long blockedUntil) && blockedUntil > now) + continue; + if (!ShouldLootCorpse(candidate)) + continue; + + double dist = _objectCache.Distance(playerId, candidate.Id); + if (dist <= maxMeters) + return true; + } + + return false; + } + + private void PauseNavigationForCorpse() + { + // STEP 4/5: the corpse-local pause flag and the "Looting" string write + // are both gone. StopNavFor is the single edge-detect for nav stops and + // the arbiter is the single writer of the string — this now just routes + // the corpse claim through them. + if (_navStopIssued && _navStoppedFor == BotActivity.Looting) + return; + + StopNavFor(BotActivity.Looting); + + int corpseId = _openedContainerId != 0 ? _openedContainerId : _targetCorpseId; + if (corpseId != 0) + LootDiag($"[RynthAi] Corpse loot: pausing navigation for corpse 0x{(uint)corpseId:X8}."); + } + + /// + /// Pure classification — evaluates an item against the active loot profile + /// without performing any pickup or side effects. Returns true if the item + /// matched a loot/salvage rule. + /// + private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) + { + actionLabel = string.Empty; + isSalvage = false; + ruleLabel = string.Empty; + + // Consumable override — checked before loot profile. Stone detection is + // centralized in ManaStoneManager.IsManaStone so this loot gate and the + // KeepCount tally below use one predicate: named-rule match if the user + // configured ManaStone rules, otherwise any ObjectClass.ManaStone when + // tapping is on (zero-config looting). + bool isConfiguredManaStone = _manaStoneManager?.IsManaStone(item) == true; + + if (isConfiguredManaStone) + { + // Count stones already in the pack against the KeepCount cap, using + // the SAME IsManaStone predicate as the loot gate above — if these + // diverged the cap would silently stop working (e.g. gate loots by + // ObjectClass but tally counts by name → tally stays 0 → over-loot). + // GetDirectInventory(forceRefresh:true) actively walks the player's + // containers via Host.GetContainerContents, so it's immune to the + // cache-classification race that bites AllKnownObjects() right after + // RL/login. IsManaStone's name fallback also keys on Name (always + // present), so the tally is reliable even before ITEM_TYPE lands. + int liveCount = 0; + if (_objectCache != null) + { + foreach (var inv in _objectCache.GetDirectInventory(forceRefresh: true)) + { + if (string.IsNullOrEmpty(inv.Name)) continue; + if (_manaStoneManager?.IsManaStone(inv) == true) + liveCount++; + } + } + + // Include stones already approved this session whose CreateObject event + // hasn't landed yet. Distinct ids only — same item re-evaluated across + // ticks must not bump the count. + int pendingNotYetCounted = 0; + foreach (int id in _pendingManaStoneIds) + { + if (id == item.Id) continue; // current item handled below + pendingNotYetCounted++; + } + int haveCount = liveCount + pendingNotYetCounted; + + // One-time-per-corpse log so we can see what the count was based on. + if (_pendingManaStoneIds.Count == 0) + Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})"); + + // If this specific stone is already approved, return the same answer + // we returned last time (no further log spam, no count change). + if (_pendingManaStoneIds.Contains(item.Id)) + { + actionLabel = "Keep"; + ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; + return true; + } + + if (haveCount < settings.ManaStoneKeepCount) + { + actionLabel = "Keep"; + ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; + ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting."); + _pendingManaStoneIds.Add(item.Id); + return true; + } + + ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); + return false; + } + + if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _)) + { + _corpseItemsEvaluated++; + var (nativeAction, nativeRule) = LootEvaluator.Classify(nativeProfile, item, _charSkills); + if (nativeRule == null) + { + if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel)) + { + _corpseItemsMatched++; + return true; + } + return false; + } + _corpseItemsMatched++; + actionLabel = nativeAction.ToString(); + isSalvage = nativeAction == LootAction.Salvage; + ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim(); + return true; + } + + // VTank .utl profile fallback + if (!TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _)) + return false; + + _corpseItemsEvaluated++; + VTankLootContext lootCtx = new(Host, _playerId) { Cache = _objectCache }; + VTankLootRule? matchedRule = null; + int matchedRuleIndex = -1; + for (int ri = 0; ri < vtankProfile.Rules.Count; ri++) + { + if (VTankLootEvaluator.Match(vtankProfile.Rules[ri], item, lootCtx)) + { + matchedRule = vtankProfile.Rules[ri]; + matchedRuleIndex = ri; + break; + } + } + + if (matchedRule == null) + { + if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel)) + { + _corpseItemsMatched++; + return true; + } + return false; + } + + _corpseItemsMatched++; + ruleLabel = string.IsNullOrWhiteSpace(matchedRule.Name) + ? $"#{matchedRuleIndex}" + : matchedRule.Name.Trim(); + actionLabel = matchedRule.Action.ToString(); + isSalvage = matchedRule.Action == VTankLootAction.Salvage; + return true; + } + + /// + /// Loot-for-tap fallback: when an item doesn't match any loot rule but it + /// holds at least the configured mana threshold AND the player has an + /// uncharged mana stone in inventory, loot the item so ManaStoneManager + /// can drain it (which destroys the item and charges the stone). + /// + private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings, + out string actionLabel, out string ruleLabel) + { + actionLabel = string.Empty; + ruleLabel = string.Empty; + + if (_manaStoneManager == null) return false; + if (!Host.HasGetObjectIntProperty) return false; + + int threshold = settings.ManaTapMinMana; + if (threshold <= 0) return false; + + if (!Host.TryGetObjectIntProperty(unchecked((uint)item.Id), + (uint)AcIntProperty.CurrentMana, out int curMana)) + return false; + if (curMana < threshold) return false; + + // Already approved this session — return same answer without re-logging + // or re-counting against the quota. + if (_pendingManaTapIds.Contains(item.Id)) + { + actionLabel = "ManaTap"; + ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})"; + return true; + } + + // Quota: each ManaTap pickup consumes one empty stone. Don't loot more + // candidates than we have free empty-stone slots, otherwise we end up + // with a pile of mana items the bot can't drain. + int freeSlots = _manaStoneManager.FreeEmptyStoneSlots() - _pendingManaTapIds.Count; + if (freeSlots <= 0) return false; + + actionLabel = "ManaTap"; + ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})"; + ChatLine($"[RynthAi] Mana tap candidate: '{item.Name}' (mana {curMana}, slot {_pendingManaTapIds.Count + 1}) — looting to drain."); + _pendingManaTapIds.Add(item.Id); + return true; + } + + /// + /// Returns true if the active loot profile has at least one rule that + /// (a) could match this item's object class, AND + /// (b) uses conditions that require appraisal data (numeric stats, spell counts, etc.) + /// + /// When false, the item can be definitively evaluated from name/class data alone, + /// so we skip Host.RequestId() to avoid inflating the client busy count. + /// + private bool ItemNeedsAppraisalForLoot(WorldObject item) + { + if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _)) + return NativeProfileNeedsAppraisalForClass(nativeProfile, item.ObjectClass); + + if (TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _)) + return VTankProfileNeedsAppraisalForClass(vtankProfile, item.ObjectClass); + + return false; // No active profile — no ID request needed + } + + private static bool NativeProfileNeedsAppraisalForClass(LootProfile profile, AcObjectClass cls) + { + foreach (var rule in profile.Rules) + { + if (!rule.Enabled) continue; + + // Determine whether the rule targets this class + bool hasClassFilter = false; + bool classMatches = false; + foreach (var cond in rule.Conditions) + { + if (cond is ObjectClassCondition occ) + { + hasClassFilter = true; + if ((AcObjectClass)(int)occ.ObjectClass == cls) + classMatches = true; + } + } + if (hasClassFilter && !classMatches) continue; // Rule filters out this class + + // Rule can match this class — does it require appraisal data? + foreach (var cond in rule.Conditions) + { + if (cond is LongValKeyGECondition + or LongValKeyLECondition + or LongValKeyECondition + or LongValKeyNECondition + or LongValKeyFlagCondition + or DoubleValKeyGECondition + or DoubleValKeyLECondition + or TotalRatingsGECondition + or MinDamageGECondition + or DamagePercentGECondition) + return true; + } + } + return false; + } + + private static bool VTankProfileNeedsAppraisalForClass(VTankLootProfile profile, AcObjectClass cls) + { + // Requirement types that need appraisal data from the server. + static bool TypeNeedsAppraisal(int t) => t is + 2 or 3 or 4 or 5 or 6 or 8 or 9 or 10 or 11 or 12 or 13 or + 14 or 15 or 16 or 17 or 2000 or 2001 or 2003 or 2005 or 2006 or 2007 or 2008; + + int targetClass = (int)cls; + + foreach (var rule in profile.Rules) + { + if (rule.Conditions.Count == 0) continue; // unconditional + + bool hasClassReq = false; + bool classMatches = false; + bool needsAppraisal = false; + + foreach (var cond in rule.Conditions) + { + if (cond.NodeType == VTankNodeTypes.ObjectClass) + { + hasClassReq = true; + if (cond.DataLines.Count > 0 + && int.TryParse(cond.DataLines[0].Trim(), + System.Globalization.NumberStyles.Integer, + System.Globalization.CultureInfo.InvariantCulture, out int cls2) + && cls2 == targetClass) + classMatches = true; + } + else if (TypeNeedsAppraisal(cond.NodeType)) + { + needsAppraisal = true; + } + } + + bool ruleApplies = !hasClassReq || classMatches; + if (ruleApplies && needsAppraisal) return true; + } + + return false; + } + + private void MarkCorpseCompleted(int corpseId) + { + if (corpseId == 0) + return; + + _completedCorpses[corpseId] = CorpseNowMs; + _corpseCooldownUntil.Remove(corpseId); + _processedCorpseItems.Clear(); + _corpseItemAttempts.Clear(); + _corpseIdsRequested = false; + _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); + ResetCurrentLootItem(); + + // Clear container state immediately. Do NOT send UseObject(corpse) to close it — + // that increments busy count and blocks the next open until the server acks the close. + // The server will auto-close this corpse when the next UseObject open is sent. + // SyncCorpseContainerState guards against re-claiming via _completedCorpses. + if (_openedContainerId == corpseId) + { + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + LootDiag($"[RynthAi] Corpse loot: completed 0x{(uint)corpseId:X8}, cleared container state."); + } + + if (_corpseItemsEvaluated > 0 && _corpseItemsMatched == 0) + { + string corpseName = _objectCache?[corpseId]?.Name ?? $"0x{(uint)corpseId:X8}"; + ChatLine($"[RynthAi] Nothing on {corpseName} matches the loot profile."); + } + LootDiag($"[RynthAi] Corpse loot: completed 0x{(uint)corpseId:X8}, releasing container."); + + // Lightweight target reset — deliberately NOT ResetCorpseTarget(), so the + // next tick can claim the next corpse immediately. The no-gap property + // this comment used to credit to holding BotAction="Looting" now comes + // from HasLootWork: with another body still in range it keeps returning + // true, so the arbiter never leaves Looting and nav never gets a step in. + StopCorpseMovement(); + _targetCorpseId = 0; + _corpseTargetSince = 0; + _lastCorpseOpenAttemptAt = 0; + _lastLootActionAt = 0; + } + + private int IncrementCorpseItemAttempt(int itemId) + { + if (!_corpseItemAttempts.TryGetValue(itemId, out int attempts)) + attempts = 0; + + attempts++; + _corpseItemAttempts[itemId] = attempts; + return attempts; + } + + private void ResetCurrentLootItem() + { + _currentLootItemId = 0; + _currentLootItemRequested = false; + _currentLootItemRequestedAt = 0; + _currentLootItemMovePending = false; + _currentLootItemMoveRequestedAt = 0; + _currentLootItemMoveAttempts = 0; + _currentLootItemActionLabel = string.Empty; + _currentLootItemName = string.Empty; + _currentLootItemIsSalvage = false; + } + + private void ApproachCorpse(int corpseId) + { + if (!TryGetHeadingToObject(corpseId, out double desiredDeg, out double absError, out double signedError)) + return; + + if (absError > 18.0) + { + StopCorpseMovement(); + // Use smooth motion turns, same as NavigationEngine/CombatManager + if (signedError > 0) + { + Host.SetMotion(MotionTurnRight, true); + Host.SetMotion(MotionTurnLeft, false); + } + else + { + Host.SetMotion(MotionTurnLeft, true); + Host.SetMotion(MotionTurnRight, false); + } + _corpseApproachTurnsActive = true; + return; + } + + ClearCorpseTurnMotions(); + + long now = CorpseNowMs; + if (!_corpseAutorunActive || now - _lastCorpseApproachHeartbeatAt >= 500) + { + Host.SetAutoRun(true); + _corpseAutorunActive = true; + _lastCorpseApproachHeartbeatAt = now; + } + } + + private void ClearCorpseTurnMotions() + { + if (!_corpseApproachTurnsActive) + return; + _corpseApproachTurnsActive = false; + Host.SetMotion(MotionTurnRight, false); + Host.SetMotion(MotionTurnLeft, false); + } + + private void StopCorpseMovement() + { + ClearCorpseTurnMotions(); + + if (!_corpseAutorunActive) + return; + + Host.SetAutoRun(false); + if (Host.HasStopCompletely) + Host.StopCompletely(); + + _corpseAutorunActive = false; + } + + private void AttemptOpenCorpse(int corpseId) + { + StopCorpseMovement(); + Host.SelectItem(unchecked((uint)corpseId)); + Host.UseObject(unchecked((uint)corpseId)); + LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}."); + } + + private void SyncCorpseContainerState() + { + if (!Host.HasGetGroundContainerId) + return; + + int rawOpen = unchecked((int)Host.GetGroundContainerId()); + if (rawOpen == _openedContainerId) + return; + + long now = CorpseNowMs; + if (_openedContainerId != 0 && rawOpen != _openedContainerId) + { + int previousOpen = _openedContainerId; + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + + if (_targetCorpseId == previousOpen) + { + if (_completedCorpses.ContainsKey(previousOpen)) + { + LootDiag($"[RynthAi] Corpse loot: observed close for completed corpse 0x{(uint)previousOpen:X8}."); + ResetCorpseTarget(); + return; + } + + ResetCurrentLootItem(); + _lastCorpseOpenAttemptAt = 0; + _lastLootActionAt = now; + LootDiag($"[RynthAi] Corpse loot: reconciled closed corpse 0x{(uint)previousOpen:X8}; will reopen if still active."); + } + } + + if (_openedContainerId == 0 && rawOpen != 0 && IsCorpseLikeObject(rawOpen)) + { + // Don't re-claim a corpse we've already completed — the server still + // reports it as open, but we're done with it. It will close when we + // open the next corpse or move away. + if (_completedCorpses.ContainsKey(rawOpen)) + return; + + bool switchedTarget = _targetCorpseId != 0 && _targetCorpseId != rawOpen; + _openedContainerId = rawOpen; + _openedContainerAt = now; + _openedContainerInventoryObservedAt = 0; + _lastLootActionAt = 0; + ResetCurrentLootItem(); + if (switchedTarget) + { + _processedCorpseItems.Clear(); + _corpseItemAttempts.Clear(); + _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); + } + + _targetCorpseId = rawOpen; + _corpseTargetSince = now; + _lastCorpseOpenAttemptAt = 0; + LootDiag($"[RynthAi] Corpse loot: reconciled open corpse 0x{(uint)rawOpen:X8} from client state."); + } + } + + /// + /// Drop the current corpse claim and reset the per-corpse item cursor. + /// + /// STEP 4: this used to take a releaseState flag whose only job was "hand + /// the Looting string back to Default so nav can resume". Every caller + /// passed true, and there is nothing to hand back any more — the arbiter + /// recomputes from HasLootWork every tick, so clearing _targetCorpseId here + /// is the entire signal. The parameter is gone rather than left vestigial. + /// + private void ResetCorpseTarget() + { + StopCorpseMovement(); + _targetCorpseId = 0; + _corpseTargetSince = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + _lastCorpseOpenAttemptAt = 0; + _lastLootActionAt = 0; + _corpseIdsRequested = false; + _corpseApproachTurnsActive = false; + ResetCurrentLootItem(); + _processedCorpseItems.Clear(); + _corpseItemAttempts.Clear(); + _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); + } + + private void HandleCorpseObjectDeleted(uint objectId) + { + int sid = unchecked((int)objectId); + // Do NOT remove from _completedCorpses here. In AC, DeleteObject fires when a corpse + // leaves render range as well as when it actually despawns — both look identical. + // If we removed it here, the bot would re-open the same corpse when it circles back + // into range. PruneCorpseCollections handles eventual cleanup of truly-gone entries. + _processedCorpseItems.Remove(sid); + _corpseItemAttempts.Remove(sid); + _corpseCooldownUntil.Remove(sid); + _ownershipSkipLogged.Remove(sid); + _corpseIdRequested.Remove(sid); + + // If this is the corpse we were actively looting (container was open and we received + // at least one inventory update), mark it completed before resetting. Without this, + // the corpse leaves range without an entry in _completedCorpses; on the next patrol + // pass TryFindNearestCorpse picks it up again and the bot re-opens an already-looted + // corpse. Marking it here is safe: if items remained, they're unrecoverable once + // we've walked far enough for DeleteObject to fire; if all matching items were already + // taken, the mark prevents the pointless re-open. + if (_targetCorpseId == sid && _openedContainerId == sid && _openedContainerInventoryObservedAt != 0) + { + LootDiag($"[RynthAi] Corpse loot: corpse 0x{objectId:X8} left range mid-loot; marking completed to prevent re-open."); + _completedCorpses[sid] = CorpseNowMs; + } + + if (_targetCorpseId == sid) + ResetCorpseTarget(); + + if (_openedContainerId == sid) + _openedContainerId = 0; + } + + private void MarkCorpseCooldown(int corpseId, int delayMs) + { + if (corpseId == 0) + return; + + _corpseCooldownUntil[corpseId] = CorpseNowMs + Math.Max(500, delayMs); + } + + private bool IsCorpseLikeObject(int objectId) + { + if (objectId == 0) + return false; + + if ((_objectCache?[objectId]?.ObjectClass ?? AcObjectClass.Unknown) == AcObjectClass.Corpse) + return true; + + if (_targetCorpseId != 0 && objectId == _targetCorpseId) + return true; + + if (!Host.TryGetObjectName(unchecked((uint)objectId), out string name) || string.IsNullOrWhiteSpace(name)) + return false; + + return name.EndsWith(" corpse", StringComparison.OrdinalIgnoreCase) + || name.Contains("'s corpse", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("corpse of ", StringComparison.OrdinalIgnoreCase); + } + + private bool TryGetHeadingToObject(int targetId, out double desiredDeg, out double absError, out double signedError) + { + desiredDeg = 0; + absError = 180.0; + signedError = 0; + + if (!Host.TryGetPlayerPose(out _, out float px, out float py, out _, out float qw, out _, out _, out float qz)) + return false; + + if (!Host.TryGetObjectPosition(unchecked((uint)targetId), out _, out float tx, out float ty, out _)) + return false; + + double dx = tx - px; + double dy = ty - py; + desiredDeg = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (desiredDeg < 0) + desiredDeg += 360.0; + + double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + double currentDeg = ((-physYawDeg) % 360.0 + 720.0) % 360.0; + + double error = desiredDeg - currentDeg; + while (error > 180.0) error -= 360.0; + while (error < -180.0) error += 360.0; + signedError = error; + absError = Math.Abs(error); + return true; + } + + private static double GetCorpseApproachRangeMaxMeters(LegacyUiSettings settings) + { + return ConvertYardsToMeters(NormalizeCorpseRangeYards(settings.CorpseApproachRangeMax, 10.0)); + } + + private static double GetCorpseApproachRangeMinMeters(LegacyUiSettings settings, double maxMeters) + { + double minMeters = ConvertYardsToMeters(NormalizeCorpseRangeYards(settings.CorpseApproachRangeMin, 2.0)); + if (minMeters <= 0.25) + minMeters = Math.Min(1.5, maxMeters); + if (minMeters > maxMeters) + minMeters = maxMeters; + return minMeters; + } + + private static int GetCorpseTimeoutMs(LegacyUiSettings settings) + { + return Math.Max(2000, settings.LootCorpseTimeoutMs); + } + + private bool HasCorpseTimedOut(LegacyUiSettings settings, long now) + { + return _targetCorpseId != 0 + && _corpseTargetSince != 0 + && now - _corpseTargetSince >= GetCorpseTimeoutMs(settings); + } + + // ── Loot-timeout clock freeze during buff/combat holds ──────────────── + // The holds in TickCorpseOpening early-return while a corpse is claimed; + // without this, _corpseTargetSince kept aging through any fight/buff cycle + // longer than LootCorpseTimeoutMs, and the first tick after the hold lifted + // abandoned a never-opened corpse (completed-marked → loot lost) and fed + // the wedge detector a phantom timeout. Re-pinning the age each held tick + // keeps (now − _corpseTargetSince) constant; the clock resumes when work does. + private long _corpseHoldFrozenAge = -1; + + private void FreezeCorpseTimeout(long now) + { + if (_targetCorpseId == 0 || _corpseTargetSince == 0) + { + _corpseHoldFrozenAge = -1; + return; + } + if (_corpseHoldFrozenAge < 0) + _corpseHoldFrozenAge = now - _corpseTargetSince; + _corpseTargetSince = now - _corpseHoldFrozenAge; + } + + private void AbandonCurrentCorpse(long now, string reason) + { + int corpseId = _targetCorpseId != 0 ? _targetCorpseId : _openedContainerId; + if (corpseId == 0) + return; + + long ageMs = _corpseTargetSince != 0 ? now - _corpseTargetSince : 0; + LootDiag($"[RynthAi] Corpse loot: abandoning corpse 0x{(uint)corpseId:X8} after {ageMs}ms ({reason})."); + ChatLine($"[RynthAi] Corpse timeout: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms."); + + // Only a corpse we actually OPENED earns the completed mark (30-min + // do-not-touch — its loot is permanently skipped). A never-opened + // abandon (approach failed, open refused) gets a short retry cooldown + // instead; after a few never-opened abandons, give up for real so an + // unreachable corpse can't cycle forever. + bool wasOpened = _openedContainerId == corpseId; + int abandons = _corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1; + _corpseAbandonCounts[corpseId] = abandons; + if (wasOpened || abandons >= 3) + { + _completedCorpses[corpseId] = now; + _corpseCooldownUntil.Remove(corpseId); + _corpseAbandonCounts.Remove(corpseId); + } + else + { + _corpseCooldownUntil[corpseId] = now + NeverOpenedAbandonRetryMs; + LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} was never opened (abandon #{abandons}) — retry in {NeverOpenedAbandonRetryMs / 1000}s instead of completed-marking."); + } + + // Force-clear container state — don't try UseObject to close. + // The server will auto-close when we open the next corpse or move away. + if (_openedContainerId == corpseId) + { + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + } + + ResetCorpseTarget(); + + // Track open timeouts to detect a wedged item-action state. A successful + // open resets this counter; a run of timeouts means AC stopped accepting + // item actions (the "you can only move or use one item at a time" lock). + if (reason.IndexOf("timeout", StringComparison.OrdinalIgnoreCase) >= 0) + { + _consecutiveLootTimeouts++; + if (_consecutiveLootTimeouts >= LootWedgeThreshold) + HandleLootWedge(now); + } + } + + /// + /// AC's item-action queue is wedged (N consecutive corpse opens timed out). + /// Halt looting briefly, fire one client-side reset (same actions as + /// /ra panic), and tell the user — a server-side lock only clears on relog, + /// so the worst thing we can do is keep hammering opens into a dead client. + /// + private void HandleLootWedge(long now) + { + _lootHaltUntil = now + LootWedgeHaltMs; + _consecutiveLootTimeouts = 0; // re-arm; if still wedged it trips again after the halt + + if (Host.HasCancelAttack) Host.CancelAttack(); + if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat); + if (Host.HasStopCompletely) Host.StopCompletely(); + if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); + _busyCount = 0; + _busyCountLastIncrementAt = 0; + _busyCountBecamePositiveAt = 0; + if (_combatManager != null) _combatManager.BusyCount = 0; + if (_buffManager != null) _buffManager.BusyCount = 0; + + ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and resetting. If equip/loot stays stuck, RELOG (server-side lock — /ra panic can't clear it)."); + Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired."); + } + + private static double NormalizeCorpseRangeYards(double value, double fallbackYards) + { + if (double.IsNaN(value) || double.IsInfinity(value) || value <= 0.0) + return fallbackYards; + + return value <= 1.0 ? value * 240.0 : value; + } + + private static double ConvertYardsToMeters(double yards) + { + return Math.Max(0.0, yards) * 0.9144; + } + + private static double ConvertMetersToYards(double meters) + { + return meters / 0.9144; + } + + private void HandleCorpseInfoCommand() + { + var settings = _dashboard?.Settings; + if (settings == null || _objectCache == null || _playerId == 0) + { + ChatLine("[RynthAi] Corpse info not ready yet."); + return; + } + + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + double minMeters = GetCorpseApproachRangeMinMeters(settings, maxMeters); + ChatLine($"[RynthAi] Corpse ranges: max={ConvertMetersToYards(maxMeters):F1} yd / {maxMeters:F1} m, min={ConvertMetersToYards(minMeters):F1} yd / {minMeters:F1} m"); + uint rawOpen = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0; + ChatLine($"[RynthAi] Corpse state: target=0x{(uint)_targetCorpseId:X8}, corpse-open=0x{(uint)_openedContainerId:X8}, raw-open=0x{rawOpen:X8}, busy={_busyCount}, inv-update={(_openedContainerInventoryObservedAt != 0 ? 1 : 0)}, completed={_completedCorpses.Count}"); + + if (TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters)) + ChatLine($"[RynthAi] Nearest corpse: {corpse!.Name} (0x{(uint)corpse.Id:X8}) at {ConvertMetersToYards(distanceMeters):F1} yd / {distanceMeters:F1} m"); + else + ChatLine("[RynthAi] No unopened corpses are currently within corpse max range."); + } + + private void HandleCorpseCheckCommand(string[] parts) + { + var settings = _dashboard?.Settings; + if (settings == null || _objectCache == null || _playerId == 0) + { + ChatLine("[RynthAi] Corpse ownership diagnostics are not ready yet."); + return; + } + + string selector = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty; + if (!TryResolveCorpseForDiagnostics(selector, out WorldObject? corpse, out string source)) + { + ChatLine("[RynthAi] No corpse found for diagnostics. Use /ra corpsecheck [target|open|nearest]."); + return; + } + + if (Host.HasRequestId) + Host.RequestId(unchecked((uint)corpse!.Id)); + + CorpseLootDecision decision = EvaluateCorpseLootDecision(corpse); + ChatLine($"[RynthAi] Corpse check ({source}): {corpse!.Name} (0x{(uint)corpse.Id:X8})"); + ChatLine($"[RynthAi] Loot From: {decision.ModeName}"); + ChatLine($"[RynthAi] Would loot: {(decision.ShouldLoot ? "YES" : "NO")}"); + ChatLine($"[RynthAi] Reason: {decision.Reason}"); + ChatLine($"[RynthAi] Player: {(string.IsNullOrWhiteSpace(decision.PlayerName) ? "" : decision.PlayerName)}"); + ChatLine($"[RynthAi] Killer: {(string.IsNullOrWhiteSpace(decision.KillerName) ? "" : decision.KillerName)}"); + ChatLine($"[RynthAi] Fellowship: {(decision.InFellowship ? "yes" : "no")} | killer is fellow: {(decision.KillerIsFellow ? "yes" : "no")}"); + if (!string.IsNullOrWhiteSpace(decision.LongDesc)) + ChatLine($"[RynthAi] LongDesc: {decision.LongDesc}"); + else + ChatLine("[RynthAi] LongDesc: (ID was requested; run the command again if the corpse was not identified yet)"); + } + + private void HandleFellowshipInfoCommand() + { + HandleFellowshipCommand(["/ra", "fellow", "status"]); + } + + private void HandleFellowshipCommand(string[] parts) + { + if (_fellowshipTracker == null) + { + ChatLine("[RynthAi] Fellowship tracker is not ready yet."); + return; + } + + string fellowSub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status"; + if (!_fellowshipTracker.IsInFellowship && fellowSub != "help") + { + ChatLine("[RynthAi] Not in a fellowship."); + return; + } + + switch (fellowSub) + { + case "status": + PrintFellowshipStatus(); + break; + + case "leader": + { + int leaderId = _fellowshipTracker.LeaderId; + string leaderName = FindFellowshipMemberNameById(leaderId); + ChatLine($"[RynthAi] Leader: {leaderName} (0x{unchecked((uint)leaderId):X8}){(_fellowshipTracker.IsLeader ? " (you)" : "")}"); + break; + } + + case "count": + ChatLine($"[RynthAi] Fellowship member count: {_fellowshipTracker.MemberCount}"); + break; + + case "names": + { + var names = new List(_fellowshipTracker.GetMemberNames()); + ChatLine($"[RynthAi] Members ({names.Count}): {string.Join(", ", names)}"); + break; + } + + case "name": + ChatLine($"[RynthAi] Fellowship name: \"{_fellowshipTracker.FellowshipName}\""); + break; + + case "open": + ChatLine($"[RynthAi] Open: {_fellowshipTracker.IsOpen}"); + break; + + case "locked": + ChatLine($"[RynthAi] Locked: {_fellowshipTracker.IsLocked}"); + break; + + case "sharexp": + ChatLine($"[RynthAi] ShareXP: {_fellowshipTracker.ShareXP}"); + break; + + case "ismember": + if (parts.Length >= 4) + { + string checkName = string.Join(" ", parts, 3, parts.Length - 3); + bool found = _fellowshipTracker.IsMember(checkName); + ChatLine($"[RynthAi] IsMember(\"{checkName}\"): {found}"); + } + else + { + ChatLine("[RynthAi] Usage: /ra fellow ismember "); + } + break; + + case "help": + ChatLine("[RynthAi] /ra fellow [status|leader|count|names|name|open|locked|sharexp|ismember ]"); + break; + + default: + ChatLine($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /ra fellow help"); + break; + } + } + + private void PrintFellowshipStatus() + { + if (_fellowshipTracker == null) + { + ChatLine("[RynthAi] Fellowship tracker is not ready yet."); + return; + } + + string playerName = GetPlayerNameForLootOwnership(); + ChatLine($"[RynthAi] Fellowship: \"{_fellowshipTracker.FellowshipName}\""); + ChatLine($"[RynthAi] Player: {(string.IsNullOrWhiteSpace(playerName) ? "" : playerName)}"); + ChatLine($"[RynthAi] Members: {_fellowshipTracker.MemberCount} | Leader: {(_fellowshipTracker.IsLeader ? "ME" : $"0x{unchecked((uint)_fellowshipTracker.LeaderId):X8}")} | Open: {_fellowshipTracker.IsOpen} | Locked: {_fellowshipTracker.IsLocked} | ShareXP: {_fellowshipTracker.ShareXP}"); + + int index = 0; + foreach (string memberName in _fellowshipTracker.GetMemberNames()) + { + int memberId = _fellowshipTracker.GetMemberId(index); + bool isLeader = memberId == _fellowshipTracker.LeaderId; + ChatLine($"[RynthAi] [{index}] {memberName} (0x{unchecked((uint)memberId):X8}){(isLeader ? " [LEADER]" : "")}"); + index++; + } + } + + private string FindFellowshipMemberNameById(int memberId) + { + if (_fellowshipTracker == null || memberId == 0) + return "(unknown)"; + + int index = 0; + foreach (string memberName in _fellowshipTracker.GetMemberNames()) + { + if (_fellowshipTracker.GetMemberId(index) == memberId) + return memberName; + + index++; + } + + return "(unknown)"; + } + + private bool TryResolveCorpseForDiagnostics(string selector, out WorldObject? corpse, out string source) + { + corpse = null; + source = string.Empty; + if (_objectCache == null || _playerId == 0) + return false; + + if ((string.IsNullOrEmpty(selector) || selector == "target") && + _currentTargetId != 0 && + IsCorpseLikeObject(unchecked((int)_currentTargetId))) + { + corpse = _objectCache[unchecked((int)_currentTargetId)]; + if (corpse != null) + { + source = "target"; + return true; + } + } + + if ((string.IsNullOrEmpty(selector) || selector == "open") && + _openedContainerId != 0 && + IsCorpseLikeObject(_openedContainerId)) + { + corpse = _objectCache[_openedContainerId]; + if (corpse != null) + { + source = "open"; + return true; + } + } + + if (selector == "target" || selector == "open") + return false; + + double maxMeters = GetCorpseApproachRangeMaxMeters(_dashboard?.Settings ?? new LegacyUi.LegacyUiSettings()); + if (TryFindNearestCorpseForDiagnostics(maxMeters, out corpse, out _)) + { + source = "nearest"; + return true; + } + + return false; + } + + private bool TryFindNearestCorpseForDiagnostics(double maxMeters, out WorldObject? corpse, out double distanceMeters) + { + corpse = null; + distanceMeters = double.MaxValue; + if (_objectCache == null || _playerId == 0) + return false; + + int playerId = unchecked((int)_playerId); + foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) + { + if (candidate.ObjectClass != AcObjectClass.Corpse) + continue; + + double dist = _objectCache.Distance(playerId, candidate.Id); + if (dist > maxMeters || dist >= distanceMeters) + continue; + + corpse = candidate; + distanceMeters = dist; + } + + return corpse != null; + } + + private void HandleCorpseOpenCommand() + { + var settings = _dashboard?.Settings; + if (settings == null || _objectCache == null || _playerId == 0) + { + ChatLine("[RynthAi] Corpse opening is not ready yet."); + return; + } + + if (_openedContainerId != 0) + { + ChatLine($"[RynthAi] A container is already open: 0x{(uint)_openedContainerId:X8}"); + return; + } + + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters)) + { + ChatLine("[RynthAi] No unopened corpse is within corpse max range."); + return; + } + + _targetCorpseId = corpse!.Id; + _corpseTargetSince = CorpseNowMs; + _lastCorpseOpenAttemptAt = 0; + ChatLine($"[RynthAi] Corpse target set to {corpse.Name} at {ConvertMetersToYards(distanceMeters):F1} yd."); + TickCorpseOpening(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs new file mode 100644 index 0000000..5112318 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.CreatureData; + +/// +/// 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. +/// +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 KnownSpellIds { get; set; } = new(); + + public int Samples { get; set; } + public string LastSeen { get; set; } = string.Empty; + public string Notes { get; set; } = string.Empty; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs new file mode 100644 index 0000000..d3ceb98 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthAi.CreatureData; + +/// +/// 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. +/// +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 _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. + } + } + } + + /// Persist if anything changed since last save. Cheap to call from a tick. + 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 + { + } + } + } + + /// Lookup by exact composite key. + public bool TryGet(string name, uint wcid, out CreatureProfile? profile) + { + lock (_lock) + { + return _byKey.TryGetValue(MakeKey(name, wcid), out profile); + } + } + + /// + /// Lookup by name only. Prefers an exact-name match with the highest sample count. + /// Returns false if no record matches. + /// + 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; + } + } + + /// Lookup by wcid (for UI joins). Returns the first profile with this Wcid. + 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; + } + + /// + /// Merge a new observation into the store. Fields with value 0 / empty are + /// ignored so partial samples don't clobber better data. + /// + 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(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; + } + } + + /// + /// Returns the lowest resist (the creature's weakest damage type). 1.0 means "no data". + /// + 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(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs new file mode 100644 index 0000000..a7d1967 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs @@ -0,0 +1,661 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace RynthCore.Plugin.RynthAi.CreatureData; + +/// +/// 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\<charName>\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|<wcid>|<name>|<hpToKill>|<samples> +/// M|<wcid>|<name>|<hp> (manual HP override) +/// D|<wcid>|<name>|<weaponId>|<element>|<tier>|<avgDamage>|<dmgSamples>|<avgCastsToKill>|<killSamples>|<critAvg>|<critSamples>|<nonCritAvg>|<nonCritSamples> +/// (The loader also accepts the older 9/10-field name-less / crit-less D rows so existing data carries over.) +/// +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 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 _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); + + /// Point the store at a character's folder and load its file. Safe to call again on character change. + 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. + } + } + } + + /// Persist if anything changed. Cheap to call from a tick. + 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 + { + } + } + } + + /// + /// Fold one observed cast's damage into the (weapon, wcid, element, tier) running + /// average, split by crit vs non-crit. comes from the + /// AttackerNotification crit flag (melee/missile) or the combat-log parse (magic). + /// + 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; + } + } + + /// + /// 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. + /// + 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; + } + } + + /// 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. + 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); + } + } + + /// 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. + 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; + } + } + + /// Average damage of one (weapon, element, tier) cast on this wcid. samples=0 when unlearned. + 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; + } + + /// Average number of (weapon, element, tier) casts to kill this wcid. killSamples=0 when unlearned (≈1 ⇒ one-shot). + 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; + } + + /// Learned total-damage-to-kill for this wcid, or 0 if not yet learned. + public double GetLearnedHp(uint wcid) + { + if (wcid == 0) return 0; + lock (_lock) + return _byWcid.TryGetValue(wcid, out var p) ? p.HpPool : 0; + } + + /// User-entered HP override for this wcid (0 = none). Authoritative when > 0. + public double GetManualHp(uint wcid) + { + if (wcid == 0) return 0; + lock (_lock) + return _byWcid.TryGetValue(wcid, out var p) ? p.HpManual : 0; + } + + /// Set (or clear, with hp <= 0) the manual HP override for a wcid. Persists on next save. + 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; + } + } + + /// User-picked weapon override for this wcid (0 = none, fall back to GetBestWeapon). + public uint GetManualWeapon(uint wcid) + { + if (wcid == 0) return 0; + lock (_lock) + return _byWcid.TryGetValue(wcid, out var p) ? p.WeaponManual : 0; + } + + /// Set (0 clears) the per-monster weapon override. Persists on next save. + 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; + } + } + + /// User-picked offhand override for this wcid (0 = none). Stored only — combat does not equip it. + public uint GetManualOffhand(uint wcid) + { + if (wcid == 0) return 0; + lock (_lock) + return _byWcid.TryGetValue(wcid, out var p) ? p.OffhandManual : 0; + } + + /// Set (0 clears) the per-monster offhand override. Persists on next save. + 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; + } + } + + /// + /// 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). + /// + 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(); + 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; + } + } + + /// 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. + public uint GetDefaultWeapon() + { + lock (_lock) return _defaultWeapon; + } + + public void SetDefaultWeapon(uint weaponId) + { + lock (_lock) { if (_defaultWeapon == weaponId) return; _defaultWeapon = weaponId; _dirty = true; } + } + + /// 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). + 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); + } + + /// Delete one learned (weapon, element, tier) row for a wcid. Drops the wcid entirely if nothing's left. + 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; + } + } + + /// Delete ALL learned history for a wcid (every weapon/spell + HP). For a character upgrade reset. + public bool DeleteWcid(uint wcid) + { + lock (_lock) + { + bool removed = _byWcid.Remove(wcid); + if (removed) _dirty = true; + return removed; + } + } + + /// + /// 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. + /// + 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; + } + } + + /// One learned row for the UI: a (wcid, weapon, element, tier) cast stat. + 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); + + /// Snapshot all learned rows for live display. Cheap; copies under lock. + public List Snapshot() + { + var list = new List(); + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs new file mode 100644 index 0000000..7c35b9e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs @@ -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 _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 + } + + /// + /// Called each tick when the macro is running. + /// Returns true if door interaction is blocking navigation. + /// + 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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs new file mode 100644 index 0000000..6261eee --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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 landblock, 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 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. +/// +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"); + + /// + /// 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. + /// + public static HashSet Load(uint landblockKey) + { + var set = new HashSet(); + 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; + } + + /// Landblock keys that have a persisted hazard file, ascending. Never throws. + public static List ListLandblocks() + { + var result = new List(); + 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; + } + + /// Number of hazard cells recorded for a landblock (0 if none). Never throws. + public static int Count(uint landblockKey) => Load(landblockKey).Count; + + /// Removes a single cell from a landblock's persisted set. Never throws. + 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(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 { } + } + + /// Deletes the persisted hazards for one landblock. Never throws. + public static void Clear(uint landblockKey) + { + try + { + string path = PathFor(landblockKey); + if (File.Exists(path)) File.Delete(path); + } + catch { } + } + + /// Deletes every persisted-hazard file. Never throws. + public static void ClearAll() + { + try + { + if (!Directory.Exists(Folder)) return; + foreach (string path in Directory.GetFiles(Folder, "*.txt")) + File.Delete(path); + } + catch { } + } + + /// + /// 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. + /// + 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(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 */ } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs new file mode 100644 index 0000000..6c207df --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs @@ -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? _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 _surfTexCache = new(); + + // Per-landblock computed hazard-cell set (recomputed when the texture set changes). + private static uint _cachedLandblock; + private static HashSet? _cachedCells; + + // ── Hazard-texture set (persistent, user-editable) ───────────────────────── + + private static HashSet Textures() + { + // caller holds _gate + if (_hazardTextures != null) return _hazardTextures; + var set = new HashSet(); + 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 ListHazardTextures() + { + lock (_gate) { var l = new List(Textures()); l.Sort(); return l; } + } + + /// Flags a texture id as hazardous, persists it, and invalidates the cell cache. True if newly added. + 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; + } + } + + /// Unflags a texture id, persists, and invalidates the cell cache. True if it was present. + 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 + { + "# 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).", + }; + var sorted = new List(_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 */ } + } + + /// Drops the in-memory set + cell cache so the next query reloads from disk (after a hand-edit). + public static void Reload() + { + lock (_gate) { _hazardTextures = null; _cachedCells = null; _cachedLandblock = 0; } + } + + public static void InvalidateCells() + { + lock (_gate) { _cachedCells = null; _cachedLandblock = 0; } + } + + // ── Surface resolution ───────────────────────────────────────────────────── + + /// + /// 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. + /// + 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; + } + + /// Reads an EnvCell's surface palette → (surfIdx, OrigTextureId) pairs. For diagnostics. Never throws. + 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; + } + + /// Distinct non-zero OrigTextureIds present in an EnvCell's surface palette. Never throws. + private static HashSet CellTextureSet(DatDatabase? cellDat, DatDatabase? portal, uint cellId) + { + var set = new HashSet(); + foreach (var (_, texId) in GetCellSurfaces(cellDat, portal, cellId)) + if (texId != 0) set.Add(texId); + return set; + } + + // ── Per-landblock hazard-cell computation ────────────────────────────────── + + /// + /// 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. + /// + public static HashSet ComputeHazardCells(uint landblockKey, DatDatabase? cellDat, DatDatabase? portal) + { + lock (_gate) + if (_cachedCells != null && _cachedLandblock == landblockKey) return _cachedCells; + + var cells = new HashSet(); + 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) ─────────────────────────────── + + /// + /// 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. + /// + public static List LearnFromCell(uint cellId, DatDatabase? cellDat, DatDatabase? portal, + double rareFractionMax = 0.25) + { + var learned = new List(); + try + { + if (cellDat == null || portal == null) return learned; + uint landblockKey = cellId >> 16; + + var freq = new Dictionary(); + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs new file mode 100644 index 0000000..cae39e2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs @@ -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 +// 2. NearestCell(graph, ns, ew) → snap a position to the nearest node +// 3. FindPath(start, goal, graph) → A*, returns ordered List +// 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 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? _cachedGraph; + + /// Returns the cached graph for the landblock, rebuilding if stale. + public static Dictionary 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 ────────────────────────────────────────────────── + + /// + /// 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 + /// + private static Dictionary BuildGraph(uint landblockKey, DatDatabase cellDat) + { + var nodes = new Dictionary(); + + 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(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 ──────────────────────────────────────────────────────── + + /// + /// 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). + /// + public static uint NearestCell(Dictionary 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; + } + + /// + /// 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. + /// + public static uint NearestSafeCell( + Dictionary graph, uint fromCell, + IReadOnlySet 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* ─────────────────────────────────────────────────────────────────── + + /// + /// Finds the shortest portal-connected path from startCell to goalCell, + /// skipping any edge classified as a drop by IsDropEdge and any neighbor cell + /// in (lava / acid pools, etc.). + /// Returns ordered List of cell IDs, or empty if unreachable. + /// + public static List FindPath( + uint startCell, uint goalCell, + Dictionary graph, + IReadOnlySet? hazardCells = null) + { + if (!graph.ContainsKey(startCell) || !graph.ContainsKey(goalCell)) + return new List(); + if (startCell == goalCell) + return new List { startCell }; + + var goalNode = graph[goalCell]; + var gScore = new Dictionary { [startCell] = 0.0 }; + var cameFrom = new Dictionary(); + var open = new PriorityQueue(); + var closed = new HashSet(); + + 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(); + } + + 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 Reconstruct(Dictionary cameFrom, uint goal) + { + var path = new List(); + uint cur = goal; + while (true) { path.Add(cur); if (!cameFrom.TryGetValue(cur, out cur)) break; } + path.Reverse(); + return path; + } + + // ── Route construction ─────────────────────────────────────────────────── + + /// + /// 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. + /// + public static NavRouteParser BuildNavRoute( + List cellPath, + Dictionary 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; + + /// + /// 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). + /// + private static HashSet GetMainRouteNodes( + Dictionary graph, uint startCell, + IReadOnlySet? 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(); + var queue = new Queue(); + 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(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(); + 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; + } + + /// + /// Generates a Circular patrol route over the dungeon's main route (the cells from + /// ). + /// + /// 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. + /// + public static NavRouteParser BuildPatrolRoute( + Dictionary graph, + uint startCell, + IReadOnlySet? 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>(); + var edges = new HashSet(); + 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(); 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 { walkStart }; + var remaining = new HashSet(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 graph, Dictionary> 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? BfsPath(Dictionary> adj, uint src, uint dst) + { + if (src == dst) return new List { src }; + var prev = new Dictionary(); + var seen = new HashSet { src }; + var q = new Queue(); + 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? BfsToUnusedEdge( + Dictionary> adj, uint src, HashSet remaining) + { + var prev = new Dictionary(); + var seen = new HashSet { src }; + var q = new Queue(); + 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> adj, uint cell, HashSet 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 RebuildPath(Dictionary prev, uint src, uint dst) + { + var path = new List { 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 ────────────────────────────────────────────── + + /// + /// 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. + /// + 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? 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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/GlobalUsings.cs b/Plugins/RynthCore.Plugin.RynthAi/GlobalUsings.cs new file mode 100644 index 0000000..9359b9f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/GlobalUsings.cs @@ -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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs new file mode 100644 index 0000000..6b89011 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs @@ -0,0 +1,231 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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). +/// +internal sealed class Jumper +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly Action _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 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; + } + } + +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs new file mode 100644 index 0000000..830076a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs @@ -0,0 +1,1304 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.Maps; +using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// +/// Dungeon map: uses physics floor polygons from the dat for accurate corner coverage. +/// Rasterise floor polygons into a typed 2D grid, then: +/// • Fill — merge grid rows into horizontal strips, draw AddRectFilled. +/// • Edges — emit a coloured line on every filled cell face bordering empty space. +/// +/// CellType colouring: +/// Flat → light-blue fill + light-blue edge +/// SlopeUp → green fill + green edge (avg vertex Z > layerZ) +/// SlopeDown → red fill + red edge (avg vertex Z < layerZ) +/// +internal sealed class DungeonMapUi +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private MainLogic? _raycast; + private WorldObjectCache? _objectCache; + + internal uint _cachedLandblock; + + internal enum CellType : byte { Flat = 0, SlopeUp = 1, SlopeDown = 2 } + + // Pre-built per Z-layer — internal so RynthRadarUi can share the cache. + internal Dictionary>? _outerEdges; + // Raw (unmerged) outer edges with source grid-cell coord, used by RynthRadarUi + // for per-cell visited-state coloring. + internal Dictionary>? _outerEdgesRaw; + internal Dictionary>? _fillStrips; + // Per-layer floor cell lookup used to build visited strips. + internal Dictionary>? _floorCells; + // Flat cells the player has walked through this session (grid coords at GridCell resolution). + private readonly HashSet<(int gx, int gy)> _visitedCells = new(); + internal List? _zLayers; + // Per-layer D3D9 textures: fill + edges baked in, O(1) vertices per layer. + internal Dictionary? _layerTextures; + // Visited flat cells merged into strips — rebuilt only when _visitedCells grows, + // so drawing stays O(strips) not O(cells). Shared with RynthRadarUi. + internal Dictionary>? _visitedFillStrips; + private int _lastVisitedCount = -1; + internal int _autoLayerIdx; + /// Force the landblock cache to be built. Used by RynthRadarUi to share walls/fills. + internal void EnsureCache(uint landblock) + { + if (landblock != _cachedLandblock || _outerEdges is null) + RefreshMap(landblock); + } + + internal int BestLayerIdxFor(float playerZ) => BestLayerIdx(playerZ); + + private readonly HashSet _visibleLayers = new(); + + private float _zoom = 5.0f; + private Vector2 _pan; + private bool _autoFollow = true; + private bool _show1U1D = true; // show current floor ± 1 (default) + private bool _open = true; + private bool _autoHidden; // true when we auto-hid the map because player went outdoors + public bool IsAutoHidden => _autoHidden; + + // Toggle-stabilisation: when toolbar is visible we track both the full window + // rect and the canvas rect. On hide we snap the window to the canvas rect so + // it sits exactly over the map area; on show we restore the full window rect. + private bool _prevHideToolbar; + private Vector2 _fullWindowPos; // window pos when toolbar is visible + private Vector2 _fullWindowSize; // window size when toolbar is visible + private Vector2 _canvasPos; // canvas top-left when toolbar is visible + private Vector2 _canvasSize; // canvas size when toolbar is visible + + // Edge colours + private static readonly uint ColBg = ImGui.ColorConvertFloat4ToU32(new Vector4(0.04f, 0.07f, 0.12f, 1.00f)); + private static readonly uint ColBorder = ImGui.ColorConvertFloat4ToU32(new Vector4(0.20f, 0.30f, 0.40f, 1.00f)); + private static readonly uint ColFlat = ImGui.ColorConvertFloat4ToU32(new Vector4(0.55f, 0.80f, 1.00f, 1.00f)); + private static readonly uint ColSlopeUp = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.35f, 0.25f, 1.00f)); // red — leads to higher floor + private static readonly uint ColSlopeDown = ImGui.ColorConvertFloat4ToU32(new Vector4(0.25f, 1.00f, 0.35f, 1.00f)); // green — leads to lower floor + private static readonly uint ColPlayer = ImGui.ColorConvertFloat4ToU32(new Vector4(0.20f, 1.00f, 0.40f, 1.00f)); + private static readonly uint ColPortal = ImGui.ColorConvertFloat4ToU32(new Vector4(0.90f, 0.45f, 1.00f, 1.00f)); // purple + private static readonly uint ColPortalRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.75f, 1.00f, 0.70f)); + private static readonly uint ColPortalLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.88f, 1.00f, 1.00f)); + private static readonly uint ColDoor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.75f, 0.55f, 0.25f, 1.00f)); // tan + private static readonly uint ColDoorRing = ImGui.ColorConvertFloat4ToU32(new Vector4(0.90f, 0.75f, 0.50f, 0.70f)); + private static readonly uint ColDoorLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(0.95f, 0.85f, 0.65f, 1.00f)); + private static readonly uint ColMonster = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.25f, 0.20f, 1.00f)); // red + private static readonly uint ColMonsterRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.55f, 0.50f, 0.70f)); + private static readonly uint ColNpc = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.85f, 0.20f, 1.00f)); // yellow-gold + private static readonly uint ColNpcRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.95f, 0.55f, 0.70f)); + private static readonly uint ColCreatureLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.90f, 0.90f, 1.00f)); + // Fill colours (semi-transparent) + private static readonly uint ColFlatFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.18f, 0.55f, 0.22f, 0.40f)); // green — unvisited + private static readonly uint ColFlatFillVisited = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.42f, 0.58f, 0.72f)); // slate blue — visited + private static readonly uint ColSlopeUpFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.55f, 0.12f, 0.08f, 0.40f)); + private static readonly uint ColSlopeDownFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.10f, 0.50f, 0.15f, 0.40f)); + + private const float GridCell = 0.5f; + private const float FloorNormalThreshold = 0.4f; // |Nz|/|N| — must exceed to be floor-like + private const float FlatNormalThreshold = 0.95f; // |Nz|/|N| — must exceed to be flat (not a ramp) + private const byte NotFloor = 255; // sentinel returned by ClassifyPoly + + /// Called immediately whenever a map setting is changed by the user. + public Action? OnSettingChanged { get; set; } + + public DungeonMapUi(RynthCoreHost host, LegacyUiSettings settings) { _host = host; _settings = settings; } + + public void SetWorldObjectCache(WorldObjectCache cache) => _objectCache = cache; + + public void SetRaycast(MainLogic raycast) + { + _raycast = raycast; + _outerEdges = null; + _fillStrips = null; + _floorCells = null; + _visitedCells.Clear(); + _cachedLandblock = 0; + } + + public void Render() + { + // Check indoor/outdoor before creating the ImGui window. + // Auto-hide when outdoors (or in portalspace), auto-show when returning indoors. + bool isIndoor = false; + if (_host.HasGetPlayerPose && _host.TryGetPlayerPose( + out uint preCellId, out _, out _, out _, out _, out _, out _, out _)) + { + isIndoor = (preCellId & 0xFFFF) >= 0x100 && (preCellId >> 16) != 0; + } + + if (!isIndoor) + { + if (!_autoHidden) + { + _autoHidden = true; + DashWindows.ShowDungeonMap = false; + } + return; + } + + if (_autoHidden) + { + _autoHidden = false; + _open = true; + DashWindows.ShowDungeonMap = true; + } + + // Snapshot map-specific settings so we can detect changes and save immediately. + bool snapDoors = _settings.MapShowDoors; + bool snapCreatures = _settings.MapShowCreatures; + bool snapToolbar = _settings.MapShowToolbar; + float snapOpacity = _settings.MapBgOpacity; + bool snapRotate = _settings.MapRotateWithPlayer; + + float op = _settings.MapBgOpacity; + bool hideToolbar = !_settings.MapShowToolbar; + + // FirstUseEver must come BEFORE any Always override — each SetNextWindowSize call + // overwrites the previous one, so Always must be last to win. + ImGui.SetNextWindowSize(new Vector2(480, 520), ImGuiCond.FirstUseEver); + + // On toggle: snap the window to the canvas rect (hide) or full window rect (show). + bool stateChanged = hideToolbar != _prevHideToolbar; + _prevHideToolbar = hideToolbar; + if (stateChanged) + { + if (hideToolbar && _canvasSize.X > 0) + { + // Shrink to exactly where the canvas was — no title bar / toolbar chrome. + ImGui.SetNextWindowPos(_canvasPos, ImGuiCond.Always); + ImGui.SetNextWindowSize(_canvasSize, ImGuiCond.Always); + } + else if (!hideToolbar && _fullWindowSize.X > 0) + { + // Restore the full window including toolbar and title bar. + ImGui.SetNextWindowPos(_fullWindowPos, ImGuiCond.Always); + ImGui.SetNextWindowSize(_fullWindowSize, ImGuiCond.Always); + } + } + + // Remove border and padding when toolbar is hidden so no empty chrome is visible. + int styleVarCount = 0; + if (hideToolbar) + { + ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + styleVarCount = 2; + } + + // Apply opacity to title bar colours too — SetNextWindowBgAlpha only covers the content area. + var titleCol = new Vector4(0.08f, 0.12f, 0.18f, op); + ImGui.PushStyleColor(ImGuiCol.TitleBg, titleCol); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.10f, 0.16f, 0.24f, op)); + + ImGui.SetNextWindowBgAlpha(op); + + ImGuiWindowFlags flags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + if (hideToolbar) flags |= ImGuiWindowFlags.NoTitleBar; + + bool beginVisible = ImGui.Begin("Dungeon Map##RynthAiDungeonMap", ref _open, flags); + if (styleVarCount > 0) ImGui.PopStyleVar(styleVarCount); + ImGui.PopStyleColor(2); + + if (!beginVisible) { ImGui.End(); return; } + if (!_open) { DashWindows.ShowDungeonMap = false; ImGui.End(); return; } + + // Track full window rect every frame when toolbar is visible. + if (!hideToolbar) + { + _fullWindowPos = ImGui.GetWindowPos(); + _fullWindowSize = ImGui.GetWindowSize(); + } + + if (_raycast is null || !_raycast.IsInitialized) + { + ImGui.TextDisabled(_raycast is null + ? "Raycasting not yet initialised — loading DAT files..." + : $"Raycasting failed: {_raycast.StatusMessage}"); + ImGui.End(); return; + } + + if (!_host.HasGetPlayerPose || !_host.TryGetPlayerPose( + out uint cellId, out float px, out float py, out float pz, + out _, out _, out _, out _)) + { ImGui.TextDisabled("Player position unavailable."); ImGui.End(); return; } + + // Indoor check already handled before window creation — this is a safety fallback. + if ((cellId & 0xFFFF) < 0x100) + { ImGui.End(); return; } + + uint landblock = cellId >> 16; + if (landblock != _cachedLandblock || _outerEdges is null) + RefreshMap(landblock); + + if (_outerEdges is null || _outerEdges.Count == 0) + { ImGui.TextDisabled($"No dungeon geometry for 0x{landblock:X4}."); ImGui.End(); return; } + + float gx = ((landblock >> 8) & 0xFF) * 192.0f; + float gy = (landblock & 0xFF) * 192.0f; + + if (!hideToolbar) + { + if (ImGui.SmallButton("^##tbToggle")) _settings.MapShowToolbar = false; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Hide settings"); + ImGui.SameLine(0, 8); + RenderToolbar(pz); + } + + RenderCanvas(px + gx, py + gy, pz, hideToolbar); + + // Save immediately when any map setting changes. + if (_settings.MapShowDoors != snapDoors || + _settings.MapShowCreatures != snapCreatures || + _settings.MapShowToolbar != snapToolbar || + _settings.MapRotateWithPlayer != snapRotate || + MathF.Abs(_settings.MapBgOpacity - snapOpacity) > 0.001f) + { + OnSettingChanged?.Invoke(); + } + + ImGui.End(); + } + + // ── Data refresh ───────────────────────────────────────────────────────── + + private void RefreshMap(uint landblock) + { + _cachedLandblock = landblock; + _pan = Vector2.Zero; + _outerEdges = null; + _outerEdgesRaw = null; + _fillStrips = null; + _floorCells = null; + _visitedFillStrips = null; + _visitedCells.Clear(); + _lastVisitedCount = -1; + if (_layerTextures is not null) + { + foreach (var t in _layerTextures.Values) t.Dispose(); + _layerTextures = null; + } + + var los = _raycast?.GeometryLoader?.DungeonLOS; + if (los is null) return; + + // Physics floor polygons for rasterisation; render polys for portal bridges + var floorPolys = los.GetDungeonMapFloorPolygons(landblock); + var portalPolys = los.GetDungeonMapPolygons(landblock); + if (floorPolys.Count == 0 && portalPolys.Count == 0) return; + + var zSet = new SortedSet(); + foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); + foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); + _zLayers = new List(zSet); + + _autoLayerIdx = 0; + _visibleLayers.Clear(); + if (_show1U1D) + { + _visibleLayers.Add(0); + if (_zLayers.Count > 1) _visibleLayers.Add(1); + } + else + { + for (int i = 0; i < _zLayers.Count; i++) _visibleLayers.Add(i); + } + + _outerEdges = new Dictionary>(_zLayers.Count); + _fillStrips = new Dictionary>(_zLayers.Count); + + const float LayerTol = 1.0f; + + foreach (float layerZ in _zLayers) + { + var filled = new Dictionary<(int, int), CellType>(); + + foreach (var poly in floorPolys) + { + if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; + var verts = poly.Vertices; + if (verts == null || verts.Length < 3) continue; + + CellType type = ClassifyPoly(verts, layerZ); + if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases + + RasterizeXY(verts, filled, type); + } + + // ── Portal gap-closing (width-matched bridges) ─────────────── + // For each pair of portals within 5 units, fill a rectangle + // bridge between them. Width = actual doorway opening derived + // from the portal polygon's larger XY bounding-box dimension. + { + var portals = new List<(float cx, float cy, float halfW)>(); + var pDedup = new HashSet<(int, int)>(); + foreach (var poly in portalPolys) + { + if (!poly.IsPortal) continue; + if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; + var verts = poly.Vertices; + if (verts == null || verts.Length < 3) continue; + float cx = 0, cy = 0; + float xMin = verts[0].X, xMax = verts[0].X; + float yMin = verts[0].Y, yMax = verts[0].Y; + for (int k = 0; k < verts.Length; k++) + { + cx += verts[k].X; cy += verts[k].Y; + if (verts[k].X < xMin) xMin = verts[k].X; + if (verts[k].X > xMax) xMax = verts[k].X; + if (verts[k].Y < yMin) yMin = verts[k].Y; + if (verts[k].Y > yMax) yMax = verts[k].Y; + } + cx /= verts.Length; cy /= verts.Length; + float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f; + halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide + if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy)))) + portals.Add((cx, cy, halfW)); + } + + const float ConnectDist = 5f; + + for (int a = 0; a < portals.Count; a++) + for (int b = a + 1; b < portals.Count; b++) + { + float ddx = portals[b].cx - portals[a].cx; + float ddy = portals[b].cy - portals[a].cy; + float distSq = ddx * ddx + ddy * ddy; + if (distSq > ConnectDist * ConnectDist) continue; + + float dist = MathF.Sqrt(distSq); + float hw = MathF.Max(portals[a].halfW, portals[b].halfW); + + // Normalised A→B direction, then perpendicular scaled by half-width + float normDx = dist > 0.001f ? ddx / dist : 1f; + float normDy = dist > 0.001f ? ddy / dist : 0f; + float perpX = -normDy * hw; + float perpY = normDx * hw; + + float pax = portals[a].cx, pay = portals[a].cy; + float pbx = portals[b].cx, pby = portals[b].cy; + + // 4 corners of the bridge quad + float c0x = pax - perpX, c0y = pay - perpY; + float c1x = pax + perpX, c1y = pay + perpY; + float c2x = pbx + perpX, c2y = pby + perpY; + float c3x = pbx - perpX, c3y = pby - perpY; + + float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x)); + float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x)); + float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y)); + float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y)); + + int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell); + int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell); + int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell); + int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell); + + for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++) + for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++) + { + float testX = (gcx2 + 0.5f) * GridCell; + float testY = (gcy2 + 0.5f) * GridCell; + if (PointInConvexQuad(testX, testY, + c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y)) + { + var key = (gcx2, gcy2); + if (!filled.ContainsKey(key)) filled[key] = CellType.Flat; + } + } + } + } + + if (filled.Count == 0) continue; + + // Snapshot the typed cell grid so RynthRadarUi can look up per-cell type for visited coloring. + (_floorCells ??= new())[layerZ] = new Dictionary<(int, int), CellType>(filled); + + // ── Outer edges ────────────────────────────────────────────── + var outer = new List<(float, float, float, float, CellType)>(filled.Count * 2); + var outerRaw = new List<(float, float, float, float, CellType, int, int)>(filled.Count * 2); + foreach (var ((gx, gy), type) in filled) + { + float x0 = gx * GridCell, y0 = gy * GridCell; + float x1 = x0 + GridCell, y1 = y0 + GridCell; + + if (!filled.ContainsKey((gx + 1, gy))) { outer.Add((x1, y0, x1, y1, type)); outerRaw.Add((x1, y0, x1, y1, type, gx, gy)); } + if (!filled.ContainsKey((gx - 1, gy))) { outer.Add((x0, y0, x0, y1, type)); outerRaw.Add((x0, y0, x0, y1, type, gx, gy)); } + if (!filled.ContainsKey((gx, gy + 1))) { outer.Add((x0, y1, x1, y1, type)); outerRaw.Add((x0, y1, x1, y1, type, gx, gy)); } + if (!filled.ContainsKey((gx, gy - 1))) { outer.Add((x0, y0, x1, y0, type)); outerRaw.Add((x0, y0, x1, y0, type, gx, gy)); } + } + if (outer.Count > 0) _outerEdges[layerZ] = MergeEdges(outer); + if (outerRaw.Count > 0) (_outerEdgesRaw ??= new())[layerZ] = outerRaw; + + // ── Fill strips: merge cells → horizontal rows → vertical columns ─ + var rows = new Dictionary>(filled.Count / 4); + foreach (var ((gx, gy), type) in filled) + { + if (!rows.TryGetValue(gy, out var row)) + rows[gy] = row = new List<(int, CellType)>(); + row.Add((gx, type)); + } + + // Horizontal merge: contiguous cells of same type in each row → one strip + var hStrips = new List<(float x0, float y0, float x1, float y1, CellType type)>(rows.Count * 2); + foreach (var (gy, row) in rows) + { + row.Sort((a, b) => a.gx.CompareTo(b.gx)); + float y0 = gy * GridCell, y1 = y0 + GridCell; + int i = 0; + while (i < row.Count) + { + CellType stripType = row[i].type; + int cur = i + 1; + while (cur < row.Count + && row[cur].gx == row[cur - 1].gx + 1 + && row[cur].type == stripType) + cur++; + hStrips.Add((row[i].gx * GridCell, y0, (row[cur - 1].gx + 1) * GridCell, y1, stripType)); + i = cur; + } + } + + // Vertical merge: rows with identical X extents and type → one tall rect + var colMap = new Dictionary<(int x0s, int x1s, CellType), List<(float y0, float y1)>>(); + foreach (var (x0, y0, x1, y1, type) in hStrips) + { + int x0s = (int)MathF.Round(x0 / GridCell); + int x1s = (int)MathF.Round(x1 / GridCell); + var key = (x0s, x1s, type); + if (!colMap.TryGetValue(key, out var lst)) colMap[key] = lst = new(); + lst.Add((y0, y1)); + } + + var strips = new List<(float, float, float, float, CellType)>(colMap.Count * 2); + foreach (var ((x0s, x1s, type), lst) in colMap) + { + lst.Sort((a, b) => a.y0.CompareTo(b.y0)); + float rx0 = x0s * GridCell, rx1 = x1s * GridCell; + int i = 0; + while (i < lst.Count) + { + float y0 = lst[i].y0, y1 = lst[i].y1; + while (i + 1 < lst.Count && lst[i + 1].y0 <= y1 + 0.001f) + y1 = MathF.Max(y1, lst[++i].y1); + strips.Add((rx0, y0, rx1, y1, type)); + i++; + } + } + if (strips.Count > 0) _fillStrips[layerZ] = strips; + } + + // ── Per-layer floor textures (fill + edges baked, O(1) vertices each) ── + if (_floorCells is not null && _host.D3DDevice != IntPtr.Zero) + { + var texDict = new Dictionary(_floorCells.Count); + foreach (var (lz, cells) in _floorCells) + { + int idx = _zLayers!.IndexOf(lz); + var tex = DungeonMapTexture.GetOrBuild(_host.D3DDevice, cells, landblock, idx); + if (tex != null) texDict[lz] = tex; + } + _layerTextures = texDict.Count > 0 ? texDict : null; + } + } + + // Reduce a colour to ~25 % opacity for non-current-floor rendering. + // ImGui packs colours as 0xAABBGGRR; the alpha is in bits 31–24. + private static uint DimCol(uint c) => + ((uint)((c >> 24 & 0xFF) * 0.25f) << 24) | (c & 0x00FFFFFFu); + + // Merge collinear/adjacent axis-aligned edge segments into the fewest possible lines. + // A 10-unit straight wall built from 20 half-unit grid edges becomes 1 line. + private static List<(float ax, float ay, float bx, float by, CellType type)> MergeEdges( + List<(float ax, float ay, float bx, float by, CellType type)> edges) + { + // Bucket horizontal (ay==by) by (ySnap, type) → list of x intervals + // Bucket vertical (ax==bx) by (xSnap, type) → list of y intervals + var hBuckets = new Dictionary<(int ySnap, CellType), List<(float lo, float hi)>>(); + var vBuckets = new Dictionary<(int xSnap, CellType), List<(float lo, float hi)>>(); + + foreach (var (ax, ay, bx, by, type) in edges) + { + if (MathF.Abs(ay - by) < 0.001f) // horizontal + { + int ySnap = (int)MathF.Round(ay / GridCell); + if (!hBuckets.TryGetValue((ySnap, type), out var lst)) + hBuckets[(ySnap, type)] = lst = new(); + lst.Add((MathF.Min(ax, bx), MathF.Max(ax, bx))); + } + else // vertical + { + int xSnap = (int)MathF.Round(ax / GridCell); + if (!vBuckets.TryGetValue((xSnap, type), out var lst)) + vBuckets[(xSnap, type)] = lst = new(); + lst.Add((MathF.Min(ay, by), MathF.Max(ay, by))); + } + } + + var result = new List<(float, float, float, float, CellType)>(hBuckets.Count + vBuckets.Count); + + foreach (var ((ySnap, type), lst) in hBuckets) + { + lst.Sort((a, b) => a.lo.CompareTo(b.lo)); + float ay = ySnap * GridCell; + int i = 0; + while (i < lst.Count) + { + float lo = lst[i].lo, hi = lst[i].hi; + while (i + 1 < lst.Count && lst[i + 1].lo <= hi + 0.001f) + hi = MathF.Max(hi, lst[++i].hi); + result.Add((lo, ay, hi, ay, type)); + i++; + } + } + + foreach (var ((xSnap, type), lst) in vBuckets) + { + lst.Sort((a, b) => a.lo.CompareTo(b.lo)); + float ax = xSnap * GridCell; + int i = 0; + while (i < lst.Count) + { + float lo = lst[i].lo, hi = lst[i].hi; + while (i + 1 < lst.Count && lst[i + 1].lo <= hi + 0.001f) + hi = MathF.Max(hi, lst[++i].hi); + result.Add((ax, lo, ax, hi, type)); + i++; + } + } + + return result; + } + + // Merge a set of flat visited grid cells into horizontal+vertical strips. + // Same algorithm as the main fill-strip builder; keeps vertex count O(strips) not O(cells). + internal static List<(float x0, float y0, float x1, float y1)> BuildVisitedStripsFrom( + IEnumerable<(int gx, int gy)> cells) + { + var rows = new Dictionary>(); + foreach (var (gx, gy) in cells) + { + if (!rows.TryGetValue(gy, out var row)) rows[gy] = row = new List(); + row.Add(gx); + } + if (rows.Count == 0) return new List<(float, float, float, float)>(); + + var hStrips = new List<(float x0, float y0, float x1, float y1)>(rows.Count * 2); + foreach (var (gy, row) in rows) + { + row.Sort(); + float y0 = gy * GridCell, y1 = y0 + GridCell; + int i = 0; + while (i < row.Count) + { + int cur = i + 1; + while (cur < row.Count && row[cur] == row[cur - 1] + 1) cur++; + hStrips.Add((row[i] * GridCell, y0, (row[cur - 1] + 1) * GridCell, y1)); + i = cur; + } + } + + var colMap = new Dictionary<(int x0s, int x1s), List<(float y0, float y1)>>(); + foreach (var (x0, y0, x1, y1) in hStrips) + { + int x0s = (int)MathF.Round(x0 / GridCell); + int x1s = (int)MathF.Round(x1 / GridCell); + var key = (x0s, x1s); + if (!colMap.TryGetValue(key, out var lst)) colMap[key] = lst = new(); + lst.Add((y0, y1)); + } + + var result = new List<(float, float, float, float)>(colMap.Count * 2); + foreach (var ((x0s, x1s), lst) in colMap) + { + lst.Sort((a, b) => a.y0.CompareTo(b.y0)); + float rx0 = x0s * GridCell, rx1 = x1s * GridCell; + int i = 0; + while (i < lst.Count) + { + float y0 = lst[i].y0, y1 = lst[i].y1; + while (i + 1 < lst.Count && lst[i + 1].y0 <= y1 + 0.001f) + y1 = MathF.Max(y1, lst[++i].y1); + result.Add((rx0, y0, rx1, y1)); + i++; + } + } + return result; + } + + private void RebuildVisitedStrips() + { + _lastVisitedCount = _visitedCells.Count; + if (_floorCells is null || _visitedCells.Count == 0 || _zLayers is null) + { + _visitedFillStrips = null; + return; + } + + var result = new Dictionary>(_zLayers.Count); + foreach (var (layerZ, cells) in _floorCells) + { + var flatVisited = new List<(int, int)>(); + foreach (var ((gx, gy), ctype) in cells) + if (ctype == CellType.Flat && _visitedCells.Contains((gx, gy))) + flatVisited.Add((gx, gy)); + if (flatVisited.Count == 0) continue; + var strips = BuildVisitedStripsFrom(flatVisited); + if (strips.Count > 0) result[layerZ] = strips; + } + _visitedFillStrips = result.Count > 0 ? result : null; + } + + // Classify a polygon as Flat / SlopeUp / SlopeDown, or NotFloor if vertical. + private static CellType ClassifyPoly(Raycasting.Vector3[] verts, float layerZ) + { + float nx = 0, ny = 0, nz = 0; + int n = verts.Length; + for (int i = 0; i < n; i++) + { + var a = verts[i]; + var b = verts[(i + 1) % n]; + nx += (a.Y - b.Y) * (a.Z + b.Z); + ny += (a.Z - b.Z) * (a.X + b.X); + nz += (a.X - b.X) * (a.Y + b.Y); + } + float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 0.0001f) return (CellType)NotFloor; + + float absNz = MathF.Abs(nz) / len; + if (absNz < FloorNormalThreshold) return (CellType)NotFloor; + if (absNz >= FlatNormalThreshold) return CellType.Flat; + + // Slope — direction by average vertex Z vs layer Z + float avgZ = 0; + for (int i = 0; i < n; i++) avgZ += verts[i].Z; + avgZ /= n; + return avgZ > layerZ + 0.3f ? CellType.SlopeUp : CellType.SlopeDown; + } + + // Scanline-rasterise a polygon's XY footprint into the typed grid. + // Vertex cells are explicitly marked first to cover degenerate thin polygons. + // Flat (0) beats slope if a cell already has a type. + private static void RasterizeXY(Raycasting.Vector3[] verts, Dictionary<(int, int), CellType> filled, CellType type) + { + int n = verts.Length; + + // ── Scanline fill ───────────────────────────────────────────────── + float minY = verts[0].Y, maxY = verts[0].Y; + for (int i = 1; i < n; i++) + { + if (verts[i].Y < minY) minY = verts[i].Y; + if (verts[i].Y > maxY) maxY = verts[i].Y; + } + + int gyMin = (int)MathF.Floor(minY / GridCell); + int gyMax = (int)MathF.Ceiling(maxY / GridCell); + + var xs = new List(n); + + for (int gy = gyMin; gy < gyMax; gy++) + { + float scanY = (gy + 0.5f) * GridCell; + xs.Clear(); + + for (int i = 0; i < n; i++) + { + float ay = verts[i].Y, ax = verts[i].X; + float by = verts[(i + 1) % n].Y, bx = verts[(i + 1) % n].X; + + if ((ay <= scanY && by > scanY) || (by <= scanY && ay > scanY)) + xs.Add(ax + (scanY - ay) / (by - ay) * (bx - ax)); + } + + if (xs.Count < 2) continue; + xs.Sort(); + + for (int i = 0; i + 1 < xs.Count; i += 2) + { + int gxMin = (int)MathF.Floor(xs[i] / GridCell); + int gxMax = (int)MathF.Ceiling(xs[i + 1] / GridCell); + for (int gx = gxMin; gx < gxMax; gx++) + { + var key = (gx, gy); + if (!filled.TryGetValue(key, out var existing) || type < existing) + filled[key] = type; + } + } + } + } + + // Returns true if (px,py) is inside the convex quad (a→b→c→d). + // Works for both CW and CCW winding by checking all cross-products share a sign. + private static bool PointInConvexQuad( + float px, float py, + float ax, float ay, float bx, float by, + float cx, float cy, float dx, float dy) + { + static float Cross(float ox, float oy, float ex, float ey, float ptx, float pty) + => (ex - ox) * (pty - oy) - (ey - oy) * (ptx - ox); + + float s0 = Cross(ax, ay, bx, by, px, py); + float s1 = Cross(bx, by, cx, cy, px, py); + float s2 = Cross(cx, cy, dx, dy, px, py); + float s3 = Cross(dx, dy, ax, ay, px, py); + + return (s0 >= 0f && s1 >= 0f && s2 >= 0f && s3 >= 0f) || + (s0 <= 0f && s1 <= 0f && s2 <= 0f && s3 <= 0f); + } + + private int BestLayerIdx(float playerZ) + { + if (_zLayers is null || _zLayers.Count == 0) return 0; + int best = 0; float bestDist = float.MaxValue; + for (int i = 0; i < _zLayers.Count; i++) + { + float d = MathF.Abs(_zLayers[i] - playerZ); + if (d < bestDist) { bestDist = d; best = i; } + } + return best; + } + + // ── Toolbar ────────────────────────────────────────────────────────────── + + // Returns true if the last-drawn item's right edge + gap + nextWidth fits before the window's right edge. + private static bool FitsOnLine(float nextWidth, float gap = 8f) + { + float itemRight = ImGui.GetItemRectMax().X; + float windowRight = ImGui.GetWindowPos().X + ImGui.GetWindowSize().X + - ImGui.GetStyle().WindowPadding.X; + return itemRight + gap + nextWidth < windowRight; + } + + private void RenderToolbar(float playerZ) + { + // ── 1U1D toggle ─────────────────────────────────────────────────── + bool was1U1D = _show1U1D; + if (was1U1D) + { + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.70f, 1.0f)); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.20f, 0.58f, 0.88f, 1.0f)); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.10f, 0.34f, 0.58f, 1.0f)); + } + if (ImGui.SmallButton("1U1D##1u1d")) + { + _show1U1D = !_show1U1D; + if (_show1U1D && _zLayers is not null) + { + _visibleLayers.Clear(); + if (_autoLayerIdx > 0) _visibleLayers.Add(_autoLayerIdx - 1); + _visibleLayers.Add(_autoLayerIdx); + if (_autoLayerIdx < _zLayers.Count - 1) _visibleLayers.Add(_autoLayerIdx + 1); + } + } + if (was1U1D) ImGui.PopStyleColor(3); + + // ── Floor buttons ───────────────────────────────────────────────── + if (_zLayers is not null && _zLayers.Count > 1) + { + float floorsWidth = 52f + _zLayers.Count * 26f + 60f; // "Floors:" + Fn buttons + All/Here + if (FitsOnLine(floorsWidth, 10f)) ImGui.SameLine(0, 10); + + ImGui.Text("Floors:"); + ImGui.SameLine(); + for (int i = 0; i < _zLayers.Count; i++) + { + if (i > 0) ImGui.SameLine(); + bool on = _visibleLayers.Contains(i); + bool isCurrent = i == _autoLayerIdx; + if (on && isCurrent) + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.65f, 0.30f, 1.0f)); + else if (on) + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.70f, 1.0f)); + if (ImGui.SmallButton($"F{i + 1}##floor{i}")) + { + _show1U1D = false; + if (on) _visibleLayers.Remove(i); else _visibleLayers.Add(i); + } + if (on) ImGui.PopStyleColor(); + } + ImGui.SameLine(0, 6); + if (ImGui.SmallButton("All##floorAll")) + { + _show1U1D = false; + _visibleLayers.Clear(); + for (int i = 0; i < _zLayers.Count; i++) _visibleLayers.Add(i); + } + ImGui.SameLine(); + if (ImGui.SmallButton("Here##floorHere")) + { + _show1U1D = false; + _visibleLayers.Clear(); + _visibleLayers.Add(BestLayerIdx(playerZ)); + } + } + + // ── Zoom ────────────────────────────────────────────────────────── + if (FitsOnLine(130f, 12f)) ImGui.SameLine(0, 12); + ImGui.Text("Zoom:"); + ImGui.SameLine(); + ImGui.SetNextItemWidth(80); + ImGui.SliderFloat("##mapzoom", ref _zoom, 1.0f, 20.0f, "%.1fx"); + if (!float.IsFinite(_zoom)) _zoom = 5.0f; + + // ── Follow / Rotate / Reset ─────────────────────────────────────── + if (FitsOnLine(180f, 12f)) ImGui.SameLine(0, 12); + ImGui.Checkbox("Follow##mapfollow", ref _autoFollow); + ImGui.SameLine(0, 6); + ImGui.Checkbox("Rotate##maprotate", ref _settings.MapRotateWithPlayer); + ImGui.SameLine(0, 6); + if (ImGui.SmallButton("Reset##mapreset")) + { _pan = Vector2.Zero; _zoom = 5.0f; _autoFollow = true; _show1U1D = true; } + + // ── Doors / Creatures ───────────────────────────────────────────── + if (FitsOnLine(148f, 12f)) ImGui.SameLine(0, 12); + ImGui.Checkbox("Doors##mapDoors", ref _settings.MapShowDoors); + ImGui.SameLine(0, 6); + ImGui.Checkbox("Creatures##mapCreatures", ref _settings.MapShowCreatures); + + // ── Opacity ─────────────────────────────────────────────────────── + if (FitsOnLine(130f, 12f)) ImGui.SameLine(0, 12); + ImGui.Text("Opacity:"); + ImGui.SameLine(0, 4); + ImGui.SetNextItemWidth(70); + ImGui.SliderFloat("##mapOpacity", ref _settings.MapBgOpacity, 0f, 1f, "%.2f"); + _settings.MapBgOpacity = Math.Clamp(_settings.MapBgOpacity, 0f, 1f); + + } + + // ── Canvas ──────────────────────────────────────────────────────────────── + + private void RenderCanvas(float playerWX, float playerWY, float playerZ, bool showExpandBtn = false) + { + Vector2 canvasSize = ImGui.GetContentRegionAvail(); + if (canvasSize.X < 50 || canvasSize.Y < 50) return; + + Vector2 origin = ImGui.GetCursorScreenPos(); + + // Record canvas screen rect while toolbar is visible so we can snap to it on hide. + if (!showExpandBtn) + { + _canvasPos = origin; + _canvasSize = canvasSize; + } + Vector2 centre = origin + canvasSize * 0.5f; + + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + + // Only the canvas background scales with opacity — fills and edges stay full colour. + uint colBgDyn = SetAlpha(ColBg, _settings.MapBgOpacity); + + dl.AddRectFilled(origin, origin + canvasSize, colBgDyn); + dl.AddRect(origin, origin + canvasSize, ColBorder); + dl.PushClipRect(origin, origin + canvasSize, true); + + if (_autoFollow) _pan = Vector2.Zero; + + if (_zLayers is not null) + { + int best = BestLayerIdx(playerZ); + if (best != _autoLayerIdx) + { + _autoLayerIdx = best; + if (_show1U1D) + { + _visibleLayers.Clear(); + if (best > 0) _visibleLayers.Add(best - 1); + _visibleLayers.Add(best); + if (best < _zLayers.Count - 1) _visibleLayers.Add(best + 1); + } + else if (_autoFollow) { _visibleLayers.Clear(); _visibleLayers.Add(best); } + } + } + + Span visZ = stackalloc float[_zLayers?.Count ?? 0]; + int visCount = 0; + if (_zLayers is not null) + foreach (int idx in _visibleLayers) + if (idx >= 0 && idx < _zLayers.Count) + visZ[visCount++] = _zLayers[idx]; + + float cxMin = origin.X, cxMax = origin.X + canvasSize.X; + float cyMin = origin.Y, cyMax = origin.Y + canvasSize.Y; + const float Margin = 20f; + + float currentLayerZ = (_zLayers is not null && _autoLayerIdx < _zLayers.Count) + ? _zLayers[_autoLayerIdx] : float.NaN; + + bool rotate = _settings.MapRotateWithPlayer; + float sinH = 0f, cosH = 1f; + if (rotate && _host.HasGetPlayerHeading && _host.TryGetPlayerHeading(out float mapHeading)) + { + float hRad = mapHeading * MathF.PI / 180f; + sinH = MathF.Sin(hRad); + cosH = MathF.Cos(hRad); + } + + // ── Paint visited flat cells under player each frame ───────────── + if (!float.IsNaN(currentLayerZ)) + { + const int PaintRadius = 2; + int pgx = (int)MathF.Floor(playerWX / GridCell); + int pgy = (int)MathF.Floor(playerWY / GridCell); + for (int dy = -PaintRadius; dy <= PaintRadius; dy++) + for (int dx = -PaintRadius; dx <= PaintRadius; dx++) + _visitedCells.Add((pgx + dx, pgy + dy)); + } + + // Rebuild visited strips only when new cells were added — O(cells) once, O(1) each frame. + if (_visitedCells.Count != _lastVisitedCount) + RebuildVisitedStrips(); + + // ── Floor texture (fill + edges baked, O(1) vertices per layer) ── + // Falls back to fill-strip geometry when texture creation failed. + if (_layerTextures is not null) + { + for (int vi = 0; vi < visCount; vi++) + { + if (!_layerTextures.TryGetValue(visZ[vi], out var tex)) continue; + if (tex.TexId == IntPtr.Zero) continue; + bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f; + uint tint = isCurrent ? 0xFFFFFFFFu : 0x40FFFFFFu; + + // Project the four world corners of the texture (NW/NE/SE/SW) + var pNW = Project(tex.WorldX0, tex.WorldY1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var pNE = Project(tex.WorldX1, tex.WorldY1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var pSE = Project(tex.WorldX1, tex.WorldY0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var pSW = Project(tex.WorldX0, tex.WorldY0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + + float qxMin = MathF.Min(MathF.Min(pNW.X, pNE.X), MathF.Min(pSE.X, pSW.X)); + float qxMax = MathF.Max(MathF.Max(pNW.X, pNE.X), MathF.Max(pSE.X, pSW.X)); + float qyMin = MathF.Min(MathF.Min(pNW.Y, pNE.Y), MathF.Min(pSE.Y, pSW.Y)); + float qyMax = MathF.Max(MathF.Max(pNW.Y, pNE.Y), MathF.Max(pSE.Y, pSW.Y)); + if (qxMax < cxMin - Margin || qxMin > cxMax + Margin || + qyMax < cyMin - Margin || qyMin > cyMax + Margin) continue; + + // UV: NW=(0,0), NE=(1,0), SE=(1,1), SW=(0,1) (row 0 = northernmost = top of texture) + dl.AddImageQuad(tex.TexId, pNW, pNE, pSE, pSW, + new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f), tint); + } + } + else if (_fillStrips is not null) + { + for (int vi = 0; vi < visCount; vi++) + { + if (!_fillStrips.TryGetValue(visZ[vi], out var strips)) continue; + bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f; + + foreach (var (x0, y0, x1, y1, type) in strips) + { + var fp00 = Project(x0, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var fp10 = Project(x1, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var fp11 = Project(x1, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var fp01 = Project(x0, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + float fxMin = MathF.Min(fp00.X, MathF.Min(fp10.X, MathF.Min(fp11.X, fp01.X))); + float fxMax = MathF.Max(fp00.X, MathF.Max(fp10.X, MathF.Max(fp11.X, fp01.X))); + float fyMin = MathF.Min(fp00.Y, MathF.Min(fp10.Y, MathF.Min(fp11.Y, fp01.Y))); + float fyMax = MathF.Max(fp00.Y, MathF.Max(fp10.Y, MathF.Max(fp11.Y, fp01.Y))); + + if (fxMax < cxMin - Margin || fxMin > cxMax + Margin || + fyMax < cyMin - Margin || fyMin > cyMax + Margin) continue; + + uint fillCol = type switch + { + CellType.SlopeUp => ColSlopeUpFill, + CellType.SlopeDown => ColSlopeDownFill, + _ => ColFlatFill, + }; + if (!isCurrent) fillCol = DimCol(fillCol); + + if (rotate) dl.AddQuadFilled(fp00, fp10, fp11, fp01, fillCol); + else dl.AddRectFilled(new Vector2(fxMin, fyMin), new Vector2(fxMax, fyMax), fillCol); + } + } + } + + // ── Visited flat cell overlay (current floor only, drawn as merged strips) ── + // Uses _visitedFillStrips (rebuilt lazily) to keep vertex count O(strips), not O(cells). + if (_visitedFillStrips is not null && !float.IsNaN(currentLayerZ) + && _visitedFillStrips.TryGetValue(currentLayerZ, out var visitedStrips)) + { + foreach (var (x0, y0, x1, y1) in visitedStrips) + { + var vp00 = Project(x0, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var vp10 = Project(x1, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var vp11 = Project(x1, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var vp01 = Project(x0, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + float vxMin = MathF.Min(vp00.X, MathF.Min(vp10.X, MathF.Min(vp11.X, vp01.X))); + float vxMax = MathF.Max(vp00.X, MathF.Max(vp10.X, MathF.Max(vp11.X, vp01.X))); + float vyMin = MathF.Min(vp00.Y, MathF.Min(vp10.Y, MathF.Min(vp11.Y, vp01.Y))); + float vyMax = MathF.Max(vp00.Y, MathF.Max(vp10.Y, MathF.Max(vp11.Y, vp01.Y))); + + if (vxMax < cxMin - Margin || vxMin > cxMax + Margin || + vyMax < cyMin - Margin || vyMin > cyMax + Margin) continue; + + if (rotate) dl.AddQuadFilled(vp00, vp10, vp11, vp01, ColFlatFillVisited); + else dl.AddRectFilled(new Vector2(vxMin, vyMin), new Vector2(vxMax, vyMax), ColFlatFillVisited); + } + } + + // ── Outer edges (fallback only — skipped when textures are available) ── + if (_layerTextures is null && _outerEdges is not null) + { + for (int vi = 0; vi < visCount; vi++) + { + if (!_outerEdges.TryGetValue(visZ[vi], out var edges)) continue; + bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f; + + foreach (var (ax, ay, bx, by, type) in edges) + { + var ep0 = Project(ax, ay, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + var ep1 = Project(bx, by, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + + if (MathF.Max(ep0.X, ep1.X) < cxMin - Margin || MathF.Min(ep0.X, ep1.X) > cxMax + Margin || + MathF.Max(ep0.Y, ep1.Y) < cyMin - Margin || MathF.Min(ep0.Y, ep1.Y) > cyMax + Margin) + continue; + + uint col = type switch + { + CellType.SlopeUp => ColSlopeUp, + CellType.SlopeDown => ColSlopeDown, + _ => ColFlat, + }; + if (!isCurrent) col = DimCol(col); + + dl.AddLine(ep0, ep1, col, 1.5f); + } + } + } + + // ── Teleport portals ────────────────────────────────────────────── + if (_objectCache != null && _host.HasGetObjectPosition && _host.HasGetItemType) + { + const uint TypePortal = 0x10000u; + const uint STypePortalDest = 38u; + float gxLB = ((_cachedLandblock >> 8) & 0xFF) * 192f; + float gyLB = (_cachedLandblock & 0xFF) * 192f; + + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + // Static GUIDs only (portals/lifestones are below 0x80000000) + if ((uint)wo.Id >= 0x80000000u) continue; + if (!_host.TryGetItemType((uint)wo.Id, out uint flags)) continue; + if ((flags & TypePortal) == 0) continue; + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint portalCellId, + out float portalX, out float portalY, out _)) continue; + if ((portalCellId >> 16) != _cachedLandblock) continue; + + float worldX = portalX + gxLB; + float worldY = portalY + gyLB; + var ps = Project(worldX, worldY, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + float psx = ps.X, psy = ps.Y; + + if (psx < cxMin - 20 || psx > cxMax + 20 || + psy < cyMin - 20 || psy > cyMax + 20) continue; + + var psc = new Vector2(psx, psy); + dl.AddCircleFilled(psc, 5f, ColPortal); + dl.AddCircle(psc, 7f, ColPortalRing, 12, 1.5f); + + string label = wo.Name; + if (_host.TryGetObjectStringProperty((uint)wo.Id, STypePortalDest, out string dest) + && !string.IsNullOrEmpty(dest)) + label = dest.Length > 22 ? dest.Substring(0, 22) + "…" : dest; + dl.AddText(new Vector2(psx + 9f, psy - 7f), ColPortalLabel, label); + } + } + + // ── Doors ───────────────────────────────────────────────────────── + if (_settings.MapShowDoors && _objectCache != null && _host.HasGetObjectPosition) + { + float gxLBd = ((_cachedLandblock >> 8) & 0xFF) * 192f; + float gyLBd = (_cachedLandblock & 0xFF) * 192f; + + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + if ((uint)wo.Id >= 0x80000000u) continue; + if (!IsDoorName(wo.Name)) continue; + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint dCellId, + out float dox, out float doy, out _)) continue; + if ((dCellId >> 16) != _cachedLandblock) continue; + + float dwx = dox + gxLBd; + float dwy = doy + gyLBd; + var ds = Project(dwx, dwy, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + float dsx = ds.X, dsy = ds.Y; + + if (dsx < cxMin - 20 || dsx > cxMax + 20 || + dsy < cyMin - 20 || dsy > cyMax + 20) continue; + + // Diamond symbol + const float Dr = 5.0f; + dl.AddQuadFilled( + new Vector2(dsx, dsy - Dr), + new Vector2(dsx + Dr, dsy), + new Vector2(dsx, dsy + Dr), + new Vector2(dsx - Dr, dsy), + ColDoor); + dl.AddQuad( + new Vector2(dsx, dsy - Dr - 1.5f), + new Vector2(dsx + Dr + 1.5f, dsy), + new Vector2(dsx, dsy + Dr + 1.5f), + new Vector2(dsx - Dr - 1.5f, dsy), + ColDoorRing, 1.2f); + dl.AddText(new Vector2(dsx + 8f, dsy - 7f), ColDoorLabel, wo.Name.Length > 20 ? wo.Name[..20] + "…" : wo.Name); + } + } + + // ── Creatures & NPCs ────────────────────────────────────────────── + if (_settings.MapShowCreatures && _objectCache != null && _host.HasGetObjectPosition) + { + const uint STypeCreatureType = 2u; + const int CreatureTypeNpc = 14; + bool canQueryCreatureType = _host.HasGetObjectIntProperty; + float gxLBc = ((_cachedLandblock >> 8) & 0xFF) * 192f; + float gyLBc = (_cachedLandblock & 0xFF) * 192f; + + foreach (var wo in _objectCache.GetLandscape()) + { + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cCellId, + out float cox, out float coy, out _)) continue; + if ((cCellId >> 16) != _cachedLandblock) continue; + + float cwx = cox + gxLBc; + float cwy = coy + gyLBc; + var csp = Project(cwx, cwy, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH); + float csx = csp.X, csy = csp.Y; + + if (csx < cxMin - 20 || csx > cxMax + 20 || + csy < cyMin - 20 || csy > cyMax + 20) continue; + + bool isNpc = canQueryCreatureType + && _host.TryGetObjectIntProperty((uint)wo.Id, STypeCreatureType, out int ct) + && ct == CreatureTypeNpc; + + var csc = new Vector2(csx, csy); + if (isNpc) + { + dl.AddCircleFilled(csc, 4f, ColNpc); + dl.AddCircle(csc, 6f, ColNpcRing, 10, 1.2f); + } + else + { + dl.AddCircleFilled(csc, 4f, ColMonster); + dl.AddCircle(csc, 6f, ColMonsterRing, 10, 1.0f); + } + + string clabel = wo.Name.Length > 20 ? wo.Name[..20] + "…" : wo.Name; + dl.AddText(new Vector2(csx + 7f, csy - 7f), ColCreatureLabel, clabel); + } + } + + // ── Player dot + heading ────────────────────────────────────────── + var playerScreen = new Vector2(centre.X + _pan.X, centre.Y + _pan.Y); + dl.AddCircleFilled(playerScreen, 4.0f, ColPlayer); + + if (_host.HasGetPlayerHeading && _host.TryGetPlayerHeading(out float heading)) + { + Vector2 tip; + if (rotate) + { + // Map rotates with player — heading arrow always points up. + tip = playerScreen + new Vector2(0f, -10f); + } + else + { + float rad = heading * MathF.PI / 180.0f; + tip = playerScreen + new Vector2(MathF.Cos(rad) * 10f, -MathF.Sin(rad) * 10f); + } + dl.AddLine(playerScreen, tip, ColPlayer, 1.5f); + } + + dl.PopClipRect(); + + // Expand button rendered BEFORE InvisibleButton so ImGui gives it + // input priority over the canvas drag area. SetCursorScreenPos is + // restored afterward so InvisibleButton still covers the full canvas. + if (showExpandBtn) + { + ImGui.SetCursorScreenPos(origin + new Vector2(4, 4)); + if (ImGui.SmallButton("v##tbToggle")) _settings.MapShowToolbar = true; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Show settings"); + ImGui.SetCursorScreenPos(origin); + } + + // InvisibleButton captures mouse so the window title-bar drag handler + // never sees the click — prevents the window from moving when panning. + ImGui.InvisibleButton("##mapcanvas", canvasSize); + + // Tell the backend to block mouse events from reaching the game when + // the cursor is over the canvas (fixes click-through to AC world). + bool hovered = ImGui.IsItemHovered(); + if (hovered) ImGui.SetNextFrameWantCaptureMouse(true); + + if (ImGui.IsItemActive() && ImGui.IsMouseDragging(ImGuiMouseButton.Left)) + { + Vector2 delta = ImGui.GetIO().MouseDelta; + if (float.IsFinite(delta.X) && float.IsFinite(delta.Y)) + { + _autoFollow = false; + _pan += delta; + } + } + + // Scroll-wheel zoom: check mouse position directly against canvas bounds. + // IsWindowHovered can return false if another item is active, so we bypass it. + { + float wheel = ImGui.GetIO().MouseWheel; + if (float.IsFinite(wheel) && wheel != 0f) + { + var mp = ImGui.GetIO().MousePos; + if (mp.X >= origin.X && mp.X <= origin.X + canvasSize.X && + mp.Y >= origin.Y && mp.Y <= origin.Y + canvasSize.Y) + { + _zoom = Math.Clamp(_zoom + wheel * 0.5f, 1.0f, 20.0f); + ImGui.SetNextFrameWantCaptureMouse(true); + } + } + } + } + + // Project a world point to canvas screen coords, optionally rotating around the player. + // AC convention: heading 0=east, 90=north (CCW from east). + // Rotate mode: player's forward direction points screen-up. + // screen_right = sinH*dx - cosH*dy + // screen_forward = cosH*dx + sinH*dy (negated for screen-Y, which increases downward) + // This matches RynthRadarUi.ProjectWorld exactly. + private static Vector2 Project(float wx, float wy, float playerWX, float playerWY, + Vector2 centre, float zoom, Vector2 pan, bool rotate, float sinH, float cosH) + { + float dx = wx - playerWX; + float dy = wy - playerWY; + if (rotate) + { + float rx = sinH * dx - cosH * dy; // screen-right + float ry = cosH * dx + sinH * dy; // screen-forward (screen-up = -ry) + dx = rx; dy = ry; + } + return new Vector2(centre.X + dx * zoom + pan.X, centre.Y - dy * zoom + pan.Y); + } + + // Sets the alpha byte of an ImGui ABGR colour to the given 0-1 value. + private static uint SetAlpha(uint col, float alpha) + { + uint a = (uint)(Math.Clamp(alpha, 0f, 1f) * 255f); + return (col & 0x00FFFFFF) | (a << 24); + } + + private static bool IsDoorName(string name) + { + if (string.IsNullOrEmpty(name)) return false; + return name.Contains("Door", StringComparison.OrdinalIgnoreCase) + || name.Contains("Gate", StringComparison.OrdinalIgnoreCase) + || name.Contains("Portcullis", StringComparison.OrdinalIgnoreCase) + || name.Contains("Hatch", StringComparison.OrdinalIgnoreCase) + || name.Contains("Trapdoor", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacuLuaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacuLuaUi.cs new file mode 100644 index 0000000..acf5102 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacuLuaUi.cs @@ -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? 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 _luaFiles = new(); + + private readonly string _selectedSnippetKey = "--- Select Snippet ---"; + private readonly Dictionary _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(); + } +} \ No newline at end of file diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs new file mode 100644 index 0000000..0ab2a56 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -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; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardDrawing.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardDrawing.cs new file mode 100644 index 0000000..408638f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardDrawing.cs @@ -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; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs new file mode 100644 index 0000000..ad74247 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -0,0 +1,3112 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Linq; +using System.Numerics; +using System.Text.Json; +using ImGuiNET; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Meta; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +internal sealed class LegacyDashboardRenderer +{ + internal static readonly Vector4 ColTeal = new(0.15f, 0.85f, 0.90f, 1.00f); + internal static readonly Vector4 ColAmber = new(0.91f, 0.70f, 0.20f, 1.00f); + internal static readonly Vector4 ColGreen = new(0.25f, 0.85f, 0.45f, 1.00f); + internal static readonly Vector4 ColTextDim = new(0.85f, 0.90f, 0.95f, 1.00f); + internal static readonly Vector4 ColTextMute = new(0.55f, 0.65f, 0.75f, 1.00f); + internal static readonly Vector4 ColHp = new(0.85f, 0.20f, 0.20f, 1.00f); + internal static readonly Vector4 ColMana = new(0.15f, 0.55f, 0.95f, 1.00f); + internal static readonly Vector4 ColBarBg = new(0.08f, 0.12f, 0.16f, 1.00f); + internal static readonly Vector4 ColPanelBg = new(0.04f, 0.07f, 0.10f, 0.95f); + internal static readonly Vector4 ColBtnOn = new(0.15f, 0.30f, 0.35f, 1.00f); + internal static readonly Vector4 ColBtnFill = new(0.06f, 0.12f, 0.18f, 1.00f); + internal static readonly Vector4 ColBtnHov = new(0.10f, 0.18f, 0.25f, 1.00f); + internal static readonly Vector4 ColBtnAct = new(0.08f, 0.15f, 0.22f, 1.00f); + internal static readonly Vector4 ColBtnBord = new(0.15f, 0.25f, 0.35f, 1.00f); + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings = new(); + public LegacyUiSettings Settings => _settings; + + /// Set by the plugin so the meta bridge JSON can carry a live + /// MetaManager snapshot for the panel's debug surface (§3.4). + internal Func? MetaSnapshotProvider; + + // Meta commands arrive on the Avalonia dispatcher thread; applied on the + // plugin-tick thread (DrainMetaCommands) so mutation is serialised with + // MetaManager.Think instead of racing it. + private readonly System.Collections.Concurrent.ConcurrentQueue _metaCmdQueue = new(); + private readonly LegacyAdvancedSettingsUi _advancedSettingsUi; + private readonly LegacyNavigationUi _navigationUi; + private readonly LegacyLuaUi _luaUi; + private readonly LegacyWeaponsUi _weaponsUi; + private readonly LegacyMetaUi _metaUi; + private readonly LegacyMonstersUi _monstersUi; + public LegacyMonstersUi MonstersUi => _monstersUi; + private readonly DungeonMapUi _dungeonMapUi; + private readonly RynthRadarUi _rynthRadarUi; + private readonly RynthChatUi _rynthChatUi; + + private readonly List _profiles = new(); + private readonly List _navFiles = new(); + private readonly List _lootFiles = new(); + private readonly List _metaFiles = new(); + // Guards the four profile-name lists above against the cross-thread race + // between BuildSnapshotJson (Avalonia panel poll thread, ~30 Hz) and the + // Refresh*Files mutators (AC pump thread). Enumerating a List while + // another thread Clear()s it throws InvalidOperationException; when that + // escaped the snapshot poll's reverse-P/Invoke boundary it fail-fasted the + // NativeAOT runtime. Copy-under-lock on read; lock the Clear+AddRange swap. + private readonly object _profileListsLock = new(); + private readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + private readonly string _lootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + private readonly string _metaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + private readonly string _settingsRoot = @"C:\Games\RynthSuite\RynthAi\SettingsProfiles\ACEmulator"; + private readonly string _monstersFolder = @"C:\Games\RynthSuite\RynthAi\MonsterProfiles"; + + private int _selectedNavIdx; + private bool _isMinimized; + private bool _isLocked; + private bool _wasMinimized; + private float _bgOpacity = 0.95f; + + public bool CloseRequested { get; internal set; } + + /// Wired by RynthAiPlugin to forward force-rebuff / cancel requests to BuffManager. + public Action? OnForceRebuffRequested { get; set; } + public Action? OnCancelForceRebuffRequested { get; set; } + + // ── Per-character settings persistence ─────────────────────────────────── + private string _charFolder = string.Empty; + private string _settingsFilePath = string.Empty; + private string _lastSavedJson = string.Empty; + private int _saveCheckCounter; + private const int SaveCheckIntervalFrames = 1; // check every frame for immediate save + + private Vector2 _lastWindowPos = new(-1, -1); + private bool _windowPosRestored; + private bool _windowSizeRestored; + private Vector2 _expandedSize = new(430, 452); + private string _targetLabel = "NO TARGET"; + private float _targetHealthPercent; + private string _targetHealthDisplay = "0"; + private uint _targetHealth; + private uint _targetMaxHealth; + private uint _targetStamina; + private uint _targetMaxStamina; + private uint _targetMana; + private uint _targetMaxMana; + private uint _currentTargetId; + private uint _playerHealth; + private uint _playerMaxHealth; + private uint _playerStamina; + private uint _playerMaxStamina; + private uint _playerMana; + private uint _playerMaxMana; + + // ── Session kills for the status feed (kills/hour). The other stats (xp/lum/deaths/vitae) + // are read engine-side (PrefetchPlayerStats) and written to the status file directly — the + // off-thread plugin pump can't do those main-thread AC reads. ── + private DateTime _sessionStartUtc = DateTime.UtcNow; + private long _sessionKills; // Interlocked: incremented on the pump thread, read in the snapshot + private double _killsPerHour; + private long _lastKillTicks; // DateTime.UtcNow.Ticks of the last kill (0 = none yet this session) + // volatile: written on the pump thread (SetFreeSlots/SetComponentCounts), read on the snapshot-poll + // thread (BuildSnapshotJson). x86 int writes are atomic but give no visibility guarantee — without + // volatile the reader can see a stale value indefinitely. (_sessionKills uses Interlocked for the same reason.) + private volatile int _freeSlots = -1; // main-pack empty slots; -1 = unknown. Pushed from the plugin tick. + private volatile int _scarabs = -1; // total scarab spell components in inventory; -1 = unknown. + private volatile int _tapers = -1; // total prismatic tapers in inventory; -1 = unknown. + // Per-tier scarab breakdown (name -> count), pushed from the pump thread as a fresh immutable array; + // volatile ref so the snapshot-poll thread always sees the latest (ref assignment is atomic). + private volatile KeyValuePair[] _scarabsByType = System.Array.Empty>(); + // Equipped gear with full appraisal, pushed from the pump thread; volatile ref. + private volatile EquipAppraisal[] _equipment = System.Array.Empty(); + + // D2 three-tier target telemetry + D6 attack-cast/kill ratio, pushed from the pump thread + // (SetScanCounts/SetCastStats) and read on the snapshot-poll thread — volatile for visibility + // (same rationale as _freeSlots above). -1 = no scan yet this session. + private volatile int _scanTotal = -1; // monsters the client renders this scan + private volatile int _scanRing = -1; // of those, within engage range + private volatile int _scanPossible = -1; // of those, surviving all combat filters (attack candidates) + private volatile int _scanLosBlocked = -1; // in-range + attackable but wall-blocked (LOS) + private volatile int _sessionAttackCasts; // offensive combat casts issued this session + private volatile int _castsSinceLastKill; // offensive casts since the last credited kill (orphan signal) + + // Full read-only inventory for the remote viewer (P1), pushed from the pump thread; volatile refs. + // Kept OUT of BuildSnapshotJson (the 150ms hot path) — served by its own RynthPluginGetInventoryJson + // export so 100s of items never ride the status snapshot. _inventoryVersion bumps on each rescan. + private volatile InventoryItemSnapshot[] _invItems = System.Array.Empty(); + private volatile InventoryContainerSnapshot[] _invContainers = System.Array.Empty(); + private int _inventoryVersion; // Interlocked: bumped on write, read in BuildInventoryJson + + // ── Monster editor (external process) ──────────────────────────────────── + // Deep-audit finding #10 (2026-06-18): System.Diagnostics.Process is the + // documented H6 hazard — HasExited/CloseMainWindow/Process.Start's + // handle-touching accessors silently AV this host under NativeAOT in + // injected x86 acclient.exe (the engine already abandoned this API for + // OpenProcess/GetExitCodeProcess in PluginLoader.IsPidAliveWin32 for the + // identical reason). Runs synchronously on the ImGui/game thread from the + // "External Editor" button. Replaced with ShellExecuteExW (retaining the + // process handle via SEE_MASK_NOCLOSEPROCESS) + Win32 liveness/close. + private FileSystemWatcher? _monsterWatcher; + private volatile bool _monsterFileChanged; + private IntPtr _monsterEditorProcessHandle = IntPtr.Zero; + private int _monsterEditorPid; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct SHELLEXECUTEINFOW + { + public int cbSize; + public uint fMask; + public IntPtr hwnd; + public string? lpVerb; + public string? lpFile; + public string? lpParameters; + public string? lpDirectory; + public int nShow; + public IntPtr hInstApp; + public IntPtr lpIDList; + public string? lpClass; + public IntPtr hkeyClass; + public uint dwHotKey; + public IntPtr hIconOrMonitor; + public IntPtr hProcess; + } + + private const uint SeeMaskNoCloseProcess = 0x00000040; + private const int SwShowNormal = 1; + private const uint WaitTimeout = 0x00000102; + private const uint WmClose = 0x0010; + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool ShellExecuteExW(ref SHELLEXECUTEINFOW lpExecInfo); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr hObject); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); + + [DllImport("user32.dll")] + private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr hWnd); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); + + /// Finds the first visible top-level window owned by the given PID (mirrors what + /// Process.CloseMainWindow does internally) so WM_CLOSE can be posted without touching + /// System.Diagnostics.Process. + private static IntPtr FindMainWindowForPid(int pid) + { + IntPtr found = IntPtr.Zero; + EnumWindows((hWnd, _) => + { + GetWindowThreadProcessId(hWnd, out uint wndPid); + if (wndPid == (uint)pid && IsWindowVisible(hWnd)) + { + found = hWnd; + return false; // stop enumerating + } + return true; + }, IntPtr.Zero); + return found; + } + + /// Releases the tracked Monster Editor process handle, if any. Call on plugin + /// Shutdown so the handle isn't leaked if the editor is still open when RynthAi unloads. + public void ReleaseMonsterEditorHandle() + { + if (_monsterEditorProcessHandle != IntPtr.Zero) + { + CloseHandle(_monsterEditorProcessHandle); + _monsterEditorProcessHandle = IntPtr.Zero; + _monsterEditorPid = 0; + } + } + + public LegacyDashboardRenderer(RynthCoreHost host) + { + _host = host; + _advancedSettingsUi = new LegacyAdvancedSettingsUi(_settings); + _navigationUi = new LegacyNavigationUi(_settings, host); + _luaUi = new LegacyLuaUi(_settings, host); + _weaponsUi = new LegacyWeaponsUi(_settings, host); + _metaUi = new LegacyMetaUi(_settings, _navFiles); + _monstersUi = new LegacyMonstersUi( + _settings, + host, + onMonstersChanged: SaveMonstersFile, + onLaunchExternalEditor: LaunchMonsterEditor, + getCurrentTarget: GetCurrentTargetForMonsterAdd); + _dungeonMapUi = new DungeonMapUi(host, _settings); + _dungeonMapUi.OnSettingChanged = SaveSettings; + _rynthRadarUi = new RynthRadarUi(host, _settings); + _rynthRadarUi.OnSettingChanged = SaveSettings; + _rynthRadarUi.SetMapData(_dungeonMapUi); + _rynthChatUi = new RynthChatUi(host, _settings); + _rynthChatUi.OnSettingChanged = SaveSettings; + RefreshAllLists(); + } + + public void OnLoginComplete() + { + RefreshAllLists(); + ResetSessionStats(); + } + + /// + /// Returns the current per-character folder (set during LoadSettings). + /// Empty string until a character has logged in. + /// + public string CharFolder => _charFolder; + + public void SetWorldFilter(WorldObjectCache cache) => _weaponsUi.SetWorldFilter(cache); + + public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr); + + public void SetRaycast(Raycasting.MainLogic raycast) + { + _dungeonMapUi.SetRaycast(raycast); + _rynthRadarUi.SetRaycast(raycast); + } + + public void PushChatLine(string? text, int chatType) => _rynthChatUi.Push(text, chatType); + + /// Set the handler invoked when the user submits a line from the + /// custom chat widget. Wired by the plugin so slash commands can be routed + /// through OnChatBarEnter before falling back to InvokeChatParser. + public Action? ChatSubmitHandler + { + get => _rynthChatUi.OnSubmit; + set => _rynthChatUi.OnSubmit = value; + } + public void SetWorldObjectCache(WorldObjectCache cache) + { + _dungeonMapUi.SetWorldObjectCache(cache); + _rynthRadarUi.SetWorldObjectCache(cache); + } + + // ── Settings persistence ───────────────────────────────────────────────── + + public void LoadSettings(string charName) + { + if (string.IsNullOrWhiteSpace(charName)) return; + + string safeChar = SanitizeFileName(charName); + _charFolder = Path.Combine(_settingsRoot, safeChar); + + // Migrate legacy settings.json → Default.json if needed + string legacyPath = Path.Combine(_charFolder, "settings.json"); + string defaultProfilePath = GetProfileFilePath("Default"); + if (!File.Exists(defaultProfilePath) && File.Exists(legacyPath)) + { + try { File.Copy(legacyPath, defaultProfilePath); } catch { } + } + + // Determine which profile was last active + string activeProfile = ReadActiveProfile(); + _settingsFilePath = GetProfileFilePath(activeProfile); + + // Fall back to Default if the profile file is missing + if (!File.Exists(_settingsFilePath)) + { + activeProfile = "Default"; + _settingsFilePath = GetProfileFilePath(activeProfile); + } + + if (File.Exists(_settingsFilePath)) + { + try + { + string json = File.ReadAllText(_settingsFilePath); + var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + if (loaded != null) + { + CopySettings(loaded, _settings); + _lastSavedJson = json; + } + } + catch { } + } + + _settings.SelectedProfile = activeProfile; + ApplyUiStateFromSettings(); + + _settings.IsMacroRunning = _settings.StartMacroOnLogin; + _settings.CurrentState = "Default"; + _settings.BotAction = "Default"; + + // Reload nav route from saved path + if (!string.IsNullOrEmpty(_settings.CurrentNavPath) && File.Exists(_settings.CurrentNavPath)) + { + try + { + _settings.CurrentRoute = NavRouteParser.Load(_settings.CurrentNavPath); + _settings.ActiveNavIndex = + (_settings.CurrentRoute.RouteType == NavRouteType.Follow || + _settings.CurrentRoute.RouteType == NavRouteType.Once) + ? 0 + : FindNearestWaypoint(_settings.CurrentRoute); + } + catch { _settings.CurrentNavPath = string.Empty; } + } + + // Auto-reload embedded navs from the last loaded meta source so + // EmbedNav rules resolve after a restart without a manual reload. + if (_settings.EmbeddedNavs.Count == 0 && + !string.IsNullOrEmpty(_settings.CurrentMetaPath) && + File.Exists(_settings.CurrentMetaPath)) + { + try + { + string ext = Path.GetExtension(_settings.CurrentMetaPath).ToLowerInvariant(); + LoadedMeta reload = ext == ".met" + ? MetFileParser.Load(_settings.CurrentMetaPath) + : ext == ".af" + ? AfFileParser.Load(_settings.CurrentMetaPath) + : new LoadedMeta(); + foreach (var kvp in reload.EmbeddedNavs) + _settings.EmbeddedNavs[kvp.Key] = kvp.Value; + } + catch { } + } + + _windowPosRestored = false; // will apply saved position on next render + _windowSizeRestored = false; // force size restore on first render after load + RefreshAllLists(); + + // Load MonsterRules from monsters.json (overrides what was in the profile) + // and migrate existing rules to that file if it doesn't exist yet. + MigrateMonstersToFile(); + LoadMonstersFromFile(); + // Always re-insert the catch-all "Default" rule at index 0; without it the + // combat system has no fallback weapon/damage selection for unmatched mobs. + _settings.EnsureDefaultRule(); + SetupMonsterWatcher(); + } + + public void SaveSettings() + { + if (string.IsNullOrEmpty(_settingsFilePath)) return; + try + { + CaptureTransientUiState(); + Directory.CreateDirectory(Path.GetDirectoryName(_settingsFilePath)!); + string json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); + File.WriteAllText(_settingsFilePath, json); + _lastSavedJson = json; + WriteActiveProfile(_settings.SelectedProfile); + } + catch { } + } + + public string SaveAsProfile(string name) + { + if (string.IsNullOrEmpty(_charFolder)) return "Not logged in."; + try + { + CaptureTransientUiState(); + Directory.CreateDirectory(_charFolder); + string json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); + string path = GetProfileFilePath(name); + File.WriteAllText(path, json); + _settings.SelectedProfile = name; + _settingsFilePath = path; + _lastSavedJson = json; + WriteActiveProfile(name); + RefreshProfilesList(); + return $"Saved profile '{name}'."; + } + catch (Exception ex) { return $"Save failed: {ex.Message}"; } + } + + public string LoadProfile(string name) + { + if (string.IsNullOrEmpty(_charFolder)) return "Not logged in."; + string path = GetProfileFilePath(name); + if (!File.Exists(path)) + return SaveAsProfile(name); + SwitchProfile(name); + return $"Loaded profile '{name}'."; + } + + /// + /// Render-independent autosave entry, driven from RynthAiPlugin.OnTick so + /// settings + the active-profile marker persist even when the in-AC ImGui + /// shell is disabled (EnableImGuiShell=false) and Render() never runs. + /// CheckAndSave self-throttles via a content hash, so this only touches disk + /// when something actually changed. + /// + public void TickAutoSave() => CheckAndSave(); + + private void CheckAndSave() + { + if (string.IsNullOrEmpty(_settingsFilePath)) return; + try + { + CaptureTransientUiState(); + string json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); + if (json != _lastSavedJson) + { + Directory.CreateDirectory(Path.GetDirectoryName(_settingsFilePath)!); + File.WriteAllText(_settingsFilePath, json); + _lastSavedJson = json; + WriteActiveProfile(_settings.SelectedProfile); + } + } + catch { } + } + + // ── monsters.json support ──────────────────────────────────────────────── + + private string MonstersFilePath + { + get + { + if (string.IsNullOrEmpty(_charFolder)) return string.Empty; + string charKey = Path.GetFileName(_charFolder); // e.g. "Toon Name" + return Path.Combine(_monstersFolder, charKey + ".json"); + } + } + + private string MonstersFilePathLegacy => string.IsNullOrEmpty(_charFolder) + ? string.Empty + : Path.Combine(_charFolder, "monsters.json"); + + /// + /// Moves any existing monsters.json from the old per-char settings folder into + /// the new MonsterProfiles folder, then seeds from in-memory rules if still absent. + /// + private void MigrateMonstersToFile() + { + string path = MonstersFilePath; + if (string.IsNullOrEmpty(path)) return; + + // Move legacy file if present and destination doesn't exist yet + string legacyPath = MonstersFilePathLegacy; + if (!string.IsNullOrEmpty(legacyPath) && File.Exists(legacyPath) && !File.Exists(path)) + { + try + { + Directory.CreateDirectory(_monstersFolder); + File.Move(legacyPath, path); + return; // moved; no need to seed from memory + } + catch { } + } + + if (File.Exists(path)) return; + if (_settings.MonsterRules.Count <= 1) return; // only Default, nothing to migrate + + try + { + Directory.CreateDirectory(_monstersFolder); + string json = JsonSerializer.Serialize(_settings.MonsterRules, RynthAiJsonContext.Default.MonsterRuleList); + File.WriteAllText(path, json); + } + catch { } + } + + /// Loads MonsterRules from monsters.json, overriding what came from the profile. + private void LoadMonstersFromFile() + { + string path = MonstersFilePath; + if (string.IsNullOrEmpty(path) || !File.Exists(path)) return; + try + { + string json = File.ReadAllText(path); + var rules = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList); + if (rules != null && rules.Count > 0) + _settings.MonsterRules = rules; + } + catch { } + } + + private void SetupMonsterWatcher() + { + _monsterWatcher?.Dispose(); + _monsterWatcher = null; + + string path = MonstersFilePath; + if (string.IsNullOrEmpty(path) || !Directory.Exists(_monstersFolder)) return; + + try + { + string charKey = Path.GetFileName(_charFolder); + _monsterWatcher = new FileSystemWatcher(_monstersFolder, charKey + ".json") + { + NotifyFilter = NotifyFilters.LastWrite, + EnableRaisingEvents = true + }; + _monsterWatcher.Changed += (_, _) => _monsterFileChanged = true; + } + catch { } + } + + /// + /// Call once per render frame. Hot-reloads MonsterRules when the external editor saves. + /// + public void TickMonsterReload() + { + if (!_monsterFileChanged) return; + _monsterFileChanged = false; + LoadMonstersFromFile(); + } + + /// Writes the in-memory MonsterRules to monsters.json so the external editor sees them. + private void SaveMonstersFile() + { + string path = MonstersFilePath; + if (string.IsNullOrEmpty(path)) return; + + try + { + // Suspend the watcher so our own write doesn't cause a redundant reload. + bool wasEnabled = false; + if (_monsterWatcher != null) + { + wasEnabled = _monsterWatcher.EnableRaisingEvents; + _monsterWatcher.EnableRaisingEvents = false; + } + + Directory.CreateDirectory(_monstersFolder); + string json = JsonSerializer.Serialize(_settings.MonsterRules, RynthAiJsonContext.Default.MonsterRuleList); + File.WriteAllText(path, json); + + if (_monsterWatcher != null) + _monsterWatcher.EnableRaisingEvents = wasEnabled; + } + catch { } + } + + // ── Radar bridge (used by the engine-side Avalonia radar panel) ───────── + /// + /// Builds a JSON snapshot for the Avalonia radar. Pass the engine's + /// currently-cached MapVersion (0 on first call); when it matches the live + /// landblock, walls/fills are omitted to keep the payload small. + /// + public string BuildRadarJson(uint engineKnownMapVersion) + => _rynthRadarUi.BuildSnapshotJson(engineKnownMapVersion); + + // ── Monsters bridge (used by the engine-side Avalonia MonstersPanel) ──── + /// + /// Builds a JSON payload describing the current MonsterRules + ItemRules + /// (for weapon/offhand picker) + currently-selected target name (for the + /// "Add Selected" button). Polled by the Avalonia panel. + /// + public string BuildMonstersJson() + { + try + { + var payload = new MonstersBridgePayload + { + Rules = _settings.MonsterRules ?? new List(), + Items = (_settings.ItemRules ?? new List()) + .Select(r => new MonsterBridgeItem { Id = r.Id, Name = r.Name }).ToList(), + CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty, + }; + + // Annotate each rule with captured creature data when available. + var store = CreatureLookupForRules; + if (store != null && payload.Rules.Count > 0) + { + foreach (var rule in payload.Rules) + { + if (string.IsNullOrEmpty(rule.Name)) continue; + var profile = store(rule.Name); + if (profile == null) continue; + var (weakType, weakVal) = CreatureData.CreatureProfileStore.GetWeakest(profile); + payload.Captured[rule.Name] = new MonsterCapturedInfo + { + MaxHealth = profile.MaxHealth, + ArmorLevel = profile.ArmorLevel, + WeakestType = weakType, + WeakestValue = weakVal, + Samples = profile.Samples, + }; + } + } + return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.MonstersBridgePayload); + } + catch + { + return "{\"rules\":[],\"items\":[],\"currentTargetName\":\"\",\"captured\":{}}"; + } + } + + /// Selectable weapons for the Damage-panel weapon/offhand pickers, as a JSON array + /// [{"id":..,"name":..}] from _settings.ItemRules — the same configured-weapons source the + /// Monsters tab's picker uses. Manual JSON (NativeAOT-trivial, no extra JsonContext type). + public string BuildCombatWeaponsJson() + { + try + { + var items = _settings.ItemRules ?? new List(); + var sb = new System.Text.StringBuilder(); + sb.Append('['); + bool first = true; + foreach (var it in items) + { + if (!first) sb.Append(','); + first = false; + sb.Append("{\"id\":").Append(it.Id).Append(",\"name\":").Append(JsonString(it.Name)).Append('}'); + } + sb.Append(']'); + return sb.ToString(); + } + catch { return "[]"; } + } + + private static string JsonString(string? s) + { + if (string.IsNullOrEmpty(s)) return "\"\""; + var sb = new System.Text.StringBuilder(s.Length + 2); + sb.Append('"'); + 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").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + sb.Append('"'); + return sb.ToString(); + } + + /// Set by RynthAiPlugin so the snapshot can decorate rules with captured profile data. + public Func? CreatureLookupForRules { get; set; } + + /// + /// Replaces the in-memory MonsterRules from JSON sent by the Avalonia panel + /// and saves to monsters.json. JSON shape: { "rules": [ MonsterRule, ... ] }. + /// Default rule (Name="Default") is always preserved at index 0 — if absent, + /// the existing one is kept; if present, it overrides. + /// + public void ApplyMonstersJson(string json) + { + if (string.IsNullOrWhiteSpace(json)) return; + try + { + var payload = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonstersBridgePayload); + if (payload?.Rules == null) return; + + // Make sure a Default rule survives — every other code path assumes + // it exists (CombatManager fallback at LegacyUiSettings:322). + var incoming = payload.Rules; + bool hasDefault = incoming.Any(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + if (!hasDefault) + { + var existingDefault = _settings.MonsterRules + .FirstOrDefault(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + // Synthesize one if neither incoming nor existing has a Default — combat's + // GetRuleForTarget fallback assumes it always exists, so never leave it absent. + incoming.Insert(0, existingDefault ?? new MonsterRule { Name = "Default" }); + } + + _settings.MonsterRules = incoming; + SaveMonstersFile(); + } + catch { } + } + + // ── Settings bridge (engine-side Avalonia SettingsPanel) ───────────────── + + public string BuildSettingsJson() + { + try + { + var s = _settings; + var payload = new SettingsBridgePayload + { + // Display + ShowTargetStaminaMana = s.ShowTargetStaminaMana, + // UI + SuppressRetailRadar = s.SuppressRetailRadar, + ShowRynthRadar = s.ShowRynthRadar, + RadarClickThrough = s.RadarClickThrough, + ShowRynthChat = s.ShowRynthChat, + ChatClickThrough = s.ChatClickThrough, + SuppressRetailPowerbar = s.SuppressRetailPowerbar, + // Misc + EnableFPSLimit = s.EnableFPSLimit, + TargetFPSFocused = s.TargetFPSFocused, + TargetFPSBackground = s.TargetFPSBackground, + EnableAutocram = s.EnableAutocram, + PeaceModeWhenIdle = s.PeaceModeWhenIdle, + StartMacroOnLogin = s.StartMacroOnLogin, + PatrolOnLogin = s.PatrolOnLogin, + EnableRaycasting = s.EnableRaycasting, + UseArcs = s.UseArcs, + BowArcVelocity = s.BowArcVelocity, + CrossbowArcVelocity = s.CrossbowArcVelocity, + AtlatlArcVelocity = s.AtlatlArcVelocity, + MagicArcVelocity = s.MagicArcVelocity, + BlacklistAttempts = s.BlacklistAttempts, + BlacklistTimeoutSec = s.BlacklistTimeoutSec, + BlacklistCastSettleMs = s.BlacklistCastSettleMs, + TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec, + GiveQueueIntervalMs = s.GiveQueueIntervalMs, + // Recharge + HealAt = s.HealAt, + RestamAt = s.RestamAt, + GetManaAt = s.GetManaAt, + TopOffHP = s.TopOffHP, + TopOffStam = s.TopOffStam, + TopOffMana = s.TopOffMana, + HealOthersAt = s.HealOthersAt, + RestamOthersAt = s.RestamOthersAt, + InfuseOthersAt = s.InfuseOthersAt, + // Melee Combat + UseRecklessness = s.UseRecklessness, + MeleeAttackPower = s.MeleeAttackPower, + MeleeAttackHeight = s.MeleeAttackHeight, + MissileAttackPower = s.MissileAttackPower, + MissileAttackHeight = s.MissileAttackHeight, + UseNativeAttack = s.UseNativeAttack, + SummonPets = s.SummonPets, + PetMinMonsters = s.PetMinMonsters, + // Spell Combat + SpellCastIntervalMs = s.SpellCastIntervalMs, + AttackSpellIntervalMs = s.AttackSpellIntervalMs, + CastDispelSelf = s.CastDispelSelf, + MinRingTargets = s.MinRingTargets, + MinSkillLevelTier1 = s.MinSkillLevelTier1, + MinSkillLevelTier2 = s.MinSkillLevelTier2, + MinSkillLevelTier3 = s.MinSkillLevelTier3, + MinSkillLevelTier4 = s.MinSkillLevelTier4, + MinSkillLevelTier5 = s.MinSkillLevelTier5, + MinSkillLevelTier6 = s.MinSkillLevelTier6, + MinSkillLevelTier7 = s.MinSkillLevelTier7, + MinSkillLevelTier8 = s.MinSkillLevelTier8, + // Ranges + MonsterRange = s.MonsterRange, + MonsterDisengageRange = s.MonsterDisengageRange, + RingRange = s.RingRange, + ApproachRange = s.ApproachRange, + CorpseApproachRangeMax = s.CorpseApproachRangeMax, + CorpseApproachRangeMin = s.CorpseApproachRangeMin, + // Navigation + BoostNavPriority = s.BoostNavPriority, + FollowNavMin = s.FollowNavMin, + NavRingThickness = s.NavRingThickness, + NavLineThickness = s.NavLineThickness, + NavHeightOffset = s.NavHeightOffset, + NavSlopeSink = s.NavSlopeSink, + ShowTerrainPassability = s.ShowTerrainPassability, + OpenDoors = s.OpenDoors, + OpenDoorRange = s.OpenDoorRange, + AutoUnlockDoors = s.AutoUnlockDoors, + MovementMode = s.MovementMode, + NavStopTurnAngle = s.NavStopTurnAngle, + NavResumeTurnAngle = s.NavResumeTurnAngle, + NavDeadZone = s.NavDeadZone, + NavSweepMult = s.NavSweepMult, + NavLookaheadYards = s.NavLookaheadYards, + NavTurnRateDegPerSec = s.NavTurnRateDegPerSec, + NavTier1TurnSpeed = s.NavTier1TurnSpeed, + PostPortalDelaySec = s.PostPortalDelaySec, + T2Speed = s.T2Speed, + T2WalkWithinYd = s.T2WalkWithinYd, + T2DistanceTo = s.T2DistanceTo, + T2ReissueMs = s.T2ReissueMs, + T2MaxRangeYd = s.T2MaxRangeYd, + T2MaxLandblocks = s.T2MaxLandblocks, + // Buffing + EnableBuffing = s.EnableBuffing, + RebuffWhenIdle = s.RebuffWhenIdle, + RebuffSecondsRemaining = s.RebuffSecondsRemaining, + BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1, + BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2, + BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3, + BuffMinSkillLevelTier4 = s.BuffMinSkillLevelTier4, + BuffMinSkillLevelTier5 = s.BuffMinSkillLevelTier5, + BuffMinSkillLevelTier6 = s.BuffMinSkillLevelTier6, + BuffMinSkillLevelTier7 = s.BuffMinSkillLevelTier7, + BuffMinSkillLevelTier8 = s.BuffMinSkillLevelTier8, + // Crafting + EnableMissileCrafting = s.EnableMissileCrafting, + MissileCraftingState = _advancedSettingsUi.MissileCraftingState, + MissileCraftingActive = _advancedSettingsUi.MissileCraftingActive, + MissileCraftingStatus = _advancedSettingsUi.MissileCraftingStatus, + // Looting + EnableLooting = s.EnableLooting, + BoostLootPriority = s.BoostLootPriority, + LootOnlyRareCorpses = s.LootOnlyRareCorpses, + LootJumpEnabled = s.LootJumpEnabled, + LootJumpHeight = s.LootJumpHeight, + LootOwnership = s.LootOwnership, + EnableAutostack = s.EnableAutostack, + EnableCombineSalvage = s.EnableCombineSalvage, + CombineBagsDuringSalvage = s.CombineBagsDuringSalvage, + LootInterItemDelayMs = s.LootInterItemDelayMs, + LootContentSettleMs = s.LootContentSettleMs, + LootEmptyCorpseMs = s.LootEmptyCorpseMs, + LootClosingDelayMs = s.LootClosingDelayMs, + LootAssessWindowMs = s.LootAssessWindowMs, + LootRetryTimeoutMs = s.LootRetryTimeoutMs, + LootOpenRetryMs = s.LootOpenRetryMs, + LootCorpseTimeoutMs = s.LootCorpseTimeoutMs, + SalvageOpenDelayFirstMs = s.SalvageOpenDelayFirstMs, + SalvageOpenDelayFastMs = s.SalvageOpenDelayFastMs, + SalvageAddDelayFirstMs = s.SalvageAddDelayFirstMs, + SalvageAddDelayFastMs = s.SalvageAddDelayFastMs, + SalvageSalvageDelayMs = s.SalvageSalvageDelayMs, + SalvageResultDelayFirstMs = s.SalvageResultDelayFirstMs, + SalvageResultDelayFastMs = s.SalvageResultDelayFastMs, + }; + return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload); + } + catch + { + return "{}"; + } + } + + public void ApplySettingsJson(string json) + { + if (string.IsNullOrWhiteSpace(json)) return; + try + { + var p = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload); + if (p == null) return; + var s = _settings; + // Display + s.ShowTargetStaminaMana = p.ShowTargetStaminaMana; + // UI + s.SuppressRetailRadar = p.SuppressRetailRadar; + s.ShowRynthRadar = p.ShowRynthRadar; + s.RadarClickThrough = p.RadarClickThrough; + s.ShowRynthChat = p.ShowRynthChat; + s.ChatClickThrough = p.ChatClickThrough; + s.SuppressRetailPowerbar = p.SuppressRetailPowerbar; + // Misc + s.EnableFPSLimit = p.EnableFPSLimit; + s.TargetFPSFocused = p.TargetFPSFocused; + s.TargetFPSBackground = p.TargetFPSBackground; + s.EnableAutocram = p.EnableAutocram; + s.PeaceModeWhenIdle = p.PeaceModeWhenIdle; + s.StartMacroOnLogin = p.StartMacroOnLogin; + s.PatrolOnLogin = p.PatrolOnLogin; + s.EnableRaycasting = p.EnableRaycasting; + s.UseArcs = p.UseArcs; + s.BowArcVelocity = p.BowArcVelocity; + s.CrossbowArcVelocity = p.CrossbowArcVelocity; + s.AtlatlArcVelocity = p.AtlatlArcVelocity; + s.MagicArcVelocity = p.MagicArcVelocity; + s.BlacklistAttempts = p.BlacklistAttempts; + s.BlacklistTimeoutSec = p.BlacklistTimeoutSec; + s.BlacklistCastSettleMs = p.BlacklistCastSettleMs; + s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec; + s.GiveQueueIntervalMs = p.GiveQueueIntervalMs; + // Recharge + s.HealAt = p.HealAt; + s.RestamAt = p.RestamAt; + s.GetManaAt = p.GetManaAt; + s.TopOffHP = p.TopOffHP; + s.TopOffStam = p.TopOffStam; + s.TopOffMana = p.TopOffMana; + s.HealOthersAt = p.HealOthersAt; + s.RestamOthersAt = p.RestamOthersAt; + s.InfuseOthersAt = p.InfuseOthersAt; + // Melee Combat + s.UseRecklessness = p.UseRecklessness; + s.MeleeAttackPower = p.MeleeAttackPower; + s.MeleeAttackHeight = p.MeleeAttackHeight; + s.MissileAttackPower = p.MissileAttackPower; + s.MissileAttackHeight = p.MissileAttackHeight; + s.UseNativeAttack = p.UseNativeAttack; + s.SummonPets = p.SummonPets; + s.PetMinMonsters = p.PetMinMonsters; + // Spell Combat + s.SpellCastIntervalMs = p.SpellCastIntervalMs; + s.AttackSpellIntervalMs = p.AttackSpellIntervalMs; + s.CastDispelSelf = p.CastDispelSelf; + s.MinRingTargets = p.MinRingTargets; + s.MinSkillLevelTier1 = p.MinSkillLevelTier1; + s.MinSkillLevelTier2 = p.MinSkillLevelTier2; + s.MinSkillLevelTier3 = p.MinSkillLevelTier3; + s.MinSkillLevelTier4 = p.MinSkillLevelTier4; + s.MinSkillLevelTier5 = p.MinSkillLevelTier5; + s.MinSkillLevelTier6 = p.MinSkillLevelTier6; + s.MinSkillLevelTier7 = p.MinSkillLevelTier7; + s.MinSkillLevelTier8 = p.MinSkillLevelTier8; + // Ranges + s.MonsterRange = p.MonsterRange; + s.MonsterDisengageRange = p.MonsterDisengageRange; + s.RingRange = p.RingRange; + s.ApproachRange = p.ApproachRange; + s.CorpseApproachRangeMax = p.CorpseApproachRangeMax; + s.CorpseApproachRangeMin = p.CorpseApproachRangeMin; + // Navigation + s.BoostNavPriority = p.BoostNavPriority; + s.FollowNavMin = p.FollowNavMin; + s.NavRingThickness = p.NavRingThickness; + s.NavLineThickness = p.NavLineThickness; + s.NavHeightOffset = p.NavHeightOffset; + s.NavSlopeSink = p.NavSlopeSink; + s.ShowTerrainPassability = p.ShowTerrainPassability; + s.OpenDoors = p.OpenDoors; + s.OpenDoorRange = p.OpenDoorRange; + s.AutoUnlockDoors = p.AutoUnlockDoors; + s.MovementMode = p.MovementMode; + s.NavStopTurnAngle = p.NavStopTurnAngle; + s.NavResumeTurnAngle = p.NavResumeTurnAngle; + s.NavDeadZone = p.NavDeadZone; + s.NavSweepMult = p.NavSweepMult; + s.NavLookaheadYards = p.NavLookaheadYards; + s.NavTurnRateDegPerSec = p.NavTurnRateDegPerSec; + s.NavTier1TurnSpeed = p.NavTier1TurnSpeed; + s.PostPortalDelaySec = p.PostPortalDelaySec; + s.T2Speed = p.T2Speed; + s.T2WalkWithinYd = p.T2WalkWithinYd; + s.T2DistanceTo = p.T2DistanceTo; + s.T2ReissueMs = p.T2ReissueMs; + s.T2MaxRangeYd = p.T2MaxRangeYd; + s.T2MaxLandblocks = p.T2MaxLandblocks; + // Buffing + s.EnableBuffing = p.EnableBuffing; + s.RebuffWhenIdle = p.RebuffWhenIdle; + s.RebuffSecondsRemaining = p.RebuffSecondsRemaining; + s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1; + s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2; + s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3; + s.BuffMinSkillLevelTier4 = p.BuffMinSkillLevelTier4; + s.BuffMinSkillLevelTier5 = p.BuffMinSkillLevelTier5; + s.BuffMinSkillLevelTier6 = p.BuffMinSkillLevelTier6; + s.BuffMinSkillLevelTier7 = p.BuffMinSkillLevelTier7; + s.BuffMinSkillLevelTier8 = p.BuffMinSkillLevelTier8; + // Crafting (EnableMissileCrafting is writable; state fields are read-only) + s.EnableMissileCrafting = p.EnableMissileCrafting; + // Looting + s.EnableLooting = p.EnableLooting; + s.BoostLootPriority = p.BoostLootPriority; + s.LootOnlyRareCorpses = p.LootOnlyRareCorpses; + s.LootJumpEnabled = p.LootJumpEnabled; + s.LootJumpHeight = p.LootJumpHeight; + s.LootOwnership = p.LootOwnership; + s.EnableAutostack = p.EnableAutostack; + s.EnableCombineSalvage = p.EnableCombineSalvage; + s.CombineBagsDuringSalvage = p.CombineBagsDuringSalvage; + s.LootInterItemDelayMs = p.LootInterItemDelayMs; + s.LootContentSettleMs = p.LootContentSettleMs; + s.LootEmptyCorpseMs = p.LootEmptyCorpseMs; + s.LootClosingDelayMs = p.LootClosingDelayMs; + s.LootAssessWindowMs = p.LootAssessWindowMs; + s.LootRetryTimeoutMs = p.LootRetryTimeoutMs; + s.LootOpenRetryMs = p.LootOpenRetryMs; + s.LootCorpseTimeoutMs = p.LootCorpseTimeoutMs; + s.SalvageOpenDelayFirstMs = p.SalvageOpenDelayFirstMs; + s.SalvageOpenDelayFastMs = p.SalvageOpenDelayFastMs; + s.SalvageAddDelayFirstMs = p.SalvageAddDelayFirstMs; + s.SalvageAddDelayFastMs = p.SalvageAddDelayFastMs; + s.SalvageSalvageDelayMs = p.SalvageSalvageDelayMs; + s.SalvageResultDelayFirstMs = p.SalvageResultDelayFirstMs; + s.SalvageResultDelayFastMs = p.SalvageResultDelayFastMs; + SaveSettings(); + } + catch { } + } + + // ── Items bridge (engine-side Avalonia ItemsPanel) ──────────────────────── + + public string BuildItemsJson() + { + try + { + var payload = new ItemsBridgePayload + { + Weapons = _settings.ItemRules ?? new List(), + Consumables = _settings.ConsumableRules ?? new List(), + EnableManaTapping = _settings.EnableManaTapping, + ManaTapMinMana = _settings.ManaTapMinMana, + ManaStoneKeepCount = _settings.ManaStoneKeepCount, + CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty, + }; + return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.ItemsBridgePayload); + } + catch + { + return "{}"; + } + } + + public void ApplyItemsJson(string json) + { + if (string.IsNullOrWhiteSpace(json)) return; + try + { + var p = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.ItemsBridgePayload); + if (p == null) return; + _settings.ItemRules = p.Weapons; + _settings.ConsumableRules = p.Consumables; + _settings.EnableManaTapping = p.EnableManaTapping; + _settings.ManaTapMinMana = p.ManaTapMinMana; + _settings.ManaStoneKeepCount = p.ManaStoneKeepCount; + SaveSettings(); + } + catch { } + } + + public void AddSelectedWeapon() { _weaponsUi.AddSelectedWeapon(); SaveSettings(); } + public void AddSelectedConsumable() { _weaponsUi.AddSelectedConsumable(); SaveSettings(); } + + private (uint Id, string Name)? GetCurrentTargetForMonsterAdd() + { + if (_currentTargetId == 0) return null; + string name = _targetLabel; + if (_host.HasGetObjectName && _host.TryGetObjectName(_currentTargetId, out string resolved) && !string.IsNullOrWhiteSpace(resolved)) + name = resolved; + if (string.IsNullOrWhiteSpace(name) || name == "NO TARGET") return null; + return (_currentTargetId, name); + } + + /// Launches the standalone Monster Rules editor for the current char folder. + private void LaunchMonsterEditor() + { + if (string.IsNullOrEmpty(_charFolder)) + { + _host.WriteToChat("[RynthAi] No character loaded — cannot open Monster Editor.", 4); + return; + } + + // Toggle: if the editor is already running, close it. + if (_monsterEditorProcessHandle != IntPtr.Zero) + { + uint wait = WaitForSingleObject(_monsterEditorProcessHandle, 0); + if (wait == WaitTimeout) // still running + { + IntPtr hwnd = FindMainWindowForPid(_monsterEditorPid); + if (hwnd != IntPtr.Zero) + PostMessage(hwnd, WmClose, IntPtr.Zero, IntPtr.Zero); + else + TerminateProcess(_monsterEditorProcessHandle, 0); // no window found — fall back to a hard kill + } + ReleaseMonsterEditorHandle(); + return; + } + + // Editor lives at: \MonsterEditor\RynthCore.MonsterEditor.exe + string rynthAiRoot = Path.GetDirectoryName(Path.GetDirectoryName(_settingsRoot)!)!; + string editorExe = Path.Combine(rynthAiRoot, "MonsterEditor", "RynthCore.MonsterEditor.exe"); + + if (!File.Exists(editorExe)) + { + _host.WriteToChat($"[RynthAi] Monster Editor not found: {editorExe}", 4); + return; + } + + var info = new SHELLEXECUTEINFOW + { + cbSize = Marshal.SizeOf(), + fMask = SeeMaskNoCloseProcess, // retain hProcess instead of closing it internally + lpVerb = "open", + lpFile = editorExe, + lpParameters = $"\"{_charFolder}\"", + nShow = SwShowNormal, + }; + + if (!ShellExecuteExW(ref info) || info.hProcess == IntPtr.Zero) + { + _host.WriteToChat("[RynthAi] Failed to launch Monster Editor.", 4); + return; + } + + _monsterEditorProcessHandle = info.hProcess; + _monsterEditorPid = (int)GetProcessId(info.hProcess); // needed to find the main window for WM_CLOSE later + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint GetProcessId(IntPtr hProcess); + + private void CaptureTransientUiState() + { + _settings.WindowLocked = _isLocked; + _settings.DashboardMinimized = _isMinimized; + _settings.WindowSizeX = _expandedSize.X; + _settings.WindowSizeY = _expandedSize.Y; + _settings.BgOpacity = _bgOpacity; + _settings.DashShowWeapons = DashWindows.ShowWeapons; + _settings.DashShowLua = DashWindows.ShowLua; + _settings.DashShowNavigation = DashWindows.ShowNavigation; + _settings.DashShowMacroRules = DashWindows.ShowMacroRules; + _settings.DashShowMonsters = DashWindows.ShowMonsters; + _settings.DashShowDungeonMap = DashWindows.ShowDungeonMap; + } + + private void ApplyUiStateFromSettings() + { + _isLocked = _settings.WindowLocked; + _isMinimized = _settings.DashboardMinimized; + _expandedSize = new Vector2(_settings.WindowSizeX, _settings.WindowSizeY); + _bgOpacity = _settings.BgOpacity; + DashWindows.ShowWeapons = _settings.DashShowWeapons; + DashWindows.ShowLua = _settings.DashShowLua; + DashWindows.ShowNavigation = _settings.DashShowNavigation; + DashWindows.ShowMacroRules = _settings.DashShowMacroRules; + DashWindows.ShowMonsters = _settings.DashShowMonsters; + DashWindows.ShowDungeonMap = _settings.DashShowDungeonMap; + } + + private string GetProfileFilePath(string profileName) + { + if (string.IsNullOrEmpty(_charFolder)) return string.Empty; + return Path.Combine(_charFolder, profileName + ".json"); + } + + private string GetActiveProfileMarkerPath() + { + if (string.IsNullOrEmpty(_charFolder)) return string.Empty; + return Path.Combine(_charFolder, "active_profile.txt"); + } + + private string ReadActiveProfile() + { + string markerPath = GetActiveProfileMarkerPath(); + if (!string.IsNullOrEmpty(markerPath) && File.Exists(markerPath)) + { + try + { + string name = File.ReadAllText(markerPath).Trim(); + if (!string.IsNullOrWhiteSpace(name)) return name; + } + catch { } + } + return "Default"; + } + + private void WriteActiveProfile(string profileName) + { + string markerPath = GetActiveProfileMarkerPath(); + if (string.IsNullOrEmpty(markerPath)) return; + try + { + Directory.CreateDirectory(_charFolder); + File.WriteAllText(markerPath, profileName); + } + catch { } + } + + private void SwitchProfile(string newProfile) + { + if (string.Equals(newProfile, _settings.SelectedProfile, StringComparison.OrdinalIgnoreCase)) + return; + + // Save current settings to current profile file + SaveSettings(); + + // Switch to the new profile + _settings.SelectedProfile = newProfile; + _settingsFilePath = GetProfileFilePath(newProfile); + WriteActiveProfile(newProfile); + + // Load from new profile file if it exists + if (File.Exists(_settingsFilePath)) + { + try + { + string json = File.ReadAllText(_settingsFilePath); + var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + if (loaded != null) + { + CopySettings(loaded, _settings); + _settings.SelectedProfile = newProfile; + _lastSavedJson = json; + } + } + catch { } + } + else + { + // New profile — force save current settings as its initial state + _lastSavedJson = string.Empty; + } + + ApplyUiStateFromSettings(); + + // Reload nav route for the new profile + _settings.CurrentRoute = new NavRouteParser(); + if (!string.IsNullOrEmpty(_settings.CurrentNavPath) && File.Exists(_settings.CurrentNavPath)) + { + try + { + _settings.CurrentRoute = NavRouteParser.Load(_settings.CurrentNavPath); + _settings.ActiveNavIndex = + (_settings.CurrentRoute.RouteType == NavRouteType.Follow || + _settings.CurrentRoute.RouteType == NavRouteType.Once) + ? 0 + : FindNearestWaypoint(_settings.CurrentRoute); + } + catch { _settings.CurrentNavPath = string.Empty; } + } + + _windowPosRestored = false; + _windowSizeRestored = false; + RefreshAllLists(); + } + + private static string SanitizeFileName(string name) + { + var sb = new System.Text.StringBuilder(name.Length); + foreach (char c in name) + sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_'); + return sb.ToString(); + } + + /// + /// Copies all JSON-serializable fields from src into dst without replacing the + /// object reference (so all existing bindings to _settings remain valid). + /// + private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) + { + // Re-serialize src, then deserialize over dst's fields via reflection-free copy. + // Simplest approach: copy field-by-field via JSON round-trip into dst. + string json = JsonSerializer.Serialize(src, RynthAiJsonContext.Default.LegacyUiSettings); + var tmp = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + if (tmp == null) return; + + // Copy all serialized fields manually (the source generator guarantees coverage) + dst.EnableBuffing = tmp.EnableBuffing; + dst.EnableCombat = tmp.EnableCombat; + dst.EnableNavigation = tmp.EnableNavigation; + dst.EnableLooting = tmp.EnableLooting; + dst.EnableMeta = tmp.EnableMeta; + dst.EnableRaycasting = tmp.EnableRaycasting; + dst.MovementMode = tmp.MovementMode; + dst.NavStopTurnAngle = tmp.NavStopTurnAngle; + dst.NavResumeTurnAngle = tmp.NavResumeTurnAngle; + dst.NavDeadZone = tmp.NavDeadZone; + dst.NavSweepMult = tmp.NavSweepMult; + dst.NavLookaheadYards = tmp.NavLookaheadYards; + dst.NavTurnRateDegPerSec = tmp.NavTurnRateDegPerSec; + dst.NavTier1TurnSpeed = tmp.NavTier1TurnSpeed; + dst.PostPortalDelaySec = tmp.PostPortalDelaySec; + dst.T2Speed = tmp.T2Speed; + dst.T2DistanceTo = tmp.T2DistanceTo; + dst.T2ReissueMs = tmp.T2ReissueMs; + dst.T2MaxRangeYd = tmp.T2MaxRangeYd; + dst.T2MaxLandblocks = tmp.T2MaxLandblocks; + dst.T2WalkWithinYd = tmp.T2WalkWithinYd; + dst.CurrentNavPath = tmp.CurrentNavPath; + dst.CurrentLootPath = tmp.CurrentLootPath; + dst.CurrentMetaPath = tmp.CurrentMetaPath; + dst.MacroSettingsIdx = tmp.MacroSettingsIdx; + dst.NavProfileIdx = tmp.NavProfileIdx; + dst.LootProfileIdx = tmp.LootProfileIdx; + dst.MetaProfileIdx = tmp.MetaProfileIdx; + dst.EnableAutostack = tmp.EnableAutostack; + dst.EnableAutocram = tmp.EnableAutocram; + dst.EnableCombineSalvage = tmp.EnableCombineSalvage; + dst.CombineBagsDuringSalvage = tmp.CombineBagsDuringSalvage; + dst.ShowTargetStaminaMana = tmp.ShowTargetStaminaMana; + dst.EnableMissileCrafting = tmp.EnableMissileCrafting; + dst.MissileCraftAmmoThreshold= tmp.MissileCraftAmmoThreshold; + dst.LootInterItemDelayMs = tmp.LootInterItemDelayMs; + dst.LootContentSettleMs = tmp.LootContentSettleMs; + dst.LootEmptyCorpseMs = tmp.LootEmptyCorpseMs; + dst.LootClosingDelayMs = tmp.LootClosingDelayMs; + dst.LootAssessWindowMs = tmp.LootAssessWindowMs; + dst.LootRetryTimeoutMs = tmp.LootRetryTimeoutMs; + dst.LootOpenRetryMs = tmp.LootOpenRetryMs; + dst.LootCorpseTimeoutMs = tmp.LootCorpseTimeoutMs; + dst.LootJumpEnabled = tmp.LootJumpEnabled; + dst.LootJumpHeight = tmp.LootJumpHeight; + dst.SalvageOpenDelayFirstMs = tmp.SalvageOpenDelayFirstMs; + dst.SalvageOpenDelayFastMs = tmp.SalvageOpenDelayFastMs; + dst.SalvageAddDelayFirstMs = tmp.SalvageAddDelayFirstMs; + dst.SalvageAddDelayFastMs = tmp.SalvageAddDelayFastMs; + dst.SalvageSalvageDelayMs = tmp.SalvageSalvageDelayMs; + dst.SalvageResultDelayFirstMs= tmp.SalvageResultDelayFirstMs; + dst.SalvageResultDelayFastMs = tmp.SalvageResultDelayFastMs; + dst.UseDispelItems = tmp.UseDispelItems; + dst.CastDispelSelf = tmp.CastDispelSelf; + dst.AutoFellowMgmt = tmp.AutoFellowMgmt; + dst.MChargesWhenOff = tmp.MChargesWhenOff; + dst.HealAt = tmp.HealAt; + dst.RestamAt = tmp.RestamAt; + dst.GetManaAt = tmp.GetManaAt; + dst.TopOffHP = tmp.TopOffHP; + dst.TopOffStam = tmp.TopOffStam; + dst.TopOffMana = tmp.TopOffMana; + dst.HealOthersAt = tmp.HealOthersAt; + dst.RestamOthersAt = tmp.RestamOthersAt; + dst.InfuseOthersAt = tmp.InfuseOthersAt; + dst.MonsterRange = tmp.MonsterRange; + dst.MonsterDisengageRange = tmp.MonsterDisengageRange; + dst.RingRange = tmp.RingRange; + dst.ApproachRange = tmp.ApproachRange; + dst.MinRingTargets = tmp.MinRingTargets; + dst.FollowNavMin = tmp.FollowNavMin; + dst.NavRingThickness = tmp.NavRingThickness; + dst.NavLineThickness = tmp.NavLineThickness; + dst.NavHeightOffset = tmp.NavHeightOffset; + dst.NavSlopeSink = tmp.NavSlopeSink; + dst.MaxMonRange = tmp.MaxMonRange; + dst.SummonPets = tmp.SummonPets; + dst.CustomPetRange = tmp.CustomPetRange; + dst.PetMinMonsters = tmp.PetMinMonsters; + dst.AdvancedOptions = tmp.AdvancedOptions; + dst.MineOnly = tmp.MineOnly; + dst.ShowEditor = tmp.ShowEditor; + dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0); + dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0); + dst.BoostNavPriority = tmp.BoostNavPriority; + dst.BoostLootPriority = tmp.BoostLootPriority; + dst.OpenDoors = tmp.OpenDoors; + dst.OpenDoorRange = tmp.OpenDoorRange; + dst.AutoUnlockDoors = tmp.AutoUnlockDoors; + dst.LootOwnership = tmp.LootOwnership; + dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; + dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; + dst.RebuffWhenIdle = tmp.RebuffWhenIdle; + dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining; + dst.BlacklistAttempts = tmp.BlacklistAttempts; + dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec; + dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs; + dst.TargetNoProgressTimeoutSec = tmp.TargetNoProgressTimeoutSec; + dst.MeleeAttackPower = tmp.MeleeAttackPower; + dst.MissileAttackPower = tmp.MissileAttackPower; + dst.UseRecklessness = tmp.UseRecklessness; + dst.UseNativeAttack = tmp.UseNativeAttack; + dst.MeleeAttackHeight = tmp.MeleeAttackHeight; + dst.MissileAttackHeight = tmp.MissileAttackHeight; + dst.UseArcs = tmp.UseArcs; + dst.BowArcVelocity = tmp.BowArcVelocity; + dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity; + dst.AtlatlArcVelocity = tmp.AtlatlArcVelocity; + dst.MagicArcVelocity = tmp.MagicArcVelocity; + dst.EnableFPSLimit = tmp.EnableFPSLimit; + dst.TargetFPSFocused = tmp.TargetFPSFocused; + dst.TargetFPSBackground = tmp.TargetFPSBackground; + // MonsterRule deep-copy preserves Category + MatchExpression via JSON round-trip + dst.MonsterRules = tmp.MonsterRules; + dst.ItemRules = tmp.ItemRules; + dst.ConsumableRules = tmp.ConsumableRules; + dst.BuffRules = tmp.BuffRules; + dst.MetaRules = tmp.MetaRules; + dst.LuaScript = tmp.LuaScript; + dst.SelectedProfile = tmp.SelectedProfile; + dst.ActiveNavIndex = tmp.ActiveNavIndex; + dst.ShowAdvancedWindow = tmp.ShowAdvancedWindow; + dst.SelectedAdvancedTab = tmp.SelectedAdvancedTab; + dst.WindowPosX = tmp.WindowPosX; + dst.WindowPosY = tmp.WindowPosY; + dst.WindowLocked = tmp.WindowLocked; + dst.DashboardVisible = tmp.DashboardVisible; + dst.DashboardMinimized = tmp.DashboardMinimized; + dst.WindowSizeX = tmp.WindowSizeX; + dst.WindowSizeY = tmp.WindowSizeY; + dst.BgOpacity = tmp.BgOpacity; + dst.DashShowWeapons = tmp.DashShowWeapons; + dst.DashShowLua = tmp.DashShowLua; + dst.DashShowNavigation = tmp.DashShowNavigation; + dst.DashShowMacroRules = tmp.DashShowMacroRules; + dst.DashShowMonsters = tmp.DashShowMonsters; + dst.DashShowDungeonMap = tmp.DashShowDungeonMap; + dst.MapShowDoors = tmp.MapShowDoors; + dst.MapShowCreatures = tmp.MapShowCreatures; + dst.MapShowToolbar = tmp.MapShowToolbar; + dst.MapBgOpacity = tmp.MapBgOpacity; + dst.MapRotateWithPlayer = tmp.MapRotateWithPlayer; + dst.ShowRadarWalls = tmp.ShowRadarWalls; + dst.RadarWallWorldRange = tmp.RadarWallWorldRange; + dst.MinSkillLevelTier1 = tmp.MinSkillLevelTier1; + dst.MinSkillLevelTier2 = tmp.MinSkillLevelTier2; + dst.MinSkillLevelTier3 = tmp.MinSkillLevelTier3; + dst.MinSkillLevelTier4 = tmp.MinSkillLevelTier4; + dst.MinSkillLevelTier5 = tmp.MinSkillLevelTier5; + dst.MinSkillLevelTier6 = tmp.MinSkillLevelTier6; + dst.MinSkillLevelTier7 = tmp.MinSkillLevelTier7; + dst.MinSkillLevelTier8 = tmp.MinSkillLevelTier8; + dst.BuffMinSkillLevelTier1 = tmp.BuffMinSkillLevelTier1; + dst.BuffMinSkillLevelTier2 = tmp.BuffMinSkillLevelTier2; + dst.BuffMinSkillLevelTier3 = tmp.BuffMinSkillLevelTier3; + dst.BuffMinSkillLevelTier4 = tmp.BuffMinSkillLevelTier4; + dst.BuffMinSkillLevelTier5 = tmp.BuffMinSkillLevelTier5; + dst.BuffMinSkillLevelTier6 = tmp.BuffMinSkillLevelTier6; + dst.BuffMinSkillLevelTier7 = tmp.BuffMinSkillLevelTier7; + dst.BuffMinSkillLevelTier8 = tmp.BuffMinSkillLevelTier8; + dst.EnableManaTapping = tmp.EnableManaTapping; + dst.ManaTapMinMana = tmp.ManaTapMinMana; + dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount; + dst.MetaDebug = tmp.MetaDebug; + dst.StartMacroOnLogin = tmp.StartMacroOnLogin; + dst.PatrolOnLogin = tmp.PatrolOnLogin; + dst.ShowTerrainPassability = tmp.ShowTerrainPassability; + dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; + dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; + dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs; + dst.EmbeddedNavs = tmp.EmbeddedNavs; + dst.SuppressRetailRadar = tmp.SuppressRetailRadar; + dst.ShowRynthRadar = tmp.ShowRynthRadar; + dst.RadarRotateWithPlayer = tmp.RadarRotateWithPlayer; + dst.RadarOpacity = tmp.RadarOpacity; + dst.RadarZoom = tmp.RadarZoom; + dst.RadarShowMonsters = tmp.RadarShowMonsters; + dst.RadarShowNpcs = tmp.RadarShowNpcs; + dst.RadarShowPortals = tmp.RadarShowPortals; + dst.RadarShowDoors = tmp.RadarShowDoors; + dst.RadarWallPaintRadius = tmp.RadarWallPaintRadius; + dst.RadarCircular = tmp.RadarCircular; + dst.RadarClickThrough = tmp.RadarClickThrough; + dst.SuppressRetailPowerbar = tmp.SuppressRetailPowerbar; + dst.ShowRynthChat = tmp.ShowRynthChat; + dst.ChatOpacity = tmp.ChatOpacity; + dst.ChatMaxLines = tmp.ChatMaxLines; + dst.ChatShowTimestamps = tmp.ChatShowTimestamps; + dst.ChatClickThrough = tmp.ChatClickThrough; + } + + private static double NormalizeCorpseRangeYards(double value, double fallbackYards) + { + if (double.IsNaN(value) || double.IsInfinity(value) || value <= 0.0) + return fallbackYards; + + // Older settings stored corpse ranges in 240-based world units. Convert those + // to direct yard values so the UI can use whole numbers like 5 or 6. + return value <= 1.0 ? value * 240.0 : value; + } + + + public void SetSelectedTarget(uint targetId) + { + _currentTargetId = targetId; + _targetLabel = "NO TARGET"; + if (targetId != 0) + { + _targetLabel = _host.HasGetObjectName && _host.TryGetObjectName(targetId, out string name) && !string.IsNullOrWhiteSpace(name) + ? name + : $"TARGET 0x{targetId:X8}"; + } + _targetHealthPercent = 0f; + _targetHealth = 0; + _targetMaxHealth = 0; + _targetStamina = 0; + _targetMaxStamina = 0; + _targetMana = 0; + _targetMaxMana = 0; + _targetHealthDisplay = targetId == 0 ? "0" : "--"; + if (targetId != 0 && _host.HasQueryHealth) _host.QueryHealth(targetId); + } + + public void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + { + if (targetId == 0 || targetId != _currentTargetId) + return; + + _targetHealthPercent = Math.Clamp(healthRatio, 0f, 1f); + if (maxHealth > 0) + { + _targetHealth = currentHealth; + _targetMaxHealth = maxHealth; + _targetHealthDisplay = $"{currentHealth}/{maxHealth}"; + } + else + { + // Try to resolve absolute health from previously identified creature data. + uint storedMax = 0; + var lookup = CreatureLookupForRules; + if (lookup != null && !string.IsNullOrEmpty(_targetLabel)) + { + var profile = lookup(_targetLabel); + if (profile != null && profile.MaxHealth > 0) + storedMax = profile.MaxHealth; + } + + if (storedMax > 0) + { + _targetMaxHealth = storedMax; + _targetHealth = (uint)Math.Round(_targetHealthPercent * storedMax); + _targetHealthDisplay = $"{_targetHealth}/{storedMax}"; + } + else + { + _targetHealth = 0; + _targetMaxHealth = 0; + _targetHealthDisplay = $"{(int)(_targetHealthPercent * 100)}%"; + } + } + + // Refresh stamina/mana from the creature vitals cache + if (_host.HasGetTargetVitals && + _host.TryGetTargetVitals(targetId, out _, out _, out uint st, out uint maxSt, out uint mn, out uint maxMn)) + { + _targetStamina = st; + _targetMaxStamina = maxSt; + _targetMana = mn; + _targetMaxMana = maxMn; + } + } + + public void Render() + { + RefreshPlayerVitals(); + + // Periodic dirty-check: serialize settings every ~2s; save if changed + if (++_saveCheckCounter >= SaveCheckIntervalFrames) + { + _saveCheckCounter = 0; + CheckAndSave(); + } + + // Plugin-wide style overrides: muted slate-blue accents instead of the + // previous vivid sky-blue, which was overpowering in the macro tab. + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.18f, 0.22f, 0.28f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.24f, 0.30f, 0.38f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.30f, 0.38f, 0.48f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.85f, 0.90f, 1.00f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.PopupBg, new Vector4(0.10f, 0.14f, 0.20f, 0.98f)); + ImGui.PushStyleColor(ImGuiCol.Header, new Vector4(0.20f, 0.28f, 0.36f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderHovered, new Vector4(0.26f, 0.36f, 0.46f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderActive, new Vector4(0.32f, 0.44f, 0.58f, 1.00f)); + // Title bars — same slate-blue family. TitleBgActive replaces ImGui's + // default vivid yellow that's especially jarring on detached viewports. + ImGui.PushStyleColor(ImGuiCol.TitleBg, new Vector4(0.14f, 0.18f, 0.24f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.22f, 0.30f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgCollapsed,new Vector4(0.10f, 0.14f, 0.20f, 0.85f)); + + try + { + RenderDashboard(); + + _metaUi.Render(); + TickMonsterReload(); + _monstersUi.Render(); + _weaponsUi.Render(); + + // Hooked up the new Lua UI here + _luaUi.Render(); + + if (DashWindows.ShowNavigation) _navigationUi.Render(); + if (_settings.ShowAdvancedWindow) _advancedSettingsUi.Render(); + } + finally + { + ImGui.PopStyleColor(11); + } + } + + // Rendered every frame regardless of whether the main dashboard is visible. + public void RenderMapWindow() + { + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.15f, 0.55f, 0.95f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.22f, 0.62f, 1.00f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.10f, 0.45f, 0.82f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.00f, 0.00f, 0.00f, 1.00f)); + try + { + if (DashWindows.ShowDungeonMap || _dungeonMapUi.IsAutoHidden) + _dungeonMapUi.Render(); + _rynthRadarUi.Render(); + _rynthChatUi.Render(); + } + finally + { + ImGui.PopStyleColor(4); + } + } + + private void RenderDashboard() + { + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 8.0f); + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 6.0f); + ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.04f, 0.06f, 0.08f, _bgOpacity)); + ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoCollapse; + if (_isMinimized) { flags |= ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize; _wasMinimized = true; } + else if (_isLocked) flags |= ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove; + // Restore saved window position on first render after login. Sanity- + // check it against the current main viewport size — if the dashboard + // was dragged partly off-screen on a previous session, or the AC + // client window shrank since, the saved coords would render the + // dashboard somewhere invisible. Snap back to (50, 50) in that case. + if (!_windowPosRestored) + { + Vector2 vpSize = ImGui.GetMainViewport().Size; + float maxX = vpSize.X > 0 ? vpSize.X - 100 : 8000; + float maxY = vpSize.Y > 0 ? vpSize.Y - 100 : 6000; + float posX = _settings.WindowPosX; + float posY = _settings.WindowPosY; + bool inBounds = + posX >= 0 && posX <= maxX && + posY >= 0 && posY <= maxY; + if (!inBounds) + { + posX = 50; + posY = 50; + _settings.WindowPosX = posX; + _settings.WindowPosY = posY; + } + ImGui.SetNextWindowPos(new Vector2(posX, posY), ImGuiCond.Always); + _windowPosRestored = true; + } + + ImGui.SetNextWindowSizeConstraints(new Vector2(400, 0), new Vector2(1200, 2000)); + if (!_isMinimized && !_isLocked) + { + // Force-apply the saved expanded size on the first frame after login — + // imgui.ini may have a stale tiny size from a previous session. + if (!_windowSizeRestored) + { + ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.Always); + ImGui.SetNextWindowCollapsed(false, ImGuiCond.Always); + _windowSizeRestored = true; + } + else if (_wasMinimized) { ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.Always); _wasMinimized = false; } + else ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.FirstUseEver); + } + else if (_isMinimized && !_windowSizeRestored) + { + // Even in minimized mode, defensively un-collapse so an old imgui.ini + // Collapsed=1 entry can't keep the window iconified. + ImGui.SetNextWindowCollapsed(false, ImGuiCond.Always); + _windowSizeRestored = true; + } + if (ImGui.Begin("RynthAi Dashboard##Main", flags)) + { + if (!_isMinimized && !_isLocked) _expandedSize = ImGui.GetWindowSize(); + RenderDashHeader(); + ImGui.PushStyleColor(ImGuiCol.ChildBg, ColPanelBg); + ImGui.PushStyleColor(ImGuiCol.Border, ColBtnBord); + ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, 1.0f); + if (ImGui.BeginChild("CombatPanel", new Vector2(-1, 200), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)) { RenderCombatPanel(); ImGui.Dummy(new Vector2(0, 2)); } + ImGui.EndChild(); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(2); + if (!_isMinimized) { ImGui.Spacing(); ImGui.Spacing(); RenderLauncherGrid(); } + } + // Capture window position for persistence + Vector2 curPos = ImGui.GetWindowPos(); + if (curPos != _lastWindowPos) + { + _settings.WindowPosX = curPos.X; + _settings.WindowPosY = curPos.Y; + _lastWindowPos = curPos; + } + + ImGui.End(); + ImGui.PopStyleColor(1); + ImGui.PopStyleVar(3); + } + + private void RenderDashHeader() + { + float width = ImGui.GetContentRegionAvail().X; + float startY = ImGui.GetCursorPosY(); + ImGui.SetWindowFontScale(1.4f); + ImGui.TextColored(ColTeal, "R"); + ImGui.SameLine(0, 2); + ImGui.TextColored(new Vector4(1, 1, 1, 1), "YNTHAI DASHBOARD"); + ImGui.SetWindowFontScale(1.0f); + ImGui.SameLine(); + ImGui.SetCursorPosY(startY + 5); + ImGui.TextColored(ColTextMute, "v4.0"); + ImGui.SameLine(width - 130); + ImGui.SetCursorPosY(startY + 2); + if (ImGui.SmallButton(_isLocked ? "Unlk" : "Lock")) _isLocked = !_isLocked; + if (ImGui.IsItemHovered()) ImGui.SetTooltip(_isLocked ? "Unlock Window" : "Lock Window"); + ImGui.SameLine(); + if (ImGui.SmallButton("-")) _bgOpacity = Math.Max(0.1f, _bgOpacity - 0.1f); + ImGui.SameLine(); + if (ImGui.SmallButton("+")) _bgOpacity = Math.Min(1.0f, _bgOpacity + 0.1f); + ImGui.SameLine(); + if (ImGui.SmallButton(_isMinimized ? "^" : "_")) { _isMinimized = !_isMinimized; SaveSettings(); } + ImGui.SameLine(); + if (ImGui.SmallButton("X")) CloseRequested = true; + ImGui.Dummy(new Vector2(0, 2)); + if (_isMinimized) return; + if (!ImGui.BeginTable("HeaderGrid", 2)) return; + + ImGui.TableSetupColumn("Left", ImGuiTableColumnFlags.WidthFixed, width * 0.40f); + ImGui.TableSetupColumn("Right", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableNextRow(); + + // ── Left column: macro button + status ────────────────────────── + ImGui.TableNextColumn(); + + var btnColor = _settings.IsMacroRunning + ? new Vector4(0.10f, 0.35f, 0.15f, 1.00f) + : new Vector4(0.25f, 0.12f, 0.12f, 1.00f); + var btnHover = _settings.IsMacroRunning + ? new Vector4(0.15f, 0.50f, 0.22f, 1.00f) + : new Vector4(0.40f, 0.18f, 0.18f, 1.00f); + var btnActive = _settings.IsMacroRunning + ? new Vector4(0.08f, 0.28f, 0.12f, 1.00f) + : new Vector4(0.20f, 0.10f, 0.10f, 1.00f); + + ImGui.PushStyleColor(ImGuiCol.Button, btnColor); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, btnHover); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, btnActive); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4.0f); + ImGui.SetWindowFontScale(1.2f); + + Vector2 pos = ImGui.GetCursorScreenPos(); + string macroLabel = _settings.IsMacroRunning ? "RUNNING##ToggleMacro" : "STOPPED##ToggleMacro"; + if (ImGui.Button(macroLabel, new Vector2(120, 28))) + _settings.IsMacroRunning = !_settings.IsMacroRunning; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Click to Start / Stop Macro"); + + ImGui.SetWindowFontScale(1.0f); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(3); + + // Status circle beside the button + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + uint circleColor = _settings.IsMacroRunning ? ImGui.ColorConvertFloat4ToU32(ColGreen) : ImGui.ColorConvertFloat4ToU32(ColTextMute); + Vector2 circlePos = pos + new Vector2(138, 14); + dl.AddCircleFilled(circlePos, 5, circleColor); + if (_settings.IsMacroRunning) dl.AddCircle(circlePos, 8, circleColor, 12, 1.5f); + + ImGui.Spacing(); + ImGui.TextColored(ColTextMute, "Meta State:"); + ImGui.SameLine(0, 8); + ImGui.TextColored(ColAmber, _settings.CurrentState); + ImGui.TextColored(ColTextMute, "Bot Activity:"); + ImGui.SameLine(0, 8); + string botDisplay = string.IsNullOrEmpty(_settings.BotAction) || _settings.BotAction == "Default" ? "Idle" : _settings.BotAction; + ImGui.TextColored(ColAmber, botDisplay); + + // ── Right column: file dropdowns (independent vertical layout) ── + ImGui.TableNextColumn(); + + ImGui.TextColored(ColTextMute, "Profile:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##ProfCombo", TruncateName(_settings.SelectedProfile, 16))) + { + string? pendingSwitch = null; + foreach (string profile in _profiles) + if (ImGui.Selectable(profile, profile == _settings.SelectedProfile)) + pendingSwitch = profile; + ImGui.EndCombo(); + if (pendingSwitch != null) SwitchProfile(pendingSwitch); + } + + ImGui.TextColored(ColTextMute, "Nav:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + string navName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath); + if (ImGui.BeginCombo("##NavCombo", TruncateName(navName, 16))) + { + for (int i = 0; i < _navFiles.Count; i++) + if (ImGui.Selectable(_navFiles[i], _selectedNavIdx == i)) { _selectedNavIdx = i; LoadSelectedNav(); } + ImGui.EndCombo(); + } + + ImGui.TextColored(ColTextMute, "Loot:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + string lootName = string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath); + if (ImGui.BeginCombo("##LootCombo", TruncateName(lootName, 16))) + { + for (int i = 0; i < _lootFiles.Count; i++) + if (ImGui.Selectable(_lootFiles[i], _settings.LootProfileIdx == i)) + { + _settings.LootProfileIdx = i; + _settings.CurrentLootPath = i == 0 ? string.Empty : Path.Combine(_lootFolder, _lootFiles[i]); + SaveSettings(); + } + ImGui.EndCombo(); + } + + ImGui.TextColored(ColTextMute, "Meta:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + string metaName = string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath); + if (ImGui.BeginCombo("##MetaCombo", TruncateName(metaName, 16))) + { + for (int i = 0; i < _metaFiles.Count; i++) + if (ImGui.Selectable(_metaFiles[i], _settings.MetaProfileIdx == i)) + { + _settings.MetaProfileIdx = i; + string path = i == 0 ? string.Empty : Path.Combine(_metaFolder, _metaFiles[i]); + _metaUi.LoadMacroFile(path); + } + ImGui.EndCombo(); + } + + ImGui.EndTable(); + ImGui.Spacing(); + } + + private void RenderMinimizedMacroButton() + { + var btnColor = _settings.IsMacroRunning + ? new Vector4(0.10f, 0.35f, 0.15f, 1.00f) + : new Vector4(0.25f, 0.12f, 0.12f, 1.00f); + var btnHover = _settings.IsMacroRunning + ? new Vector4(0.15f, 0.50f, 0.22f, 1.00f) + : new Vector4(0.40f, 0.18f, 0.18f, 1.00f); + var btnActive = _settings.IsMacroRunning + ? new Vector4(0.08f, 0.28f, 0.12f, 1.00f) + : new Vector4(0.20f, 0.10f, 0.10f, 1.00f); + + ImGui.PushStyleColor(ImGuiCol.Button, btnColor); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, btnHover); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, btnActive); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3.0f); + + string label = _settings.IsMacroRunning ? "Running##MinMacro" : "Stopped##MinMacro"; + if (ImGui.SmallButton(label)) + _settings.IsMacroRunning = !_settings.IsMacroRunning; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Click to Start / Stop Macro"); + + ImGui.PopStyleVar(); + ImGui.PopStyleColor(3); + } + + private void RenderCombatPanel() + { + if (!ImGui.BeginTable("CombatInnerTable", 2, ImGuiTableFlags.None)) return; + ImGui.TableSetupColumn("Toggles", ImGuiTableColumnFlags.WidthFixed, 68); + ImGui.TableSetupColumn("Vitals", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + if (_isMinimized) + { + var btnColor = _settings.IsMacroRunning + ? new Vector4(0.10f, 0.35f, 0.15f, 1.00f) + : new Vector4(0.25f, 0.12f, 0.12f, 1.00f); + var btnHover = _settings.IsMacroRunning + ? new Vector4(0.15f, 0.50f, 0.22f, 1.00f) + : new Vector4(0.40f, 0.18f, 0.18f, 1.00f); + var btnActive = _settings.IsMacroRunning + ? new Vector4(0.08f, 0.28f, 0.12f, 1.00f) + : new Vector4(0.20f, 0.10f, 0.10f, 1.00f); + ImGui.PushStyleColor(ImGuiCol.Button, btnColor); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, btnHover); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, btnActive); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3.0f); + string mLabel = _settings.IsMacroRunning ? "ON##MinMacro" : "OFF##MinMacro"; + if (ImGui.Button(mLabel, new Vector2(64, 20))) + _settings.IsMacroRunning = !_settings.IsMacroRunning; + if (ImGui.IsItemHovered()) ImGui.SetTooltip(_settings.IsMacroRunning ? "Macro Running - Click to Stop" : "Macro Stopped - Click to Start"); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(3); + } + Vector2 togglePos = ImGui.GetCursorScreenPos() + new Vector2(2, _isMinimized ? 6 : 28); + + // Right-click on each main toggle opens the matching settings window/tab — + // a quick shortcut so users don't have to hunt through Advanced Settings. + LegacyDashboardDrawing.DrawSquareToggle("sword", ref _settings.EnableCombat, togglePos, "CombatTgl"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) OpenAdvancedTab("Melee Combat"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Combat — left-click to toggle, right-click for settings"); + + LegacyDashboardDrawing.DrawSquareToggle("buff", ref _settings.EnableBuffing, togglePos + new Vector2(34, 0), "BuffTgl"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) OpenAdvancedTab("Buffing"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Buffing — left-click to toggle, right-click for settings"); + + LegacyDashboardDrawing.DrawSquareToggle("shoe", ref _settings.EnableNavigation, togglePos + new Vector2(0, 34), "NavTgl"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) DashWindows.ShowNavigation = true; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Navigation — left-click to toggle, right-click for routes"); + + LegacyDashboardDrawing.DrawSquareToggle("bag", ref _settings.EnableLooting, togglePos + new Vector2(34, 34), "LootTgl"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) OpenAdvancedTab("Looting"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Looting — left-click to toggle, right-click for settings"); + + LegacyDashboardDrawing.DrawWideToggle("MACRO", "gear", ref _settings.EnableMeta, togglePos + new Vector2(0, 68), "MetaTgl", 64f, 20f); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) DashWindows.ShowMacroRules = true; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Macro/Meta — left-click to toggle, right-click for rules"); + + // FR (Force Rebuff) — small button, below MACRO toggle + Vector2 frPos = togglePos + new Vector2(0, 92); + ImGui.SetCursorScreenPos(frPos); + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.28f, 0.20f, 0.04f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.46f, 0.33f, 0.06f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.20f, 0.14f, 0.03f, 1.00f)); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3.0f); + if (ImGui.Button("FR##ForceRebuff", new Vector2(64, 16))) + OnForceRebuffRequested?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Force-recast all buffs.\nRight-click to cancel."); + if (ImGui.BeginPopupContextItem("##FRCtx")) + { + if (ImGui.MenuItem("Cancel Force Rebuff")) + OnCancelForceRebuffRequested?.Invoke(); + ImGui.EndPopup(); + } + ImGui.PopStyleVar(); + ImGui.PopStyleColor(3); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextDim, TruncateName(_targetLabel, 32).ToUpperInvariant()); + ImGui.SameLine(); + float targetValueWidth = ImGui.CalcTextSize(_targetHealthDisplay).X; + float targetLineX = ImGui.GetCursorPosX(); + float targetRegionWidth = ImGui.GetContentRegionAvail().X; + ImGui.SetCursorPosX(targetLineX + Math.Max(0, targetRegionWidth - targetValueWidth)); + ImGui.TextColored(new Vector4(1, 1, 1, 1), _targetHealthDisplay); + LegacyDashboardDrawing.DrawSegmentedBar(_targetHealthPercent, ImGui.GetContentRegionAvail().X - 4); + if (_settings.ShowTargetStaminaMana && _targetMaxStamina > 0) + { + float barWidth = ImGui.GetContentRegionAvail().X - 4; + LegacyDashboardDrawing.DrawCompactVitalBar("ST", ToRatio(_targetStamina, _targetMaxStamina), ColGreen, FormatVital(_targetStamina, _targetMaxStamina), barWidth); + LegacyDashboardDrawing.DrawCompactVitalBar("MN", ToRatio(_targetMana, _targetMaxMana), ColMana, FormatVital(_targetMana, _targetMaxMana), barWidth); + } + ImGui.Dummy(new Vector2(0, 2)); + ImGui.TextColored(ColTextMute, "PLAYER VITALS"); + LegacyDashboardDrawing.DrawVitalRow("heart", "HP", ToRatio(_playerHealth, _playerMaxHealth), ColHp, FormatVital(_playerHealth, _playerMaxHealth)); + LegacyDashboardDrawing.DrawVitalRow("run", "ST", ToRatio(_playerStamina, _playerMaxStamina), ColGreen, FormatVital(_playerStamina, _playerMaxStamina)); + LegacyDashboardDrawing.DrawVitalRow("drop", "MN", ToRatio(_playerMana, _playerMaxMana), ColMana, FormatVital(_playerMana, _playerMaxMana)); + ImGui.EndTable(); + } + + private void OpenAdvancedTab(string tabName) + { + for (int i = 0; i < _settings.AdvancedTabs.Length; i++) + { + if (string.Equals(_settings.AdvancedTabs[i], tabName, StringComparison.OrdinalIgnoreCase)) + { + _settings.SelectedAdvancedTab = i; + _settings.ShowAdvancedWindow = true; + return; + } + } + // Tab not found — at least open the window so the user lands somewhere useful. + _settings.ShowAdvancedWindow = true; + } + + private void RefreshPlayerVitals() + { + if (!_host.HasGetPlayerVitals) + return; + + if (_host.TryGetPlayerVitals( + out uint health, + out uint maxHealth, + out uint stamina, + out uint maxStamina, + out uint mana, + out uint maxMana)) + { + _playerHealth = health; + _playerMaxHealth = maxHealth != 0 ? maxHealth : _playerMaxHealth; + _playerStamina = stamina; + _playerMaxStamina = maxStamina != 0 ? maxStamina : _playerMaxStamina; + _playerMana = mana; + _playerMaxMana = maxMana != 0 ? maxMana : _playerMaxMana; + } + } + + /// Reset the per-session counters at login so the per-hour rates measure THIS session. + private void ResetSessionStats() + { + _sessionStartUtc = DateTime.UtcNow; + System.Threading.Interlocked.Exchange(ref _sessionKills, 0); + System.Threading.Interlocked.Exchange(ref _lastKillTicks, 0); + } + + /// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour + /// and the "time since last kill" liveness signal. + public void RecordKill() + { + System.Threading.Interlocked.Increment(ref _sessionKills); + System.Threading.Interlocked.Exchange(ref _lastKillTicks, DateTime.UtcNow.Ticks); + } + + /// Pushed from the plugin tick (it owns the inventory cache) — main-pack empty slots. -1 = unknown. + public void SetFreeSlots(int slots) => _freeSlots = slots; + + /// Pushed from the plugin tick — D2 three-tier target counts (-1 = no scan yet). + public void SetScanCounts(int total, int ring, int possible, int losBlocked) + { + _scanTotal = total; + _scanRing = ring; + _scanPossible = possible; + _scanLosBlocked = losBlocked; + } + + /// Pushed from the plugin tick — D6 offensive attack-cast tallies. + public void SetCastStats(int sessionAttackCasts, int castsSinceLastKill) + { + _sessionAttackCasts = sessionAttackCasts; + _castsSinceLastKill = castsSinceLastKill; + } + + private volatile bool _uiHidden; // remote "Hide UI" state, surfaced to the status feed + public void SetUiHidden(bool hidden) => _uiHidden = hidden; + + /// Pushed from the plugin tick — casting-component tallies (scarabs / prismatic tapers) and the + /// per-tier scarab breakdown. -1 = unknown; byType may be null (treated as empty). + public void SetComponentCounts(int scarabs, int tapers, List> byType) + { + _scarabs = scarabs; + _tapers = tapers; + _scarabsByType = byType != null ? byType.ToArray() : System.Array.Empty>(); + } + + /// Pushed from the plugin tick — the gear the character is wearing/wielding, with full appraisal. + public void SetEquipment(List equipment) + => _equipment = equipment != null ? equipment.ToArray() : System.Array.Empty(); + + /// Pushed from the plugin tick — the full read-only inventory (containers + items) for the remote + /// viewer. Atomic ref-swap of both arrays + a monotonic version bump (consumers detect change). + public void SetInventory(List containers, List items) + { + _invContainers = containers != null ? containers.ToArray() : System.Array.Empty(); + _invItems = items != null ? items.ToArray() : System.Array.Empty(); + System.Threading.Interlocked.Increment(ref _inventoryVersion); + } + + /// Serialize the full inventory (schema "rynthcore.inventory/1") for the dedicated + /// RynthPluginGetInventoryJson export. Own builder + 32KB initial capacity (the hot + /// BuildSnapshotJson stays lean at 2KB). Reads the volatile arrays once (atomic ref). + public string BuildInventoryJson() + { + var items = _invItems; + var containers = _invContainers; + int version = System.Threading.Interlocked.CompareExchange(ref _inventoryVersion, 0, 0); + var ci = System.Globalization.CultureInfo.InvariantCulture; + var sb = new System.Text.StringBuilder(32768); + sb.Append('{'); + AppendString(sb, "schema", "rynthcore.inventory/1"); sb.Append(','); + AppendInt(sb, "version", version); sb.Append(','); + AppendInt(sb, "itemCount", items.Length); sb.Append(','); + sb.Append("\"containers\":["); + for (int i = 0; i < containers.Length; i++) + { + var c = containers[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"id\":").Append(c.Id); + sb.Append(",\"name\":\""); AppendEscaped(sb, c.Name ?? string.Empty); sb.Append('"'); + sb.Append(",\"kind\":\""); AppendEscaped(sb, c.Kind ?? string.Empty); sb.Append('"'); + sb.Append(",\"capacity\":").Append(c.Capacity); + sb.Append('}'); + } + sb.Append("],\"items\":["); + for (int i = 0; i < items.Length; i++) + { + var it = items[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"id\":").Append(it.Id); + sb.Append(",\"name\":\""); AppendEscaped(sb, it.Name ?? string.Empty); sb.Append('"'); + sb.Append(",\"wcid\":").Append(it.Wcid); + sb.Append(",\"objectClass\":").Append(it.ObjectClass); + sb.Append(",\"containerId\":").Append(it.ContainerId); + sb.Append(",\"location\":").Append(it.Location); + sb.Append(",\"slot\":").Append(it.Slot); + sb.Append(",\"stackCount\":").Append(it.StackCount); + sb.Append(",\"iconDid\":").Append(it.IconDid); + sb.Append(",\"equipped\":").Append(it.Equipped ? "true" : "false"); + sb.Append(",\"wieldedLocation\":").Append(it.WieldedLocation); + sb.Append(",\"appraisal\":"); + if (it.Appraisal is { } a) AppendInventoryAppraisal(sb, a, ci); + else sb.Append("null"); + sb.Append('}'); + } + sb.Append("]}"); + return sb.ToString(); + } + + /// Emit the appraisal sub-object for an inventory item — same field shape/names as the + /// equipment entry in BuildSnapshotJson (minus name/id/slot, which live on the item), so the + /// app reuses the existing AcEquipItem appraisal fragment verbatim. + private static void AppendInventoryAppraisal(System.Text.StringBuilder sb, EquipAppraisal a, System.Globalization.CultureInfo ci) + { + sb.Append("{\"armorLevel\":").Append(a.ArmorLevel); + if (a.Resist is { Length: 7 }) + { + sb.Append(",\"resist\":["); + for (int r = 0; r < 7; r++) { if (r > 0) sb.Append(','); sb.Append(a.Resist[r].ToString("0.###", ci)); } + sb.Append(']'); + } + sb.Append(",\"value\":").Append(a.Value).Append(",\"burden\":").Append(a.Burden) + .Append(",\"workmanship\":").Append(a.Workmanship).Append(",\"material\":").Append(a.Material) + .Append(",\"maxMana\":").Append(a.MaxMana).Append(",\"curMana\":").Append(a.CurMana) + .Append(",\"damage\":").Append(a.Damage).Append(",\"damageType\":").Append(a.DamageType) + .Append(",\"weaponDef\":").Append(a.WeaponDef.ToString("0.###", ci)) + .Append(",\"missileDef\":").Append(a.MissileDef.ToString("0.###", ci)) + .Append(",\"magicDef\":").Append(a.MagicDef.ToString("0.###", ci)) + .Append(",\"variance\":").Append(a.Variance.ToString("0.###", ci)) + .Append(",\"elementalMod\":").Append(a.ElementalMod.ToString("0.###", ci)); + sb.Append(",\"spells\":["); + for (int s = 0; s < a.Spells.Length; s++) { if (s > 0) sb.Append(','); sb.Append('"'); AppendEscaped(sb, a.Spells[s] ?? string.Empty); sb.Append('"'); } + sb.Append(']'); + sb.Append(",\"longDesc\":\""); AppendEscaped(sb, a.LongDesc ?? string.Empty); sb.Append('"'); + sb.Append('}'); + } + + /// Whole-session kills/hour from the kill counter — a pure counter + clock, safe to compute + /// on the off-thread snapshot poll (no AC read). + private void RefreshKillsPerHour() + { + double hours = (DateTime.UtcNow - _sessionStartUtc).TotalHours; + _killsPerHour = hours > 1.0 / 3600.0 ? System.Threading.Interlocked.Read(ref _sessionKills) / hours : 0; + } + + private static float ToRatio(uint value, uint maxValue) + { + if (maxValue == 0) + return 0f; + + return Math.Clamp((float)value / maxValue, 0f, 1f); + } + + private static string FormatVital(uint value, uint maxValue) + { + if (maxValue == 0) + return value == 0 ? "--/--" : $"{value}/--"; + + return $"{value}/{maxValue}"; + } + + private void RenderLauncherGrid() + { + if (!ImGui.BeginTable("LauncherGridTable", 3, ImGuiTableFlags.SizingStretchSame)) return; + ImGui.TableNextRow(); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Macro Rules", "gear", ref DashWindows.ShowMacroRules); + ImGui.TableNextColumn(); + LegacyDashboardDrawing.GridBtn("Monsters", "target", ref DashWindows.ShowMonsters); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Settings", "wrench", ref _settings.ShowAdvancedWindow); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Navigation", "map", ref DashWindows.ShowNavigation); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Items", "shield", ref DashWindows.ShowWeapons); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Lua Scripts", "code", ref DashWindows.ShowLua); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); LegacyDashboardDrawing.GridBtn("Dungeon Map", "map", ref DashWindows.ShowDungeonMap); + ImGui.TableNextColumn(); + ImGui.EndTable(); + } + + private static void RenderPlaceholderWindow(string title, ref bool open, string message) + { + ImGui.SetNextWindowSize(new Vector2(420, 260), ImGuiCond.FirstUseEver); + if (!ImGui.Begin(title, ref open)) { ImGui.End(); return; } + ImGui.TextWrapped(message); + ImGui.End(); + } + + private void RefreshAllLists() + { + RefreshProfilesList(); + RefreshNavFiles(); + RefreshLootFiles(); + RefreshMetaFiles(); + } + + private void RefreshProfilesList() + { + var list = new List { "Default" }; + try + { + if (!string.IsNullOrEmpty(_charFolder) && Directory.Exists(_charFolder)) + { + foreach (string file in Directory.GetFiles(_charFolder, "*.json")) + { + string name = Path.GetFileNameWithoutExtension(file); + if (name.Equals("settings", StringComparison.OrdinalIgnoreCase)) continue; + if (name.Equals("Default", StringComparison.OrdinalIgnoreCase)) continue; + if (name.Equals("monsters", StringComparison.OrdinalIgnoreCase)) continue; + if (!list.Contains(name, StringComparer.OrdinalIgnoreCase)) + list.Add(name); + } + } + } + catch { } + // Deep-audit finding #16 (2026-06-18): Contains/[0] used to read + // _profiles just after releasing the lock — a concurrent + // SelectProfileAtIndex export call (poll thread) could be mid-index + // against a list this same read races. Moved inside the lock. + lock (_profileListsLock) + { + _profiles.Clear(); + _profiles.AddRange(list); + if (!_profiles.Contains(_settings.SelectedProfile, StringComparer.OrdinalIgnoreCase)) + _settings.SelectedProfile = _profiles[0]; + } + } + + private void RefreshNavFiles() + { + var list = new List { "None" }; + int sel = 0; + if (Directory.Exists(_navFolder)) + foreach (string file in Directory.GetFiles(_navFolder, "*.nav")) + { + list.Add(Path.GetFileNameWithoutExtension(file)); + if (file.Equals(_settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) sel = list.Count - 1; + } + lock (_profileListsLock) { _navFiles.Clear(); _navFiles.AddRange(list); } + _selectedNavIdx = sel; + } + + private void RefreshLootFiles() + { + var list = new System.Collections.Generic.List { "None" }; + int idx = _settings.LootProfileIdx; + if (Directory.Exists(_lootFolder)) + { + var files = new System.Collections.Generic.List(); + files.AddRange(Directory.GetFiles(_lootFolder, "*.utl")); + files.AddRange(Directory.GetFiles(_lootFolder, "*.json")); + files.Sort(StringComparer.OrdinalIgnoreCase); + + foreach (string file in files) + { + list.Add(Path.GetFileName(file)); + if (file.Equals(_settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase)) + idx = list.Count - 1; + } + } + lock (_profileListsLock) { _lootFiles.Clear(); _lootFiles.AddRange(list); } + _settings.LootProfileIdx = idx; + } + + private void RefreshMetaFiles() + { + var list = new List { "None" }; + int idx = 0; + if (Directory.Exists(_metaFolder)) + { + var files = new List(); + foreach (string f in Directory.GetFiles(_metaFolder, "*.met")) + { + if (Path.GetFileName(f).StartsWith("--")) continue; + files.Add(f); + } + files.AddRange(Directory.GetFiles(_metaFolder, "*.af")); + files.Sort(StringComparer.OrdinalIgnoreCase); + + foreach (string file in files) + { + list.Add(Path.GetFileName(file)); + if (file.Equals(_settings.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)) + idx = list.Count - 1; + } + } + lock (_profileListsLock) { _metaFiles.Clear(); _metaFiles.AddRange(list); } + _settings.MetaProfileIdx = idx; + } + + private void LoadSelectedNav() + { + // Same finding #16 class as SelectProfileAtIndex above — this direct + // index into _navFiles is also reachable from the Avalonia poll + // thread (via SelectProfileAtIndex) racing the pump thread's + // Refresh*Files Clear()/AddRange(). + string? selection; + lock (_profileListsLock) + { + if (_selectedNavIdx < 0 || _selectedNavIdx >= _navFiles.Count) return; + selection = _navFiles[_selectedNavIdx]; + } + if (selection == "None") + { + _settings.CurrentNavPath = string.Empty; + _settings.CurrentRoute.Points.Clear(); + _settings.ActiveNavIndex = 0; + SaveSettings(); + return; + } + string filePath = Path.Combine(_navFolder, selection + ".nav"); + _settings.CurrentNavPath = filePath; + _settings.CurrentRoute = NavRouteParser.Load(filePath); + if (_settings.CurrentRoute.LoadWarning != null) + { + _host.Log(_settings.CurrentRoute.LoadWarning); + _host.WriteToChat($"[RynthAi] {_settings.CurrentRoute.LoadWarning}", 4); + } + // Follow and Once routes start from the top so opening Recall/Portal/Chat + // actions always fire. Circular and Linear routes jump in at the nearest point. + _settings.ActiveNavIndex = + (_settings.CurrentRoute.RouteType == NavRouteType.Follow || + _settings.CurrentRoute.RouteType == NavRouteType.Once) + ? 0 + : FindNearestWaypoint(_settings.CurrentRoute); + SaveSettings(); + } + + // ── Nav bridge (engine-side Avalonia NavPanel) ──────────────────────────── + + public string BuildNavJson() + { + try + { + var points = new List(_settings.CurrentRoute.Points.Count); + for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++) + { + var p = _settings.CurrentRoute.Points[i]; + points.Add(new NavBridgePoint + { + Idx = i, + Type = p.Type.ToString(), + Desc = p.ToString(), + NS = p.NS, + EW = p.EW, + Z = p.Z, + }); + } + + int routeTypeInt = _settings.CurrentRoute.RouteType switch + { + NavRouteType.Circular => 1, + NavRouteType.Linear => 2, + NavRouteType.Follow => 3, + _ => 4, // Once + }; + + var payload = new NavBridgePayload + { + ActiveNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) + ? "None (Unsaved)" + : Path.GetFileName(_settings.CurrentNavPath), + NavStatusLine = _settings.NavStatusLine ?? string.Empty, + NavIsStuck = _settings.NavIsStuck, + MacroRunning = _settings.IsMacroRunning, + NavigationEnabled = _settings.EnableNavigation, + RouteType = routeTypeInt, + ActiveNavIndex = _settings.ActiveNavIndex, + NavFiles = new List(_navFiles), + Points = points, + }; + return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload); + } + catch { return "{}"; } + } + + public void HandleNavCommand(string json) + { + if (string.IsNullOrWhiteSpace(json)) return; + try + { + var cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.NavCommand); + if (cmd == null) return; + + switch (cmd.Cmd) + { + case "startNav": + _settings.IsMacroRunning = true; + _settings.EnableNavigation = true; + if (_settings.BotAction != "Navigating") + _settings.BotAction = "Default"; + SaveSettings(); + break; + + case "stopNav": + _settings.EnableNavigation = false; + SaveSettings(); + break; + + case "addWaypoint": + _host.SetMotion(0x6500000D, false); // stop TurnRight + _host.SetMotion(0x6500000E, false); // stop TurnLeft + if (_host.HasGetPlayerPose && + _host.TryGetPlayerPose(out _, out float wx, out float wy, out float wz, out _, out _, out _, out _) && + NavCoordinateHelper.TryGetNavCoords(_host, out double wNS, out double wEW)) + { + InsertNavPoint(new NavPoint { NS = wNS, EW = wEW, Z = wz }, cmd.AddMode, cmd.InsertAt); + } + break; + + case "addRecall": + if (_host.HasGetPlayerPose && + _host.TryGetPlayerPose(out _, out float rx, out float ry, out float rz, out _, out _, out _, out _) && + NavCoordinateHelper.TryGetNavCoords(_host, out double rNS, out double rEW)) + { + InsertNavPoint(new NavPoint { Type = NavPointType.Recall, NS = rNS, EW = rEW, Z = rz, SpellId = cmd.SpellId }, cmd.AddMode, cmd.InsertAt); + } + break; + + case "deletePoint": + int di = cmd.Index; + if (di >= 0 && di < _settings.CurrentRoute.Points.Count) + { + _settings.CurrentRoute.Points.RemoveAt(di); + if (_settings.ActiveNavIndex == di) _settings.ActiveNavIndex = 0; + else if (_settings.ActiveNavIndex > di) _settings.ActiveNavIndex--; + _navigationUi.TryAutoSaveNav(); + } + break; + + case "clearRoute": + _settings.CurrentRoute.Points.Clear(); + _settings.ActiveNavIndex = 0; + _navigationUi.TryAutoSaveNav(); + break; + + case "saveRoute": + if (!string.IsNullOrEmpty(_settings.CurrentNavPath)) + { + try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } catch { } + } + break; + + case "setRouteType": + _settings.CurrentRoute.RouteType = cmd.RouteType switch + { + 1 => NavRouteType.Circular, + 2 => NavRouteType.Linear, + 3 => NavRouteType.Follow, + _ => NavRouteType.Once, + }; + _navigationUi.TryAutoSaveNav(); + break; + + case "loadNav": + int ni = _navFiles.IndexOf(cmd.NavName); + if (ni >= 0) { _selectedNavIdx = ni; LoadSelectedNav(); SaveSettings(); } + break; + } + } + catch { } + } + + private void InsertNavPoint(NavPoint pt, int addMode, int insertAt) + { + if (addMode == 0 || _settings.CurrentRoute.Points.Count == 0 || insertAt < 0) + _settings.CurrentRoute.Points.Add(pt); + else if (addMode == 1) + _settings.CurrentRoute.Points.Insert(insertAt, pt); + else + _settings.CurrentRoute.Points.Insert(Math.Min(insertAt + 1, _settings.CurrentRoute.Points.Count), pt); + + _navigationUi.TryAutoSaveNav(); + } + + private int FindNearestWaypoint(NavRouteParser route) + { + if (route.Points.Count == 0 || !NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) return 0; + int best = 0; + double bestDistance = double.MaxValue; + for (int i = 0; i < route.Points.Count; i++) + { + NavPoint point = route.Points[i]; + if (point.Type != NavPointType.Point) continue; + double distance = Math.Sqrt(Math.Pow(point.NS - ns, 2) + Math.Pow(point.EW - ew, 2)); + if (distance < bestDistance) { bestDistance = distance; best = i; } + } + return best; + } + private static string TruncateName(string? value, int max) => string.IsNullOrEmpty(value) ? string.Empty : value.Length > max ? value[..(max - 1)] + "..." : value; + + // ── Snapshot bridge (read by the engine-side Avalonia RynthAi panel) ──── + // The Avalonia panel mirrors this dashboard. It pulls a JSON snapshot via + // RynthPluginGetSnapshotJson every ~33ms and renders the same fields. + + public string BuildSnapshotJson() + { + // Pull a fresh read every snapshot poll. If the cache is cold (right + // after hot reload), the host's TryGetPlayerVitals will still have + // returned zero — but the next OnUpdateHealth event or live qualities + // read will fix that within a tick or two. + RefreshPlayerVitals(); + RefreshKillsPerHour(); // pure counter/clock — safe off-thread + + var sb = new System.Text.StringBuilder(2048); + sb.Append('{'); + AppendBool(sb, "macroRunning", _settings.IsMacroRunning); sb.Append(','); + AppendString(sb, "currentState", _settings.CurrentState ?? string.Empty); sb.Append(','); + AppendString(sb, "botAction", _settings.BotAction ?? "Default"); sb.Append(','); + AppendString(sb, "selectedProfile", _settings.SelectedProfile ?? "Default"); sb.Append(','); + // Copy the four profile lists under the lock so we never enumerate one + // while a Refresh*Files mutator Clear()s it on the pump thread — that + // race threw InvalidOperationException and, escaping this snapshot + // poll's reverse-P/Invoke boundary, fail-fasted the NativeAOT runtime. + List profilesCopy, navCopy, lootCopy, metaCopy; + lock (_profileListsLock) + { + profilesCopy = new List(_profiles); + navCopy = new List(_navFiles); + lootCopy = new List(_lootFiles); + metaCopy = new List(_metaFiles); + } + AppendStringArray(sb, "profiles", profilesCopy); sb.Append(','); + AppendStringArray(sb, "navProfiles", navCopy); sb.Append(','); + AppendStringArray(sb, "lootProfiles", lootCopy); sb.Append(','); + AppendStringArray(sb, "metaProfiles", metaCopy); sb.Append(','); + AppendString(sb, "currentNavName", + string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(','); + AppendString(sb, "currentLootName", + string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(','); + AppendString(sb, "currentMetaName", + string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath)); sb.Append(','); + AppendInt(sb, "selectedNavIdx", _selectedNavIdx); sb.Append(','); + AppendInt(sb, "selectedLootIdx", _settings.LootProfileIdx); sb.Append(','); + AppendInt(sb, "selectedMetaIdx", _settings.MetaProfileIdx); sb.Append(','); + AppendInt(sb, "selectedProfileIdx", Math.Max(0, profilesCopy.IndexOf(_settings.SelectedProfile ?? string.Empty))); sb.Append(','); + AppendBool(sb, "combatEnabled", _settings.EnableCombat); sb.Append(','); + AppendBool(sb, "buffingEnabled", _settings.EnableBuffing); sb.Append(','); + AppendBool(sb, "navigationEnabled", _settings.EnableNavigation); sb.Append(','); + AppendBool(sb, "lootingEnabled", _settings.EnableLooting); sb.Append(','); + AppendBool(sb, "metaEnabled", _settings.EnableMeta); sb.Append(','); + AppendUInt(sb, "currentTargetId", _currentTargetId); sb.Append(','); + AppendString(sb, "targetLabel", _targetLabel ?? "NO TARGET"); sb.Append(','); + AppendFloat(sb, "targetHealthPercent", _targetHealthPercent); sb.Append(','); + AppendString(sb, "targetHealthDisplay", _targetHealthDisplay ?? "0"); sb.Append(','); + AppendUInt(sb, "targetHealth", _targetHealth); sb.Append(','); + AppendUInt(sb, "targetMaxHealth", _targetMaxHealth); sb.Append(','); + AppendUInt(sb, "targetStamina", _targetStamina); sb.Append(','); + AppendUInt(sb, "targetMaxStamina", _targetMaxStamina); sb.Append(','); + AppendUInt(sb, "targetMana", _targetMana); sb.Append(','); + AppendUInt(sb, "targetMaxMana", _targetMaxMana); sb.Append(','); + AppendUInt(sb, "playerHealth", _playerHealth); sb.Append(','); + AppendUInt(sb, "playerMaxHealth", _playerMaxHealth); sb.Append(','); + AppendUInt(sb, "playerStamina", _playerStamina); sb.Append(','); + AppendUInt(sb, "playerMaxStamina", _playerMaxStamina); sb.Append(','); + AppendUInt(sb, "playerMana", _playerMana); sb.Append(','); + AppendUInt(sb, "playerMaxMana", _playerMaxMana); sb.Append(','); + AppendBool(sb, "showTargetStaminaMana", _settings.ShowTargetStaminaMana); sb.Append(','); + AppendBool(sb, "isLocked", _isLocked); sb.Append(','); + AppendBool(sb, "isMinimized", _isMinimized); sb.Append(','); + AppendFloat(sb, "bgOpacity", _bgOpacity); sb.Append(','); + // kills/hour, session kills, last-kill age, and free pack slots are bot-derived + // (kill counter + inventory cache); the rest of the player stats are engine top-level. + AppendFloat(sb, "killsPerHour", (float)_killsPerHour); sb.Append(','); + AppendInt(sb, "sessionKills", (int)System.Threading.Interlocked.Read(ref _sessionKills)); sb.Append(','); + long lastKillTicks = System.Threading.Interlocked.Read(ref _lastKillTicks); + int secsSinceLastKill = lastKillTicks == 0 + ? -1 + : (int)Math.Clamp((DateTime.UtcNow - new DateTime(lastKillTicks, DateTimeKind.Utc)).TotalSeconds, 0, int.MaxValue); + AppendInt(sb, "secsSinceLastKill", secsSinceLastKill); sb.Append(','); + AppendInt(sb, "freeSlots", _freeSlots); sb.Append(','); + // D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning). + AppendInt(sb, "scanTotal", _scanTotal); sb.Append(','); + AppendInt(sb, "scanRing", _scanRing); sb.Append(','); + AppendInt(sb, "scanPossible", _scanPossible); sb.Append(','); + AppendInt(sb, "scanLosBlocked", _scanLosBlocked); sb.Append(','); + AppendInt(sb, "sessionAttackCasts", _sessionAttackCasts); sb.Append(','); + AppendInt(sb, "castsSinceLastKill", _castsSinceLastKill); sb.Append(','); + int killsForRatio = (int)System.Threading.Interlocked.Read(ref _sessionKills); + AppendFloat(sb, "castsPerKill", killsForRatio > 0 ? (float)_sessionAttackCasts / killsForRatio : 0f); sb.Append(','); + AppendBool(sb, "uiHidden", _uiHidden); sb.Append(','); + AppendInt(sb, "scarabs", _scarabs); sb.Append(','); + AppendInt(sb, "tapers", _tapers); sb.Append(','); + // Per-tier scarab breakdown: [{"name":"Lead Scarab","count":N}, ...] + var byType = _scarabsByType; + sb.Append("\"scarabsByType\":["); + for (int i = 0; i < byType.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"name\":\""); + AppendEscaped(sb, byType[i].Key ?? string.Empty); + sb.Append("\",\"count\":").Append(byType[i].Value).Append('}'); + } + sb.Append("],"); + // Equipped gear with full appraisal: name/id/slot + armor/resist/weapon/value/mana/spells/desc. + var equip = _equipment; + var inv = System.Globalization.CultureInfo.InvariantCulture; + sb.Append("\"equipment\":["); + for (int i = 0; i < equip.Length; i++) + { + var a = equip[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"name\":\""); + AppendEscaped(sb, a.Name ?? string.Empty); + sb.Append("\",\"id\":").Append(a.Id).Append(",\"slot\":").Append(a.Slot); + sb.Append(",\"armorLevel\":").Append(a.ArmorLevel); + if (a.Resist is { Length: 7 }) + { + sb.Append(",\"resist\":["); + for (int r = 0; r < 7; r++) { if (r > 0) sb.Append(','); sb.Append(a.Resist[r].ToString("0.###", inv)); } + sb.Append(']'); + } + sb.Append(",\"value\":").Append(a.Value).Append(",\"burden\":").Append(a.Burden) + .Append(",\"workmanship\":").Append(a.Workmanship).Append(",\"material\":").Append(a.Material) + .Append(",\"maxMana\":").Append(a.MaxMana).Append(",\"curMana\":").Append(a.CurMana) + .Append(",\"damage\":").Append(a.Damage).Append(",\"damageType\":").Append(a.DamageType) + .Append(",\"weaponDef\":").Append(a.WeaponDef.ToString("0.###", inv)) + .Append(",\"missileDef\":").Append(a.MissileDef.ToString("0.###", inv)) + .Append(",\"magicDef\":").Append(a.MagicDef.ToString("0.###", inv)) + .Append(",\"variance\":").Append(a.Variance.ToString("0.###", inv)) + .Append(",\"elementalMod\":").Append(a.ElementalMod.ToString("0.###", inv)); + sb.Append(",\"spells\":["); + for (int s = 0; s < a.Spells.Length; s++) { if (s > 0) sb.Append(','); sb.Append('"'); AppendEscaped(sb, a.Spells[s] ?? string.Empty); sb.Append('"'); } + sb.Append(']'); + sb.Append(",\"longDesc\":\""); AppendEscaped(sb, a.LongDesc ?? string.Empty); sb.Append('"'); + sb.Append('}'); + } + sb.Append(']'); + // Recent chat lines for the phone chat view: [{"t":"text","c":}, ...] (oldest->newest). + sb.Append(",\"recentChat\":["); + var chat = _rynthChatUi.SnapshotRecent(60); + for (int i = 0; i < chat.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"t\":\""); + AppendEscaped(sb, chat[i].Text ?? string.Empty); + sb.Append("\",\"c\":").Append(chat[i].Type).Append('}'); + } + sb.Append(']'); + sb.Append('}'); + return sb.ToString(); + } + + public void TogglePanelMacro() => _settings.IsMacroRunning = !_settings.IsMacroRunning; + + public void SetSubsystemEnabled(int id, bool enabled) + { + switch (id) + { + case 0: _settings.EnableCombat = enabled; break; + case 1: _settings.EnableBuffing = enabled; break; + case 2: _settings.EnableNavigation = enabled; break; + case 3: _settings.EnableLooting = enabled; break; + case 4: _settings.EnableMeta = enabled; break; + } + SaveSettings(); + } + + /// + /// Profile kinds: 0 = nav, 1 = loot, 2 = meta, 3 = settings profile. + /// Index is into the matching list returned in BuildSnapshotJson. + /// + public void SelectProfileAtIndex(int kind, int index) + { + // Deep-audit finding #16 (2026-06-18): this export (poll thread) used + // to bounds-check and index _navFiles/_lootFiles/_metaFiles/_profiles + // with no lock at all, racing the Refresh*Files mutators' Clear()/ + // AddRange() on the pump thread — a torn read or + // ArgumentOutOfRangeException. Snapshot the one list this call needs + // under _profileListsLock first, mirroring BuildSnapshotJson. + string? navFile = null, lootFile = null, metaFile = null, profileName = null; + lock (_profileListsLock) + { + switch (kind) + { + case 0: if (index >= 0 && index < _navFiles.Count) navFile = _navFiles[index]; break; + case 1: if (index >= 0 && index < _lootFiles.Count) lootFile = _lootFiles[index]; break; + case 2: if (index >= 0 && index < _metaFiles.Count) metaFile = _metaFiles[index]; break; + case 3: if (index >= 0 && index < _profiles.Count) profileName = _profiles[index]; break; + } + } + + switch (kind) + { + case 0: + if (navFile != null) { _selectedNavIdx = index; LoadSelectedNav(); } + break; + case 1: + if (lootFile != null) + { + _settings.LootProfileIdx = index; + _settings.CurrentLootPath = index == 0 ? string.Empty : Path.Combine(_lootFolder, lootFile); + SaveSettings(); + } + break; + case 2: + if (metaFile != null) + { + _settings.MetaProfileIdx = index; + string path = index == 0 ? string.Empty : Path.Combine(_metaFolder, metaFile); + _metaUi.LoadMacroFile(path); + SaveSettings(); + } + break; + case 3: + if (profileName != null) SwitchProfile(profileName); + break; + } + } + + public void RequestForceRebuff() => OnForceRebuffRequested?.Invoke(); + public void RequestCancelForceRebuff() => OnCancelForceRebuffRequested?.Invoke(); + public void AdjustOpacity(float delta) => _bgOpacity = Math.Clamp(_bgOpacity + delta, 0.1f, 1f); + public void TogglePanelLock() => _isLocked = !_isLocked; + public void TogglePanelMinimize() { _isMinimized = !_isMinimized; SaveSettings(); } + public bool IsPanelLocked => _isLocked; + public bool IsPanelMinimized => _isMinimized; + + private static void AppendString(System.Text.StringBuilder sb, string key, string value) + { + sb.Append('"').Append(key).Append("\":\""); + AppendEscaped(sb, value); + sb.Append('"'); + } + + private static void AppendBool(System.Text.StringBuilder sb, string key, bool value) + => sb.Append('"').Append(key).Append("\":").Append(value ? "true" : "false"); + + private static void AppendInt(System.Text.StringBuilder sb, string key, int value) + => sb.Append('"').Append(key).Append("\":").Append(value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + + private static void AppendUInt(System.Text.StringBuilder sb, string key, uint value) + => sb.Append('"').Append(key).Append("\":").Append(value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + + private static void AppendFloat(System.Text.StringBuilder sb, string key, float value) + { + if (float.IsNaN(value) || float.IsInfinity(value)) value = 0f; + sb.Append('"').Append(key).Append("\":").Append(value.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture)); + } + + private static void AppendStringArray(System.Text.StringBuilder sb, string key, IEnumerable values) + { + sb.Append('"').Append(key).Append("\":["); + bool first = true; + foreach (string v in values) + { + if (!first) sb.Append(','); + first = false; + sb.Append('"'); + AppendEscaped(sb, v ?? string.Empty); + sb.Append('"'); + } + sb.Append(']'); + } + + private static void AppendEscaped(System.Text.StringBuilder sb, string value) + { + foreach (char c in value) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\b': sb.Append("\\b"); break; + case '\f': sb.Append("\\f"); 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").Append(((int)c).ToString("X4")); + else sb.Append(c); + break; + } + } + } + + // ── Meta bridge ─────────────────────────────────────────────────────────── + + private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + + public string BuildMetaJson() + { + // Avalonia dispatcher thread — MetaManager.Think enumerates MetaRules on + // the plugin-tick thread. Snapshot under the shared lock. + lock (_settings.MetaRulesLock) + { + var sb = new System.Text.StringBuilder(); + sb.Append('{'); + AppendBool(sb, "enableMeta", _settings.EnableMeta); sb.Append(','); + AppendBool(sb, "metaDebug", _settings.MetaDebug); sb.Append(','); + AppendString(sb, "currentState", _settings.CurrentState ?? "Default"); sb.Append(','); + AppendString(sb, "currentMetaPath", _settings.CurrentMetaPath ?? ""); sb.Append(','); + + sb.Append("\"rules\":"); + AppendMetaRuleArray(sb, _settings.MetaRules); + sb.Append(','); + + var files = BuildMetaFileList(); + sb.Append("\"files\":["); + for (int i = 0; i < files.Count; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"path\":\""); AppendEscaped(sb, files[i].Item1); sb.Append("\",\"display\":\""); AppendEscaped(sb, files[i].Item2); sb.Append("\"}"); + } + sb.Append("],"); + + var states = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!states.Contains("Default")) states.Add("Default"); + states = states.OrderBy(s => s, System.StringComparer.OrdinalIgnoreCase).ToList(); + AppendStringArray(sb, "states", states); sb.Append(','); + + AppendStringArray(sb, "navFiles", _navFiles); sb.Append(','); + AppendStringArray(sb, "embeddedNavKeys", _settings.EmbeddedNavs.Keys); sb.Append(','); + + string sourceText = ""; + try { sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs); } catch { } + AppendString(sb, "sourceText", sourceText); + + var snap = MetaSnapshotProvider?.Invoke(); + if (snap != null) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + sb.Append(",\"snapshot\":{"); + AppendBool(sb, "macroRunning", snap.MacroRunning); sb.Append(','); + AppendBool(sb, "metaEnabled", snap.MetaEnabled); sb.Append(','); + AppendString(sb, "currentState", snap.CurrentState); sb.Append(','); + sb.Append("\"secondsInState\":").Append(snap.SecondsInState.ToString("F1", inv)).Append(','); + sb.Append("\"stackDepth\":").Append(snap.StackDepth).Append(','); + sb.Append("\"ruleCount\":").Append(snap.RuleCount).Append(','); + sb.Append("\"stateCount\":").Append(snap.StateCount).Append(','); + AppendBool(sb, "watchdogActive", snap.WatchdogActive); sb.Append(','); + AppendString(sb, "watchdogState", snap.WatchdogState); sb.Append(','); + sb.Append("\"watchdogSecondsRemaining\":").Append(snap.WatchdogSecondsRemaining.ToString("F1", inv)).Append(','); + AppendString(sb, "lastFiredState", snap.LastFiredState); sb.Append(','); + AppendString(sb, "lastFiredCondition", snap.LastFiredCondition); sb.Append(','); + AppendString(sb, "lastFiredAction", snap.LastFiredAction); sb.Append(','); + sb.Append("\"lastFiredSecondsAgo\":").Append(snap.LastFiredSecondsAgo.ToString("F1", inv)).Append(','); + AppendString(sb, "lastExprError", snap.LastExprError); sb.Append(','); + sb.Append("\"lastExprErrorSecondsAgo\":").Append(snap.LastExprErrorSecondsAgo.ToString("F1", inv)); + sb.Append('}'); + } + + sb.Append('}'); + return sb.ToString(); + } + } + + private List<(string, string)> BuildMetaFileList() + { + var result = new List<(string, string)>(); + result.Add(("", "-- None --")); + try + { + System.IO.Directory.CreateDirectory(MetaFolder); + var entries = new List<(string, string)>(); + foreach (string f in System.IO.Directory.GetFiles(MetaFolder, "*.met")) + { + string name = System.IO.Path.GetFileName(f); + if (!name.StartsWith("--")) entries.Add((f, $"[met] {name}")); + } + foreach (string f in System.IO.Directory.GetFiles(MetaFolder, "*.af")) + entries.Add((f, $"[af] {System.IO.Path.GetFileName(f)}")); + entries.Sort((a, b) => string.Compare(a.Item2, b.Item2, System.StringComparison.OrdinalIgnoreCase)); + result.AddRange(entries); + } + catch (System.Exception ex) + { + // Was a silent catch — surface it (§2.8 philosophy) but don't spam: + // this only fires on an actual directory/IO failure, not per refresh. + _host.Log($"[Meta] BuildMetaFileList FAILED for '{MetaFolder}': {ex.GetType().Name}: {ex.Message}"); + } + return result; + } + + private static void AppendMetaRuleArray(System.Text.StringBuilder sb, List rules) + { + sb.Append('['); + for (int i = 0; i < rules.Count; i++) + { + if (i > 0) sb.Append(','); + AppendMetaRule(sb, rules[i]); + } + sb.Append(']'); + } + + private static void AppendMetaRule(System.Text.StringBuilder sb, MetaRule r) + { + sb.Append('{'); + sb.Append("\"state\":\""); AppendEscaped(sb, r.State ?? "Default"); sb.Append("\","); + sb.Append("\"condition\":").Append((int)r.Condition).Append(','); + sb.Append("\"conditionData\":\""); AppendEscaped(sb, r.ConditionData ?? ""); sb.Append("\","); + sb.Append("\"action\":").Append((int)r.Action).Append(','); + sb.Append("\"actionData\":\""); AppendEscaped(sb, r.ActionData ?? ""); sb.Append("\","); + sb.Append("\"children\":"); AppendMetaRuleArray(sb, r.Children ?? new List()); sb.Append(','); + sb.Append("\"actionChildren\":"); AppendMetaRuleArray(sb, r.ActionChildren ?? new List()); sb.Append(','); + sb.Append("\"enabled\":").Append(r.Enabled ? "true" : "false").Append(','); + long ms = r.LastFiredAt == DateTime.MinValue ? 99999L : (long)(DateTime.Now - r.LastFiredAt).TotalMilliseconds; + sb.Append("\"lastFiredMs\":").Append(ms.ToString(System.Globalization.CultureInfo.InvariantCulture)); + sb.Append('}'); + } + + /// Called from the Avalonia dispatcher (RynthPluginSendMetaCommand). + /// Queue only — applied on the plugin-tick thread via DrainMetaCommands so + /// the mutation is serialised with MetaManager.Think rather than racing it. + /// (Index-vs-id snapshot staleness still needs an engine-side schema change; + /// deferred while the engine is in release-hold soak.) + public void HandleMetaCommand(string json) + { + if (!string.IsNullOrWhiteSpace(json)) _metaCmdQueue.Enqueue(json); + } + + /// Drains queued meta commands on the plugin-tick thread. + public void DrainMetaCommands() + { + while (_metaCmdQueue.TryDequeue(out var j)) ApplyMetaCommand(j); + } + + private void ApplyMetaCommand(string json) + { + if (string.IsNullOrWhiteSpace(json)) return; + try + { + var cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MetaCommand); + if (cmd == null) return; + + // Avalonia dispatcher thread — every mutating case races + // MetaManager.Think on the plugin-tick thread. + lock (_settings.MetaRulesLock) + switch (cmd.Op) + { + case "set_enabled": + _settings.EnableMeta = string.Equals(cmd.Value, "true", System.StringComparison.OrdinalIgnoreCase); + SaveSettings(); + break; + + case "set_debug": + _settings.MetaDebug = string.Equals(cmd.Value, "true", System.StringComparison.OrdinalIgnoreCase); + SaveSettings(); + break; + + case "set_state": + if (!string.IsNullOrEmpty(cmd.Value)) + { + _settings.CurrentState = cmd.Value; + _settings.ForceStateReset = true; + } + break; + + case "load_file": + _metaUi.LoadMacroFile(cmd.Path ?? ""); + { + var w = _metaUi.LastLoadWarnings; + _host.WriteToChat( + $"[RynthAi] Meta load: {_settings.MetaRules.Count} rules from {System.IO.Path.GetFileName(cmd.Path ?? "")}" + + (w.Count > 0 ? $" — {w.Count} warning(s): {w[0]}" : ""), 1); + } + break; + + case "save_file": + if (!string.IsNullOrEmpty(cmd.Path)) + { + AfFileWriter.Save(cmd.Path, _settings.MetaRules, _settings.EmbeddedNavs); + _settings.CurrentMetaPath = cmd.Path; + SaveSettings(); + } + break; + + case "set_source": + if (!string.IsNullOrEmpty(cmd.Text)) + { + try + { + var loaded = AfFileParser.LoadFromText(cmd.Text); + string w = loaded.Warnings.Count > 0 + ? $" — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}" : ""; + if (loaded.Rules.Count > 0) + { + _settings.MetaRules = loaded.Rules; + _settings.EmbeddedNavs.Clear(); + foreach (var kvp in loaded.EmbeddedNavs) _settings.EmbeddedNavs[kvp.Key] = kvp.Value; + _settings.ForceStateReset = true; + TryAutoSaveMetaCmd(); + _host.WriteToChat($"[RynthAi] Applied source: {loaded.Rules.Count} rules{w}", 1); + } + else + { + _host.WriteToChat($"[RynthAi] Source not applied: 0 rules parsed{(w.Length > 0 ? w : " — check syntax")}", 1); + } + } + catch (System.Exception ex) + { + _host.WriteToChat($"[RynthAi] Source apply error: {ex.Message}", 1); + } + } + break; + + case "add_rule": + if (cmd.Rule != null) + { + _settings.MetaRules.Add(DtoToMetaRule(cmd.Rule)); + TryAutoSaveMetaCmd(); + } + break; + + case "update_rule": + if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) + { + _settings.MetaRules[cmd.Index] = DtoToMetaRule(cmd.Rule); + TryAutoSaveMetaCmd(); + } + break; + + case "delete_rule": + if (cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) + { + _settings.MetaRules.RemoveAt(cmd.Index); + TryAutoSaveMetaCmd(); + } + break; + + case "move_up": + if (cmd.Index > 0 && cmd.Index < _settings.MetaRules.Count) + { + var tmp = _settings.MetaRules[cmd.Index - 1]; + _settings.MetaRules[cmd.Index - 1] = _settings.MetaRules[cmd.Index]; + _settings.MetaRules[cmd.Index] = tmp; + TryAutoSaveMetaCmd(); + } + break; + + case "move_down": + if (cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count - 1) + { + var tmp = _settings.MetaRules[cmd.Index + 1]; + _settings.MetaRules[cmd.Index + 1] = _settings.MetaRules[cmd.Index]; + _settings.MetaRules[cmd.Index] = tmp; + TryAutoSaveMetaCmd(); + } + break; + + case "duplicate_rule": + if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) + { + _settings.MetaRules.Insert(cmd.Index + 1, DtoToMetaRule(cmd.Rule)); + TryAutoSaveMetaCmd(); + } + break; + + case "set_rule_enabled": + if (cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) + { + _settings.MetaRules[cmd.Index].Enabled = + string.Equals(cmd.Value, "true", System.StringComparison.OrdinalIgnoreCase); + TryAutoSaveMetaCmd(); + } + break; + } + } + catch { } + } + + private void TryAutoSaveMetaCmd() + { + _settings.MetaRulesStructuralVersion++; // editor mutation → rebuild meta index + if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) return; + try + { + string path = _settings.CurrentMetaPath; + if (System.IO.Path.GetExtension(path).Equals(".met", System.StringComparison.OrdinalIgnoreCase)) + { + path = System.IO.Path.ChangeExtension(path, ".af"); + _settings.CurrentMetaPath = path; + _host.WriteToChat($"[RynthAi] Converted .met → {System.IO.Path.GetFileName(path)} for editing (original .met left untouched).", 1); + } + lock (_settings.MetaRulesLock) + AfFileWriter.Save(path, _settings.MetaRules, _settings.EmbeddedNavs); + } + catch { } + } + + private static MetaRule DtoToMetaRule(MetaRuleDto dto) + { + var r = new MetaRule + { + State = dto.State ?? "Default", + Condition = (MetaConditionType)dto.Condition, + ConditionData = dto.ConditionData ?? "", + Action = (MetaActionType)dto.Action, + ActionData = dto.ActionData ?? "", + Enabled = dto.Enabled, + }; + foreach (var c in dto.Children ?? new List()) + r.Children.Add(DtoToMetaRule(c)); + foreach (var a in dto.ActionChildren ?? new List()) + r.ActionChildren.Add(DtoToMetaRule(a)); + return r; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs new file mode 100644 index 0000000..4c883aa --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -0,0 +1,1252 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.Meta; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +internal sealed class LegacyMetaUi +{ + private readonly LegacyUiSettings _settings; + private readonly List _navFiles; + + private bool _showMetaEditor; + private MetaRule _editingRule = new(); + + // Indices of rules whose multi-action body is expanded inline. The user + // toggles this via right-click on the row — left-click opens the editor. + private readonly HashSet _expandedRuleIndices = new(); + + // ── Popped-out expression editor ───────────────────────────────────── + // Right-clicking a condition/action expression input opens a much larger + // multi-line window so long expressions are easy to read and edit. + private bool _exprPopupOpen; + private string _exprPopupTitle = ""; + private string _exprPopupBuffer = ""; + private Action? _exprPopupApply; + private bool _exprPopupRequestFocus; + private int _editingRuleIndex = -1; + private string _newStateName = ""; + private bool _openCreateStatePopup; + + // ── Source view state ──────────────────────────────────────────────── + private bool _showSourceView; + private string _sourceText = string.Empty; + private string _sourceApplyMessage = ""; + private DateTime _sourceApplyTime = DateTime.MinValue; + + // ── Load/Save state ────────────────────────────────────────────────── + private bool _openSavePopup; + private List<(string Path, string Display)> _macroFiles = new(); + private int _selectedFileIdx = -1; + private string _saveName = "macro"; + private string _statusMessage = ""; + private DateTime _statusTime = DateTime.MinValue; + + private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + + /// Warnings from the most recent LoadMacroFile, so the Avalonia + /// bridge can surface them too (it doesn't see the LoadedMeta). + internal IReadOnlyList LastLoadWarnings { get; private set; } = System.Array.Empty(); + + // §3.3: labels come from the single source of truth (MetaSchema), indexed + // by enum int — same strings as before, no longer a hand-synced copy. + private readonly string[] _metaConditionNames = RynthCore.Plugin.RynthAi.Meta.MetaSchema.ConditionLabels; + private readonly string[] _metaActionNames = RynthCore.Plugin.RynthAi.Meta.MetaSchema.ActionLabels; + + public LegacyMetaUi(LegacyUiSettings settings, List navFiles) + { + _settings = settings; + _navFiles = navFiles; + } + + public void Render() + { + if (!DashWindows.ShowMacroRules) return; + + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 8.0f); + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 6.0f); + ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.04f, 0.06f, 0.08f, 0.97f)); + + try + { + ImGui.SetNextWindowSize(new Vector2(600, 460), ImGuiCond.FirstUseEver); + bool windowOpen = ImGui.Begin("Macro Rules##RynthAiMacroRules", ref DashWindows.ShowMacroRules); + try + { + if (windowOpen) + RenderContents(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[MetaUi] RenderContents error: {ex.Message}"); + } + finally + { + ImGui.End(); + } + } + finally + { + ImGui.PopStyleColor(1); + ImGui.PopStyleVar(3); + } + } + + private void RenderContents() + { + // ── Load / Save bar ────────────────────────────────────────────── + RenderLoadSaveBar(); + ImGui.Spacing(); + + // ── Visual / Source toggle ─────────────────────────────────────── + // Always push/pop unconditionally — conditional push/pop is easy to misbalance + // if an exception fires between push and pop. + bool wasSource = _showSourceView; + var defaultBtnCol = ImGui.GetStyle().Colors[(int)ImGuiCol.Button]; + var activeBtnCol = new Vector4(0.15f, 0.35f, 0.6f, 1f); + + ImGui.PushStyleColor(ImGuiCol.Button, wasSource ? defaultBtnCol : activeBtnCol); + if (ImGui.Button("Visual", new Vector2(60, 0)) && _showSourceView) + _showSourceView = false; + ImGui.PopStyleColor(); + + ImGui.SameLine(); + + ImGui.PushStyleColor(ImGuiCol.Button, wasSource ? activeBtnCol : defaultBtnCol); + if (ImGui.Button("Source", new Vector2(60, 0)) && !_showSourceView) + { + // Switching to source: serialise current rules + _sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs); + _showSourceView = true; + } + ImGui.PopStyleColor(); + + ImGui.Spacing(); + + // ── Source view ────────────────────────────────────────────────── + if (_showSourceView) + { + float availH = ImGui.GetContentRegionAvail().Y - 30; + ImGui.InputTextMultiline("##afSource", ref _sourceText, 1024 * 1024, + new Vector2(-1, availH), + ImGuiInputTextFlags.AllowTabInput); + + if (!string.IsNullOrEmpty(_sourceApplyMessage) && + (DateTime.Now - _sourceApplyTime).TotalSeconds < 4) + { + ImGui.TextColored(new Vector4(0, 1, 0.4f, 1f), _sourceApplyMessage); + ImGui.SameLine(); + } + + if (ImGui.Button("Apply", new Vector2(80, 0))) + { + try + { + var loaded = AfFileParser.LoadFromText(_sourceText); + string warn = loaded.Warnings.Count == 0 ? "" + : $" — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}"; + if (loaded.Rules.Count == 0) + { + _sourceApplyMessage = $"No rules parsed — check syntax.{warn}"; + } + else + { + lock (_settings.MetaRulesLock) + { + _settings.MetaRules = loaded.Rules; + _settings.EmbeddedNavs.Clear(); + foreach (var kvp in loaded.EmbeddedNavs) + _settings.EmbeddedNavs[kvp.Key] = kvp.Value; + } + _settings.ForceStateReset = true; + TryAutoSaveMeta(); + _sourceApplyMessage = $"Applied {loaded.Rules.Count} rules.{warn}"; + } + } + catch (Exception ex) + { + _sourceApplyMessage = $"Error: {ex.Message}"; + } + _sourceApplyTime = DateTime.Now; + } + + ImGui.SameLine(); + if (ImGui.Button("Revert", new Vector2(80, 0))) + { + _sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs); + _sourceApplyMessage = "Reverted to current rules."; + _sourceApplyTime = DateTime.Now; + } + + RenderMetaEditorPopup(); + return; + } + + // ── Visual view ────────────────────────────────────────────────── + // Snapshot under the lock (Think mutates MetaRules on the plugin-tick + // thread). GroupBy+ToList fully materialises, so the render below works + // off the snapshot, not the live list. + List> groupedRules; + lock (_settings.MetaRulesLock) + { + groupedRules = _settings.MetaRules + .GroupBy(r => r.State) + .OrderBy(g => g.Key) + .ToList(); + } + + if (ImGui.BeginChild("##metaRulesScroll", new Vector2(0, -35), ImGuiChildFlags.None)) + { + foreach (var group in groupedRules) + { + var stateRules = group.ToList(); + bool anyFired = false; + foreach (var r in stateRules) + { + if ((DateTime.Now - r.LastFiredAt).TotalMilliseconds < 1500) + { + anyFired = true; + break; + } + } + + string headerLabel = anyFired + ? $"{group.Key} ({stateRules.Count}) - firing##hdr_{group.Key}" + : $"{group.Key} ({stateRules.Count})##hdr_{group.Key}"; + + if (anyFired) ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.2f, 0.2f, 1f)); + bool open = ImGui.CollapsingHeader(headerLabel, ImGuiTreeNodeFlags.DefaultOpen); + if (anyFired) ImGui.PopStyleColor(); + + if (!open) continue; + + if (!ImGui.BeginTable($"##tbl_{group.Key}", 5, + ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.RowBg)) + { + continue; + } + ImGui.TableSetupColumn("Up", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Dn", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 25); + ImGui.TableSetupColumn("Condition", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags.WidthStretch); + + for (int i = 0; i < stateRules.Count; i++) + { + var rule = stateRules[i]; + int globalIdx = _settings.MetaRules.IndexOf(rule); + + ImGui.TableNextRow(); + + double fadeMs = (DateTime.Now - rule.LastFiredAt).TotalMilliseconds; + bool isFlashing = fadeMs < 1500; + if (isFlashing) + { + float t = fadeMs < 500 ? 0f : (float)((fadeMs - 500) / 1000.0); + if (t > 1f) t = 1f; + var red = new Vector4(1f, 0.25f, 0.25f, 1f); + var white = new Vector4(1f, 1f, 1f, 1f); + var blended = new Vector4( + red.X * (1 - t) + white.X * t, + red.Y * (1 - t) + white.Y * t, + red.Z * (1 - t) + white.Z * t, + 1f); + ImGui.PushStyleColor(ImGuiCol.Text, blended); + } + + ImGui.TableNextColumn(); + if (i > 0 && ImGui.Button($"^##up{globalIdx}")) + { + var prevRule = stateRules[i - 1]; + lock (_settings.MetaRulesLock) + { + int a = _settings.MetaRules.IndexOf(rule); + int b = _settings.MetaRules.IndexOf(prevRule); + if (a >= 0 && b >= 0) + { _settings.MetaRules[a] = prevRule; _settings.MetaRules[b] = rule; } + } + TryAutoSaveMeta(); + } + + ImGui.TableNextColumn(); + if (i < stateRules.Count - 1 && ImGui.Button($"v##dn{globalIdx}")) + { + var nextRule = stateRules[i + 1]; + lock (_settings.MetaRulesLock) + { + int a = _settings.MetaRules.IndexOf(rule); + int b = _settings.MetaRules.IndexOf(nextRule); + if (a >= 0 && b >= 0) + { _settings.MetaRules[a] = nextRule; _settings.MetaRules[b] = rule; } + } + TryAutoSaveMeta(); + } + + ImGui.TableNextColumn(); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1, 0, 0, 1)); + if (ImGui.Button($"X##delm{globalIdx}")) + { + lock (_settings.MetaRulesLock) + _settings.MetaRules.Remove(rule); + TryAutoSaveMeta(); + } + ImGui.PopStyleColor(); + + ImGui.TableNextColumn(); + string condText = rule.Condition.ToString() + + (string.IsNullOrEmpty(rule.ConditionData) ? "" : $": {rule.ConditionData}"); + + // Local helper — capture this row index so the action-cell right-click + // handler below toggles the same rule. SpanAllColumns + per-cell items + // means a single right-click can hit multiple IsItemClicked checks in + // one frame; the `_toggled` guard makes sure we flip exactly once. + int rowGlobalIdx = globalIdx; + bool _toggled = false; + void ToggleExpand() + { + if (_toggled) return; + _toggled = true; + if (!_expandedRuleIndices.Add(rowGlobalIdx)) + _expandedRuleIndices.Remove(rowGlobalIdx); + } + + if (ImGui.Selectable($"{condText}##edit{globalIdx}", false, ImGuiSelectableFlags.SpanAllColumns)) + { + _editingRule = new MetaRule + { + State = rule.State, + Condition = rule.Condition, + ConditionData = rule.ConditionData, + Action = rule.Action, + ActionData = rule.ActionData, + Children = CloneChildren(rule.Children), + ActionChildren = CloneChildren(rule.ActionChildren) + }; + _editingRuleIndex = globalIdx; + _showMetaEditor = true; + } + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ToggleExpand(); + + ImGui.TableNextColumn(); + if (rule.Action == MetaActionType.All) + { + var actionList = (rule.ActionChildren != null && rule.ActionChildren.Count > 0) + ? rule.ActionChildren + : rule.Children; + int childCount = actionList?.Count ?? 0; + bool expanded = _expandedRuleIndices.Contains(globalIdx); + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions] (right-click to expand)"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ToggleExpand(); + + if (expanded && actionList != null) + { + for (int ai = 0; ai < actionList.Count; ai++) + { + var child = actionList[ai]; + string childText = child.Action.ToString() + + (string.IsNullOrEmpty(child.ActionData) ? "" : $": {child.ActionData}"); + ImGui.TextDisabled($" {ai + 1}. {childText}"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ToggleExpand(); + } + } + } + else if (rule.Action == MetaActionType.EmbeddedNavRoute && + !string.IsNullOrEmpty(rule.ActionData) && rule.ActionData.Contains(';')) + { + var parts = rule.ActionData.Split(';'); + ImGui.Text($"EmbeddedNavRoute: {parts[0]} ({parts[1]} pts)"); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ToggleExpand(); + } + else + { + ImGui.Text(rule.Action.ToString() + + (string.IsNullOrEmpty(rule.ActionData) ? "" : $": {rule.ActionData}")); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ToggleExpand(); + } + + if (isFlashing) ImGui.PopStyleColor(); + } + ImGui.EndTable(); + } + } + ImGui.EndChild(); + + ImGui.Separator(); + + bool isMetaEnabled = _settings.EnableMeta; + if (ImGui.Checkbox("Enable Meta", ref isMetaEnabled)) + _settings.EnableMeta = isMetaEnabled; + + ImGui.SameLine(); + bool metaDebug = _settings.MetaDebug; + if (ImGui.Checkbox("Debug##MetaDbg", ref metaDebug)) + _settings.MetaDebug = metaDebug; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Log every rule execution to chat:\n[Meta] State | Condition → Action"); + + ImGui.SameLine(); + ImGui.Text("Current State:"); + ImGui.SameLine(); + + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##CurrentStateDropdown", _settings.CurrentState)) + { + if (ImGui.Selectable("< Create New State >")) + _openCreateStatePopup = true; + + ImGui.Separator(); + + var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default"); + + foreach (var state in uniqueStates) + { + if (ImGui.Selectable(state, _settings.CurrentState == state)) + { + if (_settings.CurrentState == state) _settings.ForceStateReset = true; + _settings.CurrentState = state; + } + } + ImGui.EndCombo(); + } + + if (_openCreateStatePopup) + { + ImGui.OpenPopup("CreateStatePopup"); + _openCreateStatePopup = false; + } + + if (ImGui.BeginPopup("CreateStatePopup", ImGuiWindowFlags.AlwaysAutoResize)) + { + ImGui.Text("Enter New State Name:"); + ImGui.InputText("##newStateIn", ref _newStateName, 64); + ImGui.Spacing(); + if (ImGui.Button("Create", new Vector2(120, 0))) + { + if (!string.IsNullOrWhiteSpace(_newStateName)) + { + _settings.CurrentState = _newStateName; + _newStateName = ""; + } + ImGui.CloseCurrentPopup(); + } + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(120, 0))) ImGui.CloseCurrentPopup(); + ImGui.EndPopup(); + } + + ImGui.SameLine(ImGui.GetWindowWidth() - 100); + if (ImGui.Button("Create", new Vector2(80, 25))) + { + _editingRule = new MetaRule { State = _settings.CurrentState }; + _editingRuleIndex = -1; + _showMetaEditor = true; + } + + RenderMetaEditorPopup(); + RenderExpressionPopup(); + } + + private void RenderMetaEditorPopup() + { + if (!_showMetaEditor) return; + + // FirstUseEver — only set the default size if no persisted size is in + // imgui.ini. ImGuiCond.Appearing was forcing the size every time the + // popup re-opened, throwing away the user's resize. + ImGui.SetNextWindowSize(new Vector2(650, 450), ImGuiCond.FirstUseEver); + if (!ImGui.Begin("Edit Meta Rule##RynthAiEditor", ref _showMetaEditor, ImGuiWindowFlags.NoCollapse)) + { + ImGui.End(); + return; + } + + float halfWidth = ImGui.GetContentRegionAvail().X / 2f - 4f; + + var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default"); + + ImGui.BeginChild("ConditionPane", new Vector2(halfWidth, -35), ImGuiChildFlags.Borders); + + ImGui.TextColored(new Vector4(0, 1, 1, 1), "Condition Type:"); + int condIdx = (int)_editingRule.Condition; + ImGui.SetNextItemWidth(-1); + if (ImGui.Combo("##CondCombo", ref condIdx, _metaConditionNames, _metaConditionNames.Length)) + { + _editingRule.Condition = (MetaConditionType)condIdx; + ClearConditionDataIfNeeded(_editingRule); + } + + ImGui.TextColored(new Vector4(0, 1, 1, 1), "State Name:"); + ImGui.SetNextItemWidth(-30f); + string tempState = _editingRule.State ?? ""; + if (ImGui.InputTextWithHint("##StateName", "State (e.g. Default)", ref tempState, 64)) + _editingRule.State = tempState; + + ImGui.SameLine(); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##StatePicker", "", ImGuiComboFlags.NoPreview)) + { + foreach (var state in uniqueStates) + { + if (ImGui.Selectable(state)) _editingRule.State = state; + } + ImGui.EndCombo(); + } + + ImGui.Separator(); + RenderRuleConditionNode(_editingRule, "root_cond"); + ImGui.EndChild(); + + ImGui.SameLine(); + + ImGui.BeginChild("ActionPane", new Vector2(0, -35), ImGuiChildFlags.Borders); + ImGui.TextColored(new Vector4(1, 1, 0, 1), "Action Type:"); + RenderRuleActionNode(_editingRule, "root_action"); + ImGui.EndChild(); + + ImGui.SetCursorPosY(ImGui.GetWindowHeight() - 30); + if (ImGui.Button(_editingRuleIndex == -1 ? "Add Rule" : "Save Rule", new Vector2(100, 25))) + { + lock (_settings.MetaRulesLock) + { + if (_editingRuleIndex == -1 || _editingRuleIndex >= _settings.MetaRules.Count) + _settings.MetaRules.Add(_editingRule); + else + _settings.MetaRules[_editingRuleIndex] = _editingRule; + } + _showMetaEditor = false; + TryAutoSaveMeta(); + } + + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(100, 25))) _showMetaEditor = false; + + ImGui.End(); + } + + private void RenderRuleConditionNode(MetaRule rule, string idContext) + { + ImGui.PushID(idContext); + + if (rule.Condition == MetaConditionType.Any || + rule.Condition == MetaConditionType.All || + rule.Condition == MetaConditionType.Not) + { + if (rule.Condition != MetaConditionType.Not || rule.Children.Count == 0) + { + if (ImGui.Button("+##add")) + rule.Children.Add(new MetaRule { Condition = MetaConditionType.Always }); + ImGui.SameLine(); + } + + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"{rule.Condition} Sub-Conditions"); + ImGui.Indent(15f); + + for (int i = 0; i < rule.Children.Count; i++) + { + var child = rule.Children[i]; + ImGui.PushID($"child_{i}"); + + int childCondIdx = (int)child.Condition; + ImGui.SetNextItemWidth(150); + if (ImGui.Combo("##Cond", ref childCondIdx, _metaConditionNames, _metaConditionNames.Length)) + { + child.Condition = (MetaConditionType)childCondIdx; + ClearConditionDataIfNeeded(child); + } + + ImGui.SameLine(); + float startX = ImGui.GetCursorPosX(); + float startY = ImGui.GetCursorPosY(); + ImGui.SameLine(ImGui.GetWindowWidth() - 35f); + + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.1f, 0.1f, 1f)); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(1f, 0.2f, 0.2f, 1f)); + bool deleteClicked = ImGui.Button("X"); + ImGui.PopStyleColor(2); + + ImGui.SetCursorPos(new Vector2(startX, startY)); + RenderRuleConditionNode(child, $"node_{i}"); + + if (deleteClicked) + { + rule.Children.RemoveAt(i); + i--; + } + + ImGui.Dummy(new Vector2(0, 2f)); + ImGui.PopID(); + } + + ImGui.Unindent(15f); + } + else + { + bool needsData = true; + string condHint = "Data..."; + + if (rule.Condition == MetaConditionType.InventoryItemCount_LE || + rule.Condition == MetaConditionType.InventoryItemCount_GE) + { + string[] parts = (rule.ConditionData ?? "").Split(','); + string itemName = parts[0]; + string itemCount = parts.Length > 1 ? parts[1] : "0"; + + ImGui.Text("Item Name:"); + ImGui.SetNextItemWidth(-28); + if (ImGui.InputText("##InvName", ref itemName, 64)) + rule.ConditionData = $"{itemName},{itemCount}"; + CopyButton("InvName", itemName); + + ImGui.Text("Item Count:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##InvCount", ref itemCount, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{itemName},{itemCount}"; + + needsData = false; + } + else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE || + rule.Condition == MetaConditionType.TimeLeftOnSpell_LE) + { + string[] parts = (rule.ConditionData ?? "").Split(','); + string spellId = parts[0]; + string seconds = parts.Length > 1 ? parts[1] : "0"; + + ImGui.Text("Spell ID:"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputText("##SpellId", ref spellId, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{spellId},{seconds}"; + + if (int.TryParse(spellId, out int id)) + { + string sName = SpellDatabase.GetSpellName(id); + if (!string.IsNullOrEmpty(sName)) + { + ImGui.SameLine(); + ImGui.TextColored(new Vector4(0, 1, 1, 1), $"({sName})"); + } + } + + ImGui.Text("Seconds Remaining:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##SpellTime", ref seconds, 16, ImGuiInputTextFlags.CharsDecimal)) + rule.ConditionData = $"{spellId},{seconds}"; + + needsData = false; + } + else + { + switch (rule.Condition) + { + case MetaConditionType.Never: + case MetaConditionType.Always: + case MetaConditionType.CharacterDeath: + case MetaConditionType.AnyVendorOpen: + case MetaConditionType.VendorClosed: + case MetaConditionType.NeedToBuff: + case MetaConditionType.PortalspaceEntered: + case MetaConditionType.PortalspaceExited: + case MetaConditionType.NavrouteEmpty: + needsData = false; + break; + case MetaConditionType.ChatMessage: + case MetaConditionType.ChatMessageCapture: + condHint = "Regex pattern..."; + break; + case MetaConditionType.PackSlots_LE: + condHint = "Min slots (e.g. 5)"; + break; + case MetaConditionType.BurdenPercentage_GE: + condHint = "Percentage (e.g. 250)"; + break; + case MetaConditionType.SecondsInState_GE: + case MetaConditionType.SecondsInStateP_GE: + condHint = "Seconds (e.g. 10)"; + break; + case MetaConditionType.NoMonstersWithinDistance: + condHint = "Distance in yards (e.g. 20)"; + break; + case MetaConditionType.MonsterNameCountWithinDistance: + condHint = "name regex,distance,min count (e.g. Drudge,20,3)"; + break; + case MetaConditionType.MonsterPriorityCountWithinDistance: + condHint = "min count,distance (e.g. 1,20)"; + break; + case MetaConditionType.DistAnyRoutePT_GE: + condHint = "Distance in yards (e.g. 10)"; + break; + case MetaConditionType.Landblock_EQ: + case MetaConditionType.Landcell_EQ: + condHint = "Hex value (e.g. A9B40000)"; + break; + case MetaConditionType.VitaePHE: + condHint = "Vitae penalty % (e.g. 5)"; + break; + } + } + + if (needsData) + { + float availableSpace = ImGui.GetWindowWidth() - ImGui.GetCursorPosX() - 65f; + ImGui.SetNextItemWidth(Math.Max(50f, availableSpace)); + + string cData = rule.ConditionData ?? ""; + if (ImGui.InputTextWithHint("##Data", condHint, ref cData, 256)) + rule.ConditionData = cData; + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + var localRule = rule; + OpenExpressionPopup("Condition Data", localRule.ConditionData ?? "", v => localRule.ConditionData = v); + } + if (ImGui.IsItemHovered() && !string.IsNullOrEmpty(cData)) + ImGui.SetTooltip("Right-click for a larger editor"); + CopyButton("CondData", cData); + } + else if (rule.Condition != MetaConditionType.InventoryItemCount_LE && + rule.Condition != MetaConditionType.InventoryItemCount_GE && + rule.Condition != MetaConditionType.TimeLeftOnSpell_GE && + rule.Condition != MetaConditionType.TimeLeftOnSpell_LE) + { + ImGui.TextDisabled("(No extra data)"); + } + } + + ImGui.PopID(); + } + + private void RenderRuleActionNode(MetaRule rule, string idContext) + { + ImGui.PushID(idContext); + + int actionIdx = (int)rule.Action; + ImGui.SetNextItemWidth(180); + if (ImGui.Combo("##ActionType", ref actionIdx, _metaActionNames, _metaActionNames.Length)) + { + rule.Action = (MetaActionType)actionIdx; + if (rule.Action == MetaActionType.All) rule.ActionData = ""; + else rule.ActionChildren?.Clear(); + } + + ImGui.SameLine(); + + if (rule.Action == MetaActionType.All) + { + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.2f, 0.6f, 0.2f, 1f)); + if (ImGui.Button("+ Add Action")) + rule.ActionChildren.Add(new MetaRule { Action = MetaActionType.ChatCommand }); + ImGui.PopStyleColor(); + + ImGui.Indent(20f); + for (int i = 0; i < rule.ActionChildren.Count; i++) + { + var child = rule.ActionChildren[i]; + ImGui.PushID($"act_child_{i}"); + + if (ImGui.Button("X")) + { + rule.ActionChildren.RemoveAt(i); + i--; + } + else + { + ImGui.SameLine(); + RenderRuleActionNode(child, $"child_node_{i}"); + } + + ImGui.PopID(); + if (i < rule.ActionChildren.Count - 1) ImGui.Separator(); + } + ImGui.Unindent(20f); + } + else + { + switch (rule.Action) + { + case MetaActionType.ChatCommand: + string cmd = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-28); + if (ImGui.InputTextWithHint("##Cmd", "e.g. /tell {1} hello!", ref cmd, 256)) + rule.ActionData = cmd; + CopyButton("Cmd", cmd); + break; + + case MetaActionType.SetMetaState: + case MetaActionType.CallMetaState: + { + string state = rule.ActionData ?? ""; + var stateList = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!stateList.Contains("Default")) stateList.Insert(0, "Default"); + if (!stateList.Contains(state) && !string.IsNullOrEmpty(state)) stateList.Add(state); + + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##StateCombo", string.IsNullOrEmpty(state) ? "Select State..." : state)) + { + foreach (var s in stateList) + { + if (ImGui.Selectable(s, state == s)) + rule.ActionData = s; + } + ImGui.EndCombo(); + } + break; + } + + case MetaActionType.EmbeddedNavRoute: + if (ImGui.BeginCombo("##NavSelect", + string.IsNullOrEmpty(rule.ActionData) ? "Select Route..." : rule.ActionData)) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var embeddedName in _settings.EmbeddedNavs.Keys) + { + if (!seen.Add(embeddedName)) continue; + string label = $"{embeddedName} (embedded)"; + if (ImGui.Selectable(label, rule.ActionData == embeddedName)) + rule.ActionData = embeddedName; + } + foreach (var navFile in _navFiles) + { + if (navFile == "None") continue; + if (!seen.Add(navFile)) continue; + if (ImGui.Selectable(navFile, rule.ActionData == navFile)) + rule.ActionData = navFile; + } + ImGui.EndCombo(); + } + break; + + case MetaActionType.SetWatchdog: + string[] wdParts = (rule.ActionData ?? "Default;10;60").Split(';'); + string wdState = wdParts[0]; + string wdMeters = wdParts.Length > 1 ? wdParts[1] : "10"; + string wdSeconds = wdParts.Length > 2 ? wdParts[2] : "60"; + + ImGui.Text("To State:"); + ImGui.SetNextItemWidth(-1); + + var wdStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList(); + if (!wdStates.Contains("Default")) wdStates.Insert(0, "Default"); + if (!wdStates.Contains(wdState) && !string.IsNullOrEmpty(wdState)) wdStates.Add(wdState); + + if (ImGui.BeginCombo("##WDStateCombo", wdState)) + { + foreach (var s in wdStates) + { + if (ImGui.Selectable(s, wdState == s)) wdState = s; + } + ImGui.EndCombo(); + } + ImGui.Spacing(); + + ImGui.Text("Meters in:"); + ImGui.SetNextItemWidth(-1); + ImGui.InputText("##WDMeters", ref wdMeters, 8, ImGuiInputTextFlags.CharsDecimal); + ImGui.Spacing(); + + ImGui.Text("Seconds:"); + ImGui.SetNextItemWidth(-1); + ImGui.InputText("##WDSecs", ref wdSeconds, 8, ImGuiInputTextFlags.CharsDecimal); + + rule.ActionData = $"{wdState};{wdMeters};{wdSeconds}"; + break; + + case MetaActionType.SetRAOption: + string[] raParts = (rule.ActionData ?? "EnableBuffing;False").Split(';'); + string raO = raParts[0]; + string raV = raParts.Length > 1 ? raParts[1] : "False"; + + ImGui.Text("Option:"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputText("##RAOpt", ref raO, 64)) rule.ActionData = $"{raO};{raV}"; + CopyButton("RAOpt", raO); + + ImGui.SameLine(); + ImGui.Text("Val:"); + ImGui.SetNextItemWidth(-28); + if (ImGui.InputText("##RAVal", ref raV, 64)) rule.ActionData = $"{raO};{raV}"; + CopyButton("RAVal", raV); + break; + + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + string expr = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-28); + if (ImGui.InputTextWithHint("##Expr", "Expression (e.g. [SlotCount] < 5)", ref expr, 256)) + rule.ActionData = expr; + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + var localRule = rule; + OpenExpressionPopup("Action Expression", localRule.ActionData ?? "", v => localRule.ActionData = v); + } + if (ImGui.IsItemHovered() && !string.IsNullOrEmpty(expr)) + ImGui.SetTooltip("Right-click for a larger editor"); + CopyButton("Expr", expr); + break; + + case MetaActionType.GetRAOption: + case MetaActionType.CreateView: + case MetaActionType.DestroyView: + string vData = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-28); + if (ImGui.InputText("##ViewData", ref vData, 128)) + rule.ActionData = vData; + CopyButton("ViewData", vData); + break; + + case MetaActionType.ReturnFromCall: + case MetaActionType.ClearWatchdog: + case MetaActionType.DestroyAllViews: + ImGui.TextDisabled("(No extra data required)"); + break; + + case MetaActionType.None: + ImGui.TextDisabled("(Select an action type)"); + break; + } + } + + ImGui.PopID(); + } + + /// + /// Opens the popped-out expression editor for the given current value with + /// a callback that writes the edited value back to its source. + /// + private void OpenExpressionPopup(string title, string current, Action apply) + { + _exprPopupTitle = title; + _exprPopupBuffer = current ?? string.Empty; + _exprPopupApply = apply; + _exprPopupOpen = true; + _exprPopupRequestFocus = true; + } + + /// + /// Renders the popped-out editor window when one is open. Larger multi-line + /// input than the inline meta editor field, with a hint at the right-click + /// trigger and an Apply/Close pair. + /// + private void RenderExpressionPopup() + { + if (!_exprPopupOpen) return; + + ImGui.SetNextWindowSize(new Vector2(720, 380), ImGuiCond.FirstUseEver); + if (_exprPopupRequestFocus) + ImGui.SetNextWindowFocus(); + if (ImGui.Begin($"Expression Editor - {_exprPopupTitle}##ExpressionPopup", ref _exprPopupOpen)) + { + ImGui.TextDisabled("Edit the expression here. Apply writes it back to the rule."); + ImGui.Separator(); + + if (_exprPopupRequestFocus) + { + ImGui.SetKeyboardFocusHere(); + _exprPopupRequestFocus = false; + } + + Vector2 inputSize = new Vector2(-1, ImGui.GetContentRegionAvail().Y - 36); + ImGui.InputTextMultiline("##ExprPopupText", ref _exprPopupBuffer, 4096, inputSize); + + ImGui.Separator(); + if (ImGui.Button("Apply", new Vector2(120, 0))) + { + _exprPopupApply?.Invoke(_exprPopupBuffer); + TryAutoSaveMeta(); + _exprPopupOpen = false; + } + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(120, 0))) + { + _exprPopupOpen = false; + } + } + ImGui.End(); + } + + private static void ClearConditionDataIfNeeded(MetaRule rule) + { + switch (rule.Condition) + { + case MetaConditionType.Always: + case MetaConditionType.Never: + case MetaConditionType.CharacterDeath: + case MetaConditionType.AnyVendorOpen: + case MetaConditionType.VendorClosed: + case MetaConditionType.NeedToBuff: + case MetaConditionType.PortalspaceEntered: + case MetaConditionType.PortalspaceExited: + case MetaConditionType.NavrouteEmpty: + case MetaConditionType.All: + case MetaConditionType.Any: + case MetaConditionType.Not: + rule.ConditionData = ""; + break; + } + } + + private static void CopyButton(string id, string text) + { + ImGui.SameLine(); + if (ImGui.SmallButton($"C##{id}")) + ImGui.SetClipboardText(text ?? ""); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Copy"); + } + + private static List CloneChildren(List source) + { + var result = new List(source.Count); + foreach (var r in source) + { + result.Add(new MetaRule + { + State = r.State, + Condition = r.Condition, + ConditionData = r.ConditionData, + Action = r.Action, + ActionData = r.ActionData, + Children = CloneChildren(r.Children), + ActionChildren = CloneChildren(r.ActionChildren) + }); + } + return result; + } + + // ── Load / Save bar (inline at top of window) ───────────────────────── + + private void RenderLoadSaveBar() + { + // Lazy-init file list (always has at least the None entry after first refresh) + if (_macroFiles.Count == 0) + RefreshMacroFileList(); + + // Combo label: show selected file, or the currently loaded file if selection is stale + string comboLabel = (_selectedFileIdx >= 0 && _selectedFileIdx < _macroFiles.Count) + ? _macroFiles[_selectedFileIdx].Display + : (!string.IsNullOrEmpty(_settings.CurrentMetaPath) + ? Path.GetFileName(_settings.CurrentMetaPath) + : "-- None --"); + + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - 210); + if (ImGui.BeginCombo("##MacroFileCombo", comboLabel)) + { + for (int i = 0; i < _macroFiles.Count; i++) + { + if (ImGui.Selectable(_macroFiles[i].Display, _selectedFileIdx == i)) + _selectedFileIdx = i; + } + ImGui.EndCombo(); + } + + ImGui.SameLine(); + if (ImGui.Button("Load", new Vector2(55, 0))) + { + if (_selectedFileIdx >= 0 && _selectedFileIdx < _macroFiles.Count) + LoadMacroFile(_macroFiles[_selectedFileIdx].Path); + } + + ImGui.SameLine(); + if (ImGui.Button("Refresh", new Vector2(55, 0))) + RefreshMacroFileList(); + + ImGui.SameLine(); + if (ImGui.Button("Save", new Vector2(55, 0))) + _openSavePopup = true; + + // Status message + if (!string.IsNullOrEmpty(_statusMessage) && (DateTime.Now - _statusTime).TotalSeconds < 5) + ImGui.TextColored(new Vector4(0, 1, 0, 1), _statusMessage); + + // Save popup + if (_openSavePopup) + { + ImGui.OpenPopup("SaveMacroPopup"); + _openSavePopup = false; + } + + if (ImGui.BeginPopup("SaveMacroPopup", ImGuiWindowFlags.AlwaysAutoResize)) + { + ImGui.Text("File name:"); + ImGui.SetNextItemWidth(250); + ImGui.InputText("##SaveName", ref _saveName, 64); + ImGui.SameLine(); + ImGui.TextDisabled(".af"); + ImGui.Spacing(); + if (ImGui.Button("Save", new Vector2(120, 0))) + { + SaveMacroFile(); + ImGui.CloseCurrentPopup(); + } + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(120, 0))) + ImGui.CloseCurrentPopup(); + ImGui.EndPopup(); + } + } + + private void RefreshMacroFileList() + { + var fileEntries = new List<(string Path, string Display)>(); + + Directory.CreateDirectory(MetaFolder); + foreach (string f in Directory.GetFiles(MetaFolder, "*.met")) + { + string name = Path.GetFileName(f); + if (name.StartsWith("--")) continue; + fileEntries.Add((f, $"[met] {name}")); + } + foreach (string f in Directory.GetFiles(MetaFolder, "*.af")) + fileEntries.Add((f, $"[af] {Path.GetFileName(f)}")); + + fileEntries.Sort((a, b) => string.Compare(a.Display, b.Display, StringComparison.OrdinalIgnoreCase)); + + _macroFiles.Clear(); + _macroFiles.Add(("", "-- None --")); // index 0 = clear + foreach (var e in fileEntries) + _macroFiles.Add(e); + + // Pre-select the currently loaded file so the combo label is correct after a session restart. + _selectedFileIdx = 0; + if (!string.IsNullOrEmpty(_settings.CurrentMetaPath)) + { + for (int i = 1; i < _macroFiles.Count; i++) + { + if (_macroFiles[i].Path.Equals(_settings.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)) + { + _selectedFileIdx = i; + break; + } + } + } + } + + internal void LoadMacroFile(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + lock (_settings.MetaRulesLock) + { + _settings.MetaRules.Clear(); + _settings.EmbeddedNavs.Clear(); + } + _settings.CurrentMetaPath = string.Empty; + _settings.CurrentState = "Default"; + _settings.ForceStateReset = true; + _statusMessage = "Macro cleared."; + _statusTime = DateTime.Now; + return; + } + + try + { + string ext = Path.GetExtension(filePath).ToLowerInvariant(); + LoadedMeta loaded; + + if (ext == ".met") + loaded = MetFileParser.Load(filePath); + else if (ext == ".af") + loaded = AfFileParser.Load(filePath); + else + { + _statusMessage = "Unsupported file type"; + _statusTime = DateTime.Now; + return; + } + + LastLoadWarnings = loaded.Warnings; + if (loaded.Rules.Count == 0) + { + _statusMessage = loaded.Warnings.Count > 0 + ? $"No rules parsed — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}" + : "No rules found (profile?)"; + _statusTime = DateTime.Now; + return; + } + + lock (_settings.MetaRulesLock) + { + _settings.MetaRules = loaded.Rules; + _settings.EmbeddedNavs.Clear(); + foreach (var kvp in loaded.EmbeddedNavs) + _settings.EmbeddedNavs[kvp.Key] = kvp.Value; + } + _settings.CurrentState = loaded.Rules[0].State; + _settings.ForceStateReset = true; + _settings.CurrentMetaPath = filePath; + + string name = Path.GetFileNameWithoutExtension(filePath); + int stateCount = loaded.Rules.Select(r => r.State).Distinct(StringComparer.OrdinalIgnoreCase).Count(); + _statusMessage = loaded.Warnings.Count == 0 + ? $"Loaded {loaded.Rules.Count} rules / {stateCount} states / {loaded.EmbeddedNavs.Count} navs from {name}" + : $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}"; + _statusTime = DateTime.Now; + } + catch (Exception ex) + { + _statusMessage = $"Load error: {ex.Message}"; + _statusTime = DateTime.Now; + } + } + + private void TryAutoSaveMeta() + { + _settings.MetaRulesStructuralVersion++; // editor mutation → rebuild meta index + if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) + return; + + try + { + string path = _settings.CurrentMetaPath; + + // .met files can't be written — save as .af alongside + if (Path.GetExtension(path).Equals(".met", StringComparison.OrdinalIgnoreCase)) + { + path = Path.ChangeExtension(path, ".af"); + _settings.CurrentMetaPath = path; + _statusMessage = $"Converted .met → {Path.GetFileName(path)} for editing (original .met left untouched)"; + _statusTime = DateTime.Now; + } + + lock (_settings.MetaRulesLock) + AfFileWriter.Save(path, _settings.MetaRules, _settings.EmbeddedNavs); + } + catch { } + } + + private void SaveMacroFile() + { + try + { + if (string.IsNullOrWhiteSpace(_saveName)) + { + _statusMessage = "Enter a file name"; + _statusTime = DateTime.Now; + return; + } + + Directory.CreateDirectory(MetaFolder); + string filePath = Path.Combine(MetaFolder, _saveName + ".af"); + lock (_settings.MetaRulesLock) + AfFileWriter.Save(filePath, _settings.MetaRules, _settings.EmbeddedNavs); + + _statusMessage = $"Saved to {_saveName}.af"; + _statusTime = DateTime.Now; + RefreshMacroFileList(); + } + catch (Exception ex) + { + _statusMessage = $"Save error: {ex.Message}"; + _statusTime = DateTime.Now; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMonstersUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMonstersUi.cs new file mode 100644 index 0000000..a9c1808 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMonstersUi.cs @@ -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; + + /// Set by the dashboard so we can show captured stats per monster row. + public Func? CreatureLookup { get; set; } + + private string _newMonsterName = string.Empty; + private string _newMonsterCategory = string.Empty; + private readonly Dictionary _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 = ""; + 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("", 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 = ""; + 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("", 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(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs new file mode 100644 index 0000000..e185f1a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs @@ -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 + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs new file mode 100644 index 0000000..17dcf12 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -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; + /// Meta state — set only by meta actions (SetState, CallState, ReturnFromCall, UI, meta load). + [JsonIgnore] public string CurrentState = "Default"; + /// 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. + [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; + /// + /// 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. + /// + public int RebuffSecondsRemaining = 300; + public bool StartMacroOnLogin; + public bool PatrolOnLogin; + + public int BlacklistAttempts = 3; + public int BlacklistTimeoutSec = 30; + /// + /// 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. + /// + public int BlacklistCastSettleMs = 1500; + /// + /// Blacklist a target after being engaged with it for this many seconds without + /// dealing any damage. 0 = disabled. Default 60s. + /// + public int TargetNoProgressTimeoutSec = 0; // 0 = disabled; set to e.g. 120 to blacklist stuck targets + + /// + /// 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. + /// + public List MonsterNameBlacklist { get; set; } = new(); + + public int GiveQueueIntervalMs = 150; + + public int SpellCastIntervalMs = 400; + + /// + /// Minimum delay between offensive (war/void) COMBAT spell casts, in ms. + /// Combat magic uses this instead of 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. + /// + public int AttackSpellIntervalMs = 1500; + + public int MeleeAttackPower = -1; + public int MissileAttackPower = -1; + /// + /// 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. + /// + 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 MonsterRules { get; set; } = new(); + public List ItemRules { get; set; } = new(); + public List ConsumableRules { get; set; } = new(); + public List BuffRules { get; set; } = new(); + public List MetaRules { get; set; } = new(); + + /// + /// Guards every read/enumerate/mutate of . The list + /// is touched from the plugin-tick thread (MetaManager.Think) AND the + /// Avalonia dispatcher thread (MetaPanel poll → BuildMetaJson / + /// HandleMetaCommand). List<T> is not thread-safe; concurrent + /// enumerate+mutate corrupts the heap. Hold this lock for the full duration + /// of any MetaRules access. + /// + [JsonIgnore] + public object MetaRulesLock { get; } = new(); + + /// + /// 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. + /// + [JsonIgnore] + public int MetaRulesStructuralVersion; + + private Dictionary> _embeddedNavs = + new(StringComparer.OrdinalIgnoreCase); + + /// + /// 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. + /// + public Dictionary> EmbeddedNavs + { + get => _embeddedNavs; + set => _embeddedNavs = value != null + ? new Dictionary>(value, StringComparer.OrdinalIgnoreCase) + : new Dictionary>(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 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; +} + +/// JSON wire-format types used by the engine-side Avalonia MonstersPanel. +public sealed class MonstersBridgePayload +{ + public List Rules { get; set; } = new(); + public List Items { get; set; } = new(); + public string CurrentTargetName { get; set; } = string.Empty; + /// Captured creature data per rule name (uppercased), filled by the plugin. + public Dictionary 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"; +} + +/// Bridge payload for the engine-side Avalonia ItemsPanel. +public sealed class ItemsBridgePayload +{ + public List Weapons { get; set; } = new(); + public List 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 NavFiles { get; set; } = new(); + public List Points { get; set; } = new(); +} + +/// One-shot command sent from the Avalonia NavPanel to the plugin. +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; +} + +/// Bridge payload for the engine-side Avalonia SettingsPanel. +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 Children { get; set; } = new(); + public List ActionChildren { get; set; } = new(); + + /// 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). + public bool Enabled { get; set; } = true; + + [JsonIgnore] + public bool HasFired { get; set; } + + /// Last time this rule's action executed — drives the red-flash UI. + [JsonIgnore] + public DateTime LastFiredAt { get; set; } = DateTime.MinValue; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs new file mode 100644 index 0000000..cada35a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs @@ -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; + + /// Auto-detect weapon element from the DamageType int property. + 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"; + } + + /// Auto-detect consumable type from item name. + 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"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaBridgeTypes.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaBridgeTypes.cs new file mode 100644 index 0000000..82e9161 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaBridgeTypes.cs @@ -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 Children { get; set; } = new(); + public List 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; } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs new file mode 100644 index 0000000..de89dc3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs @@ -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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs new file mode 100644 index 0000000..6c602ef --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs @@ -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 Points { get; set; } = new(); + + /// + /// 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. + /// + public string? LoadWarning { get; private set; } + + /// + /// 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. + /// + 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? 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 lines, Action? 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; + } + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RadarSnapshot.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RadarSnapshot.cs new file mode 100644 index 0000000..add3dff --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RadarSnapshot.cs @@ -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 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 Walls { get; set; } = new(); + + // Fallback floor strips when no baked texture exists. x0, y0, x1, y1, type × N. + [JsonPropertyName("fills")] public List Fills { get; set; } = new(); + + // Per-layer pre-merged visited floor strips. x0, y0, x1, y1 × N. + [JsonPropertyName("visited")] public List Visited { get; set; } = new(); + + // All marker kinds included; engine filters by user setting. + [JsonPropertyName("markers")] public List 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(); +} + +internal sealed class RadarFillLayer +{ + [JsonPropertyName("z")] public float Z { get; set; } + [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty(); +} + +internal sealed class RadarVisitedLayer +{ + [JsonPropertyName("z")] public float Z { get; set; } + [JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty(); +} + +// 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 { } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs new file mode 100644 index 0000000..1f69955 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs @@ -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), TypeInfoPropertyName = "MonsterRuleList")] +[JsonSerializable(typeof(List), TypeInfoPropertyName = "ConsumableRuleList")] +[JsonSerializable(typeof(Dictionary), 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 { } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthChatUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthChatUi.cs new file mode 100644 index 0000000..54a8764 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthChatUi.cs @@ -0,0 +1,395 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// +/// 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. +/// +internal sealed class RynthChatUi +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + + private readonly object _lock = new(); + private readonly List _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; } + + /// + /// 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. + /// + public Action? OnSubmit { get; set; } + + public RynthChatUi(RynthCoreHost host, LegacyUiSettings settings) + { + _host = host; + _settings = settings; + } + + private readonly record struct ChatLine(string Text, int ChatType, DateTime At); + + /// Append a chat line (called from RynthAiPlugin.OnChatWindowText). + 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; + } + + /// Snapshot the most recent lines (text + chat-type) for the remote status feed. Thread-safe. + 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(); + } + + /// 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. + 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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs new file mode 100644 index 0000000..0b19624 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs @@ -0,0 +1,1230 @@ +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.Maps; +using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// +/// RynthRadar — square, movable, resizable radar. Shares the DungeonMapUi's +/// rasterised floor + outer-edge cache so walls look identical to the big map +/// (gap-free portal bridges and all). Outdoors: dot markers only (no walls). +/// Gear icon in the top-right corner opens an inline settings popup; player +/// coords (N/S, E/W, Z) sit below the canvas. +/// +internal sealed class RynthRadarUi +{ + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private DungeonMapUi? _mapData; + private MainLogic? _raycast; + private WorldObjectCache? _objectCache; + + private bool _open = true; + private bool _placementRestored; + + // Per-session explored state (grid cells at the DungeonMapUi rasteriser's + // resolution). Cleared whenever the player transitions landblocks, so + // re-entering a dungeon resets the coloring. + private const float GridCell = 0.5f; + private readonly System.Collections.Generic.HashSet<(int gx, int gy)> _visitedCells = new(); + private uint _visitedLandblock; + // Visited cells merged into strips — rebuilt only when _visitedCells grows. + private System.Collections.Generic.Dictionary>? _visitedFillStrips; + private int _lastVisitedCount = -1; + + // Colours + private static readonly uint ColFrameOuter = ImGui.ColorConvertFloat4ToU32(new Vector4(0.04f, 0.05f, 0.08f, 1.00f)); + private static readonly uint ColFrameInner = ImGui.ColorConvertFloat4ToU32(new Vector4(0.62f, 0.52f, 0.24f, 1.00f)); + private static readonly uint ColFrameAccent = ImGui.ColorConvertFloat4ToU32(new Vector4(0.90f, 0.78f, 0.40f, 1.00f)); + private static readonly uint ColCardinal = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 1.00f, 1.00f, 1.00f)); + private static readonly uint ColCanvasBg = ImGui.ColorConvertFloat4ToU32(new Vector4(0.04f, 0.07f, 0.11f, 1.00f)); + private static readonly uint ColCrosshair = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.40f, 0.50f, 0.60f)); + private static readonly uint ColCoordText = ImGui.ColorConvertFloat4ToU32(new Vector4(0.95f, 0.97f, 1.00f, 1.00f)); + private static readonly uint ColTextOutline = ImGui.ColorConvertFloat4ToU32(new Vector4(0.00f, 0.00f, 0.00f, 0.95f)); + + // Wall colours — white by default, blue when the source cell has been visited this session. + private static readonly uint ColWallUnseen = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 1.00f, 1.00f, 1.00f)); + private static readonly uint ColWallVisited = ImGui.ColorConvertFloat4ToU32(new Vector4(0.25f, 0.60f, 1.00f, 1.00f)); + + // Floor fill colours. + private static readonly uint ColFloorFlatUnvisited = ImGui.ColorConvertFloat4ToU32(new Vector4(0.18f, 0.55f, 0.22f, 0.55f)); // green — unvisited flat + private static readonly uint ColFloorFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.12f, 0.18f, 0.28f, 0.55f)); // dim blue — slopes / non-flat + // Visited flat floor overlay — slate blue matching the UI accent family. + private static readonly uint ColFloorVisited = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.42f, 0.58f, 0.65f)); + + // Marker colours — all distinct so they read at a glance. + private static readonly uint ColPlayer = ImGui.ColorConvertFloat4ToU32(new Vector4(0.20f, 1.00f, 0.40f, 1.00f)); // green + private static readonly uint ColMonster = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.20f, 0.20f, 1.00f)); // red + private static readonly uint ColNpc = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.85f, 0.20f, 1.00f)); // yellow + private static readonly uint ColPortal = ImGui.ColorConvertFloat4ToU32(new Vector4(0.75f, 0.30f, 1.00f, 1.00f)); // magenta/purple + private static readonly uint ColDoor = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.55f, 0.10f, 1.00f)); // vivid orange + private static readonly uint ColDoorEdge = ImGui.ColorConvertFloat4ToU32(new Vector4(0.40f, 0.20f, 0.00f, 1.00f)); + + public Action? OnSettingChanged { get; set; } + + public RynthRadarUi(RynthCoreHost host, LegacyUiSettings settings) + { + _host = host; + _settings = settings; + } + + internal void SetMapData(DungeonMapUi mapData) => _mapData = mapData; + public void SetRaycast(MainLogic raycast) => _raycast = raycast; + public void SetWorldObjectCache(WorldObjectCache cache) => _objectCache = cache; + + public void Render() + { + if (!_settings.ShowRynthRadar) return; + if (!_host.HasGetPlayerPose) return; + if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out float pz, + out _, out _, out _, out _)) + return; + + bool snapRotate = _settings.RadarRotateWithPlayer; + bool snapShowM = _settings.RadarShowMonsters; + bool snapShowN = _settings.RadarShowNpcs; + bool snapShowP = _settings.RadarShowPortals; + bool snapShowD = _settings.RadarShowDoors; + float snapOp = _settings.RadarOpacity; + float snapZoom = _settings.RadarZoom; + int snapPaint = _settings.RadarWallPaintRadius; + bool snapCirc = _settings.RadarCircular; + + // Restore the window where the user left it last. A fresh RynthRadarUi + // (AC restart or RL hot-reload) starts with _placementRestored=false, so + // saved coords are re-applied on the first frame the radar shows. Sanity- + // check against the viewport so a radar dragged off-screen — or a smaller + // AC client window than last session — can't make it vanish. + if (!_placementRestored) + { + float sw = _settings.RadarSizeX > 0f ? _settings.RadarSizeX : 260f; + float sh = _settings.RadarSizeY > 0f ? _settings.RadarSizeY : 284f; + ImGui.SetNextWindowSize(new Vector2(sw, sh), ImGuiCond.Always); + + Vector2 vp = ImGui.GetMainViewport().Size; + float maxX = vp.X > 0 ? vp.X - 60f : 8000f; + float maxY = vp.Y > 0 ? vp.Y - 60f : 6000f; + float rpx = _settings.RadarPosX; + float rpy = _settings.RadarPosY; + if (rpx < 0 || rpy < 0 || rpx > maxX || rpy > maxY) + { + rpx = 60f; + rpy = 60f; + } + ImGui.SetNextWindowPos(new Vector2(rpx, rpy), ImGuiCond.Always); + _settings.RadarPosX = rpx; + _settings.RadarPosY = rpy; + _placementRestored = true; + } + ImGui.SetNextWindowSizeConstraints(new Vector2(140, 160), new Vector2(900, 932)); + ImGui.SetNextWindowBgAlpha(0f); + + ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u); + + // NoBringToFrontOnFocus keeps the gear sub-window (rendered after) on top + // when the user clicks the main window to drag or resize. + ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar + | ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoCollapse + | ImGuiWindowFlags.NoBringToFrontOnFocus; + if (_settings.RadarClickThrough) + { + // Mouse / keyboard events pass straight through to the game. The + // gear popup is unreachable while this is on — the Advanced Settings + // panel is the escape hatch. + flags |= ImGuiWindowFlags.NoInputs + | ImGuiWindowFlags.NoMove + | ImGuiWindowFlags.NoResize; + } + + bool visible = ImGui.Begin("##RynthRadar", ref _open, flags); + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(); + + if (!visible) { ImGui.End(); return; } + + Vector2 winPos = ImGui.GetWindowPos(); + Vector2 winSize = ImGui.GetWindowSize(); + + // Keep canvas square; footer sits below and is sized for the 16pt coord text. + const float FooterH = 30f; + float sq = MathF.Min(winSize.X, winSize.Y - FooterH); + if (MathF.Abs(winSize.X - sq) > 0.5f || MathF.Abs(winSize.Y - (sq + FooterH)) > 0.5f) + ImGui.SetWindowSize(new Vector2(sq, sq + FooterH)); + + // Persist placement so the radar reopens exactly here next session. + // LegacyDashboardRenderer's per-frame CheckAndSave writes the JSON when + // these change — the same path the main dashboard uses for its own pos. + // Store the canonical (squared) size so the restored frame is stable. + _settings.RadarPosX = winPos.X; + _settings.RadarPosY = winPos.Y; + _settings.RadarSizeX = sq; + _settings.RadarSizeY = sq + FooterH; + + Vector2 canvasPos = winPos; + Vector2 canvasSize = new Vector2(sq, sq); + Vector2 centre = canvasPos + canvasSize * 0.5f; + float radius = sq * 0.5f - 6f; + + // Reserve the full window extent so later cursor moves (gear button) and + // drawlist calls that extend past the implicit cursor don't trip ImGui's + // "SetCursorPos extends parent boundary" assertion in End. + ImGui.Dummy(new Vector2(sq, sq + FooterH)); + + var dl = ImGui.GetWindowDrawList(); + bool circular = _settings.RadarCircular; + + DrawFrame(dl, canvasPos, canvasSize, circular); + + var clipMin = new Vector2(canvasPos.X + 4, canvasPos.Y + 4); + var clipMax = new Vector2(canvasPos.X + canvasSize.X - 4, canvasPos.Y + canvasSize.Y - 4); + dl.PushClipRect(clipMin, clipMax, intersect_with_current_clip_rect: true); + + // Per-element circular clip: content outside this radius is skipped in circle mode. + float innerRadius = radius; + float innerRadiusSq = innerRadius * innerRadius; + + // Crosshair — shortened to the visible area so it doesn't poke out of the circle. + if (circular) + { + dl.AddLine(new Vector2(centre.X, centre.Y - innerRadius), new Vector2(centre.X, centre.Y + innerRadius), ColCrosshair, 1f); + dl.AddLine(new Vector2(centre.X - innerRadius, centre.Y), new Vector2(centre.X + innerRadius, centre.Y), ColCrosshair, 1f); + } + else + { + dl.AddLine(new Vector2(centre.X, clipMin.Y), new Vector2(centre.X, clipMax.Y), ColCrosshair, 1f); + dl.AddLine(new Vector2(clipMin.X, centre.Y), new Vector2(clipMax.X, centre.Y), ColCrosshair, 1f); + } + + // Local helper — used to cull content that lies outside the circle in circle mode. + bool InsideShape(Vector2 p) + { + if (!circular) return true; // square mode uses rect clip already + float dx = p.X - centre.X; + float dy = p.Y - centre.Y; + return dx * dx + dy * dy <= innerRadiusSq; + } + + // Heading setup. AC convention: heading 0° = east, 90° = north (math CCW from east). + float heading = 0f; + _host.TryGetPlayerHeading(out heading); + float hRad = heading * MathF.PI / 180f; + float sinH = MathF.Sin(hRad); + float cosH = MathF.Cos(hRad); + bool rotate = _settings.RadarRotateWithPlayer; + + float zoom = MathF.Max(0.5f, _settings.RadarZoom); + uint landblock = cellId >> 16; + float gxLB = ((landblock >> 8) & 0xFF) * 192f; + float gyLB = (landblock & 0xFF) * 192f; + float playerWX = px + gxLB; + float playerWY = py + gyLB; + bool isIndoor = (cellId & 0xFFFF) >= 0x100 && landblock != 0; + + // Reset per-landblock explored state so re-entering a dungeon starts fresh. + if (landblock != _visitedLandblock) + { + _visitedLandblock = landblock; + _visitedCells.Clear(); + _visitedFillStrips = null; + _lastVisitedCount = -1; + } + + // Mark the player's current grid cell as visited (plus a user-tunable + // radius around it so walls light up well before the player is on top). + if (isIndoor) + { + int pgx = (int)MathF.Floor(playerWX / GridCell); + int pgy = (int)MathF.Floor(playerWY / GridCell); + int r = Math.Clamp(_settings.RadarWallPaintRadius, 0, 40); + for (int oy = -r; oy <= r; oy++) + for (int ox = -r; ox <= r; ox++) + _visitedCells.Add((pgx + ox, pgy + oy)); + } + + // Rebuild visited strips only when new cells were added. + if (_visitedCells.Count != _lastVisitedCount && _mapData != null) + { + _lastVisitedCount = _visitedCells.Count; + RebuildRadarVisitedStrips(); + } + + // ── Floor fill + outer edges (indoor, from shared big-map cache) ─ + // We draw three layers: current − 1, current + 1, and current. The ±1 layers + // are drawn first and dimmed so the current floor stays visually dominant. + if (isIndoor && _mapData != null) + { + _mapData.EnsureCache(landblock); + var zLayers = _mapData._zLayers; + if (zLayers is { Count: > 0 }) + { + int curIdx = _mapData.BestLayerIdxFor(pz); + + // Render order: below, above, current (current drawn last → on top). + Span<(int idx, float alpha, bool isCurrent)> order = stackalloc (int, float, bool)[3]; + int n = 0; + if (curIdx - 1 >= 0) order[n++] = (curIdx - 1, 0.30f, false); + if (curIdx + 1 < zLayers.Count) order[n++] = (curIdx + 1, 0.30f, false); + order[n++] = (curIdx, 1.00f, true); + + for (int li = 0; li < n; li++) + { + float layerZ = zLayers[order[li].idx]; + float a = order[li].alpha; + bool current = order[li].isCurrent; + + // ── Floor texture (fill + edges baked) or fallback strips ── + if (_mapData._layerTextures != null && + _mapData._layerTextures.TryGetValue(layerZ, out var floorTex) && + floorTex.TexId != IntPtr.Zero) + { + uint tint = ((uint)(a * 255f) << 24) | 0x00FFFFFFu; + + // World view: player ± innerRadius/zoom. We always render to the + // full circle / square bounding box and bake the world-view extent + // into the UVs. Earlier code clamped vx*/vy* to the texture's own + // world bounds, which shrank the screen rect when the texture + // didn't reach the full radar view, producing a "square inside + // the circle" at moderate zoom. Sampler clamp at texture edges + // is acceptable; ImGui's DX9 backend uses CLAMP, so UVs outside + // [0,1] sample the edge pixels (transparent for our atlas). + float worldR = innerRadius / zoom; + float vx0 = playerWX - worldR; + float vx1 = playerWX + worldR; + float vy0 = playerWY - worldR; + float vy1 = playerWY + worldR; + + float texW = floorTex.WorldX1 - floorTex.WorldX0; + float texH = floorTex.WorldY1 - floorTex.WorldY0; + float uvX0 = (vx0 - floorTex.WorldX0) / texW; + float uvX1 = (vx1 - floorTex.WorldX0) / texW; + float uvY0 = (floorTex.WorldY1 - vy1) / texH; // row 0 = north + float uvY1 = (floorTex.WorldY1 - vy0) / texH; + + if (!rotate && circular) + { + // Non-rotating circular radar: rect is the full circle bbox so + // AddImageRounded(rounding=innerRadius) clips to a true circle. + var sNW = new Vector2(centre.X - innerRadius, centre.Y - innerRadius); + var sSE = new Vector2(centre.X + innerRadius, centre.Y + innerRadius); + dl.AddImageRounded(floorTex.TexId, sNW, sSE, + new Vector2(uvX0, uvY0), new Vector2(uvX1, uvY1), + tint, innerRadius, ImDrawFlags.RoundCornersAll); + } + else if (!rotate) + { + // Square non-rotating radar: full square bbox, sampler-clamped UVs. + var sNW = new Vector2(centre.X - innerRadius, centre.Y - innerRadius); + var sSE = new Vector2(centre.X + innerRadius, centre.Y + innerRadius); + dl.AddImage(floorTex.TexId, sNW, sSE, + new Vector2(uvX0, uvY0), new Vector2(uvX1, uvY1), tint); + } + else + { + // Rotating radar: project 4 corners of the world view rect. + // Circular clipping is not applied here — the rotated quad + // can poke out of the circle. (Acceptable: rotate mode is + // tightly bound to the radar canvas anyway.) + var pNW = ProjectWorld(vx0, vy1, playerWX, playerWY, centre, zoom, true, sinH, cosH); + var pNE = ProjectWorld(vx1, vy1, playerWX, playerWY, centre, zoom, true, sinH, cosH); + var pSE = ProjectWorld(vx1, vy0, playerWX, playerWY, centre, zoom, true, sinH, cosH); + var pSW = ProjectWorld(vx0, vy0, playerWX, playerWY, centre, zoom, true, sinH, cosH); + dl.AddImageQuad(floorTex.TexId, pNW, pNE, pSE, pSW, + new Vector2(uvX0, uvY0), new Vector2(uvX1, uvY0), + new Vector2(uvX1, uvY1), new Vector2(uvX0, uvY1), tint); + } + } + else if (_mapData._fillStrips != null && + _mapData._fillStrips.TryGetValue(layerZ, out var strips)) + { + // Fallback fill strips + foreach (var (x0, y0, x1, y1, stripType) in strips) + { + var p00 = ProjectWorld(x0, y0, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var p10 = ProjectWorld(x1, y0, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var p11 = ProjectWorld(x1, y1, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var p01 = ProjectWorld(x0, y1, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + float sxMin = MathF.Min(p00.X, MathF.Min(p10.X, MathF.Min(p11.X, p01.X))); + float sxMax = MathF.Max(p00.X, MathF.Max(p10.X, MathF.Max(p11.X, p01.X))); + float syMin = MathF.Min(p00.Y, MathF.Min(p10.Y, MathF.Min(p11.Y, p01.Y))); + float syMax = MathF.Max(p00.Y, MathF.Max(p10.Y, MathF.Max(p11.Y, p01.Y))); + var min = new Vector2(sxMin, syMin); + var max = new Vector2(sxMax, syMax); + if (max.X < clipMin.X || min.X > clipMax.X || + max.Y < clipMin.Y || min.Y > clipMax.Y) continue; + // Disc is convex — all four corners inside ⇒ whole strip inside. + if (circular && + (!InsideShape(p00) || !InsideShape(p10) || + !InsideShape(p11) || !InsideShape(p01))) continue; + + uint stripFill = SetAlpha( + stripType == DungeonMapUi.CellType.Flat ? ColFloorFlatUnvisited : ColFloorFill, + a * 0.55f); + if (rotate) dl.AddQuadFilled(p00, p10, p11, p01, stripFill); + else dl.AddRectFilled(min, max, stripFill); + } + + // Fallback walls + uint wallUnseen = SetAlpha(ColWallUnseen, a); + uint wallSeen = SetAlpha(ColWallVisited, a); + if (_mapData._outerEdgesRaw != null && + _mapData._outerEdgesRaw.TryGetValue(layerZ, out var rawEdges)) + { + foreach (var (ax, ay, bx, by, _, cellGx, cellGy) in rawEdges) + { + var p0 = ProjectWorld(ax, ay, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var p1 = ProjectWorld(bx, by, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + if (MathF.Max(p0.X, p1.X) < clipMin.X || MathF.Min(p0.X, p1.X) > clipMax.X || + MathF.Max(p0.Y, p1.Y) < clipMin.Y || MathF.Min(p0.Y, p1.Y) > clipMax.Y) continue; + if (!InsideShape(p0) || !InsideShape(p1)) continue; + uint col = (current && _visitedCells.Contains((cellGx, cellGy))) + ? wallSeen : wallUnseen; + dl.AddLine(p0, p1, col, current ? 1.5f : 1.0f); + } + } + } + + // Visited flat floor overlay — drawn as pre-merged strips (current floor only). + if (current && _visitedFillStrips != null && + _visitedFillStrips.TryGetValue(layerZ, out var vStrips)) + { + uint visitedFillCol = SetAlpha(ColFloorVisited, a); + foreach (var (wx0, wy0, wx1, wy1) in vStrips) + { + // Project all four corners of the world rect. We need them + // anyway for the rotate path, and using all four for the + // circle-cull keeps the visited overlay from bleeding past + // the radar boundary when zoomed (which the old centre-only + // check allowed). The disc is convex, so all-corners-inside + // implies the whole strip is inside. + var sp0 = ProjectWorld(wx0, wy0, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var sp1 = ProjectWorld(wx1, wy1, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var sp2 = ProjectWorld(wx1, wy0, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + var sp3 = ProjectWorld(wx0, wy1, playerWX, playerWY, centre, zoom, rotate, sinH, cosH); + + float sxMin = MathF.Min(MathF.Min(sp0.X, sp1.X), MathF.Min(sp2.X, sp3.X)); + float sxMax = MathF.Max(MathF.Max(sp0.X, sp1.X), MathF.Max(sp2.X, sp3.X)); + float syMin = MathF.Min(MathF.Min(sp0.Y, sp1.Y), MathF.Min(sp2.Y, sp3.Y)); + float syMax = MathF.Max(MathF.Max(sp0.Y, sp1.Y), MathF.Max(sp2.Y, sp3.Y)); + + if (sxMax < clipMin.X || sxMin > clipMax.X || + syMax < clipMin.Y || syMin > clipMax.Y) continue; + if (circular && + (!InsideShape(sp0) || !InsideShape(sp1) || + !InsideShape(sp2) || !InsideShape(sp3))) + continue; + + if (rotate) + dl.AddQuadFilled(sp0, sp2, sp1, sp3, visitedFillCol); + else + dl.AddRectFilled(new Vector2(sxMin, syMin), new Vector2(sxMax, syMax), visitedFillCol); + } + } + + } + } + } + + // ── Dot markers (indoor + outdoor) ─────────────────────────────── + if (_objectCache != null && _host.HasGetObjectPosition && landblock != 0) + { + const uint STypeCreatureType = 2u; + const int CreatureTypeNpc = 14; + const uint TypePortal = 0x10000u; + + if (_settings.RadarShowMonsters || _settings.RadarShowNpcs) + { + foreach (var wo in _objectCache.GetLandscape()) + { + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cCellId, + out float cox, out float coy, out _)) continue; + if ((cCellId >> 16) != landblock) continue; + + bool isNpc = _host.HasGetObjectIntProperty + && _host.TryGetObjectIntProperty((uint)wo.Id, STypeCreatureType, out int ct) + && ct == CreatureTypeNpc; + if (isNpc && !_settings.RadarShowNpcs) continue; + if (!isNpc && !_settings.RadarShowMonsters) continue; + + var p = ProjectWorld(cox, coy, px, py, centre, zoom, rotate, sinH, cosH); + if (!InRect(p, clipMin, clipMax)) continue; + if (!InsideShape(p)) continue; + dl.AddCircleFilled(p, 3f, isNpc ? ColNpc : ColMonster); + } + } + + if (_settings.RadarShowPortals || _settings.RadarShowDoors) + { + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + if ((uint)wo.Id >= 0x80000000u) continue; + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint oCellId, + out float oox, out float ooy, out _)) continue; + if ((oCellId >> 16) != landblock) continue; + + bool isPortal = _host.HasGetItemType + && _host.TryGetItemType((uint)wo.Id, out uint typeFlags) + && (typeFlags & TypePortal) != 0; + bool isDoor = !isPortal && IsDoorName(wo.Name); + if (isPortal && !_settings.RadarShowPortals) continue; + if (isDoor && !_settings.RadarShowDoors) continue; + if (!isPortal && !isDoor) continue; + + var p = ProjectWorld(oox, ooy, px, py, centre, zoom, rotate, sinH, cosH); + if (!InRect(p, clipMin, clipMax)) continue; + if (!InsideShape(p)) continue; + if (isPortal) + { + // Portal: purple diamond. + const float s = 4f; + dl.AddQuadFilled( + new Vector2(p.X, p.Y - s), + new Vector2(p.X + s, p.Y), + new Vector2(p.X, p.Y + s), + new Vector2(p.X - s, p.Y), ColPortal); + + // Destination label directly above the diamond. + string label = GetPortalLabel(wo); + if (!string.IsNullOrEmpty(label)) + { + ImFontPtr font = ImGui.GetFont(); + const float lblSize = 13f; + Vector2 ts = font.CalcTextSizeA(lblSize, float.MaxValue, 0f, label); + var lp = new Vector2(p.X - ts.X * 0.5f, p.Y - s - ts.Y - 1f); + DrawTextOutlined(dl, font, lblSize, lp, label, ColCardinal, ColTextOutline); + } + } + else + { + // Door: orange square with a dark outline — very different silhouette + // from the monster/NPC circles so it reads at a glance. + const float s = 3.5f; + dl.AddRectFilled(new Vector2(p.X - s, p.Y - s), new Vector2(p.X + s, p.Y + s), ColDoor); + dl.AddRect(new Vector2(p.X - s, p.Y - s), new Vector2(p.X + s, p.Y + s), ColDoorEdge, 0f, ImDrawFlags.None, 1f); + } + } + } + } + + // ── Player centre + heading arrow ──────────────────────────────── + dl.AddCircleFilled(centre, 3.5f, ColPlayer); + { + float ax, ay; + if (rotate) + { + ax = 0f; ay = -12f; // player's facing is always screen-up + } + else + { + // North-up: arrow follows actual world heading. + // Heading 0° = east → (+x, 0); 90° = north → (0, -y) on screen. + ax = cosH * 12f; + ay = -sinH * 12f; + } + dl.AddLine(centre, new Vector2(centre.X + ax, centre.Y + ay), ColPlayer, 2f); + } + + // In rotate+circular mode, mask any texture bleed outside the circle boundary + // by overdrawing the 4 corner areas (inside clip rect, outside circle) with the + // canvas background colour. Without this, AddImageQuad corners poke past the ring. + if (circular && rotate) + { + uint maskCol = SetAlpha(ColCanvasBg, Math.Clamp(_settings.RadarOpacity, 0f, 1f)); + DrawCircleCornerMasks(dl, centre, innerRadius, clipMin, clipMax, maskCol); + } + + dl.PopClipRect(); + + // Re-draw the circle outline rings after content so they always appear on top, + // covering any residual bleed right at the circle edge. + if (circular) + { + float ringR = sq * 0.5f - 2f; + dl.AddCircle(centre, ringR, ColFrameOuter, 64, 2f); + dl.AddCircle(centre, ringR - 3, ColFrameInner, 64, 1f); + } + + // Cardinals — ride the inner edge of the frame (square or circular). + DrawCardinals(dl, centre, sq * 0.5f - 10f, rotate ? (hRad - MathF.PI * 0.5f) : 0f, circular); + + // Gear button + popup — hoisted into a separate always-interactive sub-window + // so it stays clickable even when the main radar window has NoInputs (click-through). + { + const float btn = 14f; + Vector2 bPos; + if (circular) + { + float R = innerRadius; + const float k = 0.82f; + bPos = new Vector2( + centre.X + R * 0.707f * k - btn * 0.5f, + centre.Y - R * 0.707f * k - btn * 0.5f); + } + else + { + bPos = new Vector2(canvasPos.X + canvasSize.X - btn - 6f, canvasPos.Y + 6f); + } + RenderGearWindow("##rradar_gear_win", "*##rradar_gear", "##rradar_settings", bPos, btn); + } + + // Footer — outdoor shows world coords (N/S, E/W, Z); indoor hides N/S and E/W + // since they barely change inside a single landblock, and shows the landblock + // ID + Z instead. + { + string? coords = null; + if (isIndoor) + { + coords = $"LB {landblock:X4} Z {pz:0.0}"; + } + else if (NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) + { + coords = $"{MathF.Abs((float)ns):0.0}{(ns >= 0 ? "N" : "S")} {MathF.Abs((float)ew):0.0}{(ew >= 0 ? "E" : "W")} Z {pz:0.0}"; + } + + if (coords != null) + { + ImFontPtr font = ImGui.GetFont(); + const float coordSize = 16f; + Vector2 ts = font.CalcTextSizeA(coordSize, float.MaxValue, 0f, coords); + Vector2 tp = new Vector2(canvasPos.X + (canvasSize.X - ts.X) * 0.5f, + canvasPos.Y + canvasSize.Y + (FooterH - ts.Y) * 0.5f); + DrawTextOutlined(dl, font, coordSize, tp, coords, ColCoordText, ColTextOutline); + } + } + + // Scroll-wheel zoom over the canvas area. + // Note: we deliberately do NOT use an InvisibleButton here, because it would block + // the window's edge-resize grips and drag-to-move behaviour. + if (ImGui.IsWindowHovered()) + { + var mp = ImGui.GetIO().MousePos; + if (mp.X >= clipMin.X && mp.X <= clipMax.X && mp.Y >= clipMin.Y && mp.Y <= clipMax.Y) + { + float wheel = ImGui.GetIO().MouseWheel; + if (float.IsFinite(wheel) && wheel != 0f) + { + _settings.RadarZoom = Math.Clamp(_settings.RadarZoom + wheel * 0.25f, 0.5f, 20f); + ImGui.SetNextFrameWantCaptureMouse(true); + } + } + } + + ImGui.End(); + + if (snapRotate != _settings.RadarRotateWithPlayer + || snapShowM != _settings.RadarShowMonsters + || snapShowN != _settings.RadarShowNpcs + || snapShowP != _settings.RadarShowPortals + || snapShowD != _settings.RadarShowDoors + || snapPaint != _settings.RadarWallPaintRadius + || snapCirc != _settings.RadarCircular + || MathF.Abs(snapOp - _settings.RadarOpacity) > 0.001f + || MathF.Abs(snapZoom - _settings.RadarZoom) > 0.001f) + { + OnSettingChanged?.Invoke(); + } + } + + // ── Frame drawing ─────────────────────────────────────────────────── + + private void DrawFrame(ImDrawListPtr dl, Vector2 pos, Vector2 size, bool circular) + { + float op = Math.Clamp(_settings.RadarOpacity, 0f, 1f); + uint bg = SetAlpha(ColCanvasBg, op); + + Vector2 a = pos; + Vector2 b = pos + size; + + if (circular) + { + Vector2 c = (a + b) * 0.5f; + float r = MathF.Min(size.X, size.Y) * 0.5f - 2f; + const int seg = 64; + + dl.AddCircleFilled(c, r, bg, seg); + // Ring outlines are drawn AFTER content (see Render) so they always appear on top. + + // Four compass tick marks just inside the rim (N/E/S/W) in the accent colour. + float ti = r - 8f; + float to = r - 2f; + dl.AddLine(new Vector2(c.X, c.Y - ti), new Vector2(c.X, c.Y - to), ColFrameAccent, 2f); + dl.AddLine(new Vector2(c.X, c.Y + ti), new Vector2(c.X, c.Y + to), ColFrameAccent, 2f); + dl.AddLine(new Vector2(c.X - ti, c.Y), new Vector2(c.X - to, c.Y), ColFrameAccent, 2f); + dl.AddLine(new Vector2(c.X + ti, c.Y), new Vector2(c.X + to, c.Y), ColFrameAccent, 2f); + return; + } + + float rr = 4f; + dl.AddRectFilled(a, b, bg, rr); + dl.AddRect(new Vector2(a.X + 1, a.Y + 1), new Vector2(b.X - 1, b.Y - 1), ColFrameOuter, rr, ImDrawFlags.None, 2f); + dl.AddRect(new Vector2(a.X + 3, a.Y + 3), new Vector2(b.X - 3, b.Y - 3), ColFrameInner, rr, ImDrawFlags.None, 1f); + + float cl = 8f; + float co = 2f; + dl.AddLine(new Vector2(a.X - co, a.Y + cl), new Vector2(a.X - co, a.Y - co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(a.X - co, a.Y - co), new Vector2(a.X + cl, a.Y - co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(b.X - cl, a.Y - co), new Vector2(b.X + co, a.Y - co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(b.X + co, a.Y - co), new Vector2(b.X + co, a.Y + cl), ColFrameAccent, 2f); + dl.AddLine(new Vector2(a.X - co, b.Y - cl), new Vector2(a.X - co, b.Y + co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(a.X - co, b.Y + co), new Vector2(a.X + cl, b.Y + co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(b.X - cl, b.Y + co), new Vector2(b.X + co, b.Y + co), ColFrameAccent, 2f); + dl.AddLine(new Vector2(b.X + co, b.Y + co), new Vector2(b.X + co, b.Y - cl), ColFrameAccent, 2f); + } + + private static void DrawCardinals(ImDrawListPtr dl, Vector2 centre, float halfSize, float rotationRad, bool circular) + { + ReadOnlySpan labels = new[] { "N", "E", "S", "W" }; + // Clockwise angles from screen-up, when rotationRad = 0 (north-up). + ReadOnlySpan angles = new[] { 0f, MathF.PI * 0.5f, MathF.PI, MathF.PI * 1.5f }; + + ImFontPtr font = ImGui.GetFont(); + const float size = 18f; + + for (int i = 0; i < 4; i++) + { + float a = angles[i] + rotationRad; + // Direction vector from centre: (sin a, -cos a) so angle 0 = up. + float dx = MathF.Sin(a); + float dy = -MathF.Cos(a); + + float x, y; + if (circular) + { + // Ride the circle of radius = halfSize. + x = centre.X + dx * halfSize; + y = centre.Y + dy * halfSize; + } + else + { + // Project onto the SQUARE of half-side `halfSize`: scale dir so + // that max(|dx|,|dy|) equals halfSize → label sits on the perimeter. + float m = MathF.Max(MathF.Abs(dx), MathF.Abs(dy)); + if (m < 1e-4f) continue; + float k = halfSize / m; + x = centre.X + dx * k; + y = centre.Y + dy * k; + } + + Vector2 ts = font.CalcTextSizeA(size, float.MaxValue, 0f, labels[i]); + var pos = new Vector2(x - ts.X * 0.5f, y - ts.Y * 0.5f); + DrawTextOutlined(dl, font, size, pos, labels[i], ColCardinal, ColTextOutline); + } + } + + /// Draws text with a 1px black outline (4-way offset) for legibility + /// over varied backgrounds. + private static void DrawTextOutlined(ImDrawListPtr dl, ImFontPtr font, float size, + Vector2 pos, string text, uint fg, uint outline) + { + dl.AddText(font, size, new Vector2(pos.X + 1, pos.Y), outline, text); + dl.AddText(font, size, new Vector2(pos.X - 1, pos.Y), outline, text); + dl.AddText(font, size, new Vector2(pos.X, pos.Y + 1), outline, text); + dl.AddText(font, size, new Vector2(pos.X, pos.Y - 1), outline, text); + dl.AddText(font, size, new Vector2(pos.X + 1, pos.Y + 1), outline, text); + dl.AddText(font, size, new Vector2(pos.X - 1, pos.Y - 1), outline, text); + dl.AddText(font, size, new Vector2(pos.X + 1, pos.Y - 1), outline, text); + dl.AddText(font, size, new Vector2(pos.X - 1, pos.Y + 1), outline, text); + dl.AddText(font, size, pos, fg, text); + } + + /// + /// Renders the gear button and its settings popup in a separate, always- + /// interactive ImGui sub-window, so the gear stays clickable even when the + /// main radar window has NoInputs (click-through). + /// + private void RenderGearWindow(string winId, string btnId, string popupId, Vector2 pos, float size) + { + ImGui.SetNextWindowPos(pos); + ImGui.SetNextWindowSize(new Vector2(size, size)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u); + + const ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar + | ImGuiWindowFlags.NoResize + | ImGuiWindowFlags.NoMove + | ImGuiWindowFlags.NoCollapse + | ImGuiWindowFlags.NoBackground + | ImGuiWindowFlags.NoSavedSettings + | ImGuiWindowFlags.NoBringToFrontOnFocus; + + bool open = true; + if (ImGui.Begin(winId, ref open, flags)) + { + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0f, 0f, 0f, 0.55f)); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.25f, 0.30f, 0.40f, 0.85f)); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.20f, 0.25f, 0.35f, 1f)); + if (ImGui.Button(btnId, new Vector2(size, size))) + ImGui.OpenPopup(popupId); + ImGui.PopStyleColor(3); + RenderSettingsPopup(); + } + ImGui.End(); + + ImGui.PopStyleColor(); + ImGui.PopStyleVar(2); + } + + private void RenderSettingsPopup() + { + // Push RynthAi dark-navy palette so the popup matches the rest of the UI + ImGui.PushStyleColor(ImGuiCol.PopupBg, new Vector4(0.08f, 0.10f, 0.16f, 0.97f)); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.90f, 0.92f, 0.96f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.14f, 0.18f, 0.28f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.20f, 0.27f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.17f, 0.23f, 0.35f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.90f, 0.78f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.SliderGrab, new Vector4(0.62f, 0.52f, 0.24f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, new Vector4(0.90f, 0.78f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.Separator, new Vector4(0.25f, 0.35f, 0.52f, 1.00f)); + + if (!ImGui.BeginPopup("##rradar_settings")) + { + ImGui.PopStyleColor(9); + return; + } + + ImGui.Text("Radar Settings"); + ImGui.Separator(); + + ImGui.Checkbox("Rotate with Player", ref _settings.RadarRotateWithPlayer); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("On: player facing points up and compass rotates.\nOff: north is always up."); + + ImGui.Checkbox("Circular Radar", ref _settings.RadarCircular); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Off: square frame. On: circular frame (content outside the circle is culled)."); + + ImGui.Checkbox("Click-Through", ref _settings.RadarClickThrough); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Mouse events pass through to the game. Move/resize/gear are disabled while on.\nTurn it back off from Advanced Settings → Navigation → Radar."); + + ImGui.SetNextItemWidth(140); + ImGui.SliderFloat("Opacity", ref _settings.RadarOpacity, 0.15f, 1f, "%.2f"); + ImGui.SetNextItemWidth(140); + ImGui.SliderFloat("Zoom", ref _settings.RadarZoom, 0.5f, 20f, "%.1f"); + ImGui.SetNextItemWidth(140); + ImGui.SliderInt("Paint Radius", ref _settings.RadarWallPaintRadius, 1, 20); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Distance (in 0.5m grid cells) around the player that\nmarks walls as explored. Higher = walls light up from further away."); + + ImGui.Separator(); + ImGui.Text("Show:"); + ImGui.Checkbox("Monsters##rradar", ref _settings.RadarShowMonsters); + ImGui.Checkbox("NPCs##rradar", ref _settings.RadarShowNpcs); + ImGui.Checkbox("Portals##rradar", ref _settings.RadarShowPortals); + ImGui.Checkbox("Doors##rradar", ref _settings.RadarShowDoors); + + ImGui.EndPopup(); + ImGui.PopStyleColor(9); + } + + // ── Visited strip cache ───────────────────────────────────────────── + + private void RebuildRadarVisitedStrips() + { + if (_mapData?._floorCells is null || _visitedCells.Count == 0 || _mapData._zLayers is null) + { + _visitedFillStrips = null; + return; + } + + var result = new System.Collections.Generic.Dictionary>( + _mapData._zLayers.Count); + foreach (var (layerZ, cells) in _mapData._floorCells) + { + var flatVisited = new System.Collections.Generic.List<(int, int)>(); + foreach (var ((gx, gy), ctype) in cells) + if (ctype == DungeonMapUi.CellType.Flat && _visitedCells.Contains((gx, gy))) + flatVisited.Add((gx, gy)); + if (flatVisited.Count == 0) continue; + var strips = DungeonMapUi.BuildVisitedStripsFrom(flatVisited); + if (strips.Count > 0) result[layerZ] = strips; + } + _visitedFillStrips = result.Count > 0 ? result : null; + } + + // ── Projection ────────────────────────────────────────────────────── + + /// + /// Project a world-space XY point (landblock-local is fine as long as playerX/playerY + /// are expressed in the same basis) to radar screen coords. + /// + /// AC convention: +X = east, +Y = north, heading 0° = east, 90° = north (CCW from east). + /// + private static Vector2 ProjectWorld( + float wx, float wy, float playerX, float playerY, + Vector2 centre, float zoom, bool rotate, float sinH, float cosH) + { + float dx = wx - playerX; // east offset + float dy = wy - playerY; // north offset + + float sx, sy; + if (rotate) + { + // Rotate world by (90° - heading) so facing → screen-up. + // newX = sin(h)*dx - cos(h)*dy (screen right) + // newY = cos(h)*dx + sin(h)*dy (screen up → screen -Y) + float right = sinH * dx - cosH * dy; + float forward = cosH * dx + sinH * dy; + sx = centre.X + right * zoom; + sy = centre.Y - forward * zoom; + } + else + { + sx = centre.X + dx * zoom; + sy = centre.Y - dy * zoom; + } + return new Vector2(sx, sy); + } + + private static bool InRect(Vector2 p, Vector2 min, Vector2 max) + => p.X >= min.X && p.X <= max.X && p.Y >= min.Y && p.Y <= max.Y; + + private static uint SetAlpha(uint col, float alpha) + { + uint a = (uint)(Math.Clamp(alpha, 0f, 1f) * 255f); + return (col & 0x00FFFFFF) | (a << 24); + } + + /// + /// Best-effort portal display name. STypePortalDest (38) holds the raw destination + /// when available, otherwise we fall back to the object name. The label is then + /// reduced to just the destination proper: + /// • first line only (strip anything past a newline) + /// • tokenise on whitespace/punctuation + /// • drop any token that is literally "portal" + /// • drop any token that looks like a coord ("5.6N", "-12.3W", etc.) + /// Result is trimmed and ellipsis-truncated at 22 chars. + /// + private string GetPortalLabel(WorldObject wo) + { + const uint STypePortalDest = 38u; + string label = wo.Name ?? string.Empty; + + if (_host.HasGetObjectStringProperty + && _host.TryGetObjectStringProperty((uint)wo.Id, STypePortalDest, out string dest) + && !string.IsNullOrEmpty(dest)) + { + label = dest; + } + + int nl = label.IndexOf('\n'); + if (nl >= 0) label = label.Substring(0, nl); + + var sb = new System.Text.StringBuilder(); + int i = 0; + while (i < label.Length) + { + while (i < label.Length && IsLabelSep(label[i])) i++; + if (i >= label.Length) break; + int start = i; + while (i < label.Length && !IsLabelSep(label[i])) i++; + string tok = label.Substring(start, i - start); + + if (tok.Equals("portal", StringComparison.OrdinalIgnoreCase)) continue; + if (tok.Equals("to", StringComparison.OrdinalIgnoreCase)) continue; + if (LooksLikeCoord(tok)) continue; + if (IsNumericToken(tok)) continue; + + if (sb.Length > 0) sb.Append(' '); + sb.Append(tok); + } + + string result = sb.ToString().Trim(); + if (result.Length > 22) result = result.Substring(0, 22) + "…"; + return result; + } + + private static bool IsLabelSep(char c) + => c == ' ' || c == '\t' || c == ',' || c == ';' || c == ':' || c == '(' || c == ')' || c == '.'; + + /// True if the token looks like a coordinate — a digit/sign followed + /// eventually by a compass letter (N/S/E/W), e.g. "5.6N", "-12.3W", "0N". + /// Note: IsLabelSep consumes '.' so coord fragments arrive as "56N" / "123W". + /// True if every char in the token is a digit or sign (e.g. "49", "-12", + /// "+5"). Catches bare coord numbers that don't carry a compass letter. + private static bool IsNumericToken(string tok) + { + if (tok.Length == 0) return false; + int start = 0; + if (tok[0] == '-' || tok[0] == '+') { if (tok.Length == 1) return false; start = 1; } + for (int i = start; i < tok.Length; i++) + if (!char.IsDigit(tok[i])) return false; + return true; + } + + private static bool LooksLikeCoord(string tok) + { + if (tok.Length < 2) return false; + char last = tok[tok.Length - 1]; + bool endsCompass = last == 'N' || last == 'S' || last == 'E' || last == 'W' + || last == 'n' || last == 's' || last == 'e' || last == 'w'; + if (!endsCompass) return false; + char first = tok[0]; + if (!(char.IsDigit(first) || first == '-' || first == '+')) return false; + for (int i = 1; i < tok.Length - 1; i++) + if (!char.IsDigit(tok[i])) return false; + return true; + } + + private static bool IsDoorName(string name) + { + if (string.IsNullOrEmpty(name)) return false; + return name.Contains("Door", StringComparison.OrdinalIgnoreCase) + || name.Contains("Gate", StringComparison.OrdinalIgnoreCase) + || name.Contains("Portcullis", StringComparison.OrdinalIgnoreCase) + || name.Contains("Hatch", StringComparison.OrdinalIgnoreCase) + || name.Contains("Trapdoor", StringComparison.OrdinalIgnoreCase); + } + + // ── Circular-clip helpers ─────────────────────────────────────────── + + /// + /// Covers the 4 corner areas (inside clipMin/clipMax square but outside the circle) + /// with via triangle fans, masking any content that bled + /// outside the circle boundary (e.g. AddImageQuad corners in rotate mode). + /// Angle convention: (cos a, sin a) in screen coords where +Y is down. + /// NW arc: PI → 3PI/2 (left→top, through upper-left) + /// NE arc: -PI/2 → 0 (top→right, through upper-right) + /// SE arc: 0 → PI/2 (right→bottom, through lower-right) + /// SW arc: PI/2 → PI (bottom→left, through lower-left) + /// + private static void DrawCircleCornerMasks(ImDrawListPtr dl, Vector2 centre, + float radius, Vector2 clipMin, Vector2 clipMax, uint color) + { + MaskCornerFan(dl, new Vector2(clipMin.X, clipMin.Y), centre, radius, MathF.PI, MathF.PI * 1.5f, color); + MaskCornerFan(dl, new Vector2(clipMax.X, clipMin.Y), centre, radius, -MathF.PI * 0.5f, 0f, color); + MaskCornerFan(dl, new Vector2(clipMax.X, clipMax.Y), centre, radius, 0f, MathF.PI * 0.5f, color); + MaskCornerFan(dl, new Vector2(clipMin.X, clipMax.Y), centre, radius, MathF.PI * 0.5f, MathF.PI, color); + } + + private static void MaskCornerFan(ImDrawListPtr dl, Vector2 corner, Vector2 centre, + float radius, float startAngle, float endAngle, uint color) + { + const int Segs = 8; + var prev = new Vector2(centre.X + MathF.Cos(startAngle) * radius, + centre.Y + MathF.Sin(startAngle) * radius); + for (int i = 1; i <= Segs; i++) + { + float a = startAngle + (endAngle - startAngle) * i / Segs; + var cur = new Vector2(centre.X + MathF.Cos(a) * radius, + centre.Y + MathF.Sin(a) * radius); + dl.AddTriangleFilled(corner, prev, cur, color); + prev = cur; + } + } + + // ── Snapshot bridge for the engine-side Avalonia radar panel ──────────── + // Mirrors the data Render() consumes, but never touches ImGui — safe to + // call whether or not the ImGui radar is showing. Visited-cell tracking + // advances here too, so the visited overlay populates even when the user + // has the ImGui radar hidden in favour of the Avalonia panel. + + /// + /// Build a JSON snapshot for the Avalonia radar. + /// is the MapVersion the engine currently has cached; pass 0 on first call. + /// When it matches the live landblock, walls/fills are omitted to keep the + /// payload small. + /// + internal string BuildSnapshotJson(uint engineKnownMapVersion) + { + try + { + var payload = BuildSnapshotPayload(engineKnownMapVersion); + return System.Text.Json.JsonSerializer.Serialize( + payload, RadarSnapshotJsonContext.Default.RadarSnapshotPayload); + } + catch + { + return "{}"; + } + } + + private RadarSnapshotPayload BuildSnapshotPayload(uint engineKnownMapVersion) + { + var payload = new RadarSnapshotPayload(); + if (!_host.HasGetPlayerPose) return payload; + if (!_host.TryGetPlayerPose(out uint cellId, out float px, out float py, out float pz, + out _, out _, out _, out _)) + return payload; + + uint landblock = cellId >> 16; + bool isIndoor = (cellId & 0xFFFF) >= 0x100 && landblock != 0; + float gxLB = ((landblock >> 8) & 0xFF) * 192f; + float gyLB = (landblock & 0xFF) * 192f; + float playerWX = px + gxLB; + float playerWY = py + gyLB; + + // Reset visited state on landblock change — matches Render() exactly. + if (landblock != _visitedLandblock) + { + _visitedLandblock = landblock; + _visitedCells.Clear(); + _visitedFillStrips = null; + _lastVisitedCount = -1; + } + + if (isIndoor) + { + int pgx = (int)MathF.Floor(playerWX / GridCell); + int pgy = (int)MathF.Floor(playerWY / GridCell); + int r = Math.Clamp(_settings.RadarWallPaintRadius, 0, 40); + for (int oy = -r; oy <= r; oy++) + for (int ox = -r; ox <= r; ox++) + _visitedCells.Add((pgx + ox, pgy + oy)); + } + + if (_visitedCells.Count != _lastVisitedCount && _mapData != null) + { + _lastVisitedCount = _visitedCells.Count; + RebuildRadarVisitedStrips(); + } + + _host.TryGetPlayerHeading(out float heading); + + // Outdoor landblocks share geometry-less snapshots — MapVersion=landblock + // still works, but GeometryIncluded stays false because there's no wall data. + bool sameVersion = engineKnownMapVersion != 0 && engineKnownMapVersion == landblock; + + payload.MapVersion = landblock; + payload.GeometryIncluded = !sameVersion && isIndoor; + payload.IsIndoor = isIndoor; + payload.Player = new RadarPlayer + { + CellId = cellId, + Landblock = landblock, + X = px, Y = py, Z = pz, + WorldX = playerWX, WorldY = playerWY, + Heading = heading, + }; + + // NS/EW only meaningful outdoors; we send always so the panel can + // decide whether to display them. NaN signals "unavailable". + if (NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) + { + payload.Ns = ns; + payload.Ew = ew; + } + + if (isIndoor && _mapData != null) + { + _mapData.EnsureCache(landblock); + var zLayers = _mapData._zLayers; + if (zLayers is { Count: > 0 }) + { + payload.LayerZs.Capacity = zLayers.Count; + foreach (var z in zLayers) payload.LayerZs.Add(z); + int curIdx = _mapData.BestLayerIdxFor(pz); + payload.CurrentLayerZ = zLayers[curIdx]; + + if (payload.GeometryIncluded) + { + if (_mapData._outerEdgesRaw != null) + { + foreach (var kv in _mapData._outerEdgesRaw) + { + var edges = kv.Value; + var arr = new float[edges.Count * 6]; + for (int i = 0; i < edges.Count; i++) + { + var (ax, ay, bx, by, _, gx, gy) = edges[i]; + int o = i * 6; + arr[o] = ax; arr[o + 1] = ay; + arr[o + 2] = bx; arr[o + 3] = by; + arr[o + 4] = gx; arr[o + 5] = gy; + } + payload.Walls.Add(new RadarWallLayer { Z = kv.Key, Segments = arr }); + } + } + if (_mapData._fillStrips != null) + { + foreach (var kv in _mapData._fillStrips) + { + var strips = kv.Value; + var arr = new float[strips.Count * 5]; + for (int i = 0; i < strips.Count; i++) + { + var (x0, y0, x1, y1, type) = strips[i]; + int o = i * 5; + arr[o] = x0; arr[o + 1] = y0; + arr[o + 2] = x1; arr[o + 3] = y1; + arr[o + 4] = (float)(int)type; + } + payload.Fills.Add(new RadarFillLayer { Z = kv.Key, Strips = arr }); + } + } + } + + if (_visitedFillStrips != null) + { + foreach (var kv in _visitedFillStrips) + { + var strips = kv.Value; + var arr = new float[strips.Count * 4]; + for (int i = 0; i < strips.Count; i++) + { + var (x0, y0, x1, y1) = strips[i]; + int o = i * 4; + arr[o] = x0; arr[o + 1] = y0; + arr[o + 2] = x1; arr[o + 3] = y1; + } + payload.Visited.Add(new RadarVisitedLayer { Z = kv.Key, Strips = arr }); + } + } + } + } + + if (_objectCache != null && _host.HasGetObjectPosition && landblock != 0) + { + const uint STypeCreatureType = 2u; + const int CreatureTypeNpc = 14; + const uint TypePortal = 0x10000u; + + foreach (var wo in _objectCache.GetLandscape()) + { + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cCellId, + out float cox, out float coy, out float coz)) continue; + if ((cCellId >> 16) != landblock) continue; + + bool isNpc = _host.HasGetObjectIntProperty + && _host.TryGetObjectIntProperty((uint)wo.Id, STypeCreatureType, out int ct) + && ct == CreatureTypeNpc; + payload.Markers.Add(new RadarMarker + { + Kind = isNpc ? (byte)1 : (byte)0, + X = cox + gxLB, Y = coy + gyLB, Z = coz, + }); + } + + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + if ((uint)wo.Id >= 0x80000000u) continue; + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint oCellId, + out float oox, out float ooy, out float ooz)) continue; + if ((oCellId >> 16) != landblock) continue; + + bool isPortal = _host.HasGetItemType + && _host.TryGetItemType((uint)wo.Id, out uint typeFlags) + && (typeFlags & TypePortal) != 0; + bool isDoor = !isPortal && IsDoorName(wo.Name); + if (!isPortal && !isDoor) continue; + + payload.Markers.Add(new RadarMarker + { + Kind = isPortal ? (byte)2 : (byte)3, + X = oox + gxLB, Y = ooy + gyLB, Z = ooz, + Label = isPortal ? GetPortalLabel(wo) : null, + }); + } + } + + return payload; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs new file mode 100644 index 0000000..4506835 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -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; + +/// +/// 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. +/// +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 _cramPending = new(); // item id -> in-flight move + private readonly Dictionary _cramBackoff = new(); // item id -> confirmed-fail backoff + private readonly Dictionary _stackPending = new(); // "tgt_src" -> in-flight merge + private readonly Dictionary _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 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 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(); + 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(Dictionary 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(Dictionary map, Func stamp, DateTime now) + where TKey : notnull + { + List? 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs new file mode 100644 index 0000000..8cb3156 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs @@ -0,0 +1,75 @@ +using System.Text.RegularExpressions; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// Evaluates SDK LootCondition/LootRule/LootProfile data against live AC WorldObjects. +/// Kept separate from the SDK so the editor has zero AC dependencies. +/// +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; + } + + /// + /// Returns the first matching rule's action, or null if nothing matched. + /// Callers treat null as "leave on corpse" — do not pick up. + /// + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs new file mode 100644 index 0000000..e06715c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs @@ -0,0 +1,1084 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// Drives the salvage state machine for loot-rule items marked Salvage. +/// Items are enqueued by CorpseOpenController after pickup confirmation. +/// +/// Flow per item: +/// Idle → call OpenSalvagePanel(ustId), wait OpenDelay +/// → call AddNewItem(itemId), wait AddDelay +/// → call Salvage(), wait SalvageDelay +/// → wait ResultDelay → Idle (next item or CombineSalvage) +/// +/// First-open delays (400ms/600ms) let the panel animate open and the +/// gmSalvageUI singleton hook fire before we make thiscall instance calls. +/// Fast delays (50ms) apply once the panel has been opened at least once. +/// +public sealed class SalvageManager +{ + private enum Phase { Idle, OpeningPanel, AddingItem, Salvaging, WaitingForResult, CombiningSalvage } + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly WorldObjectCache? _cache; + + private readonly Queue _queue = new(); + private Phase _phase = Phase.Idle; + private long _phaseReadyAt; + private uint _currentItemId; + private uint _currentUstId; + private bool _panelEverOpened; + private bool _firstResultCycle = true; + private bool _pendingCombineScan; + + // Combine-salvage state — process one material group per cycle by opening + // the salvage panel, adding all under-full bags of that material, and hitting + // Salvage so the server merges them server-side. Far more reliable than the + // old MoveItemExternal-into-bag approach which AC silently rejects when the + // bags have different workmanship. + private enum CombinePhase { None, OpeningPanel, AddingBags, Salvaging, WaitingForResult } + private List>? _combineGroups; + private int _combineGroupIdx; + private int _combineAddIdx; + private CombinePhase _combinePhase = CombinePhase.None; + private long _combinePhaseReadyAt; + + // Verification — snapshot of the bag ids submitted for the current group's + // Execute. After the result delay, we count how many of these are still in + // the cache to decide whether the server actually merged them. + private List? _combineGroupSnapshot; + + // Polling deadline for verification. The salvage delete event from the + // server can arrive 500ms-1s after Execute on busy servers; we keep + // checking inventory until either the items are gone OR this deadline + // passes. Without this, fast result delays (~300ms) produce false-negative + // re-queues and prevent _pendingCombineScan from ever firing. + private long _waitingResultDeadline; + private const long ResultMaxWaitMs = 2000; + + // Session-level combine metrics. Logged per-group so the user can see + // running totals without needing a separate diagnostic surface. + private int _combineGroupsSucceeded; + private int _combineGroupsFailed; + private int _bagsMergedThisSession; + + // Per-item retry counter so a failed salvage gets re-queued a few times + // before we give up. AC sometimes drops a Salvage execute when the bot is + // busy with other actions; the item stays in the pack and we want to try + // again when the queue gets back to idle. + private readonly Dictionary _itemRetryCount = new(); + private const int MaxItemRetries = 3; + + // Backoff after a refused panel step. Without it a failed UseObject/AddItem + // re-queues the item and TickIdle dequeues it again on the very next tick, + // so one busy hiccup burns all three attempts inside ~50ms and the item is + // dropped. A second is long enough for the action queue to clear. + private long _idleRetryReadyAt; + private const long RetryBackoffMs = 1000; + + // Same for the combine sweep: a refused UseObject used to skip the whole + // material group immediately, and with no timer set the next tick tried the + // next group — so one hiccup could tear through every group in the sweep. + // Retry the group a few times on the same backoff before giving up on it. + private int _combineOpenAttempts; + private const int MaxCombineOpenAttempts = 3; + + // Last thing that went wrong, for GetStateSnapshot. The Log() trail has this + // but the log is where you look *after* you know salvage is the problem; + // this is so a state dump says so on its own. + private string _lastError = string.Empty; + private long _lastErrorAt; + + // Periodic combine sweep — even when no items have been salvaged this + // session (or every salvage gave up after retries), we still want to + // periodically merge any under-full bags sitting in inventory. + private long _lastCombineSweepAt; + private const long CombineSweepIntervalMs = 30_000; + + private static long NowMs => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + /// + /// Set by the plugin to point at the currently-loaded loot profile's + /// SalvageCombine block (if any). When non-null and Enabled, bags are + /// grouped by (MaterialType, WorkmanshipBand) per the profile's rules + /// instead of just (MaterialType). + /// + public Func? CombineConfigProvider { get; set; } + + public SalvageManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache? cache) + { + _host = host; + _settings = settings; + _cache = cache; + } + + /// Returns true while a salvage operation is in flight. + public bool IsBusy => _phase != Phase.Idle || _queue.Count > 0; + + /// Enqueue an item to be salvaged. Called by CorpseOpenController after pickup. + public void EnqueueItem(uint itemId) + { + if (itemId == 0) + return; + + // A salvage bag is ALREADY salvage. Feeding one into the single-item + // flow opens the panel on a lone bag, Executes a no-op, fails the + // "still present" check, and retry-storms — this is the user-reported + // "keeps salvaging bags by themselves" behaviour. Bags are consolidated + // by the combine sweep (grouped, never solo); they must never enter the + // single-item queue. + string? name = _cache?[unchecked((int)itemId)]?.Name; + if (IsSalvageBag(name)) + { + Log($"[Salvage] Ignoring enqueue of salvage bag 0x{itemId:X8} ({name}) — bags are combined by the sweep, not salvaged solo."); + if (_settings.EnableCombineSalvage) _pendingCombineScan = true; + return; + } + + _queue.Enqueue(itemId); + _pendingCombineScan = false; // reset; will be set again when queue drains + } + + /// Called every game tick from RynthAiPlugin.OnTick. + public void OnTick(int busyCount) + { + if (!_host.HasSalvagePanel || !_host.HasUseObject) + return; + + long now = NowMs; + + switch (_phase) + { + case Phase.Idle: + TickIdle(now, busyCount); + break; + + case Phase.OpeningPanel: + if (now >= _phaseReadyAt) + BeginAddingItem(now); + break; + + case Phase.AddingItem: + if (now >= _phaseReadyAt) + BeginSalvaging(now); + break; + + case Phase.Salvaging: + if (now >= _phaseReadyAt) + BeginWaitingForResult(now); + break; + + case Phase.WaitingForResult: + if (now < _phaseReadyAt) break; + // Poll: if the item is still in inventory and we're under the + // deadline, wait for the next tick. Server delete events for + // salvage-consumed items can lag the result delay by 500ms+. + if (_currentItemId != 0 + && now < _waitingResultDeadline + && IsItemInDirectInventory(_currentItemId)) + { + break; + } + OnResultReady(now); + break; + + case Phase.CombiningSalvage: + TickCombiningSalvage(now); + break; + } + } + + // ── Phase handlers ──────────────────────────────────────────────────────── + + private void TickIdle(long now, int busyCount) + { + if (_queue.Count == 0) + { + if (_pendingCombineScan && _settings.EnableCombineSalvage) + { + _pendingCombineScan = false; + _lastCombineSweepAt = now; + BeginCombineSalvage(now); + return; + } + // Periodic standalone sweep: if 30s have passed since the last + // combine attempt and there are still under-full bag groups in the + // pack, run another pass. Catches bags accumulated from sources + // outside the salvage queue (or sessions where every salvage gave + // up after retries). + if (_settings.EnableCombineSalvage + && busyCount == 0 + && now - _lastCombineSweepAt >= CombineSweepIntervalMs) + { + _lastCombineSweepAt = now; + BeginCombineSalvage(now); + } + return; + } + + // Don't start while the game is busy processing a prior action. + if (busyCount > 0) + return; + + // Serving out the backoff from a refused panel step. + if (now < _idleRetryReadyAt) + return; + + uint itemId = _queue.Dequeue(); + if (itemId == 0) + return; + + // Backstop for the EnqueueItem guard: the item's name may not have been + // cached at enqueue time. Never run the single-item salvage flow on a + // bag — it's already salvage; the combine sweep consolidates it. + string? dqName = _cache?[unchecked((int)itemId)]?.Name; + if (IsSalvageBag(dqName)) + { + Log($"[Salvage] Dequeued a salvage bag 0x{itemId:X8} ({dqName}) — skipping solo salvage; combine sweep will consolidate it."); + if (_settings.EnableCombineSalvage) _pendingCombineScan = true; + return; + } + + uint ustId = FindUst(); + if (ustId == 0) + { + _host.WriteToChat("[RynthAi] Salvage: No UST found in inventory — item skipped. Add a Ust to your pack.", 2); + NoteError("no UST in inventory — item skipped"); + Log($"[Salvage] No UST found in inventory — skipping 0x{itemId:X8}."); + return; + } + + _currentItemId = itemId; + _currentUstId = ustId; + + // UseObject on the UST mimics a double-click — this is the reliable path to + // trigger gmSalvageUI::OpenSalvagePanel (our hook captures the instance there). + // SendNotice_OpenSalvagePanel does not reliably call the hooked function. + if (!_host.UseObject(_currentUstId)) + { + Log($"[Salvage] UseObject(UST) failed for 0x{_currentUstId:X8} — re-queuing item."); + NoteError($"UseObject(UST) failed for 0x{_currentUstId:X8}"); + _currentItemId = 0; + _currentUstId = 0; + RequeueOrDrop(itemId, "UseObject(UST) failed"); + _idleRetryReadyAt = now + RetryBackoffMs; + return; + } + + int openDelay = _panelEverOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; + _phaseReadyAt = now + openDelay; + _phase = Phase.OpeningPanel; + } + + private void BeginAddingItem(long now) + { + if (!_host.SalvagePanelAddItem(_currentItemId)) + { + Log($"[Salvage] SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel instance not ready — re-queuing)."); + NoteError($"SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel not ready)"); + // Re-queue the item so we retry on the next idle cycle. Reset panel-ever-opened + // so the longer first-open delays are applied on retry. + uint failedItemId = _currentItemId; + _currentItemId = 0; + _currentUstId = 0; + _panelEverOpened = false; + _phase = Phase.Idle; + RequeueOrDrop(failedItemId, "SalvagePanelAddItem failed"); + _idleRetryReadyAt = now + RetryBackoffMs; + return; + } + + // Combine-during-salvage: add ALL under-full bags of the same material + // (and workmanship band, if configured) alongside the new item so the + // server merges everything in one operation. + int extraBags = 0; + if (_settings.CombineBagsDuringSalvage) + extraBags = AddAllMatchingUnderFullBags(_currentItemId); + + bool wasFirstOpen = !_panelEverOpened; + _panelEverOpened = true; + // Allow 50 ms per extra bag so AC can register each add before Execute fires. + int addDelay = (wasFirstOpen ? _settings.SalvageAddDelayFirstMs : _settings.SalvageAddDelayFastMs) + + extraBags * _settings.SalvageAddDelayFastMs; + _phaseReadyAt = now + addDelay; + _phase = Phase.AddingItem; + } + + // STypes (canonical values from Chorizite STypes.cs — verified against + // the live binary; the PropertyNames.IntNames index in this codebase is + // off-by-some-rows so do NOT use it as the source of truth). + private const uint StypeMaxStructure = 91; + private const uint StypeStructure = 92; + private const uint StypeItemWorkmanship = 105; + private const uint StypeMaterialType = 131; + // On a salvage BAG, ItemWorkmanship(#105) is a cumulative SUM, not a 1-10 + // value (ACE Player_Crafting.TryAddSalvage). The per-bag average workmanship + // used for band grouping is #105 / NumItemsInMaterial(#170). + private const uint StypeNumItemsInMaterial = 170; + + /// + /// Scans inventory for every under-full salvage bag whose material (and + /// workmanship band, if configured) matches , adds + /// each one to the open salvage panel, and returns how many were added. + /// Adding them all at once lets the server merge everything in one Salvage + /// operation instead of leaving partial bags for the periodic sweep. + /// + private int AddAllMatchingUnderFullBags(uint itemId) + { + if (_cache == null) return 0; + if (!_host.TryGetObjectIntProperty(itemId, StypeMaterialType, out int itemMat) || itemMat == 0) + return 0; + + RynthCore.Loot.SalvageCombineSettings? cfg = CombineConfigProvider?.Invoke(); + bool useBands = cfg != null && cfg.Enabled; + + // The freshly-looted ITEM carries a true 1-10 ItemWorkmanship(#105) — + // unlike a bag, whose #105 is a cumulative sum. So the item's band is + // read directly here; bag keys come from TryGetBagCombineKey (average). + string itemKey; + if (useBands) + { + if (!_host.TryGetObjectIntProperty(itemId, StypeItemWorkmanship, out int itemWm) || itemWm <= 0) + return 0; + string? itemBand = cfg!.GetBandKey(itemMat, itemWm); + if (itemBand == null) return 0; + itemKey = $"{itemMat}|{itemBand}"; + } + else + { + itemKey = itemMat.ToString(); + } + + int added = 0; + foreach (WorldObject bag in _cache.GetDirectInventory(forceRefresh: true)) + { + uint bagId = unchecked((uint)bag.Id); + if (bagId == itemId) continue; + if (!IsSalvageBag(bag.Name)) continue; + if (!IsBagUnderFull(bagId, bag.Name)) continue; + if (!TryGetBagCombineKey(bagId, bag.Name, cfg, useBands, out string bagKey, out _)) continue; + if (bagKey != itemKey) continue; + + if (_host.SalvagePanelAddItem(bagId)) + { + Log($"[Salvage] Combine-during-salvage: added bag {bag.Name} 0x{bagId:X8} ({added + 1})."); + added++; + } + } + + return added; + } + + private void BeginSalvaging(long now) + { + if (!_host.SalvagePanelExecute()) + { + Log($"[Salvage] SalvagePanelExecute failed for 0x{_currentItemId:X8} — re-queuing."); + RequeueOrDrop(_currentItemId, "execute failed"); + _currentItemId = 0; + _phase = Phase.Idle; + return; + } + + _phaseReadyAt = now + _settings.SalvageSalvageDelayMs; + _phase = Phase.Salvaging; + } + + private void BeginWaitingForResult(long now) + { + int resultDelay = _firstResultCycle + ? _settings.SalvageResultDelayFirstMs + : _settings.SalvageResultDelayFastMs; + _firstResultCycle = false; + _phaseReadyAt = now + resultDelay; + _waitingResultDeadline = now + resultDelay + ResultMaxWaitMs; + _phase = Phase.WaitingForResult; + } + + private void OnResultReady(long now) + { + // If the item we tried to salvage is STILL in the player's actual + // inventory after the result delay, the salvage didn't consume it + // (panel closed mid-execute, bot got busy, AC dropped the request, + // etc.). Re-queue so we try again. + // + // We use GetDirectInventory(forceRefresh: true) — a live walk of the + // player's containers — instead of _cache[id] because salvage-consumed + // items don't reliably trigger OnDeleteObject in the cache, leading to + // false positives where successfully-salvaged items get re-queued. + uint itemId = _currentItemId; + bool itemStillPresent = itemId != 0 && IsItemInDirectInventory(itemId); + + _currentItemId = 0; + _phase = Phase.Idle; + + if (itemStillPresent) + { + Log($"[Salvage] Item 0x{itemId:X8} still in inventory after salvage cycle — re-queuing."); + RequeueOrDrop(itemId, "item still present after result"); + } + else + { + // Successful salvage — clear retry counter for this id. + _itemRetryCount.Remove(itemId); + } + + // Always trigger a combine scan on the next idle tick when the queue + // drains — both to consolidate any newly-merged bags and so combine + // doesn't depend on the busyCount==0 gate of the periodic timer (which + // an active combat macro rarely satisfies). + if (_queue.Count == 0) + _pendingCombineScan = true; + } + + /// + /// Re-queue an item that failed a salvage step. Counts retries per id and + /// drops the item once it's failed MaxItemRetries times in a row, so a + /// truly un-salvageable item doesn't trap the queue forever. + /// + private void RequeueOrDrop(uint itemId, string reason) + { + if (itemId == 0) return; + + int prior = _itemRetryCount.TryGetValue(itemId, out int n) ? n : 0; + int next = prior + 1; + if (next > MaxItemRetries) + { + _itemRetryCount.Remove(itemId); + Log($"[Salvage] Giving up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason})."); + NoteError($"gave up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason})"); + // Trigger a combine scan if dropping this item left the queue empty. + if (_queue.Count == 0) _pendingCombineScan = true; + return; + } + _itemRetryCount[itemId] = next; + _queue.Enqueue(itemId); + Log($"[Salvage] Re-queued 0x{itemId:X8} ({reason}) — attempt {next}/{MaxItemRetries}."); + } + + // ── Combine salvage bags ────────────────────────────────────────────────── + + private void BeginCombineSalvage(long now) + { + if (_cache == null) return; + + RynthCore.Loot.SalvageCombineSettings? cfg = CombineConfigProvider?.Invoke(); + bool useBands = cfg != null && cfg.Enabled; + + // Group under-full bags by MaterialType (and Workmanship band, if a + // SalvageCombine config is loaded and enabled). Bags at 100/100 are + // skipped (already full); singleton groups are skipped (nothing to merge). + // forceRefresh: true — startup combines work because the engine's replay + // freshly populates the cache, but during a session the snapshot drifts + // and forceRefresh:false returns yesterday's inventory. Always walk live. + var byKey = new Dictionary>(StringComparer.Ordinal); + var inv = _cache.GetDirectInventory(forceRefresh: true); + int scannedItems = inv.Count; + int salvageBagCount = 0; + int underFullCount = 0; + int rejMaterialUnknown = 0; + int rejWmUnread = 0; + foreach (WorldObject item in inv) + { + if (!IsSalvageBag(item.Name)) continue; + salvageBagCount++; + uint id = unchecked((uint)item.Id); + if (!IsBagUnderFull(id, item.Name)) continue; + underFullCount++; + + if (!TryGetBagCombineKey(id, item.Name, cfg, useBands, out string key, out string diag)) + { + rejMaterialUnknown++; + continue; + } + if (diag == "workmanship-unread") rejWmUnread++; + + if (!byKey.TryGetValue(key, out var list)) { list = new List(); byKey[key] = list; } + list.Add(id); + } + + _combineGroups = new List>(); + int eligibleBags = 0; + foreach (var kv in byKey) + { + eligibleBags += kv.Value.Count; + if (kv.Value.Count >= 2) + _combineGroups.Add(kv.Value); + } + + if (_combineGroups.Count == 0) + { + _combineGroups = null; + Log($"[Salvage] Combine sweep: scanned {scannedItems} inv items, {salvageBagCount} salvage bag(s), {underFullCount} under-full, {eligibleBags} mat-eligible, rej(mat?={rejMaterialUnknown},wm?={rejWmUnread}), 0 mergeable groups."); + return; + } + Log($"[Salvage] Combine sweep: scanned {scannedItems} inv items, {salvageBagCount} salvage bag(s), {underFullCount} under-full, rej(mat?={rejMaterialUnknown},wm?={rejWmUnread}) → {_combineGroups.Count} mergeable group(s)."); + + _combineGroupIdx = 0; + _combineAddIdx = 0; + _combinePhase = CombinePhase.None; + _combinePhaseReadyAt = now; + _phase = Phase.CombiningSalvage; + } + + private void TickCombiningSalvage(long now) + { + if (_combineGroups == null) { _phase = Phase.Idle; return; } + if (_combineGroupIdx >= _combineGroups.Count) + { + _combineGroups = null; + _combinePhase = CombinePhase.None; + _phase = Phase.Idle; + return; + } + + if (now < _combinePhaseReadyAt) return; + + var group = _combineGroups[_combineGroupIdx]; + switch (_combinePhase) + { + case CombinePhase.None: + { + uint ust = FindUst(); + if (ust == 0) + { + Log("[Salvage] Combine: no UST available — aborting combine cycle."); + NoteError("combine: no UST in inventory"); + _combineGroups = null; + _phase = Phase.Idle; + return; + } + if (!_host.UseObject(ust)) + { + _combineOpenAttempts++; + if (_combineOpenAttempts < MaxCombineOpenAttempts) + { + Log($"[Salvage] Combine: UseObject(UST) failed — retrying this group in {RetryBackoffMs}ms (attempt {_combineOpenAttempts}/{MaxCombineOpenAttempts})."); + _combinePhaseReadyAt = now + RetryBackoffMs; + return; + } + Log($"[Salvage] Combine: UseObject(UST) failed {_combineOpenAttempts}x — skipping this group."); + NoteError($"combine: UseObject(UST) failed {_combineOpenAttempts}x — group skipped"); + _combineOpenAttempts = 0; + _combineGroupIdx++; + _combineAddIdx = 0; + _combinePhaseReadyAt = now + RetryBackoffMs; + return; + } + _combineOpenAttempts = 0; + int openDelay = _panelEverOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; + _combinePhaseReadyAt = now + openDelay; + _combinePhase = CombinePhase.OpeningPanel; + break; + } + case CombinePhase.OpeningPanel: + { + _panelEverOpened = true; + _combineAddIdx = 0; + _combinePhase = CombinePhase.AddingBags; + _combinePhaseReadyAt = now; + break; + } + case CombinePhase.AddingBags: + { + if (_combineAddIdx < group.Count) + { + uint bagId = group[_combineAddIdx]; + if (_host.SalvagePanelAddItem(bagId)) + Log($"[Salvage] Combine: added bag 0x{bagId:X8} to panel ({_combineAddIdx + 1}/{group.Count})."); + else + Log($"[Salvage] Combine: SalvagePanelAddItem failed for 0x{bagId:X8}."); + _combineAddIdx++; + _combinePhaseReadyAt = now + _settings.SalvageAddDelayFastMs; + } + else + { + _combinePhase = CombinePhase.Salvaging; + _combinePhaseReadyAt = now; + } + break; + } + case CombinePhase.Salvaging: + { + // Snapshot the bag IDs we expect the server to merge so the + // verification pass in WaitingForResult can count survivors. + _combineGroupSnapshot = new List(group); + + if (!_host.SalvagePanelExecute()) + Log($"[Salvage] Combine group {_combineGroupIdx + 1}/{_combineGroups!.Count}: SalvagePanelExecute returned false (group of {group.Count} bag(s)) — verifying server-side outcome anyway."); + + _combinePhase = CombinePhase.WaitingForResult; + _combinePhaseReadyAt = now + _settings.SalvageSalvageDelayMs + _settings.SalvageResultDelayFastMs; + _waitingResultDeadline = _combinePhaseReadyAt + ResultMaxWaitMs; + break; + } + case CombinePhase.WaitingForResult: + { + // Poll: if any snapshot bag is still in inventory and we're + // under the deadline, wait. Server delete events for merged + // bags arrive after the result delay on busy servers. + if (now < _waitingResultDeadline + && _combineGroupSnapshot != null + && AnySnapshotBagStillInInventory(_combineGroupSnapshot)) + { + break; + } + VerifyCombineGroupResult(); + _combineGroupIdx++; + _combineAddIdx = 0; + _combinePhase = CombinePhase.None; + _combinePhaseReadyAt = now; + break; + } + } + } + + /// + /// Compares the surviving bag ids against the snapshot taken before + /// SalvagePanelExecute. Uses GetDirectInventory(forceRefresh: true) for + /// ground truth — _cache[id] is unreliable for salvage-consumed bags + /// because OnDeleteObject doesn't always fire on the merge path. + /// + /// Outcomes (M = input bags, S = survivors): + /// S == M → no merge happened (server ignored Execute / panel was empty / etc.) + /// S == 1 → clean merge into a single bag + /// 1 < S < M → partial merge (overflow / mixed-band / next sweep can finish it) + /// + private void VerifyCombineGroupResult() + { + var snapshot = _combineGroupSnapshot; + _combineGroupSnapshot = null; + if (snapshot == null || snapshot.Count == 0 || _cache == null) return; + + var liveIds = SnapshotDirectInventoryIds(); + int survivors = 0; + foreach (uint id in snapshot) + { + if (liveIds.Contains(id)) + survivors++; + } + + int merged = snapshot.Count - survivors; + int groupNum = _combineGroupIdx + 1; + int totalGroups = _combineGroups?.Count ?? 0; + + if (survivors == snapshot.Count) + { + _combineGroupsFailed++; + string ids = string.Join(", ", snapshot.ConvertAll(id => $"0x{id:X8}")); + Log($"[Salvage] Combine group {groupNum}/{totalGroups}: NO MERGE — all {snapshot.Count} bag(s) still in inventory. Surviving ids: {ids}. Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); + return; + } + + _combineGroupsSucceeded++; + _bagsMergedThisSession += merged; + + if (survivors <= 1) + { + Log($"[Salvage] Combine group {groupNum}/{totalGroups}: merged {snapshot.Count} bag(s) → {survivors} survivor (+{merged} consumed). Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); + } + else + { + Log($"[Salvage] Combine group {groupNum}/{totalGroups}: PARTIAL merge — {snapshot.Count} bag(s) → {survivors} survivors (+{merged} consumed). Remaining bag(s) will be picked up by next sweep. Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); + } + } + + /// + /// True when a salvage bag is under-full (structure < max) and thus worth + /// merging. The #92/#91 property reads are authoritative but fail-close off + /// the AC main thread (P0-2 qualities gate) — which is ALWAYS the case from + /// the plugin pump. The old code then "assumed under-full", so on this ACE + /// server (bags are "Salvage (N)" where N is the FILL level — + /// Player_Crafting.cs ~281, see TryGetSalvageBagMaterial) every FULL + /// "Salvage (100)" looked mergeable forever → a combine sweep every 30s + /// that re-merged already-full bags and interrupted vendors/gameplay. + /// Fix: when the properties can't be read, trust the bag NAME's trailing + /// "(N)" fill level (covers both "Iron Salvage (91)" and ACE "Salvage + /// (100)"); only if there's no parseable fill do we treat the bag as full + /// (skip) so an unreadable bag can never drive an endless sweep. + /// + private bool IsBagUnderFull(uint bagId, string? name) + { + if (_host.TryGetObjectIntProperty(bagId, StypeStructure, out int cur) + && _host.TryGetObjectIntProperty(bagId, StypeMaxStructure, out int max)) + return max <= 0 || cur < max; + + if (TryParseTrailingNumber(name, out int fill)) + return fill < 100; + + Log($"[Salvage] IsBagUnderFull: Structure unreadable AND name '{name}' has no numeric fill — treating 0x{bagId:X8} as full (skip) so it can't drive an endless sweep."); + return false; + } + + /// + /// Resolves a salvage bag's material id from MaterialType(#131) — the only + /// reliable source. The previous "parse trailing (NN) as material" fallback + /// was WRONG on ACE: ACE names bags "Salvage ({Structure})" + /// (Player_Crafting.cs ~line 281) — the number is the bag's FILL LEVEL, not + /// its material — so the fallback scattered same-material bags across + /// different bogus keys and they never combined. When the property can't be + /// read we skip the bag for this sweep; the next sweep picks it up once the + /// client has the bag's material cached. + /// + private bool TryGetSalvageBagMaterial(uint bagId, string? name, out int material) + { + material = 0; + if (_host.TryGetObjectIntProperty(bagId, StypeMaterialType, out int mat) && mat > 0) + { + material = mat; + return true; + } + return false; + } + + /// + /// Resolves the combine grouping key for a salvage BAG. + /// + /// ACE's server merges bags by MaterialType + under-full only + /// (Player_Crafting.GetSalvageBag) — workmanship is never a server-side + /// merge criterion. Banding is a client-side user preference to keep + /// different-workmanship salvage in separate bags. A bag's int + /// ItemWorkmanship(#105) is a cumulative SUM (TryAddSalvage), so the band + /// must be derived from the AVERAGE: #105 / NumItemsInMaterial(#170). + /// + /// When workmanship can't be read we fall back to a "{mat}|?" key instead + /// of excluding the bag — excluding every bag is exactly the original + /// "never combines" bug. Same-material unknown-band bags then still merge + /// with each other, which is server-safe (the server ignores workmanship). + /// Returns false only when the MATERIAL itself is unknown (can't group at + /// all); carries a short reason for logging. + /// + private bool TryGetBagCombineKey(uint bagId, string? name, + RynthCore.Loot.SalvageCombineSettings? cfg, bool useBands, + out string key, out string diag) + { + key = string.Empty; + diag = string.Empty; + + if (!TryGetSalvageBagMaterial(bagId, name, out int mat)) + { + diag = "material-unknown"; + return false; + } + + if (!useBands) + { + key = mat.ToString(); + return true; + } + + if (TryGetBagAvgWorkmanship(bagId, out int avgWm)) + { + string? band = cfg!.GetBandKey(mat, avgWm); + if (band != null) + { + key = $"{mat}|{band}"; + return true; + } + // avg falls in a gap between configured bands — keep it separate by + // exact average so identical-average bags still merge together. + diag = $"avgWm {avgWm} outside bands"; + key = $"{mat}|wm{avgWm}"; + return true; + } + + diag = "workmanship-unread"; + key = $"{mat}|?"; + return true; + } + + /// + /// Average workmanship of a salvage bag = ItemWorkmanship(#105, a cumulative + /// sum) / NumItemsInMaterial(#170). Integer floor — band ranges are integer, + /// so flooring is exact for grouping (bags with the same average land in the + /// same band). Returns false if either property is unreadable or the bag is + /// empty/fresh (#170 == 0), in which case the caller treats the band as + /// unknown rather than excluding the bag. + /// + private bool TryGetBagAvgWorkmanship(uint bagId, out int avgWm) + { + avgWm = 0; + if (!_host.TryGetObjectIntProperty(bagId, StypeItemWorkmanship, out int sum) || sum <= 0) + return false; + if (!_host.TryGetObjectIntProperty(bagId, StypeNumItemsInMaterial, out int n) || n <= 0) + return false; + avgWm = sum / n; + if (avgWm < 1) avgWm = 1; + return true; + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + /// + /// True if appears in a fresh walk of the player's + /// inventory containers. Ground truth for "did the server actually destroy + /// this item" — the cache's _byId can hold stale entries for salvage- + /// consumed items because OnDeleteObject doesn't fire on every merge path. + /// + private bool IsItemInDirectInventory(uint id) + { + if (_cache == null) return false; + var inv = _cache.GetDirectInventory(forceRefresh: true); + foreach (var item in inv) + { + if (unchecked((uint)item.Id) == id) return true; + } + return false; + } + + /// + /// Snapshots the ids currently in the player's direct inventory as a + /// HashSet for O(1) survivor counting. + /// + private HashSet SnapshotDirectInventoryIds() + { + var set = new HashSet(); + if (_cache == null) return set; + foreach (var item in _cache.GetDirectInventory(forceRefresh: true)) + set.Add(unchecked((uint)item.Id)); + return set; + } + + /// + /// True if any of 's ids are still in the + /// player's direct inventory. Used by combine WaitingForResult polling. + /// + private bool AnySnapshotBagStillInInventory(List snapshot) + { + var liveIds = SnapshotDirectInventoryIds(); + foreach (uint id in snapshot) + { + if (liveIds.Contains(id)) return true; + } + return false; + } + + // Canonical UST weenie class id. Same for every UST instance on every + // character and every server (the WCID is part of the weenie definition, + // not the per-instance GUID). Most reliable signal we have. + private const uint UstWcid = 20646; + + private uint FindUst() + { + if (_cache == null) + return 0; + + // Pass 1 — WCID match. Universal: every UST shares weenie class 20646 + // so this works on every server / variant / character regardless of + // name, ItemType classification, or cache state. + if (_host.HasGetObjectWcid) + { + foreach (var item in _cache.AllKnownObjects()) + { + if (!IsCarriedByPlayer(item)) continue; + if (!_host.TryGetObjectWcid(unchecked((uint)item.Id), out uint wcid)) continue; + if (wcid == UstWcid) return unchecked((uint)item.Id); + } + } + + // Pass 2 — type-based via the cached ObjectClass. Same intent as the + // WCID pass but reads the cached classification (ItemType TinkeringTool + // bit). Catches USTs whose WCID lookup hasn't been bound on the host. + foreach (var item in _cache.AllKnownObjects()) + { + if (item.ObjectClass != AcObjectClass.Ust) continue; + if (!IsCarriedByPlayer(item)) continue; + return unchecked((uint)item.Id); + } + + // Pass 3 — name-based fallback. Some items get cached before their + // ItemType is read; the cache stays AcObjectClass.Unknown until then. + // The name path catches those. + foreach (WorldObject item in _cache.GetDirectInventory(forceRefresh: false)) + { + if (IsUst(item.Name)) return unchecked((uint)item.Id); + } + + // Pass 4 — same name fallback after a forced refresh. + var fresh = _cache.GetDirectInventory(forceRefresh: true); + foreach (WorldObject item in fresh) + { + if (IsUst(item.Name)) return unchecked((uint)item.Id); + } + + // Pass 5 — WCID retry over the freshly-walked direct inventory in case + // a UST only just appeared in the cache via the forced refresh. + if (_host.HasGetObjectWcid) + { + foreach (var item in fresh) + { + if (!_host.TryGetObjectWcid(unchecked((uint)item.Id), out uint wcid)) continue; + if (wcid == UstWcid) return unchecked((uint)item.Id); + } + } + + // Diagnostic on miss — sample what's in inventory so we can see + // whether the UST really isn't there or just has an unexpected name. + int shown = 0; + var names = new List(); + foreach (WorldObject item in fresh) + { + if (string.IsNullOrEmpty(item.Name)) continue; + names.Add(item.Name); + if (++shown >= 40) break; + } + Log($"[Salvage] UST search miss. {fresh.Count} item(s) scanned. Sample: {string.Join(", ", names)}"); + + return 0; + } + + /// + /// True when the item lives in the player's pack (or one of the player's + /// side-packs). Skips USTs lying in nearby corpses or another player's pack. + /// + private bool IsCarriedByPlayer(WorldObject item) + { + if (_cache == null) return false; + uint playerId = _host.GetPlayerId(); + // Fail closed when the player id isn't readable yet — matches every other + // playerId==0 guard in the plugin (InventoryManager:94, WorldObjectCache:977, + // FindPackFor). Returning true here counted every scanned object as ours. + if (playerId == 0) return false; + + int pid = unchecked((int)playerId); + if (item.Wielder != 0 && item.Wielder != pid) return false; + if (item.Container == pid) return true; + // Container==0 means "not in any pack" — that's a wielded item (ours only if + // we're the wielder) or an item lying on the ground. It used to return true + // for both, so ground USTs read as carried. 2026-06-03 audit P2. + if (item.Container == 0) return item.Wielder == pid; + + var owner = _cache[item.Container]; + if (owner == null) return false; + if (owner.ObjectClass == AcObjectClass.Corpse) return false; + return owner.Wielder == pid || owner.Container == pid; + } + + private static bool IsUst(string? name) + { + if (string.IsNullOrEmpty(name)) + return false; + // UST names carry "Ust" as its own word (e.g. "Salvaging Ust", "Aged Legendary + // Salvaging Ust", "Sturdy Iron Salvaging Ust"). A bare Contains also matched + // "Just"/"Robust"/"Lustrous" (2026-06-03 audit P2); a word match keeps working + // if a name ever carries a suffix, which EndsWith would not. + // Exclude actual salvage bags — the "Salvage (Material)" format, via IsSalvageBag. + return HasWordUst(name) && !IsSalvageBag(name); + } + + /// True when "Ust" appears as a whole word (letter/digit boundaries). + private static bool HasWordUst(string name) + { + for (int i = 0; i + 3 <= name.Length; i++) + { + if (!(name[i] is 'U' or 'u') || !(name[i + 1] is 'S' or 's') || !(name[i + 2] is 'T' or 't')) + continue; + if (i > 0 && char.IsLetterOrDigit(name[i - 1])) continue; + if (i + 3 < name.Length && char.IsLetterOrDigit(name[i + 3])) continue; + return true; + } + return false; + } + + /// + /// Parses a trailing "(NN)" group from a salvage-bag name (e.g. + /// "Gold Salvage (91)" → 91). Returns false if the name has no trailing + /// integer in parentheses. + /// + private static bool TryParseTrailingNumber(string? name, out int value) + { + value = 0; + if (string.IsNullOrEmpty(name)) return false; + int close = name.LastIndexOf(')'); + if (close <= 0 || close != name.Length - 1) return false; + int open = name.LastIndexOf('(', close - 1); + if (open < 0) return false; + string inside = name.Substring(open + 1, close - open - 1); + return int.TryParse(inside, out value); + } + + private static bool IsSalvageBag(string? name) + { + if (string.IsNullOrEmpty(name)) + return false; + // Two known formats observed across servers/emulators: + // "Salvage (Gold)" — retail-style, material in parens + // "Gold Salvage (91)" — emulator style, fullness in parens + // Both contain "Salvage (" as a substring; "Salvaging Ust" doesn't. + return name.Contains("Salvage (", StringComparison.OrdinalIgnoreCase); + } + + private void Log(string message) => _host.Log(message); + + private void NoteError(string what) + { + _lastError = what; + _lastErrorAt = NowMs; + } + + /// + /// One-shot view of the salvage FSM. Salvage had no snapshot (Combat/Buff/Meta + /// did), so a wedged panel cycle meant reading the log backwards to work out + /// which phase it died in. Read-only; safe from the UI or a chat command. + /// + public SalvageStateSnapshot GetStateSnapshot() + { + long now = NowMs; + return new SalvageStateSnapshot + { + HasPanelApi = _host.HasSalvagePanel && _host.HasUseObject, + EnableCombine = _settings.EnableCombineSalvage, + Phase = _phase.ToString(), + PhaseReadyInMs = Math.Max(0, _phaseReadyAt - now), + QueueCount = _queue.Count, + CurrentItemId = _currentItemId, + CurrentUstId = _currentUstId, + PanelEverOpened = _panelEverOpened, + PendingCombineScan = _pendingCombineScan, + RetryTrackedItems = _itemRetryCount.Count, + RetryBackoffInMs = Math.Max(0, _idleRetryReadyAt - now), + CombinePhase = _combinePhase.ToString(), + CombineGroupIdx = _combineGroupIdx, + CombineGroupCount = _combineGroups?.Count ?? 0, + CombineAddIdx = _combineAddIdx, + CombineOpenAttempts = _combineOpenAttempts, + MsSinceCombineSweep = _lastCombineSweepAt == 0 ? -1 : now - _lastCombineSweepAt, + GroupsSucceeded = _combineGroupsSucceeded, + GroupsFailed = _combineGroupsFailed, + BagsMerged = _bagsMergedThisSession, + LastError = _lastError, + MsSinceLastError = _lastErrorAt == 0 ? -1 : now - _lastErrorAt, + }; + } + + public struct SalvageStateSnapshot + { + public bool HasPanelApi; + public bool EnableCombine; + public string Phase; + public long PhaseReadyInMs; + public int QueueCount; + public uint CurrentItemId; + public uint CurrentUstId; + public bool PanelEverOpened; + public bool PendingCombineScan; + public int RetryTrackedItems; + public long RetryBackoffInMs; + public string CombinePhase; + public int CombineGroupIdx; + public int CombineGroupCount; + public int CombineAddIdx; + public int CombineOpenAttempts; + public long MsSinceCombineSweep; + public int GroupsSucceeded; + public int GroupsFailed; + public int BagsMerged; + public string LastError; + public long MsSinceLastError; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs new file mode 100644 index 0000000..952268f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -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; + +/// +/// 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). +/// +public sealed class VTankLootContext +{ + public RynthCoreHost Host { get; } + public uint PlayerId { get; } + + private readonly Dictionary _skillCache = new(); + private readonly Dictionary _spellNameCache = new(); + private readonly Dictionary _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 _paletteCache = new(); + + public (uint[] SubIds, uint[] Offsets) GetItemPalettes(uint itemId) + { + if (_paletteCache.TryGetValue(itemId, out var cached)) return cached; + var empty = (Array.Empty(), Array.Empty()); + 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(); + 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; } +} + +/// +/// 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. +/// +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 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 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 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 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 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 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 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 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 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 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 d, int idx) + => int.Parse(d[idx], NumberStyles.Integer, CultureInfo.InvariantCulture); + + private static double ReadDouble(IList 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 d) => (ReadInt(d, 0), ReadInt(d, 1)); + private static (double Val, int Key) Double(IList 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 d) => (ReadDouble(d, 0), ReadInt(d, 1)); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs new file mode 100644 index 0000000..66096c0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -0,0 +1,755 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Mag-Tools /mt command compatibility — maps /mt commands to /ra equivalents. +/// Partial class of RynthAiPlugin. +/// +public sealed partial class RynthAiPlugin +{ + private Dictionary? _spellNameToId; + + /// + /// Handle a /mt command. Returns true if recognized and handled. + /// Called from OnChatBarEnter (manual typing) and MetaManager (ChatCommand actions). + /// + 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