From c6e8bb8dbfc78cc268366effba0e1fa7cee48e3e Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Mon, 23 Nov 2026 00:08:31 -0500 Subject: [PATCH] feat: SK backlog from test through 2026.11.22.48 (Trade Shop + inventory/loot/chat/nav) Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop Storefront, loot checklist editor, chat routing, window placements, and related engine work. See Changelog/2026-11-22-sk-backlog-test-merge.md. --- .github/workflows/release.yml | 7 +- .gitignore | 6 + AGENTS.md | 133 ++ BUILD.md | 4 + Build-Release-All.ps1 | 73 + CLAUDE.md | 133 ++ ...-04-22-inno-installer-prereq-dotnet-x64.md | 15 + ...sharedhost-and-bundled-runtime-fallback.md | 18 + ...04-22-installer-previous-release-folder.md | 12 + ...-04-22-launcher-injector-self-contained.md | 17 + ...4-22-minhook-preload-before-multiclient.md | 12 + ...-04-22-net-prereq-launcher-matches-inno.md | 16 + ...-22-plugin-extra-path-dedupe-hot-reload.md | 16 + Changelog/2026-04-22-release-0.4.1.md | 37 + Changelog/2026-04-22-release-0.4.3-bundle.md | 6 + Changelog/2026-04-22-release-0.4.7-bundle.md | 14 + Changelog/2026-04-22-release-0.4.8.md | 28 + Changelog/2026-04-22-release-0.4.9.md | 27 + .../2026-04-22-rynth-bundle-installer.md | 27 + .../2026-04-22-tmds-dbus-protocol-security.md | 12 + ...3-installer-dotnet-prereq-advisory-only.md | 13 + .../2026-04-23-launcher-host-diagnostics.md | 18 + ...ase-0.4.10-bundle-ub-rythai-ilt-banking.md | 19 + Changelog/2026-04-23-release-0.4.10.md | 20 + ...release-0.4.11-runtimeconfig-rename-fix.md | 32 + Changelog/2026-04-23-release-0.4.2.md | 41 + Changelog/2026-04-23-release-0.4.7-bundle.md | 7 + ...lease-0.4.8-bundle-installer-streamline.md | 8 + ...-04-23-release-0.4.9-runtime-fdd-bundle.md | 9 + Changelog/2026-04-24-release-0.4.4-bundle.md | 6 + Changelog/2026-04-25-desktop-rolling-logs.md | 8 + Changelog/2026-04-25-release-0.4.5-bundle.md | 7 + Changelog/2026-04-26-release-0.4.6-bundle.md | 7 + Changelog/2026-10-04-aelrynth-sync.md | 12 + Changelog/2026-10-04-aelrynth-urls.md | 9 + ...026-10-04-char-and-hub-launcher-buttons.md | 26 + ...reate-seeds-and-fatal-only-crash-logger.md | 70 + ...026-10-04-dashboard-map-and-lua-buttons.md | 34 + Changelog/2026-10-04-floating-huds.md | 93 ++ .../2026-10-04-full-installer-2026.10.4.2.md | 68 + ...lt-hub-button-imgui-on-top-live-logging.md | 60 + Changelog/2026-10-04-ilt-hub-pet-roster.md | 65 + Changelog/2026-10-04-installer-2026.10.4.1.md | 42 + ...26-10-04-installer-2026.10.4.10-release.md | 36 + ...26-10-04-installer-2026.10.4.11-release.md | 27 + ...26-10-04-installer-2026.10.4.12-release.md | 18 + ...26-10-04-installer-2026.10.4.13-release.md | 23 + ...26-10-04-installer-2026.10.4.14-release.md | 20 + ...26-10-04-installer-2026.10.4.15-release.md | 23 + ...26-10-04-installer-2026.10.4.16-release.md | 22 + ...26-10-04-installer-2026.10.4.17-release.md | 23 + ...26-10-04-installer-2026.10.4.18-release.md | 24 + ...26-10-04-installer-2026.10.4.19-release.md | 27 + ...26-10-04-installer-2026.10.4.20-release.md | 24 + ...taller-2026.10.4.3-experimental-plugins.md | 40 + ...4-installer-2026.10.4.4-dotnet10-prereq.md | 50 + ...nstaller-2026.10.4.5-suite-dir-per-mode.md | 31 + ...staller-2026.10.4.6-tool-launch-buttons.md | 16 + ...nstaller-2026.10.4.7-deployment-package.md | 45 + ...026-10-04-installer-2026.10.4.8-release.md | 28 + ...026-10-04-installer-2026.10.4.9-release.md | 24 + ...26-10-04-item-info-click-and-pet-layout.md | 70 + Changelog/2026-10-04-items-panel-shields.md | 39 + ...6-10-04-loot-name-rules-and-ground-loot.md | 66 + ...2026-10-04-merge-result-cdecl-crash-fix.md | 35 + .../2026-10-04-missile-ammo-detection.md | 56 + ...26-10-04-nav-editor-overlay-breadcrumbs.md | 98 ++ Changelog/2026-10-04-nav-panel-scroll-fix.md | 27 + ...6-10-04-panel-window-owner-thread-fixes.md | 42 + Changelog/2026-10-04-pet-refill-loop-fix.md | 52 + .../2026-10-04-pet-scan-type-detection.md | 44 + .../2026-10-04-plugin-overlay-windows.md | 31 + ...nder-snapshot-fix-and-imgui-diagnostics.md | 34 + ...0-04-pwd-int-snapshot-and-merge-results.md | 54 + Changelog/2026-10-04-sk-local-unified.md | 54 + Changelog/2026-10-04-tmds-dbus-advisory.md | 26 + .../2026-10-05-aelrynth-2026.10.5.1-merge.md | 131 ++ ...ar-panel-rework-progression-pets-quests.md | 73 + Changelog/2026-10-05-charms-tracking-tab.md | 58 + Changelog/2026-10-05-chat-standard-filters.md | 70 + Changelog/2026-10-05-chat-translation.md | 139 ++ .../2026-10-05-floating-window-placement.md | 63 + .../2026-10-05-guardian-and-remote-slots.md | 58 + ...6-10-05-guardian-vendor-and-item-lookup.md | 38 + ...-10-05-ilt-hub-context-char-hub-logging.md | 59 + .../2026-10-05-imgui-over-avalonia-port.md | 41 + ...26-10-05-installer-2026.10.4.21-release.md | 46 + ...26-10-05-installer-2026.10.4.22-release.md | 35 + ...6-10-05-inventory-add-to-item-count-hud.md | 22 + .../2026-10-05-mini-remote-is-ilt-hub.md | 63 + ...026-10-05-mini-remote-target-and-summon.md | 44 + Changelog/2026-10-05-native-drag-real-item.md | 49 + ...5-nav-breadcrumbs-route-overlay-toggles.md | 36 + Changelog/2026-10-05-release-2026.10.5.10.md | 25 + Changelog/2026-10-05-release-2026.10.5.11.md | 30 + Changelog/2026-10-05-release-2026.10.5.2.md | 33 + Changelog/2026-10-05-release-2026.10.5.3.md | 30 + Changelog/2026-10-05-release-2026.10.5.4.md | 29 + Changelog/2026-10-05-release-2026.10.5.5.md | 39 + Changelog/2026-10-05-release-2026.10.5.6.md | 29 + Changelog/2026-10-05-release-2026.10.5.7.md | 29 + Changelog/2026-10-05-release-2026.10.5.8.md | 35 + Changelog/2026-10-05-release-2026.10.5.9.md | 21 + .../2026-10-05-rynthai-cimgui-binding.md | 52 + ...-10-05-rynthai-launcher-remote-commands.md | 44 + ...se-2026.10.5.14-heartbeat-always-logged.md | 45 + ...2026-10-06-upstream-snapshot-comparison.md | 117 ++ .../2026-10-07-merge-main-into-QOL-items.md | 66 + ...ease-2026.10.5.15-loot-add-t11-checkbox.md | 32 + ...7-release-2026.10.5.16-main-integration.md | 51 + ...ease-2026.10.5.17-progression-ub-parity.md | 57 + ...-release-2026.10.5.18-aug-cost-settings.md | 34 + ...26-10-08-installer-2026.10.5.21-release.md | 43 + ...-08-release-2026.10.5.20-t11-item-state.md | 28 + ...release-2026.10.5.21-mini-remote-drawer.md | 56 + ...10-09-release-2026.10.5.22-buffs-picker.md | 37 + ...ookresolver-ui-1.0.1-tmds-dbus-security.md | 24 + ...26-10-10-installer-2026.10.5.24-release.md | 44 + ...026.10.5.23-large-address-alignment-fix.md | 64 + .../2026-10-11-build-comp-10-11-merge.md | 59 + Changelog/2026-10-11-chat-discord-relay.md | 83 ++ .../2026-10-11-gametick-chatclient-guard.md | 10 + ...26-10-11-installer-2026.10.5.25-release.md | 38 + ...26-10-11-installer-2026.10.5.26-release.md | 50 + .../2026-10-11-installer-2026.10.5.37.md | 28 + .../2026-10-11-installer-2026.10.5.38.md | 30 + ...10-11-inventory-attribute-filter-charms.md | 7 + Changelog/2026-10-11-items-remove-missing.md | 7 + ...026-10-11-mini-remote-ilt-tabs-guardian.md | 6 + Changelog/2026-10-11-mini-remote-merge.md | 6 + ...2026-10-11-nav-closest-waypoint-setting.md | 7 + Changelog/2026-10-11-popout-embed-crash.md | 7 + .../2026-10-11-recall-on-death-setting.md | 5 + Changelog/2026-10-11-tracker-lum5m-passup.md | 7 + Changelog/2026-10-11-universal-quests-pets.md | 7 + ...0-12-confirmation-answers-crafting-menu.md | 28 + ...ironment-throttle-attack-power-settings.md | 39 + .../2026-10-12-hot-release-2026.10.5.39.md | 50 + .../2026-10-12-hot-release-2026.10.5.40.md | 33 + .../2026-10-12-hot-release-2026.10.5.41.md | 31 + .../2026-10-12-hot-release-2026.10.5.42.md | 36 + .../2026-10-12-hot-release-2026.10.5.43.md | 46 + .../2026-10-12-hot-release-2026.10.5.44.md | 39 + .../2026-10-12-items-damage-type-colors.md | 20 + ...2026-10-12-progression-attributes-merge.md | 12 + ...hip-menu-ilt-settings-push-2026.10.5.47.md | 47 + .../2026-10-13-full-install-2026.10.5.46.md | 45 + .../2026-10-13-full-install-2026.10.5.47.md | 61 + ...026-10-13-ilt-fellowship-installer-text.md | 11 + ...-10-13-ilt-verdict-logging-2026.10.5.52.md | 36 + ...-13-launcher-known-servers-2026.10.5.48.md | 37 + ...-2026.10.13.3-api-renumber-2026.10.5.55.md | 56 + ...-13-merge-dynamic-sections-2026.10.5.50.md | 65 + ...ni-remote-rail-hidden-tabs-2026.10.5.51.md | 47 + ...10-13-mini-remote-sections-2026.10.5.46.md | 100 ++ ...e-quests-menu-hub-launcher-2026.10.5.49.md | 41 + ...026-10-13-port-build-comp-onto-upstream.md | 34 + ...0-13-security-review-fixes-2026.10.5.45.md | 83 ++ ...ist-and-forced-server-load-2026.10.5.56.md | 49 + .../2026-10-13-server-plugins-2026.10.5.48.md | 74 + ...026-10-13-server-selection-2026.10.5.53.md | 76 + ...3-session-stats-moved-tabs-2026.10.5.54.md | 73 + ...-hook-scoped-to-ac-imports-2026.10.5.61.md | 61 + ...-14-first-login-new-server-2026.10.5.58.md | 109 ++ ...10-14-gesture-safe-attacks-2026.10.5.57.md | 49 + ...failed-prefs-swap-recovery-2026.10.5.60.md | 61 + ...t-timer-optimized-defaults-2026.10.5.59.md | 48 + ...-borderless-restore-chrome-2026.10.5.67.md | 29 + ...e-private-createfilew-slot-2026.10.5.64.md | 65 + ...borderless-remember-layout-2026.10.5.65.md | 41 + ...6-10-15-loot-picker-filter-2026.10.5.66.md | 19 + ...-breadcrumbs-route-overlay-2026.10.5.62.md | 45 + ...ulted-dungeons-options-nav-2026.10.5.68.md | 17 + ...16-bar-hide-itemcount-ginv-2026.10.16.6.md | 13 + ...t-combat-standard-filters-2026.10.16.10.md | 28 + ...-filters-hide-retail-chat-2026.10.16.23.md | 40 + ...6-chat-filters-ubit-parity-2026.10.16.2.md | 31 + ...k-detect-software-overlay-2026.10.16.13.md | 16 + .../2026-10-16-engine-kite-pull-away-ui.md | 15 + ...ull-install-suite-plugins-2026.10.16.21.md | 27 + .../2026-10-16-hotbuild-local-2026.10.5.69.md | 12 + Changelog/2026-10-16-hotpush-2026.10.15.8.md | 11 + ...16-hotreload-no-erl-bypass-2026.10.16.5.md | 35 + ...ory-itemcount-ginv-buttons-2026.10.16.4.md | 24 + ...ventory-miniremote-off-bar-2026.10.16.8.md | 15 + ...-16-inventory-rsort-button-2026.10.16.7.md | 14 + ...-16-inworld-hotreload-hold-2026.10.16.3.md | 33 + .../2026-10-16-launcher-dxvk-toggle-0.1.8.md | 25 + ...-launcher-scroll-clip-server-list-0.1.9.md | 24 + ...16-miniremote-dock-undock-2026.10.16.11.md | 25 + ...miniremote-rail-off-orphan-2026.10.15.9.md | 18 + ...-10-16-oracle-skills-embed-2026.10.16.1.md | 31 + ...e-skills-embed-into-local-2026.10.16.14.md | 35 + ...6-plugin-chat-queue-depth-2026.10.16.20.md | 21 + ...-popout-keep-floating-pos-2026.10.16.12.md | 20 + ...10-16-port-sk-engine-work-2026.10.16.22.md | 25 + ...16-progress-enl-calculator-2026.10.16.9.md | 18 + ...runtime-borderless-display-2026.10.5.70.md | 26 + ...nav-vision-tracker-oracle-2026.10.16.16.md | 41 + ...6-test-build-full-install-2026.10.16.24.md | 18 + ...6-test-hotbuild-installer-2026.10.16.18.md | 21 + ...t-merge-aelrynth-hotbuild-2026.10.16.15.md | 27 + ...dater-local-ahead-of-feed-2026.10.16.19.md | 25 + ...17-borderless-fill-monitor-2026.10.17.4.md | 34 + ...at-coord-links-arrow-clear-2026.10.17.2.md | 31 + ...ngine-settings-multiclient-2026.10.17.3.md | 27 + ...phics-per-account-no-fight-2026.10.18.3.md | 55 + ...17-graphics-settings-panel-2026.10.18.1.md | 90 ++ ...uncher-prefs-swap-live-ini-2026.10.18.2.md | 35 + ...17-test-build-full-install-2026.10.17.6.md | 45 + ...7-test-build-full-install-2026.10.18.13.md | 44 + ...17-test-build-full-install-2026.10.18.2.md | 37 + ...17-test-build-full-install-2026.10.18.4.md | 32 + ...ow-not-saved-at-login-size-2026.10.17.8.md | 34 + ...ndow-placement-shared-file-2026.10.17.7.md | 43 + ...-reset-borderless-position-2026.10.17.5.md | 51 + ...026-10-18-chat-link-probe-2026.10.18.25.md | 36 + ...hics-low-memory-safeguard-2026.10.18.11.md | 20 + ...18-inventory-vault-button-2026.10.18.14.md | 17 + ...18-inventory-vault-modern-2026.10.18.15.md | 12 + ...t-add-attribute-checklist-2026.10.18.10.md | 14 + ...8-test-build-full-install-2026.10.18.24.md | 68 + ...system-text-in-system-tab-2026.10.18.30.md | 44 + ...ng-chat-queue-25000-lines-2026.10.18.29.md | 20 + ...tems-prismatic-damage-type-2026.10.19.3.md | 13 + ...merge-rynth-main-2026.10.19.1-into-test.md | 61 + ...l-needed-sigil-how-to-get-2026.10.18.31.md | 20 + ...plugin-imgui-context-crash-2026.10.20.4.md | 46 + ...t-filter-slow-rules-retry-2026.10.20.11.md | 30 + ...mand-replies-in-typed-tab-2026.10.20.14.md | 49 + ...-history-automated-budget-2026.10.20.18.md | 25 + ...oll-follow-and-keep-place-2026.10.20.18.md | 31 + ...aves-per-character-layout-2026.10.20.13.md | 88 ++ .../2026-10-24-inventory-filter-like-this.md | 48 + ...ory-add-to-damage-weapons-2026.10.20.19.md | 14 + ...ws-keep-their-spot-per-character-api-91.md | 23 + ...026-11-11-dungeon-map-visited-per-floor.md | 7 + ...2-progress-tab-ilt-sections-only-on-ilt.md | 6 + ...6-11-15-item-tool-give-amount-and-every.md | 14 + .../2026-11-22-inventory-add-to-trade-shop.md | 5 + ...6-11-22-inventory-trade-shop-storefront.md | 8 + ...11-22-settings-game-client-vtank-import.md | 12 + Changelog/2026-11-22-sk-backlog-test-merge.md | 16 + ...taller-full-rynthsuite-setup-2026-04-22.md | 19 + Plugins/RynthAi/Combat/BuffManager.cs | 580 ++++++++ Plugins/RynthAi/Combat/CombatActionHelper.cs | 356 +++++ Plugins/RynthAi/Combat/CombatManager.cs | 1302 +++++++++++++++++ Plugins/RynthAi/Combat/FellowshipTracker.cs | 361 +++++ .../RynthAi/Combat/MissileCraftingManager.cs | 521 +++++++ Plugins/RynthAi/Combat/SpellDatabase.cs | 104 ++ Plugins/RynthAi/Combat/SpellManager.cs | 215 +++ Plugins/RynthAi/Combat/Vtank spelldump.txt | Bin 0 -> 912312 bytes Plugins/RynthAi/DecalInspector.cs | 38 + .../RynthAi/Logic/BackgroundFpsUnlocker.cs | 81 + Plugins/RynthAi/Logic/CommandProcessor.cs | 812 ++++++++++ Plugins/RynthAi/Logic/NavigationManager.cs | 1154 +++++++++++++++ Plugins/RynthAi/Logic/RynthJumper.cs | 256 ++++ Plugins/RynthAi/Loot/LootManager.cs | 1150 +++++++++++++++ Plugins/RynthAi/Loot/VTankLootParser.cs | 285 ++++ Plugins/RynthAi/Lua/LuaBridge.cs | 115 ++ Plugins/RynthAi/Lua/LuaManager.cs | 154 ++ Plugins/RynthAi/Meta/MetaManager.cs | 684 +++++++++ Plugins/RynthAi/Meta/VTankMetaParser.cs | 172 +++ Plugins/RynthAi/Nav/MovementActionHelper.cs | 310 ++++ Plugins/RynthAi/Nav/NavigationManager.cs | 1139 ++++++++++++++ Plugins/RynthAi/Nav/Tier2Log.cs | 76 + Plugins/RynthAi/Nav/Tier2MovementHelper.cs | 942 ++++++++++++ Plugins/RynthAi/Nav/VTankNavParser.cs | 163 +++ Plugins/RynthAi/PluginCore.cs | 1115 ++++++++++++++ .../RynthAi/Raycasting/BlacklistManager.cs | 143 ++ Plugins/RynthAi/Raycasting/BoundingVolume.cs | 245 ++++ Plugins/RynthAi/Raycasting/DatDatabase.cs | 321 ++++ Plugins/RynthAi/Raycasting/DungeonLOS.cs | 658 +++++++++ Plugins/RynthAi/Raycasting/GeometryLoader.cs | 1112 ++++++++++++++ .../RynthAi/Raycasting/LandblockStructs.cs | 751 ++++++++++ Plugins/RynthAi/Raycasting/MainLogic.cs | 98 ++ Plugins/RynthAi/Raycasting/RaycastEngine.cs | 235 +++ Plugins/RynthAi/Raycasting/ScatterSystem.cs | 948 ++++++++++++ Plugins/RynthAi/Raycasting/TargetingFSM.cs | 364 +++++ Plugins/RynthAi/Raycasting/Vector3Helper.cs | 143 ++ Plugins/RynthAi/RynthAi.csproj | 174 +++ Plugins/RynthAi/UI/AdvancedSettingsUI.cs | 483 ++++++ Plugins/RynthAi/UI/LuaUI.cs | 157 ++ Plugins/RynthAi/UI/MetaUI.cs | 650 ++++++++ Plugins/RynthAi/UI/MonstersUI.cs | 282 ++++ Plugins/RynthAi/UI/RouteUI.cs | 337 +++++ Plugins/RynthAi/UI/RynthAiUI.Rendering.cs | 9 + Plugins/RynthAi/UI/RynthAiUI.cs | 997 +++++++++++++ Plugins/RynthAi/UI/UISettings.cs | 314 ++++ Plugins/RynthAi/app.config | 19 + Plugins/RynthAi/packages.config | 6 + Plugins/RynthAi/properties/AssemblyInfo.cs | 16 + .../Nav/VTankNavParser.cs | 150 ++ .../RynthCore.Plugin.RynthAi/PluginExports.cs | 95 ++ .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 429 ++++++ .../RynthCore.Plugin.RynthAi.csproj | 57 + docs/ACCLIENT_HOOK_INVENTORY.md | 91 ++ docs/DXVK_TEXTURE_SMOKE.md | 85 ++ docs/ub-hub-merge-playbook.md | 117 ++ find_bytes.cs | 20 + installer/Build-Installer.ps1 | 799 +++++++--- installer/Publish-Update.ps1 | 54 +- installer/RynthCore.iss | 568 ++++++- .../previous-release/last-built-version.txt | 1 + .../last-release-manifest.json | 124 ++ .../previous-release/previous-version.txt | 1 + last-built-version.txt | 1 + loot-port-plan.txt | 204 +++ native/Loader/Loader.c | 62 +- native/Loader/Loader.h | 2 +- scripts/Fetch-Dxvk.ps1 | 67 + scripts/Run-AllTests.ps1 | 52 + .../AccountProfileDialog.axaml.cs | 12 +- src/RynthCore.App.Avalonia/MainWindow.axaml | 13 + .../MainWindow.axaml.cs | 175 ++- .../RynthCore.App.Avalonia.csproj | 11 +- src/RynthCore.App.Avalonia/RynthUpdater.cs | 12 +- .../AcClientLaunchSettingsService.cs | 90 +- src/RynthCore.App/AppSettings.cs | 7 + src/RynthCore.App/DxvkPackageService.cs | 305 ++++ .../Compatibility/CharacterCaptureHooks.cs | 115 +- .../Compatibility/ChatCallbackHooks.cs | 29 +- .../Compatibility/ChatCommandDispatcher.cs | 31 + .../Compatibility/ChatCommandReplies.cs | 6 + .../Compatibility/ChatHooks.cs | 2 + .../Compatibility/ChatLinkProbe.cs | 177 +++ .../Compatibility/ClientHelperHooks.cs | 2 +- .../Compatibility/ClientObjectHooks.cs | 3 +- .../Compatibility/ConfirmationResponder.cs | 2 +- .../Compatibility/DatFileShareHooks.cs | 278 ++-- .../Compatibility/EngineStatusMetrics.cs | 75 +- .../Compatibility/HeartbeatLogger.cs | 2 + .../Compatibility/InventoryModel.cs | 90 ++ .../Compatibility/LazyImportSlotScanner.cs | 187 +++ .../Compatibility/LogoffOriginProbe.cs | 21 + .../Compatibility/RynthCoreChatCommands.cs | 111 +- .../Compatibility/ServerCommandFallback.cs | 53 + .../Compatibility/SessionRates.cs | 160 ++ .../Compatibility/SmartBoxHooks.cs | 2 +- src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs | 5 + src/RynthCore.Engine/D3D9/DxvkDetection.cs | 156 ++ src/RynthCore.Engine/D3D9/EndSceneHook.cs | 4 + src/RynthCore.Engine/EntryPoint.cs | 48 +- src/RynthCore.Engine/Graphics/AcGraphics.cs | 464 ++++++ .../Graphics/AcGraphicsPrefs.cs | 384 +++++ src/RynthCore.Engine/Hotkeys/HotkeyService.cs | 5 +- src/RynthCore.Engine/ImGui/DX9Backend.cs | 49 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 85 +- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 37 +- src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs | 10 +- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 4 +- .../ImGui/Panels/ChatFiltersFace.cs | 11 +- src/RynthCore.Engine/ImGui/Panels/ChatView.cs | 163 ++- .../ImGui/Panels/Classic/ClassicLootTab.cs | 16 +- .../ImGui/Panels/DamageFace.cs | 10 +- .../ImGui/Panels/DamageTypeColors.cs | 35 + .../ImGui/Panels/DashboardDrawers.cs | 2 +- .../ImGui/Panels/DungeonMapFace.cs | 10 +- .../ImGui/Panels/InventoryFace.AttrFilter.cs | 22 +- .../ImGui/Panels/InventoryFace.Classic.cs | 27 +- .../ImGui/Panels/InventoryFace.LikeFilter.cs | 228 +++ .../ImGui/Panels/InventoryFace.MultiSelect.cs | 25 + .../ImGui/Panels/InventoryFace.cs | 71 +- .../ImGui/Panels/ItemToolFace.cs | 50 +- .../ImGui/Panels/ItemsFace.cs | 24 +- .../ImGui/Panels/LootAddDialog.cs | 522 ++++++- .../ImGui/Panels/LootEditorFace.cs | 80 +- src/RynthCore.Engine/ImGui/Panels/LuaFace.cs | 2 +- .../ImGui/Panels/MetaFace.Editor.cs | 4 +- .../ImGui/Panels/MetaFace.List.cs | 2 +- .../ImGui/Panels/MetaFace.Schedule.cs | 6 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 2 +- .../ImGui/Panels/MiniRemoteFace.Sections.cs | 24 +- .../ImGui/Panels/MiniRemoteFace.cs | 42 +- .../ImGui/Panels/OracleCompanionStrip.cs | 109 ++ src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 3 +- .../ImGui/Panels/RynthAiFace.Drawers.cs | 4 +- .../ImGui/Panels/RynthAiFace.cs | 29 +- .../ImGui/Panels/RynthNavArrowFace.cs | 56 +- .../ImGui/Panels/RynthNavFace.cs | 109 +- .../ImGui/Panels/ScriptWindowFace.cs | 3 + .../ImGui/Panels/SkillsFace.Progression.cs | 291 ++-- src/RynthCore.Engine/ImGui/RynthCoreShell.cs | 8 +- .../Plugins/EngineSettings.cs | 30 +- .../Plugins/PluginContract.cs | 18 +- .../Plugins/PluginContractVersion.cs | 10 +- .../Plugins/PluginManager.ServerPlugins.cs | 4 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 57 +- .../Plugins/PluginManifestGate.cs | 19 +- .../Plugins/WindowPlacementApi.cs | 45 + src/RynthCore.Engine/UI/AcWindowChrome.cs | 1003 ++++++++----- src/RynthCore.Engine/UI/AvaloniaOverlay.cs | 14 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 114 +- src/RynthCore.Engine/UI/Data/ChatHistory.cs | 41 + src/RynthCore.Engine/UI/Data/ChatReplyTab.cs | 73 + src/RynthCore.Engine/UI/Data/ChatRouting.cs | 40 +- .../UI/Data/ChatSettingsDto.cs | 4 + .../UI/Data/ChatSettingsMerge.cs | 75 + src/RynthCore.Engine/UI/Data/ItemToolData.cs | 11 +- src/RynthCore.Engine/UI/Data/ItemsData.cs | 31 +- src/RynthCore.Engine/UI/Data/LootEditData.cs | 118 +- .../UI/Data/ProgressionData.cs | 13 + src/RynthCore.Engine/UI/Data/RynthNavData.cs | 21 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 187 ++- src/RynthCore.Engine/UI/Data/UiDataHub.cs | 6 + .../UI/Dcomp/DcompOverlayWindow.cs | 7 +- .../UI/InventoryTitleLayout.cs | 41 +- src/RynthCore.Engine/UI/LayeredWindow.cs | 25 +- src/RynthCore.Engine/UI/PanelStatePath.cs | 80 + src/RynthCore.Engine/UI/Panels/ItemsPanel.cs | 12 +- .../UI/Panels/RynthAiPanel.cs | 18 +- .../UI/Panels/RynthChatPresets.cs | 15 +- .../UI/Panels/SettingsPanel.cs | 14 + .../UI/Sections/NotLoadedServers.cs | 19 +- .../UI/Sections/SectionRegistry.cs | 4 +- src/RynthCore.Engine/UI/ServerMenus.cs | 2 +- .../UI/WindowPlacementStore.cs | 140 ++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 3 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 42 +- .../build/RynthCore.PluginSdk.targets | 2 +- .../AcGraphicsPrefsTests.csproj | 25 + tools/AcGraphicsPrefsTests/Program.cs | 140 ++ tools/BarDeclutterTests/Program.cs | 58 +- tools/ChatCommandReplyTests/Program.cs | 11 +- tools/ChatFilterTests/ChatFilterTests.csproj | 3 + tools/ChatFilterTests/Program.cs | 136 ++ tools/ChatHistoryBench/Program.cs | 49 + tools/ChatHistoryBench/Stubs.cs | 15 + .../DatShareSlotTests.csproj | 24 + tools/DatShareSlotTests/Program.cs | 241 +++ tools/EngineSettingsTests/Program.cs | 31 +- tools/LootAddWireTests/Program.cs | 3 +- tools/PanelStateTests/PanelStateTests.csproj | 22 + tools/PanelStateTests/Program.cs | 54 + tools/PluginManifestTests/Program.cs | 39 +- tools/SectionsTests/Program.cs | 89 +- tools/SectionsTests/SectionsTests.csproj | 1 + tools/SettingsLayoutTests/Program.cs | 2 +- 438 files changed, 39578 insertions(+), 1304 deletions(-) create mode 100644 AGENTS.md create mode 100644 Build-Release-All.ps1 create mode 100644 CLAUDE.md create mode 100644 Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md create mode 100644 Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md create mode 100644 Changelog/2026-04-22-installer-previous-release-folder.md create mode 100644 Changelog/2026-04-22-launcher-injector-self-contained.md create mode 100644 Changelog/2026-04-22-minhook-preload-before-multiclient.md create mode 100644 Changelog/2026-04-22-net-prereq-launcher-matches-inno.md create mode 100644 Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md create mode 100644 Changelog/2026-04-22-release-0.4.1.md create mode 100644 Changelog/2026-04-22-release-0.4.3-bundle.md create mode 100644 Changelog/2026-04-22-release-0.4.7-bundle.md create mode 100644 Changelog/2026-04-22-release-0.4.8.md create mode 100644 Changelog/2026-04-22-release-0.4.9.md create mode 100644 Changelog/2026-04-22-rynth-bundle-installer.md create mode 100644 Changelog/2026-04-22-tmds-dbus-protocol-security.md create mode 100644 Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md create mode 100644 Changelog/2026-04-23-launcher-host-diagnostics.md create mode 100644 Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md create mode 100644 Changelog/2026-04-23-release-0.4.10.md create mode 100644 Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md create mode 100644 Changelog/2026-04-23-release-0.4.2.md create mode 100644 Changelog/2026-04-23-release-0.4.7-bundle.md create mode 100644 Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md create mode 100644 Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md create mode 100644 Changelog/2026-04-24-release-0.4.4-bundle.md create mode 100644 Changelog/2026-04-25-desktop-rolling-logs.md create mode 100644 Changelog/2026-04-25-release-0.4.5-bundle.md create mode 100644 Changelog/2026-04-26-release-0.4.6-bundle.md create mode 100644 Changelog/2026-10-04-aelrynth-sync.md create mode 100644 Changelog/2026-10-04-aelrynth-urls.md create mode 100644 Changelog/2026-10-04-char-and-hub-launcher-buttons.md create mode 100644 Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md create mode 100644 Changelog/2026-10-04-dashboard-map-and-lua-buttons.md create mode 100644 Changelog/2026-10-04-floating-huds.md create mode 100644 Changelog/2026-10-04-full-installer-2026.10.4.2.md create mode 100644 Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md create mode 100644 Changelog/2026-10-04-ilt-hub-pet-roster.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.1.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.10-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.11-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.12-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.13-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.14-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.15-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.16-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.17-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.18-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.19-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.20-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.8-release.md create mode 100644 Changelog/2026-10-04-installer-2026.10.4.9-release.md create mode 100644 Changelog/2026-10-04-item-info-click-and-pet-layout.md create mode 100644 Changelog/2026-10-04-items-panel-shields.md create mode 100644 Changelog/2026-10-04-loot-name-rules-and-ground-loot.md create mode 100644 Changelog/2026-10-04-merge-result-cdecl-crash-fix.md create mode 100644 Changelog/2026-10-04-missile-ammo-detection.md create mode 100644 Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md create mode 100644 Changelog/2026-10-04-nav-panel-scroll-fix.md create mode 100644 Changelog/2026-10-04-panel-window-owner-thread-fixes.md create mode 100644 Changelog/2026-10-04-pet-refill-loop-fix.md create mode 100644 Changelog/2026-10-04-pet-scan-type-detection.md create mode 100644 Changelog/2026-10-04-plugin-overlay-windows.md create mode 100644 Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md create mode 100644 Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md create mode 100644 Changelog/2026-10-04-sk-local-unified.md create mode 100644 Changelog/2026-10-04-tmds-dbus-advisory.md create mode 100644 Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md create mode 100644 Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md create mode 100644 Changelog/2026-10-05-charms-tracking-tab.md create mode 100644 Changelog/2026-10-05-chat-standard-filters.md create mode 100644 Changelog/2026-10-05-chat-translation.md create mode 100644 Changelog/2026-10-05-floating-window-placement.md create mode 100644 Changelog/2026-10-05-guardian-and-remote-slots.md create mode 100644 Changelog/2026-10-05-guardian-vendor-and-item-lookup.md create mode 100644 Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md create mode 100644 Changelog/2026-10-05-imgui-over-avalonia-port.md create mode 100644 Changelog/2026-10-05-installer-2026.10.4.21-release.md create mode 100644 Changelog/2026-10-05-installer-2026.10.4.22-release.md create mode 100644 Changelog/2026-10-05-inventory-add-to-item-count-hud.md create mode 100644 Changelog/2026-10-05-mini-remote-is-ilt-hub.md create mode 100644 Changelog/2026-10-05-mini-remote-target-and-summon.md create mode 100644 Changelog/2026-10-05-native-drag-real-item.md create mode 100644 Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.10.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.11.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.2.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.3.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.4.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.5.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.6.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.7.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.8.md create mode 100644 Changelog/2026-10-05-release-2026.10.5.9.md create mode 100644 Changelog/2026-10-05-rynthai-cimgui-binding.md create mode 100644 Changelog/2026-10-05-rynthai-launcher-remote-commands.md create mode 100644 Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md create mode 100644 Changelog/2026-10-06-upstream-snapshot-comparison.md create mode 100644 Changelog/2026-10-07-merge-main-into-QOL-items.md create mode 100644 Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md create mode 100644 Changelog/2026-10-07-release-2026.10.5.16-main-integration.md create mode 100644 Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md create mode 100644 Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md create mode 100644 Changelog/2026-10-08-installer-2026.10.5.21-release.md create mode 100644 Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md create mode 100644 Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md create mode 100644 Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md create mode 100644 Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md create mode 100644 Changelog/2026-10-10-installer-2026.10.5.24-release.md create mode 100644 Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md create mode 100644 Changelog/2026-10-11-build-comp-10-11-merge.md create mode 100644 Changelog/2026-10-11-chat-discord-relay.md create mode 100644 Changelog/2026-10-11-installer-2026.10.5.25-release.md create mode 100644 Changelog/2026-10-11-installer-2026.10.5.26-release.md create mode 100644 Changelog/2026-10-11-installer-2026.10.5.37.md create mode 100644 Changelog/2026-10-11-installer-2026.10.5.38.md create mode 100644 Changelog/2026-10-12-confirmation-answers-crafting-menu.md create mode 100644 Changelog/2026-10-12-environment-throttle-attack-power-settings.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.39.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.40.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.41.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.42.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.43.md create mode 100644 Changelog/2026-10-12-hot-release-2026.10.5.44.md create mode 100644 Changelog/2026-10-12-items-damage-type-colors.md create mode 100644 Changelog/2026-10-12-progression-attributes-merge.md create mode 100644 Changelog/2026-10-13-fellowship-menu-ilt-settings-push-2026.10.5.47.md create mode 100644 Changelog/2026-10-13-full-install-2026.10.5.46.md create mode 100644 Changelog/2026-10-13-full-install-2026.10.5.47.md create mode 100644 Changelog/2026-10-13-ilt-fellowship-installer-text.md create mode 100644 Changelog/2026-10-13-ilt-verdict-logging-2026.10.5.52.md create mode 100644 Changelog/2026-10-13-launcher-known-servers-2026.10.5.48.md create mode 100644 Changelog/2026-10-13-merge-2026.10.13.3-api-renumber-2026.10.5.55.md create mode 100644 Changelog/2026-10-13-merge-dynamic-sections-2026.10.5.50.md create mode 100644 Changelog/2026-10-13-mini-remote-rail-hidden-tabs-2026.10.5.51.md create mode 100644 Changelog/2026-10-13-mini-remote-sections-2026.10.5.46.md create mode 100644 Changelog/2026-10-13-oracle-quests-menu-hub-launcher-2026.10.5.49.md create mode 100644 Changelog/2026-10-13-port-build-comp-onto-upstream.md create mode 100644 Changelog/2026-10-13-security-review-fixes-2026.10.5.45.md create mode 100644 Changelog/2026-10-13-server-list-and-forced-server-load-2026.10.5.56.md create mode 100644 Changelog/2026-10-13-server-plugins-2026.10.5.48.md create mode 100644 Changelog/2026-10-13-server-selection-2026.10.5.53.md create mode 100644 Changelog/2026-10-13-session-stats-moved-tabs-2026.10.5.54.md create mode 100644 Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md create mode 100644 Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md create mode 100644 Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md create mode 100644 Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md create mode 100644 Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md create mode 100644 Changelog/2026-10-15-borderless-restore-chrome-2026.10.5.67.md create mode 100644 Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md create mode 100644 Changelog/2026-10-15-display-borderless-remember-layout-2026.10.5.65.md create mode 100644 Changelog/2026-10-15-loot-picker-filter-2026.10.5.66.md create mode 100644 Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md create mode 100644 Changelog/2026-10-15-vaulted-dungeons-options-nav-2026.10.5.68.md create mode 100644 Changelog/2026-10-16-bar-hide-itemcount-ginv-2026.10.16.6.md create mode 100644 Changelog/2026-10-16-chat-combat-standard-filters-2026.10.16.10.md create mode 100644 Changelog/2026-10-16-chat-filters-hide-retail-chat-2026.10.16.23.md create mode 100644 Changelog/2026-10-16-chat-filters-ubit-parity-2026.10.16.2.md create mode 100644 Changelog/2026-10-16-dxvk-detect-software-overlay-2026.10.16.13.md create mode 100644 Changelog/2026-10-16-engine-kite-pull-away-ui.md create mode 100644 Changelog/2026-10-16-full-install-suite-plugins-2026.10.16.21.md create mode 100644 Changelog/2026-10-16-hotbuild-local-2026.10.5.69.md create mode 100644 Changelog/2026-10-16-hotpush-2026.10.15.8.md create mode 100644 Changelog/2026-10-16-hotreload-no-erl-bypass-2026.10.16.5.md create mode 100644 Changelog/2026-10-16-inventory-itemcount-ginv-buttons-2026.10.16.4.md create mode 100644 Changelog/2026-10-16-inventory-miniremote-off-bar-2026.10.16.8.md create mode 100644 Changelog/2026-10-16-inventory-rsort-button-2026.10.16.7.md create mode 100644 Changelog/2026-10-16-inworld-hotreload-hold-2026.10.16.3.md create mode 100644 Changelog/2026-10-16-launcher-dxvk-toggle-0.1.8.md create mode 100644 Changelog/2026-10-16-launcher-scroll-clip-server-list-0.1.9.md create mode 100644 Changelog/2026-10-16-miniremote-dock-undock-2026.10.16.11.md create mode 100644 Changelog/2026-10-16-miniremote-rail-off-orphan-2026.10.15.9.md create mode 100644 Changelog/2026-10-16-oracle-skills-embed-2026.10.16.1.md create mode 100644 Changelog/2026-10-16-oracle-skills-embed-into-local-2026.10.16.14.md create mode 100644 Changelog/2026-10-16-plugin-chat-queue-depth-2026.10.16.20.md create mode 100644 Changelog/2026-10-16-popout-keep-floating-pos-2026.10.16.12.md create mode 100644 Changelog/2026-10-16-port-sk-engine-work-2026.10.16.22.md create mode 100644 Changelog/2026-10-16-progress-enl-calculator-2026.10.16.9.md create mode 100644 Changelog/2026-10-16-runtime-borderless-display-2026.10.5.70.md create mode 100644 Changelog/2026-10-16-sense-rnav-vision-tracker-oracle-2026.10.16.16.md create mode 100644 Changelog/2026-10-16-test-build-full-install-2026.10.16.24.md create mode 100644 Changelog/2026-10-16-test-hotbuild-installer-2026.10.16.18.md create mode 100644 Changelog/2026-10-16-test-merge-aelrynth-hotbuild-2026.10.16.15.md create mode 100644 Changelog/2026-10-16-updater-local-ahead-of-feed-2026.10.16.19.md create mode 100644 Changelog/2026-10-17-borderless-fill-monitor-2026.10.17.4.md create mode 100644 Changelog/2026-10-17-chat-coord-links-arrow-clear-2026.10.17.2.md create mode 100644 Changelog/2026-10-17-engine-settings-multiclient-2026.10.17.3.md create mode 100644 Changelog/2026-10-17-graphics-per-account-no-fight-2026.10.18.3.md create mode 100644 Changelog/2026-10-17-graphics-settings-panel-2026.10.18.1.md create mode 100644 Changelog/2026-10-17-launcher-prefs-swap-live-ini-2026.10.18.2.md create mode 100644 Changelog/2026-10-17-test-build-full-install-2026.10.17.6.md create mode 100644 Changelog/2026-10-17-test-build-full-install-2026.10.18.13.md create mode 100644 Changelog/2026-10-17-test-build-full-install-2026.10.18.2.md create mode 100644 Changelog/2026-10-17-test-build-full-install-2026.10.18.4.md create mode 100644 Changelog/2026-10-17-window-not-saved-at-login-size-2026.10.17.8.md create mode 100644 Changelog/2026-10-17-window-placement-shared-file-2026.10.17.7.md create mode 100644 Changelog/2026-10-17-window-reset-borderless-position-2026.10.17.5.md create mode 100644 Changelog/2026-10-18-chat-link-probe-2026.10.18.25.md create mode 100644 Changelog/2026-10-18-graphics-low-memory-safeguard-2026.10.18.11.md create mode 100644 Changelog/2026-10-18-inventory-vault-button-2026.10.18.14.md create mode 100644 Changelog/2026-10-18-inventory-vault-modern-2026.10.18.15.md create mode 100644 Changelog/2026-10-18-loot-add-attribute-checklist-2026.10.18.10.md create mode 100644 Changelog/2026-10-18-test-build-full-install-2026.10.18.24.md create mode 100644 Changelog/2026-10-19-automated-system-text-in-system-tab-2026.10.18.30.md create mode 100644 Changelog/2026-10-19-incoming-chat-queue-25000-lines-2026.10.18.29.md create mode 100644 Changelog/2026-10-19-items-prismatic-damage-type-2026.10.19.3.md create mode 100644 Changelog/2026-10-19-merge-rynth-main-2026.10.19.1-into-test.md create mode 100644 Changelog/2026-10-19-skills-aug-still-needed-sigil-how-to-get-2026.10.18.31.md create mode 100644 Changelog/2026-10-20-popout-plugin-imgui-context-crash-2026.10.20.4.md create mode 100644 Changelog/2026-10-23-chat-filter-slow-rules-retry-2026.10.20.11.md create mode 100644 Changelog/2026-10-24-chat-command-replies-in-typed-tab-2026.10.20.14.md create mode 100644 Changelog/2026-10-24-chat-history-automated-budget-2026.10.20.18.md create mode 100644 Changelog/2026-10-24-chat-scroll-follow-and-keep-place-2026.10.20.18.md create mode 100644 Changelog/2026-10-24-chat-settings-safe-saves-per-character-layout-2026.10.20.13.md create mode 100644 Changelog/2026-10-24-inventory-filter-like-this.md create mode 100644 Changelog/2026-10-25-inventory-add-to-damage-weapons-2026.10.20.19.md create mode 100644 Changelog/2026-10-26-plugin-windows-keep-their-spot-per-character-api-91.md create mode 100644 Changelog/2026-11-11-dungeon-map-visited-per-floor.md create mode 100644 Changelog/2026-11-12-progress-tab-ilt-sections-only-on-ilt.md create mode 100644 Changelog/2026-11-15-item-tool-give-amount-and-every.md create mode 100644 Changelog/2026-11-22-inventory-add-to-trade-shop.md create mode 100644 Changelog/2026-11-22-inventory-trade-shop-storefront.md create mode 100644 Changelog/2026-11-22-settings-game-client-vtank-import.md create mode 100644 Changelog/2026-11-22-sk-backlog-test-merge.md create mode 100644 Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md create mode 100644 Plugins/RynthAi/Combat/BuffManager.cs create mode 100644 Plugins/RynthAi/Combat/CombatActionHelper.cs create mode 100644 Plugins/RynthAi/Combat/CombatManager.cs create mode 100644 Plugins/RynthAi/Combat/FellowshipTracker.cs create mode 100644 Plugins/RynthAi/Combat/MissileCraftingManager.cs create mode 100644 Plugins/RynthAi/Combat/SpellDatabase.cs create mode 100644 Plugins/RynthAi/Combat/SpellManager.cs create mode 100644 Plugins/RynthAi/Combat/Vtank spelldump.txt create mode 100644 Plugins/RynthAi/DecalInspector.cs create mode 100644 Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs create mode 100644 Plugins/RynthAi/Logic/CommandProcessor.cs create mode 100644 Plugins/RynthAi/Logic/NavigationManager.cs create mode 100644 Plugins/RynthAi/Logic/RynthJumper.cs create mode 100644 Plugins/RynthAi/Loot/LootManager.cs create mode 100644 Plugins/RynthAi/Loot/VTankLootParser.cs create mode 100644 Plugins/RynthAi/Lua/LuaBridge.cs create mode 100644 Plugins/RynthAi/Lua/LuaManager.cs create mode 100644 Plugins/RynthAi/Meta/MetaManager.cs create mode 100644 Plugins/RynthAi/Meta/VTankMetaParser.cs create mode 100644 Plugins/RynthAi/Nav/MovementActionHelper.cs create mode 100644 Plugins/RynthAi/Nav/NavigationManager.cs create mode 100644 Plugins/RynthAi/Nav/Tier2Log.cs create mode 100644 Plugins/RynthAi/Nav/Tier2MovementHelper.cs create mode 100644 Plugins/RynthAi/Nav/VTankNavParser.cs create mode 100644 Plugins/RynthAi/PluginCore.cs create mode 100644 Plugins/RynthAi/Raycasting/BlacklistManager.cs create mode 100644 Plugins/RynthAi/Raycasting/BoundingVolume.cs create mode 100644 Plugins/RynthAi/Raycasting/DatDatabase.cs create mode 100644 Plugins/RynthAi/Raycasting/DungeonLOS.cs create mode 100644 Plugins/RynthAi/Raycasting/GeometryLoader.cs create mode 100644 Plugins/RynthAi/Raycasting/LandblockStructs.cs create mode 100644 Plugins/RynthAi/Raycasting/MainLogic.cs create mode 100644 Plugins/RynthAi/Raycasting/RaycastEngine.cs create mode 100644 Plugins/RynthAi/Raycasting/ScatterSystem.cs create mode 100644 Plugins/RynthAi/Raycasting/TargetingFSM.cs create mode 100644 Plugins/RynthAi/Raycasting/Vector3Helper.cs create mode 100644 Plugins/RynthAi/RynthAi.csproj create mode 100644 Plugins/RynthAi/UI/AdvancedSettingsUI.cs create mode 100644 Plugins/RynthAi/UI/LuaUI.cs create mode 100644 Plugins/RynthAi/UI/MetaUI.cs create mode 100644 Plugins/RynthAi/UI/MonstersUI.cs create mode 100644 Plugins/RynthAi/UI/RouteUI.cs create mode 100644 Plugins/RynthAi/UI/RynthAiUI.Rendering.cs create mode 100644 Plugins/RynthAi/UI/RynthAiUI.cs create mode 100644 Plugins/RynthAi/UI/UISettings.cs create mode 100644 Plugins/RynthAi/app.config create mode 100644 Plugins/RynthAi/packages.config create mode 100644 Plugins/RynthAi/properties/AssemblyInfo.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj create mode 100644 docs/ACCLIENT_HOOK_INVENTORY.md create mode 100644 docs/DXVK_TEXTURE_SMOKE.md create mode 100644 docs/ub-hub-merge-playbook.md create mode 100644 find_bytes.cs create mode 100644 installer/previous-release/last-built-version.txt create mode 100644 installer/previous-release/last-release-manifest.json create mode 100644 installer/previous-release/previous-version.txt create mode 100644 last-built-version.txt create mode 100644 loot-port-plan.txt create mode 100644 scripts/Fetch-Dxvk.ps1 create mode 100644 src/RynthCore.App/DxvkPackageService.cs create mode 100644 src/RynthCore.Engine/Compatibility/ChatLinkProbe.cs create mode 100644 src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs create mode 100644 src/RynthCore.Engine/Compatibility/ServerCommandFallback.cs create mode 100644 src/RynthCore.Engine/Compatibility/SessionRates.cs create mode 100644 src/RynthCore.Engine/D3D9/DxvkDetection.cs create mode 100644 src/RynthCore.Engine/Graphics/AcGraphics.cs create mode 100644 src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/InventoryFace.LikeFilter.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/OracleCompanionStrip.cs create mode 100644 src/RynthCore.Engine/Plugins/WindowPlacementApi.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatReplyTab.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatSettingsMerge.cs create mode 100644 src/RynthCore.Engine/UI/PanelStatePath.cs create mode 100644 src/RynthCore.Engine/UI/WindowPlacementStore.cs create mode 100644 tools/AcGraphicsPrefsTests/AcGraphicsPrefsTests.csproj create mode 100644 tools/AcGraphicsPrefsTests/Program.cs create mode 100644 tools/DatShareSlotTests/DatShareSlotTests.csproj create mode 100644 tools/DatShareSlotTests/Program.cs create mode 100644 tools/PanelStateTests/PanelStateTests.csproj create mode 100644 tools/PanelStateTests/Program.cs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c4a7c68..7421c81 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -50,9 +50,12 @@ jobs: $override = "${{ github.event.inputs.rynthsuite_ref }}" if ($override) { $want = $override } Write-Host "Cloning RynthSuite to: $dest (pin target: $want)" + # Sibling fork on the same GitHub owner (BlankenshipG in this environment). + # Canonical public source is https://aelrynth.com/git/RynthSuite.git — CI uses + # the GitHub sibling so the release build matches this fork pair. # If RynthSuite is private, set a GH_PAT secret and use the token URL: - # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/tombohar/RynthSuite.git $dest - git clone https://github.com/tombohar/RynthSuite.git $dest + # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/${{ github.repository_owner }}/RynthSuite.git $dest + git clone "https://github.com/${{ github.repository_owner }}/RynthSuite.git" $dest if ($LASTEXITCODE -ne 0) { throw "git clone RynthSuite failed" } git -C $dest fetch --tags --quiet if ($want -and (git -C $dest rev-parse --verify --quiet "$want^{commit}")) { diff --git a/.gitignore b/.gitignore index 97871b1..36bf792 100644 --- a/.gitignore +++ b/.gitignore @@ -49,4 +49,10 @@ installer/Releases/ # Process Monitor / debug log dumps (session junk) *.PML Logfile*.XML +# Archived installers (Build-Installer.ps1 keeps the previous release here; only the version marker is tracked) +installer/previous-release/*.exe + +# Local publish/bundle output (SK-era Build-Installer staging and old bundle exes) +installer/_toolpublish/ +build_out/ out/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..37f53e3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,133 @@ +# RynthCore — Codex Context + +A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Replaces Decal + UBService with a self-contained injection system. Hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. + +--- + +## ⚠ Active Focus: RynthAi ImGui Plugin + +**Do NOT work on `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs` (the Avalonia version of RynthAi).** +The Avalonia RynthAi panel is disabled (`EntryPoint.cs` registration is commented out) and parked until the ImGui plugin is feature-complete. All RynthAi work goes in `Plugins/RynthCore.Plugin.RynthAi/` which uses ImGui via `RynthCore.PluginCore`. + +--- + +## Project Layout + +``` +C:\Projects\RynthCore\ +└── src\ + ├── RynthCore.Injector\ Console app — injects Engine into acclient.exe + │ └── Program.cs LoadLibrary + CreateRemoteThread injection + └── RynthCore.Engine\ NativeAOT x86 DLL — lives inside acclient.exe + ├── EntryPoint.cs Exported RynthCoreInit, preloads native DLLs, spawns init thread + ├── D3D9\ + │ ├── D3D9VTable.cs Temp device to harvest vtable pointers + │ ├── EndSceneHook.cs MinHook detour on EndScene + │ └── TestRenderer.cs v0.1 proof-of-life, kept for reference + └── ImGui\ + ├── ImGuiController.cs Context creation, frame loop orchestration + ├── DX9Backend.cs Renders ImGui draw data via raw D3D9 vtable calls + └── Win32Backend.cs WndProc subclass for mouse/keyboard input +``` + +Deploy folder: `C:\Games\RynthCore\` + +--- + +## Build + +```bash +# Engine (NativeAOT — slow first build, ~2 min) +cd src\RynthCore.Engine +dotnet publish -c Release + +# Injector +cd src\RynthCore.Injector +dotnet publish -c Release +``` + +Both projects target **x86** only. The Engine is NativeAOT (`PublishAot=true`) — it has no .NET runtime dependency and injects as a plain native DLL. + +Deploy output: +``` +C:\Games\RynthCore\ +├── RynthCore.Engine.dll ← Engine publish output +├── RynthCore.Injector.exe ← Injector publish output +├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint +└── cimgui.dll ← ImGui C bindings (x86, docking branch) +``` + +Log file: `%USERPROFILE%\Desktop\RynthCore.log` + +--- + +## Key Technical Facts + +### NativeAOT / x86 +- .NET 9, `net9.0-windows`, `PlatformTarget=x86`, `RuntimeIdentifier=win-x86` +- `AllowUnsafeBlocks=true`, `PublishAot=true`, `TrimMode=link` +- `ImGui.NET` assembly is trim-rooted to preserve P/Invoke bindings +- `SetWindowLongA` not `SetWindowLongPtrA` — the Ptr variant doesn't exist on x86 + +### Injection flow +1. `RynthCore.Injector.exe` calls `CreateRemoteThread(LoadLibrary, "RynthCore.Engine.dll")` +2. `RynthCoreInit` export fires under loader lock — immediately spawns background thread +3. Init thread sleeps 2s (lets AC finish D3D9 init), preloads minhook + cimgui, then installs EndScene hook + +### D3D9 hook +- Vtable discovery: creates a throwaway device via `D3D9VTable.cs`, captures 119 vtable entries +- Hook installed via MinHook on `EndScene` (vtable index 42) +- All D3D9 calls go through cached delegates (stdcall, `this` as first param) — never via COM wrappers +- State save/restore is manual (get/set each render state) — D3D9 state blocks don't work reliably inside EndScene + +### ImGui / cimgui version situation +- ImGui.NET NuGet: **1.91.6.1** +- cimgui.dll must match: use `%USERPROFILE%\.nuget\packages\imgui.net\1.91.6.1\runtimes\win-x86\native\cimgui.dll` +- Post-1.90 struct layout: `ImDrawData.CmdLists` is an **ImVector (12 bytes)**, not a raw pointer (4 bytes) +- `DX9Backend.cs` reads `ImDrawData` fields from native memory at confirmed offsets as a safety fallback: + - `+4` = CmdListsCount + - `+16` = CmdLists array pointer + - `+20/24` = DisplayPos (X, Y) + - `+28/32` = DisplaySize (X, Y) + +### ImGui input API +- Uses the **modern** API: `AddKeyEvent` / `AddMouseButtonEvent` / `AddMousePosEvent` +- `KeyMap` / `KeysDown` / `MouseDown` arrays were removed in ImGui 1.87 — do not use them +- WndProc subclass via `SetWindowLongA` (not Ptr) in `Win32Backend.cs` + +### DX9Backend render notes +- `DrawIndexedPrimitiveUP` takes user-memory pointers directly — **do not** call `SetStreamSource(null)` before it, this crashes the driver +- Vertex format: `D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1` — xyz (3 floats) + BGRA color (uint) + uv (2 floats) +- ImGui gives RGBA pixel data; D3D9 `A8R8G8B8` is BGRA in memory — swizzle R↔B on upload +- Color conversion per vertex: `(c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16)` +- Font texture: `POOL_MANAGED`, created once in `Init`, `TexID` set via `io.Fonts.SetTexID` + +### Multi-viewport (docking/undocking outside AC window) +- `DockingEnable` is on +- `ViewportsEnable` is commented out — requires cimgui built with `IMGUI_ENABLE_VIEWPORTS` + +--- + +## Common Pitfalls + +| Symptom | Cause | +|---------|-------| +| `DisplaySize = <1, 1>` | cimgui.dll version mismatch (pre/post 1.90 layout) | +| Font cache crash on frame 2 | `io.Fonts.TexID` was zero after init (usually fixed by matching cimgui) | +| Crash in `SetupRenderStateNative` | Do not call `SetStreamSource(null, 0)` — invalid for UP drawing | +| Duplicate `vtxCount` compile error | Was present in early source — remove the second declaration | +| Hook not firing | acclient.exe must be running and past login before injection | +| `ChangePortalMode` event (future) | Crashes Decal — never use (RynthCore note carried from NexTank) | + +--- + +## Current Status (v0.2) + +- [x] D3D9 EndScene hook stable +- [x] ImGui context, font texture, WndProc subclass working +- [x] ImGui demo window + RynthCore info panel rendering +- [x] Mouse/keyboard input forwarded; ImGui captures input when hovered +- [ ] Multi-viewport (needs IMGUI_ENABLE_VIEWPORTS cimgui build) +- [ ] NexTank UI panels ported to RynthCore +- [ ] Network message hooks +- [ ] World state / actions API diff --git a/BUILD.md b/BUILD.md index 8f94d96..bc28371 100644 --- a/BUILD.md +++ b/BUILD.md @@ -215,6 +215,10 @@ cd C:\Projects\RynthCore\installer This runs `dotnet publish` for the Launcher, Loader, Engine, and RynthAi plugin (from RynthSuite), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer. +It also publishes the **experimental plugins** — RynthChat, RynthJuice, RynthNav, RynthTracker, RynthVision and **ub-Rythai** (`RynthSuite\Plugins\ub-Rythai\RynthCore.Plugin.UbRythai`) — as optional installer components (unchecked by default) that install to `\\RynthCore.Plugin..dll`. + +`..\Build-Release-All.ps1 -Version ` builds `RynthCore.sln` first and then runs `Build-Installer.ps1`. + Output: `installer\Output\RynthCore-Setup.exe` ### Options diff --git a/Build-Release-All.ps1 b/Build-Release-All.ps1 new file mode 100644 index 0000000..2c680ff --- /dev/null +++ b/Build-Release-All.ps1 @@ -0,0 +1,73 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Builds a full Release of RynthCore + RynthSuite and produces the Windows installer. + +.DESCRIPTION + 1. Compiles RynthCore.sln in Release (validates all SDK projects before the slow publishes). + 2. Invokes installer\Build-Installer.ps1, which publishes the launcher, engine, loader, + RynthAi, the Loot/Monster editors and the experimental plugins (incl. ub-Rythai), stages + them, archives the previous installer when -Version changes, and compiles RynthCore.iss + into installer\Output\RynthCore-Setup-.exe (requires Inno Setup 6). + 3. With -Version, Build-Installer.ps1 also assembles the deployment package + installer\Output\Release-\ and installer\Output\RynthCore--deploy.zip + (installer + SHA256SUMS.txt + release-manifest.json + RELEASE-NOTES.md, hash-verified). + +.PARAMETER Version + Installer version (e.g. 2026.10.4.7). Passed through to Build-Installer.ps1. + +.PARAMETER RynthSuiteRoot + RynthSuite checkout. Default (empty): the sibling ..\RynthSuite folder. + +.PARAMETER IsccPath + ISCC.exe location. Default (empty): Build-Installer.ps1 searches the usual Inno Setup paths. + +.EXAMPLE + .\Build-Release-All.ps1 -Version 2026.10.4.7 +#> +param( + [string]$Version = "", + [string]$RynthSuiteRoot = "", + [string]$IsccPath = "" +) + +$ErrorActionPreference = "Stop" +# This script lives at the RynthCore repository root. +$RepoRoot = $PSScriptRoot + +$sln = Join-Path $RepoRoot "RynthCore.sln" +if (-not (Test-Path $sln)) { + throw "RynthCore.sln not found at: $sln" +} + +# Plugin API delegates must be cdecl. On x86 a delegate without +# [UnmanagedFunctionPointer(CallingConvention.Cdecl)] marshals as stdcall, and every cdecl call +# from a plugin then pops its arguments twice and corrupts the plugin's stack. +$contract = Join-Path $RepoRoot "src\RynthCore.Engine\Plugins\PluginContract.cs" +$contractLines = [IO.File]::ReadAllLines($contract) +$badDelegates = @() +for ($i = 0; $i -lt $contractLines.Length; $i++) { + if ($contractLines[$i] -notmatch '^\s*(internal|public)\s+(unsafe\s+)?delegate\s') { continue } + # Nearest previous line that is not blank and not a // comment must carry the attribute. + $j = $i - 1 + while ($j -ge 0 -and ($contractLines[$j].Trim() -eq '' -or $contractLines[$j].Trim().StartsWith('//'))) { $j-- } + if ($j -lt 0 -or $contractLines[$j] -notmatch 'UnmanagedFunctionPointer\(CallingConvention\.Cdecl\)') { + $badDelegates += " line $($i + 1): $($contractLines[$i].Trim())" + } +} +if ($badDelegates.Count -gt 0) { + throw "PluginContract.cs delegate(s) missing [UnmanagedFunctionPointer(CallingConvention.Cdecl)]:`n$($badDelegates -join "`n")" +} + +Write-Host "Building solution: $sln" -ForegroundColor Cyan +dotnet build $sln -c Release +if ($LASTEXITCODE -ne 0) { throw "Solution build failed (exit $LASTEXITCODE)" } + +# Only forward parameters Build-Installer.ps1 actually declares. +$invokeArgs = @{ Configuration = "Release" } +if ($Version) { $invokeArgs.Version = $Version } +if ($RynthSuiteRoot) { $invokeArgs.RynthSuiteRoot = $RynthSuiteRoot } +if ($IsccPath) { $invokeArgs.IsccPath = $IsccPath } + +& (Join-Path $RepoRoot "installer\Build-Installer.ps1") @invokeArgs +if ($LASTEXITCODE -ne 0) { throw "Build-Installer.ps1 failed (exit $LASTEXITCODE)" } diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b1e83fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,133 @@ +# RynthCore — Claude Context + +A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Replaces Decal + UBService with a self-contained injection system. Hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. + +--- + +## ⚠ Active Focus: RynthAi ImGui Plugin + +**Do NOT work on `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs` (the Avalonia version of RynthAi).** +The Avalonia RynthAi panel is disabled (`EntryPoint.cs` registration is commented out) and parked until the ImGui plugin is feature-complete. All RynthAi work goes in `Plugins/RynthCore.Plugin.RynthAi/` which uses ImGui via `RynthCore.PluginCore`. + +--- + +## Project Layout + +``` +C:\Projects\RynthCore\ +└── src\ + ├── RynthCore.Injector\ Console app — injects Engine into acclient.exe + │ └── Program.cs LoadLibrary + CreateRemoteThread injection + └── RynthCore.Engine\ NativeAOT x86 DLL — lives inside acclient.exe + ├── EntryPoint.cs Exported RynthCoreInit, preloads native DLLs, spawns init thread + ├── D3D9\ + │ ├── D3D9VTable.cs Temp device to harvest vtable pointers + │ ├── EndSceneHook.cs MinHook detour on EndScene + │ └── TestRenderer.cs v0.1 proof-of-life, kept for reference + └── ImGui\ + ├── ImGuiController.cs Context creation, frame loop orchestration + ├── DX9Backend.cs Renders ImGui draw data via raw D3D9 vtable calls + └── Win32Backend.cs WndProc subclass for mouse/keyboard input +``` + +Deploy folder: `C:\Games\RynthCore\` + +--- + +## Build + +```bash +# Engine (NativeAOT — slow first build, ~2 min) +cd src\RynthCore.Engine +dotnet publish -c Release + +# Injector +cd src\RynthCore.Injector +dotnet publish -c Release +``` + +Both projects target **x86** only. The Engine is NativeAOT (`PublishAot=true`) — it has no .NET runtime dependency and injects as a plain native DLL. + +Deploy output: +``` +C:\Games\RynthCore\ +├── RynthCore.Engine.dll ← Engine publish output +├── RynthCore.Injector.exe ← Injector publish output +├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint +└── cimgui.dll ← ImGui C bindings (x86, docking branch) +``` + +Log file: `%USERPROFILE%\Desktop\RynthCore.log` + +--- + +## Key Technical Facts + +### NativeAOT / x86 +- .NET 9, `net9.0-windows`, `PlatformTarget=x86`, `RuntimeIdentifier=win-x86` +- `AllowUnsafeBlocks=true`, `PublishAot=true`, `TrimMode=link` +- `ImGui.NET` assembly is trim-rooted to preserve P/Invoke bindings +- `SetWindowLongA` not `SetWindowLongPtrA` — the Ptr variant doesn't exist on x86 + +### Injection flow +1. `RynthCore.Injector.exe` calls `CreateRemoteThread(LoadLibrary, "RynthCore.Engine.dll")` +2. `RynthCoreInit` export fires under loader lock — immediately spawns background thread +3. Init thread sleeps 2s (lets AC finish D3D9 init), preloads minhook + cimgui, then installs EndScene hook + +### D3D9 hook +- Vtable discovery: creates a throwaway device via `D3D9VTable.cs`, captures 119 vtable entries +- Hook installed via MinHook on `EndScene` (vtable index 42) +- All D3D9 calls go through cached delegates (stdcall, `this` as first param) — never via COM wrappers +- State save/restore is manual (get/set each render state) — D3D9 state blocks don't work reliably inside EndScene + +### ImGui / cimgui version situation +- ImGui.NET NuGet: **1.91.6.1** +- cimgui.dll must match: use `%USERPROFILE%\.nuget\packages\imgui.net\1.91.6.1\runtimes\win-x86\native\cimgui.dll` +- Post-1.90 struct layout: `ImDrawData.CmdLists` is an **ImVector (12 bytes)**, not a raw pointer (4 bytes) +- `DX9Backend.cs` reads `ImDrawData` fields from native memory at confirmed offsets as a safety fallback: + - `+4` = CmdListsCount + - `+16` = CmdLists array pointer + - `+20/24` = DisplayPos (X, Y) + - `+28/32` = DisplaySize (X, Y) + +### ImGui input API +- Uses the **modern** API: `AddKeyEvent` / `AddMouseButtonEvent` / `AddMousePosEvent` +- `KeyMap` / `KeysDown` / `MouseDown` arrays were removed in ImGui 1.87 — do not use them +- WndProc subclass via `SetWindowLongA` (not Ptr) in `Win32Backend.cs` + +### DX9Backend render notes +- `DrawIndexedPrimitiveUP` takes user-memory pointers directly — **do not** call `SetStreamSource(null)` before it, this crashes the driver +- Vertex format: `D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1` — xyz (3 floats) + BGRA color (uint) + uv (2 floats) +- ImGui gives RGBA pixel data; D3D9 `A8R8G8B8` is BGRA in memory — swizzle R↔B on upload +- Color conversion per vertex: `(c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16)` +- Font texture: `POOL_MANAGED`, created once in `Init`, `TexID` set via `io.Fonts.SetTexID` + +### Multi-viewport (docking/undocking outside AC window) +- `DockingEnable` is on +- `ViewportsEnable` is commented out — requires cimgui built with `IMGUI_ENABLE_VIEWPORTS` + +--- + +## Common Pitfalls + +| Symptom | Cause | +|---------|-------| +| `DisplaySize = <1, 1>` | cimgui.dll version mismatch (pre/post 1.90 layout) | +| Font cache crash on frame 2 | `io.Fonts.TexID` was zero after init (usually fixed by matching cimgui) | +| Crash in `SetupRenderStateNative` | Do not call `SetStreamSource(null, 0)` — invalid for UP drawing | +| Duplicate `vtxCount` compile error | Was present in early source — remove the second declaration | +| Hook not firing | acclient.exe must be running and past login before injection | +| `ChangePortalMode` event (future) | Crashes Decal — never use (RynthCore note carried from NexTank) | + +--- + +## Current Status (v0.2) + +- [x] D3D9 EndScene hook stable +- [x] ImGui context, font texture, WndProc subclass working +- [x] ImGui demo window + RynthCore info panel rendering +- [x] Mouse/keyboard input forwarded; ImGui captures input when hovered +- [ ] Multi-viewport (needs IMGUI_ENABLE_VIEWPORTS cimgui build) +- [ ] NexTank UI panels ported to RynthCore +- [ ] Network message hooks +- [ ] World state / actions API diff --git a/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md b/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md new file mode 100644 index 0000000..bc0dbcc --- /dev/null +++ b/Changelog/2026-04-22-inno-installer-prereq-dotnet-x64.md @@ -0,0 +1,15 @@ +# Inno Setup — .NET 10+ Desktop (x64) prerequisite page (2026-04-22) + +## Summary + +`installer/RynthCore.iss` now includes a custom wizard page (after **Welcome**) that: + +- Detects .NET 10 in the 64-bit registry in **either** way: + - `HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\` (version folder major ≥ 10), or + - `HKLM\SOFTWARE\Microsoft\dotnet\InstalledManifests\x64\` — any subkey name containing `Manifest-10.` (e.g. `...Manifest-10.0.100` under **InstalledManifests\x64** in `regedit`). +- Offers **Open download page** (Microsoft .NET 10 download hub) and **Check again** after the user installs. +- **Disables Next** on 64-bit Windows until the runtime is present, so file copy cannot start without it. +- On **32-bit** Windows, skips the requirement (tools are x64-only; `RynthCore.exe` still installs). +- On **silent** install (`/SILENT`, `/VERYSILENT`), **skips** the page so automation is not blocked; the admin must pre-provision the x64 runtime for the editors. + +RynthCore.exe / Injector remain self-contained; this check is only for the bundled **x64** tool exes. diff --git a/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md b/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md new file mode 100644 index 0000000..5bd24ea --- /dev/null +++ b/Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md @@ -0,0 +1,18 @@ +# Changelog — Installer .NET 10 check + self-contained host fallback (2026-04-22) + +## Summary + +- **Inno (`RynthCore.iss`):** The prerequisite page for the x64 .NET 10+ Desktop/Loot-Monster tool chain now also treats a valid install as **HKLM64\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost** (and the parallel `SOFTWARE\Microsoft\dotnet\Setup\...` key when present) when **Version** is **10+**. This matches how the runtime advertises the shared host, not only `...\shared\Microsoft.WindowsDesktop.App\...` or `InstalledManifests` (SDK) entries. +- **Build-Installer (`Build-Installer.ps1`):** Launcher and Injector `dotnet publish` for the bundle add **`-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable`**. Self-contained apphosts should not roll forward to **%ProgramFiles%\dotnet\shared\...** when a matching **major** is bundled next to the executable. + +## Reason + +Users reported the app (or the installer) still “checking for .NET in the wrong place.” The registry under **Setup\InstalledVersions\x64\sharedhost** is a primary signal for a machine .NET host install. Separately, a self-contained build can still consult global locations unless **RollForward** is set to not roll to a **shared** host install. + +## Follow-up + +Rebuild the bundle with `Build-Installer.ps1 -Version ` and verify on a machine **without** a user-visible **WindowsDesktop.App** shared folder but **with** a normal .NET 10+ runtime (sharedhost) install. + +--- + +**Related assembly:** `RynthCore.App.Avalonia` **0.1.2** (Informational: `0.1.2-scd-rollforward-disable`). diff --git a/Changelog/2026-04-22-installer-previous-release-folder.md b/Changelog/2026-04-22-installer-previous-release-folder.md new file mode 100644 index 0000000..ca599b1 --- /dev/null +++ b/Changelog/2026-04-22-installer-previous-release-folder.md @@ -0,0 +1,12 @@ +# Changelog — Installer previous-release archive (2026-04-22) + +## Summary + +- **`installer\Build-Installer.ps1`:** When **`-Version`** is supplied and Inno Setup is about to run, if **`installer\previous-release\last-built-version.txt`** differs from that version and **`installer\Output\RynthBundle-Setup.exe`** exists, the existing setup is copied to **`installer\previous-release\RynthBundle-Setup-.exe`** before the new compile overwrites `Output\`. +- After a **successful** `ISCC` run, **`last-built-version.txt`** is rewritten to the new `-Version` string. +- **`.gitignore`:** `installer/previous-release/*.exe` so archived installers stay local; **`last-built-version.txt`** remains tracked (seeded at **0.4.1**). +- **`BUILD.md`:** Documents the behavior under the installer section. + +## Reason + +Keeps the last shipping bundle installer on disk when bumping **`-Version`**, without manual copies. diff --git a/Changelog/2026-04-22-launcher-injector-self-contained.md b/Changelog/2026-04-22-launcher-injector-self-contained.md new file mode 100644 index 0000000..d37979e --- /dev/null +++ b/Changelog/2026-04-22-launcher-injector-self-contained.md @@ -0,0 +1,17 @@ +# Launcher + Injector: self-contained publish (2026-04-22) + +## Problem + +`RynthCore.exe` and `RynthCore.Injector.exe` were built **framework-dependent**. On PCs without a global **.NET Desktop Runtime 10 (x86)**, Windows shows the standard apphost dialog (“You must install .NET to run this application”) — that is the OS host, not C# code in the app. + +## Change + +- **`installer/Build-Installer.ps1`:** `dotnet publish` for `RynthCore.App.Avalonia` and `RynthCore.Injector` now uses **`--self-contained true`** (still **win-x86**). The install layout carries the .NET host + runtime next to the apphosts; **no separate x86 runtime install** is required to run the launcher or injector from the game folder. +- **`installer/staging` prerequisites text:** `RynthCore-Prerequisites.txt` updated — x64 **only** for optional **LootEditor** / **MonsterEditor** (still FDD). +- **`installer/RynthCore.iss`:** Removed the Start Menu shortcut **“Install .NET Desktop Runtime (Download)”** so the primary experience does not push a global .NET install for the main app. +- **`BUILD.md`:** Aligned with the same story. +- **`RynthCore.App.Avalonia`:** Version **0.1.0 → 0.1.1** (informational tag `0.1.1-launcher-scd-installer`). + +## Tradeoff + +Installer and on-disk size grow (bundled .NET 10 x86 for two executables). This matches the request that the **app** not depend on a preinstalled runtime; only the **optional** x64 tools still document a separate download. diff --git a/Changelog/2026-04-22-minhook-preload-before-multiclient.md b/Changelog/2026-04-22-minhook-preload-before-multiclient.md new file mode 100644 index 0000000..76b9d38 --- /dev/null +++ b/Changelog/2026-04-22-minhook-preload-before-multiclient.md @@ -0,0 +1,12 @@ +# Changelog — MinHook preload before multi-client init (2026-04-22) + +## Summary + +- **EntryPoint:** `RynthCoreInit` now preloads `minhook.x86.dll` from the resolved engine directory **before** `MultiClientHooks.Initialize()` runs. +- **Reason:** Multi-client hooks call MinHook P/Invokes immediately; without an explicit `LoadLibrary` on the full path, Windows often searches from the **AC client** directory first, producing `Unable to load DLL 'minhook.x86.dll'` even when the file exists under `Runtime\`. The init thread’s later preload was too late for that first hook pass. +- **Build stamp:** `EntryPoint.BuildStamp` bumped to `2026-04-22-v55-minhook-before-multiclient`. + +## User-visible effect + +- Fewer spurious **“multi-client hook failed - Unable to load DLL 'minhook.x86.dll'”** lines when `minhook.x86.dll` is deployed next to the engine. +- Init thread still preloads MinHook (harmless duplicate load if already mapped). diff --git a/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md b/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md new file mode 100644 index 0000000..fb186ce --- /dev/null +++ b/Changelog/2026-04-22-net-prereq-launcher-matches-inno.md @@ -0,0 +1,16 @@ +# Changelog — Launcher .NET 10+ x64 probe matches Inno (2026-04-22) + +## Problem + +The installer’s prerequisite page used specific **HKLM64** rules for the **Loot/Monster** x64 FDD tools, while the launcher only reported **x86** self-contained **sidecar** files (`RynthCore.runtimeconfig.json` / `deps.json`). That was a different notion of “runtime” and was easy to confuse with the setup’s **registry** check. + +## Change + +- **`src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs`:** Implements the same three registry paths as **`installer/RynthCore.iss`**: `Microsoft.WindowsDesktop.App` 10+ folders, `InstalledManifests\x64` **manifest-10.**, and **`sharedhost` Version** 10+ under `dotnet\Setup` and `Microsoft\dotnet\Setup`. Uses **`RegistryView.Registry64`**. On 32-bit OS, returns “satisfied” (N/A) like Inno. +- **`LauncherHostDiagnostics`:** The activity line and `RynthCore-Launcher.log` now include a clear **x64 suite tools** line with the same result as setup, plus the official download URL when not detected. +- **`RynthCore.iss`:** Comment points maintainers to **`NetDesktopX64Prerequisite.cs`**. + +## Versions + +- **RynthCore.DesktopLog** `1.0.0` → **`1.0.1`** +- **RynthCore.App.Avalonia** `0.1.2` → **`0.1.3`** diff --git a/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md b/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md new file mode 100644 index 0000000..8c1e79d --- /dev/null +++ b/Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md @@ -0,0 +1,16 @@ +# RynthCore Engine v57 — plugin extra path dedupe and unload cleanup + +**Build stamp:** `2026-04-22-v57-plugin-extra-path-dedupe` + +## Problem + +When the same logical DLL appeared twice — typically `RynthCore.Plugin.RynthAi.dll` under `Runtime\Plugins\` and again as an **extra plugin path** (e.g. `C:\Games\Rynthcore\RynthCore.Plugin.RynthAi.dll`) — the loader staged both copies into the same per-session shadow directory using the **same file name**. The second `File.Copy(..., overwrite: true)` failed with *The process cannot access the file ... because it is being used by another process*, which cluttered logs and could confuse hot-reload behavior for plugins loaded afterward (e.g. **ub-Rythai** / `RynthCore.Plugin.UbRythai.dll`). + +## Changes + +1. **`PluginManager.LoadPluginsFromDisk`** — Skips an extra path when its file name (or canonical full path) was already loaded from the default plugins directory or from an earlier extra entry. +2. **`LoadedPlugin.ClearResolvedDelegates`** / **`PluginLoader.Unload`** — Clears resolved managed delegates before `FreeLibrary` so the native module reference count can drop cleanly on rescan. + +## User action + +If you intentionally need two different builds under the **same** DLL file name, remove the duplicate path from the launcher list or rename one DLL; the engine now loads at most one instance per file name per session. diff --git a/Changelog/2026-04-22-release-0.4.1.md b/Changelog/2026-04-22-release-0.4.1.md new file mode 100644 index 0000000..e2864ac --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.1.md @@ -0,0 +1,37 @@ +# Release notes — RynthBundle **0.4.1** (2026-04-22) + +## Installer + +- **Output:** `installer\Output\RynthBundle-Setup.exe` +- **App version (Inno Setup):** `0.4.1` (passed to `Build-Release-All.ps1` / `Build-Installer.ps1` via `-Version`). +- **Full pipeline:** `RynthCore.sln` **Release** build, then publish (launcher self-contained x86, engine NativeAOT x86, injector x86, RynthSuite plugins, LootEditor + MonsterEditor self-contained x64), staging, **ISCC** compile — completed successfully on this date. + +## Previous release (archived version label) + +- **Prior documented bundle version:** **0.4.0** (examples in `BUILD.md` before this release). Use **0.4.1** for new builds and release tagging going forward. + +## Highlights in this bundle + +### Security + +- **Tmds.DBus.Protocol** pinned to **0.21.3** where Avalonia pulled vulnerable **0.20.x** (versions below **0.21.3** on that package line; **NU1903**, [GHSA-xrw6-gwf8-vvr9](https://github.com/tmds/Tmds.DBus/security/advisories/GHSA-xrw6-gwf8-vvr9)). See `Changelog/2026-04-22-tmds-dbus-protocol-security.md`. + +### Engine build stamp + +- **`EntryPoint.BuildStamp`:** `2026-04-22-v56-tmds-dbus-protocol-0213` (identifies injected engine build at runtime). + +### Related detailed changelogs + +- `Changelog/2026-04-22-rynth-bundle-installer.md` — unified installer layout and staging behavior. +- `Changelog/2026-04-22-minhook-preload-before-multiclient.md` — MinHook preload ordering for multi-client hooks. + +## RynthSuite repo + +- Tools and plugins staged from sibling **`RynthSuite`** (or `-RynthSuiteRoot`). Suite-side dependency notes: `..\RynthSuite\Changelog\2026-04-22-tmds-dbus-protocol-security.md`. + +## Build command used + +```powershell +cd +.\Build-Release-All.ps1 -Version 0.4.1 -RynthSuiteRoot "\RynthSuite" +``` diff --git a/Changelog/2026-04-22-release-0.4.3-bundle.md b/Changelog/2026-04-22-release-0.4.3-bundle.md new file mode 100644 index 0000000..48dfd31 --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.3-bundle.md @@ -0,0 +1,6 @@ +# RynthBundle 0.4.3 (2026-04-22) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.3.exe` (copy also at `RynthBundle-Setup.exe` when the copy step succeeds). +- **Prior installer archived:** `installer\previous-release\RynthBundle-Setup-0.4.2.exe` (from last-built version **0.4.2** before this build). +- **Components:** RynthCore (launcher, engine, injector, `Runtime\` layout), RynthSuite plugins (e.g. RynthAi) + **LootEditor** and **MonsterEditor** under `Tools\`, and **ub-Rythai** (`RynthCore.Plugin.UbRythai`) in `Runtime\Plugins\` when the sibling `ub-Rythai` repo is present. +- **Build:** `Build-Release-All.ps1 -Version 0.4.3` at repo root (runs `dotnet build` then `installer\Build-Installer.ps1`). diff --git a/Changelog/2026-04-22-release-0.4.7-bundle.md b/Changelog/2026-04-22-release-0.4.7-bundle.md new file mode 100644 index 0000000..2c65117 --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.7-bundle.md @@ -0,0 +1,14 @@ +# RynthBundle 0.4.7 (2026-04-22) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.7.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.6**; prior bundle archived under `installer\previous-release\` when present; `last-built-version.txt` → **0.4.7** after a successful ISCC run with `-Version`. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present next to RynthCore. +- **Notable RynthAi in this line:** **0.6.8** — assembly / informational version bump for this distribution build (previous plugin line: **0.6.7**). +- **Launcher:** `LauncherHostDiagnostics.cs` — add missing `using System;` so `dotnet publish` of the Avalonia host succeeds (`AppContext`, `Environment`). +- **Build:** From the RynthCore repo root: + + ```powershell + .\Build-Release-All.ps1 -Version 0.4.7 + ``` + + With a non-default layout, pass **`-RynthSuiteRoot`** (and optionally **`-UbRythaiPluginProject`** / **`-SkipUbRythai`**) as documented in `Build-Release-All.ps1`. diff --git a/Changelog/2026-04-22-release-0.4.8.md b/Changelog/2026-04-22-release-0.4.8.md new file mode 100644 index 0000000..7fabe6a --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.8.md @@ -0,0 +1,28 @@ +# Release notes — RynthBundle **0.4.8** (2026-04-22) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.8.exe` (Inno **`OutputBaseFilename`** is versioned when **`-Version 0.4.8`** is passed to **`Build-Installer.ps1`**). +- **App version (Inno Setup):** `0.4.8`. +- **Pipeline:** launcher self-contained x86 (with **`RollForward=Disable`** on publish), engine NativeAOT x86, injector self-contained x86, **RynthSuite** `Plugins\RynthCore.Plugin.*`, **ub-Rythai** when present, LootEditor + MonsterEditor x64, staging, Inno Setup. + +## Highlights in this bundle + +- **.NET 10+ prerequisite (Loot/Monster tools):** `RynthCore.iss` also accepts **`HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost`** (and the parallel **`SOFTWARE\Microsoft\dotnet\Setup\...`** key) when **`Version`** is **10+**. See `Changelog/2026-04-22-installer-prereq-sharedhost-and-bundled-runtime-fallback.md`. +- **Launcher / injector publish:** `Build-Installer.ps1` passes **`-p:SelfContained=true -p:PublishSelfContained=true -p:RollForward=Disable`** for the bundled apphosts. +- **Launcher assembly:** `RynthCore.App.Avalonia` **0.1.2** (Informational: `0.1.2-scd-rollforward-disable`). + +## Build command used + +```powershell +cd "D:\asherons call-int code\RynthCore\installer" +.\Build-Installer.ps1 -Version 0.4.8 +``` + +## Previous bundle + +- **0.4.7** — prior **`last-built-version.txt`** before this build; see `installer\previous-release\` for archived **`RynthBundle-Setup.exe`** when the script bumps the version and the unversioned file was present. + +## Notes + +- Inno may emit: *Architecture identifier "x64" is deprecated* (harmless; substitute **`x64os`** / **`x64compatible`** is a follow-up for the **.iss** if desired). diff --git a/Changelog/2026-04-22-release-0.4.9.md b/Changelog/2026-04-22-release-0.4.9.md new file mode 100644 index 0000000..2e3e08f --- /dev/null +++ b/Changelog/2026-04-22-release-0.4.9.md @@ -0,0 +1,27 @@ +# Release notes — RynthBundle **0.4.9** (2026-04-22) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.9.exe` +- **App version (Inno Setup):** `0.4.9` +- **Pipeline:** `Build-Installer.ps1 -Version 0.4.9` — self-contained launcher/injector, NativeAOT engine + plugins, Loot/Monster x64 FDD, staging, Inno (same as **0.4.8**). + +## Highlights in this bundle + +- **x64 .NET 10+ probe parity:** Launcher uses **`RynthCore.DesktopLog.NetDesktopX64Prerequisite`** (registry checks aligned with `RynthCore.iss`); see `Changelog/2026-04-22-net-prereq-launcher-matches-inno.md`. +- **RynthCore.App.Avalonia** **0.1.3** · **RynthCore.DesktopLog** **1.0.1** + +## Build command used + +```powershell +cd "D:\asherons call-int code\RynthCore\installer" +.\Build-Installer.ps1 -Version 0.4.9 +``` + +## Previous bundle + +- **0.4.8** — `Changelog/2026-04-22-release-0.4.8.md` + +## Notes + +- Inno may show the **deprecated “x64”** architecture warning (see **0.4.8** release notes). diff --git a/Changelog/2026-04-22-rynth-bundle-installer.md b/Changelog/2026-04-22-rynth-bundle-installer.md new file mode 100644 index 0000000..224544d --- /dev/null +++ b/Changelog/2026-04-22-rynth-bundle-installer.md @@ -0,0 +1,27 @@ +# Changelog — RynthBundle unified installer (2026-04-22) + +## Summary + +- **Single installer output:** `installer\Output\RynthBundle-Setup.exe` (Inno Setup 6). +- **Build entry point:** repository root script `Build-Release-All.ps1` builds `RynthCore.sln` in Release, then runs `installer\Build-Installer.ps1`. +- **Bundled components:** + - RynthCore Avalonia launcher (self-contained x86), renamed to `RynthCore.exe` + - RynthCore Engine (NativeAOT x86) and native dependencies under `Runtime\` + - **RynthCore.Injector** (framework-dependent x86 publish) under `Runtime\` for manual CLI injection + - All RynthSuite `Plugins\RynthCore.Plugin.*` projects discovered under the sibling `RynthSuite` repo — published to `Runtime\Plugins\` and RynthAi DLL mirrored under `Suite\RynthAi\` + - **LootEditor** and **MonsterEditor** (self-contained x64) under `Tools\` with full publish trees (including `runtimes\` subfolders) + +## Installer script fixes + +- **Recursive staging:** self-contained and framework-dependent publish outputs that include subdirectories are now copied in full; previously only top-level files were copied, which broke tool publishing. +- **Injector:** included in the publish and staging steps so the bundle matches a full RynthCore deployment. + +## Documentation + +- `BUILD.md` updated to reference `RynthBundle-Setup.exe` and the root `Build-Release-All.ps1` flow. + +## Prerequisites (unchanged) + +- .NET SDK (matching project `TargetFramework`, e.g. .NET 10) and Visual Studio build prerequisites for NativeAOT where applicable +- [Inno Setup 6](https://jrsoftware.org/isdl.php) for compiling `installer\RynthCore.iss` +- `RynthSuite` as a **sibling** of `RynthCore` (same parent folder), or pass `-RynthSuiteRoot` to `Build-Installer.ps1` diff --git a/Changelog/2026-04-22-tmds-dbus-protocol-security.md b/Changelog/2026-04-22-tmds-dbus-protocol-security.md new file mode 100644 index 0000000..890c433 --- /dev/null +++ b/Changelog/2026-04-22-tmds-dbus-protocol-security.md @@ -0,0 +1,12 @@ +# Changelog — Tmds.DBus.Protocol security bump (2026-04-22) + +## Summary + +- **Packages:** Pinned **Tmds.DBus.Protocol** to **0.21.3** on projects that pull it transitively through Avalonia (Avalonia UI stack / FreeDesktop). +- **Reason:** NuGet audit **NU1903** — high severity [GHSA-xrw6-gwf8-vvr9](https://github.com/tmds/Tmds.DBus/security/advisories/GHSA-xrw6-gwf8-vvr9). Versions below **0.21.3** on this package line are affected; **0.21.3** is the maintained backport compatible with Avalonia 11.2.x. +- **Projects:** `RynthCore.App.Avalonia`, `RynthCore.Engine`. +- **Build stamp:** `EntryPoint.BuildStamp` set to `2026-04-22-v56-tmds-dbus-protocol-0213`. + +## User-visible effect + +- No functional change expected for normal Windows desktop use; dependency graph uses a patched protocol assembly and restores without the NU1903 advisory for these projects. diff --git a/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md b/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md new file mode 100644 index 0000000..9302462 --- /dev/null +++ b/Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md @@ -0,0 +1,13 @@ +# Changelog — Rynth bundle installer: .NET x64 prereq advisory only (2026-04-23) + +## Summary + +**`installer/RynthCore.iss`:** The post-Welcome **.NET 10+ (x64)** page for Loot/Monster tools is now **informational only**. **Next** stays enabled regardless of registry detection; copy and install always proceed. Copy and button text clarify that **`RynthCore.exe` / injector** remain self-contained. + +## Scope + +This policy applies to the **Rynth client / bundle installer** only. **UB-ILT / UBLoader** retains its own **UtilityBelt** net10 registry gate in **`FilterCore.LoadPluginAssembly`** (unchanged). + +## Related + +- **`RynthCore.DesktopLog.NetDesktopX64Prerequisite`** — unchanged; still mirrors the same registry paths for launcher log / activity alignment. diff --git a/Changelog/2026-04-23-launcher-host-diagnostics.md b/Changelog/2026-04-23-launcher-host-diagnostics.md new file mode 100644 index 0000000..57b202f --- /dev/null +++ b/Changelog/2026-04-23-launcher-host-diagnostics.md @@ -0,0 +1,18 @@ +# RynthCore launcher — host / runtime diagnostics + +Date: 2026-04-23 + +## Summary + +The Avalonia launcher (`RynthCore.App.Avalonia`, shipped as `RynthCore.exe` in the bundle) now logs **host resolution** details at startup: + +- **Activity panel:** one short line (`Host: … runtimeconfig=… deps=…`) so operators see sidecar status without opening log files. +- **Desktop log** (`RynthCore-Launcher.log`): multi-line block with `ProcessPath`, base directory, framework/OS/arch, CLR version, and presence of `RynthCore*.runtimeconfig.json` / `RynthCore*.deps.json` (including legacy `RynthCore.App.Avalonia.*` names for mismatch triage). + +## Why + +After renaming the published apphost to `RynthCore.exe`, mismatched host metadata filenames can cause false “install .NET” prompts. Sidecar logging makes that state obvious in the field. + +## Version + +- `RynthCore.App.Avalonia` NuGet-style `Version`: **0.1.0** (`InformationalVersion`: `0.1.0-launcher-host-diagnostics`). diff --git a/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md b/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md new file mode 100644 index 0000000..0615400 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.10-bundle-ub-rythai-ilt-banking.md @@ -0,0 +1,19 @@ +# RynthBundle 0.4.10 + +Date: 2026-04-23 + +## Summary + +Bundle refresh to ship **ub-Rythai 3.1.9** with UB-ILT-style **ILT mode** (`Auto` / `On` / `Off`), world-name auto list, manual banking override, and **banking** helpers (`/bank` refresh, balance parsing, transfers, optional auto-transfer). + +## Engine + +- `RynthCore.Engine` build stamp: `2026-04-23-v60-bundle-0410-ub-rythai-ilt-banking`. + +## Plugins + +- **RynthCore.Plugin.UbRythai** `3.1.9` — see `ub-Rythai/Changelog/Changelog-3.1.9-ilt-mode-and-banking.md`. + +## Installer + +- Run `installer\Build-Installer.ps1 -Version 0.4.10` to produce `RynthBundle-Setup-0.4.10.exe` (and canonical `RynthBundle-Setup.exe` copy when not locked). diff --git a/Changelog/2026-04-23-release-0.4.10.md b/Changelog/2026-04-23-release-0.4.10.md new file mode 100644 index 0000000..cc0770c --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.10.md @@ -0,0 +1,20 @@ +# Release notes — RynthBundle **0.4.10** (2026-04-23) + +## Installer + +- **Output:** `installer\Output\RynthBundle-Setup-0.4.10.exe` +- **Inno app version:** `0.4.10` +- **Command:** `Build-Installer.ps1 -Version 0.4.10` + +## Highlights + +- **RynthAi** **0.6.9** (staged under `Runtime\Plugins\`) — VirindiTank dashboard import activates copied loot and merges text **MyMonsters** `.usd` for the current character; see `RynthSuite/Changelog/2026-04-23-rynthai-vt-import-active-character.md`. +- **RynthCore installer:** .NET x64 prerequisite page remains **advisory** (Next never blocked); see `Changelog/2026-04-23-installer-dotnet-prereq-advisory-only.md`. + +## Previous bundle + +- **0.4.9** — `Changelog/2026-04-22-release-0.4.9.md` + +## Notes + +- Inno may emit the **deprecated “x64”** architecture warning (non-fatal). diff --git a/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md b/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md new file mode 100644 index 0000000..5db22dd --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.11-runtimeconfig-rename-fix.md @@ -0,0 +1,32 @@ +# RynthBundle 0.4.11 + +Date: 2026-04-23 + +## Summary + +Fix launcher runtime detection so an installed .NET 10 runtime is correctly used instead of repeatedly showing a runtime-install prompt. + +## Root Cause + +The installer staging step renamed `RynthCore.App.Avalonia.exe` to `RynthCore.exe`, but did not rename: + +- `RynthCore.App.Avalonia.runtimeconfig.json` +- `RynthCore.App.Avalonia.deps.json` + +That mismatch can break host runtime resolution for the renamed apphost. + +## Fix + +Updated `installer/Build-Installer.ps1` so staging now renames launcher host metadata with the apphost: + +- `RynthCore.App.Avalonia.runtimeconfig.json` -> `RynthCore.runtimeconfig.json` +- `RynthCore.App.Avalonia.deps.json` -> `RynthCore.deps.json` + +## Build Stamp + +- `RynthCore.Engine` build stamp: `2026-04-23-v61-bundle-0411-runtime-detection-fix` + +## Build + +- `Build-Installer.ps1 -Version 0.4.11` +- Output: `installer/Output/RynthBundle-Setup-0.4.11.exe` diff --git a/Changelog/2026-04-23-release-0.4.2.md b/Changelog/2026-04-23-release-0.4.2.md new file mode 100644 index 0000000..8cc4c32 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.2.md @@ -0,0 +1,41 @@ +# Release notes — RynthBundle **0.4.2** (2026-04-23) + +## Installer + +- **Primary output:** `installer\Output\RynthBundle-Setup-0.4.2.exe` (when `-Version 0.4.2` is passed, `Build-Installer.ps1` sets Inno **`OutputBaseFilename`** to a versioned name so the compile succeeds even if `RynthBundle-Setup.exe` is locked by another process). +- **Canonical copy:** the script **best-effort** copies that file to `installer\Output\RynthBundle-Setup.exe` when possible (skip if the destination is open). +- **App version (Inno Setup):** `0.4.2` (pass `-Version 0.4.2` to `Build-Release-All.ps1` / `Build-Installer.ps1`). +- **Pipeline:** `RynthCore.sln` **Release**, then publish (launcher self-contained x86, engine NativeAOT x86, injector x86, **RynthSuite** `Plugins\RynthCore.Plugin.*`, **ub-Rythai** `RynthCore.Plugin.UbRythai` when the sibling `ub-Rythai` repo is present, LootEditor + MonsterEditor x64), staging, Inno Setup. + +## Highlights in this bundle + +### ub-Rythai (Utility Belt–style RynthCore plugin) + +- **`installer\Build-Installer.ps1`** now discovers **`..\ub-Rythai\RynthCore.Plugin.UbRythai\RynthCore.Plugin.UbRythai.csproj`** (same parent folder as `RynthCore` and `RynthSuite`), publishes it with the other NativeAOT plugins, and stages **`RynthCore.Plugin.UbRythai.dll`** into **`Runtime\Plugins\`**. +- **`-SkipUbRythai`** omits that step (for environments without the checkout). **`-UbRythaiPluginProject`** overrides the project path. +- Plugin assembly version for this release line: **3.1.8** (`ub-Rythai/RynthCore.Plugin.UbRythai/RynthCore.Plugin.UbRythai.csproj`). + +### RynthCore engine + +- **Build stamp:** `2026-04-22-v57-plugin-extra-path-dedupe` — skips duplicate extra plugin paths that would re-stage the same DLL name and break hot reload; clears export delegates before `FreeLibrary` on unload. See `Changelog/2026-04-22-plugin-extra-path-dedupe-hot-reload.md`. + +## Build command used + +```powershell +cd +.\Build-Release-All.ps1 -Version 0.4.2 +``` + +With a non-default RynthSuite or ub-Rythai layout: + +```powershell +.\Build-Release-All.ps1 -Version 0.4.2 -RynthSuiteRoot "D:\src\RynthSuite" -UbRythaiPluginProject "D:\src\ub-Rythai\RynthCore.Plugin.UbRythai\RynthCore.Plugin.UbRythai.csproj" +``` + +## Previous bundle + +- **0.4.1** — `Changelog/2026-04-22-release-0.4.1.md`. When `-Version` bumps, `Build-Installer.ps1` may archive the prior `RynthBundle-Setup.exe` under `installer\previous-release\` (see `Changelog/2026-04-22-installer-previous-release-folder.md`). + +## GitHub Actions + +- **`.github/workflows/release.yml`** passes **`-SkipUbRythai`** until the workflow clones the **ub-Rythai** repo alongside RynthSuite (local `Build-Release-All.ps1` includes ub-Rythai when `..\ub-Rythai\` is present). Release artifact filename is **`RynthBundle-Setup-.exe`**. diff --git a/Changelog/2026-04-23-release-0.4.7-bundle.md b/Changelog/2026-04-23-release-0.4.7-bundle.md new file mode 100644 index 0000000..0103817 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.7-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.7 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.7.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.6**; prior bundle **0.4.6** archived under `installer\previous-release\`; `last-built-version.txt` → **0.4.7**. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable RynthAi in this line:** **0.6.7** — missile auto-combat: correct launcher vs ammo detection (crossbow name no longer matches “bolt” ammo heuristic), skip loose ammo when resolving wielded launcher kind, wield slot fallback via `CurrentWieldedLocation`. +- **Build:** `Build-Release-All.ps1 -Version 0.4.7` from the RynthCore repo root. diff --git a/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md b/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md new file mode 100644 index 0000000..a58cebd --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.8-bundle-installer-streamline.md @@ -0,0 +1,8 @@ +# RynthBundle 0.4.8 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.8.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.7**; prior bundle archived under `installer\previous-release\` when `-Version` differs; `last-built-version.txt` → **0.4.8**. +- **Installer streamlining:** + - Removed the duplicate **`Suite\RynthAi\RynthCore.Plugin.RynthAi.dll`** mirror; the plugin ships only under **`Runtime\Plugins\`**. User data and optional manual DLL copies remain under **`C:\Games\RynthSuite\RynthAi\`** (`[Dirs]` in `RynthCore.iss`). + - **Engine `cimgui`:** one shipped native next to `RynthCore.Engine.dll` — **`RynthCore.cimgui.dll`** only. MSBuild copies the prefixed name, then deletes redundant **`cimgui.dll`** / **`Native\*.cimgui*`** drops from ImGui.NET / ILC so the publish folder is not bloated. +- **Build:** `Build-Release-All.ps1 -Version 0.4.8` from the RynthCore repo root. diff --git a/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md b/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md new file mode 100644 index 0000000..20996b3 --- /dev/null +++ b/Changelog/2026-04-23-release-0.4.9-runtime-fdd-bundle.md @@ -0,0 +1,9 @@ +# RynthBundle 0.4.9 (2026-04-23) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.9.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.8**; prior bundle archived under `installer\previous-release\`; `last-built-version.txt` -> **0.4.9**. +- **Size reduction (major):** launcher and Suite tools are now **framework-dependent** instead of self-contained: + - `RynthCore.App.Avalonia` published `win-x86 --self-contained false` + - `RynthCore.LootEditor` and `RynthCore.MonsterEditor` published `win-x64 --self-contained false` +- **Runtime link only (no bundled download):** installer now includes a Start Menu shortcut to the official .NET runtime page and ships `RynthCore-Prerequisites.txt` in the install root with direct runtime guidance. +- **Build:** `Build-Release-All.ps1 -Version 0.4.9` from the RynthCore repo root. diff --git a/Changelog/2026-04-24-release-0.4.4-bundle.md b/Changelog/2026-04-24-release-0.4.4-bundle.md new file mode 100644 index 0000000..38aab8e --- /dev/null +++ b/Changelog/2026-04-24-release-0.4.4-bundle.md @@ -0,0 +1,6 @@ +# RynthBundle 0.4.4 (2026-04-24) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.4.exe` (and `RynthBundle-Setup.exe` when the canonical copy step succeeds). +- **Prior version archived:** the previous `installer\Output\RynthBundle-Setup.exe` (**0.4.3**) was copied to `installer\previous-release\RynthBundle-Setup-0.4.3.exe` at build time; `last-built-version.txt` now records **0.4.4**. +- **Bundle contents (same as prior full bundles):** RynthCore (launcher, engine, injector, `Runtime\` tree); all **RynthSuite** `Plugins\RynthCore.Plugin.*` (e.g. RynthAi) plus **LootEditor** and **MonsterEditor** under `Tools\`; **ub-Rythai** (`RynthCore.Plugin.UbRythai`) from the sibling `ub-Rythai` repository. +- **Notable in this line:** RynthSuite **RynthCore.Plugin.RynthAi** is built at the current **0.6.4** line (suite tool path + IL3000 handling). Build entry point: `Build-Release-All.ps1 -Version 0.4.4`. diff --git a/Changelog/2026-04-25-desktop-rolling-logs.md b/Changelog/2026-04-25-desktop-rolling-logs.md new file mode 100644 index 0000000..49d4699 --- /dev/null +++ b/Changelog/2026-04-25-desktop-rolling-logs.md @@ -0,0 +1,8 @@ +# Desktop log rotation (2026-04-25) + +- New library **`RynthCore.DesktopLog`** with **`DesktopRollingLog`**: all lines append to **`Desktop\\{fileStem}.log`**. When a file would exceed **10 MB**, the current file is moved to **`Desktop\\RynthLogs\\`**, named **`{fileStem}-roll-yyyyMMdd-HHmmssfff.log`**, then a new active file is created. For each **file stem** and each **local calendar day**, at most **10** such rolled files are kept (oldest for that day deleted first so the new segment fits the cap). +- **Three log stems in use** + - **`RynthCore`** (was `RynthCore.log` only) — in-process engine output, same path as before. + - **`RynthCore-Launcher`** — one line on Avalonia app startup; writes **`RynthCore-Launcher.log`**, same rotation. + - **`RynthCore-Injector`** — injector console lines to **`RynthCore-Injector.log`**, same rotation; success message references all three and the `RynthLogs` archive folder. +- **Build stamp** updated to `2026-04-25-v58-desktop-log-rotate`. diff --git a/Changelog/2026-04-25-release-0.4.5-bundle.md b/Changelog/2026-04-25-release-0.4.5-bundle.md new file mode 100644 index 0000000..313fda3 --- /dev/null +++ b/Changelog/2026-04-25-release-0.4.5-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.5 (2026-04-25) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.5.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Prior bundle:** `installer\previous-release\` archives the previous `RynthBundle-Setup.exe` when the version bumps; `last-built-version.txt` records **0.4.5**. +- **Contents:** Same bundle layout as prior releases — RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable engine / host changes in this line:** desktop **log rotation** (10 MB active, up to 10 rolled files per day per log under `Desktop\RynthLogs`), three stems (`RynthCore.log`, `RynthCore-Launcher.log`, `RynthCore-Injector.log`), build stamp **v58**. +- **Build:** `Build-Release-All.ps1 -Version 0.4.5` from the RynthCore repo root. diff --git a/Changelog/2026-04-26-release-0.4.6-bundle.md b/Changelog/2026-04-26-release-0.4.6-bundle.md new file mode 100644 index 0000000..2c03da3 --- /dev/null +++ b/Changelog/2026-04-26-release-0.4.6-bundle.md @@ -0,0 +1,7 @@ +# RynthBundle 0.4.6 (2026-04-26) + +- **Setup:** `installer\Output\RynthBundle-Setup-0.4.6.exe` (and `RynthBundle-Setup.exe` when the canonical copy succeeds). +- **Version bump:** from **0.4.5**; prior bundle archived under `installer\previous-release\`; `last-built-version.txt` → **0.4.6**. +- **Bundle:** RynthCore (launcher, engine, injector), RynthSuite plugins + tools, **ub-Rythai** when the sibling repo is present. +- **Notable RynthAi in this line:** **0.6.6** — ImGui Monsters table `WidthFixed | NoResize` fix (assert when opening RynthAi UI). +- **Build:** `Build-Release-All.ps1 -Version 0.4.6` from the RynthCore repo root. diff --git a/Changelog/2026-10-04-aelrynth-sync.md b/Changelog/2026-10-04-aelrynth-sync.md new file mode 100644 index 0000000..eea0256 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-sync.md @@ -0,0 +1,12 @@ +# Changelog — 2026-10-04 (upstream snapshot) + +## feat: port aelrynth git snapshot onto GitHub history + +Applied `upstream/main` (`9b5e276`, RynthCore as of 2026-09-27, release 2026.9.27.2) as a new commit on top of BlankenshipG `main`. Histories are unrelated, so this is a tree overlay — not a fast-forward or force-replace. + +- Added aelrynth-only product code: Loader, StatusAgent, HookManifest/HookResolver, DComp overlay, SEH trampoline, signed updater, vendor/trade API (PluginContract +16 functions) +- Overlapping engine/launcher files taken from aelrynth (newer than origin 2026-04-25) +- Kept unique origin-only trees: `Plugins/RynthAi/` (Decal-era), `Plugins/RynthCore.Plugin.RynthAi/` stub, `AGENTS.md`/`CLAUDE.md`, `ImGuiController.cs`, `OverlayFrameBuffer.cs` +- Re-applied dead-link fixes: installer + CI clone URLs point at aelrynth.com / `${{ github.repository_owner }}` siblings + +No PluginSdk version bump (still 0.2.0 on both trees). Packaged aelrynth installer (2026.10.4.3) is newer than this git tip. diff --git a/Changelog/2026-10-04-aelrynth-urls.md b/Changelog/2026-10-04-aelrynth-urls.md new file mode 100644 index 0000000..8670c97 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-urls.md @@ -0,0 +1,9 @@ +# Changelog — 2026-10-04 (docs/CI) + +## fix: point dead tombohar URLs at aelrynth / sibling fork + +- `installer/RynthCore.iss` `AppPublisherURL` → https://aelrynth.com/rynth.html +- `.github/workflows/release.yml` sibling clone → `github.com/${{ github.repository_owner }}/RynthSuite` +- Canonical public git remains https://aelrynth.com/git/RynthCore.git (see product page) + +No engine/SDK version bump (docs and CI URL-only). diff --git a/Changelog/2026-10-04-char-and-hub-launcher-buttons.md b/Changelog/2026-10-04-char-and-hub-launcher-buttons.md new file mode 100644 index 0000000..dbda06e --- /dev/null +++ b/Changelog/2026-10-04-char-and-hub-launcher-buttons.md @@ -0,0 +1,26 @@ +# Launcher buttons: "ILT Hub" renamed to "Char", new "Hub" button (2026-10-04) + +RynthAi 0.6.25, plus an engine change to the Avalonia RynthAi panel. + +## What changed + +The floating HUDs were hard to find: they start hidden and were only reachable through +Settings > Inventory Management or chat commands. Both dashboards now have a launcher for them. + +| Dashboard | Char | Hub | +|-----------|------|-----| +| Avalonia RynthAi panel | Opens the ILT Hub (`/ra hub show`) | Left-click shows/hides the Mini Remote (`/ra remote`). Right-click opens the Inventory HUDs setup window (`/ra huds`). | +| ImGui dashboard launcher grid | Toggles the ILT Hub window. Only shown on ILT/ACECustom worlds, as before. | Toggles the Mini Remote. Lit while it is shown. Shown on every world. | + +- Only the button labels changed. The ILT Hub window title, `/ra hub` and the `[ILT Hub]` chat + messages are unchanged. +- In the ImGui grid, Hub uses the third cell of the last row, which was empty. + +## Files + +- Engine `UI/Panels/RynthAiPanel.cs`: "ILT Hub" launcher renamed to "Char"; new "Hub" launcher + (row 3, column 2) with a right-click handler. +- `LegacyUi/LegacyDashboardRenderer.cs`: "Char" label, "Hub" grid button, and the + `MiniRemoteVisible` / `SetMiniRemoteVisible` hooks. +- `RynthAiPlugin.cs`: wires the hooks to the HUD state at login and clears them at logout. +- Version 0.6.24 → 0.6.25. diff --git a/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md new file mode 100644 index 0000000..1f5444a --- /dev/null +++ b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md @@ -0,0 +1,70 @@ +# Engine: object identity seeded at create, native crash logger made fatal-only + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** next installer (2026.10.4.10; previous 2026.10.4.9) + +## 1. Names and types readable from the moment an object is created + +### Problem +Off-thread plugin reads (`TryGetObjectName` / `TryGetItemType`) are served only from the +main-thread identity snapshot, rebuilt every 500 ms. For about 10 s after login that snapshot +resolves almost no names (`[SnapshotDiag] ... names=1`) because qualities aren't populated yet. +The plugin's quick classify retries finish in about 10 ms, so every login-burst object without a +position (pack contents) gave up: about 200 `CLASSIFY-GIVEUP` lines per login, and items stayed +unclassified until a slow retry caught them. + +### Fix +- `CreateObjectHooks` now passes the server's `PublicWeenieDesc` to the new + `ClientObjectHooks.SeedIdentityFromCreate`. It runs on AC's main thread before the plugin is + told about the object. + - It reads `_name` (PWD +4) and `_type` (PWD +56). These are the same offsets the existing + PWD-direct fallbacks use on the embedded copy. + - Every read is validated: the descriptor must start with an acclient.exe vtable, and the + string read is page-checked and length-capped. +- Off-thread lookups use these create seeds when the snapshot has no entry. For types, the seed + is also used when the snapshot says `0` (qualities not loaded yet). The snapshot still wins + whenever it has a real value. +- Seeds are removed in `DeleteObjectHooks`. A 16,384-entry cap clears them if a delete is ever + missed. +- Diagnostics: `[CreateSeed] #1..5` sample lines, plus one + `create-descriptor identity seeds active` summary, so the first in-game log confirms the + offsets. +- Position is unchanged: the position snapshot is taken every 100 ms and already worked at login. + +## 2. Native crash logger: fatal crashes only (`RynthCore.SehTrampoline.dll` v2) + +### Problem +`CrashVeh` logged **every** first-chance access violation, including ones AC or our own `SEH_*` +wrappers catch. Its stack sweep then read 4,096 slots past ESP regardless of where the stack +ended, faulted off the top of the stack, and logged that fault too +(`SehTrampoline.dll+0x13E8`, dataAddr on a page boundary). Every run began with 3–4 noise +entries, and with the 24-entry cap a real fatal crash could find the log already full. + +### Fix (`native/SehTrampoline/SehTrampoline.c`) +- **Stack sweep bounded** to `[Esp, NtCurrentTeb()->NtTib.StackBase)`, and skipped when ESP + isn't inside the thread's stack. +- **Per-thread guards:** + - `t_inLogger`: faults raised while the logger runs are never logged. + - `t_sehDepth`: every `SEH_*` wrapper brackets its call, so AVs those wrappers catch are + ignored. +- **Fatal-only routing:** + - **Unhandled-exception filter** (`SetUnhandledExceptionFilter`, chained to the previous + filter, with a re-entry guard): an unhandled exception is written immediately as FATAL. + - **AVs inside NativeAOT code** (engine/plugins, detected via the `DotNetRuntimeDebugHeader` + export) are written immediately. The runtime fail-fasts on these through + `RaiseFailFastException`, which bypasses every filter. 0xC0000602 / 0xC0000409 are also + written immediately. + - **Every other first-chance AV** (acclient.exe, drivers, DINPUT8…) is formatted into an + 8-slot in-memory ring. It is written only if the process then dies: through the filter, or + at `ExitProcess` (DllMain detach) if it happened within the last 30 s. That keeps + crashes AC's own handler swallows. AVs AC handles and survives never reach the file. +- Separate caps: 16 immediate records and 8 fatal records per run. Formatting is now + bounds-checked (8 KB per record). +- New export `RC_SehTrampolineVersion()` returns 2. The engine logs + `native crash logger installed (v2, fatal-only)` at startup. + +## Build +- `Build-SehTrampoline.ps1`: compiles clean (MSVC 14.50, x86, /W3). +- `RynthCore.Engine` Release build succeeds (no new warnings). +- Not yet verified in game. diff --git a/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md b/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md new file mode 100644 index 0000000..48f25dc --- /dev/null +++ b/Changelog/2026-10-04-dashboard-map-and-lua-buttons.md @@ -0,0 +1,34 @@ +# Avalonia RynthAi panel: Map and Lua buttons (2026-10-04) + +Engine `RynthAiPanel` plus RynthAi 0.6.21. Ships in the next installer after 2026.10.4.16. + +## Problem + +The right halves of the split launcher buttons, **Lua** (next to Meta) and **Map** (next to +Nav), had no click handler, so they did nothing. Both windows are ImGui windows inside +RynthAi, and in Avalonia mode RynthAi's overlay render path never drew either of them. + +There is no separate RynthLua plugin: the Lua Scripts editor is RynthAi's `LegacyLuaUi`, +controlled by `DashWindows.ShowLua`. So the Lua button follows the same pattern as Map and +the ILT Hub button. + +## Engine (`UI/Panels/RynthAiPanel.cs`) + +- **Map** sends the remote command `map toggle`, and **Lua** sends `lua toggle`. Both go through + `RynthPluginApplyRemoteCommand`, the same path as the ILT Hub button. Both buttons have tooltips. +- `AddSplitLauncher` now returns its two half buttons. + +## RynthAi 0.6.21 + +- New remote commands and chat commands `/ra map [show|hide]` and `/ra lua [show|hide]`. With no + argument they toggle. They go through `HandleWindowCommand` to `LegacyDashboardRenderer.SetDungeonMapVisible` / + `SetLuaWindowVisible`, which persist the choice and print a chat confirmation. Turning the map on + while outdoors says it will appear indoors. Both commands are listed in the `/ra` help. +- `OnRenderOverlay` (Avalonia mode) now calls `RenderMapWindow(includeRadarAndChat: false)`. + It draws only the dungeon map, because the Avalonia Radar panel and RynthChat already exist. + ImGui-shell mode still draws all three. +- `RenderOverlayWindows` now also draws the Lua Scripts editor. Opening it rescans the + `LuaScripts` folder. +- Fix: the dungeon map would not reopen after being closed with its title-bar X (its own `_open` + flag stayed false and closed it again on the same frame) until you went outdoors and back. + `DungeonMapUi.Render` now reopens whenever `ShowDungeonMap` is set. diff --git a/Changelog/2026-10-04-floating-huds.md b/Changelog/2026-10-04-floating-huds.md new file mode 100644 index 0000000..f29351f --- /dev/null +++ b/Changelog/2026-10-04-floating-huds.md @@ -0,0 +1,93 @@ +# Floating HUDs: item count HUD, Mini Remote, quest favorites (2026-10-04) + +RynthAi 0.6.23, plus an engine Settings button. Ships in the next installer after 2026.10.4.17. + +## What changed + +Four new floating windows, modelled on UtilityBelt's Item Hud, Mini Remote and quest +favorites. They are ordinary ImGui windows. You can dock them, undock them, or drag them +outside the AC window, because the engine has docking and multi-viewport enabled. Each HUD +remembers its own position. + +| Window | Controlled from | Command | +|--------|-----------------|---------| +| Inventory HUDs (setup) | Advanced Settings > Inventory Management > **Inventory HUDs...**, and the same button in the Avalonia Settings panel | `/ra huds [show\|hide]` | +| Item count HUD | Inventory HUDs setup window | `/ra itemhud [show\|hide]` | +| Mini Remote | Inventory HUDs setup window | `/ra remote [show\|hide]` | +| Quest favorites HUD | ILT Hub > Character > Quest tracker | `/ra quests favhud [show\|hide]` | +| Quests (pop-out tracker) | ILT Hub quest tracker **Pop out** button | `/ra quests window [show\|hide]` | + +Running a command without `show` or `hide` toggles the window. + +### Item count HUD + +- Shows one row per pinned item: the item's icon (read from portal.dat) and how many you + carry, with stacks added up across all packs. The count turns red at 0. Names are optional. +- Right-click the HUD to show names, lock its position, change the icon size (12–48 px), + open the setup window, or hide it. + +### Mini Remote + +- **Stats** (ILT-like worlds): session time, plus XP, Luminance, kills, coins and pyreals per hour. + **Reset XP** restarts the session rates. **Report** prints a summary to local chat. +- **Pet**: the essence that is out ("Out" / "Healing"), or the next combat essence + ("Ready" / "Empty"). +- **Item gems**: a 5×6 grid of item slots. Click a slot to use that item; the slot dims when + you carry none. Right-click a slot to assign the selected item or clear it. +- **Toggles**: Macro, Combat, Buff, Nav, Loot, Meta, Pet (summon pets). +- **Bank** (ILT-like worlds): P, Lum, LK, MK, EC, WE from the ILT Hub bank tracker. +- **Rebuff**: FB (force rebuff) and CFB (cancel force rebuff). +- Right-click the window background to hide sections, lock its position, open the setup + window, or hide it. + +### Inventory HUDs setup window + +- Show/hide the item HUD (with or without names) and the Mini Remote. +- **Scan pack**, **Add from inventory** (pins the selected item), **Drop missing** (unpins + items you no longer carry). +- An **On HUD** list (Up/Down to reorder) and a filterable **Not on HUD** list of everything in + your pack, with `<` / `>` to move items between them. Double-click an item in Not on HUD to + pin it. +- Mini Remote slot picker with **Set** (from the selected item), **Clear** and **Refresh**. + +Item HUD and Mini Remote settings are saved per character in `huds.json`. + +### Quest favorites + +- The ILT Hub quest tracker has a new star column. Click `*` to favourite a quest. + **Favorites only** filters the table to starred quests. +- **Show floating favorites HUD** opens a small HUD listing starred quests, with ready / + time-left. Right-click it to lock it, open the quest tracker, refresh `/myquests`, or hide it. +- **Pop out** moves the quest tracker into its own "Quests" window. Closing that window docks + it back into the Hub. +- Favorites and HUD flags are saved per character in `ilt-hub.json` (`Character.QuestFavorites`). + +## Not carried over from UtilityBelt + +These UtilityBelt Mini Remote and Quests features were left out: + +- Storm, Chat XL, Guardian/Translate, the profile combos and the Fellow toggle. RynthAi has no + equivalent systems for these yet. +- The L / LumS / KillL / PassL / C / Conv stat cells. +- The quest rewards editor. + +## Files + +- New `Huds/` folder: + - `HudController.cs`: pack scan, pump-thread actions, commands. + - `HudState.cs`: settings and `huds.json` store. + - `HudIconCache.cs`: decodes portal.dat icons and uploads D3D9 textures. + - `DxtUtil.cs`: DXT decoder. + - `HudDraw.cs`, `ItemCountHud.cs`, `MiniRemoteHud.cs`, `HudSetupUi.cs`. +- `IltHub/IltQuests.cs`: favorites, favorites HUD, pop-out window. +- `IltHub/IltHubState.cs`, `IltHubStore.cs`: quest favorite fields. +- `IltHub/IltHubUi.cs`, `IltHubController.cs`: floating window rendering and the `quests` verbs. +- `IltHub/IltSessionRates.cs`: `RateSummary` for the Mini Remote. +- `IltHub/IltPets.cs`: Mini Remote pet line. +- `LegacyUi/LegacyAdvancedSettingsUi.cs`, `LegacyDashboardRenderer.cs`: Inventory HUDs button. +- `RynthAiPlugin.cs`, `RynthAiCommands.cs`: wiring and `/ra` help. +- `Diagnostics/RynthLog.cs`: new `Huds` log category. +- Engine: + - `UI/Panels/SettingsPanel.cs`: Inventory HUDs button in Inventory Management. + - `UI/Panels/RynthAiPanel.cs`: `SendRynthAiCommand` helper. +- RynthAi version 0.6.22 → 0.6.23. diff --git a/Changelog/2026-10-04-full-installer-2026.10.4.2.md b/Changelog/2026-10-04-full-installer-2026.10.4.2.md new file mode 100644 index 0000000..7c63ef3 --- /dev/null +++ b/Changelog/2026-10-04-full-installer-2026.10.4.2.md @@ -0,0 +1,68 @@ +# RynthCore 2026.10.4.2: full RynthCore + RynthSuite installer + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.2.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.1` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.1.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`), based on `fix/tmds-dbus-advisory` +**Bundled RynthSuite:** RynthAi `0.5.3`, Loot Editor, Monster Editor (from RynthSuite `feat/ilt-hub`) + +## Why: the launcher would not start + +On 2026-10-04 an old **RynthBundle 0.4.7** installer was run over the 2026.10.3.4 install. It replaced +`RynthCore.App.Avalonia.dll` with the 0.4.x build, which needs `RynthCore.DesktopLog.dll`, but left the newer +`RynthCore.App.Avalonia.deps.json`, which does not list it. The renamed apphost (`RynthCore.exe`) loads exactly +what the deps.json lists, so .NET failed at startup with `FileNotFoundException: RynthCore.DesktopLog` +(Event Log, .NET Runtime 1026). The new installer fixes such an install in place (see **Cleanup** below). + +## One installer, two folders you choose + +- **Wizard pages:** + - **Select Destination Location** picks the RynthCore folder (default `C:\Games\RynthCore`). + - **Select Components** offers Full, RynthCore only, or Custom. RynthCore is always installed; RynthAi and the + Monster Editor are optional. + - **Select RynthSuite Location** picks the RynthSuite folder. It defaults to a `RynthSuite` folder next to + the RynthCore folder you picked, or the folder used last time. The page is skipped when no Suite component is selected. +- **Silent installs:** `RynthCore-Setup-2026.10.4.2.exe /SILENT /DIR="D:\Games\RynthCore" /SUITEDIR="D:\Games\RynthSuite"`. + Without `/SUITEDIR` the Suite goes next to `/DIR`, or to the previously used folder. +- **Registry:** both folders are written to `Software\Rynth` (`CoreDir`, `SuiteDir`). That is HKCU for per-user installs + and HKLM for all-users installs. All of RynthCore and RynthSuite now read them. +- **Plugin auto-registration:** the installer leaves `PendingPluginRegistration` with the RynthAi DLL path. On the next + start the launcher adds it to the Plugins list (replacing any stale entry with the same file name whose file is gone), + syncs `engine.json` and clears the value. A fresh install therefore loads RynthAi with no manual setup. +- **Shortcuts:** RynthCore, Loot Editor, Monster Editor, RynthSuite folder, Uninstall, and an optional desktop icon. + +### Cleanup of older layouts +Before copying, the installer deletes leftovers from 0.4.x and RynthBundle installs in the RynthCore folder: +root `*.dll`/`*.json`/`*.pdb`, `RynthCore.App.Avalonia.exe`, old `Runtime\*.dll`/`*.json`, `Runtime\RynthCore.Injector.exe` +and `Runtime\Plugins\`. Then it lays down a complete, matching set. User data (`Logs`, settings in `%APPDATA%\RynthCore`, +everything under `\RynthAi`) is never touched, and the RynthSuite data folders survive an uninstall. + +## Code: no more hard-coded `C:\Games\...` + +New `src/RynthCore.App/RynthInstallPaths.cs`, linked into the launcher, engine, loader, injector and status agent. +It resolves the folders in this order: `RYNTHCORE_DIR`/`RYNTHSUITE_DIR` environment variables, then HKCU, then HKLM +(32-bit view), then the old `C:\Games\...` defaults. It uses a direct `RegGetValueW` P/Invoke, so it is NativeAOT-safe. +The engine resolves it on its init worker, never under the loader lock. + +| Was | Now | +|---|---| +| `C:\Games\RynthCore\Logs` (launcher, loader, injector, engine) | `\Logs` | +| `C:\Games\RynthCore\AcClient\acclient.exe` (injector) | `\AcClient\acclient.exe` | +| `C:\Games\RynthSuite\RynthAi\imgui.ini`, MetaFiles | `\RynthAi\...` | +| Status agent defaults | derived from the resolved folders | + +## Build script (`installer\Build-Installer.ps1`) +- **Publishes:** launcher, Engine, Loader, the RynthAi plugin, the Loot Editor, and now the **Monster Editor** + (self-contained win-x86). +- **Staging:** RynthCore goes to `staging\core`, RynthSuite to `staging\suite\RynthAi` (plugin plus `MonsterEditor\`). +- **Versions:** the RynthAi plugin is no longer stamped with the installer version. It keeps its own semantic version + (0.5.3), and everything else gets `-p:Version=`. +- **New check:** every project assembly listed in the launcher's `deps.json` must be staged next to it. This guards + directly against the DesktopLog failure above. +- **Previous release:** `installer\previous-release\last-built-version.txt` tracks the last build. When the version + changes, that build's installer is archived to `previous-release\` (git-ignored) before the new one is built. +- **Output:** `RynthCore-Setup-.exe`, plus a `RynthCore-Setup.exe` copy. + +## Not included +RynthChat, RynthJuice, RynthNav, RynthTracker and RynthVision are experimental and stay out of the installer. +RynthNav and RynthJuice still hard-code `C:\Games\RynthCore`. diff --git a/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md b/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md new file mode 100644 index 0000000..6229a91 --- /dev/null +++ b/Changelog/2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md @@ -0,0 +1,60 @@ +# 2026-10-04 — ILT Hub panel button, ImGui windows on top, live logging levels + +Launcher 0.1.5. Needs RynthAi 0.6.18 for the RynthAi logging rows. + +## ILT Hub button (Avalonia RynthAi panel) + +* New **ILT Hub** launcher button (third row of the RynthAi panel launcher grid). + Sends `hub show` through the plugin's `RynthPluginApplyRemoteCommand` export — + the same path as typing `/ra hub show`. +* New `SendRemoteCmd(action, value)` helper marshals both strings, calls the + export and frees them (the plugin copies them and applies on its pump thread). + +## Plugin ImGui windows draw on top of the Avalonia layer + +* `EngineFrameController.RunImGuiFrame` still builds the ImGui frame at the same + point, but no longer submits the draw data. `EndSceneHook` now calls the new + `EngineFrameController.RenderDeferredImGui()` **after** + `OverlayTextureRenderer.Render`, so the plugin overlay windows (ILT Hub, Item + Info, ...) are drawn over the Avalonia panels. +* Input follows the new stacking: when ImGui is hovered or has an active widget, + mouse messages go to ImGui instead of the Avalonia panel underneath + (`Win32Backend.ImGuiOwnsMouseOverAvalonia`). An Avalonia drag/resize already + in progress keeps its capture so the release is never lost. +* Nothing is submitted twice: the pending draw is cleared at the start of each + ImGui frame and after submission. + +## Live, per-category logging (engine + launcher) + +### Engine + +* New `LogSettings` reads engine.json: + * `"LoggingLevel"`: global threshold, now including **Off** + (Off, Error, Warning, Info, Debug, Trace; `Verbose`/`Warn` accepted). + * `"LogCategories"`: per-category emit level (Off, Trace, Debug, Info) for + General, D3D9, Compat, Render, Plugin, UI, Verbose. A category's lines are + written at its level, so a Trace/Debug category set to **Info** shows in the + normal log, and **Off** silences it. +* A background thread polls engine.json once a second and reloads on change + (logs `LogSettings: engine.json changed - logging reloaded (...)`). Stopped in + `EngineLifecycle.Shutdown` before unload. +* `RynthLog` category methods route through the category levels (the hard-coded + `*Enabled` booleans are gone; defaults are unchanged: Render Off, Verbose Debug, + everything else Info). +* Lines are tagged with their real level: `[DBG]` and `[TRC]` instead of `[INF]`. +* `Warn` is now hidden at level Error/Off; `Error` is always written. + `LastIssue` is still recorded for filtered warnings. +* `EngineSettings.Save()` now copies through engine.json fields it doesn't own + (e.g. `LogCategories`, `EnableDcompOverlay`) instead of dropping them. + +### Launcher (Runtime tab) + +* **Logging level** box gains **Off**, and applies immediately (writes + engine.json on change; no Save needed). Unknown saved values fall back to Info. +* New **Logging** card, every change saved immediately and applied live: + * Engine categories: Off / Trace / Debug / Info per category. + * RynthAi categories: Off / Trace / Info per category (diagnostics.json). + * RynthAi key events: Off / Trace / Info per event (diagnostics.json). + * Reload button re-reads both files. +* New `LoggingSettingsStore` does the read-modify-write of both files + (atomic temp-file swap for diagnostics.json, every other field preserved). diff --git a/Changelog/2026-10-04-ilt-hub-pet-roster.md b/Changelog/2026-10-04-ilt-hub-pet-roster.md new file mode 100644 index 0000000..d1a7aeb --- /dev/null +++ b/Changelog/2026-10-04-ilt-hub-pet-roster.md @@ -0,0 +1,65 @@ +# ILT Hub Pet tab: UtilityBelt-style pet roster (2026-10-04) + +RynthAi 0.6.22. Ships in the next installer after 2026.10.4.17. + +## What changed + +The ILT Hub **Pet** tab's flat "Carried essences" table (name / uses / order) is replaced +by a roster modelled on UtilityBelt's Pets tab. + +### Three stat lines per pet + +| Line | Contents | +|------|----------| +| 1 | Name, Bond, Lvl, Craft (coloured by damage type) | +| 2 | Sex (M/F, `n` neutered, `j` juvenile), growth, mutations, stored potency (active level and +damage %), mastery, damage type | +| 3 | Ratings `[D, DR, C, CD, CR, CDR]`, uses (red when empty), breeding status, "ID pending" until appraised | + +Stats come from the ACECustom pet properties UtilityBelt reads (bond 9053, potency 9056, +mutations 9070–9075, maturity 9077, mastery 362, gear ratings 370–375 falling back to the +base rating ids). Active potency follows ACE: `min(stored, ceil(bond / 10))`, minimum 1, +capped at 150, +2% damage per level. Sex uses the server's GUID hash unless an override +bool is set. + +Un-appraised essences are appraised automatically, two per 2-second scan. **Scan pack** +re-appraises every pet essence to refresh bond and potency after fights. + +### Type and sort + +- **Type**: Combat, Healing or Cosmetic. Combat essences and Healing Buddy / Dule box pets + are classified automatically. Any essence can be re-typed: select it in your pack and press + **Add sel.**, or right-click a row ("Move to …", "Clear type override"). Overrides are + saved per character in `ilt-hub.json` (`Pet.Assignments`). +- **Sort**: Priority, Bond, Potency, Breed ready, Level, Uses, Name. + +### Selecting and summoning by type + +- **Combat**: the tick list is still the `ConsumableRules` Pet list that PetManager summons + from, so there is no second summoner. With Sort = Priority, the arrows set the summon order. +- **Healing**: the tick picks the heal pet used by the healing helper. The old free-text + "Heal-pet essence" field is replaced by this tick. No tick means the first Healing Buddy / + Dule box, as before. The healing settings moved into a collapsible "Healing pet settings" header. +- **Cosmetic** (new): tick one display pet. **Keep cosmetic pet out** summons it in peace + mode when no other pet is out and the combat summoner isn't hunting, re-summoning after a + configurable delay (default 15 s). +- **Summon** uses the highlighted row, or the type's ticked pet. **Despawn** dismisses + whatever pet is out by using the essence that summoned it again (matched by name, else the + last essence summoned from the Hub). An **Active summon** line shows the pet that is out. + +## Combat pet hand-off + +`PetManager` has a new optional hook, `YieldPetForCombat`. When a pet already holds the slot +and monsters are near, PetManager asks the ILT Hub. If the pet is the cosmetic pet, the Hub +dismisses it, and PetManager waits 3 seconds and then summons a combat pet as usual. Other +pets (combat or heal) are never dismissed by this hook. + +## Files + +- New `IltHub/IltPetStats.cs`: stat model, property reader, 3-line formatter and sorter. +- `IltHub/IltPets.cs`: roster snapshot, classification, Summon/Despawn/Scan pack/Add sel., + cosmetic keep-out, new UI. +- `IltHub/IltHubState.cs`: `RosterKind`, `RosterSort`, `Assignments`, `CosmeticPetName`, + `KeepCosmeticOut`, `CosmeticRespawnSeconds`, plus the new `IltPetAssignment` class. The values + are normalized on load (`IltHubStore`). +- `Combat/PetManager.cs`: `YieldPetForCombat` hook. `IltHubController` wires it at login. +- Version 0.6.21 → 0.6.22. diff --git a/Changelog/2026-10-04-installer-2026.10.4.1.md b/Changelog/2026-10-04-installer-2026.10.4.1.md new file mode 100644 index 0000000..5f2c2e7 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.1.md @@ -0,0 +1,42 @@ +# RynthCore installer — release 2026.10.4.1 + +**Build date:** 2026-10-04 +**Previous release:** 2026.10.3.4 (the version currently installed in `C:\Games\RynthCore`) +**Output:** `installer\Output\RynthCore-Setup.exe`, with a versioned copy at +`installer\Output\RynthCore-Setup-2026.10.4.1.exe` (72.9 MB) + +## What's inside + +Built with `installer\Build-Installer.ps1 -Version 2026.10.4.1` from: + +- **RynthCore** `main` @ `eda3cdf` (GitHub BlankenshipG/RynthCore). This includes the + aelrynth 2026.9.27.2 snapshot port and the URL fix. +- **RynthSuite** `feat/ilt-hub` @ `ad61194` (GitHub BlankenshipG/RynthSuite). This adds the + RynthAi 0.5.1 plugin with the ILT Hub. It's a local test build and is not on `main`. + +| Component | Notes | +|---|---| +| Launcher (`RynthCore.exe`) | Self-contained Avalonia, x86 | +| `Runtime\RynthCore.Engine.dll` | NativeAOT x86, 33 MB | +| `Runtime\RynthCore.Loader.dll` | NativeAOT x86 (hot-reload loader) | +| `Runtime\RynthCore.SehTrampoline.dll` | Rebuilt from `native\SehTrampoline\SehTrampoline.c` (MSVC 14.50, x86) | +| `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | 0.5.1-legacy-ui (ILT Hub) | +| `Tools\LootEditor` | Self-contained, x86 | + +`release.txt` reads `2026100401 / 2026.10.4.1`, so the launcher updater treats this build +as newer than 2026.10.3.4. + +## Security + +- Code review (diff since `8260c60`, which covers the signed updater, StatusAgent, the + release CI and the deploy scripts): no medium, high or critical findings. +- Dependency advisory: NuGet reports `Tmds.DBus.Protocol` 0.20.0 + ([GHSA-xrw6-gwf8-vvr9](https://github.com/advisories/GHSA-xrw6-gwf8-vvr9), high). + Avalonia pulls it in for the launcher, the engine and the Loot Editor. It's the Linux + D-Bus transport and isn't used on Windows. It should still be upgraded through an + Avalonia bump or a direct package pin. + +## Not done + +- The installer is unsigned (no Authenticode) and wasn't published to the update feed. +- Nothing was installed over `C:\Games\RynthCore`. Run the setup manually to test it. diff --git a/Changelog/2026-10-04-installer-2026.10.4.10-release.md b/Changelog/2026-10-04-installer-2026.10.4.10-release.md new file mode 100644 index 0000000..efb8175 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.10-release.md @@ -0,0 +1,36 @@ +# Installer 2026.10.4.10 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `a7cdbee`, RynthSuite `898bf8b`) +**Previous release:** 2026.10.4.9 + +## Contents +- **Engine 2026.10.4.10:** the CreateObject hook records each object's name and ItemType from the + server's create descriptor. Off-thread lookups therefore work at login, before the 500 ms + identity snapshot can resolve names (`2026-10-04-create-seeds-and-fatal-only-crash-logger.md`). +- **RynthCore.SehTrampoline.dll v2:** `native-crash.log` now records fatal crashes only: + - Unhandled exceptions are caught by a chained unhandled-exception filter. + - Faults in engine/plugin code are logged immediately, because the runtime kills the process + without running any filter. + - Other first-chance AVs are written only if the process dies soon after. + - The stack sweep stops at StackBase. + - Per-thread guards stop the logger from logging its own faults and AVs that its `SEH_*` + wrappers catch. +- **RynthAi 0.6.16:** keys, gems, spell components, food, misc items and portals are classified + by ItemType and ownership instead of being left as "Unknown" and rechecked every 2 s + (`RynthSuite/Changelog/RynthAi-0.6.16-typed-item-classification.md`). The CLASSIFY-GIVEUP + flood at login is gone. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.10.exe` + (SHA-256 `57462ea3fc03a71e92666cc54a961aa89f7b03a182540d05878ca6ce8f63e984`) +- `Release-2026.10.4.10/` and `RynthCore-2026.10.4.10-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.10`: everything built and the Inno Setup compile + succeeded. The first run stopped at the SEH trampoline staleness check: the DLL had been + built before `SehTrampoline.c` was committed. It was rebuilt from the identical source and the + release was rerun. The 2026.10.4.9 installer was archived as the previous release. +- Not yet verified in game. + - Check `[CreateSeed]` lines in the engine log for sensible names and types. + - Check that `native crash logger installed (v2, fatal-only)` is logged. diff --git a/Changelog/2026-10-04-installer-2026.10.4.11-release.md b/Changelog/2026-10-04-installer-2026.10.4.11-release.md new file mode 100644 index 0000000..1e1ee2e --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.11-release.md @@ -0,0 +1,27 @@ +# Installer 2026.10.4.11 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `903d3ea`, RynthSuite `c236832`) +**Previous release:** 2026.10.4.10 + +## Contents +- **RynthJuice 0.1.2:** mob health polling used to re-check the same first 80 of about 700 + tracked objects. It now reaches every tracked object (`RynthSuite/Changelog/RynthJuice-0.1.2-rotating-mob-poll.md`): + - Candidates are checked in rotation, 80 per poll. + - Confirmed attackable mobs are polled every cycle, so health bars stay continuous. + - Objects with a known non-creature ItemType are never tracked. + - The safety cap was raised from 800 to 4096. +- **Engine 2026.10.4.10 changes are unchanged** apart from the version stamp. This includes + the create-time name/type seeds, which RynthJuice now relies on to drop items immediately. + The engine is stamped 2026.10.4.11. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.11.exe` + (SHA-256 `714bcdb1ec4b99ff98445f55386514839485afb4ae5501a19b52d7e08d5398de`) +- `Release-2026.10.4.11/` and `RynthCore-2026.10.4.11-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.11`: everything built and the Inno Setup compile + succeeded. The 2026.10.4.10 installer was archived as the previous release. +- Not yet verified in game. To check, compare the `[RynthJuice] pollcycle ... mobs=` and + `attackable=` counts with the engine's attackable count. diff --git a/Changelog/2026-10-04-installer-2026.10.4.12-release.md b/Changelog/2026-10-04-installer-2026.10.4.12-release.md new file mode 100644 index 0000000..8e840b9 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.12-release.md @@ -0,0 +1,18 @@ +# Installer 2026.10.4.12 + +Previous release: 2026.10.4.11 (RynthJuice rotating mob poll). + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.12.exe` + SHA-256 `3E3AAFD5DA6DFFE8FCC1A50B64C9431F6F705157D9E28296C7946EFFD16D1858` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.12-deploy.zip` +* Source: RynthCore SK-local@6f9b985, RynthSuite SK-local@72d858e +* Plugin API: v68 + +## Included + +* Engine: off-thread PublicWeenieDesc int snapshot (stack size, max stack, + container, wielder, location, capacities, material) and merge-stack results + API (`GetMergeStackResult`). See + `2026-10-04-pwd-int-snapshot-and-merge-results.md`. +* RynthAi 0.6.17: AutoStack uses engine merge results, partial-merge success + detection, cooldown on full targets. diff --git a/Changelog/2026-10-04-installer-2026.10.4.13-release.md b/Changelog/2026-10-04-installer-2026.10.4.13-release.md new file mode 100644 index 0000000..bc296bd --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.13-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.13 + +Previous release: 2026.10.4.12 (PWD int snapshot + AutoStack merge results). + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.13.exe` + SHA-256 `E822BD93F8BF32AA04866CBDCC3300C566E814EB0B3602D647100CB843C89012` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.13-deploy.zip` +* Source: RynthCore SK-local@6b94752, RynthSuite SK-local@82decc8 +* Plugin API: v68 (unchanged) + +## Included + +* Avalonia RynthAi panel: ILT Hub button (sends `hub show`). +* Plugin ImGui windows (ILT Hub, Item Info, ...) draw on top of the Avalonia + layer and get mouse priority when hovered. +* Live logging: global level (now with Off) and per-category engine levels from + engine.json, reloaded within 1 s; launcher 0.1.5 Logging card edits engine + categories and RynthAi categories/key events on the fly. +* RynthAi 0.6.18: per-category Off/Trace/Info levels (Info promotes trace lines + to the normal log), ILT Hub key events, `hub` remote command. + +See `2026-10-04-ilt-hub-button-imgui-on-top-live-logging.md` and +RynthSuite `Changelog/RynthAi-0.6.18-launcher-log-levels.md`. diff --git a/Changelog/2026-10-04-installer-2026.10.4.14-release.md b/Changelog/2026-10-04-installer-2026.10.4.14-release.md new file mode 100644 index 0000000..d20ff7b --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.14-release.md @@ -0,0 +1,20 @@ +# Installer 2026.10.4.14 + +Previous release: 2026.10.4.13 (ILT Hub button, ImGui on top, live logging) - crash-prone with AutoStack on. + +* Installer: `installer/Output/RynthCore-Setup-2026.10.4.14.exe` + SHA-256 `90E791016252CAECD165CEB9006BEFA4AA641A816B079FC63B802F8F8C7A2A63` +* Deploy zip: `installer/Output/RynthCore-2026.10.4.14-deploy.zip` +* Source: RynthCore SK-local@19095e1, RynthSuite SK-local@bd9be89 +* Plugin API: v69 + +## Included + +* Crash fix: `GetMergeStackResult` thunk is now cdecl. 4.12/4.13 corrupted + RynthAi's stack on every AutoStack merge check and killed the client. +* Release build rejects any plugin API delegate without the Cdecl attribute. +* RynthAi 0.6.19: ILT Hub draw diagnostics (overlay entry/skip, window geometry) + and off-screen rescue. + +See `2026-10-04-merge-result-cdecl-crash-fix.md` and RynthSuite +`Changelog/RynthAi-0.6.19-hub-draw-diagnostics.md`. \ No newline at end of file diff --git a/Changelog/2026-10-04-installer-2026.10.4.15-release.md b/Changelog/2026-10-04-installer-2026.10.4.15-release.md new file mode 100644 index 0000000..ad77b77 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.15-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.15 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.15.exe` +- SHA-256: `F76A08FDC4AF1096C022DAF1CC1A27FDB834B79641D8C23A9A27B64E1D3017CB` +- Deploy package: `installer/Output/RynthCore-2026.10.4.15-deploy.zip` +- Previous release: 2026.10.4.14 + +## Changes + +- **Engine fix: plugin ImGui windows now draw.** The plugin render snapshot was never + published after plugins loaded, so `RenderAll` / `RenderOverlayAll` called no plugins + and windows such as the RynthAi ILT Hub never appeared. See + `2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md`. +- **Engine diagnostics:** one-time Info lines for the ImGui gate, init, first frame, branch, + first draw submit and overlay plugin binding, plus a 30 s heartbeat. Repeated frame + exceptions are rate-limited. +- CS0162 (unreachable code) is now a build error in the engine. + +## Upgrade notes + +- No plugin API change (still v69); plugins do not need rebuilding. +- `engine.json` may still be at `Trace` from earlier debugging. Set the logging level back to + `Info` in the launcher once the Hub is confirmed working. diff --git a/Changelog/2026-10-04-installer-2026.10.4.16-release.md b/Changelog/2026-10-04-installer-2026.10.4.16-release.md new file mode 100644 index 0000000..f018738 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.16-release.md @@ -0,0 +1,22 @@ +# Installer 2026.10.4.16 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.16.exe` +- SHA-256: `8D901EF8A6B80F9CB817372E7FBFAB18E334393E30A9BE3AC7F3FF9578E6E682` +- Deploy package: `installer/Output/RynthCore-2026.10.4.16-deploy.zip` +- Previous release: 2026.10.4.15 + +## Changes + +- **Floating panels are destroyed on the thread that owns them.** `LayeredWindow.Dispose` + destroys inline when the caller owns the window, and otherwise posts a self-destroy + message to the panel window itself. Before, the destroy always went to the game + thread, so panels created on another thread could be left frozen on screen. +- **The login-time pop-out waits for the game window hook**, so restored floating panels + are created on AC's game thread like every other pop-out. It falls back after 60 s. + +See `2026-10-04-panel-window-owner-thread-fixes.md` for details. + +## Upgrade notes + +- No plugin API change (still v69); plugins do not need rebuilding. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.17-release.md b/Changelog/2026-10-04-installer-2026.10.4.17-release.md new file mode 100644 index 0000000..6c38982 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.17-release.md @@ -0,0 +1,23 @@ +# Installer 2026.10.4.17 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.17.exe` +- SHA-256: `7F21D78BEDD12DCFCFC865DA682E12498819B00C6BFC60BBDBA8BBF5D04E8EFF` +- Deploy package: `installer/Output/RynthCore-2026.10.4.17-deploy.zip` +- Previous release: 2026.10.4.16 +- RynthAi: 0.6.21 + +## Changes + +- **Items window: Shields section.** "Add Selected Shield", the shield list with delete, and the + auto-equip toggle. Shields no longer appear under Weapons. See + `2026-10-04-items-panel-shields.md`. +- **RynthAi panel Map and Lua buttons work.** Map toggles the dungeon map and Lua toggles the + Lua Scripts editor. Both are also available as `/ra map` and `/ra lua`. In Avalonia mode both + windows are now drawn on top of the overlay. The dungeon map also reopens again after being + closed with its X. See `2026-10-04-dashboard-map-and-lua-buttons.md`. + +## Upgrade notes + +- No plugin API change (still v69). RynthAi must be 0.6.20 or newer for the new Shields button and + the new Map/Lua commands (this installer ships 0.6.21). +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.18-release.md b/Changelog/2026-10-04-installer-2026.10.4.18-release.md new file mode 100644 index 0000000..9af1076 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.18-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.18 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.18.exe` +- SHA-256: `70F6A3C0EBE1C279D60E48C739E4664F8CE625B9AA5D055283B2C207219ACF26` +- Deploy package: `installer/Output/RynthCore-2026.10.4.18-deploy.zip` +- Previous release: 2026.10.4.17 +- RynthAi: 0.6.23 + +## Changes + +- **Floating HUDs.** Three new undockable windows: an item count HUD, a UB-style Mini Remote, and + a quest favorites HUD. The item HUD and Mini Remote are set up from Inventory Management > + **Inventory HUDs...** (both the ImGui Advanced Settings and the Avalonia Settings panel) or + `/ra huds`. The ILT Hub quest tracker gained a favorites star, the floating favorites HUD and a + **Pop out** button. See `2026-10-04-floating-huds.md`. +- **ILT Hub pet roster** (RynthAi 0.6.22, first shipped here). The Pet tab shows UB-style stats per + pet, sorts, and summons by type (Combat, Healing, Cosmetic). See + `2026-10-04-ilt-hub-pet-roster.md`. + +## Upgrade notes + +- No plugin API change. The engine's Inventory HUDs button needs RynthAi 0.6.23 or newer; older + plugins ignore the command. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.19-release.md b/Changelog/2026-10-04-installer-2026.10.4.19-release.md new file mode 100644 index 0000000..29e3dab --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.19-release.md @@ -0,0 +1,27 @@ +# Installer 2026.10.4.19 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.19.exe` +- SHA-256: `780425B79594914296AC5E9E35708192E94E1D40697D96365D64D9A34FFEA1C3` +- Deploy package: `installer/Output/RynthCore-2026.10.4.19-deploy.zip` +- Previous release: 2026.10.4.18 +- RynthAi: 0.6.26 + +## Changes + +- **Missile ammo detection** (RynthAi 0.6.24). Ammo already in the ammo slot is recognised even + when its name isn't a stock arrow/bolt/dart name: it is matched by equip slot, `CombatUse` and + `AmmoType`, with a fallback probe and an `[AmmoDiag]` log line. See + `2026-10-04-missile-ammo-detection.md`. +- **Char / Hub launcher buttons** (RynthAi 0.6.25). "ILT Hub" is now **Char**, and a new **Hub** + button toggles the Mini Remote (right-click in the Avalonia panel opens Inventory HUDs). See + `2026-10-04-char-and-hub-launcher-buttons.md`. +- **Pet scan by type** (RynthAi 0.6.26 + engine). The ILT Hub Pet tab and Scan pack only count + real pet devices (essence WCID block, summoning-gem icon underlay, Summoning use requirement, + ACECustom bond/potency). A name ending in "Essence" is no longer enough. The engine now serves + `IconOverlay` / `IconUnderlay` DIDs. See `2026-10-04-pet-scan-type-detection.md`. + +## Upgrade notes + +- No plugin API version change. `IconOverlay` / `IconUnderlay` reads return false on older + engines, and RynthAi then confirms pets from appraisal data instead. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.20-release.md b/Changelog/2026-10-04-installer-2026.10.4.20-release.md new file mode 100644 index 0000000..9729d55 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.20-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.20 release (2026-10-04) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.20.exe` +- SHA-256: `8A5FE0DBB55A66FAD4BCB4FFBE70F205ADF2B8269BE60C748395214A45F66D53` +- Deploy package: `installer/Output/RynthCore-2026.10.4.20-deploy.zip` +- Previous release: 2026.10.4.19 +- RynthAi: 0.6.27 + +## Changes + +- **Looting fix: name rules never matched** (RynthAi 0.6.27). Loot rules that match on item name + read an empty string, because ACE never sends `Name` in appraisal data and the evaluator runs + off the main thread. Every corpse item was left behind; SilentKelpie looted nothing across 225 + items. Name reads now fall back to the object's snapshot name. See + `2026-10-04-loot-name-rules-and-ground-loot.md`. +- **Loot items on the ground** (RynthAi 0.6.27). A port of UB-IT AutoGroundLoot: loose ground + items that match the active loot profile are picked up within the corpse max range. Corpses + are looted first. Turn it on in Advanced Settings > Looting > **Loot Items On Ground** or with + `/ra groundloot on|off|status|scan`. + +## Upgrade notes + +- No engine or plugin API change. Ground loot is off by default. +- `engine.json` may still be at `Trace` from earlier debugging; set it back to `Info` in the launcher. diff --git a/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md b/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md new file mode 100644 index 0000000..9d5ea99 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.3-experimental-plugins.md @@ -0,0 +1,40 @@ +# RynthCore 2026.10.4.3: experimental plugins as optional installer components + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.3.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.2` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.2.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## What's new + +The **Select Components** page has a new **RynthSuite: Experimental plugins** group. Each plugin is unchecked by +default in every install type; ticking one switches the install to Custom. + +| Component | Installs to | Version | +|---|---|---| +| `experimental\rynthchat` | `\RynthChat\RynthCore.Plugin.RynthChat.dll` | 0.1.1 | +| `experimental\rynthjuice` | `\RynthJuice\RynthCore.Plugin.RynthJuice.dll` | 0.1.1 | +| `experimental\rynthnav` | `\RynthNav\RynthCore.Plugin.RynthNav.dll`, plus `\NavData\` | 0.5.5 | +| `experimental\rynthtracker` | `\RynthTracker\RynthCore.Plugin.RynthTracker.dll` | 0.1.1 | +| `experimental\rynthvision` | `\RynthVision\RynthCore.Plugin.RynthVision.dll` | 0.1.1 | + +- **Registration:** every selected plugin (RynthAi included) goes into `Software\Rynth\PendingPluginRegistration` + as a `;`-separated list. On next start the launcher adds them all to its Plugins list and syncs `engine.json`. +- **Suite folder page:** shown whenever any RynthSuite component is selected, experimental ones included. +- **RynthNav data:** the installer creates `\NavData` (kept on uninstall). It ships the starter + `portals.tsv` from `RynthNav.PortalGraph` only when that folder has none, so a newer generated file is never overwritten. + Navmesh tiles (`nav_XXXX.tile`) are **not** shipped; bake them with `RynthNav.Baker --tiled` (its default output + is `C:\Games\RynthCore\NavData`; pass `--out` for a different RynthCore folder). +- **Silent installs:** pick components with `/COMPONENTS`, for example + `/COMPONENTS="core,rynthai,monstereditor,experimental\rynthnav,experimental\rynthvision"`. + +## Build script (`installer\Build-Installer.ps1`) +- New step **7/7** publishes the five plugins (NativeAOT, x86), each keeping its own version. +- RynthJuice, RynthNav and RynthVision set `` to the live `C:\Games\RynthSuite\\` for dev hot-reload. + The build overrides it to each project's `bin\...\publish\`, so building an installer never touches a live install. +- Staging: `staging\suite\\` per plugin and `staging\navdata\portals.tsv`. All of them are in the required-files check. + +## Upgrade notes +- Re-running the installer without an experimental plugin does not remove one installed earlier. Uninstall + RynthCore, or delete `\\` and its row in the launcher's Plugins tab. +- These plugins are work in progress and may change or break between builds. diff --git a/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md b/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md new file mode 100644 index 0000000..98e2201 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.4-dotnet10-prereq.md @@ -0,0 +1,50 @@ +# RynthCore 2026.10.4.4: .NET 10 check with automatic download and install + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.4.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.3` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.3.exe`) +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## Installer: .NET 10 Desktop Runtime (x86) + +- **Detection:** setup looks for a 10.x `Microsoft.WindowsDesktop.App` under `Program Files (x86)\dotnet\shared\`, or its + registration in `HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App` (32-bit view). + x86 matches RynthCore's x86 launcher and tools. The Desktop Runtime also contains the base .NET runtime. +- **When it's missing,** the Tasks page shows a **Prerequisites** task, checked by default: *Download and install the + Microsoft .NET 10 Desktop Runtime (x86)*. When the runtime is already there, the task is not shown at all. +- **Install:** on leaving the Ready page, setup downloads the latest 10.x runtime from Microsoft + (`https://aka.ms/dotnet/10.0/windowsdesktop-runtime-win-x86.exe`, about 55 MB) with a progress page, then runs it + with `/install /quiet /norestart`. The runtime's own installer asks for administrator approval (UAC) when setup + isn't elevated. +- **Silent installs** run the same step just before the files are copied, without a progress page. Skip it with + `/MERGETASKS="!installdotnet"`. That's useful offline, or for the launcher's silent self-update when no one is + there to approve UAC. +- **Never blocking:** exit codes 0, 3010, 1641 and 1638 (a newer runtime is already installed) count as success. A + failed download, a cancelled UAC prompt (1602) or any other error is logged and shown in a message box with the + manual download link, and the RynthCore install carries on. + +Why it isn't required: the launcher, Loot Editor and Monster Editor are self-contained (they bundle .NET 10.0.5), and the +engine, loader and plugins are NativeAOT. The shared runtime is a safety net for framework-dependent add-ons and tools. +Earlier blocking .NET pages (0.4.x) had to be made advisory for exactly this reason. + +## Build script: .NET 10 SDK + +`Build-Installer.ps1` needs a .NET 10 SDK to publish, so before building (skipped with `-SkipBuild`) it: +1. uses the `dotnet` on PATH if it lists a 10.x SDK; +2. otherwise reuses an earlier per-user install in `%LOCALAPPDATA%\Microsoft\dotnet`; +3. otherwise downloads Microsoft's `dotnet-install.ps1`, **checks its Authenticode signature** (must be valid and signed + by Microsoft Corporation), and installs the latest 10.0 SDK per-user. No admin is needed. Then it uses that SDK for the + rest of the build (`DOTNET_ROOT` and `PATH` are set for this session only). + +Pass `-NoDotNetInstall` to fail with a download link instead of installing. + +**Tested:** in an isolated session with no `dotnet` on PATH, the script verified the signature, installed SDK 10.0.401 to +a scratch folder and found it again on a second run without re-downloading. + +NativeAOT publishing also needs the Visual Studio C++ build tools ("Desktop development with C++"). The script doesn't +install those. + +## Not tested end to end +The runtime download and install path in the installer was compiled but not run on the build machine. That machine already +has the x86 Desktop Runtime 10.0.7, so the task stays hidden there. Running it would have meant installing 10.0.12 +machine-wide. diff --git a/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md b/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md new file mode 100644 index 0000000..dd7dbb9 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.5-suite-dir-per-mode.md @@ -0,0 +1,31 @@ +# RynthCore 2026.10.4.5: installer only reuses a RynthSuite folder from the same install mode + +**Release date:** 2026-10-04 +**Installer:** `installer\Output\RynthCore-Setup-2026.10.4.5.exe` (also copied to `RynthCore-Setup.exe`) +**Previous release:** `2026.10.4.4` (archived to `installer\previous-release\RynthCore-Setup-2026.10.4.4.exe`). Don't +use 2026.10.4.4 for a per-user install on a machine that also has an all-users install (see below). +**Branch:** `feat/full-installer` (local test build, not on `main`) + +## Fix + +To pre-fill the **Select RynthSuite Location** page, the installer used to read `Software\Rynth\SuiteDir` from HKCU **and +then HKLM**. A per-user install on a machine that already had an all-users install therefore adopted the all-users +RynthSuite folder. The two installs then shared those files, and **uninstalling the per-user install deleted the +all-users install's RynthAi DLL and Monster Editor.** + +The lookup now reads only the hive of the current install mode (Inno's `HKA`: HKCU for per-user, HKLM for all-users), +matching how `GetPreviousData` and `UsePreviousAppDir` already behave. A per-user install with no per-user history +defaults to a `RynthSuite` folder next to its RynthCore folder again. + +The runtime resolver (`RynthInstallPaths`: HKCU, then HKLM) is unchanged. A per-user install's own values still +take precedence for that user. + +## Found by +A per-user test install of 2026.10.4.4 into a scratch folder on the build machine, which had an all-users 2026.10.4.3 +install in `C:\Games`. The test install wrote into `C:\Games\RynthSuite` and its uninstall removed +`RynthAi\RynthCore.Plugin.RynthAi.dll` and the Monster Editor. Both were restored right away from the same-source build +(RynthAi 0.5.3, 217 Monster Editor files). User data folders, the experimental plugins and `C:\Games\RynthCore` were not affected. + +## Also in this build +Everything from 2026.10.4.4: the .NET 10 Desktop Runtime check with automatic download and install in the installer, +and the .NET 10 SDK check with per-user auto-install in `Build-Installer.ps1`. diff --git a/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md b/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md new file mode 100644 index 0000000..c3eb85d --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.6-tool-launch-buttons.md @@ -0,0 +1,16 @@ +# Installer 2026.10.4.6 — RynthAi tool launch buttons + +**Date:** 2026-10-04 +**Branch:** `feat/full-installer` (testing only — not merged to `main`) + +## Changes +- Bundles **RynthAi 0.5.4**, which adds **Loot Editor** and **Monster Editor** launch buttons to the + in-game Items window and the Advanced Settings → Looting page. No more launching the editors from + the shell or Explorer while playing. +- No installer script changes; tool locations are unchanged (`\Tools\LootEditor`, + `\RynthAi\MonsterEditor`), and RynthAi finds them through the registered install paths. + +## Build +- `installer\Build-Installer.ps1 -Version 2026.10.4.6` +- Previous installer archived: `installer\previous-release\RynthCore-Setup-2026.10.4.5.exe` +- Output: `installer\Output\RynthCore-Setup-2026.10.4.6.exe` diff --git a/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md b/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md new file mode 100644 index 0000000..7d7c68a --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.7-deployment-package.md @@ -0,0 +1,45 @@ +# Installer 2026.10.4.7 — deployment-ready release package + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Previous release:** 2026.10.4.6 + +## Added +- `Build-Installer.ps1 -Version ` now finishes with a **deployment package**: + - `installer\Output\Release-\` + - `RynthCore-Setup-.exe` — the installer (its stamped ProductVersion must equal ``). + - `release-manifest.json` — version, release number, build time, previous release, RynthCore and + RynthSuite branch/commit/dirty flag, every shipped component's version (launcher, engine, + loader, Loot Editor, RynthAi, Monster Editor, experimental plugins) and the installer's size + SHA-256. + - `RELEASE-NOTES.md` — install / silent-install / hash-verification steps, component table, and the + Changelog entries from **both** repos added or changed since the previous release (by the previous + manifest's commits; falls back to the previous version's build date). + - `SHA256SUMS.txt` — `sha256sum`-format hashes of the files above. + - `installer\Output\RynthCore--deploy.zip` — the folder zipped, then extracted to a temp folder and + re-checked against `SHA256SUMS.txt`. + - `installer\previous-release\last-release-manifest.json` — kept so the next release lists only new notes. +- `-AllowDirty` and `-NoPackage` switches. + +## Changed +- Release (`-Version`) builds refuse uncommitted changes to tracked files in either repo (checked before the + slow publishes) so every package maps to exact commits; `-AllowDirty` overrides and flags the manifest. + `installer\previous-release\` is exempt because the script rewrites its markers. +- `last-built-version.txt` is written only after the whole build (including the package) succeeds, so a + failed package step is retried rather than skipped. +- `Build-Release-All.ps1` documents the package output. + +## Fixed +- **Previous-release archive mislabel:** when `RynthCore-Setup-.exe` was not in `Output\` (e.g. it + was built in another checkout), the canonical `RynthCore-Setup.exe` — possibly an older build — was archived + under the previous version's name. It is now archived only when its ProductVersion matches. +- **`Publish-Update.ps1` could not publish:** it copied the RynthAi plugin from `staging\plugins\RynthAi\`, + which the full installer layout no longer creates (`staging\suite\RynthAi\`). It also now takes the + versioned `RynthCore-Setup-.exe` (the unversioned copy is best effort and may be stale). +- **False "SehTrampoline.dll is STALE" after checkouts/merges:** the check compared file times, and git rewrites + `SehTrampoline.c` (new mtime, same content) on checkout. When the source matches HEAD its last commit + time is used instead; local edits still use the file time. +- **Launcher showed `0.1.3-x64-prereq-probe` instead of the release:** the SK-era launcher `.csproj` hard-coded + `InformationalVersion`, which overrides the `-p:Version` release stamp. Removed; launcher file version + 0.1.3 -> 0.1.4. The launcher / About now report `2026.10.4.7 ()`. +- Rebuilding the same `-Version` keeps that release's original "changes since" baseline (stored as + `changelogSince` in the manifest) instead of diffing against itself. diff --git a/Changelog/2026-10-04-installer-2026.10.4.8-release.md b/Changelog/2026-10-04-installer-2026.10.4.8-release.md new file mode 100644 index 0000000..7193d4d --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.8-release.md @@ -0,0 +1,28 @@ +# Installer 2026.10.4.8 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `45f9ad2`, RynthSuite `975151b`) +**Previous release:** 2026.10.4.7 + +## Contents +- **Engine / launcher / loader** 2026.10.4.8 + - Nav panel waypoint list no longer jumps back to the top while editing + (`2026-10-04-nav-panel-scroll-fix.md`). +- **RynthAi 0.6.14** (was 0.6.11 in 2026.10.4.7): + - 0.6.12: shields in Items for the secondary (off) hand. + - 0.6.13: Mag-style item info line (`/ra iteminfo`): ratings, damage, spells, slayer, imbues, … + - 0.6.14: "RynthAi Item Info" settings window with live preview, per-field and per-rating + toggles, spell mode, chat type and prefix. The item info options now persist across reloads. +- Loot Editor, Monster Editor and experimental plugins rebuilt at RynthSuite `975151b`. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.8.exe` + (SHA-256 `a028c97469d6ad2d83a343c14e4b4884693ca524b16486825470d07cbba4a627`) +- `Release-2026.10.4.8/`: installer, `SHA256SUMS.txt`, `release-manifest.json`, `RELEASE-NOTES.md` +- `RynthCore-2026.10.4.8-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.8`: solution build, all NativeAOT publishes and the + Inno Setup compile succeeded. The 2026.10.4.7 installer was archived as the previous release, + and `installer/previous-release/` markers were updated to 2026.10.4.8. +- Not yet verified in game. diff --git a/Changelog/2026-10-04-installer-2026.10.4.9-release.md b/Changelog/2026-10-04-installer-2026.10.4.9-release.md new file mode 100644 index 0000000..c997109 --- /dev/null +++ b/Changelog/2026-10-04-installer-2026.10.4.9-release.md @@ -0,0 +1,24 @@ +# Installer 2026.10.4.9 + +**Date:** 2026-10-04 +**Branch:** `SK-local` (RynthCore `7a58cdc`, RynthSuite `22b77c5`) +**Previous release:** 2026.10.4.8 + +## Contents +- **Engine 2026.10.4.9:** new optional plugin export `RynthPluginRenderOverlay`, so plugins can show + extra windows beside the Avalonia UI while the ImGui shell is off + (`2026-10-04-plugin-overlay-windows.md`, engine.json `EnablePluginOverlayWindows`, default on). +- **RynthAi 0.6.15:** the **ILT Hub** window (and the Item Info settings window) now show as + separate windows next to the Avalonia RynthAi panel. Open with `/ra hub` and + `/ra iteminfo settings`. RynthAi's macro and automation never depend on these windows. + +## Artifacts (`installer/Output/`) +- `RynthCore-Setup-2026.10.4.9.exe` + (SHA-256 `95854d75eb1635e34474a9ef29deb65fc6dbc825d45e782fc9ecae501536efab`) +- `Release-2026.10.4.9/` and `RynthCore-2026.10.4.9-deploy.zip` (103 MB, hash-verified) + +## Build +- `Build-Release-All.ps1 -Version 2026.10.4.9`: everything built and the Inno Setup compile + succeeded. The remaining trim warnings are the existing ones in `AvaloniaOverlay.cs`. The + 2026.10.4.8 installer was archived as the previous release. +- Not yet verified in game. diff --git a/Changelog/2026-10-04-item-info-click-and-pet-layout.md b/Changelog/2026-10-04-item-info-click-and-pet-layout.md new file mode 100644 index 0000000..31c36bf --- /dev/null +++ b/Changelog/2026-10-04-item-info-click-and-pet-layout.md @@ -0,0 +1,70 @@ +# Item info: ID on left/right click + pet-style layout — RynthAi 0.6.29 + +**Date:** 2026-10-04 +**Component:** RynthCore.Plugin.RynthAi 0.6.28 → 0.6.29 + +## What's new + +### ID + print on click +- New **"ID + print on click"** option: **Off / Left mouse click / Right mouse click**. +- Clicking an item in the world or in your packs IDs it if needed and prints its info to chat. + It also prints for an item that was already selected; the old "on select" option only fired when the selection changed. +- Ignored: + - clicks on RynthCore / ImGui windows; + - drags (moving more than 6 px while held, e.g. dragging items between packs); + - holds longer than 0.6 s (right-button camera turning). +- The info is printed for the item that is selected 150 ms after the button is released. + With **Right mouse click**, if the client doesn't change the selection on a right click, it prints the + currently selected item. That still works as left-click to select, right-click to print. +- The weapon / armor / jewelry / other type filters apply to both the select and click triggers. +- If on-select and on-click both fire for the same item, it prints once (1.5 s duplicate guard). +- Requires the ImGui overlay (clicks are read from the overlay's input state). Works with both + the ImGui dashboard and the Avalonia UI overlay path. + +### Pet-style layout for weapons and armor +- New **Layout** option: **Pet-style lines** (new default) or **One line (Mag-Tools)** (the previous output). +- Pet-style mirrors the ILT Hub pet roster: a name/identity line, then indented detail lines: + + ``` + [RynthAi] Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8 + [RynthAi] CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md + [RynthAi] [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270 + [RynthAi] Spells: Legendary Blood Thirst + ``` + + - Line 1: name (damage type + mastery), set, AL, tinks, applied materials, craft / salvage work, keyring. + - Line 2: imbues, armor cleave, crit stats, splits, range, cleaving, slayer, damage, variance, + elemental / damage-mod bonuses, %a / %md / %mgc.d / %msl.d / %mc, unenchantable protections. + - Line 3: ratings cluster, then wield / activation / difficulty requirements and value / burden. + - Line 4: spells. + - Empty lines are skipped, so plain armor prints only one or two lines. +- New **Detail lines colour** (chat type for lines 2–4), default "Same as name line", with a Test button. +- Every existing field and rating toggle, the spell mode, the prefix and the chat type apply to both layouts. + The one-line output is identical to 0.6.28. + +## Where to set it +- **Advanced Settings → Display → Item Info**: "ID + print on click" and "Layout" combos. +- **Item Info window** (`/ra iteminfo settings`): click trigger in *When to print*, layout and + detail colour in *Chat output*. The preview shows the multi-line layout. +- Commands: + - `/ra iteminfo click left|right|off` + - `/ra iteminfo layout pet|line` + +## Implementation notes +- `MagItemDescriber.Build` now returns a `MagItemDescription` (title plus fields tagged with a + `MagItemSection`, in Mag print order). `ToOneLine()` reproduces the classic line and + `ToPetLines()` groups the same fields by section. `Describe()` is kept as a one-line wrapper. +- Click detection (`DetectItemInfoClick`) runs on the render thread in `OnRender` / + `OnRenderOverlay`, edge-detecting `io.MouseDown`. The selection is read on the plugin tick + (`ResolveItemInfoClick`, handed over with `Interlocked`), so all describe / ID state stays on one thread. +- New `MagItemInfoSettings` fields: `ClickTrigger`, `Layout`, `DetailChatType` (sanitized and included in reset). + +## Files +- `Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs` +- `Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs` (render hooks, on-select dedupe, VersionPointer 0.6.29) +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs` (help line) +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj` (0.6.29) diff --git a/Changelog/2026-10-04-items-panel-shields.md b/Changelog/2026-10-04-items-panel-shields.md new file mode 100644 index 0000000..fcddecb --- /dev/null +++ b/Changelog/2026-10-04-items-panel-shields.md @@ -0,0 +1,39 @@ +# Items panel: Shields section and "Add Selected Shield" (2026-10-04) + +Engine Avalonia `ItemsPanel` plus RynthAi 0.6.20. Ships in the next installer after 2026.10.4.16. + +## Problem + +RynthAi stores off-hand shields in its item list (`ItemRule.Action = "Shield"`), and its +ImGui Items tab has a Shields section. The engine's Avalonia Items window (the one +opened from the dashboard) never got that section: + +- "Add Selected Weapon" rejects shields with "That is a shield — use Add Selected Shield", + but that button didn't exist in the engine panel, so shields couldn't be added there. +- Shields already in the list showed up under Weapons with an element picker. + +## Engine (`UI/Panels/ItemsPanel.cs`) + +- New **Shields (off-hand)** section between Weapons and Consumables: + - an "Auto-equip with one-handed melee weapons" ON/OFF toggle with a tooltip (shown when the + plugin reports the setting); + - a shield list with a Del button on each row; + - **Add Selected Shield**, which calls the plugin's new `RynthPluginAddSelectedShield` export. + With an older plugin the click does nothing and logs that RynthAi 0.6.20+ is required. +- The Weapons section now lists only non-shield entries. +- `WeaponEntry` carries `action` and the payload carries `autoEquipShield`; both are part of + change detection, so plugin-side edits appear within the 1 s poll. +- Deletes now remove the row's own entry instead of a list index, because the weapon and + shield rows are filtered views of one list. + +## RynthAi 0.6.20 + +- New export `RynthPluginAddSelectedShield`, which goes through `LegacyDashboardRenderer.AddSelectedShield` + to the existing `LegacyWeaponsUi.AddSelectedShield` and then saves settings. +- `ItemsBridgePayload.AutoEquipShield` (`bool?`) is sent to the panel. It's applied on write-back + only when present, so older engine panels leave the setting alone. +- `ApplyItemsJson`: + - new entries keep the `Shield` action the panel sends (anything else becomes `Weapon`); + - deleting a shield from the engine panel clears any monster off-hand that pointed at it and + saves the monsters file (the same cleanup as the ImGui Del button). +- Version bumped to 0.6.20 (`csproj`, `RynthAiPlugin.VersionPointer`). diff --git a/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md b/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md new file mode 100644 index 0000000..1e2760b --- /dev/null +++ b/Changelog/2026-10-04-loot-name-rules-and-ground-loot.md @@ -0,0 +1,66 @@ +# Looting fix (name rules never matched) + ground-item looting + +**Date:** 2026-10-04 +**Components:** RynthAi plugin 0.6.27 (RynthSuite) + +## Problem: SilentKelpie looted nothing + +SilentKelpie's log for this session (pid 30364) shows 21 corpses claimed, opened and fully +evaluated. All 225 items evaluated across two sessions came out `-> leave`. That includes items +the active profile (`T10locky.utl`) explicitly keeps by name, such as "Thaelaryn Core" via its +`(T) Thaelaryn Core` rule. + +### Cause +VTank name rules (node type 1, `StringValueMatch` on key 1 = Name) and native JSON name rules +read the name through `WorldObject.Values(StringValueKey.Name)`. That goes to the engine's +string-property read, which off the main thread only answers from the appraisal cache. ACE does +not mark `PropertyString.Name` as an assessment property, so appraisal data never contains it. +Because the loot evaluator runs on the plugin pump thread, every name read returned `""` and +every name rule failed. The object's own `Name` (from the network snapshot, which is what the +`[LootEval]` log line prints) was correct all along. + +### Fix +`Combat/AcStubs.cs` `WorldObject.Values(StringValueKey, ...)`: when the live read is empty and +the key is `Name`, return the snapshot `Name`. This affects every consumer of name rules: corpse +loot (VTank and native profiles), `/ra lootcheck`, AutoVendor rules, ILT equip suits and meta +expressions. + +## New: loot items on the ground (UB-IT AutoGroundLoot) + +- **Setting:** Advanced Settings > Looting > **Loot Items On Ground** (`EnableGroundLoot`, default + off; saved with the profile). +- **Command:** `/ra groundloot on|off|status|scan`. `scan` clears the skip list. +- **Range:** the corpse max range (`CorpseApproachRangeMax`, yards, Ranges tab). +- **Rules:** the active loot profile, through the same `ClassifyItemAgainstProfile` corpses use. + This covers VTank `.utl` and native `.json` profiles, mana stone and mana-tap rules, and + salvage items queued for salvaging. +- **What counts as a ground item:** readable ownership with no container and no wielder, plus a + world position within range. Scenery, creatures, players, NPCs, vendors, portals, doors, + corpses, lifestones, signs, housing, containers, combat pets and services are excluded. +- **Appraisal:** stat-gated rules request an appraisal first (two per scan). If none arrives + within 3 s, the item is classified best-effort, matching the corpse assess window. +- **Pickup:** only when the activity arbiter hands Looting the tick, so navigation is already + stopped. It sends `MoveItemExternal(item → player)`, and ACE walks the character over and picks + the item up. The pickup is confirmed when the item gets a container, is retried up to 3 times + over 5 s windows, and is then skipped for 5 minutes. Non-matching items are re-checked after + 60 s. +- **Priority:** corpses come first. Ground loot runs only when no corpse is claimed or open. A + ground pickup already sent finishes before the next corpse is claimed. +- **Logging:** every ground evaluation is logged as `[LootEval] ground '' ... -> KEEP|leave`, + and claims and pickups as `Ground loot: ...`. + +## Files +- `Combat/AcStubs.cs`: Name fallback. +- `Combat/WorldObjectCache.cs`: new `IsOnGround(id)`. +- `GroundLootController.cs` (new): scan, claim, pickup, confirm, `/ra groundloot`. +- `CorpseOpenController.cs`: ground loot hooked into `TickCorpseOpening`; `HasLootWork` includes + ground matches. +- `LegacyUi/LegacyUiSettings.cs`, `LegacyDashboardRenderer.cs`, `LegacyAdvancedSettingsUi.cs`: + `EnableGroundLoot` setting and checkbox. +- `RynthAiPlugin.cs`, `RynthAiCommands.cs`: command registration and help; ground state cleared + on logout. + +## Notes +- `T10locky.utl` has no Pyreal rule (its only coin rule matches "Coin"), so Pyreals are still left + on corpses. That is how the profile is set up, not a bug. +- Versions: RynthAi `0.6.26` → `0.6.27`. diff --git a/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md b/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md new file mode 100644 index 0000000..d76cff2 --- /dev/null +++ b/Changelog/2026-10-04-merge-result-cdecl-crash-fix.md @@ -0,0 +1,35 @@ +# 2026-10-04 — Fix: GetMergeStackResult stack corruption crash (API v69) + +## Problem + +Builds 2026.10.4.12 and .13 crashed a couple of seconds after AutoStack started +logging merges with garbage item names and IDs (e.g. `src=0x40C16E04 -> +tgt=0xFFFF7C95`, then `Event_StackableMerge from=0x40C16E04 to=0xBD8B1053`, a +target that didn't even match the request). The process died with no exception, +so the crash logger caught nothing and the launcher recorded a "normal close". + +## Cause + +`GetMergeStackResultCallbackDelegate` (PluginContract.cs) was the only one of the +API delegates without `[UnmanagedFunctionPointer(CallingConvention.Cdecl)]`. On +x86 that makes `Marshal.GetFunctionPointerForDelegate` produce a **stdcall** +thunk, while plugins call it as **cdecl**. Both sides popped the 16 bytes of +arguments, so RynthAi's stack shifted on every call. AutoStack (RynthAi 0.6.17+) +calls it on every pending-merge check, so locals turned to garbage until the +process died. + +## Fix + +* Added the missing `[UnmanagedFunctionPointer(CallingConvention.Cdecl)]`. +* API version bumped to **v69**. The SDK's `HasGetMergeStackResult` now requires + v69, so a rebuilt plugin never calls the broken v68 thunk on a 4.12/4.13 engine + (it falls back to the 10 s grace check). +* `Build-Release-All.ps1` now fails the release if any delegate in + `PluginContract.cs` is missing the Cdecl attribute. + +## ILT Hub draw diagnostics + +* Engine logs `PluginManager: first RenderOverlay call for ` once per + plugin per session, proving the overlay export is being driven. +* See RynthSuite `Changelog/RynthAi-0.6.19-hub-draw-diagnostics.md` for the + plugin-side lines. diff --git a/Changelog/2026-10-04-missile-ammo-detection.md b/Changelog/2026-10-04-missile-ammo-detection.md new file mode 100644 index 0000000..d5a4adc --- /dev/null +++ b/Changelog/2026-10-04-missile-ammo-detection.md @@ -0,0 +1,56 @@ +# Missile combat: equipped ammo not detected (2026-10-04) + +RynthAi 0.6.24. + +## Symptom + +Silentkelpie (InfiniteLeaftide) had ammo equipped for the Corrupted Bow, but RynthAi never +fired. The log shows the bow equipped and the stance reaching Missile (mode 4) with a target +locked, then `attack=never` on every combat tick from 22:13 onwards. Combat also never tried to +equip ammo from the pack. + +## Cause + +Combat refuses to fire in missile mode until `HasWieldedAmmo()` passes. That check had two weak +points: + +1. **Name only.** A wielded stack only counted as ammo if its name contained "arrow" (bow), + "quarrel"/"bolt" (crossbow) or "dart" (atlatl). Server-custom ammo with any other name was + invisible, both in the ammo slot and in the pack, which is why combat never tried to equip + anything either. +2. **Snapshot only.** It only looked at the direct-inventory snapshot. That snapshot merges in + wielded gear the object cache had already filed as inventory with a readable wield slot. + Ammo equipped before login can be missing from it, or read wield slot 0. + +The log can't say which of the two hit Silentkelpie: no line names the ammo stack. The fix +covers both, and adds a diagnostic line (below) that names it next time. + +## Fix + +- **The ammo slot counts as ammo.** Any item the player wields in the ammunition slot (EquipMask + `0x00800000`) is treated as ammo, whatever its name. This is safe because the server (ACE + `Player_Inventory`) refuses to wield ammo whose AmmoType conflicts with the launcher. +- **Property-based recognition.** Loose ammo is also recognized by COMBAT_USE = Ammo (STypeInt 51), + matched to the launcher by AMMO_TYPE (STypeInt 50) when readable. This covers: + - auto-equipping from the pack; + - Items > Missile ammunition > "Add selected as ammo"; + - the per-monster "Sel" ammo button. +- **Launcher detection.** Launcher kind now comes from the launcher's AMMO_TYPE when readable, + else from its name. Items in the ammo slot are never mistaken for the launcher. +- **Fallback probe.** If the snapshot shows no ammo, combat probes every known missile-class or + ammo-named object's wield slot through the host (wielder info, ownership info, then + CurrentWieldedLocation). The result is reused for 750 ms. +- **`[AmmoDiag]` log line** (Combat category, at most every 15 s while ammo is missing). It names + the ammo found outside the snapshot, or lists every wielded missile-class object with its slot, + COMBAT_USE and AMMO_TYPE. +- `MissileCraftingManager` uses the same ammo-slot rule. + +## Files + +- `Combat/MissileAmmoHelper.cs`: slot constants, `IsAmmoSlot`, `KindFromAmmoType`, + `IsWieldedAmmoForKind`, `GetAmmoKind`, `GetKindFromMissileWeapon`, public `PlayerWieldLocation`. +- `Combat/CombatManager.cs`: `HasWieldedAmmo` fallback probe and `[AmmoDiag]`. + `TryEnsureMissileAmmoForCombat` reuses `HasWieldedAmmo`. +- `Combat/MissileCraftingManager.cs`: ammo-slot aware launcher and ammo checks. +- `LegacyUi/LegacyWeaponsUi.cs`, `LegacyUi/LegacyMonstersUi.cs`: property-based ammo recognition. +- Version 0.6.23 → 0.6.24. diff --git a/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md b/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md new file mode 100644 index 0000000..3199d43 --- /dev/null +++ b/Changelog/2026-10-04-nav-editor-overlay-breadcrumbs.md @@ -0,0 +1,98 @@ +# Nav editor expansion, waypoint overlay/HUD and breadcrumb tracker + +**Date:** 2026-10-04 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.29 → 0.6.30 + +## Summary + +The Navigation tab has been rebuilt around the editing features UtilityBelt-IT +added to VTank-style navs. On top of that come an on-screen waypoint overlay (HUD, +step labels, guide line) and a breadcrumb tracker that records where you have +walked and can turn that trail into a route. + +## Nav editor (Navigation tab) + +- **File row:** New (with confirmation), Save (opens Save As for an unsaved route), + Save As (sanitised file name, confirms before overwriting) and Reload. +- **Insert position:** new steps go at the End, Above the selection or Below it, + like UB-IT's "insert before". +- **Add steps:** Point (your position), Snap to path (inserts into the nearest + segment), Pause, Chat (adds the leading `/` automatically), Recall (pick from the + spell list or type an id), Portal (uses the selected object) and Point at the + selected object. +- **Edit steps:** Up, Down, Duplicate, Delete (or the Delete key), Set active, + Select nearest, Reverse route, and select All or None. +- **Step list:** multi-select with Ctrl or Shift, double-click a step to make it + active, and right-click for a context menu. +- **Step editor:** shown when one step is selected. Edit NS/EW/height, "Set to my + position", pause duration, chat text, recall spell and portal target ("Use + selected object"). +- Edits are copy-on-write, so the navigation engine never sees a half-edited + route. The active step follows its waypoint when steps are moved. + +## Recording (Record tab) + +- **Record mode** (UB-IT KeyStoreRecorder style): adds a Point every N yards while + you walk. +- **Portal capture:** when you use a portal while recording, it adds a Portal step + for the portal you selected in the last 20 seconds, followed by an optional + pause. +- **Saving:** recording autosaves every 10 steps and again when it stops (or when + the session ends). + +## Breadcrumb tracker + +- **Trail:** records your path at a set spacing. A portal trip or teleport starts + a new trail segment instead of drawing a line across the map. +- **Drawing:** the trail is drawn in the world with a fade, within a set range, + using Nav3D (or the ImGui fallback when Nav3D isn't available). +- **Trail → route:** turns the latest trail segment into a new Once route. +- **Backtrack route:** the same as Trail → route, but reversed, to walk back the + way you came. +- **Clear trail.** + +## Waypoint overlay and HUD + +- **Nav HUD window:** route name and type, recording state, current step and its + type, distance with an up/down height hint, a direction arrow relative to your + facing, the next step, remaining or loop distance, nav status and trail stats. +- **Step labels:** "#index Nyd" labels on the next N Point steps. +- **Guide line:** a line from you to the active waypoint, like UB-IT's yellow + breadcrumb line. + +## Display options (Display tab) + +- Route markers on or off, and how many markers to draw around the active step. +- Ring and line thickness, and height offset. +- Colours for rings, the active ring, lines, the guide line and the trail, plus + Reset colours. +- HUD visibility, including a "only while navigating" option. + +## Tools tab + +- **Simplify route:** Douglas–Peucker with an adjustable tolerance. Removes + redundant Point steps and keeps every action step. +- **Height repair:** "Select raw-height steps" and "Divide Z by 240". + +## Bug fix: waypoint height + +The Add-point button, the `/ra addnavpt` command and the web bridge saved the raw +world height instead of height ÷ 240 (the VTank .nav unit). Those waypoints drew +their markers far above the ground. All three now save the correct value. Use the +height repair tool to fix routes that were already saved. + +## New chat commands + +- `/ra navrec [on|off]`: toggle route recording. +- `/ra navhud [on|off]`: show or hide the nav HUD. +- `/ra navtrail [clear]`: show trail stats, or wipe the trail. + +## Files + +- New: `LegacyUi/NavOverlaySettings.cs`, `LegacyUi/NavRouteEditing.cs`, + `NavBreadcrumbTracker.cs`, `NavOverlayRenderer.cs` +- Rewritten: `LegacyUi/LegacyNavigationUi.cs` +- Modified: `LegacyUi/LegacyUiSettings.cs`, `LegacyUi/LegacyDashboardRenderer.cs`, + `LegacyUi/NavCoordinateHelper.cs`, `NavMarkerRenderer.cs`, `RynthAiPlugin.cs`, + `RynthAiCommands.cs`, `RynthCore.Plugin.RynthAi.csproj` diff --git a/Changelog/2026-10-04-nav-panel-scroll-fix.md b/Changelog/2026-10-04-nav-panel-scroll-fix.md new file mode 100644 index 0000000..c2f31e3 --- /dev/null +++ b/Changelog/2026-10-04-nav-panel-scroll-fix.md @@ -0,0 +1,27 @@ +# Engine — Nav panel waypoint list no longer jumps while editing + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** next installer release (2026.10.4.8; previous 2026.10.4.7) + +## Fixed +- **Nav panel (Avalonia "Nav" tab, `UI/Panels/NavPanel.cs`): the waypoint list kept scrolling + back to the top, so points could not be selected or deleted.** + - Cause: the 1-second poll timer rebuilt the entire panel every tick, including a brand-new + waypoint `ScrollViewer`, so its scroll offset reset to 0 once a second. A rebuild that landed + between mouse press and release also dropped the click on a row or its X button. + - The waypoint `ScrollViewer` (and its row stack) is now created once and only refilled on + rebuild; the scroll offset is saved and re-applied (immediately and after layout). + - The poll only rebuilds when the plugin's nav JSON actually changed. + - The poll does not rebuild while the mouse is over the waypoint list; the change is picked up + on the first poll after the pointer leaves. + - Rebuilds caused by your own edits (optimistic local updates) always resync on the next poll, + so a command the plugin rejected can't leave stale state on screen. + +## Not changed +- The ImGui Navigation window in the RynthAi plugin (`LegacyNavigationUi`) did not have this + problem (ImGui keeps the list-box scroll position itself). + +## Build +- `RynthCore.Engine`: `dotnet build -c Release` and NativeAOT `dotnet publish -c Release` succeed; + no new warnings. The engine version is stamped by the release build (`-p:Version=yyyy.m.d.n`). diff --git a/Changelog/2026-10-04-panel-window-owner-thread-fixes.md b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md new file mode 100644 index 0000000..be2f448 --- /dev/null +++ b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md @@ -0,0 +1,42 @@ +# Floating panel windows: destroy on the owner thread, create on the game thread (2026-10-04) + +Ships in the next installer after 2026.10.4.15. + +## Destroy each panel window on the thread that owns it + +`LayeredWindow.Dispose` used to call `Win32Backend.PostDestroyWindow`, which always +posted the destroy to the game window. That was wrong for any panel not created on +the game thread (for example the login-time pop-out, created on the Avalonia UI +thread). The game thread's `DestroyWindow` then failed because it didn't own the +window, and the panel stayed on screen, frozen. The post was also dropped if the +game WndProc had already been unhooked at shutdown. + +- New `LayeredWindow.DestroyOnOwnerThread`: it looks up the window's owning thread with + `GetWindowThreadProcessId`. + - If the window no longer exists, it logs and returns. + - If the caller owns the window, it calls `DestroyWindow` inline. + - Otherwise it posts the new `WM_RYNTH_SELF_DESTROY` (0x8005) to the panel window itself. + The panel's own `StaticWndProc` then destroys it on its owner thread. This never + blocks the caller, and it works after the game WndProc is unhooked. +- `PostMessage` in `LayeredWindow` now sets the last error, so a failed post is logged + with the real error code. +- Removed `Win32Backend.PostDestroyWindow` and its `WM_RYNTH_DESTROY_HWND` (0x8003) + handler; 0x8003 is reserved and not reused. The shutdown sweep + (`WM_RYNTH_SWEEP_PANELS`) remains as a backstop for panels that were never disposed. + +## Hold the login-time pop-out until panels can be created on the game thread + +Floating panels saved as popped out are restored when `LoginComplete` fires. That can +happen before the engine has found and subclassed the game window, so +`FloatingPanelHost` took its legacy path and created the window on the Avalonia UI +thread. That path brings back the Win11 `WS_EX_NOACTIVATE` click-drop race and the +cross-thread destroy problem above. + +- New `Win32Backend.CanRunOnGameThread`: true once the game window is known and its + WndProc is subclassed, which is what `RunOnGameThread` needs. The window handle + alone isn't enough. +- `AvaloniaOverlay.RestoreFloatingPanels` now polls every 200 ms on the UI thread until + `CanRunOnGameThread` is true, then restores. It logs once when it starts holding and + again when it releases. +- After 60 s it restores anyway on the legacy path and logs a warning line, so the panels + are not lost on a client that is never hooked. diff --git a/Changelog/2026-10-04-pet-refill-loop-fix.md b/Changelog/2026-10-04-pet-refill-loop-fix.md new file mode 100644 index 0000000..17de9bd --- /dev/null +++ b/Changelog/2026-10-04-pet-refill-loop-fix.md @@ -0,0 +1,52 @@ +# Pet essence refill loop fix — RynthAi 0.6.28 + engine + +**Date:** 2026-10-04 +**Components:** RynthCore.Engine (property caches), RynthCore.Plugin.RynthAi 0.6.27 → 0.6.28 + +## Problem + +SilentStorm got stuck refilling the same pet essence (0x9757B329) over and over. The log +(`RynthCore.9568.log.old`) showed `Pet: refilling essence … with spirit …` about every 7 s, +and every 30 s once cooldowns kicked in. Each attempt used an Encapsulated Spirit on the essence. +The server switches the player to peace mode and plays the clap animation for every refill, +so the character kept dropping out of combat. + +## Root cause + +- `PetManager` decides whether an essence is empty by reading its `Structure` (charges) through + `TryGetObjectIntProperty`. The plugin pump runs off the main thread, so that read was + served **only** from the appraisal cache. That cache is a snapshot from the last time the item was ID'd. +- When the server refills an essence it sends a `PublicUpdatePropertyInt(Structure = MaxStructure)`. + The engine stored that in the property-update cache, but the off-thread read never consulted + that cache, and the appraisal snapshot was never patched. So the essence kept reading 0 charges. +- The server's reply ("You add the spirit to the essence." / "This essence is already full.") + sent `PetManager` back to Idle without recording anything. On the next tick it read 0 again + and issued another refill. + +## Fix + +### Engine +- `PropertyUpdateHooks.CacheInt` / `CacheBool` now also patch the appraisal cache entry for that + object, if one exists (`AppraisalHooks.PatchCachedInt` / `PatchCachedBool`). Off-thread reads + now see live server updates (Structure after a refill or summon, etc.) instead of the last ID's value. +- `ClientObjectHooks.TryGetObjectIntProperty`: off the main thread, an appraisal-cache miss now + falls back to the property-update cache (a thread-safe managed dictionary) instead of failing. + +### RynthAi plugin (also protects against older engines) +- The server's success and already-full replies now mark the essence as confirmed full for up to 30 min. + While that mark is set, a stale 0-charge read is ignored and the essence is used for summoning. + The mark clears as soon as a summon reports "not enough charges". +- After a confirmed refill the plugin requests a fresh ID of the essence, so the cached charges and the + ILT pet roster agree. +- Loop guard: once an essence has been refilled twice within 2 min and still reads empty, it + is parked for 5 min with a log line, rather than burning more spirits. +- New log lines: `Pet: refill complete (essence …, server confirmed).`, + `Pet: essence … is already full; charge read was stale.`, and the parking message. + +## Files +- `RynthCore/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs` +- `RynthCore/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs` +- `RynthCore/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs` +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs` +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj` (0.6.28) +- `RynthSuite/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs` (VersionPointer 0.6.28) diff --git a/Changelog/2026-10-04-pet-scan-type-detection.md b/Changelog/2026-10-04-pet-scan-type-detection.md new file mode 100644 index 0000000..405155b --- /dev/null +++ b/Changelog/2026-10-04-pet-scan-type-detection.md @@ -0,0 +1,44 @@ +# Pet scan: detect pets by type, not by "Essence" in the name + +**Date:** 2026-10-04 +**Components:** RynthAi plugin 0.6.26 (RynthSuite), RynthCore Engine / PluginSdk (next installer, 2026.10.4.19) + +## Problem + +The ILT Hub **Pet** tab (roster, **Scan pack**, heal-pet lookup, Mini Remote pet line) counted +any carried item whose name ended in ` Essence` as a combat pet. Augmentation gems and other +non-pet items with that suffix (for example "Jibril's Essence") showed up in the roster and got +appraised by Scan pack. + +## Fix + +### RynthAi — `IltHub/IltPets.cs` +- New `IsPetDevice(WorldObject)` decides by item type: + - **Never pets:** Encapsulated Spirit, the charm block (78780030–78780089), capture + devices (78780001–78780012) and the summoned combat pet creature block (787802001–787802072). + - **Pets:** + - the ACECustom combat essence WCID block (787801001–787801072); + - the summoning-gem icon underlay (DID 0x06007420), which needs no appraisal; + - `UseRequiresSkill` / `UseRequiresSkillSpec` = Summoning (54); + - ACECustom `BondLevel` (9053) > 0 or `PotencyStored` (9056) present. + - **Name hints only nominate items.** A name ending in " Essence", Healing Buddy / Dule box, + stamina buddy/crate/pet, or cosmetic/plush/display pet only makes an item a candidate. + It counts as a pet once it shows charges (`MaxStructure` > 0), matching UtilityBelt's pet scan. +- `ClassifyKind` now requires `IsPetDevice`. After that, naming picks the type: heal naming + → Healing, cosmetic naming → Cosmetic, otherwise Combat. Manual re-types ("Add sel." / + right-click) and the ticked heal pet still win. +- **Scan pack** appraises every confirmed pet and also any un-appraised pet-named candidate, + so its type can be confirmed or ruled out. The chat line reports both counts. The 2 s + background trickle also appraises candidates, two per scan. + +### Engine / SDK +- `ClientObjectHooks.TryGetObjectDataIdProperty` now serves `IconOverlay` (50, PWD+20) and + `IconUnderlay` (52, PWD+24) as well as `Icon` (8). This is the same network-populated + PublicWeenieDesc read, so it works on never-appraised pack items. No API version change: + older engines just return false for 50/52, and the plugin falls back to the appraisal-based + signals. + +## Notes +- Without the new engine, a real pet whose WCID is outside the essence block appears once its + appraisal lands (via Scan pack or the background trickle) instead of right away. +- Versions: RynthAi `0.6.25` → `0.6.26`. diff --git a/Changelog/2026-10-04-plugin-overlay-windows.md b/Changelog/2026-10-04-plugin-overlay-windows.md new file mode 100644 index 0000000..a5ca6be --- /dev/null +++ b/Changelog/2026-10-04-plugin-overlay-windows.md @@ -0,0 +1,31 @@ +# Engine — plugin overlay windows while the ImGui shell is off + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** installer 2026.10.4.9 (previous 2026.10.4.8) + +## Problem +`EngineSettings.EnableImGuiShell` is hard-off unless the developer env var +`RYNTHCORE_FORCE_IMGUI=1` is set. `EngineFrameController.RunImGuiFrame` skipped both +`RynthCoreShell.Render` and `PluginManager.RenderAll`, so any plugin window without an Avalonia +panel could never show. That included RynthAi's ILT Hub (log: the Hub was created and the server +features came back, but no window) and its Item Info settings window. + +## Added +- **Optional plugin export `void RynthPluginRenderOverlay()`** (`PluginContract.cs`, + `PluginLoader.cs`, `LoadedPlugin.RenderOverlay`). With the ImGui shell off, the engine calls it + every frame through the new `PluginManager.RenderOverlayAll()`. A plugin draws only its extra + windows there, beside the Avalonia UI. Plugins without the export are unaffected. Their full ImGui + UIs stay hidden, so nothing duplicates an Avalonia panel. The old ImGui bar stays hidden too. +- **Failure isolation:** if `RenderOverlay` throws, only that plugin's overlay windows are switched + off for the session. The plugin is **not** marked `Failed`, so its tick, automation and Avalonia + panels keep running. (`RenderAll` keeps its old behaviour.) +- **engine.json `"EnablePluginOverlayWindows"`** (default `true`) to hide the overlay windows. + `EngineSettings.Save` writes it, and the launcher's `EngineJsonStore` preserves it. + The windows need `EnableImGuiBackend` (default `true`). +- Same not-in-world guard as `RenderAll` (no drawing between logoff and the next login complete). + +## Build +- `RynthCore.Engine` Release build succeeds (no new warnings). Shipped with RynthAi 0.6.15, which + exports `RynthPluginRenderOverlay` (ILT Hub + Item Info windows). +- Not yet verified in game. diff --git a/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md b/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md new file mode 100644 index 0000000..e8b2b20 --- /dev/null +++ b/Changelog/2026-10-04-plugin-render-snapshot-fix-and-imgui-diagnostics.md @@ -0,0 +1,34 @@ +# Plugin render snapshot fix and ImGui pipeline diagnostics (2026-10-04) + +Ships in installer 2026.10.4.15. + +## Fix: plugin overlay windows never drew (ILT Hub not showing) + +`PluginManager.RenderAll` and `RenderOverlayAll` iterate `_pluginsRenderSnapshot`, a +copy of the plugin list published by `PublishPluginsRenderSnapshot()`. Since the aelrynth +2026.9.27.2 snapshot port (commit 4ddbb52e), the publish call that belonged at the end of +`LoadPluginsFromDisk()` had landed after the `return` in `TryGetCanonicalPath()`, where it +could never run. The only publish that ran was in `UnloadAllPlugins()`, which published an +empty list. The result was that every plugin's ImGui render and overlay callbacks were +skipped, so windows like the RynthAi ILT Hub never appeared even though `hub show` worked. + +- `LoadPluginsFromDisk()` now publishes the snapshot after loading and logs the plugin count. +- The unreachable call has been removed. +- `RynthCore.Engine.csproj` now treats CS0162 (unreachable code) as a build error, so a + misplaced statement like this one fails the build. + +## Diagnostics: per-frame ImGui pipeline + +All of these lines appear in the normal log at Info, and each is written once (or when its value changes): + +- `reached ImGui gate (EnableImGuiBackend, EnableImGuiShell, EnablePluginOverlayWindows)`. +- ImGui init: success, or an Error naming the failing step (EnsureCore, Win32Backend.Init, + DX9Backend.InitImGui), and an Error if frames are skipped because init failed. +- `first ImGui frame started` with the display size, and `first deferred ImGui draw submitted`. +- Which branch the frame took (shell, overlay or none), logged when it changes. +- `RenderOverlayAll`: waiting for login, then `login seen, N of M plugin(s) will draw overlay windows` + with each plugin's state (overlay / no-overlay, not-init, failed). +- A heartbeat every 30 s: frames completed, draws submitted, last-frame draw lists and vertices, + overlay calls, login seen, overlay plugin count. +- Engine-frame and ImGui-frame exceptions: the first one is logged as an Error with the full exception, + then a count every 30 s instead of one line per frame. diff --git a/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md b/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md new file mode 100644 index 0000000..546c356 --- /dev/null +++ b/Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md @@ -0,0 +1,54 @@ +# 2026-10-04 — PublicWeenieDesc int snapshot + merge-stack results (API v68) + +## Problem + +AutoStack failed almost every merge (one session: 515 attempts / 514 failures; +the day: 1,521 / 1,515 — mostly Prismatic Tapers and Diamond Scarabs). + +* The RynthAi update loop runs on the plugin pump thread, not AC's main thread. +* Since audit finding #24 (no live AC memory reads off-thread), + `TryGetObjectIntProperty` refused stack size / max stack size off-thread and + had no snapshot to fall back on, so every stack read as "unknown" → 1. +* The engine's main-thread merge then read the *real* counts, found the target + full and silently skipped it (logged only at Verbose). RynthAi waited its 10 s + grace window and logged a failure — forever, for the same pairs. +* The same bad count fed AutoCram amounts, missile-crafting head/shaft counts + and ExpressionEngine item-count expressions. + +## Fix + +### PublicWeenieDesc int snapshot (`ClientObjectHooks`) + +* The 100 ms main-thread position walk (`PrefetchPositions` → + `CapturePositionForId`) now also captures, per object, the PWD fields: + container (+28), wielder (+32), valid locations (+40), location (+44), + items capacity (+48), containers capacity (+52), stack size (+96), + max stack size (+100) and material (+148). +* One `VirtualQuery` range check per object guards the whole field block; the + walk stays allocation-free (struct values in pre-sized dictionaries). +* The snapshot is double-buffered and swapped together with the weenie-pointer + buffers under `_weeniePtrSwapLock`, so readers always see one coherent frame. +* Off-thread reads route to the snapshot: + * `TryGetObjectIntProperty` for STypes 6, 7, 9, 10, 11, 12, 131. + Stack size / max stack of `<= 0` still prefer the appraisal cache. + * `TryReadPwdInt32` (previously returned `false` off-thread). + * `TryGetObjectOwnershipInfo` / `TryGetObjectWielderInfo` (container, + wielder, location). +* Main-thread reads are unchanged (live PWD reads). +* A one-time `PWD int snapshot warm` log line confirms the snapshot is serving. + +### Merge-stack results (`MergeStackResults`, API v68) + +* New `MergeStackResults` table keyed by (source, target) records the outcome + of every `MergeStackInternal` exit: `Queued`, `Sent` (with amount), + `TargetFull`, `Failed`, `QueueFull`. +* New API slot `GetMergeStackResultFn` (appended; `PluginContractVersion` 68): + returns the latest status plus amount and age in milliseconds. +* SDK: `RynthCoreHost.CurrentApiVersion = 68`, `HasGetMergeStackResult`, + `GetMergeStackResult(...)` and `RynthCoreHost.MergeStackStatus` constants. + Returns `None` on older engines, so plugins degrade to their old behaviour. + +## Compatibility + +* ABI: append-only; plugins built against v66/v67 keep working. +* No behaviour change on the main thread. diff --git a/Changelog/2026-10-04-sk-local-unified.md b/Changelog/2026-10-04-sk-local-unified.md new file mode 100644 index 0000000..6973b36 --- /dev/null +++ b/Changelog/2026-10-04-sk-local-unified.md @@ -0,0 +1,54 @@ +# SK-local unified branch — full installer + SK logging + ub-Rythai component + +**Date:** 2026-10-04 +**Branch:** `SK-local` (now contains `main`, `feat/full-installer`, `fix/tmds-dbus-advisory`, +`SK`, and PR #2 docs) + +## Branch integration +- `feat/full-installer` merged into `SK-local`: aelrynth snapshot port, Loader, full installer + (installers 2026.10.4.1–2026.10.4.6), update checker, crash relaunch / stuck-client handling, + per-PID logs, tmds.dbus advisory fix. +- `origin/main` (PR #2 Hub playbook) merged; SK-local's newer playbook revision kept. + +## Kept from SK-local +- **Engine logging level** (`EngineLogLevel`, `EntryPoint.ShouldLog`, `engine.json` `LoggingLevel`) + combined with full-installer's tagged WRN/ERR lines, `RynthLog.LastIssue` and per-PID log files. + `EngineSettings.Save()` preserves the launcher-chosen `LoggingLevel`. +- **Launcher:** "Inject all running AC sessions" toggle and Logging level dropdown, alongside the new + stagger / crash-relaunch / stuck-client / window-title options. The level is written to + `engine.json` through `EngineJsonStore.SetString` (new; preserves every other key). +- **PluginManager:** basename / canonical-path de-duplication of plugin DLLs. +- `TryPreloadMinHookForEarlyInit` before multi-client init. + +## Taken from full-installer +- Injector (unified log, launch command), installer scripts, release workflow, BUILD.md. +- Solution adds `RynthCore.DesktopLog` and `RynthCore.Loader`; the stale + `Plugins\RynthCore.Plugin.RynthAi` stub is no longer in the solution (the real plugin is in RynthSuite). +- The Desktop rolling log (`DesktopRollingLog`) is superseded by the unified/per-PID logs. + +## Fixed +- Auto-merge had left SK-era fragments in full-installer's scripts: an undefined `$PluginProjects` + check in `Build-Installer.ps1` (would abort every build), a duplicate bundle-archive block, the + `RynthBundle-Setup` output name in `RynthCore.iss`, and `-SkipUbRythai` / `RynthBundle-Setup-*.exe` + in the release workflow. All restored to full-installer's working versions. +- `Build-Release-All.ps1` now forwards only parameters `Build-Installer.ps1` declares + (`-Version`, `-RynthSuiteRoot`, `-IsccPath`). +- Engine / Injector `.csproj` restored to full-installer: SK's cimgui de-duplication deleted the plain + `cimgui.dll` that `Build-Installer.ps1` requires in `Runtime\` (and that plugins import by name), and + the DesktopLog reference was no longer used there. The launcher keeps DesktopLog (host diagnostics). + +## Added +- **ub-Rythai 3.1.10** as an optional experimental installer component + (`experimental\ubrythai` → `\UbRythai\RynthCore.Plugin.UbRythai.dll`, registered with the + launcher like the other experimental plugins). `RynthCore.iss` uses an `ExperimentalCount` constant + instead of hard-coded `0 to 4` loops. + +## Repository hygiene +- Stopped tracking SK-era build output: `installer/_toolpublish/` (published Loot/Monster Editor + binaries) and `build_out/RynthBundle-Setup-0.4.7.exe`. Both are git-ignored now; files remain on disk + and in history. + +## Build +- Engine, Launcher, Injector and Loader build with 0 errors on the merged branch. +- No installer was compiled for this entry; the next installer build should use + `installer\Build-Installer.ps1 -Version 2026.10.4.7` (previous: 2026.10.4.6). diff --git a/Changelog/2026-10-04-tmds-dbus-advisory.md b/Changelog/2026-10-04-tmds-dbus-advisory.md new file mode 100644 index 0000000..0845e7c --- /dev/null +++ b/Changelog/2026-10-04-tmds-dbus-advisory.md @@ -0,0 +1,26 @@ +# Security: pin Tmds.DBus.Protocol 0.21.3 (NU1903) + +**Date:** 2026-10-04 +**Branch:** `fix/tmds-dbus-advisory` (based on `main`; not merged) +**Advisory:** NU1903 / [GHSA-xrw6-gwf8-vvr9](https://github.com/advisories/GHSA-xrw6-gwf8-vvr9) (high severity) + +## Problem +Avalonia 11.x (through `Avalonia.FreeDesktop`) depends on `Tmds.DBus.Protocol` 0.20.x, which has a +known vulnerability. NuGet restore reported NU1903 for every project that references Avalonia. + +## Fix +A direct `PackageReference` to `Tmds.DBus.Protocol` **0.21.3** overrides the vulnerable transitive version: + +- `src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj` +- `src/RynthCore.Engine/RynthCore.Engine.csproj` + +The same pin is in RynthSuite (`Tools/RynthCore.LootEditor`, `Tools/RynthCore.MonsterEditor`) on `feat/ilt-hub`. + +## Verification +- `dotnet restore` / `dotnet list package --include-transitive` resolve `Tmds.DBus.Protocol 0.21.3` in all projects. +- No NU190x warnings remain. +- RynthAi 0.5.2 builds and publishes (NativeAOT) against this branch. + +## Notes +- No runtime behaviour change on Windows. D-Bus is only used by Avalonia on Linux desktops. +- Drop the explicit pin once Avalonia ships a release that depends on a fixed version. diff --git a/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md b/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md new file mode 100644 index 0000000..1db4197 --- /dev/null +++ b/Changelog/2026-10-05-aelrynth-2026.10.5.1-merge.md @@ -0,0 +1,131 @@ +# Merge: upstream aelrynth RynthCore 2026.10.5.1 into SK-local + +**Date:** 2026-10-05 +**Branch:** `merge/aelrynth-2026.10.5.1` (local only, not pushed) +**Upstream:** https://aelrynth.com/git/rynth/RynthCore (`upstream/main`, c3e1548) +**Component:** RynthCore (engine, plugin SDK, launcher, installer). RynthSuite is not part of this merge. + +## Summary + +Brings the upstream 2026.10.5.1 snapshot into our fork. Upstream publishes squashed +snapshots with no shared history, so the snapshot we had already ported (9b5e276, +2026.9.27.2) was recorded first as the merge base. This merge is a 3-way merge on top of it. + +Upstream's architecture wins wherever the two sides overlapped. Our features were ported +into the new structure rather than kept beside it. + +## What upstream brings + +- **UI data hub:** panels now read from `UiSources` and act through command classes + (`RynthAiCommands`, `ItemsCommands`, `NavCommands`, `SettingsCommands`). Plugin exports + are bound through `PluginExportBinder` and run on the pump thread (`UiDataHub.Post`). +- **ImGui "faces":** ImGui versions of the panels (`ImGui/Panels/*Face.cs`). +- **Chat:** chat model and router in `UI/Data/ChatData.cs`, with rules that have an + action, a "when" condition and a colour. +- **Settings:** data-driven settings (`SettingsSchema` / `SettingRow`). +- **Frame pipeline:** `EngineFrameController` replaces `ImGuiController` (deleted). + ImGui is now drawn *before* the Avalonia overlay, so draw order matches mouse hit-testing. +- **Unloadable engine:** a CoreCLR engine hosted by a native C loader (`native/Loader`, + `RynthCore.Shim`, app-local .NET runtime in `Runtime\dotnet`). The NativeAOT engine + is still available. +- **Plugin API stubs:** every plugin API slot is routed through native loader stubs. +- **Decal bridge (experimental):** a Decal network filter that lets an account run as + "Decal + RynthCore", with installer and launcher registration. +- **Item data:** a full PublicWeenieDesc byte snapshot (`PwdLayout`) for off-thread item reads. +- **Monster HUD, Lua panel**, plus many other fixes in the snapshot. + +## Our features kept + +- **Plugin API v77 (ABI change):** `GetMergeStackResultFn` moves to the end of the + API struct, after upstream's v68–v76 slots. Our previous slot position collided with + upstream's, so `PluginContract.Current`, `RynthCoreApiNative` and + `RynthCoreHost.CurrentApiVersion` are now 77. `HasGetMergeStackResult` requires v77. +- **Plugin overlay windows:** the ILT Hub, Item Info, Lua and Map overlay windows still + render when the ImGui shell is off. This is a new branch in + `EngineFrameController`, using `PluginManager.HasOverlayPlugins` and the + `EnablePluginOverlayWindows` setting. +- **Engine settings:** `LoggingLevel` is kept next to upstream's Decal settings. + The Decal keys were added to `OwnedFields` so settings.json never gets duplicate keys. +- **Window messages:** the layered-window self-destroy message moved from 0x8005 to + 0x8051. Upstream now uses 0x8005 for `WM_RYNTH_POST_ACTION` on the game window. +- **Chat standard filters and match modes:** ported into upstream's `ChatModel` and + `ChatRouter`. + - Contains / Starts with / Ends with / Regex modes for each rule. + - Standard (canned) filters run after custom rules and can hide lines or move them to a tab. + - Both the Avalonia filters panel and the ImGui `ChatFiltersFace` have the mode picker + and the Standard filters section. + - Settings JSON is unchanged (`filters[].mode`, `presets[]`). `RynthChatPresets` + state is `volatile` because routing runs on the pump thread. +- **Items panel Shields:** the Shields section is now backed by + `ItemsCommands.AddSelectedShield` (`RynthPluginAddSelectedShield`). +- **Inventory HUDs button:** a new `SettingKind.Button` row type in `SettingsSchema` + (Avalonia panel and ImGui face). It opens the HUD / Mini Remote window through + `RynthAiCommands.ApplyRemoteCommand("huds", "show")`. +- **RynthAi dashboard:** + - Char → `hub show`. + - Hub → `remote toggle`; right-click → `huds show`. + - The Map half of the Nav/Map button → `map toggle`. + - All four go through `RynthAiCommands.ApplyRemoteCommand`. +- **Meta folder:** `MetaData.MetaFolder` follows the install path + (`RynthInstallPaths.RynthAiDir\MetaFiles`) instead of a hard-coded `C:\Games` path. +- **Nav panel:** waypoint list polling pauses while the pointer is over the list. + +## Dropped in favour of upstream + +- `PropertyUpdateHooks` int/bool caches and `AppraisalHooks.PatchCachedInt/Bool`. + Upstream folds property updates into its appraisal cache. +- Our duplicate PublicWeenieDesc int snapshot in `ClientObjectHooks`. Off-thread + `TryReadPwdInt32` now reads upstream's byte snapshot via `TryGetPwdSnapshotRawInt32`. +- The deferred ImGui draw path (`RenderDeferredImGui`) and the multi-viewport experiment + (`ViewportProbe`, `ViewportPlatformBackend`, `ViewportRendererBackend`, `ViewportOffsets`). +- The launcher's "allow multiple clients" bypass of the duplicate-session check. + Upstream now keys sessions by account and server. + +## Installer and release scripts + +- `Build-Installer.ps1` keeps our layout: two install folders (`staging\core` / + `staging\suite`), experimental plugins, Monster Editor, release package and manifest. + New options: + - **Default engine is now upstream's unloadable CoreCLR engine** plus the native loader + (`scripts\Publish-EngineCoreClr.ps1`; needs the Visual Studio C++ tools). + `-NativeAot` builds the previous NativeAOT engine and loader. + - **Decal bridge:** built and staged to `{app}\DecalBridge` when Decal 3.0 is installed + (or `-DecalDir`). Without Decal the build continues with a warning. + `-IncludeDecalBridge` makes a missing Decal an error; `-SkipDecalBridge` leaves it out. + - The required-files check also covers the CoreCLR shim and runtime, and the bridge when built. +- `RynthCore.iss`: our Suite-folder pages and publisher info, plus upstream's Decal bridge + registration on install/update (`CurStepChanged`) and unregistration on uninstall. +- `Publish-Update.ps1`: our paths. A missing Decal bridge now only gives a warning + instead of blocking the publish. + +## Verification + +- `dotnet build RynthCore.sln -c Release`: 0 errors. +- NativeAOT publish of `RynthCore.Engine` and `RynthCore.Loader`: OK. +- `scripts\Publish-EngineCoreClr.ps1` (CoreCLR engine, native loader, shim, .NET 10.0.5 + app-local runtime) to a scratch folder: OK. +- Not yet tested in game. + +### RynthSuite against the v77 SDK + +- RynthSuite's own upstream merge (`merge/aelrynth-2026.10.5.1`, 532fa67) was checked out + next to this worktree (`D:\rynth-merge\RynthSuite`), so its `..\RynthCore` project + references resolve to this branch's SDK. +- RynthAi NativeAOT publish: OK. Full `RynthSuite.slnx` Release build: 0 errors. +- `RynthCore.RynthAiHostTests`: 356 passed, 0 failed (5 known failures). +- No RynthSuite code changes were needed. That branch's `InventoryManager` uses + upstream's `MergeStackInternal` and no longer calls `GetMergeStackResult`, so it needs + no v77 gate. +- A RynthAi built from SK-local RynthSuite (0.6.32 and earlier) reads + `GetMergeStackResultFn` at its old v68 slot, which upstream now uses for something else. + Only pair this engine with a RynthAi built from the merged RynthSuite. + +## Follow-ups + +- The installer's default engine is upstream's CoreCLR engine (confirmed). Test it in + game before releasing; `-NativeAot` is the fallback. +- Several new upstream paths are hard-coded to `C:\Games\...` (native loader log dir, + `RynthUpdater` default Suite dir, NavData, usage-stats dumps, ImGui pop-outs, + Decal bridge log dir). Installs in other folders may be affected. +- The ImGui `ItemsFace` has no Shields section yet (the Avalonia Items panel does). +- The `ImGuiStackRecovery` work in the main checkout is uncommitted and not part of this branch. diff --git a/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md b/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md new file mode 100644 index 0000000..fbeafc4 --- /dev/null +++ b/Changelog/2026-10-05-char-panel-rework-progression-pets-quests.md @@ -0,0 +1,73 @@ +# Char panel rework: Progression on the Skills panel, Pets and Quests windows (RynthAi 0.5.4-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.3-legacy-ui + +## Why + +The ILT Hub's Character tab mixed three different things: + +- live session stats; +- character progression (XP, augmentations, enlightenment), which belongs with skills; +- quests. + +Pets and quests are things you keep open while playing, so they get their own windows. + +## Skills panel: new Progression tab (ILT worlds only) + +The engine's Skills panel gains a third tab, **Progression**, next to Skills and Attributes & +Vitals. It shows only when RynthAi reports an ILT-like world. It has three sections: + +- **XP planner**: XP for the next raise and for the next N raises (slider 1-100) of every attribute + and vital. Costs are computed exactly from the client's XP tables (`SkillDat.CostOf`). The Hub's + version used `/xp all` and +7.5-7.7% per-level estimates. Raising stays on the Attributes & Vitals + tab. +- **Augmentations**: the Hub's planner with the same controls. It has Load /aug, Lum per Enlightened + Coin, and per-aug targets. It shows luminance and coin totals, coins short and banked luminance. +- **Enlightenment**: same controls as the Hub had: + - next step, plan-to-level totals, coins per token and tokens short; + - the requirement checklist; + - Enlighten now, auto-enlighten (arm / spend XP first / check interval). + - "Enlighten now" and arming auto-enlighten ask in a Skills-panel confirmation first. The server + still shows its own Yes/No dialog. + +How it works: + +- RynthAi still owns the planner math and the saved inputs, so the numbers can't drift from the + Hub's. +- New export `RynthPluginGetProgressionJson` (built by `IltHubController.BuildProgressionJson` and + `IltProgression.AppendSnapshotJson`). The engine polls it through the new + `UiSources.Progression` (once a second while the Skills panel is open). +- Edits go back as the remote command `prog `, handled by `IltProgression.HandleRemote` + on the pump thread. The subcommands are `augload`, `augtarget`, `lumpercoin`, `enltarget`, + `coinspertoken`, `enlighten`, `autoenl on|off|arm`, `spendfirst` and `checkevery`. + +## Pets and Quests windows + +- **Pets**: new undocked "Pets" window. Open it with `/ra pets [show|hide|toggle]`, the Pet tab's + "Pop out" button, or Char right-click > Pets window. Closing it docks the roster back into the Pet + tab. It draws only on ILT worlds. The open state is saved per character (`PetsWindowOpen`). +- **Quests**: the existing undocked quest window now carries Quest bonus (`/qb`) above the tracker. + Open it with `/ra quests window [show|hide|toggle]` or Char right-click > Quests window. + +## ILT Hub layout + +- Tabs: **Character · Quests · Pet · Banking · Gear · Games**. Tab buttons are narrower (92 px) so + all six fit the Hub's width. +- **Character**: Session rates, plus a note pointing to the Skills panel's Progression tab. +- **Quests** (new tab): Quest tracker + Quest bonus. It shows "open in its own window / Dock back" + while the Quests window is open. +- **Pet**: the roster with a "Pop out" button. It shows "Dock back" while the Pets window is open. +- Saved tab selections still open the same tab. New tabs are appended to the persisted index list, + and only the display order changed. +- Removed from the Hub: the XP calculator (replaced by the exact Skills-panel planner) and the Hub's + copies of the Augmentations / Enlightenment UI. Unused `/xp all` capture and `/attr` raise code + went with them. The spend-XP-before-auto-enlighten loop is unchanged. + +## Dashboard + +- **Char** launcher, left-click: ILT Hub (unchanged). +- **Char** launcher, right-click (new menu): ILT Hub, Pets window, Quests window, and + Progression (Skills panel). Progression opens the Skills panel on the Progression tab + (`SkillsFace.ShowProgression`). diff --git a/Changelog/2026-10-05-charms-tracking-tab.md b/Changelog/2026-10-05-charms-tracking-tab.md new file mode 100644 index 0000000..39b4690 --- /dev/null +++ b/Changelog/2026-10-05-charms-tracking-tab.md @@ -0,0 +1,58 @@ +# Charms Tracking tab (Settings) - RynthAi 0.5.10-legacy-ui + +Date: 2026-10-05 +Previous RynthAi version: 0.5.9-legacy-ui +Next installer: 2026.10.5.9 (not built yet; includes the Nav breadcrumb / route overlay toggles) + +## Charm list check against ACECustom + +RynthAi's charm registry (`IltHub/IltInventory.cs`, `Charms`) was compared with ACECustom's +`CharmAbilityRegistry.cs`. All 13 registry charms are present with every tier WCID: + +| Charm | WCIDs | Player ability flag | +|-------|-------|---------------------| +| Mana Barrier | 777700001, 777700054, 777710004, 777720004 | 50010 | +| Infinite Casting Stone | 777700019, 777700055 | 50028 | +| Asheron's Favor | 777700020, 777710002, 777720002 | 50030 | +| Artisan's | 777700021, 777710003, 777720003 | 50031 | +| Shrapnel | 777700022 | 50032 | +| Agony | 777700023 | 50033 | +| Split Cast | 777700024 | 50035 | +| Explosive Arrow | 777700025, 777710005, 777720005 | 50036 | +| Omni Strike | 777700026 | 50037 | +| Fork | 777700027, 777710007, 777720007 | 50039 | +| Auto-Rebuff | 777700300 | none (server keeps it in memory) | +| Summon Essence Refill | 78780030 | 9049 | +| Universal Summoning Mastery (universal pet charm) | 78780031 | 50038 | + +Guardian Hand is not an ACECustom registry charm; RynthAi still recognises it by name on the Gear window. + +## New: Settings > Charms Tracking + +The engine Settings panel has a new last sidebar tab, **Charms Tracking**, with one row per charm: + +- **Acquired**: `Carried` (in your pack or equipped, with a count when you have several), + `Stored` (this character carried it before; RynthAi remembers it per character in + `ilt-hub.json`, because the client only sees carried items) or `Not yet`. +- **Status**: `ON` / `OFF` from the charm's appraisal text ("Status: ON"), falling back to the + character's ability flag. Appraisal is requested automatically (throttled to every 30 s per item). +- **Tier**: current / max tier (CharmLevel / CharmMaxLevel, or "Charm [Tier x/y]" from the appraisal). +- **Server**: `Disabled` when the server refused the charm (Auto-Rebuff, Universal Summoning + Mastery) or a feature dump reported it off, `Enabled` when reported on, otherwise `-` + (players can't query the server's /charms list). +- Hover a charm name for its effect. A summary line shows how many are acquired and active. +- Off ILT worlds the tab says so and points to `/ra hub force on`. + +## Fix + +- Pets: an Infinite Casting Stone that is switched OFF no longer counts as "casting supplies" + (an OFF stone doesn't waive spell components). + +## Files + +- RynthSuite: `IltHub/IltCharmTracker.cs` (new), `IltHub/IltInventory.cs` (charm flags, effects, + tier reader, casting-stone check), `IltHub/IltHubState.cs` / `IltHubStore.cs` (`CharmsSeen`), + `IltHub/IltHubController.cs`, `PluginExports.cs` (`RynthPluginGetCharmsJson`), + `RynthAiPlugin.LocalFeatures.cs`, `RynthAiVersionCommand.cs` (0.5.10-legacy-ui). +- RynthCore: `UI/Data/CharmsData.cs` (new `CharmsSource`), `UI/Data/UiSources.cs`, + `ImGui/Panels/SettingsFace.cs` (Charms Tracking tab). \ No newline at end of file diff --git a/Changelog/2026-10-05-chat-standard-filters.md b/Changelog/2026-10-05-chat-standard-filters.md new file mode 100644 index 0000000..9a8e639 --- /dev/null +++ b/Changelog/2026-10-05-chat-standard-filters.md @@ -0,0 +1,70 @@ +# RynthChat: standard (canned) filters and easier custom rules + +**Date:** 2026-10-05 +**Component:** RynthCore Engine — RynthChat filters panel (`UI/Panels/RynthChatFiltersPanel.cs`) + +## Summary + +The Chat Filters window used to be a list of raw regex rows. It now has a +**Standard filters** page of ready-made tick-boxes, modelled on UtilityBelt-IT's +chat filter categories. Custom rules now work with plain text, so you no longer +need to know regex. + +## Standard filters page + +38 canned filters in 6 groups. Each group has **All on** / **All off** buttons and +an "n/total on" count, and a search box at the top narrows the list. + +| Group | Filters | +|---------|---------| +| Combat | Your attacks evaded, You evade attacks, Damage you deal, Damage you take, Your spells resisted, You resist spells, Not-a-PK failures, Dirty Fighting procs, Monster death messages | +| Casting | Your spell words, Others' spell words, Spell fizzles, Component usage, Your buff casts, Buffs others cast on you, Spell expiry (keeps Brilliance / Prodigal / Spectral) | +| Items | Healing kit success / failure, Salvage results / failures, Aura of the Craftsman, Mana stone usage, Periodic healing ticks | +| Social | Trade / buff bot spam (-t- / -b-), Failed assess on you, Kill task complete, General / Trade / LFG / Roleplay / Society channels | +| NPCs | Master Arbitrator (Colosseum) | +| Pets | Pet hits, Pet attacks evaded, Pet damage taken, Pet died, Pet recall blocked, Pet heal overflow | + +- **Tick a box** to hide those lines. **Type a tab name** beside it to move them + to that tab instead; the tab is created automatically, like custom rules do. +- **Hover a filter** to see what it catches and an example line. +- **Player chat is protected:** filters on system text skip the Chat and Channels + tabs, so a player typing the same words in Local is never hidden. +- **Spell words:** ACE sends incantations as chat type 0x11, which RynthChat files + under Combat. "Your spell words" therefore never hides real Local speech. + +## Custom rules page + +- **Match modes:** each rule has a click-to-cycle mode button: **Contains**, + **Starts with**, **Ends with** (plain text, case-insensitive) or **Regex**. + - New rules default to Contains. + - Plain-text modes match the message itself, so the timestamp prefix can't + break "Starts with". + - Regex mode keeps the old behaviour (matches "hh:mm:ss Sender: message"), so + existing rules load and behave exactly as before. +- **Order:** first match wins, and ▲▼ reorder rules. Custom rules are checked + before the standard filters, so a custom rule can override a preset. + +## Line tester + +Paste any chat line at the bottom of the window to see which custom rule or +standard filter catches it, and whether it is hidden or moved. + +- **"as System / Combat / …":** picks the channel the line is treated as arriving on. +- **Not filtered:** if nothing catches the line, the tester names the standard + filter you'd need to tick. +- **Make rule:** turns the test text into a Contains rule, ready to trim down. + +## Settings + +Saved in `%APPDATA%\RynthCore\rynthchat_settings.json`: + +- `filters[].mode`: match mode. When missing, the rule is treated as Regex. +- `presets[]`: `{ id, enabled, tab }`, written only for filters you changed. +- Deleting a custom tab also turns off any standard filter that moved lines to it. + +## Files + +- New: `src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs` +- Rewritten: `src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs` +- Modified: `src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs` (match modes, + preset routing, tester, persistence) diff --git a/Changelog/2026-10-05-chat-translation.md b/Changelog/2026-10-05-chat-translation.md new file mode 100644 index 0000000..d5b8a62 --- /dev/null +++ b/Changelog/2026-10-05-chat-translation.md @@ -0,0 +1,139 @@ +# Chat auto-translation (inbound and outbound) + +**Date:** 2026-10-05 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.31 → 0.6.32 + +## What's new + +RynthAi can translate chat automatically, modelled on UB-IT's Chat Translate tool +but with a choice of translation service. + +- **Incoming:** lines on the channels you tick are translated into your receive + language. Each translation is written back to chat as + `[Translate] [General] Bob (es): Hello everyone`, in the same colour and tab as + the original. It shows in AC's chat window and in RynthChat (the RynthAi + dashboard chat and the RynthChat panel). Lines already in your language are + left alone. +- **Outgoing:** what you type on the ticked channels is held back, translated into + your send language and sent with the same command (`/f`, `/t Bob,`, `/cg`, ...). + This works from AC's chat bar, RynthChat and meta chat commands. Start a line + with `\` to send it untranslated. If the translation fails, the original is sent + instead (this can be switched off). +- **Channels:** each of these can be ticked separately to listen to, send on, or + both: Local, Tell, Fellowship, Allegiance, Patron, Vassals, Covassals, Monarch, + General, Trade, LFG, Roleplay, Society and Olthoi. +- **Translation services:** + - **Google Cloud Translation** (default): needs an API key; 500k characters a + month are free. + - **DeepL:** Free-plan keys ending in `:fx` are sent to the free endpoint + automatically. + - **LibreTranslate:** your own server URL, or the public server with a key. + +### Chat Translate window + +Opened with `/ra translate window` or the Mini Remote's "Window" button. It has: + +- **Header:** Enabled, Incoming and Outgoing switches, counters (translations + done, characters used, requests queued) and the last error. +- **Language row:** Receive, a swap button (<->), Send, and Default (puts the send + language back to the default). +- **Log:** every translation, both directions. Hover a line to see the original. +- **Compose:** pick a channel (and a tell name), type in any language, then + Translate & send, or Preview only. +- **Channels:** a Listen and a Send checkbox for every channel, plus all / none / + defaults buttons. +- **Settings:** the same page as Advanced Settings > Translate. + +### Settings (Advanced Settings > Translate) + +- Service, API key (hidden unless "Show" is ticked) and endpoint. +- **Receive (my language)**, the language incoming chat is in (auto-detect by + default), and the **Default send language**. Every login starts with the + default send language. +- Skip my own lines, write incoming translations to chat, show what I typed after + sending, send the original on failure, the send-untranslated prefix, the minimum + time between requests (750 ms default) and the log size. +- A Test box that translates into the current send language. + +### Mini Remote (hub) + +A new **Translate** row has an on/off box, Receive and Send pickers with a swap +button, a "def" button to go back to the default send language, and a Window +button. It can be hidden from the Mini Remote's right-click menu. + +### Commands + +`/ra translate` (or `/ra tr`): + +- `on` / `off` +- `in [on|off]` and `out [on|off]` +- `window` +- `send `, `recv `, `default ` +- `swap` +- `reset` (send language back to the default) +- `test ` +- With no argument it prints the status. + +## How it works + +- `ChatTranslator` runs on the plugin pump thread. + - Chat hooks and the UI only add work to a queue. + - One HTTP request runs at a time, spaced by the minimum interval. Outgoing + lines go ahead of incoming ones. + - Incoming lines are de-duplicated for 5 s, and the incoming queue is capped at + 40. +- **Incoming parsing:** + - Understands `Name says, "..."`, `Name says on the X channel, "..."`, + `Name tells you, "..."` and the `[Channel]` prefix. + - Removes tell-link markup. + - Expands AC's `` Unicode escapes before translating. + - The channel comes from the prefix, the "on the X channel" text, the chat + colour, or words such as "patron" and "vassal". + - Your own lines and the translator's `[Translate]` echoes are skipped. +- **Outgoing:** + - The translated text is resent through the chat parser with the original + command prefix. + - A short-lived "resend" set lets that line pass back through `OnChatBarEnter` + without being translated again. + - Characters above U+00FF are sent as `` escapes. Latin-1 letters such + as ä and ñ stay as they are. +- **Chat echoes:** `Host.WriteToChat` drops calls made within 100 ms of each other + off AC's main thread, so echoes are queued 150 ms apart and retried when one is + dropped. +- **HTTP:** a single `HttpClient` with a 15 s timeout. Requests are built with + `Utf8JsonWriter` and responses read with `JsonDocument`, which is safe for + NativeAOT (the publish finishes with no trim or AOT warnings). +- **Settings file:** `RynthAi\translate.json` is shared by every character. It is + saved every 2 s, and only when something changed. + +## Notes + +- The API key is stored in plain text in `translate.json`. +- AC's chat font can't draw CJK, Thai or Arabic script. Translations into those + languages show as boxes in AC chat. +- Listening to Local also translates NPC speech, which uses more of your quota. + Local is off by default. +- The Advanced Settings page list gained "Translate" before "Diagnostics". + +## Files + +- New: + - `Translate/ChatTranslator.cs` + - `Translate/TranslateClient.cs` + - `Translate/TranslateSettings.cs` + - `Translate/TranslateChannels.cs` + - `Translate/TranslateLanguages.cs` + - `Translate/AcChatEscapes.cs` + - `Translate/TranslateUi.cs` +- Modified: + - `RynthAiPlugin.cs` + - `RynthAiCommands.cs` + - `Huds/MiniRemoteHud.cs` + - `Huds/HudController.cs` + - `Huds/HudState.cs` + - `LegacyUi/LegacyAdvancedSettingsUi.cs` + - `LegacyUi/LegacyDashboardRenderer.cs` + - `LegacyUi/LegacyUiSettings.cs` + - `LegacyUi/RynthAiJsonContext.cs` + - `RynthCore.Plugin.RynthAi.csproj` diff --git a/Changelog/2026-10-05-floating-window-placement.md b/Changelog/2026-10-05-floating-window-placement.md new file mode 100644 index 0000000..b53319c --- /dev/null +++ b/Changelog/2026-10-05-floating-window-placement.md @@ -0,0 +1,63 @@ +# Floating windows open where they can be seen (RynthAi 0.5.5-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.4-legacy-ui + +## Problem + +New windows with no saved position opened in the top-left corner of the game view: + +- the Pets window at ImGui's default (60,60); +- the Item HUD at (20,220); +- the Mini Remote at (20,120); +- the Dungeon Map in the panel cascade (100,100 and onwards). + +Popped-out panels are separate Windows windows above the game window. They often sit in that +corner, and nothing drawn inside the game frame (ImGui windows included) can appear over them. So +the new windows opened hidden underneath. The draw-order fix (`2026-10-05-imgui-over-avalonia-port.md`) +only covers the Avalonia layer painted inside the game frame. + +## Changes + +### RynthAi (plugin) + +- New `UiPlacement` helper: + - `CenterFirstUse(offset)`: before `Begin`, sets a `FirstUseEver` position centred in the game + view (pivot 0.5,0.5). It only applies when imgui.ini has nothing saved for the window. + - `RescueOncePerShow(ref checked)`: once per show, moves the window to the middle if less than + 40 px of it is on screen. The test is the ILT Hub's existing off-screen check, now shared as + `UiPlacement.IsOnScreen`. +- First-use spots (centre plus offset): + + | Window | First-use spot | + | --- | --- | + | ILT Hub | centre | + | Pets | centre | + | Quests (popped out) | centre + (40,40) | + | Item HUD | centre + (220,-160) | + | Mini Remote | centre + (-220,-160) | + + All five also get the off-screen check each time they're shown. +- The ILT Hub's off-screen rescue now moves the window to the middle of the game view instead of + (40,40), which is where popped-out panels usually sit. + +### Engine + +- `PanelSpec.OpenCentered`: a panel with nothing saved and no `DefaultPos` opens centred in the game + view instead of the cascade. The Dungeon Map uses it. +- Docked panels open clear of popped-out windows. + - When an engine panel opens docked, `ImGuiPanelHost` checks the visible popped-out windows + (`LayeredWindow.VisibleContentRects`: every Avalonia and ImGui pop-out and the floating bar). + - If more than half of the panel would be hidden, it opens at the nearest spot on a 9x9 grid over + the game view that's hidden the least. The open's normal save records that spot. + - Each move is logged as `ImGuiPanelHost: would open under a popped-out window; moved from + (x,y) to (x,y).` + +## Limits + +- Plugin windows (Pets, Quests, Item HUD, Mini Remote, Hub) are centred on first use and pulled back + if off-screen. They don't yet avoid popped-out panels: the plugin can't see where those are. That + would need a new PluginSdk host call. +- ImGui windows still can't draw above popped-out panels. To keep both visible, dock the panel, or + move it away from where the windows open. diff --git a/Changelog/2026-10-05-guardian-and-remote-slots.md b/Changelog/2026-10-05-guardian-and-remote-slots.md new file mode 100644 index 0000000..a462a8b --- /dev/null +++ b/Changelog/2026-10-05-guardian-and-remote-slots.md @@ -0,0 +1,58 @@ +# 2026-10-05 - ILT Guardian window, Mini Remote slot assignment + +RynthAi 0.5.11-legacy-ui (previous 0.5.10-legacy-ui) with the RynthCore engine changes below. +Ships in installer 2026.10.5.10. + +## Guardian window (ported from UB-IT's Guardian tab) + +Open it from the Mini Remote's Options, the dashboard Char button's right-click menu, or +`/ra hub open guardian` (`/ra guardian window`). + +- **Riddle translator.** Translates incoming "Guardian of the Temple of Enlightenment" and + "Guardian of Attribute Enlightenment" tells and says (all 18 Temple spell words and the full + attribute-riddle table, typo-tolerant), plus a paste box for manual translation. The answer + shows in the window and as a "Guardian:" row on the Mini Remote for 10 minutes, with a + Give button. +- **Hand-in.** Gives one of the answer item to the guardian (whole item when it isn't a stack). + For the Temple guardian, when you carry none and "Buy if missing" is on, it first buys one + from the open or nearest vendor through the engine's vendor trade API. It waits out the busy + hourglass, has per-step timeouts, and reports every failure in chat. "Auto hand-in" runs it + after each chat answer (off by default). +- **Attribute turn-ins.** One row per Fiun attribute NPC plus the riddle. Counts and cooldowns + come from /myquests when the server reports the flag, otherwise from "/qb list" wait stamps + (a stamp appearing counts a turn-in and starts an estimated cooldown; "Assumed cooldown" + sets its length). Rows can be overridden with `infi attribute.csv` in the RynthAi folder or + UB's `Documents\Asheron's Call` location. +- **Commands:** `/ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]`. +- **Not ported:** UB's `/fillcomps` + "buy all" spell-component restock during the Temple + hand-in. It is unrelated to the guardian quest, and the engine buys specific items rather + than the client's buy list. + +New files: `IltHub/IltGuardian.cs`, `IltHub/IltGuardianPhrasebook.cs`, `IltHub/IltTempleAttributes.cs`. +Settings persist per character in `ilt-hub.json` (`Guardian` block, `GuardianWindowOpen`). + +## Mini Remote slot assignment + +Previously, items could not be put into Mini Remote slots from the game inventory or from a +popped-out RynthCore Inventory. + +- **Game inventory drag-and-drop (engine `ItemDragBridge`).** A left drag that starts on a + carried item in AC's own inventory is now published to ImGui. Releasing it on an **empty** + Mini Remote slot assigns it. A game drag released over any RynthCore window is handed back + to AC at its starting point, so the item is never dropped on the ground. +- **Popped-out RynthCore Inventory.** Drags from a popped-out Inventory window now reach the + Mini Remote (the pop-out runs in its own ImGui context). +- **Click to assign.** Clicking an item in the RynthCore Inventory also selects it in the game. + The Mini Remote remembers the last carried item you selected for 2 minutes, so the combat + bot re-selecting monsters no longer loses it before you click an empty slot. +- **Inventory right-click: "Add to Mini Remote".** Adds the item to the first empty slot or a + chosen slot (remote command `remoteslot <slot|first> <objectId>`). +- Empty-slot tooltips explain all three ways to assign. + +### Known limits + +- The engine infers a game-inventory drag from AC's selection. Dragging an AC panel while a + pack item is selected looks the same, which is why game drags only fill empty slots. + Dragging from the RynthCore Inventory can replace a filled slot. +- If an AC panel is dragged and released over a RynthCore window while a pack item is selected, + the panel returns to where the drag started. diff --git a/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md b/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md new file mode 100644 index 0000000..bbdbd7b --- /dev/null +++ b/Changelog/2026-10-05-guardian-vendor-and-item-lookup.md @@ -0,0 +1,38 @@ +# ILT Guardian: hand-in finds the vendor and the item in your pack + +**Date:** 2026-10-05 +**Component:** RynthAi 0.5.13-legacy-ui (previous 0.5.12-legacy-ui), `IltHub/IltGuardian.cs` + +## Problem + +The riddle was translated correctly, but the hand-in never got further: + +- **Temple guardian** (Myrrh, Saffron): every attempt failed within ~30 ms with + "no Myrrh carried and no vendor nearby", while Archmage Yuzai Zhen (`0x77F15002`) stood next to you. +- **Attribute guardian** (Ashwood Talisman): after buying the talisman, every attempt failed with + "no Ashwood Talisman in your packs". + +## Causes + +1. The vendor search looked for `ObjectClass == Vendor`. The world cache classifies every creature, + vendors included, as Monster (or Npc later); nothing is ever classed Vendor, so no vendor could match. +2. The item search used the world cache's inventory set. That set is filled asynchronously (a fresh + purchase can be missing), and items from an open vendor's stock land in it too (they have no + position), so it isn't a reliable "what's in my pack" list. + +## Fix + +- Vendors are recognised by the weenie **BF_VENDOR** bitfield flag (`0x200`) through + `TryGetObjectBitfield` (a cache entry classed Vendor still counts). +- The hand-in item is looked up in a **live walk of your pack and side packs** + (`GetDirectInventory(forceRefresh: true)`, AC's container contents with live names). Worn items are skipped. +- Item and vendor-stock names are compared ignoring case and extra spaces. +- When something isn't found, the IltHub log says why: + - `[IltGuardian] no '<item>' among N carried items; similar names: ...` + - `[IltGuardian] vendor search: N landscape objects, bitfield=yes, vendors: '<name>' 0x... <dist> m` + - `[IltGuardian] vendor for '<item>': <name> 0x...` when a vendor is picked. + +## Not changed + +- Buying applies to the Temple guardian only (Attribute guardian items must be carried). +- Search range stays 60 m for the vendor and the guardian. diff --git a/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md b/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md new file mode 100644 index 0000000..8d546da --- /dev/null +++ b/Changelog/2026-10-05-ilt-hub-context-char-hub-logging.md @@ -0,0 +1,59 @@ +# ILT Hub windows draw again, Char/Hub on the ImGui dashboard, hidden-log warning + +**Date:** 2026-10-05 +**Component:** RynthCore Engine (merge branch `merge/aelrynth-2026.10.5.1`, after installer 2026.10.5.2) + +## Summary + +Fixes three problems found testing installer 2026.10.5.2. + +## ILT Hub (and the other RynthAi windows) never appeared + +RynthAi logged `[Overlay] OnRenderOverlay skipped: no ImGui context.` on both clients. + +- **Cause:** the merged engine handed plugins the ImGui context only when the ImGui shell is on. + In this build the shell can only be turned on through an environment variable. RynthAi's own + ImGui windows (ILT Hub, Mini Remote, Inventory HUDs, Item Info, translator window, nav overlay) + draw only with that context, so they all skipped. UbRythai also refused to start without it + (its `Initialize` returns 11). +- **Fix (`ImGui/EngineFrameController.cs`):** plugins also get the context when plugin overlay + windows are enabled (`EnablePluginOverlayWindows`, default on) and the ImGui layer is on. + The plugin host copies the context once at init, so plugin init waits for the first ImGui + frame. The wait is capped at about 5 s (300 pump frames). If ImGui init fails or stalls, + plugins start anyway and a warning is logged. +- The merged RynthAi reads the context only for those windows, so this does not switch it into + its old legacy ImGui UI (the reason upstream withheld it). + +## Char and Hub buttons were missing + +With the ImGui layer on, the engine always shows upstream's ImGui RynthAi dashboard +(`RynthAiFace`) in the game window. Char and Hub had only been ported to the Avalonia dashboard, +which is no longer shown there. + +- **Fix (`ImGui/Panels/RynthAiFace.cs`):** the launcher row now has 10 buttons. After Patrol: + - **Char:** opens the ILT Hub (`/ra hub show`). + - **Hub:** left-click toggles the Mini Remote (`/ra remote`); right-click opens the Inventory + HUDs setup (`/ra huds`). + +## Engine log nearly empty + +The 2026.10.5.2 session logs had only loader lines and two warnings. + +- **Cause:** `engine.json` had `LoggingLevel: Info` with every `LogCategories` entry at + `Trace`. A category's value is the level its lines are written at, so every engine and + plugin line became a Trace line and was dropped by the Info global level. The startup banner + went through the same filter. +- **Fix (`EntryPoint.cs`, `LogSettings.cs`):** + - The startup banner (build, OS/CLR, logging summary) is always written. + - A new warning names any category set above the global level. It is logged at startup and + whenever `engine.json` changes, e.g. `LogSettings: General=Trace, ... write above the + global LoggingLevel (Info), so those lines are NOT logged.` +- Your `engine.json` now has `LoggingLevel: Trace` (changed at 09:10), so the next session + logs everything as-is. + +## Files + +- `src/RynthCore.Engine/ImGui/EngineFrameController.cs` +- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs` +- `src/RynthCore.Engine/LogSettings.cs` +- `src/RynthCore.Engine/EntryPoint.cs` diff --git a/Changelog/2026-10-05-imgui-over-avalonia-port.md b/Changelog/2026-10-05-imgui-over-avalonia-port.md new file mode 100644 index 0000000..438a8e7 --- /dev/null +++ b/Changelog/2026-10-05-imgui-over-avalonia-port.md @@ -0,0 +1,41 @@ +# ImGui windows draw over the Avalonia panels again (merge branch) + +Date: 2026-10-05 +Branch: RynthCore `merge/aelrynth-2026.10.5.1` (local) +Restores: SK-local 6b94752 (draw order part) + +## Problem + +In 2026.10.5.4 the ILT Hub, Mini Remote and Inventory HUDs open, but an Avalonia panel covering +the same screen area hides them. The Hub, saved at about (540,105), 633x786, only shows where no +panel covers it. + +SK-local 6b94752 submitted ImGui draw data after the Avalonia blit. The aelrynth merge took +upstream's `EngineFrameController`. Upstream builds the ImGui frame in `BuildImGuiFrame` and +submits it inside `OnEndScene`, before `EndSceneHook` blits the Avalonia quad. So the panels drew +on top again. + +## Fix + +- `EngineFrameController.OnEndScene` keeps the built frame (device + timing) instead of submitting + it. The pending frame is cleared at the start of every `OnEndScene`, so a frame that throws early + never resubmits stale draw data. +- New `EngineFrameController.RenderDeferredImGui()` submits it once. `UiFrameStats` gets build + + pop-out + submit time, as before. +- `EndSceneHook` calls `RenderDeferredImGui()` after `OverlayTextureRenderer.Render`. It runs even + when the Avalonia blit doesn't (character select), so ImGui draws exactly as before there. +- Popped-out panels still render inside `OnEndScene`. They use their own render targets and restore + AC's target and viewport. + +## Mouse priority (checked, unchanged) + +6b94752's `Win32Backend.ImGuiOwnsMouseOverAvalonia` survived the merge. A mouse message skips the +Avalonia forward while ImGui wants the mouse (`io.WantCaptureMouse` or a monster nameplate), unless +an Avalonia drag/resize holds pointer capture. So clicks on a visible ImGui window go to ImGui, not +to the panel underneath. Only a misplaced doc comment was fixed. + +## Notes + +- ImGui windows and in-client ImGui panels now cover any Avalonia panel or popup they overlap. + Avalonia gets the click only where no ImGui window is under the cursor. +- Engine build only; not in an installer yet. diff --git a/Changelog/2026-10-05-installer-2026.10.4.21-release.md b/Changelog/2026-10-05-installer-2026.10.4.21-release.md new file mode 100644 index 0000000..bf64393 --- /dev/null +++ b/Changelog/2026-10-05-installer-2026.10.4.21-release.md @@ -0,0 +1,46 @@ +# Installer 2026.10.4.21 release (2026-10-05) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.21.exe` +- SHA-256: `5C18E6CEFE3A2A0FA60FEB542FEFB8934DB46E078291840F1571C97AEC0F46E7` +- Deploy package: `installer/Output/RynthCore-2026.10.4.21-deploy.zip` +- Previous release: 2026.10.4.20 (archived in `installer/previous-release/`) +- RynthAi: 0.6.31 + +## Changes + +- **Pet refill loop fix** (RynthAi 0.6.28 + engine). SilentStorm kept re-using Encapsulated + Spirits on a full essence, because the engine served a stale empty charge count. Property + updates now patch the appraisal cache, and the plugin trusts the server's "full" reply and + parks an essence after repeated refills. See `2026-10-04-pet-refill-loop-fix.md`. +- **Item info on click** (RynthAi 0.6.29). Optionally print weapon and armour info to chat on a + left or right click, in the same multi-line layout as pets. See + `2026-10-04-item-info-click-and-pet-layout.md`. +- **Nav editor, waypoint overlay and breadcrumbs** (RynthAi 0.6.30). + - **Editor:** UB-IT-style editing (insert above/below, multi-select, duplicate, reverse, snap + to path, pause / chat / recall / portal steps, Save As), plus route recording with portal + capture and a Simplify tool. + - **Overlay:** a Nav HUD (distance, direction arrow, next step), step labels and a guide line. + - **Breadcrumbs:** a trail you can turn into a route or a backtrack route. + - **Height fix:** waypoints added from the UI, `/ra addnavpt` and the bridge were saved at + the wrong height; a repair tool fixes saved routes. + - See `2026-10-04-nav-editor-overlay-breadcrumbs.md`. +- **Mini Remote target and summon** (RynthAi 0.6.31). The Mini Remote shows the creature combat + is attacking (name, distance, health bar) and your summon's health and time left. See + `2026-10-05-mini-remote-target-and-summon.md`. +- **Chat standard filters** (engine). + - **Standard filters:** the Chat Filters window has a page of 38 canned UB-IT-style filters + (combat, casting, items, social, NPC, pets). Tick one to hide those lines, or name a tab to + move them there. + - **Custom rules:** now support plain-text Contains / Starts with / Ends with as well as regex. + - **Line tester:** shows which filter catches a pasted line. + - See `2026-10-05-chat-standard-filters.md`. + +## Upgrade notes + +- **Settings:** existing chat filter rules load unchanged (they stay in Regex mode). All + standard filters start off. +- **Mini Remote polling:** while it is open, the Mini Remote polls the summon's health every + 3 s and re-queries the combat target afterwards. If mobs start getting blacklisted while + the summon row is showing, report it. +- **Logging:** `engine.json` may still be at `Trace` from earlier debugging; set it back to + `Info` in the launcher. diff --git a/Changelog/2026-10-05-installer-2026.10.4.22-release.md b/Changelog/2026-10-05-installer-2026.10.4.22-release.md new file mode 100644 index 0000000..114c9df --- /dev/null +++ b/Changelog/2026-10-05-installer-2026.10.4.22-release.md @@ -0,0 +1,35 @@ +# Installer 2026.10.4.22 release (2026-10-05) + +- Installer: `installer/Output/RynthCore-Setup-2026.10.4.22.exe` +- SHA-256: `9E29C47918DFAE7CBCF6DEF51386E55D9ECB9B7D410D9E2FEA5D29CE86911379` +- Deploy package: `installer/Output/RynthCore-2026.10.4.22-deploy.zip` +- Previous release: 2026.10.4.21 (archived in `installer/previous-release/`) +- RynthAi: 0.6.32 + +## Changes + +- **Chat auto-translation** (RynthAi 0.6.32). + - **Incoming:** chat on the channels you tick is translated into your receive language and + written back to AC chat and RynthChat as `[Translate] [Channel] Name (lang): text`. + - **Outgoing:** lines you type on the ticked channels are translated into your send language + before they go out. Start a line with `\` to send it untranslated. + - **Channels:** all 14 (Local, Tell, Fellowship, the allegiance channels, General, Trade, + LFG, Roleplay, Society, Olthoi) can be ticked for listen and send separately. + - **Services:** Google Cloud Translation (default), DeepL or LibreTranslate. + - **Where to find it:** + - Chat Translate window: `/ra translate window` + - Settings: Advanced Settings > Translate, which includes the default send language + - Mini Remote: a new row for the receive and send languages, with a swap button + - See `2026-10-05-chat-translation.md`. + +## Upgrade notes + +- **Setup:** translation is off until you add an API key (Settings tab or Advanced Settings > + Translate) and tick Enabled. Outgoing translation also has its own switch, and is off by + default. +- **Settings file:** settings are shared by all characters in `RynthAi\translate.json`. The API + key is stored there in plain text. +- **Fonts:** AC's chat font can't draw CJK, Thai or Arabic script, so translations into those + languages show as boxes in chat. +- **Advanced Settings:** "Translate" was added just above "Diagnostics" in the page list. If + the window was left on Diagnostics, it opens on Translate once. diff --git a/Changelog/2026-10-05-inventory-add-to-item-count-hud.md b/Changelog/2026-10-05-inventory-add-to-item-count-hud.md new file mode 100644 index 0000000..f9ba2ad --- /dev/null +++ b/Changelog/2026-10-05-inventory-add-to-item-count-hud.md @@ -0,0 +1,22 @@ +# Inventory: "Add to item count HUD" (RynthAi 0.5.3-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.2-legacy-ui + +## What's new + +- The in-client **Inventory** panel's right-click menu has **Add to item count HUD** for any item + that isn't a pack. It adds the item, by name, to RynthAi's floating item count HUD and shows the + HUD. You no longer have to select the item in the game first and use the HUD setup window. +- Typed equivalent: `/ra itemhud add <item name>`. +- RynthAi confirms in chat: `Added <name> to the item count HUD.` or `<name> is already on the item + count HUD.` The icon and WCID fill in on the HUD's next pack scan. + +## How it works + +- Engine `InventoryFace` sends the remote command `itemhudadd=<item name>` through + `RynthAiCommands.ApplyRemoteCommand`. +- RynthAi's `ApplyRemoteCommand` queues it to the pump thread and calls + `HudController.AddToItemHudAndShow` (new). `/ra itemhud add` uses the same handler. +- `/ra itemhud [show|hide|toggle]` is unchanged. diff --git a/Changelog/2026-10-05-mini-remote-is-ilt-hub.md b/Changelog/2026-10-05-mini-remote-is-ilt-hub.md new file mode 100644 index 0000000..af2a03b --- /dev/null +++ b/Changelog/2026-10-05-mini-remote-is-ilt-hub.md @@ -0,0 +1,63 @@ +# Mini Remote is the ILT Hub (RynthAi 0.5.8-legacy-ui) + +Date: 2026-10-05 +Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands` + +## What changed + +The tabbed **ILT Hub** window is retired. The **Mini Remote** is now the Hub, the same way +UtilityBelt's ILT Mini Remote works. + +### Mini Remote +- New top row with two buttons: + - **V/H** switches between stacked sections (vertical) and three side-by-side columns + (horizontal). The columns are: status (stats, target, pet, Reset XP / Report), actions + (item slots, toggles) and economy (bank, rebuff, translate). The choice is saved + (`HudState.MiniRemoteHorizontal`). + - **Options** opens the same menu as right-clicking the remote. +- The Options menu has a new **ILT Hub** group at the top: + - Character, Quests, Pets, Banking, Gear and Games each open or close their own window. + An item is ticked while its window is open, and greyed out until the server reports the + feature on. + - A pointer to the Skills panel for Progression. + - On non-ILT worlds: the world status, **Treat this world as ILT** and **Refresh server + features**. +- The Options menu also has a **Horizontal layout** checkbox (same as V/H). +- The empty-bank hint now reads "Options > Banking". + +### Hub section windows +- Each former tab is its own window. Each one opens near the centre the first time and is + moved back on screen if its saved position leaves it off-screen. + - **ILT Character**: world / server-options header (Refresh, Force ILT, Profiles), session + rates, and the Progression note. This window also explains why the Hub is idle on other + worlds. + - **Quests**: quest bonus and quest tracker. The old "Pop out" button is gone, because this + window is now the tracker's only home. + - **Pets**, **Banking**, **Gear**, **Games**. +- Open/closed state is saved per character (`IltCharacterState.CharacterWindowOpen`, + `BankingWindowOpen`, `GearWindowOpen`, `GamesWindowOpen`, plus the existing + `PetsWindowOpen` and `QuestTrackerPoppedOut`). +- The Games HUD, the quest favorites HUD and the confirmation dialog are unchanged. +- Bank auto-refresh and the gear / split-arrow scans used to run only while the Hub window was + open. They now run while the Mini Remote or any Hub section window is open. + +### Commands +- `/ra hub` and `/ra hub show|hide|toggle` now show, hide or toggle the Mini Remote. +- New: `/ra hub open character|quests|pets|banking|gear|games [show|hide|toggle]`. + Aliases: `char`, `rates`, `quest`, `pet`, `bank`, `game`. +- `/ra pets` and `/ra quests window` still work. They are the same as `/ra hub open pets` and + `/ra hub open quests`. + +### Engine dashboard (RynthAiFace) +- **Char** left-click opens the Mini Remote (the Hub). +- **Char** right-click menu: Mini Remote (ILT Hub), then Character, Quests, Pets, Banking, + Gear and Games (each toggles its window), then Progression (Skills panel). + +## Not ported from UtilityBelt's Mini Remote +- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle. +- The LumS, KillL, PassL and Conv rate lines (RynthAi doesn't track these yet). +- Loot-profile and character-profile pickers on the remote. + +## Versions +- RynthAi plugin: 0.5.8-legacy-ui (previous 0.5.7-legacy-ui). +- The next installer is 2026.10.5.8 (previous 2026.10.5.7). diff --git a/Changelog/2026-10-05-mini-remote-target-and-summon.md b/Changelog/2026-10-05-mini-remote-target-and-summon.md new file mode 100644 index 0000000..9a95cb6 --- /dev/null +++ b/Changelog/2026-10-05-mini-remote-target-and-summon.md @@ -0,0 +1,44 @@ +# Mini Remote: attack target and summon health / time left + +**Date:** 2026-10-05 +**Component:** RynthAi plugin (RynthSuite `Plugins/RynthCore.Plugin.RynthAi`) +**Version:** 0.6.30 → 0.6.31 + +## What's new + +The Mini Remote HUD has two new live rows. + +- **Target:** the creature combat is attacking, with its name, distance in yards + and a health bar (green, yellow or red). It reads "Target: none" when combat has + no target, and the bar shows "HP --" until the first health update arrives. +- **Summon:** while your pet is out, shows its name, a health bar and the time + left, with a countdown bar that turns yellow under 90 s and red under 30 s. A + "Healing" tag appears while the ILT Hub heal pet is working. When no pet is out, + the row shows the ILT Hub's next combat essence with Ready / Empty, as before. + +Both rows can be switched off from the Mini Remote's right-click menu ("Attack +target" and "Pet / summon"). + +## How it works + +- A new `CombatHudTracker` runs on the pump thread and publishes an immutable + snapshot for the HUD. It only runs while the Mini Remote and one of these rows + are shown. +- **Target:** comes from `CombatManager.activeTargetId`. Health uses the object + cache's health ratio, which the server already pushes during the fight. +- **Summon:** found as "<Player>'s <Pet>" in the landscape. + - **Time left:** the new pet is appraised once (up to 3 tries, 5 s apart), and + its `RemainingLifespan` (268) anchors a local countdown. `Lifespan` (267) sets + the bar's full length. + - **Fallback:** if the server never reports a lifespan, the row shows how long + the pet has been out instead. + - **Health:** polled with `QueryHealth` every 3 s. The server streams health for + only the most recently queried creature, so each pet poll is followed by a + re-query of the combat target (or your selected target). This keeps combat's + damage detection working. + +## Files + +- New: `Huds/CombatHudTracker.cs` +- Modified: `Huds/MiniRemoteHud.cs`, `Huds/HudController.cs`, `Huds/HudState.cs`, + `RynthAiPlugin.cs`, `RynthCore.Plugin.RynthAi.csproj` diff --git a/Changelog/2026-10-05-native-drag-real-item.md b/Changelog/2026-10-05-native-drag-real-item.md new file mode 100644 index 0000000..19b40f0 --- /dev/null +++ b/Changelog/2026-10-05-native-drag-real-item.md @@ -0,0 +1,49 @@ +# Mini Remote: dragging from the game inventory uses the item you dragged + +**Date:** 2026-10-05 +**Components:** RynthCore.Engine (next installer 2026.10.5.11), RynthAi 0.5.12-legacy-ui (previous 0.5.11-legacy-ui) + +## Problem + +Dragging an item from AC's own inventory onto a Mini Remote slot assigned whatever item was +selected before the drag, not the item being dragged. AC does not change the selected object +when a drag starts, and the engine's drag bridge read the dragged item from the selection. + +Log evidence (session pid 33152): three drags of different items all published +`0x803AAE1B` (Frozen Valley Everlasting Portal Gem, the last clicked item), which landed in slot 17. + +## Fix + +- **New `Compatibility/DragDropHooks.cs`** hooks `UIElementManager::StartDragandDrop` + (`0x0045E120`, thiscall). It resolves the dragged UI element to an object id with AC's own + `UIElement_ItemList::InqDropIconInfo` (`0x004E3380`, cdecl). Same approach as Chorizite's UIHooks. + - Both addresses are resolved by byte patterns that are unique in the shipped client. If either + pattern misses, the hook is skipped (no hard-coded fallback) and the old behavior remains. +- **`ItemDragBridge`** + - `OnNativeDragStart(itemId)` takes the hooked item while a game-owned left press is held, for + carried items only (pack, side pack or worn). Spell-bar drags are ignored. + - Hooked drags are published as `RYNTH_INV_ITEM`, so they can go on **any** slot (and replace an + assigned one), exactly like drags from the RynthCore Inventory. + - The selection guess (`RYNTH_GAME_ITEM`, empty slots only) now runs only when the hook is not installed. + - Released over an ImGui window, the drop is still handed back to AC at the drag's start, so the + item never lands on the ground. +- **RynthAi** — `MiniRemoteHud` comment updated to describe both payloads; version 0.5.12-legacy-ui. + +## Verifying + +The engine log shows, at startup: + +- `HookResolver[DragDrop.InqDropIconInfo]: RESOLVED via pattern-unique @ 0x004E3380` +- `HookResolver[DragDrop.StartDragandDrop]: RESOLVED via pattern-unique @ 0x0045E120` +- `Compat: drag-start hook ready` + +Then, on each AC inventory drag: + +- `DragDropHooks: AC drag start item=0x........` (first 20 drags) +- `ItemDragBridge: native inventory drag 0x........ published to ImGui.` + +## Unchanged + +- Click an item (game inventory or RynthCore Inventory), then click an empty Mini Remote slot. +- RynthCore Inventory right-click **Add to Mini Remote**. +- Drag from the RynthCore Inventory or a popped-out Inventory. diff --git a/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md b/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md new file mode 100644 index 0000000..271a21b --- /dev/null +++ b/Changelog/2026-10-05-nav-breadcrumbs-route-overlay-toggles.md @@ -0,0 +1,36 @@ +# Nav panel: Breadcrumbs and Route overlay toggles (RynthAi 0.5.9-legacy-ui) + +Date: 2026-10-05 +Branches: RynthCore `merge/aelrynth-2026.10.5.1`, RynthSuite `fix/rynthai-launcher-remote-commands` + +## What changed + +### Nav panel (engine, `NavFace`) +A new row under Route / Insert has two checkbox-style toggles. A ticked box and teal text means +on. Both are saved per character in RynthAi's settings. +- **Breadcrumbs**: records the trail you walk and draws it on the ground. Turning it off stops + recording and hides the trail. Turning it back on starts a new trail segment, so the trail + never draws a line across the stretch you walked while it was off. +- **Route overlay**: draws the route in the world: waypoint rings and connecting lines, waypoint + labels, and the guide line to the active waypoint. The waypoint HUD window keeps its own + switch (`/ra navhud`). + +### RynthAi +- `NavOverlaySettings.ShowRouteMarkers` now does something. It was saved but never read, so + route rings always drew. `NavMarkerRenderer` now skips the rings and lines when it is off, + and the waypoint labels and guide line follow it too. +- `NavOverlaySettings.TrackBreadcrumbs` now also hides the drawn trail when off. +- Nav bridge: the snapshot carries `TrackBreadcrumbs` and `ShowRouteOverlay`. New commands + `setBreadcrumbs` and `setRouteOverlay` (with `On`) save the settings. +- Chat commands: + - `/ra navtrail on|off|toggle` (the existing `clear` and the status report still work; the + report now says whether tracking is on). + - New `/ra navoverlay [on|off]` (no argument toggles). + +### Compatibility +- An older RynthAi doesn't send the two flags, so both toggles show off; clicking them does + nothing until RynthAi is updated. + +## Versions +- RynthAi plugin: 0.5.9-legacy-ui (previous 0.5.8-legacy-ui). +- The next installer is 2026.10.5.9 (previous 2026.10.5.8). diff --git a/Changelog/2026-10-05-release-2026.10.5.10.md b/Changelog/2026-10-05-release-2026.10.5.10.md new file mode 100644 index 0000000..178a73f --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.10.md @@ -0,0 +1,25 @@ +# Release 2026.10.5.10 + +Date: 2026-10-05 +Previous release: 2026.10.5.9 +RynthAi plugin: 0.5.11-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.10.exe` (130748020 bytes) +- SHA256: `F63859E43033581B9BC90CB92663F2B2BD9233C6E24E5893775E3DCF1BB4FAAD` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.10-deploy.zip` + +## Included changes + +- ILT Guardian window, ported from UB-IT's Guardian tab: Temple / Attribute guardian riddle + translator (chat auto-detect and paste box), hand-in to the guardian with an optional vendor + buy for the Temple guardian, and the attribute turn-in tracker (/myquests, falling back to + /qb wait stamps). The last answer also shows on the Mini Remote with a Give button. + `/ra guardian ...`. +- Mini Remote slots can now be filled by dragging from AC's own inventory (empty slots) or from + a popped-out RynthCore Inventory. Clicking an item in the RynthCore Inventory selects it in the + game, the remote remembers the last selected pack item for 2 minutes, and the Inventory's + right-click menu has "Add to Mini Remote". + +See `2026-10-05-guardian-and-remote-slots.md` for details and known limits. diff --git a/Changelog/2026-10-05-release-2026.10.5.11.md b/Changelog/2026-10-05-release-2026.10.5.11.md new file mode 100644 index 0000000..06f0c0a --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.11.md @@ -0,0 +1,30 @@ +# Release 2026.10.5.11 + +Date: 2026-10-05 +Previous release: 2026.10.5.10 (saved in `installer/previous-release/`) +RynthAi plugin: 0.5.13-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.11.exe` (130761857 bytes) +- SHA256: `9BE7F21A15C0D175F5F00C252EEA7BF4CAADAF798676EA96B3673E47267C424E` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.11-deploy.zip` + +## Included changes + +- **Mini Remote: drags from AC's own inventory use the dragged item.** The engine hooks AC's + drag start (`UIElementManager::StartDragandDrop`) instead of reading the selection, which AC + leaves on the last clicked item. These drags can now go on any slot, including assigned ones. + See `2026-10-05-native-drag-real-item.md`. +- **ILT Guardian hand-in finds the vendor and the item.** Vendors are recognised by the weenie + vendor flag (nothing was ever classed Vendor, so the nearby vendor was never found), and the + hand-in item is looked up in a live walk of your packs (a fresh purchase was missed). + See `2026-10-05-guardian-vendor-and-item-lookup.md`. + +## What to check in game + +- Engine log at startup: `Compat: drag-start hook ready`. +- Drag an item from the game inventory onto a Mini Remote slot; the log shows + `DragDropHooks: AC drag start item=0x...` with that item's id. +- Temple guardian answer with the item not carried: the IltHub log shows + `[IltGuardian] vendor for '<item>': <vendor>`, then the buy and the give. diff --git a/Changelog/2026-10-05-release-2026.10.5.2.md b/Changelog/2026-10-05-release-2026.10.5.2.md new file mode 100644 index 0000000..11d4ead --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.2.md @@ -0,0 +1,33 @@ +# Release 2026.10.5.2: first build on the aelrynth 2026.10.5.1 merge + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.2.exe` (previous release: 2026.10.4.22) +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67) + +## Summary + +The first installer built from the merge of upstream aelrynth 2026.10.5.1 with SK-local. +The version sorts above upstream's 2026.10.5.1, so the launcher's updater sees it as newer. +This is a test build of the merge: it has not been tested in game yet. + +## What's in it + +- **Engine:** upstream's unloadable CoreCLR engine, hosted by the native loader, with an + app-local .NET 10 runtime in `Runtime\dotnet`. This is the installer's new default; + the previous NativeAOT engine is still available via `Build-Installer.ps1 -NativeAot`. +- **Plugin API v77:** the RynthAi in this installer is built against it. Do not use an + older SK-local RynthAi (0.6.32 or earlier) with this engine. It reads the + merge-stack-result entry from a slot that upstream now uses for something else. +- **RynthAi:** the upstream plugin with the SK-local features wired on (ILT Hub, HUDs, + translation, item info, ground loot, nav overlay). It reports `0.5.1-legacy-ui`. +- **Upstream features and SK-local ports:** see + `2026-10-05-aelrynth-2026.10.5.1-merge.md` for the full list. +- **Decal bridge:** not included in this build (Decal 3.0 is not installed on the build + machine). "Decal + RynthCore" accounts can't run from this installer. + +## Known gaps + +- Several new upstream paths are hard-coded to `C:\Games\...`. Installs in other folders + may log or save to the wrong place. +- The ImGui Items view has no Shields section yet; the Avalonia Items panel has one. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local and is not in this build. diff --git a/Changelog/2026-10-05-release-2026.10.5.3.md b/Changelog/2026-10-05-release-2026.10.5.3.md new file mode 100644 index 0000000..8de883a --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.3.md @@ -0,0 +1,30 @@ +# Release 2026.10.5.3: ILT Hub windows, Char/Hub buttons, logging warning + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.3.exe` (previous release: 2026.10.5.2) +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `merge/aelrynth-2026.10.5.1` (532fa67, unchanged) + +## Summary + +A second test build of the aelrynth 2026.10.5.1 merge, fixing what 2026.10.5.2 got wrong in game. +Details: `2026-10-05-ilt-hub-context-char-hub-logging.md`. + +## Fixes + +- **ILT Hub and RynthAi's other ImGui windows** (Mini Remote, Inventory HUDs, Item Info, + translator, nav overlay) draw again. Plugins now get the engine's ImGui context when plugin + overlay windows are enabled. **UbRythai** starts again too; it refuses to start without that context. +- **Char and Hub buttons** are back on the in-game RynthAi dashboard (the ImGui one): + - Char opens the ILT Hub. + - Hub: left-click toggles the Mini Remote; right-click opens the Inventory HUDs setup. +- **Logging:** + - The engine's startup banner is always written. + - A warning names any log category set above the global LoggingLevel; those categories + are not logged at all. + +## Still open + +- No Decal bridge in this build (Decal 3.0 is not installed on the build machine). +- Several new upstream paths are hard-coded to `C:\Games\...`. +- The ImGui Items view has no Shields section yet. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local. diff --git a/Changelog/2026-10-05-release-2026.10.5.4.md b/Changelog/2026-10-05-release-2026.10.5.4.md new file mode 100644 index 0000000..4e057a0 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.4.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.4: Char/Hub buttons open their windows + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.4.exe` (previous release: 2026.10.5.3) +**SHA-256:** `0546B00D544DF8C97899C62F47FB96EF4655CD0E9662A9E43CE43C962E98F494` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1`; RynthSuite `fix/rynthai-launcher-remote-commands` (8a25c5f, on top of 532fa67) +**Engine:** CoreCLR (app-local runtime) + +## Summary + +A third test build of the aelrynth 2026.10.5.1 merge. Details: +`2026-10-05-rynthai-launcher-remote-commands.md`. + +## Fixes + +- **Char / Hub dashboard buttons** open their windows. 2026.10.5.3 showed the buttons, but RynthAi + threw away the commands they send. The aelrynth merge had dropped `hub` / `huds` / `remote` from + RynthAi's remote-command switch. + - Char opens the ILT Hub (`/ra hub show`). + - Hub: left-click toggles the Mini Remote (`/ra remote toggle`); right-click opens Inventory HUDs (`/ra huds show`). +- RynthAi logs an unknown remote command as `ignored`, not `applied`. +- RynthAi plugin version is 0.5.2-legacy-ui (previous: 0.5.1-legacy-ui). + +## Still open + +- No Decal bridge in this build (Decal 3.0 is not installed on the build machine). +- Several new upstream paths are hard-coded to `C:\Games\...`. +- The ImGui Items view has no Shields section yet. +- RynthAi's 0.6.33 augmentation clamp fix is still stashed on SK-local. diff --git a/Changelog/2026-10-05-release-2026.10.5.5.md b/Changelog/2026-10-05-release-2026.10.5.5.md new file mode 100644 index 0000000..09409ff --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.5.md @@ -0,0 +1,39 @@ +# Release 2026.10.5.5: ImGui draws over Avalonia, Char panel rework, inventory to item count HUD + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.5.exe` (previous release: 2026.10.5.4) +**SHA-256:** `5343A879A06C308094E840C49E14B2F86A4D5E8111E9FE150FE06B7ED4CD09C5` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (69cfe75); RynthSuite `fix/rynthai-launcher-remote-commands` (52f8f95) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.4-legacy-ui + +## Summary + +The fourth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. + +## Fixes + +- **ImGui windows draw on top of Avalonia panels.** The ImGui frame is still built in + `EndScene`, but its draw data is now submitted after `OverlayTextureRenderer.Render`. Before + this, the ILT Hub and other ImGui windows could be hidden behind a docked Avalonia panel. Mouse + priority over ImGui windows (`Win32Backend.ImGuiOwnsMouseOverAvalonia`) survived the merge + unchanged. Details: `2026-10-05-imgui-over-avalonia-port.md`. + +## Features + +- **Inventory panel > right-click > "Add to item count HUD"** adds the item (by name) to the + floating item count HUD and shows it. Typed equivalent: `/ra itemhud add <name>`. Details: + `2026-10-05-inventory-add-to-item-count-hud.md`. +- **Char panel rework**. Details: `2026-10-05-char-panel-rework-progression-pets-quests.md`. + - The Skills panel has a Progression tab (ILT worlds) with: + - an exact XP planner; + - the Augmentation and Enlightenment planners. + - Pets has its own window (`/ra pets`). The Quests window (`/ra quests window`) now includes + Quest bonus. + - ILT Hub tabs: Character (Session rates), Quests, Pet, Banking, Gear, Games. + - Char launcher right-click menu: ILT Hub, Pets window, Quests window, Progression. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.6.md b/Changelog/2026-10-05-release-2026.10.5.6.md new file mode 100644 index 0000000..b6d4dee --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.6.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.6: Floating windows open where they can be seen + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.6.exe` (previous release: 2026.10.5.5) +**SHA-256:** `B4F4410EBC67AAD91CE8FCEAD402CAA046446A3C28501921A350B1E3CCDA77FE` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (3f06ed3); RynthSuite `fix/rynthai-launcher-remote-commands` (871c5d9) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.5-legacy-ui + +## Summary + +The fifth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-floating-window-placement.md`. + +## Fixes + +- **Plugin windows open near the middle the first time.** This covers Pets, the popped-out Quests + window, the Item HUD, the Mini Remote and the ILT Hub. Before, they opened in the top-left corner, + hidden under popped-out panels. +- **Off-screen check.** Each time one of those windows is shown, it moves to the middle if less than + 40 px of it is on screen. The ILT Hub's rescue now uses the middle instead of (40,40). +- **Dungeon Map** opens centred when nothing is saved for it. +- **Engine panels open clear of popped-out windows.** A docked panel that would be more than half + hidden opens at the nearest clearer spot. The move is saved and logged by `ImGuiPanelHost`. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.7.md b/Changelog/2026-10-05-release-2026.10.5.7.md new file mode 100644 index 0000000..80dc4e7 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.7.md @@ -0,0 +1,29 @@ +# Release 2026.10.5.7: RynthAi windows appear again + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.7.exe` (previous release: 2026.10.5.6) +**SHA-256:** `14CD10DAC7F7245528C7BE94A35395A21FA6EDD5679B5EA3A51FA23EB28D4BED` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (b63b9fe); RynthSuite `fix/rynthai-launcher-remote-commands` (3ddd7ea) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.7-legacy-ui + +## Summary + +The sixth test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-rynthai-cimgui-binding.md`. + +## Fixes + +- **RynthAi's own windows draw again.** This covers the Mini Remote, Pets, Quests, ILT Hub, Item HUD + and Inventory HUDs. + - Cause: since the merge, the engine loads `RynthCore.cimgui.dll`, so RynthAi's ImGui calls went to + a second `cimgui.dll` that the engine never draws. + - Fix: RynthAi now binds to the engine's module, as ub-Rythai does. The RynthAi UI log should show + `[ImGui] cimgui bound to loaded RynthCore.cimgui.dll`. +- **Two clients no longer overwrite each other's RynthAi logs.** The second client writes + `{name}.{pid}.txt` beside the first client's file. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + and CS0618 in `EntryPoint.cs`. diff --git a/Changelog/2026-10-05-release-2026.10.5.8.md b/Changelog/2026-10-05-release-2026.10.5.8.md new file mode 100644 index 0000000..3c1a42f --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.8.md @@ -0,0 +1,35 @@ +# Release 2026.10.5.8: the Mini Remote is the ILT Hub + +**Date:** 2026-10-05 +**Installer:** `RynthCore-Setup-2026.10.5.8.exe` (previous release: 2026.10.5.7) +**SHA-256:** `DBB04B9A5FF1B8DC986B4C50421E42814F64DF072BFB805634ECE0F2BBD5A784` +**Sources:** RynthCore `merge/aelrynth-2026.10.5.1` (9408852); RynthSuite `fix/rynthai-launcher-remote-commands` (4d700e3) +**Engine:** CoreCLR (app-local runtime) +**RynthAi:** 0.5.8-legacy-ui + +## Summary + +The seventh test build of the aelrynth 2026.10.5.1 merge. Nothing has been tested in game. +Details: `2026-10-05-mini-remote-is-ilt-hub.md`. + +## Changes + +- **The tabbed ILT Hub window is gone; the Mini Remote is the Hub** (UtilityBelt style). + - The new **V/H** button switches between stacked sections and three columns. + - The new **Options** button (or right-click) opens the Hub's windows: Character, Quests, Pets, + Banking, Gear and Games. Each is its own window. +- `/ra hub` and the dashboard's **Char** button now open the Mini Remote. + - New command: `/ra hub open <section>`. + - Char's right-click menu lists the section windows. +- Bank auto-refresh and the gear scans now run while the Mini Remote or any Hub window is open. + +## Not yet ported from UtilityBelt's Mini Remote + +- Storm and Reset Storm, the Guardian textbox, and the Fellow toggle. +- The LumS, KillL, PassL and Conv rate lines. +- The loot-profile and character-profile pickers. + +## Build notes + +- Only the usual warnings: Decal isn't installed on the build machine, so there's no Decal bridge; + CS0618 in `EntryPoint.cs`; and the existing nullable warnings. diff --git a/Changelog/2026-10-05-release-2026.10.5.9.md b/Changelog/2026-10-05-release-2026.10.5.9.md new file mode 100644 index 0000000..e38a982 --- /dev/null +++ b/Changelog/2026-10-05-release-2026.10.5.9.md @@ -0,0 +1,21 @@ +# Release 2026.10.5.9 + +Date: 2026-10-05 +Previous release: 2026.10.5.8 +RynthAi plugin: 0.5.10-legacy-ui + +## Installer + +- File: `installer/Output/RynthCore-Setup-2026.10.5.9.exe` (130756527 bytes) +- SHA256: `E59D61BF61DE7089D56731F40273661FEF9DF1CEA548759C333DF1077CE138E9` +- Deploy zip: `installer/Output/RynthCore-2026.10.5.9-deploy.zip` + +## Included changes + +- Settings > Charms Tracking tab: every ACECustom registry charm with acquired (Carried / Stored / + Not yet), ON/OFF status, tier and server state. See `2026-10-05-charms-tracking-tab.md`. + The charm list was checked against ACECustom: all 13 charms, including the Infinite Casting Stone + and Universal Summoning Mastery, are present with every tier WCID. +- Nav: Breadcrumbs on/off and Route overlay on/off toggles (Nav panel, `/ra navtrail on|off`, + `/ra navoverlay on|off`). See `2026-10-05-nav-breadcrumbs-route-overlay-toggles.md`. +- Pets: an Infinite Casting Stone switched OFF no longer counts as casting supplies. \ No newline at end of file diff --git a/Changelog/2026-10-05-rynthai-cimgui-binding.md b/Changelog/2026-10-05-rynthai-cimgui-binding.md new file mode 100644 index 0000000..65c0a30 --- /dev/null +++ b/Changelog/2026-10-05-rynthai-cimgui-binding.md @@ -0,0 +1,52 @@ +# RynthAi overlay windows draw again: bind to the engine's cimgui (RynthAi 0.5.6-legacy-ui) + +Date: 2026-10-05 +Branches (local): RynthSuite `fix/rynthai-launcher-remote-commands` +Previous plugin version: 0.5.5-legacy-ui + +## Problem + +Since the aelrynth merge, none of RynthAi's own ImGui windows appear. That covers the ILT Hub, the +Pets and Quests windows, the Mini Remote, the Item HUD and the Inventory HUDs setup. The launcher +buttons and `/ra` commands reach the plugin (`applied remote command: remote=toggle` / +`pets=toggle`), but nothing shows. + +## Cause + +The engine now loads its ImGui build as `RynthCore.cimgui.dll` (log: `ImGuiNative: Loading +...\Runtime\RynthCore.cimgui.dll`). + +RynthAi is NativeAOT. Its ImGui.NET P/Invokes ask for `cimgui`, which no loaded module is named. +Windows therefore loaded a second, different `cimgui.dll` from the install's `Runtime` folder. RynthAi +set that module's context pointer to the engine's context and built its windows through a separate +ImGui instance, so they never reached the engine's draw data. The engine heartbeat shows this: the +plugin's overlay call runs every frame (`overlayCalls` = frames), but `drawLists=3` doesn't change +after `/ra hub show` or `/ra remote toggle`. + +ub-Rythai already avoids this with a DllImport resolver bound to the engine's module (log: +`ub-Rythai: ImGui native resolver bound to engine cimgui.`). RynthAi had no such resolver. + +## Fix + +- New `ImGuiNativeBinding`, called at the top of `RynthAiPlugin.Initialize` before any ImGui call. It + registers `NativeLibrary.SetDllImportResolver` for the ImGui.NET assembly. + - `cimgui` resolves to the loaded `RynthCore.cimgui.dll`, else a loaded `cimgui.dll`, else the + default search (the old behaviour). + - It's registered once per process, so a reused plugin DLL copy doesn't throw. + - Logged in the UI log as `[ImGui] native resolver registered ...` and, on the first ImGui call, + `[ImGui] cimgui bound to loaded RynthCore.cimgui.dll (0x...)`. +- No changes to the windows themselves. The Mini Remote looks as it did before the merge: stats, + ResetXP / Report, item buttons, toggles, profile pickers, Guardian, Translate, Chat XL and Rebuff. + +## Two clients no longer overwrite each other's RynthAi logs (RynthAi 0.5.7-legacy-ui) + +- Before: with two clients running, RynthAi's shared log files (`Logs\Diagnostics\rynthai_*.txt`, + `exceptions_*.txt`, `Trace\*.txt`) lost and garbled lines. Each process opened the file in Append + mode once with `FileShare.ReadWrite`, kept a buffered writer, and wrote at its own end-of-file + offset, overwriting the other client's lines. +- Now each file has one writing process. `RynthLog.OpenWriter` opens it with `FileShare.Read`, so + readers are fine but a second writer is refused. When another client already holds the file, this + process writes `{name}.{pid}.txt` beside it, e.g. `rynthai_2026-10-05.30060.txt`. The engine's own + logs (`RynthCore.{pid}.log`) are per process the same way. +- Retention and pruning are unchanged. The per-process files are `*.txt` in the same folders, so + they age out with the rest. diff --git a/Changelog/2026-10-05-rynthai-launcher-remote-commands.md b/Changelog/2026-10-05-rynthai-launcher-remote-commands.md new file mode 100644 index 0000000..1f22d41 --- /dev/null +++ b/Changelog/2026-10-05-rynthai-launcher-remote-commands.md @@ -0,0 +1,44 @@ +# RynthAi 0.5.2-legacy-ui: Char / Hub launchers open their windows again + +Date: 2026-10-05 +Branch: RynthSuite `fix/rynthai-launcher-remote-commands` (local, based on `merge/aelrynth-2026.10.5.1` @ 532fa67) +Previous plugin version: 0.5.1-legacy-ui + +## Problem + +On 2026.10.5.3 the dashboard's **Char** and **Hub** launcher buttons showed, but clicking them did +nothing: no ILT Hub, no Mini Remote, no Inventory HUDs window. + +The engine log showed every click arriving at RynthAi +(`[RynthAi] applied remote command: hub=show`, `remote=toggle`, `huds=show`), and the overlay was +drawing (`OnRenderOverlay drawing (iltHub=ready)`). The ILT Hub diagnostics had no +`command: /ra hub ...` line for any click. + +## Cause + +The launchers send remote commands through the engine broker into `RynthAiPlugin.ApplyRemoteCommand`. +The aelrynth 2026.10.5.1 version of that switch has no `hub` / `quests` / `huds` / `itemhud` / +`remote` / `miniremote` cases. SK-local had them, and the merge dropped them. The commands fell +through the switch untouched, and the trailing log line still reported them as "applied". + +Typed `/ra hub ...` commands use a separate dispatcher (`DispatchRaCommand`) that still had the cases. +That is why `/ra hub status`, `force on` and `refresh` worked, but no button did. + +## Fix + +- `ApplyRemoteCommand` routes `hub` / `quests` to `IltHubController.HandleCommand`, and routes + `huds` / `itemhud` / `remote` / `miniremote` to `HandleHudCommand`. These are the same handlers as + the typed commands, and both run on the pump thread. +- Unknown remote commands log `ignored unknown remote command: ...` instead of falsely logging + "applied". +- `map` / `lua` were not restored. Upstream's engine owns those windows now. + +## Typed equivalents + +- `/ra hub show`: ILT Hub (the Char button) +- `/ra remote toggle`: Mini Remote (Hub button, left-click) +- `/ra huds show`: Inventory HUDs setup (Hub button, right-click) + +## Not yet shipped + +Built locally; not in an installer yet (next would be 2026.10.5.4). Nothing pushed. diff --git a/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md new file mode 100644 index 0000000..01080f3 --- /dev/null +++ b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md @@ -0,0 +1,45 @@ +# RynthCore 2026.10.5.14 — engine heartbeat is always logged + +**Date:** 2026-10-06 +**Branch:** `fix/heartbeat-always-logged` (from `main` 143eaa9); deployed build is the +same fix cherry-picked onto `fix/restore-sk-features` (the 2026.10.5.13 line) +**Previous release:** 2026.10.5.13 (895a63a) +**Component:** `RynthCore.Engine` only (no plugin API change) + +## Problem + +The launcher killed healthy, in-world clients and relaunched them every few minutes +(Silentkelpie and Silentstorm, 2026-10-06 14:46 to 15:13; launcher log lines +`WEDGE: PID … killed - engine heartbeat silent for >120s while process alive`). + +- The launcher's wedge watchdog treats `RynthCore.<pid>.log` not being written for + 120 s as a dead engine and kills the process. +- The engine's once-a-second heartbeat line (`hb #N … fps= … login= …`) was written + through `RynthLog.Info`, which writes at the **General category's** level. +- With `LoggingLevel = Info` and `General = Trace` (launcher logging settings), the + heartbeat was emitted at Trace and filtered out by the global Info threshold, so the + log went quiet once a character was in-world and the watchdog fired. +- The launcher copies its own `LoggingLevel` into `engine.json` on every launch, so a + hand edit of `engine.json` only lasted until the next relaunch. +- Knock-on effect: relaunches landed while the killed character was still logged in on + the server, and the new client was booted to the end-of-session screen + (`LogOffCharacter(immediate=1)` from `gmEpilogueUI`) about 35 s after launch. + +## Fix + +- New `RynthLog.Heartbeat(string)`: writes unconditionally (every `LoggingLevel`, + including Off), tagged `[INF]`, like `RynthLog.Error` does for errors. +- `HeartbeatLogger` writes the `hb #` line through `RynthLog.Heartbeat`. +- No change to the line format, so every launcher's `WedgeHbRegex` still parses it. + +## Notes + +- The startup warning about categories above the global level stays; it still applies + to every other line. +- Workaround for older engines: set the launcher's global logging level to Trace, or + turn off auto-restart of wedged clients. + +## Files + +- `src/RynthCore.Engine/RynthLog.cs` — `Heartbeat` method. +- `src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs` — heartbeat uses it. diff --git a/Changelog/2026-10-06-upstream-snapshot-comparison.md b/Changelog/2026-10-06-upstream-snapshot-comparison.md new file mode 100644 index 0000000..c7696a1 --- /dev/null +++ b/Changelog/2026-10-06-upstream-snapshot-comparison.md @@ -0,0 +1,117 @@ +# Upstream snapshot comparison: rynth/RynthCore 2026.10.6.1 vs GitHub main + +Date: 2026-10-06 +Report only. Nothing has been merged or pushed. + +| Side | Ref | Commit | +|---|---|---| +| Upstream (aelrynth `rynth/RynthCore`) | `aelrynth/main` | `abf9146` Snapshot for release 2026.10.6.1 (internal 1cbe514) | +| GitHub (`BlankenshipG/RynthCore`) | `origin/main` | `143eaa9` feat(ui): nav route editing, progression, charms and chat presets | +| Common base | merge-base | `913a2a0` release 2026.10.5.20 | + +Upstream snapshot not on GitHub: `abf9146`, 93 files, +10168 / -597. + +GitHub commits not upstream. All three are in open rynth/RynthCore PR #2; PR #1 is superseded. +- `9709a39` install-aware paths, logging levels, item drag bridge +- `4be686e` plugin overlay windows and create-time identity seeds +- `143eaa9` nav route editing, progression, charms and chat presets + +## Policy for the next merge + +- **Keep everything we sent up:** + - logging levels and desktop log; + - item drag bridge; + - plugin overlay windows; + - progression, charms and chat presets; + - nav route editing; + - install-aware paths. +- **Bring down the new upstream items flagged below**, merge them in and test them. + +## FLAG: new upstream items to bring down, merge and test + +### New files (38): missing on GitHub +- **Flight recorder** (network capture ring): + - `Net/FlightCapture.cs`, `Net/FlightFormat.cs`, `Net/FlightRecorder.cs`, `Net/FlightRing.cs` + - `tools/FlightRecorderTests` +- **Video patch:** + - `D3D9/VideoPatch.cs`, `D3D9/VideoPatchPolicy.cs`, `ImGui/VideoPatchBanner.cs` + - `tools/VideoPatchTests` +- **Meta editor:** + - `ImGui/Panels/MetaFace.Editor.cs` + - `UI/Data/MetaEditing.cs`, `UI/Data/MetaLocation.cs`, `UI/Data/MetaRuleDto.cs` + - `tools/MetaEditTests` +- **Item count HUD:** + - `ImGui/Panels/ItemCountFace.cs` + - `UI/Data/ItemHudModel.cs`, `UI/Data/ItemHudStore.cs` + - `tools/ItemHudTests` +- **Mini remote:** `ImGui/Panels/MiniRemoteFace.cs`. +- **Engine settings:** + - `Plugins/EngineSettingsFile.cs`, `Plugins/PluginPathDedupe.cs` + - `tools/EngineSettingsTests` +- **Chat filters:** + - `UI/Data/ChatFilterPresets.cs`, `UI/Data/ChatRuleMatching.cs`, `UI/Data/ChatSettingsDto.cs` + - `tools/ChatFilterTests` +- **Panels:** `UI/PanelDestroyFallback.cs`, `tools/PanelWindowTests`. +- **Install paths:** `src/Shared/RynthInstallPaths.cs`, `tools/InstallPathsTests`. See the + overlaps below. + +### Upstream edits to files GitHub never changed (31): merge cleanly +- **Launcher:** `RynthUpdater.NavData`, `UsageStats`. +- **Compatibility:** + - `AcActionTrace`, `AcMainThreadQueue`, `BusyCountHooks`, `ClientActionGates` + - `GameTickHooks`, `HeartbeatLogger`, `InventoryModel`, `LoginLifecycleHooks` + - `RawPacketHooks`, `RynthCoreChatCommands`, `SmartBoxHooks` +- **D3D9:** `AcUiPassHook`, `Nav3DRenderInjector`. +- **ImGui:** + - `ImGuiBar`, `ImGuiPopOuts`, `MonsterHud` + - `MetaFace`, `MetaFace.Schedule`, `P1Faces`, `RynthNavFace` + - `UiDropTargets`, `RynthNavData` +- **Tools:** test project files, `PluginManifestTests/Program.cs`, `tools/pe_pattern.py`. + +### Edited on both sides (24): needs a hand merge (14 conflict in a trial merge) + +Conflicting: +- `RynthCore.App.Avalonia/LauncherDiag.cs`, `MainWindow.axaml.cs`, `RynthCore.App.Avalonia.csproj` +- `Engine/ImGui/EngineFrameController.cs` +- `Engine/ImGui/Panels/ChatFiltersFace.cs`, `Engine/ImGui/Panels/InventoryFace.cs` +- `Engine/LogPaths.cs`, `Engine/RynthCore.Engine.csproj` +- `Engine/UI/Data/ChatData.cs`, `Engine/UI/Data/MetaData.cs` +- `Injector/Program.cs`, `Loader/EntryPoint.cs` +- `StatusAgent/AgentConfig.cs`, `StatusAgent/RynthCore.StatusAgent.csproj` + +Auto-merged, but changed on both sides, so review them: +- `D3D9/EndSceneHook.cs`, `EngineLifecycle.cs`, `EntryPoint.cs` +- `ImGui/Win32Backend.cs` +- `Plugins/EngineSettings.cs`, `Plugins/PluginManager.cs` +- `UI/Data/SettingsData.cs`, `UI/LayeredWindow.cs` +- `Injector.csproj`, `Loader.csproj` + +## Overlaps to resolve when merging + +1. **Install paths: two copies of `RynthInstallPaths`.** GitHub has + `src/RynthCore.App/RynthInstallPaths.cs`; upstream has `src/Shared/RynthInstallPaths.cs`, + linked into several projects. The two differ by about 190 lines. Keep one and update the + links (App, Engine, Injector, Loader, StatusAgent, tests). +2. **Chat presets:** our `UI/Panels/RynthChatPresets.cs` against upstream's + `ChatFilterPresets` / `ChatRuleMatching` / `ChatSettingsDto`, which touch the same + `ChatData.cs` and `ChatFiltersFace.cs`. Review both side by side; don't keep two preset + systems. +3. **Panel destroy:** our posted-destroy fix (PR #2) against upstream's + `PanelDestroyFallback.cs`, both in `LayeredWindow.cs`. +4. **Logging:** our `LogSettings.cs` and logging levels against upstream's `LogPaths.cs` and + `EngineSettingsFile.cs` changes. + +## Suggested test pass after merging + +- New upstream tools: `ChatFilterTests`, `EngineSettingsTests`, `FlightRecorderTests`, + `InstallPathsTests`, `ItemHudTests`, `MetaEditTests`, `PanelWindowTests`, `VideoPatchTests`. +- Existing tools: `PluginManifestTests`, `StatusAgentTests`, `LauncherUpdateTests`, + `NavDataUpdateTests`, `UsageStatsTests`. +- NativeAOT Engine publish. +- In game: + - overlay windows and item drag; + - chat presets and filters; + - meta editor; + - item count HUD; + - video patch banner; + - logging level settings in the launcher. diff --git a/Changelog/2026-10-07-merge-main-into-QOL-items.md b/Changelog/2026-10-07-merge-main-into-QOL-items.md new file mode 100644 index 0000000..8e07510 --- /dev/null +++ b/Changelog/2026-10-07-merge-main-into-QOL-items.md @@ -0,0 +1,66 @@ +# QOL-items: main merged in, PR #10 conflicts resolved (plugin API 80) + +**Date:** 2026-10-07 +**Branch:** `QOL-items` ([PR #10](https://github.com/BlankenshipG/RynthCore/pull/10), into `main`) +**Merged:** `origin/main` 784ddf1 (engine 2026.10.5.16) into `QOL-items` f2bd3b2 +**Plugin API:** 80 (previous: 77 on `QOL-items`, 79 on `main`) + +## Why + +PR #10 could not merge: `main` took the 2026-10-05 evening upstream snapshot (913a2a0) and the +three commits that sent the SK features upstream (9709a39, 4be686e, 143eaa9), and both lines +edited the same 15 files. This merge brings `main` into `QOL-items` so the PR merges cleanly. +Nothing on `main` is rewritten. + +## Plugin API: GetMergeStackResult moves to v80 + +Both lines used API v77 for different table fields: +- `QOL-items`: v77 = `GetMergeStackResultFn`. +- `main` (upstream): v77 = `GetScreenModeFn`, `GetUiHookFlagsFn`; v78 = + `SetServerMessageInterestFn`; v79 = `GetTrainingInfoFn`, `RaiseFn`, `TrainSkillFn`. + +`main`'s numbering is the one upstream ships, so it stays. `GetMergeStackResultFn` is appended +after `TrainSkillFn` as v80, in both the engine's `RynthCoreAPI` and the SDK's +`RynthCoreApiNative`. `PluginContractVersion.Current`, `RynthCoreSdkApiVersion` (SDK targets) and +`RynthCoreHost.HasGetMergeStackResult` (now `Version >= 80`) follow. + +A plugin built against the old `QOL-items` SDK would read the wrong slot for +`GetMergeStackResult`. No RynthSuite plugin calls it, and RynthAi (RynthSuite `main` 272e9f5) +builds against the merged SDK, but rebuild plugins against this SDK before running them on this +engine. + +## Conflicts resolved + +`main`'s side already contains the `QOL-items` change plus upstream's additions in most files, so +those hunks take `main`: +- `ImGui/EngineFrameController.cs`: line endings only; `main` adds the Client::Cleanup guard. +- `ImGui/Panels/NavFace.cs`: header lists the route editor. +- `Plugins/EngineSettings.cs`: `DisabledUiHooks` read before `LoggingLevel`. +- `Plugins/LoadedPlugin.cs`: v77/v78 export pointers, `Manifest`, `NotStartedReason`. +- `RynthLog.cs`: `Heartbeat` (always written), the Move / UseDone traces, `Write` wrapper. +- `UI/Data/ChatData.cs`, `UI/Data/NavData.cs`: route editor fields and requests. +- `UI/Data/SettingsData.cs`, `ImGui/Panels/SettingsFace.cs`, `UI/Panels/SettingsPanel.cs`: the + TraceCategories row next to Button / Text / Status; the Diagnostics tab icon. +- `StatusAgent/AgentConfig.cs`: `CellDatPath` and `NavAtlasPath`. + +Merged by hand: +- `Plugins/PluginContract.cs`: header lists both `RynthPluginRenderOverlay` and + `RynthPluginOnServerMessage`; table as above; `PluginContractVersion` lives only in + `PluginContractVersion.cs`. +- `Plugins/PluginManager.cs`: `main` gathers the plugin list first and loads it afterwards, so + `QOL-items`' duplicate guard (same file name or same resolved path) now records each candidate + as it is accepted instead of after loading. +- `ImGui/Panels/SettingsFace.cs`: git kept two identical copies of `TextRow`, `StatusRow` and + `ButtonRow` (both lines added them); one copy removed. +- `tools/PluginManifestTests`: the table's tail is now the v79 slots then `GetMergeStackResultFn`. + +## Verification + +- `RynthCore.sln` (Release, x86): builds, no errors. +- PluginManifestTests 156/156, LauncherUpdateTests 134/134, TrainingCostTests 70/70, + ReloadDeferralTests 19/19, NetMessageTests 203/203. +- StatusAgentTests does not compile, the same as on `main` (its project compiles + `AgentConfig.cs` without `RynthInstallPaths`); not caused by this merge. +- RynthSuite `main` against this SDK: RynthAi builds; host tests 431 passed, 5 known failures, + 1 unrelated failure (map bake reads the real dats), the same as before. +- No release was built or deployed from this merge. diff --git a/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md new file mode 100644 index 0000000..1dcf913 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md @@ -0,0 +1,32 @@ +# RynthCore 2026.10.5.15 — "Include T11 attributes" in the Add to loot profile popup + +**Date:** 2026-10-07 +**Branch:** `feat/loot-add-t11-checkbox` (from `fix/restore-sk-features` 5926a46) +**Previous release:** 2026.10.5.14 +**Pairs with:** RynthAi 0.5.21-legacy-ui (RynthSuite `feat/loot-add-t11-attributes`) + +## What's new + +The "Add to loot profile" popup has a new **Include T11 attributes** checkbox under Match. The +popup opens from the Inventory panel's right-click menu, or from "Add selected item" in the Loot +Editor. + +- When checked, RynthAi adds the item's T11 conditions to the rule: tier, weapon grade, + damage %, every modifier, slot special and Cast on Strike. Each must be at least as good as + the clicked item's. +- It works with every match mode, and the preview updates as soon as it is toggled. +- The tooltip lists what is added, and why Can Wield and Zone Locked are not: they depend on + the character and on where the item was assessed. +- "(not a T11 item)" shows next to the checkbox when the item isn't T11 gear. + +## Compatibility + +- `LootEditItemRequestDto.IncludeT11` is new; an older RynthAi ignores it. +- `LootEditItemDraftDto.IncludeT11` and `IsT11` are new; an older RynthAi never sends them, so + they read false. With an older RynthAi the checkbox has no effect, and "(not a T11 item)" + shows for every item. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs` +- `src/RynthCore.Engine/UI/Data/LootEditData.cs` diff --git a/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md new file mode 100644 index 0000000..0448368 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md @@ -0,0 +1,51 @@ +# RynthCore engine 2026.10.5.16 — 2026-10-06/07 work brought onto main + +**Date:** 2026-10-07 +**Branch:** `integrate/main-2026-10-07` (from `main` 143eaa9), fast-forwarded into `main` +**Previous release:** 2026.10.5.15 (the T11 checkbox build on `fix/restore-sk-features`) + +## Why + +The night of 2026-10-06 left engine changes on three local branches, none of them on `main`. +This release puts the ones that apply to `main` on it in one line. It pairs with RynthAi +0.5.22-legacy-ui on RynthSuite `main`. + +## What's in it + +| Commit on main | From | Change | +|----------------|------|--------| +| b467573 | `fix/heartbeat-always-logged` 2c67875 | The heartbeat line is written at every logging level (2026.10.5.14) | +| b361152 | `SK-local` f2bd3b2 | Attribute raiser on the Skills face's Progression tab; text and status rows for Server Features | +| ead4828 | `feat/loot-add-t11-checkbox` ef0e6cf | "Include T11 attributes" checkbox in the Add to loot profile popup (2026.10.5.15) | +| (docs) | untracked in the main checkout | The upstream snapshot comparison report (`2026-10-06-upstream-snapshot-comparison.md`) | + +## Left out on purpose + +ab18df2 on `SK-local`, "log CoreCLR-hosted engine AVs immediately in the native crash logger", +patches the crash logger rewrite in `native/SehTrampoline/SehTrampoline.c` from a7cdbee. `main` +never got a7cdbee: its trampoline is the older 406-line version, against 674 lines on `SK-local`, +so the cherry-pick conflicted in four places. a7cdbee also changes create-time object seeding, +which overlaps `main`'s own identity seeds from 4be686e. Bringing the crash logger over is its own +port, and it only takes effect after `scripts/Build-SehTrampoline.ps1` rebuilds the native DLL. +ab18df2 stays on `SK-local` until then. + +5926a46 is the same heartbeat fix as 2c67875 on the `fix/restore-sk-features` line, so it was not +picked twice. + +## Conflicts resolved + +`main` added a TraceCategories settings row in the same places f2bd3b2 adds its Text and Status +rows. Both are kept: +- `UI/Data/SettingsData.cs`: `SettingKind` has `TraceCategories, Text, Status`, and + `TraceCategoryLevels` stays. +- `ImGui/Panels/SettingsFace.cs`: all three switch cases, then `TraceCategoriesRow` / + `SaveCategories`, then `TextRow` / `StatusRow`. +- `UI/Panels/SettingsPanel.cs` (the Avalonia face): all three cases. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs '-p:Version=2026.10.5.16'` to + `out/staged-2026.10.5.16`. It built with no errors, and every warning was already on `main`. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.16. +- Not deployed. The live engine (2026.10.5.15) is built from the `fix/restore-sk-features` line, + not from `main`. diff --git a/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md b/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md new file mode 100644 index 0000000..b06d415 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.17-progression-ub-parity.md @@ -0,0 +1,57 @@ +# RynthCore engine 2026.10.5.17 — Progression tab laid out like UB's ILT Tools XP and Augs tabs + +**Date:** 2026-10-07 +**Previous release:** 2026.10.5.16 (main integration) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.23-legacy-ui, which sends the new snapshot fields. With an older +RynthAi the panel falls back to plain +1 / +10 buttons and the old totals lines. + +## Attribute raiser (`ImGui/Panels/SkillsFace.Progression.cs`) + +- The table now has UB's columns: **Auto** (tick), **Stat**, **Base**, **+1 Level**, **+10 + Levels** and **Order** (arrows). +- The raise buttons fill their cells and are labelled with what they cost: the next-level cost + from `/xp all`, and `~` plus the projected cost for ten levels. + - Teal with a teal border: you can afford it. + - Red and disabled: the known cost is more than your unassigned XP. + - Plain: the cost hasn't been read yet. The button still works and the server decides. + - Tooltips give the exact XP and why a button is off. +- The header shows "Level N Total XP X Unassigned Y". +- "Refresh costs" is now "Refresh XP", with "Last updated: HH:mm:ss" beside it. +- The footnote explains that +10 is a 7.7%-per-level estimate. + +## Augmentations + +- Four buttons, as in UB's Augs tab: + - **Refresh current** reads your levels with `/aug`. RynthAi also does this once when the tab + first opens. + - **Reset targets** sets every target back to the current level. + - **Copy Discord** and **Copy in-game** put RynthAi's ready-made text on the clipboard with + `ImGui.SetClipboardText`. +- The table now has **Current / Target / Inc / Luminance / Coins** columns and a **TOTALS** row. +- **Target** has −/+ step buttons (Ctrl for 100). Typing commits on Enter or when the box loses + focus, so a half-typed number is never sent. It is clamped to current..cap before sending. +- **Lum per e-coin** also commits on Enter or focus loss (it used to send on every keystroke) and + accepts k / m / b / t. +- Under the table: E-coins needed / banked / short, the luminance needed to buy them, and your + banked luminance. + +## Data (`UI/Data/ProgressionData.cs`) + +- `AttrRaiser`: `Updated`, `XpHeader`. +- `AttrRow`: `Known`, `Afford1`, `Afford10`, `Cost10`, `CostFull`, `Cost10Full`. +- `AugPlanner`: `TotalCurrent`, `TotalTarget`, `TotalIncrease`, `TotalLum`, `TotalCoins`, + `CoinsLine`, `LumToBuy`, `CopyDiscord`, `CopyIngame`. +- `AugRow`: `Increase`. +- Every new field has a default, so an older RynthAi's snapshot still deserializes. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -Target out\staged-2026.10.5.17 -EngineOnly -MsBuildArgs + @('-p:Version=2026.10.5.17')`. It built with no errors; the one warning (CS0618 in + `EntryPoint.cs`) was already there. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.17. +- Not deployed. Called with no `-Target`, the script deploys to the live Runtime, and its + status-export check refused this checkout. +- This is a `QOL-items` engine (plugin API 80). Deploy it only together with a RynthAi built + against the `QOL-items` SDK, such as RynthAi 0.5.23. diff --git a/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md b/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md new file mode 100644 index 0000000..980e6bb --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.18-aug-cost-settings.md @@ -0,0 +1,34 @@ +# RynthCore engine 2026.10.5.18 — Aug cost settings in the Progression tab + +**Date:** 2026-10-07 +**Previous release:** 2026.10.5.17 (Progression tab laid out like UB's ILT Tools) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.24-legacy-ui. With an older RynthAi the editor is hidden. + +## What's new + +The Augmentations section has a collapsible **Cost settings for <world>** block. Its header says +whether the world is on the InfiniteLeaftide defaults or has its own (custom) rules. + +- **Tier multipliers:** five boxes (Below S1, From S1, From S2, From S3, From S4). The defaults are + UB's 1 / 4 / 8 / 16 / 24, and decimals are allowed. +- **Per-aug rules:** a table with Base, Growth%, S1, S2, S3, S4, Cap (0 = no limit) and Coins per + level. +- **Reset to InfiniteLeaftide defaults:** drops this world's changes. +- A note explains the formula: level i costs (Base + (i − 1) × Base × Growth% / 100) × the + multiplier of its tier, and a tier starts at its S level. + +Every box commits on Enter or when it loses focus, so a half-typed value never reaches RynthAi. +RynthAi saves the rules for the current world only, and the plan above re-prices on the next +snapshot. + +## Data (`UI/Data/ProgressionData.cs`) + +- `AugPlanner.Config`, of type `AugCostConfig`: World, Custom, Multipliers and Rows. +- `AugCostRule`: Key, Label, Base, Percent, Coins, S1 to S4, and Cap. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -Target out\staged-2026.10.5.18 -EngineOnly -MsBuildArgs + @('-p:Version=2026.10.5.18')`. It built with no errors; the one warning was already there. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.18. diff --git a/Changelog/2026-10-08-installer-2026.10.5.21-release.md b/Changelog/2026-10-08-installer-2026.10.5.21-release.md new file mode 100644 index 0000000..5c5492a --- /dev/null +++ b/Changelog/2026-10-08-installer-2026.10.5.21-release.md @@ -0,0 +1,43 @@ +# Installer 2026.10.5.21 + +**Date:** 2026-10-08 +**Source:** RynthCore `QOL-items` d46cd91; RynthSuite c60243c, built from a clean worktree. +Both are clean in the manifest. **Local only**: the commits are not pushed. +**Previous installer:** 2026.10.5.11, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.21:** Mini Remote drawer on the RynthAi dashboard. Right-click Hub + or use the drawer tab. Adds the new optional plugin export `RynthPluginRenderEmbed` + (`2026-10-08-release-2026.10.5.21-mini-remote-drawer.md`). +- **Engine 2026.10.5.20:** the Add-to-loot T11 tooltip covers stamped tier and gear grade. + Earlier 2026.10.5.x work on this branch is included too. +- **RynthAi 0.5.27-legacy-ui:** the Mini Remote draws inside that drawer, with its own + Options menu. Also includes 0.5.26 (new ACECustom T11 item state for item ID and loot + rules) and the 0.5.23 / 0.5.24 progression and aug-cost work. +- **RynthCore.SehTrampoline.dll** was rebuilt from `SehTrampoline.c`. The prebuilt DLL + predated commit ab18df2 (CoreCLR-hosted engine AVs logged immediately), and the build + refuses a stale DLL. + +## Not included + +- The uncommitted ENL sigil-chain work (RynthAi 0.5.25 working tree, another session). + It ships later as its own release. +- The `feat/skills-augments-tab` engine branch. + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.21.exe`, 125.4 MB, SHA-256 + `9b5ca2a6f41d4615376281f8511a10c2ed614a1b8ec7282be3859a75c302e6cd`. +- `Release-2026.10.5.21/` and `RynthCore-2026.10.5.21-deploy.zip` (124.9 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.21 -RynthSuiteRoot <clean RynthSuite worktree>`. +- The optional RynthJuice and UbRythai plugins are git-ignored and empty in this + checkout. Their sources were copied into the build worktree from the 2026-10-06 build + tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`). +- The manifest lists the RynthAi plugin as `1.0.0+c60243c`: its assembly version. The + in-game version is `/ra version`, 0.5.27-legacy-ui. +- The engine and RynthAi are already deployed live to `C:\Games` (both clients + hot-reloaded). The installer is not yet verified on a fresh install. diff --git a/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md b/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md new file mode 100644 index 0000000..3cdff30 --- /dev/null +++ b/Changelog/2026-10-08-release-2026.10.5.20-t11-item-state.md @@ -0,0 +1,28 @@ +# RynthCore engine 2026.10.5.20 - Add-to-loot text for the new T11 item state + +**Date:** 2026-10-08 +**Previous release:** 2026.10.5.18 (2026.10.5.19 is reserved by the Skills augments-tab work on +`feat/skills-augments-tab`, not yet released) +**Branch:** `QOL-items` +**Pairs with:** RynthAi 0.5.26-legacy-ui + +## Why + +RynthAi 0.5.26 reads the T11 state ACECustom added in its endgame updates: the stamped loot tier +(`ZcTier` 50109, `WeaponAugScaleTier` 9061), the weapon quality roll (`WeaponAugScaleQuality` 9060), +Gear Grade, property slots, Tainted and the jewelry Cast on Strike. "Add to loot profile" with +"Include T11 attributes" now adds the stamped tier and Gear Grade, so the checkbox tooltip had to say so. + +## What changed + +- `ImGui/Panels/LootAddDialog.cs`: the "Include T11 attributes" tooltip lists the server's stamped tier, + gear grade, and that property slots / Tainted are not added. +- No engine-side key tables changed: the new loot keys (T11: Gear Grade, Tier Is Exact, Property + Slots, Tainted, T11 Mod: Cast on Strike, and the named ZcTier / WeaponAugScale* properties) and the + Gear Grade letter table come from RynthAi's editor vocabulary, so the loot editor face shows them + as soon as RynthAi 0.5.26 is loaded. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs @('-p:Version=2026.10.5.20')` +- Previous live engine saved to `C:\Games\RynthCore\PreviousReleases\2026.10.5.18-engine\`. diff --git a/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md b/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md new file mode 100644 index 0000000..c5dd3d6 --- /dev/null +++ b/Changelog/2026-10-08-release-2026.10.5.21-mini-remote-drawer.md @@ -0,0 +1,56 @@ +# RynthCore 2026.10.5.21: Mini Remote drawer on the RynthAi dashboard + +Released 2026-10-08. Previous release: 2026.10.5.20 (T11 item state tooltip). +Pairs with RynthAi 0.5.27-legacy-ui. + +## What's new + +- **Mini Remote drawer.** The RynthAi dashboard has a fourth left-edge drawer, + under Ranges, Loaded files and Patrol. It holds RynthAi's whole Mini Remote: + - session rates with Reset XP / Report + - the attack target and summon health bars, with the summon's time left + - the 5 x 6 item slots (click to use, right-click to assign, drag items in) + - the macro toggles, bank balances and rebuff buttons + - the Translate row and the Guardian answer +- **Options inside the drawer.** The remote's Options button, or a right-click on + it, opens the same menu as the floating window: which sections show, the ILT Hub + windows, horizontal layout, Inventory HUDs setup, and "Floating window too". +- **Opening it.** Use the drawer tab, or right-click the **Hub** launcher (as + right-clicking Patrol opens its drawer). Left-click Hub still toggles the floating + Mini Remote. On a popped-out dashboard (no drawers), right-click Hub shows the + floating Mini Remote. +- The drawer sizes itself to the remote: one column when stacked, three side by side + in horizontal layout. It is never taller than the screen; past that it scrolls. +- The drawer's open / closed state is saved with the dashboard, as line 11 of + `rynthai_avalonia.cache`. + +## Changed + +- Right-click **Hub** no longer opens Inventory HUDs setup directly. It is in the + Mini Remote's Options menu (and `/ra huds`). + +## Plugin API + +- New optional plugin export: + `int RynthPluginRenderEmbed(const char* surface, float width, float height, float* wantWidth, float* wantHeight)` + (Cdecl). + - The engine calls it on the render thread, inside a child window of the size + given, in the main ImGui context. + - The plugin draws the named UTF-8 surface there and reports the content size it + wants. + - Returns 1 if it drew, 0 if it isn't ready or doesn't know the surface. +- The export is resolved at load, like `RynthPluginRenderOverlay`. + - A plugin without it shows a "needs RynthAi 0.5.27 or later" note in the drawer. + - If it throws, the export is switched off for the session; the plugin keeps + running. +- No `RynthCoreAPI` struct change; the API version is unchanged. + +## Files + +- `ImGui/Panels/RynthAiFace.Drawers.cs`: `RemoteDrawer`. +- `ImGui/Panels/RynthAiFace.cs`: the drawer added to the dashboard; Hub right-click. +- `ImGui/Panels/DashboardDrawers.cs`: header comment. +- `Plugins/PluginManager.cs`: `RenderEmbed` (render thread, login gated). +- `Plugins/LoadedPlugin.cs`, `Plugins/PluginLoader.cs`: `RenderEmbedPtr`. +- `Plugins/PluginContract.cs`: export documented. +- `UI/RynthAiDashboardState.cs`: `RemoteOpen` (cache line 11). diff --git a/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md b/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md new file mode 100644 index 0000000..30a9031 --- /dev/null +++ b/Changelog/2026-10-09-release-2026.10.5.22-buffs-picker.md @@ -0,0 +1,37 @@ +# RynthCore 2026.10.5.22: Buffs picker in Loaded Files + +Released 2026-10-09. Previous release: 2026.10.5.21 (Mini Remote drawer). +Pairs with RynthAi 0.5.31-legacy-ui. + +## What's new + +- **Buffs picker.** The RynthAi dashboard's loaded files (the docked Loaded files drawer, and + the header of a popped-out dashboard) have a fifth row, **Buffs:**, under Meta. It lists + "Built-in" (buffing's own list) and every buff profile in `RynthAi\BuffProfiles`; picking one + makes buffing use it. +- **Spells button.** A sparkle button at the end of the Buffs row opens or closes RynthAi's + Spells window, where buff profiles are built. +- **Settings > Buffing** has a "Buff Profiles: Spells..." button that opens the same window. +- The Loaded files tooltips (drawer tab, popped-out caret) list the Buffs choice too. + +## Compatibility + +- With a RynthAi older than 0.5.31 the snapshot has no buff profiles: the row shows "Built-in" + and its picker has nothing to choose; the Spells button does nothing (the plugin logs an unknown + remote command). + +## Files + +- `UI/Data/RynthAiData.cs`: `RynthAiSnapshot.BuffProfiles` / `CurrentBuffName` / + `SelectedBuffIdx`; `RynthAiView.BuffText`. +- `ImGui/Panels/RynthAiFace.cs`: fifth selector slot (picker kind 4), the Buffs row in the + header grid, the Spells button option on `Selector`, caret tooltip. +- `ImGui/Panels/RynthAiFace.Drawers.cs`: the Buffs row and height in `FilesDrawer`, tab tooltip. +- `UI/Data/SettingsData.cs`: Buffing > Buff Profiles button (`spells show`). + +## Checks + +- Release publish (NativeAOT) succeeds. +- RynthAi's host tests check the plugin side of the picker (list, pick by index, snapshot + fields). +- Not yet tried in game. diff --git a/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md b/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md new file mode 100644 index 0000000..dd3d0e5 --- /dev/null +++ b/Changelog/2026-10-10-hookresolver-ui-1.0.1-tmds-dbus-security.md @@ -0,0 +1,24 @@ +# HookResolver UI 1.0.1: Tmds.DBus.Protocol security update + +Released 2026-10-10. Previous release: 1.0.0 (no version was set; the SDK default). +Developer tool only: nothing that ships in the installer changes. + +## What's fixed + +- **Dependabot alert #1 (high), GHSA-xrw6-gwf8-vvr9.** Through Avalonia (Avalonia.FreeDesktop), + `tools/HookResolver.UI` pulled in `Tmds.DBus.Protocol` older than 0.21.3. In those versions a + malicious D-Bus peer can spoof signals, exhaust file descriptors and cause a denial of service. + D-Bus is only used on Linux, so the Windows tool was never exposed, but the alert is real for the + manifest. +- The project now references `Tmds.DBus.Protocol` 0.21.3 directly, the same override the engine + and the launcher already have. + +## Files + +- `tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj`: direct `Tmds.DBus.Protocol` 0.21.3 + reference; `Version` 1.0.1. + +## Checks + +- Release build succeeds with no warnings or errors (no NU1903). +- `dotnet list package --include-transitive` resolves `Tmds.DBus.Protocol` 0.21.3. diff --git a/Changelog/2026-10-10-installer-2026.10.5.24-release.md b/Changelog/2026-10-10-installer-2026.10.5.24-release.md new file mode 100644 index 0000000..e78d235 --- /dev/null +++ b/Changelog/2026-10-10-installer-2026.10.5.24-release.md @@ -0,0 +1,44 @@ +# Installer 2026.10.5.24 + +**Date:** 2026-10-10 +**Source:** RynthCore `main` 75bac26; RynthSuite `main` fc0d7a0. Both are clean in the manifest. +RynthCore 75bac26 is on GitHub `main`. RynthSuite fc0d7a0 (RynthAi 0.5.32) is a local commit, not +pushed yet. +**Previous installer:** 2026.10.5.21, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.24** (same code as the live 2026.10.5.23, now stamped with the installer + version): + - 2026.10.5.23: large-address alignment fix. On a large-address-aware client the 190 + `and r32,0x80000003` sites in AC's unpack code rounded heap blocks above 2 GB to the wrong + size and crashed in open world. The engine now patches them in memory at load + (`2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md`). + - 2026.10.5.22: Buffs picker under Loaded Files and the Spells window button. +- **HookResolver UI 1.0.1:** Tmds.DBus.Protocol pinned to 0.21.3 (GHSA-xrw6-gwf8-vvr9). It is a + developer tool and is not in the installer; listed because its changelog falls in this range. +- **RynthAi 0.5.32-legacy-ui:** + - 0.5.32: Mini Remote / ILT Hub Lum/h follows the bank's luminance property, so + fellowship and zone-share luminance count. + - 0.5.25 (first shipped here): enlightenment planner breaks levels 301-325 down into the + sigil craft chain (crafts left, raw items, e-coin demand). + - 0.5.28 - 0.5.31: Mini Remote drawer without Toggles, item info kept on profile load, + Bounties window, Spells window and buff profiles. + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.24.exe`, 125.5 MB, SHA-256 + `377b3325f6bafc49bf0f892d14227cabc2f500af2c5465b152ccb25302fd6fa2`. +- `Release-2026.10.5.24/` and `RynthCore-2026.10.5.24-deploy.zip` (125.1 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.24` from the main checkouts. +- The optional RynthJuice and UbRythai plugins are not tracked in RynthSuite. Their sources were + copied in from the 2026-10-06 build tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`) for + the build and removed afterwards. +- RynthAi host tests before the build: 470 tests, 464 passed, 5 known failures, 1 failure (the + map bake, which needs the real dat files on this machine - same as 0.5.31). +- The manifest lists the RynthAi plugin as `1.0.0+fc0d7a0`, its assembly version. The in-game + version is `/ra version`, 0.5.32-legacy-ui. +- Not deployed live and not published as an update. Not yet tried on a fresh install. diff --git a/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md new file mode 100644 index 0000000..7b73590 --- /dev/null +++ b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md @@ -0,0 +1,64 @@ +# RynthCore 2026.10.5.23: fix AC crashes when its memory goes above 2 GB + +Released 2026-10-10. Previous release: 2026.10.5.22 (Buffs picker). +No plugin changes; any RynthAi version works with it. + +## What's fixed + +- **Random client crashes on long open-world sessions** (hunting nav routes across many + landblocks while fighting and looting). Windows reported them as faults in `acclient.exe` + (`+0x1271C3`, `+0x12718B`, `+0x126A70`, `+0x139153`) or, when they passed through an engine + hook, in `coreclr.dll`. + +## Cause + +Asheron's Call pads its read and write position to a multiple of 4 bytes when it unpacks dat +files and network messages. It works the padding out as a *signed* `address % 4`. The client +runs large-address-aware, so once a session has used enough memory, AC gets buffers above +2 GB. Their addresses count as negative, the remainder comes out negative, and AC pads 4 +bytes too many. It then reads every later field from the wrong place, writes zeros over real +data, and reads garbage counts until it runs off the end of the memory region. + +A crash dump of kelpie (10 October, 10:32) showed motion table 0x09000009 being unpacked into a +buffer at 0x80438034. The data on disk was fine, but 21 bytes of the in-memory copy were zeroed. +Replaying AC's padding code at that address zeroes the same 21 bytes, and reads the modifier +count as 0xFFFF0000, the value on the crashed stack. At an address below 2 GB the same data +unpacks cleanly. + +## The fix + +At startup the engine finds every place in `acclient.exe` that pads this way (190 in the +retail client) and changes `and reg, 0x80000003` to `and reg, 3` in memory. The remainder is +then 0 to 3 at any address, so AC pads correctly above 2 GB too. Below 2 GB nothing changes. +`acclient.exe` on disk is not modified. A site is only changed when it is followed by AC's +"already aligned" check, so a signed `% 4` of a value that can really be negative is left +alone (one in the retail client: a 16-bit ring index). + +The change stays for the life of the client: a hot reload finds every site already patched +and logs `0 site(s) patched, 190 already patched`. + +To turn it off for diagnostics, add `"EnableLargeAddressAlignmentFix": false` to +`%APPDATA%\RynthCore\engine.json`. The launcher keeps that setting when it saves. + +## Files + +- `Compatibility/LargeAddressAlignmentScan.cs` (new): the byte-pattern scan for the padding + code. +- `Compatibility/LargeAddressAlignmentPatch.cs` (new): finds `.text` in the loaded client, + rewrites each site's immediate (one byte, page protection restored per site), flushes the + instruction cache, and logs the counts. +- `EntryPoint.cs`: runs the patch in early init, right after the multi-client hooks. +- `Plugins/EngineSettings.cs`: the `EnableLargeAddressAlignmentFix` kill-switch. +- `tools/LargeAddressAlignmentTests` (new): offline checks. + +## Checks + +- `tools/LargeAddressAlignmentTests` (31 checks) pass: + - The real `acclient.exe` has 190 sites, including the ones in the crash dumps. + - The 16-bit ring index is left alone. + - A patched image rescans as fully patched. + - Bytes that only look like the pattern are refused. + - The padding above and below 2 GB comes out as expected. +- Release publish of the CoreCLR engine succeeds. +- Not yet run in game. The engine log should show + `Compat: large-address alignment fix - 190 site(s) patched`. diff --git a/Changelog/2026-10-11-build-comp-10-11-merge.md b/Changelog/2026-10-11-build-comp-10-11-merge.md new file mode 100644 index 0000000..1080036 --- /dev/null +++ b/Changelog/2026-10-11-build-comp-10-11-merge.md @@ -0,0 +1,59 @@ +# Local build branch build-comp-10-11: rynth release 2026.10.11.1 plus local work + +**Date:** 2026-10-11 +**Branch:** `build-comp-10-11` (local only, not pushed) + +## Contents + +1. `main` merged with rynth's `aelrynth/main` (release 2026.10.11.1), commit `f71981b`. +2. Inventory multi-select (`feat/inventory-multi-select`, see + `2026-10-11-inventory-multi-select.md`), commit `63db698`. A group drop also keeps rynth's + in-pack slot (`DropOnSelection(..., slot)`). +3. Follow-up fixes (this commit). + +## How the merge was settled + +- **Rynth's side:** + - Discord relay (`DiscordRouteQueue`, `tools/ChatDiscordTests`); + - installer, injector, loader and launcher diagnostics; + - log paths, plugin path dedupe, layered windows; + - chat line colours; + - `EngineSettingsFile.Merge`, which keeps the launcher's keys. Our `EnablePluginOverlayWindows` + and `LoggingLevel` are added to `OwnedKeys`. +- **Shared install paths:** every project links the read-only `src/Shared/RynthInstallPaths.cs`. + Our launcher-only helpers (`ReadSetting`, `DeleteUserSetting`) moved to + `RynthCore.App.Avalonia/InstallerHandoff.cs`. +- **Both:** + - frame controller (keeps plugin overlay windows live); + - panel spec (`DefaultPos`, `OpenCentered`, `NoResize`); + - Win32 backend (`CanRunOnGameThread`); + - chat presets DTO; + - heartbeat logging. + +## Follow-up fixes + +- Settings > RynthAi: one item info toggle. Rynth's second "Item Info On Select" row under + Inventory Management bound the same setting as our "Describe Items When Selected" row in the + Item Info section. The Item Info section stays, with the "Item Info Options" button, and its + tooltip now says the bot's own picks are skipped. +- `RynthCore.Engine.csproj`: the `Tmds.DBus.Protocol` 0.21.3 pin was listed twice (both sides + added it). One remains. + +## Local test install + +- Engine **2026.10.5.27** (previous local release 2026.10.5.26; rynth's 2026.10.11.1 was + installed), published with `scripts\Publish-EngineCoreClr.ps1 -AllowBehind` (this checkout has + no `status-export` branch) to `C:\Games\RynthCore\Runtime`, together with the loader and shim. +- The replaced engine, loader and shim are in + `C:\Games\_rynth-backups\20261011-pre-build-comp-10-11\Runtime`. + +## Verification + +- Engine, App.Avalonia, Injector, Loader and StatusAgent build with 0 errors. +- Tests pass: + - EngineSettingsTests (164) + - ChatDiscordTests (316) + - ChatFilterTests (823) + - InstallPathsTests (56) + - PanelWindowTests + - PluginManifestTests diff --git a/Changelog/2026-10-11-chat-discord-relay.md b/Changelog/2026-10-11-chat-discord-relay.md new file mode 100644 index 0000000..8caf77a --- /dev/null +++ b/Changelog/2026-10-11-chat-discord-relay.md @@ -0,0 +1,83 @@ +# Chat: Discord relay in RynthChat's settings + +**Date:** 2026-10-11 +**Area:** Engine (`RynthCore.Engine`), RynthChat face. Ships with RynthAi 0.5.34-legacy-ui, which +removes RynthAi's own relay (RynthSuite `Changelog/2026-10-11-release-0.5.34-discord-relay-moved-to-chat.md`). + +## What's new + +The chat window can copy chat to Discord, configured from the chat window itself: + +- **Chat > gear menu > Discord:** a "Copy chat to Discord" switch, the relay's status, and + **Discord settings…**, which opens the new **Discord** panel. +- **Discord panel, Routes tab:** a route is one Discord channel and the chat it receives. You can + have as many routes as you like, for example tells to one channel and allegiance to another. + - **Connection:** a webhook URL, or a bot token plus channel ID, with Save, Clear and + **Send test**. The webhook display name defaults to the character's name. Paused routes have a + **Resume** button. + - **Speech channels:** Local, Tell, Fellowship, Allegiance, Patron, Vassals, Covassals, Monarch, + General, Trade, LFG, Roleplay, Society and Olthoi, with All, None and Defaults buttons. The + defaults are tells, fellowship and the allegiance channels. + - **Chat tabs:** every line that shows in a ticked tab is relayed. This covers the built-in tabs + (Chat, Channels, System, Combat, Rynth, Other) and any tabs you have made with chat rules. + - **Keywords:** optional. When set, only lines that contain one of the words are sent. + - **How often:** each route uses the relay's default pacing or its own. The batch window + (0–60 s) groups lines that arrive close together into one message. The message spacing + (1 s–10 min) sets the minimum time between posts. The panel shows the resulting messages per + minute. +- **Settings tab:** + - Who relays: only these characters, skip your own lines, and skip lines a chat rule hides. + - Message format: game time and a `[Character]` tag. + - The default pacing. + - Queue and log limits. +- **Log tab:** what was sent, errors, and pauses. +- **`/rc discord [on|off|status|window|test [route]|resume [route]]`**. + +## Behaviour + +- The relay reads RynthChat's own line feed. It keeps that feed running while the relay is on, + even with the Chat window closed. Scrollback from before the relay started (engine start, hot + reload, switching the relay on) is never re-posted. +- Discord limits are honoured: + - Messages are packed to 2000 characters. + - 429 responses wait for `retry_after`, and the `X-RateLimit-*` buckets are respected. + - 5xx and network errors retry with backoff. + - 400, 401, 403 and 404 pause the route until **Resume**, so a bad credential isn't retried. +- Mentions can't ping (`allowed_mentions.parse = []`), Markdown and `@everyone` are escaped, and + embeds are suppressed. +- Webhook URLs and bot tokens are encrypted with Windows DPAPI for the current user. The plain + text is never saved or logged, and errors are redacted. Encryption and file writes run off AC's + thread. +- Settings are shared by every client and character in + `%AppData%\RynthCore\rynthchat_discord.json`. With several clients in one fellowship or + allegiance, set "only these characters" so each line is posted once. +- **Import:** the first start with no settings file imports RynthAi 0.5.33's + `RynthAi\discord.json`. The import keeps the routes, saved secrets (same DPAPI entropy), channels + and keywords; "other lines" become the Other tab. + +## Files + +- New: `src/RynthCore.Engine/UI/Data/Discord/`: + - `ChatDiscord.cs` (runtime) + - `ChatDiscordLogic.cs` (per-line decisions) + - `ChatDiscordSettings.cs` (settings, store and import) + - `ChatSpeech.cs` (speech channel parsing) + - `DiscordClient.cs`, `DiscordFormat.cs`, `DiscordSecrets.cs` +- New: `src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs` (the Discord panel). +- Changed: + - `UI/Data/ChatData.cs`: new lines and a tick go to the relay from the chat poll. + - `ImGui/Panels/ChatFace.cs`: the Discord section in the gear menu. + - `EntryPoint.cs`: loads the settings and registers the panel when RynthChat is present. + - `EngineLifecycle.cs`: cancels in-flight posts on shutdown. + - `Compatibility/RynthCoreChatCommands.cs`: `/rc discord`. +- New tests: `tools/ChatDiscordTests` (`dotnet run -c Release`): 218 checks, all passing. + +## Verification + +- `dotnet build -c Release` of the engine: no errors and no new warnings. +- NativeAOT `dotnet publish -c Release`: no new trim or AOT warnings. The Avalonia ones are + unchanged. +- `tools/ChatDiscordTests`: PASS (218 checks). The tests cover speech parsing, route selection, + formatting and escaping, scrollback detection, batching, validation of pasted values, the request + body and 429 handling, settings round-trip and repair, the RynthAi import, and DPAPI. +- Not yet tried in game against a live Discord channel. diff --git a/Changelog/2026-10-11-gametick-chatclient-guard.md b/Changelog/2026-10-11-gametick-chatclient-guard.md index 39a980b..5503754 100644 --- a/Changelog/2026-10-11-gametick-chatclient-guard.md +++ b/Changelog/2026-10-11-gametick-chatclient-guard.md @@ -44,3 +44,13 @@ AC's main thread: - An x86 harness against the new DLL: a clean call returns its value, a null read is caught and attributed to the right module, and a call after the caught fault works. Version reports 4. - Not yet seen in game: the chat-server fault can't be reproduced on demand. + +## Installed + +- Published to `C:\Games\RynthCore\Runtime` with `Publish-EngineCoreClr.ps1 -AllowBehind` + (engine file version 2026.10.5.38, plus the loader, shim and trampoline v4). The old trampoline, + loader and shim were in use and were moved aside. +- Clients 8396 and 48400 hot-reloaded to 2026.10.5.38 (gen 2) at 23:34:56. They keep the v3 + trampoline until they restart, so the guard is off for them until then. +- Previous engine: `C:\Games\RynthCore\PreviousReleases\2026.10.5.36-engine`. +- The full installer 2026.10.5.37 predates this fix. diff --git a/Changelog/2026-10-11-installer-2026.10.5.25-release.md b/Changelog/2026-10-11-installer-2026.10.5.25-release.md new file mode 100644 index 0000000..ec1e951 --- /dev/null +++ b/Changelog/2026-10-11-installer-2026.10.5.25-release.md @@ -0,0 +1,38 @@ +# Installer 2026.10.5.25 + +**Date:** 2026-10-11 +**Source:** RynthCore `main` 58b4efe; RynthSuite `feat/discord-chat-relay` 3ffcba7. Both are clean +in the manifest. RynthSuite 3ffcba7 (RynthAi 0.5.33) is on GitHub in +[RynthSuite PR #11](https://github.com/BlankenshipG/RynthSuite/pull/11), stacked on PR #10 (0.5.32). +**Previous installer:** 2026.10.5.24, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.25:** no code changes since 2026.10.5.24, which had the large-address + alignment fix. It is now stamped with the new installer version. +- **RynthAi 0.5.33-legacy-ui:** + - 0.5.33: Discord chat relay. Copies chosen chat channels (tells, fellowship, allegiance and so + on, plus optional keyword filters) to a Discord channel by webhook or bot token. Secrets are + stored with Windows DPAPI for the current user, mentions and Markdown are escaped, and Discord + rate limits are honoured. Window: `/ra discord window` + (`2026-10-11-release-0.5.33-discord-chat-relay.md` in RynthSuite). + - 0.5.32: sigil craft chain in the enlightenment planner; Lum/h from the bank property. + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.25.exe`, 125.5 MB, SHA-256 + `e59e6c9e88569acce4024c00ee5b0e4c821cc74d9153a1101d0781d7de8f5bb2`. +- `Release-2026.10.5.25/` and `RynthCore-2026.10.5.25-deploy.zip` (125.1 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.25` from the local checkouts. +- The optional RynthJuice and UbRythai plugins are not tracked in RynthSuite. Their sources were + copied in from the 2026-10-06 build tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`) for + the build and removed afterwards. +- RynthAi host tests for 0.5.33: 481 tests, 475 passed, 5 known failures, 1 failure (the map bake, + which needs the real dat files on this machine). The 11 Discord relay tests pass. +- The manifest lists the RynthAi plugin by its assembly version. The in-game version is + `/ra version`, 0.5.33-legacy-ui. +- Local build only: not deployed live, not pushed, not published as an update. Not yet tried on + a fresh install. diff --git a/Changelog/2026-10-11-installer-2026.10.5.26-release.md b/Changelog/2026-10-11-installer-2026.10.5.26-release.md new file mode 100644 index 0000000..b2001e5 --- /dev/null +++ b/Changelog/2026-10-11-installer-2026.10.5.26-release.md @@ -0,0 +1,50 @@ +# Installer 2026.10.5.26 + +**Date:** 2026-10-11 +**Source:** +- RynthCore `main` c55c897 (merge of [RynthCore PR #16](https://github.com/BlankenshipG/RynthCore/pull/16)). +- RynthSuite `main` ef46b1c (merge of [RynthSuite PR #12](https://github.com/BlankenshipG/RynthSuite/pull/12)). +- Both are clean in the manifest. + +**Previous installer:** 2026.10.5.25, archived by the build in `installer/previous-release/`. + +## Contents + +- **Engine 2026.10.5.26:** Discord relay in the chat window + (`2026-10-11-chat-discord-relay.md`). + - Chat > gear menu > Discord: a switch, the status, and **Discord settings…**. + - Routes go by webhook or by bot + channel ID. + - Each route picks speech channels and chat tabs, has keywords, and uses the default pacing or + its own. + - Also: who relays, message format, a send log, and `/rc discord`. + - The first start imports RynthAi 0.5.33's `RynthAi\discord.json`. +- **RynthAi 0.5.34-legacy-ui:** RynthAi's own relay is removed, so the engine's is the only one. + `/ra discord` points to the new place + (`2026-10-11-release-0.5.34-discord-relay-moved-to-chat.md` in RynthSuite). + +## Artifacts (`installer/Output/`) + +- `RynthCore-Setup-2026.10.5.26.exe`, 125.6 MB, SHA-256 + `2a6d16dcca8786c23ad7ce6e85c7e1080dddac0864b3305a4121d90ba4b9587c`. +- `Release-2026.10.5.26/` and `RynthCore-2026.10.5.26-deploy.zip` (125.1 MB, hash-verified). + +## Build + +- Command: `Build-Release-All.ps1 -Version 2026.10.5.26` from the local `main` checkouts. +- The optional RynthJuice and UbRythai plugins are not tracked in RynthSuite. Their sources were + copied in from the 2026-10-06 build tree (`C:\Games\Rynthcore\build\sk-attr\RynthSuite`) for + the build and removed afterwards. +- Tests: + - `tools/ChatDiscordTests`: PASS (218 checks). + - RynthAi host tests: 470 tests, 464 passed, 5 known failures, 1 failure (the map bake, which + needs the real dat files on this machine). +- The manifest lists the RynthAi plugin by its assembly version. The in-game version is + `/ra version`, 0.5.34-legacy-ui. +- Local build only: not deployed live and not published as an update. Not yet tried in game. + +## Upstream + +The engine relay is also on the SK fork's `sk` branch (55e75e0), in the standing +[rynth RynthCore PR #6](https://aelrynth.com/git/rynth/RynthCore/pulls/6). There it sits after the +chat face's "Line colours" section and uses the default panel placement. Upstream RynthAi never had +its own relay, so RynthSuite needed no change. diff --git a/Changelog/2026-10-11-installer-2026.10.5.37.md b/Changelog/2026-10-11-installer-2026.10.5.37.md new file mode 100644 index 0000000..b321317 --- /dev/null +++ b/Changelog/2026-10-11-installer-2026.10.5.37.md @@ -0,0 +1,28 @@ +# Full installer 2026.10.5.37 + +Full installer `RynthCore-Setup-2026.10.5.37.exe` (previous full installer: 2026.10.5.26). It is +built with `installer\Build-Installer.ps1 -Version 2026.10.5.37`. + +## What it ships + +- Everything since 2026.10.5.26, which until now only went out as engine-only updates + (2026.10.5.27 to 2026.10.5.36). See the other 2026-10-11 Changelog entries for details: + - the Mini Remote merge (ILT Hub and Infinite Bounties under one window), universal Quests and + Pets tabs, and Character / Server menus; + - tracker and Mini Remote using the same luminance and XP logic; + - Navigation: go to the closest waypoint; + - Items: Remove Missing; + - On Death: recall with a spell or an item; + - inventory multi-select and the inventory attribute filter; + - the Charms tab moved into the ILT Mini Remote; + - Banking updated to ACECustom's current `/bank` (Prestige Coins, deposit, withdraw). +- RynthAi 0.5.45-legacy-ui. The engine, launcher and tools are stamped 2026.10.5.37. Apart from + the version number, the engine is the same code as the installed 2026.10.5.36. + +## Output + +- `installer\Output\RynthCore-Setup-2026.10.5.37.exe`, plus a `RynthCore-Setup.exe` copy. +- The deployment package `installer\Output\Release-2026.10.5.37\` and + `RynthCore-2026.10.5.37-deploy.zip`, containing SHA256SUMS, the release manifest and + RELEASE-NOTES. +- The previous installer is archived in `installer\previous-release\`. diff --git a/Changelog/2026-10-11-installer-2026.10.5.38.md b/Changelog/2026-10-11-installer-2026.10.5.38.md new file mode 100644 index 0000000..230eb75 --- /dev/null +++ b/Changelog/2026-10-11-installer-2026.10.5.38.md @@ -0,0 +1,30 @@ +# Full installer 2026.10.5.38 + +Full installer `RynthCore-Setup-2026.10.5.38.exe` (previous full installer: 2026.10.5.37). It is +built with `installer\Build-Installer.ps1 -Version 2026.10.5.38` from branch `build-comp-10-11` in +both repos. + +## What it ships + +- Everything in 2026.10.5.37 (see `2026-10-11-installer-2026.10.5.37.md`): the Mini Remote merge, + universal Quests and Pets, Character / Server menus, shared tracker logic, closest-waypoint + navigation, Items: Remove Missing, recall on death, inventory multi-select and attribute + filter, Charms in the ILT Mini Remote, ACECustom banking, and RynthJuice and UbRythai. +- New since 2026.10.5.37: + - Game-tick crash guard: a native fault inside AC's `Client::UseTime` (the `chatclient.dll` + null read that took down two clients at 23:22) drops one tick instead of ending the client. + RynthCore.SehTrampoline.dll v4. See `2026-10-11-gametick-chatclient-guard.md`. + - `Publish-EngineCoreClr.ps1` moves a locked trampoline aside so new launches get the new one. + - RynthAi 0.5.46-legacy-ui: `fix/loot-merge-pacing` (24f3c4f), corpses with several + stackable keeps are looted to the end (RynthSuite + `Changelog/2026-10-11-release-0.5.46-loot-merge-pacing.md`). +- The engine, launcher and tools are stamped 2026.10.5.38, the same engine code as the installed + 2026.10.5.38. + +## Output + +- `installer\Output\RynthCore-Setup-2026.10.5.38.exe`, plus a `RynthCore-Setup.exe` copy. +- The deployment package `installer\Output\Release-2026.10.5.38\` and + `RynthCore-2026.10.5.38-deploy.zip`, containing SHA256SUMS, the release manifest and + RELEASE-NOTES. +- The previous installer (2026.10.5.37) is archived in `installer\previous-release\`. diff --git a/Changelog/2026-10-11-inventory-attribute-filter-charms.md b/Changelog/2026-10-11-inventory-attribute-filter-charms.md index e2057a1..1ac2cc5 100644 --- a/Changelog/2026-10-11-inventory-attribute-filter-charms.md +++ b/Changelog/2026-10-11-inventory-attribute-filter-charms.md @@ -70,3 +70,10 @@ The engine builds in Release. The filter has 5 new host tests in RynthSuite (`InventoryAttributeFilterTests`), and all of them pass. Not yet tested in game. + +## Installed + +- Published to `C:\Games\RynthCore\Runtime` (file version 2026.10.5.36). No client was running; it + loads on the next client start. +- Previous engine: `C:\Games\RynthCore\PreviousReleases\2026.10.5.35-engine` and + `C:\Games\_rynth-backups\20261011-pre-attr-filter\Runtime`. diff --git a/Changelog/2026-10-11-items-remove-missing.md b/Changelog/2026-10-11-items-remove-missing.md index de9304b..01e6f66 100644 --- a/Changelog/2026-10-11-items-remove-missing.md +++ b/Changelog/2026-10-11-items-remove-missing.md @@ -14,3 +14,10 @@ - With a RynthAi that lacks `RynthPluginCleanItems`, the click is logged and nothing happens. The engine builds in Release. Not yet tested in game. + +## Installed + +- 2026-10-11 22:41: published to `C:\Games\RynthCore\Runtime` (FileVersion 2026.10.5.34). Both + running clients (pids 33684 and 61616) hot-reloaded to it (gen 3) without errors. +- 2026.10.5.33 is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.33-engine` and + `C:\Games\_rynth-backups\20261011-pre-items-clean\Runtime`. diff --git a/Changelog/2026-10-11-mini-remote-ilt-tabs-guardian.md b/Changelog/2026-10-11-mini-remote-ilt-tabs-guardian.md index 2b73459..972e9e9 100644 --- a/Changelog/2026-10-11-mini-remote-ilt-tabs-guardian.md +++ b/Changelog/2026-10-11-mini-remote-ilt-tabs-guardian.md @@ -45,3 +45,9 @@ - ItemHudTests: 63 assertions pass. - Engine and plugin both build in Release. - In-game checks are listed in the matching RynthSuite changelog. + +## Local test install + +Installed 2026-10-11 to `C:\Games\RynthCore\Runtime` (engine 2026.10.5.29). The previous engine +(2026.10.5.28) is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.28-engine` and +`C:\Games\_rynth-backups\20261011-pre-ilt-tabs`. diff --git a/Changelog/2026-10-11-mini-remote-merge.md b/Changelog/2026-10-11-mini-remote-merge.md index 83ff39c..1a4b2bf 100644 --- a/Changelog/2026-10-11-mini-remote-merge.md +++ b/Changelog/2026-10-11-mini-remote-merge.md @@ -38,3 +38,9 @@ the window shows the engine grid instead. ## Tests - ItemHudTests: PASS (63 assertions). + +## Local test install + +- Engine `2026.10.5.28+f88c931` published to `C:\Games\RynthCore\Runtime` (`-EngineOnly`, so a + running client hot-reloads onto it). +- Previous engine and plugin backed up to `C:\Games\_rynth-backups\20261011-pre-miniremote\`. diff --git a/Changelog/2026-10-11-nav-closest-waypoint-setting.md b/Changelog/2026-10-11-nav-closest-waypoint-setting.md index 314f11e..515d453 100644 --- a/Changelog/2026-10-11-nav-closest-waypoint-setting.md +++ b/Changelog/2026-10-11-nav-closest-waypoint-setting.md @@ -17,3 +17,10 @@ engine doesn't send it. Not yet tested in game. + +## Installed + +- 2026-10-11 22:33: published to `C:\Games\RynthCore\Runtime` (FileVersion 2026.10.5.33). Both + running clients (pids 33684 and 61616) hot-reloaded to it (gen 2) without errors. +- 2026.10.5.32 is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.32-engine` and + `C:\Games\_rynth-backups\20261011-pre-nav-closest\Runtime`. diff --git a/Changelog/2026-10-11-popout-embed-crash.md b/Changelog/2026-10-11-popout-embed-crash.md index 88bc54b..a0b84c2 100644 --- a/Changelog/2026-10-11-popout-embed-crash.md +++ b/Changelog/2026-10-11-popout-embed-crash.md @@ -41,3 +41,10 @@ EndSceneDetour -> EngineFrameController.OnEndScene -> ImGuiPopOuts.RenderAll - The engine builds in Release, and ItemHudTests pass. - Not yet checked in game: the popped-out Mini Remote, with a current and with an older RynthAi. + +## Installed + +- 2026-10-11: published 2026.10.5.30 to `C:\Games\RynthCore\Runtime` + (`Publish-EngineCoreClr.ps1 -EngineOnly`), with RynthAi 0.5.39. +- 2026.10.5.29 is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.29-engine` and + `C:\Games\_rynth-backups\20261011-pre-popout-fix\Runtime`. diff --git a/Changelog/2026-10-11-recall-on-death-setting.md b/Changelog/2026-10-11-recall-on-death-setting.md index 8e3a38b..48a03cc 100644 --- a/Changelog/2026-10-11-recall-on-death-setting.md +++ b/Changelog/2026-10-11-recall-on-death-setting.md @@ -18,3 +18,8 @@ - An older RynthAi ignores the new fields. The engine builds in Release. Not yet tested in game. + +## Installed + +- Published to `C:\Games\RynthCore\Runtime` (file version 2026.10.5.35). Both running clients (pids 33684 and 61616) hot-reloaded to build 2026.10.5.35 cleanly. That was hot reload 3 of 3 for each, so the next engine update needs a client restart. +- Previous engine: `C:\Games\Rynthcore\PreviousReleases\2026.10.5.34-engine` and `C:\Games\_rynth-backups\20261011-pre-death-recall\Runtime`. diff --git a/Changelog/2026-10-11-tracker-lum5m-passup.md b/Changelog/2026-10-11-tracker-lum5m-passup.md index ef4e5b4..7a871ec 100644 --- a/Changelog/2026-10-11-tracker-lum5m-passup.md +++ b/Changelog/2026-10-11-tracker-lum5m-passup.md @@ -42,3 +42,10 @@ kills the same way. The Tracker panel shows the new figures: - The engine builds in Release, and ItemHudTests pass (63 assertions). - Not yet checked in game. + +## Installed + +- 2026-10-11 22:30: published to `C:\Games\RynthCore\Runtime` (FileVersion 2026.10.5.32). No AC + client was running, so nothing hot-reloaded. +- 2026.10.5.31 is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.31-engine` and + `C:\Games\_rynth-backups\20261011-pre-shared-stats\Runtime`. diff --git a/Changelog/2026-10-11-universal-quests-pets.md b/Changelog/2026-10-11-universal-quests-pets.md index cba5c4b..9af451a 100644 --- a/Changelog/2026-10-11-universal-quests-pets.md +++ b/Changelog/2026-10-11-universal-quests-pets.md @@ -27,3 +27,10 @@ - The engine builds in Release, and ItemHudTests pass. - Not yet checked in game. + +## Installed + +- 2026-10-11 22:08: published to `C:\Games\RynthCore\Runtime`. Both running clients (pids 11468 + and 61016) hot-reloaded to it (gen 3) without errors. +- 2026.10.5.30 is saved in `C:\Games\Rynthcore\PreviousReleases\2026.10.5.30-engine` and + `C:\Games\_rynth-backups\20261011-pre-universal-tabs\Runtime`. diff --git a/Changelog/2026-10-12-confirmation-answers-crafting-menu.md b/Changelog/2026-10-12-confirmation-answers-crafting-menu.md new file mode 100644 index 0000000..5110e2d --- /dev/null +++ b/Changelog/2026-10-12-confirmation-answers-crafting-menu.md @@ -0,0 +1,28 @@ +# Engine API v81: answer the server's craft dialog; Char menu > Crafting + +RynthCore engine, branch build-comp-10-11. It pairs with RynthAi 0.5.51 (the Crafting tab). + +## What changed + +- **Confirmation answers** (`Compatibility\ConfirmationResponder.cs`, new): + - Binds `CM_Character::Event_ConfirmationResponse` (0x006A2030, by byte pattern) at probe time + (`ClientHelperHooks`). + - `SmartBoxHooks` hands every ConfirmationRequest (game event 0x0274) to it. When a plugin has + armed that prompt type, the engine reads the "N percent" from the text, answers Yes when N + is at least the plugin's minimum (or the minimum is 0) and No otherwise, and the client's + dialog never opens. AC's handler returns 0 on every path, so skipping it is safe. + - Unarmed prompts go to the client as before and are only recorded. +- **Plugin API v81** (`PluginContract`, `PluginManager`, SDK): + - `ArmConfirmationFn(type, minPercent, timeoutMs)`: one-shot, up to 120 s; timeout 0 disarms. + - `GetLastConfirmationFn(...)`: the last prompt's type, context, percent, outcome (shown, + accepted, declined, send failed) and age, with a sequence number. + - SDK: `RynthCoreHost.HasConfirmationAnswers`, `ArmConfirmation`, `TryGetLastConfirmation`, + `ConfirmationKind`, `ConfirmationOutcome`; `RynthCoreSdkApiVersion` 81. +- **RynthAi Char menu** (`ImGui\Panels\RynthAiFace.cs`): "Crafting" after Pets opens the Mini + Remote's Crafting tab (`/rc miniremote tab crafting`). +- `tools\PluginManifestTests`: the two new slots are checked at the end of the table. + +## Not tested in game yet + +The engine builds and the manifest tests pass (182 assertions). The dialog answer hasn't been +tried against a live server yet. \ No newline at end of file diff --git a/Changelog/2026-10-12-environment-throttle-attack-power-settings.md b/Changelog/2026-10-12-environment-throttle-attack-power-settings.md new file mode 100644 index 0000000..8f618ca --- /dev/null +++ b/Changelog/2026-10-12-environment-throttle-attack-power-settings.md @@ -0,0 +1,39 @@ +# Settings and Damage panel: environment-hit throttle, per-monster attack power + +Engine: the next build after 2026.10.5.38. The version is set when the installer is built. Pairs +with RynthAi 0.5.47-legacy-ui. + +## What changed + +- `UI/Data/SettingsData.cs`: + - New properties: + - `VariablePowerMin` (50) and `VariablePowerMax` (100); + - `MissileEnvironmentResponse` and `MagicEnvironmentResponse` (0 Off, 1 Move closer, + 2 New target, 3 Move closer then new target); + - `EnvironmentImpactLimit` (2), `EnvironmentImpactWindowSec` (20), + `EnvironmentApproachMeters` (6), `EnvironmentMinDistance` (3) and `EnvironmentSkipSec` (30). + - Melee Combat tab: + - a "Variable Power (monster rules)" section with Variable Min % and Max %; + - a "Hitting the Environment" section with Missile Response and the shared numbers (Hits to + trip, Window, Move closer by, Closest, Skip target). + - Spell Combat tab: a "Hitting the Environment" section with Magic Response. +- `UI/Panels/MonstersPanel.cs`: + - `Rule.AttackPower` (default "Default"); + - change detection (`RulesEqual`) includes it. +- `UI/Data/DamageData.cs`: + - `DamageCommands.AttackPowerModes` (Default, High, Reckless, Variable, Reckless + Variable). + - A new rule copied from the DEFAULT line follows it ("Default"), the same as the off hand and pet. + - A rule copied from a name rule keeps that rule's power. +- `ImGui/Panels/DamageDetailFace.cs`: a "Power" combo on every rule, the DEFAULT line included, + next to Damage and Extra vuln. + +What RynthAi does with these settings is described in RynthSuite +`Changelog/2026-10-12-environment-impact-throttle-attack-power.md`. + +## Compatibility + +- An older RynthAi ignores the new settings and the AttackPower field. +- RynthAi 0.5.47 with an older engine keeps its own values, and keeps each rule's power when the + engine sends rules without it. + +The engine builds in Release. Not yet tested in game. diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.39.md b/Changelog/2026-10-12-hot-release-2026.10.5.39.md new file mode 100644 index 0000000..d475cd6 --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.39.md @@ -0,0 +1,50 @@ +# Hot release 2026.10.5.39 (local test deploy) + +A local hot release for testing, deployed to the live install on this machine. There is no installer +and nothing was published. + +## What's deployed + +| Component | Where | Build | +|---|---|---| +| Engine (CoreCLR) | `C:\Games\RynthCore\Runtime\RynthCore.Engine.dll` | 2026.10.5.39, RynthCore build-comp-10-11 `5474b9b` | +| RynthAi plugin (NativeAOT) | `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | 0.5.48-legacy-ui, RynthSuite build-comp-10-11 `fea3a1c` | + +What's new since the 2026.10.5.38 installer: + +- Environment-hit throttle, with separate Missile and Magic responses: move closer, new target, or + move closer then new target. See `RynthSuite/Changelog/2026-10-12-environment-impact-throttle-attack-power.md`. +- Per-monster attack power: High, Reckless, Variable, or Reckless + Variable. It appears as the + Power column on the monster rules, and the settings rows are on the Melee Combat and Spell Combat + tabs. See `Changelog/2026-10-12-environment-throttle-attack-power-settings.md`. +- Upstream's magic position re-sync sidestep, coordinated with the throttle. See + `RynthSuite/Changelog/2026-10-12-magic-resync-port.md`. + +## How it was deployed + +- Engine: `scripts\Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs -p:Version=2026.10.5.39`. + `-AllowBehind` is needed because the script's guard checks a `status-export` branch, and this + repo has no such branch. The engine it replaced (2026.10.5.38) was built from this same branch, + one commit earlier, so nothing was rolled back. +- RynthAi: `dotnet publish -c Release` (NativeAOT, the same way the installer builds it), copied + over the plugin DLL. +- Both injected clients (pid 48400 and 8396) hot-reloaded onto the new engine within about 20 s. + Both staged the new RynthAi build, and their heartbeats were healthy afterwards. Client 48400 has + now used its 3 hot reloads (`MaxHotReloads`): any newer engine needs that client restarted. The + third acclient (pid 15208) isn't injected. New launches get the new files. + +## Previous release (rollback) + +The files that were replaced are saved in `C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.39-hot\`: + +- `Runtime\RynthCore.Engine.dll` and `.pdb`: engine 2026.10.5.38. +- `RynthAi\RynthCore.Plugin.RynthAi.dll`: the RynthAi that was installed before, stamped + 2026.10.12.1 (an upstream build, not the one from the 2026.10.5.38 installer). + +To roll back, copy the RynthAi DLL back first, then the engine pdb and then the engine DLL into +`Runtime\`. Running clients that still have a hot reload left reload onto it by themselves. + +## Versions + +The installer's last-built version stays at 2026.10.5.38. Build the next installer with +`-Version 2026.10.5.39` if nothing else changes, or with 2026.10.5.40 if more work lands first. \ No newline at end of file diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.40.md b/Changelog/2026-10-12-hot-release-2026.10.5.40.md new file mode 100644 index 0000000..793118c --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.40.md @@ -0,0 +1,33 @@ +# Hot release 2026.10.5.40 (local test deploy) + +A local hot release for testing, deployed to the live install on this machine. There is no installer +and nothing was published. + +| Component | Build | +|---|---| +| Engine (CoreCLR), `C:\Games\RynthCore\Runtime` | 2026.10.5.40, RynthCore build-comp-10-11 `a2ddd12` | +| RynthAi (NativeAOT), `C:\Games\RynthSuite\RynthAi` | 0.5.49-legacy-ui, RynthSuite build-comp-10-11 `31a6cfb` | + +What's new over 2026.10.5.39: the Items window colors each weapon by its damage type, and the Pets +roster colors each essence by its damage type, both with UB-ILT's palette. See +`Changelog/2026-10-12-items-damage-type-colors.md` and +`RynthSuite/Changelog/2026-10-12-pets-damage-type-colors.md`. + +## Clients + +- **pid 8396:** reloaded onto engine 2026.10.5.40 and RynthAi 0.5.49. That was its third hot + reload, so any newer engine needs this client restarted. +- **pid 48400:** refused the reload because it had already used its 3 hot reloads. It stays on + 2026.10.5.39 with RynthAi 0.5.48 until it's restarted. +- **pid 15208:** not injected. New launches get the new files. + +## Previous release (rollback) + +The files that were replaced are saved in `C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.40-hot\`: +engine 2026.10.5.39 (dll and pdb) and RynthAi 0.5.48. To roll back, copy the RynthAi DLL back first, +then the engine pdb, then the engine DLL. + +## Versions + +The installer's last-built version stays at 2026.10.5.38. Build the next installer as 2026.10.5.40 +if nothing else changes. \ No newline at end of file diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.41.md b/Changelog/2026-10-12-hot-release-2026.10.5.41.md new file mode 100644 index 0000000..bcfaca1 --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.41.md @@ -0,0 +1,31 @@ +# Hot release 2026.10.5.41 (local test deploy) + +A local hot release for testing, deployed to the live install on this machine. There is no installer +and nothing was published. + +| Component | Build | +|---|---| +| Engine (CoreCLR), `C:\Games\RynthCore\Runtime` | 2026.10.5.41, RynthCore build-comp-10-11 `6ee84bb` (no engine code change since .40) | +| RynthAi (NativeAOT), `C:\Games\RynthSuite\RynthAi` | 0.5.50-legacy-ui, RynthSuite build-comp-10-11 `ccbbf86` | + +What's new over 2026.10.5.40: missile combat's swap between launchers that shoot different ammo. +RynthAi no longer asks for Missile mode until the new launcher and its ammo are on, which ends the +stance flicker. The launcher now goes 400 ms after the old ammo reads off, so the swap takes about +1.5-2 s instead of 5-6 s. See `RynthSuite/Changelog/2026-10-12-missile-launcher-swap-speed.md`. + +## Clients + +- **pid 8396 and pid 48400:** both refused the reload because each has used its 3 hot reloads. + Restart a client to load engine 2026.10.5.41 and RynthAi 0.5.50. +- **pid 15208:** not injected. New launches get the new files. + +## Previous release (rollback) + +The files that were replaced are saved in `C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.41-hot\`: +engine 2026.10.5.40 (dll and pdb) and RynthAi 0.5.49. To roll back, copy the RynthAi DLL back first, +then the engine pdb, then the engine DLL. + +## Versions + +The installer's last-built version stays at 2026.10.5.38. Build the next installer as 2026.10.5.41 +if nothing else changes. \ No newline at end of file diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.42.md b/Changelog/2026-10-12-hot-release-2026.10.5.42.md new file mode 100644 index 0000000..4a0120c --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.42.md @@ -0,0 +1,36 @@ +# Hot release 2026.10.5.42 (local test deploy) + +A local hot release for testing, deployed to the live install on this machine. There is no installer +and nothing was published. + +| Component | Build | +|---|---| +| Engine (CoreCLR), `C:\Games\RynthCore\Runtime` | 2026.10.5.42, RynthCore build-comp-10-11 `edc137d` (plugin API v81) | +| RynthAi (NativeAOT), `C:\Games\RynthSuite\RynthAi` | 0.5.51-legacy-ui, RynthSuite build-comp-10-11 `5af2417` | + +What's new over 2026.10.5.41: the universal Crafting tab (Mini Remote > Character > Crafting, or +RynthCore's RynthAi Char menu > Crafting). It has Armor, Weapons (Melee / Missile / Caster), Jewelry +and Items tinkering, each with Retail and Server sections, plus Chunking / Clap and Split arrows, +which moved off the Gear tab. Engine API v81 answers AC's craft dialog for it: Yes only at the +tab's minimum percent. See `Changelog/2026-10-12-confirmation-answers-crafting-menu.md` and +`RynthSuite/Changelog/2026-10-12-crafting-tab-tinkering.md`. + +## Clients + +- **pid 2256 and pid 64256:** hot-reloaded to engine gen 2 (2026.10.5.42) at 13:04, and each staged + RynthAi 0.5.51. Both logged in and running at about 59 fps afterwards. Each has 2 hot reloads left. +- **pid 15208:** not injected. New launches get the new files. +- The engine's Compat lines aren't written at this install's logging level (Info), so the + confirmation sender's bind line isn't in the logs. If it didn't bind, the Crafting tab falls back + to AC's own dialog. + +## Previous release (rollback) + +The files that were replaced are saved in `C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.42-hot\`: +engine 2026.10.5.41 (dll and pdb) and RynthAi 0.5.50. To roll back, copy the RynthAi DLL back first, +then the engine pdb, then the engine DLL. + +## Versions + +The installer's last-built version stays at 2026.10.5.38. Build the next installer as 2026.10.5.42 +if nothing else changes. \ No newline at end of file diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.43.md b/Changelog/2026-10-12-hot-release-2026.10.5.43.md new file mode 100644 index 0000000..8cfb8e3 --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.43.md @@ -0,0 +1,46 @@ +# Hot release 2026.10.5.43 (local test deploy) + +A local hot release for testing, deployed to the live install on this machine. There is no installer +and nothing was published. + +| Component | Build | +|---|---| +| Engine (CoreCLR), `C:\Games\RynthCore\Runtime` | 2026.10.5.43, RynthCore build-comp-10-11 `a1af0f5` (plugin API v81, no engine code change) | +| RynthAi (NativeAOT), `C:\Games\RynthSuite\RynthAi` | 0.5.52-legacy-ui, RynthSuite build-comp-10-11 `2fcd4e2` | + +What's new over 2026.10.5.42 (all RynthAi, Mini Remote > Character > Crafting): + +- **Trinkets** tab: Infinite Leaftide's Diamond, Ruby, Gromnie Hide and Pyreal by tier (Minor, + Moderate, Major). It can prepare a raw bag on that tier's Ammunition first. +- **Rings** tab: UB-IT's inscription chain (quill on trophy, then on ink, then on a glyph). It also + applies the "Inscription of ..." scrolls to the item selected in AC or to the last Jewelry / + weapon scan. +- **Auto next batch** on every tinker tab. Items finished this session are left out of later + scans, so Leaftide weapon lines can't go on twice. +- **Fix:** the tinker runner now reaches its "done" step. + +See `RynthSuite/Changelog/2026-10-12-crafting-trinkets-rings-autobatch.md`. + +The engine was republished only to version the release and trigger the reload that stages the +new plugin. + +## Clients + +- **pid 64256:** hot-reloaded to engine gen 3 (2026.10.5.43) at 13:18:07, and staged RynthAi + 0.5.52 (hash matches the deployed DLL). +- **pid 2256:** the reload request came at 13:18:05. RynthAi held it while the character was in + combat (ReloadDeferral, 2-minute cap), so it reloaded to gen 3 at 13:20:07 and staged RynthAi + 0.5.52 (hash matches). +- No errors in either log after the reload. Each client has **1 hot reload left** (cap 3). +- **pid 15208:** not injected. New launches get the new files. + +## Previous release (rollback) + +The files that were replaced are saved in `C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.43-hot\`: +engine 2026.10.5.42 (dll and pdb) and RynthAi 0.5.51. To roll back, copy the RynthAi DLL back first, +then the engine pdb, then the engine DLL. + +## Versions + +The installer's last-built version stays at 2026.10.5.38. Build the next installer as 2026.10.5.43 +if nothing else changes. \ No newline at end of file diff --git a/Changelog/2026-10-12-hot-release-2026.10.5.44.md b/Changelog/2026-10-12-hot-release-2026.10.5.44.md new file mode 100644 index 0000000..ff1df4a --- /dev/null +++ b/Changelog/2026-10-12-hot-release-2026.10.5.44.md @@ -0,0 +1,39 @@ +# Hot release 2026.10.5.44 (local test deploy) + +Local hot release for testing. Deployed to the live install on this machine. No installer, +nothing published upstream. + +| Component | Build | +|---|---| +| Engine (CoreCLR), `C:\Games\RynthCore\Runtime` | 2026.10.5.44 | +| RynthAi (NativeAOT), `C:\Games\RynthSuite\RynthAi` | 0.5.53-legacy-ui | + +## What's new over 2026.10.5.43 + +**Augmentations — Refresh current (RynthAi)** + +Current stayed at 0 because `/aug` capture finished on the banner (`---` / +`Advanced Augmentation Levels:`) before `Creature:` lines arrived (chat-hold / pump lag). +Idle now arms only after a level line; Refresh coalesces while `/aug` is in flight; a +passive chat window also fills Current. Status text reports queue / timeout / parse results. + +**Attributes UI (Engine)** + +Skills > Progression merges XP planner + Attribute raiser into one **Attributes** section. +When the server supports infinite attributes, a segment shows **Auto-raise past retail max** +and the `/xp` / `/attr` raiser controls. + +See: +- `RynthSuite/Changelog/2026-10-12-aug-refresh-current-and-attributes-merge.md` +- `RynthCore/Changelog/2026-10-12-progression-attributes-merge.md` + +## Previous release (rollback) + +`C:\Games\RynthCore\HotBackups\20261012-before-2026.10.5.44-hot\` — engine 2026.10.5.43 +and RynthAi 0.5.52. Copy RynthAi back first, then the engine DLL/PDB, then hot-reload. + +## Clients + +Running clients hot-reload when they next pick up the new Runtime / staged plugin (cap +remaining after 2026.10.5.43: **1** per client that already reloaded twice today). +New launches get the new files immediately. diff --git a/Changelog/2026-10-12-items-damage-type-colors.md b/Changelog/2026-10-12-items-damage-type-colors.md new file mode 100644 index 0000000..86b96f2 --- /dev/null +++ b/Changelog/2026-10-12-items-damage-type-colors.md @@ -0,0 +1,20 @@ +# Items panel: weapons colored by damage type, as in UB-ILT + +RynthCore engine, branch build-comp-10-11. It pairs with RynthAi 0.5.49, which colors the Pets +roster with the same palette. + +## What changed + +- `ImGui\Panels\DamageTypeColors.cs` (new): one text color per damage type, from UB-ILT's + `LeaftideDamageTypeVtColors`, the palette its Items, Spell and Pets tabs share: + - Slash 255,180,120. Pierce 240,200,140. Bludgeon 220,190,140. + - Cold 160,210,255. Fire 255,130,70. Acid 160,255,140. + - Lightning 255,240,120. Nether 200,160,255. + - Anything else (Shield, Auto, None) keeps the normal text color. + - RynthAi's `IltHub\IltDamageTypeTint.cs` holds the same values; keep the two tables in step. +- `ImGui\Panels\ItemsFace.cs`: each weapon's name and its Element button are drawn in that + element's color. Changing the element recolors the row at once. Consumables are unchanged. + +## Not tested in game yet + +The engine builds cleanly. The colors haven't been checked in game yet. \ No newline at end of file diff --git a/Changelog/2026-10-12-progression-attributes-merge.md b/Changelog/2026-10-12-progression-attributes-merge.md new file mode 100644 index 0000000..8a68fb4 --- /dev/null +++ b/Changelog/2026-10-12-progression-attributes-merge.md @@ -0,0 +1,12 @@ +# Progression: one Attributes section (2026.10.5.44) + +Skills > Progression merges the old **XP planner** and **Attribute raiser** into a single +**Attributes** section: + +- Retail XP-table costs (next N raises) stay at the top. +- Below a separator, an **Infinite attributes** segment appears when RynthAi reports the + server supports raising past the retail cap (`/xp` + `/attr`), including + **Auto-raise past retail max**. + +Pairs with RynthAi 0.5.53 (aug Refresh current fix). See +`RynthSuite/Changelog/2026-10-12-aug-refresh-current-and-attributes-merge.md`. diff --git a/Changelog/2026-10-13-fellowship-menu-ilt-settings-push-2026.10.5.47.md b/Changelog/2026-10-13-fellowship-menu-ilt-settings-push-2026.10.5.47.md new file mode 100644 index 0000000..59932db --- /dev/null +++ b/Changelog/2026-10-13-fellowship-menu-ilt-settings-push-2026.10.5.47.md @@ -0,0 +1,47 @@ +# RynthCore 2026.10.5.47: Fellowship in the Char menu, no Hub launcher, ILT settings for RynthILT + +Branch `feat/dynamic-sections`, after 8cf45a0 (2026.10.5.46). It pairs with RynthAi 0.5.56 and +RynthILT 0.1.1 on the RynthSuite branch of the same name; build them together. + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.46 | 2026.10.5.47 | + +## RynthAi dashboard + +- **Fellowship in the Char menu.** The Char launcher's right-click menu has **Fellowship** with the + other universal Mini Remote tabs. It runs `/rc miniremote tab fellowship`, which opens the + Mini Remote on RynthAi's Fellowship view. The Char tooltip lists it. +- **The Hub launcher is gone.** It opened the same Mini Remote window as the bar button. The + launcher row is now nine buttons. + - The Mini Remote window: the bar's Mini Remote button, `/rc miniremote`, or Char > Mini Remote. + - The Mini Remote drawer: its drawer tab on the dashboard's edge. + - The drawer's tooltip and its "can't draw here" notes no longer mention Hub. + +## ILT settings for RynthILT + +RynthILT 0.1.1 shows a copy of the Infinite Leaftide settings. The engine now gives it what it needs: + +- **The "servermenu" push also goes to RynthILT** when it is installed. It is sent through + `RynthPluginApplyRemoteCommand`, when it changes and every 10 s, because RynthILT can load after + the last change. A push that isn't delivered is tried again on the next check (1 s). +- **The push carries more:** + - `V` lines add a seventh field, the verdict's reason (for example "forced on for this character"). + - New `N` lines list a server's world names: `N ilt <pattern> default|engine.json`. + - RynthAi 0.5.54 and older skip unknown line kinds and extra fields, so the change is compatible. +- New `PluginManager.SendPluginCommand(plugin, action, value)`: the engine's own command to a loaded + plugin's optional `RynthPluginApplyRemoteCommand`. It returns false when the plugin isn't loaded or + doesn't have the export. + +## Other + +- `/rc miniremote tab` help lists `fellowship`. + +## Files + +- `ImGui/Panels/RynthAiFace.cs`: the Hub launcher is removed; Fellowship is added to the Char menu. +- `ImGui/Panels/RynthAiFace.Drawers.cs`: texts. +- `UI/ServerMenus.cs`: the RynthILT push, reasons, world names. +- `Plugins/PluginManager.cs`: `SendPluginCommand`. +- `EntryPoint.cs`: `PushToRynthIlt`. +- `Compatibility/RynthCoreChatCommands.cs`: comment. diff --git a/Changelog/2026-10-13-full-install-2026.10.5.46.md b/Changelog/2026-10-13-full-install-2026.10.5.46.md new file mode 100644 index 0000000..82f206b --- /dev/null +++ b/Changelog/2026-10-13-full-install-2026.10.5.46.md @@ -0,0 +1,45 @@ +# Full install build 2026.10.5.46 (local) + +Local full installer built from the working trees on this machine. Not published upstream. + +Previous installer: 2026.10.5.38 (archived in `installer\previous-release\`). Hot releases +2026.10.5.39 - 2026.10.5.45 were engine/plugin deploys only; this is the first installer since. + +## Source + +| Repo | Branch | Commit | Uncommitted changes | +|---|---|---|---| +| RynthCore | build-comp-10-11 | 887ac12 | yes (`SkillsFace.Progression.cs`) | +| RynthSuite | build-comp-10-11 | 20d50ef | yes (IltHub chat capture / parse / progression / server options, attribute raiser tests) | + +Built with `-AllowDirty`, so the manifest and RELEASE-NOTES.md are flagged as dirty: the package +includes those uncommitted edits and does not map exactly to the commits above. + +## Components + +| Component | Version | +|---|---| +| Launcher, Engine (CoreCLR, unloadable) | 2026.10.5.46 | +| RynthAi plugin (NativeAOT) | 0.5.54-legacy-ui | +| Loot Editor, Monster Editor | 2026.10.5.46 | +| RynthChat, RynthNav, RynthTracker, RynthVision (experimental) | 1.0.0 | +| RynthJuice (experimental) | 0.1.2-experimental | +| UbRythai (experimental) | 3.1.11 | + +## Output + +- `installer\Output\RynthCore-Setup-2026.10.5.46.exe` (126 MB), also copied to + `RynthCore-Setup.exe`. +- `installer\Output\Release-2026.10.5.46\` and `RynthCore-2026.10.5.46-deploy.zip` (installer, + SHA256SUMS.txt, release-manifest.json, RELEASE-NOTES.md with 17 Changelog entries); the zip was + re-extracted and hash-verified. + +## Notes + +- No Decal bridge: Decal 3.0 isn't installed on this machine, so "Decal + RynthCore" accounts + can't launch with this build. +- Commands: `dotnet build RynthCore.sln -c Release`, then + `installer\Build-Installer.ps1 -Version 2026.10.5.46 -AllowDirty` (Build-Release-All.ps1 has + no -AllowDirty switch). +- Not installed on this machine yet; running the installer needs the AC clients and the + launcher closed. diff --git a/Changelog/2026-10-13-full-install-2026.10.5.47.md b/Changelog/2026-10-13-full-install-2026.10.5.47.md new file mode 100644 index 0000000..4e6e5e6 --- /dev/null +++ b/Changelog/2026-10-13-full-install-2026.10.5.47.md @@ -0,0 +1,61 @@ +# Full install build 2026.10.5.47 (local) + +Local full installer plus a local deploy of the feed plugins, built from the checkouts on this +machine after they were synced with upstream release 2026.10.13.2. Not published upstream. + +Previous installer: 2026.10.5.46 (archived in `installer\previous-release\`). + +## Source + +| Repo | Branch | Commit | Uncommitted changes | +|---|---|---|---| +| RynthCore | build-comp-10-11 | 5792dbb | no | +| RynthSuite | build-comp-10-11 | 46536db | no | + +Both commits contain rynth's main at release 2026.10.13.2 (RynthCore 401a861, RynthSuite +56b9f6c) with the local build-comp-10-11 work merged on top, so this is the first local build +that is in sync with upstream. Built without `-AllowDirty`: the manifest maps to exact commits. + +## What's new over 2026.10.5.46 + +- Everything in upstream 2026.10.13.1 and 2026.10.13.2, including the RynthILT split: the ILT Hub + (progression, augmentations, enlightenment) now lives in the RynthILT plugin instead of RynthAi. +- Plugin API v84: confirmation answers (craft-chance prompt) for plugins. +- The aug "Refresh current" fix and the single Attributes section, now in RynthILT. +- Crafting tab in the RynthAi Mini Remote (tinkering, trinkets, Rings chain, auto next batch). +- Environment-hit throttle, attack power modes, mixed-launcher swaps, pet damage-type colours. +- Security review fixes: SafeImGui for '%' in shown text, chat-origin checks so player chat + can't fake server replies, combat lines or the vault feed, StatusAgent hardening. +- RynthLua: `string.format` no longer dies on a nil argument. + +## Components + +| Component | Version | +|---|---| +| Launcher, Engine (CoreCLR, unloadable) | 2026.10.5.47 | +| RynthAi plugin (NativeAOT) | 0.5.55-legacy-ui | +| Loot Editor, Monster Editor | 2026.10.5.47 | +| RynthChat, RynthJuice, RynthNav, RynthTracker, RynthVision, UbRythai (experimental) | unchanged | +| RynthILT, RynthInventory, RynthLua (feed plugins, deployed separately) | local build | + +## Output + +- `installer\Output\RynthCore-Setup-2026.10.5.47.exe` (126 MB), also copied to + `RynthCore-Setup.exe`. SHA256 `c2db69579fe0a9fd69ba90b0df2fb021327e15d102ffef50202f3570ade890fd`. +- `installer\Output\Release-2026.10.5.47\` and `RynthCore-2026.10.5.47-deploy.zip` (installer, + SHA256SUMS.txt, release-manifest.json, RELEASE-NOTES.md); the zip was re-extracted and + hash-verified. +- Feed plugins: `D:\rynth-build\feed-2026.10.5.47\{RynthILT,RynthInventory,RynthLua}`. +- `RynthCore.SehTrampoline.dll` was rebuilt from upstream's `SehTrampoline.c` (crash-log + filter); its CrashLogFilter tests pass (229 checks). + +## Notes + +- The installer does not carry RynthILT, RynthInventory or RynthLua: upstream ships those + through the launcher's plugin feed. Their local builds are copied into + `C:\Games\RynthSuite\<plugin>` after the install, with the old DLLs kept as `.previous`. +- The launcher will show "RynthCore 2026.10.13.2 is available", because 2026.10.5.47 is a + lower release number. Don't take that update while testing: it replaces this build. +- No Decal bridge: Decal 3.0 isn't installed on this machine. +- Commands: `dotnet build RynthCore.sln -c Release`, then + `installer\Build-Installer.ps1 -Version 2026.10.5.47`. diff --git a/Changelog/2026-10-13-ilt-fellowship-installer-text.md b/Changelog/2026-10-13-ilt-fellowship-installer-text.md new file mode 100644 index 0000000..b4d3dfd --- /dev/null +++ b/Changelog/2026-10-13-ilt-fellowship-installer-text.md @@ -0,0 +1,11 @@ +# RynthCore: installer text for RynthILT's fellowship commands + +Branch `feat/dynamic-sections`, after 2026.10.5.48. No engine or launcher change, so no new +release number. The text goes out with the next installer build. + +`installer/Publish-Update.ps1`: the RynthILT line in the README and its feed description now +mention the `/fship` fellowship commands. RynthILT 0.1.3 adds them to the Mini Remote's Fellowship +section (see RynthSuite `Changelog/2026-10-13-fellowship-view-ilt-fship.md`). + +The Fellowship section itself needs no change: RynthILT's pane comes through the sections +manifest that 2026.10.5.46 added (a `fellowship` contribution, server `ilt`). diff --git a/Changelog/2026-10-13-ilt-verdict-logging-2026.10.5.52.md b/Changelog/2026-10-13-ilt-verdict-logging-2026.10.5.52.md new file mode 100644 index 0000000..4255cf6 --- /dev/null +++ b/Changelog/2026-10-13-ilt-verdict-logging-2026.10.5.52.md @@ -0,0 +1,36 @@ +# 2026.10.5.52 - log the ILT verdict at Info + +Previous release: 2026.10.5.51. + +## Problem + +A session's engine log never said whether the client counted the server as +Infinite Leaftide (ILT), or why: + +- `IltInfo.Refresh` logged the verdict through `RynthLog.Compat`, and only when + it flipped to ILT. A "not ILT" verdict never logged at all. +- With every category set to Trace under a global LoggingLevel of Info (the + launcher's Logging page), category lines are written at Trace and dropped, + so even the ILT line was missing. + +## Change + +- `RynthLog.Milestone`: an INFO line written whenever the global level allows + Info, whatever the categories' emit levels are. It is meant for rare state + changes a support log has to show. +- `IltInfo.Refresh` logs its verdict through it once per announced world and + on every change. The line includes the reason (override, world name, host or + RynthILT), whether RynthILT is loaded, what RynthILT says, and the saved + per-character override, e.g. + + `IltInfo: world 'InfiniteLeaftide' is ILT-like (RynthILT loaded=True, says ILT=True, override=Auto)` + +## Install + +Installed locally on 2026-10-13 with RynthCore-Setup-2026.10.5.52.exe (silent), +along with RynthAi 0.5.59-legacy-ui (Item Info self ratings, RynthSuite). + +## Files + +- `src/RynthCore.Engine/RynthLog.cs` +- `src/RynthCore.Engine/Compatibility/IltInfo.cs` diff --git a/Changelog/2026-10-13-launcher-known-servers-2026.10.5.48.md b/Changelog/2026-10-13-launcher-known-servers-2026.10.5.48.md new file mode 100644 index 0000000..528cc3c --- /dev/null +++ b/Changelog/2026-10-13-launcher-known-servers-2026.10.5.48.md @@ -0,0 +1,37 @@ +# RynthCore 2026.10.5.48: known-server list in the launcher's Add Server dialog + +Local full install. Previous release: 2026.10.5.47. + +## What changed + +- **Launcher: Known server picker.** The Server Profile dialog (Add Server and Edit) has a "Known + server" list at the top. Picking a server fills in Server Name, Host, Port and Emulator; Alias + and Rodat keep what you typed. "Custom server" leaves the fields alone, so any server still + works. When you edit a saved profile, the list selects the known server whose host matches. +- The list (`src/RynthCore.App/KnownServerCatalog.cs`) has the 17 servers RynthSuite ships a + server plugin for. They come from the public server list (github.com/acresources/serverslist, + checked 2026-10-13) plus Aelrynth (aelrynth.com:9020). Infinite Leaftide is + `game.infiniteleaftide.online:9000` (ACE), with plugin RynthILT. +- Host matching: the same host, or one under the known host's own domain + (`infiniteleaftide.online` finds ILT). Hosts on shared dynamic-DNS domains (ddns.net, duckdns.org + and others) and IP addresses match only themselves. + +The picker was written on `feat/dynamic-sections` (commit 8ee7ef4), which had not reached this +branch, so 2026.10.5.47 shipped without it. This brings over only the launcher part: +`KnownServerCatalog.cs` is byte-identical to that commit. The rest of that commit (the +server-plugin load gate, the SDK manifest "server" block) is not included. + +## Files + +- `src/RynthCore.App/KnownServerCatalog.cs` (new): the catalog, `FindById`, `FindByHost`, `ApplyTo`. +- `src/RynthCore.App.Avalonia/ServerProfileDialog.axaml(.cs)`: the picker and its note line. +- `src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj`: links the catalog. +- `tools/LauncherSettingsTests`: "known servers" scenario (129 checks pass). + +## Also in this install (RynthSuite) + +RynthILT 0.2.2 (Leaftide feature list, "RynthILT.Server" interface), RynthOracle 0.2.1 (Infinite +Leaftide fellowship tab), RynthAi 0.5.56-legacy-ui (fellowships up to 29). See RynthSuite +`Changelog/2026-10-13-ilt-features-oracle-fellowship.md`. + +Not yet tested in game. diff --git a/Changelog/2026-10-13-merge-2026.10.13.3-api-renumber-2026.10.5.55.md b/Changelog/2026-10-13-merge-2026.10.13.3-api-renumber-2026.10.5.55.md new file mode 100644 index 0000000..5686239 --- /dev/null +++ b/Changelog/2026-10-13-merge-2026.10.13.3-api-renumber-2026.10.5.55.md @@ -0,0 +1,56 @@ +# 2026.10.5.55 - rynth snapshot 2026.10.13.3 merged, plugin API v86 + +Previous release: 2026.10.5.54. + +Goes with RynthSuite's `Changelog/2026-10-13-merge-2026.10.13.3-api-renumber.md`: +RynthAi 0.5.63-legacy-ui, RynthOracle 0.2.6, ub-Rythai 3.1.14, RynthJuice 0.1.3 +and the 16 server plugins at 0.1.3. Install them with this engine. + +## Problem + +rynth's snapshot 2026.10.13.3 made plugin API v84 `GetObjectProperties`. This +build had already used v84 for `ArmConfirmation` / `GetLastConfirmation` and +v85 for `GetServerStateJson`, so the same version number meant different +tables. + +## Change + +- Merged snapshot 2026.10.13.3: + - `GetObjectProperties` (ObjectPropertyRecord, ObjectPropertyDump, + PropertyWire) + - the SDK's `ObjectProperties` + - `tools/ObjectPropertyTests` +- Our table entries now follow upstream's: + - v84: `GetObjectPropertiesFn` (upstream) + - v85: `ArmConfirmationFn`, `GetLastConfirmationFn` + - v86: `GetServerStateJsonFn` +- `PluginContractVersion.Current` and `RynthCoreSdkApiVersion` are now 86. +- In the SDK, `HasConfirmationAnswers` now needs v85+ and + `HasGetServerStateJson` v86+. +- Plugins built against the 2026.10.5.54 layout (v85) must be rebuilt. + +## Tests + +- tools/PluginManifestTests: PASS (233 assertions). It checks the new slot + order, that each new slot sits right after the previous one, and that the + SDK and engine offsets match. +- tools/SectionsTests: 140/140. +- tools/ObjectPropertyTests: 88/88. + +## Install + +Installed locally on 2026-10-14 with RynthCore-Setup-2026.10.5.55.exe +(silent; RynthCore a76885b, RynthSuite e56d70e). The installer brought RynthAi +0.5.63-legacy-ui, ub-Rythai 3.1.14 and RynthJuice 0.1.3. RynthOracle 0.2.6 and +the 16 server plugins at 0.1.3 were copied from their NativeAOT `publish` +builds. Old DLLs were backed up to each plugin's PreviousReleases folder, named +by the version they replaced. RynthILT 0.2.6 and RynthInventory 0.1.2 don't +call the moved functions and were left as they were. + +## Files + +- `src/RynthCore.Engine/Plugins/PluginContract.cs`, `PluginContractVersion.cs`, `PluginManager.cs` +- `src/RynthCore.PluginSdk/RynthCoreApiNative.cs`, `RynthCoreHost.cs`, `build/RynthCore.PluginSdk.targets` +- `src/RynthCore.Engine/UI/Sections/ServerStateJson.cs`, `ServerSelectionStore.cs` (comments) +- `tools/PluginManifestTests/Program.cs`, `tools/SectionsTests/*` (comments) +- Upstream's files from snapshot 2026.10.13.3 diff --git a/Changelog/2026-10-13-merge-dynamic-sections-2026.10.5.50.md b/Changelog/2026-10-13-merge-dynamic-sections-2026.10.5.50.md new file mode 100644 index 0000000..91a90a9 --- /dev/null +++ b/Changelog/2026-10-13-merge-dynamic-sections-2026.10.5.50.md @@ -0,0 +1,65 @@ +# RynthCore 2026.10.5.50: merge feat/dynamic-sections into build-comp-10-11 + +This merge brings the `feat/dynamic-sections` branch onto the local build line. It pairs with the +RynthSuite merge of the same name, so build the two together. + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.49 | 2026.10.5.50 | +| Engine plugin API | 81 | 81 (unchanged) | + +The branch's own notes (`2026-10-13-mini-remote-sections-2026.10.5.46.md`, +`...-fellowship-menu-ilt-settings-push-2026.10.5.47.md` and +`...-server-plugins-2026.10.5.48.md`) are kept as they were written. Their version numbers come +from the branch and were never shipped on this line. Everything they describe ships as +2026.10.5.50. + +## What arrives + +- **Mini Remote sections.** These come from `SectionRegistry`, `SectionCatalog`, + `SectionManifest` and `MiniRemoteFace.Sections`. Plugins declare their sections, and the engine + places them into the Mini Remote menus by server. +- **Per-character server overrides.** `ServerForce`/`ServerForceStore` save Auto, On or Off for + each character and server. Set them with `/rc server <id> auto|on|off` and + `/rc server names ilt add|remove <pattern>`. The "servermenu" push (lines V, X, S, I and N) + reaches RynthAi, RynthILT and every server plugin. +- **One plugin per server.** This is `PluginManifestGate.SelectServerPlugins` together with the + SDK's `"server"` manifest block. It fails open, and `engine.json` + `"LoadAllServerPlugins": true` turns it off. +- **Known-server picker** in the launcher's Server Profile dialog. + +## Conflict decisions + +- `IltInfo` keeps this line's detection, combined with RynthILT's reported verdict when the + override is Auto. RynthILT now reports only its local verdict, so the engine's verdict cannot + echo back and latch ILT on. +- `EntryPoint.RegisterServerMenus` uses `SectionRegistry`. The Char menu keeps this line's + Quests and Quest Timers entries. Its Fellowship item runs `/ro fellowship`, which now opens + RynthOracle's Fellowship tab. +- `RynthAiFace` and its drawers keep this line's Hub-free layout and add the section hooks. +- `ServerProfileDialog` keeps the known-server picker. +- `installer/Publish-Update.ps1` keeps this line's plugin list and adds the 16 server plugins. +- `EngineSettings` adds `LoadAllServerPlugins` alongside this line's settings. + +## Deployment note + +The 16 server plugins stay disabled in the launcher until this engine is installed. An older +engine has no server gate, so it would load all of them at once. + +## Build and install + +- `installer\Output\RynthCore-Setup-2026.10.5.50.exe` and `RynthCore-2026.10.5.50-deploy.zip` + (126 MB, verified). 2026.10.5.49 is recorded as the previous release. +- Installed silently on this machine. RynthOracle, RynthILT and the 16 server plugins aren't in + the installer and were copied in directly. Each replaced plugin DLL is saved in that plugin's + `PreviousReleases\<version>` folder. +- The launcher's RynthLua entry now points at `C:\Games\RynthSuite\RynthLua`. The old settings + file is saved as `appsettings.json.pre-2026.10.5.50.bak`. The server plugins stay enabled, + because this engine has the server gate. + +## Tests + +- `tools/EngineSettingsTests`: 207 passed. +- `tools/PluginManifestTests`: 227 passed. +- `tools/SectionsTests`: 77 passed. +- `tools/LauncherSettingsTests`: 129 passed. diff --git a/Changelog/2026-10-13-mini-remote-rail-hidden-tabs-2026.10.5.51.md b/Changelog/2026-10-13-mini-remote-rail-hidden-tabs-2026.10.5.51.md new file mode 100644 index 0000000..c4452a8 --- /dev/null +++ b/Changelog/2026-10-13-mini-remote-rail-hidden-tabs-2026.10.5.51.md @@ -0,0 +1,47 @@ +# RynthCore 2026.10.5.51: ILT tabs come back when the sections rail is hidden + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.50 | 2026.10.5.51 | +| Engine plugin API | 81 | 81 (unchanged) | + +## The problem + +After 2026.10.5.50, Infinite Leaftide's Banking tab and the ILT settings view could not be +found in the Mini Remote. + +When RynthAi publishes sections, the engine asked RynthAi for its remote without its tab bar +("miniremote-remote"), because the sections rail replaces that bar. RynthILT's tabs (Character, +Banking, Gear, Charms, Games) then live only in the Char, Inventory and Games sections. ILT +settings lives only in the Char section's "Server: Infinite Leaftide" tab. + +The rail can be hidden (right-click menu, "Show the sections rail"), and that choice is saved for +the whole PC (`panel_columns.txt`, `MiniRemote.rail`). With the rail hidden, those tabs and +sections had no visible way in. The only routes were the right-click menu and +`/rc miniremote section <name>`. + +## The fix + +- `MiniRemoteFace.Surface` asks for "miniremote-remote" only while the rail shows. With the rail + hidden it asks for "miniremote-window", so RynthAi's remote draws its own tab bar again, + including RynthILT's Banking, Gear, Charms, Character and Games tabs. +- The "Show the sections rail" tooltip says what hiding the rail does. + +## Where things are + +- **Banking** is in the Inventory section's Banking tab, or in RynthAi's tab bar when the rail is + hidden. `/rc miniremote tab banking` opens it either way. +- **ILT settings** is in the Char section's "Server: Infinite Leaftide" tab, which shows only + while RynthCore treats the world as ILT. `/ilt settings` opens RynthILT's own window. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs`: `Surface` checks `RailShown`. +- `src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs`: the rail tooltip. + +## Local install (2026-10-13 20:30) + +- `installer\Output\RynthCore-Setup-2026.10.5.51.exe` installed silently to `C:\Games\RynthCore`. + The 2026.10.5.50 installer is archived in `installer\previous-release\`. +- RynthILT 0.2.5 (RynthSuite `ce91cf4`, the client-side ILT feature profile) was copied to + `C:\Games\RynthSuite\RynthILT`. 0.2.4 is kept in `PreviousReleases\0.2.4`. diff --git a/Changelog/2026-10-13-mini-remote-sections-2026.10.5.46.md b/Changelog/2026-10-13-mini-remote-sections-2026.10.5.46.md new file mode 100644 index 0000000..aaf663e --- /dev/null +++ b/Changelog/2026-10-13-mini-remote-sections-2026.10.5.46.md @@ -0,0 +1,100 @@ +# RynthCore 2026.10.5.46: Mini Remote sections, server overrides per character + +Branch `feat/dynamic-sections`, from 887ac12 (2026.10.5.45). It pairs with the RynthSuite branch of the +same name (RynthAi 0.5.55); build the two together. An older RynthAi still works: it publishes no +sections, so the engine shows its own panels and the remote as before. + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.45 | 2026.10.5.46 | + +The plugin contract version is unchanged. The new export is optional. + +## The Mini Remote is a rail of sections + +The Mini Remote window now has a narrow rail on its left. The first entry is the remote itself +(RynthAi's remote, or the engine's slot grid without RynthAi). Below it are the twelve core sections, +always in this order: Char, Map, Skills, Combat, Nav, Inventory, Crafting, Spells, Chat, Friends, +Fellowship, Pets. A plugin can add more sections; they show only while they have something in them. + +- A section draws the engine panels that belong to it, whole, as tabs: Map has Radar and Dungeon Map, + Skills has Skills, Combat has Damage and Monsters, Nav has Nav and RynthNav, Inventory has Inventory, + Item Count and Items, Chat has Chat. Char starts with an overview. +- Below the panels is a server area: one collapsing group per active server ("Server: Infinite + Leaftide"), then "Plugins" for items that apply on every world. Groups hold plugin option views and + command buttons. +- Sections with no engine panel (Crafting, Spells, Friends, Fellowship, Pets) are filled by plugins. + Without one they say so. +- The right-click menu lists the same sections and the server items, and can hide the rail. +- The chosen section and the rail setting are saved with the window. +- `/rc miniremote section <id>` opens a section. `/rc miniremote tab <tab>` opens the matching section + when a plugin publishes it, else the remote's tab as before. + +### Embedded panels + +`ImGuiPanelHost.DrawEmbedded` draws a registered panel inside another window. Each host gets its own +panel instance, so the docked or floating panel keeps its own state. An embedded panel can't move or +resize the window it's drawn in. A copy that hasn't drawn for 750 ms gets `OnHidden`. A panel that +throws is shown as an error line instead of breaking the window. The Mini Remote can't embed itself. + +## Plugin sections: `RynthPluginGetSectionsJson` + +New optional export `const char* RynthPluginGetSectionsJson(void)` (UTF-8 JSON, schema 1). The engine +reads it every 2 seconds on the render thread, only after login. + +- `servers`: servers the plugin knows. The built-in ids `ilt` and `aelrynth` keep the engine's own + detection; a new id is detected from its `worldNames` and `hosts` lists. +- `sections`: extra sections, with a label and a rail order. +- `contributions`: what goes in a section. `server` empty means every world, else only while that + server is active. `surface` is drawn inline through `RynthPluginRenderEmbed`; `command` is a button. + `primary` makes a surface one of the section's tabs instead of an item in the server area. + +Everything from a plugin is checked (`UI/Sections/SectionManifest.cs`): + +- Ids are short lower-case words. +- Labels are one line, text is capped, a command must be a single `/...` chat command, and a surface + name can't end in `:popout`. +- The lists are capped (16 servers, 32 sections, 128 contributions), and so are the JSON size + (256 KB) and its depth. +- A bad entry is skipped and the rest of the manifest is kept. + +## One server registry, with per-character overrides + +`UI/Sections/SectionRegistry.cs` holds the servers (Infinite Leaftide and Aelrynth built in, plus any a +plugin declares), each with its detection, its override and the reason. It rebuilds the sections once a +second or when an override changes. + +- Every server has an Auto / On / Off override per character. It is saved in + `%LOCALAPPDATA%\RynthCore\server_force.txt`. Before login it holds for the session only. +- `/rc server` lists the servers. `/rc server <id> auto|on|off` sets one. The older + `/rc server aelrynth|other|auto` still works. +- `/rc ilt on|off|auto` uses the same store. +- `/rc server names ilt [add|remove <pattern>]` edits engine.json `IltServerNames` (patterns up to 64 + characters; the defaults are copied in the first time). +- The Char overview shows each server's verdict, why, and Auto / On / Off buttons. +- The engine's own server items (Guardian, Progression, Bounties, and RynthAi's tabs when RynthAi + publishes no sections) are now entries in the registry. + +The "servermenu" push to RynthAi now also carries the servers (`V id name active force detected`) and +the rail (`X id label`). An older RynthAi skips those lines. + +## Tests + +- New `tools/SectionsTests` (77 checks): the overrides file, the manifest parser and its limits, the + section catalog (core order, server-scoped items, plugin sections) and declared-server detection. +- `tools/EngineSettingsTests` checks `EditIltServerName` against a real engine.json: the defaults + are kept on the first edit, the launcher's keys survive, and repeats, unknown, empty and overlong + patterns change nothing. It now links `IltDetect.cs` and `AelrynthWire.cs`. +- RynthSuite's host tests link the parser and catalog and check RynthAi's manifest against them. +- Every other test project passes, apart from two known failures that already happen on 2026.10.5.45: + RynthLua.ScriptWindowsTests (4 checks) and the RynthAi host test that needs the real dat files. + +## Files + +- New: `UI/Sections/ServerForce.cs`, `ServerForceStore.cs`, `SectionManifest.cs`, `SectionCatalog.cs`, + `SectionRegistry.cs`; `ImGui/Panels/MiniRemoteFace.Sections.cs`; `tools/SectionsTests`. +- Tests changed: `tools/EngineSettingsTests`. +- Changed: `ImGui/ImGuiPanelHost.cs`, `ImGui/Panels/MiniRemoteFace.cs`, `UI/ServerMenus.cs`, + `Compatibility/IltInfo.cs`, `Compatibility/ServerInfo.cs`, `Compatibility/RynthCoreChatCommands.cs`, + `Plugins/EngineSettings.cs`, `Plugins/LoadedPlugin.cs`, `Plugins/PluginLoader.cs`, + `Plugins/PluginManager.cs`, `EntryPoint.cs`. \ No newline at end of file diff --git a/Changelog/2026-10-13-oracle-quests-menu-hub-launcher-2026.10.5.49.md b/Changelog/2026-10-13-oracle-quests-menu-hub-launcher-2026.10.5.49.md new file mode 100644 index 0000000..0bbf21e --- /dev/null +++ b/Changelog/2026-10-13-oracle-quests-menu-hub-launcher-2026.10.5.49.md @@ -0,0 +1,41 @@ +# RynthCore 2026.10.5.49: Char menu opens RynthOracle's quests; Hub launcher removed + +Local full install. Previous release: 2026.10.5.48. + +## What changed + +- **RynthAi dashboard: Hub launcher removed.** The Hub button opened the same Mini Remote window as + Char, so it is gone. The launcher row has 9 buttons. The Mini Remote is still the bar button + (`/rc miniremote`), Char (on its Character tab), and "Mini Remote" in Char's right-click menu; + its drawer is the drawer tab on the dashboard's edge. The Avalonia copy of the dashboard + (`UI/Panels/RynthAiPanel.cs`) loses its Hub button too, and its right-click (Inventory HUDs + setup, `/ra huds`) moves to Char. +- **Char menu: Quests are RynthOracle's.** "Quests" now opens or closes RynthOracle's window + (`RynthOracle/Oracle`) instead of the Mini Remote's Quests tab, which moved to RynthOracle. A + new "Quest Timers" item opens its Quest Timers window (`RynthOracle/QuestTimers`). Both are + ticked while open and greyed out when RynthOracle isn't loaded. +- **Script windows: open by key.** `ScriptWindowRegistry.PlayerSetVisible(string key, bool)`, + `Has(key)` and `IsOpen(key)` find a plugin's script window by its key and show or hide it as the + bar does: the owner gets a Visibility event with reason 2. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs`: 9 launchers, `OracleMenuItem`, Char menu. +- `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs`: Hub button removed, its right-click on Char. +- `src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs`: key lookups. +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs`: comment (tab list). + +## Build and install + +- `installer\Output\RynthCore-Setup-2026.10.5.49.exe` and `RynthCore-2026.10.5.49-deploy.zip` + (125.8 MB, verified). The 2026.10.5.48 installer is archived in `installer\previous-release\`. +- Installed silently on this machine. RynthOracle and RynthILT aren't in the installer and were + copied in directly. The replaced plugin DLLs are in each plugin's `PreviousReleases\<version>`. + +## Also in this install (RynthSuite) + +RynthOracle 0.2.2 (quests merged in, rewards, Quest Timers window), RynthAi 0.5.57-legacy-ui +(Mini Remote Quests tab removed), RynthILT 0.2.3 (`/qb` list for RynthOracle). See RynthSuite +`Changelog/2026-10-13-quests-to-oracle-rewards-timers.md`. + +Not yet tested in game. diff --git a/Changelog/2026-10-13-port-build-comp-onto-upstream.md b/Changelog/2026-10-13-port-build-comp-onto-upstream.md new file mode 100644 index 0000000..af4dc2e --- /dev/null +++ b/Changelog/2026-10-13-port-build-comp-onto-upstream.md @@ -0,0 +1,34 @@ +# Port: local build-comp-10-11 onto upstream 2026.10.13.2 (plugin API v84) + +Branch `port/build-comp-on-2026.10.13.2`, based on `aelrynth/main`. Upstream's version is kept for +everything rynth already took; only what upstream lacks is re-applied. Nothing is pushed. + +## Plugin API + +Upstream used v80-v83 (GetContainerOrder / PutItemInContainer, GetMergeStackResult, SalvageDirect, +GetObjectServerAge / RemoveClientObject). The local ArmConfirmation / GetLastConfirmation slots +move to **v84**, appended after RemoveClientObjectFn in `PluginContract.cs` and +`RynthCoreApiNative.cs`. `PluginContractVersion.Current` and the SDK targets are 84; +`RynthCoreHost.HasConfirmationAnswers` checks `Version >= 84`. PluginManifestTests updated +for the new slot order. + +## Kept from the local branch + +- Installer: local component layout, `overwritereadonly` on every ignoreversion file, + `Permissions: users-modify` on the install folders, and the read-only clearing in + `Build-Installer.ps1`. +- Items panel weapon rows tinted by damage type; Skills panel Progression header wording. +- SafeImGui coverage (`%` in ImGui text): ChatFace, MetaFace.Editor and the Inventory Give/Drop + zone tooltip (it carries the target's name). Strings that are already escaped are not wrapped + twice. + +## Taken from upstream + +- `native/SehTrampoline` v6. +- Server Features, Progression and Guardian live in RynthILT; the engine's ILT server menu and + chat commands follow upstream. + +## Tests + +- Engine builds in Release. +- `tools/PluginManifestTests`: PASS (195 assertions). diff --git a/Changelog/2026-10-13-security-review-fixes-2026.10.5.45.md b/Changelog/2026-10-13-security-review-fixes-2026.10.5.45.md new file mode 100644 index 0000000..3b4a26a --- /dev/null +++ b/Changelog/2026-10-13-security-review-fixes-2026.10.5.45.md @@ -0,0 +1,83 @@ +# RynthCore 2026.10.5.45: security review fixes (engine, StatusAgent 1.0.1, installer) + +Branch `fix/security-review-2026-10-13`, from d76e062. It pairs with the RynthSuite branch of the same +name (RynthAi 0.5.54); build the two together. + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.44 | 2026.10.5.45 | +| StatusAgent | 1.0.0 | 1.0.1 | + +## F1: a '%' in shown text could crash the client + +This is the same printf-format problem as in RynthSuite. ImGui.NET passes `Text`, `TextColored`, +`TextWrapped`, `TextDisabled`, `BulletText`, `SetTooltip`, `SetItemTooltip` and `LabelText` strings to +native ImGui as a format string with no arguments. + +- New `src/RynthCore.Engine/ImGui/SafeImGui.cs` (root namespace) doubles every `%`. +- 246 calls in 39 engine files use it, among them the shell, the chat, item, inventory, loot-editor, + meta and nav panels, and the plates. +- Script windows already drew through `igTextUnformatted`. +- `Panels/SkillsFace.Progression.cs` (5 calls) is left for after the local uncommitted work in it lands. + +## L1: the engine's own server-reply readers + +The engine eats its own `/mastery-data` and `/mule-data` replies before AC draws them. A player could +type a copy and have it read or hidden. For the mastery reader this worked through an emote, which has +no quote for `MasteryWire`'s check to catch. + +- New `Net/ChatOrigin.cs` holds the player chat types (ACE `ChatMessageType`) and a line-start marker + match. It is also compiled into NetMessageTests. +- `ChatCallbackHooks.EatOwnReply(line, chatType)` skips player chat types. That covers both feeds. +- `AelrynthVaultWire`: + - `IsMuleLine` and `TryParse` need `~ael1 ` at the start of the line. + - `IsUnknownCommand` needs "Unknown command:" at the start and exactly `mule-data`. +- `VaultWireTests` gains spoof cases. + +## M2: the status server, before it is opened to other PCs + +What it already did: it requires a token (compared in constant time), binds 127.0.0.1 by default, and +its file endpoints take only numbers (pid, landblock, icon id), so there is no path traversal. + +New in `ServeGuard.cs`: + +- **Token length.** A `ServePrefix` other than 127.0.0.1, localhost or [::1] needs a `ServeToken` of at + least 16 characters. The agent says so and stays off. Before, it showed the urlacl hint. +- **Lockout.** 10 bad tokens from one address within a minute lock it out for 5 minutes, even with the + right token. Loopback is never locked out. The lockout is logged once. +- **Bounded request bodies.** A command may be 64 KB, a WebRTC offer 256 KB, a client log 16 KB. + Anything larger gets 413. Before, every body was read whole. +- **Safe log text.** Client text in the log (user agent, client log, SDP lines, command values) has + control characters replaced and is capped, so nobody can forge log lines. +- **Startup warning.** A non-loopback bind is plain HTTP; the agent says to use it only inside a VPN + such as Tailscale or WireGuard. + +StatusAgentTests gains a ServeGuard section: 146 checks pass. + +## Low: MinHook load and the .NET runtime download + +- **MinHook.** `MinHook.ResolveApi` loaded `minhook.x86.dll` by bare name. When the early preload + missed it, Windows' search order (the AC folder, the current directory, PATH) could load a planted + copy into the client. It now loads the file that `EntryPoint.FindNativeDll` finds in the engine's own + folders, and fails if there is none. +- **.NET runtime download.** The installer downloaded aka.ms's moving "latest" .NET 10 Desktop Runtime + and ran it unchecked. It now downloads 10.0.12 (x86) from builds.dotnet.microsoft.com and Inno Setup + checks its SHA-256 first: + + ```text + 57c1d40967b73785b9ef95de5f0878e9264423228971a71eb362c03ae01937f5 + ``` + + On 2026-10-13 that file matched Microsoft's release-metadata SHA-512 and carried a valid Microsoft + Authenticode signature. The `.iss` explains how to move to a newer build. Any 10.x already installed + is still accepted. + +## Tests + +| Suite | Result | +|---|---| +| NetMessageTests | 311 checks pass | +| StatusAgentTests | 146 checks pass | +| All other RynthCore `tools` test projects | pass | + +The engine builds. The installer script compiles; it was checked with the staging files skipped. diff --git a/Changelog/2026-10-13-server-list-and-forced-server-load-2026.10.5.56.md b/Changelog/2026-10-13-server-list-and-forced-server-load-2026.10.5.56.md new file mode 100644 index 0000000..a180510 --- /dev/null +++ b/Changelog/2026-10-13-server-list-and-forced-server-load-2026.10.5.56.md @@ -0,0 +1,49 @@ +# 2026.10.5.56 - Diagnostics server list fills in; forcing a server loads its plugin + +Previous release: 2026.10.5.55. + +Goes with RynthSuite's `Changelog/2026-10-13-server-plugins-always-declare-0.1.4.md`: +the 16 server plugins at 0.1.4. Install them with this engine. No plugin API change +(still v86). + +## Problem + +- Options > Diagnostics said "No servers known yet" even in game. The server list + (`SectionRegistry.Tick`) was only ticked from `ServerMenus.Tick`, which only ran + inside `ImGuiBar.Draw`. With the bar hidden (the rail instead) nothing built the + list, and no server plugin was sent its "servermenu" verdict. +- The load gate skips the server plugins for other hosts. Those servers never + appeared in the list, so forcing one On did nothing: its plugin was not loaded. + +## Change + +- `EngineFrameController` now calls `ServerMenus.Tick()` every frame while panels + are live, bar shown or not. `ImGuiBar.Draw` no longer calls it. +- `PluginManifestGate.LoadPlan.SkippedServerPlugins` records the server plugins + the gate skipped. `PluginManager` remembers them + (`PluginManager.ServerPlugins.cs`). +- New `NotLoadedServers` (pure): the skipped servers are added to the Diagnostics + list as "installed but not loaded", and can be picked like any other. +- Forcing a not-loaded server On loads only that plugin, on the pump thread, + without a rescan: + - the picker in Options > Diagnostics, + - `/rc server <id> on`, + - a saved per-character override. + The plugin is checked by the manifest resolver, loaded, initialized and sent + `OnUIInitialized` / `OnLoginComplete`, then chat confirms + "[RynthCore] Loaded X for Y (forced On in Options > Diagnostics)." A failure is + reported in chat as well. +- The empty-list text now reads "No servers known yet (the list fills in once a + character is in game)." + +## Tests + +- `tools/SectionsTests`: `NotLoadedServerList` (148/148 checks pass). +- `tools/PluginManifestTests`: `ServerGatePlanFromFiles` checks the skipped + server plugin is recorded (236 assertions pass). +- RynthSuite `RynthServerPack.Tests`: 14 tests, 819 checks pass. + +## Notes + +- A forced plugin stays loaded for the session; setting the server back to Auto + or Off takes effect on the next client start. diff --git a/Changelog/2026-10-13-server-plugins-2026.10.5.48.md b/Changelog/2026-10-13-server-plugins-2026.10.5.48.md new file mode 100644 index 0000000..cc4babf --- /dev/null +++ b/Changelog/2026-10-13-server-plugins-2026.10.5.48.md @@ -0,0 +1,74 @@ +# RynthCore 2026.10.5.48: one plugin per server, server detection, known-server picker + +Branch `feat/dynamic-sections`, after 989d7a3 (2026.10.5.47). It pairs with the RynthSuite branch +of the same name, which adds 16 server plugins (RynthColdeve, RynthAelrynth, ...) and RynthILT +0.1.2; build them together. + +| Component | Previous | Now | +|---|---|---| +| Engine | 2026.10.5.47 | 2026.10.5.48 | +| Plugin SDK manifest | no server block | optional `"server"` block | +| Engine plugin API | 81 | 81 (unchanged) | + +## Server plugins: the right plugin for the server you connect to + +Each server RynthSuite supports now has its own plugin, built like RynthILT, so each can be +updated on its own. The engine decides which one loads: + +- **A plugin can name its server.** The SDK writes an optional `"server"` block into the embedded + manifest: `{ id, name, hosts[], worldNames[] }`. Plugins set it in their csproj with + `RynthPluginServerId`, `RynthPluginServerName`, `RynthPluginServerHosts` and + `RynthPluginServerWorldNames` (lists separated by `|`). The generated `RynthPluginInfo` gets the + same values as constants, so the plugin and the engine use one copy of the detection data. + Older engines ignore the block. +- **Only the matching server plugin loads.** Before loading, the engine compares the client's + connect host (the launch command line's `-h`) with every installed server plugin's hosts. When + one plugin claims the host, the other server plugins are skipped and logged (not refused in chat). + Hosts match exactly, as a host under a listed domain, or by a `*` pattern; an IP matches only + itself. +- **It fails open.** When the host is unknown, or no server plugin claims it, every plugin loads as + before. `engine.json` `"LoadAllServerPlugins": true` turns the check off. +- **The "servermenu" push goes to every server plugin** whose sections manifest declares a server, + when it changes and every 10 s. So each plugin's server card shows the engine's verdict, the + per-character override (Auto/On/Off) and the reason. +- **Plugin lookups prefer the exact name.** Commands and embedded panels matched plugin names by + substring, so "RynthLeafDawn" could reach "RynthLeafdawning". An exact match now wins; the + substring match remains the fallback. + +## Launcher: set up an account on a known server + +- The **Server Profile** dialog has a **Known server** picker with every server that has a server + plugin (16 plus Infinite Leaftide). Picking one fills in Name, Host, Port and Emulator; Alias and + Rodat stay as typed. The note under it names the plugin RynthCore loads for that server. +- Editing a saved profile selects its known server by host. Choosing "Custom server" leaves the + fields alone, so any server still works. +- Hosts, ports and emulators come from the public server list + (github.com/acresources/serverslist, checked 2026-10-13). Aelrynth is not on that list and uses + aelrynth.com:9020. + +## Publishing + +- `installer/Publish-Update.ps1` builds and ships the 16 server plugins with the others. Each has a + feed description, and the zip README lists them. RynthILT's description now calls it Infinite + Leaftide's server plugin. + +## Tests + +- `tools/PluginManifestTests`: the server block's parsing, round trip and id rules; host matching; + the load gate keeps only the host's plugin and fails open; a plan built from real files. +- `tools/LauncherSettingsTests`: the known-server catalog (unique ids and hosts, ApplyTo keeps the + profile's id, alias and Rodat, host lookup including shared dynamic-DNS domains). +- RynthSuite `Tools/RynthServerPack.Tests` checks the catalog against the plugins: each entry names + a real server plugin that claims its host, with the same port and emulator. + +## Files + +- `PluginSdk/Manifest/RynthPluginManifest.cs`: `RynthPluginServer`, parsing and writing the block. +- `PluginSdk/build/RynthCore.PluginSdk.targets`: the csproj properties, the manifest block and the + `RynthPluginInfo` constants. +- `Engine/Plugins/PluginManifestGate.cs`: `SelectServerPlugins`, `LoadPlan.SkippedForServer`. +- `Engine/Plugins/PluginManager.cs`: passes the connect host to the gate; exact-name-first lookups. +- `Engine/Plugins/EngineSettings.cs`: `LoadAllServerPlugins`. +- `Engine/UI/ServerMenus.cs`: the push to every server plugin. +- `App/KnownServerCatalog.cs` (new), `App.Avalonia/ServerProfileDialog.axaml(.cs)`: the picker. +- `installer/Publish-Update.ps1`: the server plugins. diff --git a/Changelog/2026-10-13-server-selection-2026.10.5.53.md b/Changelog/2026-10-13-server-selection-2026.10.5.53.md new file mode 100644 index 0000000..4affe3d --- /dev/null +++ b/Changelog/2026-10-13-server-selection-2026.10.5.53.md @@ -0,0 +1,76 @@ +# 2026.10.5.53 - one server identity for every plugin, and a server picker + +Previous release: 2026.10.5.52. + +## Problem + +Each plugin worked out "which server is this" on its own: + +- RynthOracle used GetServerInfo (Aelrynth only), then the world name, then + RynthILT's profile. It never saw the Mini Remote's per-character server + overrides or a server plugin's declaration. +- ub-Rythai's ILT banking matched the world name only. +- Server plugins (RynthColdeve, RynthConquest, ...) knew their server's rules + (botting policy, rule set, account limits, commands), but no other plugin + could ask for them. +- The only way to force a server was "/rc server <id> on|off", one server at a + time, with no place in Options to see or change it. + +## Change + +- Plugin API v85, `GetServerStateJson(byte* buffer, int capacity)`: the + engine's server list as UTF-8 JSON (schema 1). It has `host`, `world`, `pick` + ("auto", a server id, or "mixed"), `active`, `activeName` and `activePlugin` + (the plugin that owns the active server, which other plugins ask for its + settings). Each entry in `servers[]` has `id`, `name`, `active`, `detected`, + `force`, `builtIn`, `plugin` and `reason`. The function returns the byte + length; when that is >= capacity, nothing is written. SDK: + `RynthCoreHost.HasGetServerStateJson` and `TryGetServerStateJson(out json)`. +- `ServerSelection` (pure): picking server X forces X On and every other server + Off for this character; "auto" resets every override. It also answers which + server is active (a forced-On server beats detection) and which plugin owns a + server (the one that declares it, else the one with the most contributions + for it, e.g. RynthILT for "ilt"). +- Options > Diagnostics > Server: a picker listing "Auto (detect)" and every + server from the loaded plugins, marked [active] or [detected]. Below it is a + table showing each server's state, this character's override, and which + plugin supplies its settings. A pick applies at once and reaches every plugin + through the "servermenu" push and GetServerStateJson. +- Chat: `/rc server pick <id>|auto` does the same. +- Picks are logged at Info (`ServerSelection: ...`). + +## Tests + +- tools/SectionsTests: 116/116. New cases cover the pick plan, the current pick, + the active server, the owner plugin, the JSON and the buffer convention. +- tools/PluginManifestTests: PASS (229 assertions). The API table layout now + ends with GetServerStateJsonFn. + +## Install + +Installed locally on 2026-10-13 with RynthCore-Setup-2026.10.5.53.exe +(silent), along with RynthAi 0.5.61-legacy-ui, RynthOracle 0.2.4, ub-Rythai +3.1.12 and the 16 server plugins at 0.1.1 (RynthSuite ea84e27). Old DLLs were +backed up to each plugin's PreviousReleases folder. + +The previously installed server plugins (copied at 19:06) were the managed +`bin` builds (about 35 KB), not the NativeAOT `publish` builds (about 2.3 MB), +so none of them could load. The ones installed now are the `publish` builds, +and each one exports RynthPluginQueryInterface. + +Engine log categories in engine.json were set back to the defaults: Info for +General, D3D9, Compat, Plugin and UI; Render off; Verbose at Debug. + +## Files + +- `src/RynthCore.Engine/UI/Sections/ServerSelection.cs` (new) +- `src/RynthCore.Engine/UI/Sections/ServerStateJson.cs` (new) +- `src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs` (new) +- `src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs` (new) +- `src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs` +- `src/RynthCore.Engine/UI/Data/SettingsData.cs` +- `src/RynthCore.Engine/UI/Panels/SettingsPanel.cs` +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs` +- `src/RynthCore.Engine/Plugins/PluginContract.cs`, `PluginContractVersion.cs`, `PluginManager.cs` +- `src/RynthCore.PluginSdk/RynthCoreApiNative.cs`, `RynthCoreHost.cs`, `build/RynthCore.PluginSdk.targets` +- `tools/SectionsTests/*`, `tools/PluginManifestTests/Program.cs` diff --git a/Changelog/2026-10-13-session-stats-moved-tabs-2026.10.5.54.md b/Changelog/2026-10-13-session-stats-moved-tabs-2026.10.5.54.md new file mode 100644 index 0000000..a212f4c --- /dev/null +++ b/Changelog/2026-10-13-session-stats-moved-tabs-2026.10.5.54.md @@ -0,0 +1,73 @@ +# 2026.10.5.54 - Mini Remote "Session Stats", moved tabs, one session formula + +Previous release: 2026.10.5.53. + +Goes with RynthSuite's "Mini Remote tabs moved, one XP / luminance session" +release (`RynthSuite/Changelog/2026-10-13-oracle-character-global-banking-one-session.md`): +RynthAi 0.5.62-legacy-ui, RynthILT 0.2.6, RynthOracle 0.2.5, RynthInventory +0.1.2, RynthTracker 0.4.1, ub-Rythai 3.1.13 and the 16 server plugins at 0.1.2. + +## Problem + +- The Mini Remote's "Char" section mixed several things: session rates, the ILT + character page, charms, banking and the server-force checkboxes. +- The engine's XP / luminance rates (status feed, Mini Remote overview) used + their own rule, a per-process baseline that reset on an XP drop. That rule + didn't match RynthAi's or RynthTracker's numbers on ACECustom (bank 9005) or + Aelrynth (9102 / 9103). + +## Change + +- The "char" section is now labelled "Session Stats". Its id stays "char", so + saved rail picks and `/rc miniremote section char` still work. +- If a plugin contributes a primary view to "char" for every world (RynthAi's + "section:session"), the engine drops its own overview there, so only one + session shows. A server-scoped view doesn't do this. +- `/rc miniremote tab character|char|charms` now runs `/ro character` + (RynthOracle's Character tab). `/rc miniremote tab banking|bank` now runs + `/ginv bank` (RynthInventory's Banking tab). The ILT tabs left are Gear and + Games. +- New `/rc diagnostics` (alias `serverpick`) opens Options on the Diagnostics + tab. This is now the only place to force a server; the plugins link to it. +- New `Compatibility/SessionRates.cs` (pure) uses the same formula as + RynthSuite's `Plugins/Shared/SessionStats.cs`: + - Totals are the sum of positive rises. + - Bank 9005 rises count as income. Once 9005 has been read, AvailableLuminance + rises are treated as withdrawals. + - A deposit or incoming transfer seen in chat is left out of the next bank + rise. + - 9102 is added and 9103 is subtracted. + - A different character starts a new session. + `EngineStatusMetrics` (GetEngineStatusJson) and the Mini Remote's own overview + use it. The player quad properties the engine caches now include 9005, and + PluginManager passes chat lines to it. +- On the RynthAi panel, the Char button and the "Character" menu item open + RynthOracle's Character tab. Without RynthOracle they open the Mini Remote's + Session Stats section. + +## Tests + +- tools/SectionsTests: 140/140. New cases cover the Session Stats label, a + universal session surface dropping the overview, and a server-scoped one + keeping it. New SessionRates cases cover rises and drops, the ACECustom bank, + deposits and transfers seen in chat, Aelrynth 9102 / 9103, and a new + character. + +## Install + +Installed locally on 2026-10-13 with RynthCore-Setup-2026.10.5.54.exe +(silent; RynthCore 3405fb7, RynthSuite a316298). The installer brought RynthAi +0.5.62-legacy-ui, RynthTracker 0.4.1 and ub-Rythai 3.1.13. RynthILT 0.2.6, +RynthOracle 0.2.5, RynthInventory 0.1.2 and the 16 server plugins at 0.1.2 were +copied from their NativeAOT `publish` builds. Old DLLs were backed up to each +plugin's PreviousReleases folder, named by the version they replaced. + +## Files + +- `src/RynthCore.Engine/Compatibility/SessionRates.cs` (new) +- `src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs`, `ClientObjectHooks.cs` +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs` +- `src/RynthCore.Engine/Plugins/PluginManager.cs`, `EntryPoint.cs` +- `src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs`, `MiniRemoteFace.Sections.cs`, `RynthAiFace.cs` +- `src/RynthCore.Engine/UI/Sections/SectionCatalog.cs` +- `tools/SectionsTests/Program.cs`, `SectionsTests.csproj` diff --git a/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md b/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md new file mode 100644 index 0000000..817f99e --- /dev/null +++ b/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md @@ -0,0 +1,61 @@ +# 2026.10.5.61 - engine: DAT share hook no longer intercepts Direct3D and driver file opens + +Previous release: 2026.10.5.60. + +## Problem + +On one PC every RynthCore launch ended with "Could not initialize Direct3D. Please ensure that +DirectX 9.0 or higher is installed." (twice), then "The game encountered a fatal DirectX issue +while attempting to start...", and AC exited with code 1 about 6 seconds in. The same client +started from another launcher (no engine) worked. 2026.10.5.60 (saved UserPreferences.ini +recovery) did not change it. + +In all three logs (builds 2026.10.14.2 and 2026.10.5.60) the error came 27-36 ms after the +engine started loading RynthChat, the plugin right after RynthAi. RynthAi took 378, 390 and +1175 ms to load, and the error moved with it, so AC's device creation was waiting on the engine +and failed as soon as it continued. + +The DAT share hook (on with "Allow multiple clients") detoured the kernel32 `CreateFileA` and +`CreateFileW` exports with MinHook. That caught every caller in the process, including +d3d9.dll and the GPU driver, which open files (shader caches) while AC creates its device. Each +of those opens ran through managed code, which can wait on the runtime while plugins load, and +the detour did not hand back the Win32 last error: callers read it even after a successful +CreateFile (ERROR_ALREADY_EXISTS with OPEN_ALWAYS), and on some drivers that fails device +creation. + +## Change + +- The hook patches only the import slots of the modules that open AC's data files: + `acclient.exe` (imports CreateFileA) and its CRT `MSVCR70.dll` (CreateFileA/W, used by + fopen/_wfopen; the "W" DAT lines in the log come from here). Direct3D, drivers, the runtime + and plugins call CreateFile without the engine in the way. +- The detour sets the Win32 last error back to the value CreateFile left before returning. +- The import slots are written back at engine shutdown (new step + `DatFileShareHooks.Uninstall`), because the detours belong to the engine generation that hot + reload unloads. +- A detour calls whatever its slot held before, so a Decal detour on the kernel32 export still + runs. +- The startup log now lists the hooked slots, for example + `Compat: DAT share - hooked MSVCR70.dll!CreateFileW import (...)`, and the DAT open lines + (`Compat: DAT share - W [filtered]: client_portal.dat ...`) still appear when multi-client is + on. + +## Code + +- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`: MinHook export hooks replaced by + IAT slot hooks (`HookModuleImports`, `InstallSlot`, `Uninstall`, `IatHook` record); detours + take the slot's original delegate and restore the last error (`SetWin32LastError`). +- `src/RynthCore.Engine/EngineLifecycle.cs`: `DatFileShareHooks.Uninstall` before + `MH_DisableHook(ALL)`. + +## Tests + +- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors, no new + warnings. No test project covers the hook; it needs a running client. +- Import tables checked on this PC: `acclient.exe` imports `KERNEL32!CreateFileA` (and + `CreateFileMappingA`); `MSVCR70.dll` imports `KERNEL32!CreateFileA` and `CreateFileW`. + +## For an affected PC before updating + +Set `"EnableDatShareHook": false` in `%APPDATA%\RynthCore\engine.json` (or turn off "Allow +multiple clients"), then launch. If the client starts, this hook was the cause. diff --git a/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md b/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md new file mode 100644 index 0000000..2a91a71 --- /dev/null +++ b/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md @@ -0,0 +1,109 @@ +# 2026.10.5.58 - launcher: first login on a new server, every character on the account + +Previous release: 2026.10.5.57. Launcher project version 0.1.6 (was 0.1.5). + +## Problem + +An account set up for a new server never got in. The `SK` profile (Conquest, +`acconquest.ddns.net:9000`, and earlier Aelrynth) had no password saved, so +the launcher started the client with `-v ""`. The client refuses an empty +password before it connects: it shows "You can only run the game from the +launcher program" and exits about 4 seconds later. All six `SK` launches in the +logs (Aelrynth, 2026-10-13 08:31 to 23:47; Conquest, 23:48) ended this way, and +the launcher only recorded each one as a crash. + +An empty password would fail on the server too. ACE creates a new account on its +first login (`AllowAutoAccountCreation`), but only when a password is sent, and +it boots a login without one. + +Also: + +- A new account profile had no server picked unless you chose one, and the + launch list then put it on the first server profile. +- The launch list showed "(None - no auto-login) | offline" as if it were a + character name. + +## Change + +- **First Login dialog.** A manual launch of an account with no usable password + (none saved, or one that can't be decrypted on this Windows user) asks for it + first, instead of starting a client that can only fail. It has: + - An optional list of the account names used in your other profiles, to pick + an account you already have. + - The account name. On ACE, a new name creates the account on this first + login, if the server allows it. + - A password with confirmation, saved encrypted like the other accounts. If + another profile has the same account name with a saved password, a checkbox + reuses it (the encrypted copy is copied, never the plain text). + - "Log in as": stop at character select, or any character already known for + the account. + + Cancelling skips that account and logs why. Automatic launches don't show the + dialog. They skip the account, logging it at most once every 5 minutes. +- **Characters on the account.** With no character chosen, the client stops at + character select, where you can create characters. The engine already saves + the account's character list from character select, including newly created + characters. + - Stopping at character select before any character is known saves an empty + choice, not "(None)". Once the first character exists and is the only one, + the next launch logs it in. + - With several characters, the launch list's dropdown, and the new "Log in as" + in Edit Account, list them all. You pick which one logs in, or stop at + character select. +- **Account Profile dialog.** + - New "Log in as" list. + - A new account defaults to the server selected in the list. + - A server must be picked when there are server profiles. + - Account names over 50 characters (ACE's limit), or with ':' on GDLE (whose + login argument is `account:password`), are refused. +- **Launch list status.** "Needs password | launch to set up" for an account + without one, and "Character select" instead of the "(None)" text. +- **Never an empty password.** + - `AcLaunchArgumentBuilder.BuildArguments` refuses to build a command line with + an empty password, with the reason. + - The launch preview says the password is missing instead of showing `-v ""`. + - `RynthCore.Injector launch` refuses too. + +## Tests + +- tools/LauncherSettingsTests: 152 checks pass. + - The old checks that an account without a password "still launches as before + (empty)" now check that it's refused, with the reason, on ACE and GDLE. + - New: account-name checks, and a "first login on a new server" scenario: + - known account names + - reusing another profile's saved password (the copied encrypted password + still decrypts) + - the Log in as choices and what each saves + - the dialog's input checks +- tools/AelrynthTests: 89/89. +- The launcher and the injector build. The dialogs were not shown in a test run. + +## Files + +- `src/RynthCore.App/FirstLoginRules.cs` (new), `AcLaunchArgumentBuilder.cs`, `LaunchAccountProfile.cs` +- `src/RynthCore.App.Avalonia/FirstLoginDialog.axaml` and `.axaml.cs` (new) +- `src/RynthCore.App.Avalonia/AccountProfileDialog.axaml` and `.axaml.cs`, `MainWindow.axaml.cs`, + `RynthCore.App.Avalonia.csproj` +- `src/RynthCore.Injector/LaunchCommand.cs` +- `tools/LauncherSettingsTests/Program.cs`, `LauncherSettingsTests.csproj` + +## Install + +- Launcher only; the engine stays at 2026.10.5.57. Published like + `installer\Build-Installer.ps1` step 1: `-r win-x86 --self-contained true + -p:Version=2026.10.5.58`. The apphost `RynthCore.App.Avalonia.exe` is + installed as `RynthCore.exe`; the .pdb files are not installed. +- The first copy was published with `--self-contained false` and wouldn't start: + "You must install or update .NET ... 'Microsoft.NETCore.App', version '10.0.0' + (x86)". The install folder carries its own .NET 10.0.5 runtime and the old + `runtimeconfig.json` lists it under `includedFrameworks`; a framework-dependent + launcher instead asks for a shared x86 runtime. The self-contained build + bundles the same 10.0.5 runtime, so only the five launcher files change (the + other 213 published files are byte-identical to the install). No machine-wide .NET + install is needed. +- Checked locally: the launcher starts, shows its window, reports + 2026.10.5.58, and logs no errors. +- The previous launcher (2026.10.5.55) is backed up in + `C:\Games\RynthCore\PreviousReleases\launcher-2026.10.5.55`. To roll back, + close the launcher and copy those five files over `C:\Games\RynthCore`. +- Running game clients don't depend on the launcher and keep running. diff --git a/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md b/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md new file mode 100644 index 0000000..60e8d4d --- /dev/null +++ b/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md @@ -0,0 +1,49 @@ +# 2026.10.5.57 - attacks and target selects no longer wait behind gestures + +Previous release: 2026.10.5.56. + +Goes with RynthAi 0.5.64-legacy-ui (fewer weapon swaps, faster point-blank +stall recovery: `RynthSuite/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md`). + +## Problem + +While a gesture is in flight (the CMotionInterp pending-motion list is not +empty), `AcMainThreadQueue` defers the whole action ring for up to +`DrainDeferMaxMs` (2.5 s). With a crossbow or bow, a gesture is in flight +nearly all the time. In Silentkelpie's 2026-10-14 logs, target selects and +attacks ran 1.0-1.9 s late, and some attacks went past the 1.5 s stale limit +and were dropped. + +## Change + +- New `AcMainThreadQueue.RunsDuringGesture`. The retail client does these from + a key press at any moment, swing or not, so they now run during the defer: + - `SetSelectedObject` (the target select). + - `NativeAttack` (ClientCombatSystem StartAttackRequest / EndAttackRequest, + which the client itself holds until the motion allows it). + - `CancelAttack` (the 0x1B7 packet). +- These run from the head of the ring up to the first entry that doesn't + qualify, using `ActionRing.TryPeek` and `Pop`. FIFO order is kept: nothing + overtakes a held entry. +- Stance changes, movement, raw attack packets and item moves stay deferred as + before. When the gesture-safe entries empty the ring, the defer clock resets, + so the next held entry gets its full defer. + +## Tests + +- Engine builds. All RynthCore tool tests pass (EngineRobustnessTests 1159 + checks, among others). There is no unit harness for the drain (it needs AC's main + thread). The change is checked live through RynthAi's logs: attacks should no + longer be reported late or stale behind crossbow gestures. + +## Files + +- `src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs` + +## Install + +Installed locally on 2026-10-14: `RynthCore.Engine.dll` and `.pdb` 2026.10.5.57 (RynthCore b8c84ad, +published with `scripts\Publish-EngineCoreClr.ps1 -EngineOnly`) copied to +C:\Games\RynthCore\Runtime. The 2026.10.5.55 engine was backed up to +PreviousReleases\2026.10.5.55-engine. Running clients keep the old engine until +they are restarted. diff --git a/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md b/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md new file mode 100644 index 0000000..d0d2394 --- /dev/null +++ b/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md @@ -0,0 +1,61 @@ +# 2026.10.5.60 - launcher: undo a saved UserPreferences.ini that stops the client starting + +Previous release: 2026.10.5.59. Launcher project version 0.1.7 (was 0.1.6). + +## Problem + +A client launched from RynthCore showed "Could not initialize Direct3D. Please ensure that +DirectX 9.0 or higher is installed." twice, then "The game encountered a fatal DirectX issue +while attempting to start. Try a different screen resolution or bit depth...", and exited +about 12 seconds after start. The same client started fine from another launcher. + +The engine was not involved: its D3D9 hooks only start at login, and the log had no D3D9 +lines. The difference was the launcher. Before every launch it copies the account's saved +game settings (`%APPDATA%\RynthCore\prefs\<account>@<server>.ini`, or the file set on the +profile) over the live `Documents\Asheron's Call\UserPreferences.ini`. The game reads its +resolution and full-screen mode from that file. A saved copy with a display mode the PC can't +use (another monitor, an old resolution) fails every launch, and the saved copy is only +refreshed after a normal session, so it was restored again on every launch. Another launcher +uses the live file, which is why it worked. + +## Change + +- When a client quits within 30 s (the existing "counted as crash" window) and its launch + swapped in a saved UserPreferences.ini that differs from the live file: + - The saved copy is renamed to `<name>.ini.failed-yyyyMMdd-HHmmss` (kept, never swapped in + again). The account's old name-only copy (`<account>.ini`) is set aside too when it holds + the same settings, because it re-seeds a missing per-server copy. + - The live UserPreferences.ini is put back to what it was before the swap, unless another + launch has swapped it since. + - The activity log says what happened. The next launch uses the live file, and the next + normal session saves a fresh copy. +- A file the user picked on the profile (UserPrefsPath) is never renamed; the live file is + still put back and the activity log points at the profile setting. +- Nothing changes when the saved copy matched the live file (the swap can't have caused the + exit), e.g. a missing password or a server that is down. + +## Code + +- `src/RynthCore.App/UserPrefsSwapRecovery.cs` (new): `UserPrefsSwap` record (stash path, + live path, stash bytes, live bytes before the swap), `SwapChangedPrefs`, `Recover` + (quarantine + restore), `QuarantinePath`. +- `src/RynthCore.App/AcClientLaunchSettingsService.cs`: `SwapUserPreferences` returns the + `UserPrefsSwap` (was `bool`) and reads the live file before overwriting it. +- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs`: the three launch paths (RynthCore, Decal / + Decal + RynthCore, no injection) use `ApplyPrefsSwap` and record the swap per PID + (`TrackPrefsSwap`); `DetectQuickExits` calls `RecoverFailedPrefsSwap` for a quick exit. A swap + generation counter decides whether the live file can still be put back. + `ResolveLegacyUserPrefsPath` is shared with `ResolveUserPrefsPath`. +- `RynthCore.App.Avalonia.csproj`: links the new file; version 0.1.7. + +## Tests + +- `tools/LauncherSettingsTests`: 5 new scenarios (swap changed the live file or not; failed + stash set aside and live file restored; a different name-only stash kept; profile override + and later swap leave files alone; no live file before). `PASS: 163 checks`. +- `dotnet build src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release`: 0 errors. + +## For an affected PC now + +Rename or delete `%APPDATA%\RynthCore\prefs\<account>@<server>.ini` (and `<account>.ini`) for +the failing account, or clear the UserPreferences file on its profile, then launch again. diff --git a/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md b/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md new file mode 100644 index 0000000..bc3061a --- /dev/null +++ b/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md @@ -0,0 +1,48 @@ +# 2026.10.5.59 - Loot Timers show their optimized defaults, with a button to use them + +Previous release: 2026.10.5.58 (installed engine 2026.10.5.57). + +Goes with RynthSuite's `Changelog/2026-10-14-loot-baseline-0.5.65.md` (RynthAi 0.5.65), which +measured the loot timer baseline and applied it to RynthAi's own Advanced Settings. The +engine's Settings panel (Looting tab) still showed the old list with no defaults. + +## Change + +- **Settings > Looting > Loot Timers (ms) - (optimized default).** Each timer's label ends + with its optimized default in brackets: + - Content Settle (100) + - Empty Corpse Wait (300) + - Assess Window (300) + - Loot Retry Timeout (1000) + - Corpse Open Retry (1500) + - Corpse Timeout (12000) +- **Use optimized defaults** button: sets all six timers to those values and saves them to + RynthAi like a typed value. It works in the in-game panel and in the launcher's panel. +- Each timer has a tooltip (what it waits for, and the measured appraisal times for Assess + Window). +- Inter-Item Delay and Closing Delay are no longer shown: RynthAi's corpse looting never reads + them (RynthAi hid them in 0.5.65). They are still carried so a save doesn't send them missing. +- The engine's own defaults for the timers (used until RynthAi sends its settings) now match + the optimized defaults: Assess Window 200 -> 300 ms, Loot Retry Timeout 500 -> 1000 ms. + +## Code + +- `UI/Data/SettingsData.cs`: new `LootTimerDefaults` (the six values, same as RynthSuite's + `LootBaseline.cs`; `Label`, `Apply`, `AllDefault`). `SettingRow` gains an optional + `Edit` action for buttons that change settings, built with `EditButton`. +- `ImGui/Panels/SettingsFace.cs` and `UI/Panels/SettingsPanel.cs`: a button row with `Edit` + applies it to the panel's copy and saves it (the launcher panel also rebuilds the tab so the + number boxes show the new values). + +## Tests + +- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors. No test + project compiles `SettingsData.cs`. + +## Install + +Installed locally on 2026-10-14: `RynthCore.Engine.dll` and `.pdb` 2026.10.5.59 (RynthCore 1590c2a, +published with `scripts\Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs -p:Version=2026.10.5.59`; +the script's `status-export` branch no longer exists, and the installed 2026.10.5.57 commit is in +this build) copied to C:\Games\RynthCore\Runtime. The 2026.10.5.57 engine was backed up to +PreviousReleases\2026.10.5.57-engine. Running clients hot-reload onto the new engine. diff --git a/Changelog/2026-10-15-borderless-restore-chrome-2026.10.5.67.md b/Changelog/2026-10-15-borderless-restore-chrome-2026.10.5.67.md new file mode 100644 index 0000000..79d2694 --- /dev/null +++ b/Changelog/2026-10-15-borderless-restore-chrome-2026.10.5.67.md @@ -0,0 +1,29 @@ +# 2026.10.5.67 - Borderless Windowed: restore title bar when turning off + +Previous release: 2026.10.5.66. + +## Bug + +Turning **Borderless Windowed** off did not bring back the Asheron's Call title bar +and borders — especially when the client was maximized (or otherwise filled the +monitor). `IsLikelyExclusiveFullscreen` treated that maximized borderless frame as +exclusive fullscreen and skipped the restore path, so chrome stayed gone. Turning +the setting back on then did nothing useful. + +Seen on Silentkelpie (pid 34764 / earlier 55676): log showed `borderless windowed on` +and never `window borders restored`. + +## Fix + +- Do not block chrome restore for maximized borderless windows we stripped. +- Only skip applying borderless when the client already looks like true exclusive + fullscreen and we have not already taken chrome off. +- If the saved style was lost (hot reload) or already lacked a caption, rebuild + chrome with the full border mask so Off still heals a stuck window. +- Settings toggle uses the same HWND resolver as Tick. + +## Test plan + +- [ ] Windowed AC: Borderless on → chrome gone; off → title bar and borders return. +- [ ] Maximized windowed: same on/off cycle restores chrome. +- [ ] Exclusive fullscreen: Borderless toggle does not fight the client. diff --git a/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md b/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md new file mode 100644 index 0000000..0d89b2e --- /dev/null +++ b/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md @@ -0,0 +1,65 @@ +# 2026.10.5.64 - engine: second client can open the DAT files again (2025 client) + +Previous release: 2026.10.5.62. + +## Problem + +With "Allow multiple clients" on, only the first client started. Every client launched after it +(Silentstorm, SK, ...) showed "Can't open the data files. Check that they exist and that you +have permission to write to them. The program will now exit." about half a second after the +engine loaded. + +The 2025 client (`C:\Turbine\Asheron's Call-ryn\ACClient.exe`, 0.0.11.6096) does not import +`kernel32!CreateFileW`. A Layer-for-Unicode style stub at `0x006B8D00` looks it up on first use +and stores it in a private slot at `0x00837374`, and AC opens every DAT file through that slot. + +- Up to 2026.10.5.60 the DAT share hook detoured the kernel32 export, so it caught those opens. + The log showed them as `Compat: DAT share - W [filtered]: client_portal.dat ... share=0x1->0x7`. +- 2026.10.5.61 moved the hook to the import tables of `acclient.exe` and `MSVCR70.dll`, to keep + Direct3D and drivers out of it. The private slot is in no import table, so from .61 on no DAT + open was rewritten. The `W [filtered]` lines stopped appearing. +- The first client then opened the DATs read/write and denied writes to everyone else + (`share=0x1`). A second client's own read/write open failed with a sharing violation. + +Confirmed on the running client: the three import slots pointed at the engine's detours, but the +private slot `0x00837374` still held `kernel32!CreateFileW`. + +## Change + +- The DAT share hook also finds acclient.exe's private CreateFileW/CreateFileA slots, then points + them at the same detours. Uninstall restores them like the import slots. +- The slots are found by the stub's full byte pattern, not a fixed address: + - push slot, push the function name, push "kernel32.dll", call the resolver, then + `jmp [slot]` through the same slot; + - the name must stand alone ("MyCreateFileW" does not count); + - the DLL operand must name kernel32.dll. +- If the slot hasn't been resolved yet (it still points at its stub), the detour calls + `kernel32!CreateFileW` directly, because calling the stub would overwrite the slot. +- Direct3D, drivers, the runtime and plugins still call CreateFile without the engine in the way. +- The startup log lists the slot, for example + `Compat: DAT share - hooked acclient.exe!CreateFileW private slot (stub 0x006B8D00) (slot 0x00837374, was 0x76ACEA10).` + With multi-client on, the `W [filtered]: client_portal.dat` lines come back. + +## Code + +- `src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs` (new): reads the section table + of a mapped image and finds the stubs (`ReadSections`, `FindSlots`). +- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`: + - `HookLazySlots` hooks the private slots; + - `HookSlot` builds the A/W detour for import slots and private slots alike; + - the log line names the kind of slot. +- `tools/DatShareSlotTests` (new), 20 checks: + - synthetic stubs; + - near misses that must not match (another jmp slot, another DLL, a longer name, no call, a + slot outside the image, a lone push of the name); + - the real 2025 client: slot `0x00837374`, stub `0x006B8D00`, no CreateFileA slot. + +## Tests + +- `dotnet run -c Release --project tools\DatShareSlotTests`: 20 checks, 0 failed. +- `dotnet build src\RynthCore.Engine -c Release`: 0 errors, no new warnings. + +## Before updating + +Close the other clients first. A client already running on .61/.62 holds the DATs deny-write, +so a new client can't start alongside it until it is closed, even on .64. diff --git a/Changelog/2026-10-15-display-borderless-remember-layout-2026.10.5.65.md b/Changelog/2026-10-15-display-borderless-remember-layout-2026.10.5.65.md new file mode 100644 index 0000000..c21aeac --- /dev/null +++ b/Changelog/2026-10-15-display-borderless-remember-layout-2026.10.5.65.md @@ -0,0 +1,41 @@ +# 2026.10.5.65 - Settings > Display: borderless windowed and remember layout + +Previous release: 2026.10.5.64. + +## Change + +Under **Settings > Display**: + +- **Borderless Windowed** — strips the Asheron's Call title bar and borders while + staying windowed (exclusive fullscreen is left alone). Stored in `engine.json` + as `BorderlessWindowed` (default off); applies to every client on this PC. +- **Remember Open Windows and Positions** — when on (default), reopen Rynth panels + where you left them, keep Vision HUD / `imgui.ini` layout, and restore the AC + window position across launches. When off, do not overwrite `panel_state.txt` or + reopen panels / AC placement from the last session (`RememberWindowLayout` in + `engine.json`). +- **Save Layout Now** — writes open panels, AC window placement, Vision self-plate, + and ImGui window positions to disk immediately. + +## Files + +| Area | Notes | +|---|---| +| `UI/AcWindowChrome.cs` | New: GWL_STYLE borderless + `ac_window.txt` placement | +| `Plugins/EngineSettings.cs` | `BorderlessWindowed`, `RememberWindowLayout` | +| `UI/Data/SettingsData.cs` | Display rows; `SettingKind.Color` (was missing on this branch) | +| `UI/PanelStateStore.cs` | Gate saves; `Flush()` for Save Now | +| `ImGui/ImGuiPanelHost.cs` / `UI/AvaloniaOverlay.cs` | Skip restore when remember is off | +| `ImGui/EngineFrameController.cs` | Throttled `AcWindowChrome.Tick` | + +Also restored a few files that were already broken on `build-comp-10-11` so the +engine could compile again (`SettingsFace`, `ImGuiBar` DrawControls/BarMenu, +`RynthAiFace`, `MiniRemoteFace` + `.Sections`) from aelrynth `main`. + +## Test plan + +- [ ] Windowed AC: toggle Borderless Windowed on/off; chrome hides and returns. +- [ ] Exclusive fullscreen: toggle does not break the client. +- [ ] Arrange panels, Save Layout Now, restart client with Remember on: panels reopen. +- [ ] Remember off: rearrange panels, restart: previous saved layout is not overwritten; + panels do not force-reopen from disk. diff --git a/Changelog/2026-10-15-loot-picker-filter-2026.10.5.66.md b/Changelog/2026-10-15-loot-picker-filter-2026.10.5.66.md new file mode 100644 index 0000000..cb6919a --- /dev/null +++ b/Changelog/2026-10-15-loot-picker-filter-2026.10.5.66.md @@ -0,0 +1,19 @@ +# 2026.10.5.66 - Loot editor pickers: type-to-filter + +Previous release: 2026.10.5.65. + +## Change + +The shared ImGui `FaceKit.Picker` (loot face key/value lists, and any other face +using it) shows a **Type to filter…** box when the list has 12 or more items. +Players can type part of a name (e.g. `olth` for Olthoi) instead of scrolling +long lists such as **Slayer Type** creature names, materials, or long keys. + +Filter is case-insensitive substring match; empty filter shows the full list. +Selecting still returns the original list index to the caller. + +## Pair with + +RynthSuite loot vocab rename: long key 166 displays as **Slayer Type** with an +A–Z creature-type value table (see Suite changelog +`2026-10-15-loot-slayer-type-picker.md`). diff --git a/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md b/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md new file mode 100644 index 0000000..4464622 --- /dev/null +++ b/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md @@ -0,0 +1,45 @@ +# Breadcrumbs and Route overlay on Settings > Navigation (2026.10.5.62) + +Date: 2026-10-15 + +| Component | Version | Previous release | +|---|---|---| +| RynthCore.Engine | 2026.10.5.62 | 2026.10.5.61 | + +## What's new + +Settings > Navigation now has the Nav panel's two overlay switches, at the top of "Nav Marker +Display": + +- **Breadcrumbs**: record the trail you walk and draw it on the ground (`/ra navtrail on|off`). +- **Route Overlay**: draw the route in the world, meaning the waypoint rings and lines, the + waypoint labels and the guide line (`/ra navoverlay on|off`). + +They are the same switches as on the Nav panel, not copies. A change in either place shows in the +other: + +- The Nav panel's toggle also asks the Settings page to fetch again. It updates the Nav panel's + own settings copy too, so a nav point reach saved straight afterwards doesn't send the old value + back. +- A save from the Settings page also asks the Nav panel to fetch again. + +Both panels share the tooltips (`SettingsSchema.BreadcrumbsTip` and `RouteOverlayTip`). + +## Compatibility + +The new fields (`TrackBreadcrumbs` and `ShowRouteOverlay` in `RynthAiSettings`) are nullable. + +- **Older RynthAi:** it doesn't send them, so the two rows stay hidden, and a save sends null, + which RynthAi reads as unchanged. +- **RynthAi 0.5.70-legacy-ui or later:** sends and applies them. + +## Files + +- `src/RynthCore.Engine/UI/Data/SettingsData.cs`: the fields, the two rows, the shared tooltips, + and the Nav refresh after a save. +- `src/RynthCore.Engine/ImGui/Panels/NavFace.cs`: the shared tooltips and the local settings copy. +- `src/RynthCore.Engine/UI/Data/RynthAiData.cs`: a Settings refresh after each nav command. + +## Install + +The installer build (`installer\Build-Installer.ps1`) stamps the engine as 2026.10.5.62. diff --git a/Changelog/2026-10-15-vaulted-dungeons-options-nav-2026.10.5.68.md b/Changelog/2026-10-15-vaulted-dungeons-options-nav-2026.10.5.68.md new file mode 100644 index 0000000..8a35032 --- /dev/null +++ b/Changelog/2026-10-15-vaulted-dungeons-options-nav-2026.10.5.68.md @@ -0,0 +1,17 @@ +# Options > Navigation > Vaulted Dungeons (2026.10.5.68) + +Date: 2026-10-15 +Previous release: 2026.10.5.67 + +## What + +Adds an Options > Navigation checkbox **Vaulted Dungeons** (under Infinite Leaftide). When on, +RynthAi shows RynthILT's Mini Remote "Vaulted Dungeons" tab on ILT / ACECustom worlds. + +Also: ChatData.ChannelForType maps chat type 0x1C (28) to Channels so ILT Trade/General lines +match RynthChat's classifier. + +## Files + +- UI/Data/SettingsData.cs — EnableVaultedDungeons + Navigation schema row +- UI/Data/ChatData.cs — type 0x1C → Channels diff --git a/Changelog/2026-10-16-bar-hide-itemcount-ginv-2026.10.16.6.md b/Changelog/2026-10-16-bar-hide-itemcount-ginv-2026.10.16.6.md new file mode 100644 index 0000000..aa9b714 --- /dev/null +++ b/Changelog/2026-10-16-bar-hide-itemcount-ginv-2026.10.16.6.md @@ -0,0 +1,13 @@ +# 2026.10.16.6 - Bar: hide Item Count (opens from Inventory) + +Previous: 2026.10.16.5. + +## Change + +Item Count no longer gets its own ImGui bar icon. Open it from Inventory's Count +button (or `/rc itemcount` / Character menu). Global Inventory's bar button is +cleared in RynthInventory 0.1.2 (Scripts menu + Inventory GInv / `/ginv` remain). + +## Files + +- ImGui/ImGuiBar.cs diff --git a/Changelog/2026-10-16-chat-combat-standard-filters-2026.10.16.10.md b/Changelog/2026-10-16-chat-combat-standard-filters-2026.10.16.10.md new file mode 100644 index 0000000..d7e0461 --- /dev/null +++ b/Changelog/2026-10-16-chat-combat-standard-filters-2026.10.16.10.md @@ -0,0 +1,28 @@ +# 2026.10.16.10 - Chat standard filters: combat response breakdown + +Previous: 2026.10.16.9. + +## What + +Standard filters (Chat Filters panel) can now hide combat responses by kind, +matching UB ChatHandler's melee / magic split plus the common prefixes: + +- Melee / missile damage you deal or take (`… points of … damage`) +- Magic damage you deal or take (`… points with SpellName`) +- Recklessness / Sneak Attack / Critical prefixes (filter alone or with the rest) +- Periodic healing ticks (also under Combat, not only Items) +- Stamina / mana / health restore-or-spend lines +- Umbrella "All damage you deal / take" still covers both `of` and `with` forms + (the old patterns only caught `of`, so war magic hits slipped through) + +Missile hits share the melee text form in AC; environment misses stay on their +own filter. + +## Files + +- `UI/Panels/RynthChatPresets.cs` +- `UI/Data/ChatFilterPresets.cs` + +## Deploy + +`Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.10')` diff --git a/Changelog/2026-10-16-chat-filters-hide-retail-chat-2026.10.16.23.md b/Changelog/2026-10-16-chat-filters-hide-retail-chat-2026.10.16.23.md new file mode 100644 index 0000000..5d1e261 --- /dev/null +++ b/Changelog/2026-10-16-chat-filters-hide-retail-chat-2026.10.16.23.md @@ -0,0 +1,40 @@ +# 2026.10.16.23 — Chat filters hide lines in the retail chat too; settings follow other clients + +**Kind:** Hot push (Engine). Previous `2026.10.16.22`. + +## Problem + +1. A standard filter (or a Hide rule) such as **Kill task progress** hid the line in RynthChat, + but AC's own chat window still printed it ("You have killed 22556 Fanatical Fiuns! You must + kill 100000 to complete your task."). +2. With several clients open, ticked standard filters came back off: every client writes its whole + state to the one `%AppData%\RynthCore\rynthchat_settings.json` and never re-read it, so the + last client to save overwrote the others' changes. + +## Cause + +1. RynthChat's rules and standard filters live in the engine and only decided where a line shows + in RynthChat. AC's print path holds each incoming line for a verdict, but that verdict came only + from plugins (their `eat` flag); the engine's own Hide decision was never asked. +2. No re-read of the shared settings file after startup. + +## Fix + +1. After the plugins' verdict on a held line, the engine runs the same rules and standard filters + (`ChatModel.ShouldHideInRetail`: same channel the RynthChat plugin would give it, a separate + router that doesn't double-count hits). A hidden line is kept out of AC's chat window. + New option under **Standard filters**: *Hidden lines are hidden in the retail chat too* + (on by default, saved as `hideInRetail`). Moved / copied lines still show in the retail chat. +2. Every client checks the settings file every 2 s and reloads rules, standard filters, tabs and + display options when another client changed it (its own saves are recognised and skipped; + its selected tab is kept; an unreadable file is ignored). + +## Notes + +- Only lines the engine holds can be kept out: with `/rc chathold off`, or if the plugin pump is + stalled, a line prints before the verdict and shows as before. +- Re-tick **Kill task progress** / **Kill task complete** once: the shared file lost them. + +## Checks + +Engine builds; ChatFilterTests 1310, ChatHoldTests 46, ChatDiscordTests 316, ChatTellTests 59 pass. diff --git a/Changelog/2026-10-16-chat-filters-ubit-parity-2026.10.16.2.md b/Changelog/2026-10-16-chat-filters-ubit-parity-2026.10.16.2.md new file mode 100644 index 0000000..0dcdec6 --- /dev/null +++ b/Changelog/2026-10-16-chat-filters-ubit-parity-2026.10.16.2.md @@ -0,0 +1,31 @@ +# 2026.10.16.2 - Chat standard filters: UB-IT parity + +Previous: 2026.10.16.1. + +## What + +Standard filters (`RynthChatPresets`, Chat Filters panel) now cover the rest of +UB-IT `ChatFilterTool` / classic `ChatHandler` options that can be matched from +line text alone: + +- Kill-task **progress** (ACECustom / UB-IT) +- Master Arbitrator **spam** (selective) vs **all** +- Missile environment miss, periodic damage, fail-to-affect +- Give/take vitals, heal-self casts, healed-by-other, consumables +- Aetheria surge, cloak procs, banked luminance +- You're too busy / Casting status (when those lines hit chat) + +Still not text-presets (need Decal WorldFilter / StatusTextIntercept): vendor +tells, monster tells, NPC chatter, StatusTextAll. + +The "add as rule" picker (`ChatFilterPresets`) gained matching extras for the +same common spam lines. + +## Files + +- `UI/Panels/RynthChatPresets.cs` +- `UI/Data/ChatFilterPresets.cs` + +## Deploy + +`Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.2')` diff --git a/Changelog/2026-10-16-dxvk-detect-software-overlay-2026.10.16.13.md b/Changelog/2026-10-16-dxvk-detect-software-overlay-2026.10.16.13.md new file mode 100644 index 0000000..d7ed340 --- /dev/null +++ b/Changelog/2026-10-16-dxvk-detect-software-overlay-2026.10.16.13.md @@ -0,0 +1,16 @@ +# 2026.10.16.13 — DXVK detection + software overlay policy + +## Summary + +Adds a one-shot `DxvkDetection` probe for drop-in / non-system `d3d9.dll` (DXVK smoke path). When DXVK or another game-dir d3d9 is active, Rynth forces the software Avalonia overlay (`CreateTexture` + `LockRect`) and skips D3D9Ex shared-HANDLE uploads. Smoke checklist: `docs/DXVK_TEXTURE_SMOKE.md`. + +## Changes + +- `D3D9/DxvkDetection.cs` — module path + FileVersionInfo / `dxvk.conf` probe; Milestone log lines for grepping. +- `D3D9Bootstrapper` — probe + overlay policy as soon as `d3d9.dll` is loaded (Decal and post-login paths). +- `AvaloniaOverlay` — prefer software bridge when DXVK / non-system d3d9 is detected. +- Docs: `docs/DXVK_TEXTURE_SMOKE.md` (DLL layout, log greps, pass/fail). + +## Version + +- Engine ProductVersion: **2026.10.16.13** (hot push from 2026.10.16.12). diff --git a/Changelog/2026-10-16-engine-kite-pull-away-ui.md b/Changelog/2026-10-16-engine-kite-pull-away-ui.md new file mode 100644 index 0000000..cfd542f --- /dev/null +++ b/Changelog/2026-10-16-engine-kite-pull-away-ui.md @@ -0,0 +1,15 @@ +# Engine — Pull-away kite UI (with RynthAi 0.5.79) + +**Date:** 2026-10-16 +**Kind:** Hot push companion to RynthAi kite +**ProductVersion:** stamp with `-p:Version=2026.10.16.14` (above live Runtime `2026.10.16.13`) + +## Summary + +Engine settings and Damage detail expose RynthAi’s new pull-away kite: + +- **Damage detail → Kite**: Default / Off / PullAway (per monster; Default follows DEFAULT row) +- **Settings → Melee Combat → Pull Away (Kite)**: Pull Distance (m), Tag Before Fleeing +- **MonstersPanel.Rule.Kite** on the monsters bridge (older engines omit it; RynthAi carries the prior value) + +No combat logic in the Engine — execution is entirely in RynthAi `CombatManager.Kite`. diff --git a/Changelog/2026-10-16-full-install-suite-plugins-2026.10.16.21.md b/Changelog/2026-10-16-full-install-suite-plugins-2026.10.16.21.md new file mode 100644 index 0000000..3407c7b --- /dev/null +++ b/Changelog/2026-10-16-full-install-suite-plugins-2026.10.16.21.md @@ -0,0 +1,27 @@ +# 2026.10.16.21 — Full install ships the RynthSuite companion plugins + +**Kind:** Hot push (test build installer). Previous live tip `2026.10.16.20` (Engine + Oracle 0.3.3). + +## Problem + +The installer packaged only RynthAi and the six experimental plugins. RynthOracle, +RynthILT, RynthInventory and RynthSort — where most of today's fixes live (quest refresh, +aug Refresh current, Fellowship `/fship`) — were never in a full install; they only arrived +through the update feed or a hand copy. RynthAi's DLL also read `1.0.0` (published without +the release version). + +## Change + +- New installer component group **RynthSuite: Companion plugins** (on in a Full install): + RynthOracle, RynthILT, RynthInventory, RynthSort. Each installs to + `<RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll` and is registered with the launcher + like RynthAi. +- `Build-Installer.ps1` publishes them (NativeAOT) with the release calver, stages and + checks them, and lists them in `release-manifest.json`. +- RynthAi publishes with the release calver too (its plugin version stays + `HandWrittenVersion`). + +## Includes + +Engine `2026.10.16.20` chat queue (4096) and RynthOracle 0.3.3 quest refresh fix, on the +`test/hotbuild-2026-10-16-on-aelrynth` merge (current `aelrynth/main`). diff --git a/Changelog/2026-10-16-hotbuild-local-2026.10.5.69.md b/Changelog/2026-10-16-hotbuild-local-2026.10.5.69.md new file mode 100644 index 0000000..01e5a25 --- /dev/null +++ b/Changelog/2026-10-16-hotbuild-local-2026.10.5.69.md @@ -0,0 +1,12 @@ +# RynthCore 2026.10.5.69 — local hotbuild (tonight) + +Date: 2026-10-16 +Engine: 2026.10.5.69 (previous 2026.10.5.68) + +## Included from local (build-comp-10-11) + +- Options > Navigation > Vaulted Dungeons checkbox (`EnableVaultedDungeons`). +- Chat type 0x1C (28) → Channels (ILT/ACECustom `[Trade]`/`[General]`). +- Borderless / chrome restore and related display layout work from 2026-10-15 changelogs (.65–.67), carried forward in this compile. + +Hot-deployed to `C:\Games\RynthCore` with matching Suite plugins (see Suite changelog). diff --git a/Changelog/2026-10-16-hotpush-2026.10.15.8.md b/Changelog/2026-10-16-hotpush-2026.10.15.8.md new file mode 100644 index 0000000..b403408 --- /dev/null +++ b/Changelog/2026-10-16-hotpush-2026.10.15.8.md @@ -0,0 +1,11 @@ +# 2026.10.15.8 - Hot push: tonight features above rynth tip + +Previous release / tip: 2026.10.15.7 (aelrynth + Games plugins). Local track was wrongly on 2026.10.5.x. + +## Hot push bump + +Calver ProductVersion **2026.10.15.8** (patch +1 from tip). Includes Display borderless/layout, Navigation Vaulted Dungeons gate, chat type 0x1C. + +## Deploy + +CoreCLR Runtime via Publish-EngineCoreClr with `-p:Version=2026.10.15.8`. diff --git a/Changelog/2026-10-16-hotreload-no-erl-bypass-2026.10.16.5.md b/Changelog/2026-10-16-hotreload-no-erl-bypass-2026.10.16.5.md new file mode 100644 index 0000000..637c339 --- /dev/null +++ b/Changelog/2026-10-16-hotreload-no-erl-bypass-2026.10.16.5.md @@ -0,0 +1,35 @@ +# 2026.10.16.5 - Hot reload: ERl no longer bypasses the in-world hold + +Previous: 2026.10.16.4. + +## Why + +Automatic FileWatcher hold (16.3) worked — clients logged +`holding reload - engine says not safe yet (in-world)`. Pressing ERl / RL / +`/rc rl` while still in-world set the manual bypass, `MayHotReload` returned 1, +Shutdown skipped the world gate, and CoreCLR re-init AVed (e.g. pid 37684 at +10:25:42, `clr_37684_*.dmp`, gen 2 init then native crash in coreclr). + +## What + +- `RynthCoreMayHotReload` no longer treats a recent ERl as "safe now". +- `ReloadInWorldGate.ShouldHold` holds for manual as well as automatic reloads + (unless `AllowInWorldAutoHotReload`). +- Shutdown's world gate always runs while in-world; ERl only skips the combat / + plugin blocker wait once out of the world. +- ERl / RL / `/rc rl` / hotkey go through `RequestManualReload`: signal still + fires (applies on logout), chat warns once while in-world. + +## Deploy + +Logout / character select once so clients on 16.3–16.4 pick this up (do not ERl +in-world on those builds). Then: + +`Publish-EngineCoreClr.ps1 -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.5')` + +## Files + +- `ReloadInWorldGate.cs`, `EntryPoint.cs`, `EngineSettings.cs` +- `RynthCoreShell.cs`, `ImGuiBar.cs`, `HotkeyService.cs`, `RynthCoreChatCommands.cs` +- `AvaloniaOverlay.cs`, `DcompOverlayWindow.cs`, `Loader.c` +- `tools/ReloadInWorldGateTests` diff --git a/Changelog/2026-10-16-inventory-itemcount-ginv-buttons-2026.10.16.4.md b/Changelog/2026-10-16-inventory-itemcount-ginv-buttons-2026.10.16.4.md new file mode 100644 index 0000000..b6d5b0b --- /dev/null +++ b/Changelog/2026-10-16-inventory-itemcount-ginv-buttons-2026.10.16.4.md @@ -0,0 +1,24 @@ +# 2026.10.16.4 - Inventory: Item Count and Global Inventory buttons + +Previous: 2026.10.16.3. + +## Change + +Inventory opens the related windows from its own chrome instead of hunting through +menus: + +- Modern header: Bag (Item Count) and Globe (Global Inventory) next to Classic / Close. +- Classic title bar: Count and GInv text buttons (with Vault / size / tools). +- Character menu: Global Inventory line (`RynthInventory/Main`, same as `/ginv`). +- Settings > Inventory Management > Floating HUDs tooltip clarifies the floating + pack item count HUD (`/ra huds`) is not the Item Count panel (`/rc itemcount`). + +Item Count toggles via `PanelRouter` (`/rc itemcount`). Global Inventory toggles the +RynthInventory script window, or runs `/ginv` when the plugin is not loaded yet. + +## Files + +- ImGui/Panels/InventoryFace.cs +- ImGui/Panels/InventoryFace.Classic.cs +- ImGui/Panels/RynthAiFace.cs +- UI/Data/SettingsData.cs diff --git a/Changelog/2026-10-16-inventory-miniremote-off-bar-2026.10.16.8.md b/Changelog/2026-10-16-inventory-miniremote-off-bar-2026.10.16.8.md new file mode 100644 index 0000000..9d12ae8 --- /dev/null +++ b/Changelog/2026-10-16-inventory-miniremote-off-bar-2026.10.16.8.md @@ -0,0 +1,15 @@ +# 2026.10.16.8 - Inventory: Mini Remote button (off the top bar) + +Previous: 2026.10.16.7. + +## Change + +Mini Remote no longer gets its own ImGui bar icon (the 2×2 grid next to +Inventory). Open it from Inventory's Remote / SquaresFour button, Character +menu, or `/rc miniremote`. + +## Files + +- ImGui/ImGuiBar.cs +- ImGui/Panels/InventoryFace.cs +- ImGui/Panels/InventoryFace.Classic.cs diff --git a/Changelog/2026-10-16-inventory-rsort-button-2026.10.16.7.md b/Changelog/2026-10-16-inventory-rsort-button-2026.10.16.7.md new file mode 100644 index 0000000..7d21733 --- /dev/null +++ b/Changelog/2026-10-16-inventory-rsort-button-2026.10.16.7.md @@ -0,0 +1,14 @@ +# 2026.10.16.7 - Inventory: RynthSort button (off the top bar) + +Previous: 2026.10.16.6. + +## Change + +Inventory's header (Modern icons / Classic "Sort") opens RynthSort, same as +`/rsort`. RynthSort no longer gets its own bar button (plugin 0.3.2): use +Inventory, the Scripts menu, or `/rsort`. + +## Files + +- ImGui/Panels/InventoryFace.cs +- ImGui/Panels/InventoryFace.Classic.cs diff --git a/Changelog/2026-10-16-inworld-hotreload-hold-2026.10.16.3.md b/Changelog/2026-10-16-inworld-hotreload-hold-2026.10.16.3.md new file mode 100644 index 0000000..cfe37cb --- /dev/null +++ b/Changelog/2026-10-16-inworld-hotreload-hold-2026.10.16.3.md @@ -0,0 +1,33 @@ +# 2026.10.16.3 - Hold automatic hot reloads while in-world + +Previous: 2026.10.16.2. + +## Why + +Stacked FileWatcher hot publishes while logged in were crashing clients: the +loader shut the engine down, then CoreCLR re-init failed mid-flight (no +`Reload: complete`, large CLR dumps). Combat deferral only waits for plugin +blockers; a quiet in-world unload still tore everything down. + +## What + +- Automatic FileWatcher reloads wait until logout / character select (or ERl / + `/rc rl`). No force-timeout while still in the world. +- New engine export `RynthCoreMayHotReload` (loader 2.2+ polls before Shutdown). +- Old loaders still safe: `RynthCoreShutdown` runs the same in-world gate. +- `engine.json` `AllowInWorldAutoHotReload` (default false) restores the old + mid-session auto-reload behaviour if set true by hand. + +## Files + +- `ReloadInWorldGate.cs`, `EntryPoint.cs`, `Plugins/EngineSettings.cs` +- `native/Loader/Loader.c`, `Loader.h` (LOADER_VERSION 2.2) +- `tools/ReloadInWorldGateTests` + +## Deploy + +`Publish-EngineCoreClr.ps1 -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.3')` + +EngineOnly is enough for the Shutdown gate on running clients. Full publish +stages loader 2.2; running clients keep the old loader until restart (engine +gate still holds). diff --git a/Changelog/2026-10-16-launcher-dxvk-toggle-0.1.8.md b/Changelog/2026-10-16-launcher-dxvk-toggle-0.1.8.md new file mode 100644 index 0000000..852850c --- /dev/null +++ b/Changelog/2026-10-16-launcher-dxvk-toggle-0.1.8.md @@ -0,0 +1,25 @@ +# Launcher 0.1.8 — Enable DXVK toggle + fetch / installer seed + +## Summary + +Adds an opt-in **Enable DXVK (Vulkan D3D9)** launch-behavior checkbox. When on, the launcher installs DXVK’s x86 `d3d9.dll` next to `acclient.exe` (and removes a Rynth-managed copy when off). Package cache: `<RynthCore>\Runtime\dxvk\` — seeded by the installer or fetched from GitHub (`Fetch / update DXVK` / `scripts\Fetch-Dxvk.ps1`). + +## Changes + +- `AppSettings.EnableDxvk` (default **false**). +- `DxvkPackageService` — cache, apply/remove with preexisting park, GitHub latest fetch (x32 only). +- `AcClientLaunchSettingsService.Apply` — applies DXVK with intro/multi-client settings. +- Launcher UI: checkbox + Fetch button + cache status line. +- `scripts\Fetch-Dxvk.ps1` — CLI/installer seed helper. +- `Build-Installer.ps1` — stages `Runtime\dxvk` into the core payload. +- Docs: `docs/DXVK_TEXTURE_SMOKE.md` updated for launcher path. + +## Notes + +- Engine `DxvkDetection` (2026.10.16.13) already forces software overlay textures when DXVK is active. +- Toggle requires **AC relaunch** to pick up / drop the drop-in DLL. +- Does not push to remotes; hot-publish launcher separately when ready. + +## Version + +- Launcher HandWritten / Assembly: **0.1.8** (from 0.1.7). diff --git a/Changelog/2026-10-16-launcher-scroll-clip-server-list-0.1.9.md b/Changelog/2026-10-16-launcher-scroll-clip-server-list-0.1.9.md new file mode 100644 index 0000000..efceacc --- /dev/null +++ b/Changelog/2026-10-16-launcher-scroll-clip-server-list-0.1.9.md @@ -0,0 +1,24 @@ +# Launcher 0.1.9 — Launch Targets / Updates no longer clipped off-screen + +## Summary + +The Launcher tab looked like it had “lost” the server / launch-target list: Updates and Launch Targets were laid out above the visible clip and could not be scrolled back into view. Saved `appsettings.json` profiles were fine (still 5 servers / 7 accounts); only the UI scroll layout was wrong. + +## Cause + +Server Profiles and Account Profiles used a Grid `*` row inside the outer `ScrollViewer` → `StackPanel`. With infinite height available, that star row expanded incorrectly and pushed the cards above (Updates, Launch Targets) out of reach. + +## Fix + +- Server / Account profile grids: `Auto,Auto,*,Auto` → `Auto,Auto,Auto,Auto` with `MaxHeight="280"` on the ListBoxes so the outer scroll owns the page. +- Name the Launcher `ScrollViewer` and reset `Offset` to top on window open and when re-selecting the Launcher tab. + +## Version + +- Launcher HandWritten / Assembly: **0.1.9** (from 0.1.8). +- Hot ProductVersion when publishing: next stamp above live tip (e.g. `2026.10.16.16` if engine is `.15`). + +## Notes + +- Does not change `appsettings.json`. Restart the launcher to pick up the fix. +- No push / Games install until asked. diff --git a/Changelog/2026-10-16-miniremote-dock-undock-2026.10.16.11.md b/Changelog/2026-10-16-miniremote-dock-undock-2026.10.16.11.md new file mode 100644 index 0000000..2a04f8e --- /dev/null +++ b/Changelog/2026-10-16-miniremote-dock-undock-2026.10.16.11.md @@ -0,0 +1,25 @@ +# 2026.10.16.11 - Mini Remote: dock / undock / open undocked + +## Why + +Mini Remote already had the host title ↗/↙ pop-out, but there was no clear way to +open it undocked or toggle dock from Char / Options / chat. Undocked is the +comfortable place for the expanded Mini Remote Options (sections, layout, slot size). + +## Changes + +- `/rc miniremote undock` (aliases: `popout`, `float`): open on Remote and pop out. +- `/rc miniremote dock` (alias: `redock`): dock back, or open docked if closed. +- Char right-click menu: **Mini Remote (undocked)**. +- Mini Remote sections menu: **Undock Mini Remote** / **Dock Mini Remote**. +- Helpers: `MiniRemoteFace.OpenUndocked` / `DockOrOpen`. + +Paired with RynthAi: Float/Dock beside Options; undocked Options left-click opens +the expanded section popup. + +## Files + +- `Compatibility/RynthCoreChatCommands.cs` +- `ImGui/Panels/MiniRemoteFace.cs` +- `ImGui/Panels/MiniRemoteFace.Sections.cs` +- `ImGui/Panels/RynthAiFace.cs` diff --git a/Changelog/2026-10-16-miniremote-rail-off-orphan-2026.10.15.9.md b/Changelog/2026-10-16-miniremote-rail-off-orphan-2026.10.15.9.md new file mode 100644 index 0000000..d2e2fc3 --- /dev/null +++ b/Changelog/2026-10-16-miniremote-rail-off-orphan-2026.10.15.9.md @@ -0,0 +1,18 @@ +# 2026.10.15.9 - Mini Remote: rail-off no longer orphans Crafting/sections + +Previous: 2026.10.15.8. + +## Fix + +Undocked (and docked) Mini Remote could show only Crafting's Armor/Weapons/Jewelry +tabs with no Remote stats and no Gear/Games/Vaulted hub bar: the window was on a +non-Remote section with the sections rail hidden, so the hub tab bar never drew. + +- Hiding the rail snaps back to Remote (restores miniremote-window tab bar). +- Picking a non-Remote section while the rail is off turns the rail back on. +- Draw safety: rail-off + non-Remote forces Remote. + +## Files + +- ImGui/Panels/MiniRemoteFace.cs +- ImGui/Panels/MiniRemoteFace.Sections.cs diff --git a/Changelog/2026-10-16-oracle-skills-embed-2026.10.16.1.md b/Changelog/2026-10-16-oracle-skills-embed-2026.10.16.1.md new file mode 100644 index 0000000..0a6d855 --- /dev/null +++ b/Changelog/2026-10-16-oracle-skills-embed-2026.10.16.1.md @@ -0,0 +1,31 @@ +# 2026.10.16.1 - Skills under Oracle; buffing prots/banes UI removed + +Previous: 2026.10.15.9. Major feature (new Oracle surface). + +## Skills → Oracle + +The standalone Skills panel body (raise / train / attributes / ILT progression) +now embeds inside RynthOracle as three tabs: + +- **Skills** — raise and train (`/ro skills`, `/rc skills`) +- **Attributes** — attributes and vitals (`/ro attrs`) +- **Progress** — ILT progression planners (`/ro progress`, `/rc progression`) + +Engine bridge: `OracleSkillsEmbed` + `ScriptWindowFace` draws `SkillsFace` after +the Oracle tab strip when `/rc oracle-skills <0|1|2|off>` is set. The Skills bar +button is removed; Character / Mini Remote menus open Oracle instead. Standalone +Skills remains as a fallback when Oracle is not loaded. + +## Files (Core) + +- `ImGui/Panels/OracleSkillsEmbed.cs` (new) +- `ImGui/Panels/SkillsFace.cs` — `DrawEmbedded` / hosted body +- `ImGui/Panels/ScriptWindowFace.cs` — Oracle embed draw + clear on hide +- `ImGui/ImGuiBar.cs` — drop Skills bar button +- `ImGui/Panels/RynthAiFace.cs` — Character menu → `/ro skills|attrs|progress` +- `Compatibility/RynthCoreChatCommands.cs` — `/rc oracle-skills`, retarget skills/progression + +## Deploy + +`Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.1')` +→ `C:\Games\RynthCore\Runtime\`. Matching Suite plugins stamp the same calver. diff --git a/Changelog/2026-10-16-oracle-skills-embed-into-local-2026.10.16.14.md b/Changelog/2026-10-16-oracle-skills-embed-into-local-2026.10.16.14.md new file mode 100644 index 0000000..581351e --- /dev/null +++ b/Changelog/2026-10-16-oracle-skills-embed-into-local-2026.10.16.14.md @@ -0,0 +1,35 @@ +# 2026.10.16.14 — Oracle Skills embed into local Engine (fix Skills bar / ILT bridge) + +**Previous:** 2026.10.16.13 (DXVK smoke). Hot push. + +## What was wrong + +Games was mixed: + +- **RynthOracle 0.3.1** (sk) expects `/rc oracle-skills` and embeds Skills / Attributes / Progress inside Oracle. +- **Engine 2026.10.16.13** (local) still had the **Skills top-bar button** and **no** `oracle-skills` bridge → log: `unknown subcommand '/rc oracle-skills 2'`. +- Oracle Character charms / Pet Breeding read `RynthILT.Data` only while those tabs are open; Progress planners also need the embed + RynthILT. Without the bridge, Oracle looked “empty” of ILT skill/progress UI. + +## Fix (local Engine, DXVK kept) + +Port from sk `ae6de53`: + +- `OracleSkillsEmbed.cs` + `/rc oracle-skills` +- `SkillsFace.DrawEmbedded` / hosted body +- `ScriptWindowFace` draws embed for `RynthOracle/Oracle` +- Remove Skills (and Item Count / Mini Remote) from `ImGuiBar` +- Char menu → `/ro skills|attrs|progress` +- **Inventory title bar / modern header:** Count, GInv, Sort, Remote buttons + (bar removal left them nowhere until this port) +- **Radar → RynthNav:** removed from ImGui/DComp top bar; RynthNav header + Radar toggle + `/rc radar` + Char menu; OverlayHost/RadarFace/snapshot/ + settings/`/rc ui open Radar` unchanged +- **Chat combat standard filters:** port sk `2026.10.16.2` / `.10` presets + (`ChatFilterPresets` + `RynthChatPresets`) so Combat Standard filters + (melee/magic deal/take, recklessness, sneak, stamina, etc.) show in + Chat Filters again — live Engine 13 still had the short Combat list + +## Deploy + +`Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.14')` +→ `C:\Games\RynthCore\Runtime\`, then reinject / relog. diff --git a/Changelog/2026-10-16-plugin-chat-queue-depth-2026.10.16.20.md b/Changelog/2026-10-16-plugin-chat-queue-depth-2026.10.16.20.md new file mode 100644 index 0000000..a5922bb --- /dev/null +++ b/Changelog/2026-10-16-plugin-chat-queue-depth-2026.10.16.20.md @@ -0,0 +1,21 @@ +# 2026.10.16.20 — Plugin chat queue keeps long server replies + +**Kind:** Hot push (Engine). + +## Problem + +Incoming chat waits in a queue until the plugin pump hands it to the plugins. The queue held +256 lines and silently dropped the oldest. A `/myquests` reply (one line per quest flag, +often several hundred) arriving while the pump was slow lost its head, so RynthOracle's +second quest refresh in a session came back mostly empty. + +## Fix + +- `PluginManager.MaxPendingIncomingChats` 256 → 4096. +- Dropped lines are counted and logged at most every 10 s + (`PluginManager: N incoming chat line(s) dropped before plugins heard them`). + +## Deploy + +Engine change: install with all AC clients closed (or relog after the installer). Don't +hot-copy `RynthCore.Engine.dll` into a running `Runtime\`. diff --git a/Changelog/2026-10-16-popout-keep-floating-pos-2026.10.16.12.md b/Changelog/2026-10-16-popout-keep-floating-pos-2026.10.16.12.md new file mode 100644 index 0000000..fa53329 --- /dev/null +++ b/Changelog/2026-10-16-popout-keep-floating-pos-2026.10.16.12.md @@ -0,0 +1,20 @@ +# 2026.10.16.12 - Pop-out HUDs keep their floating screen position after redock + +## Why + +Float a panel (Mini Remote, RynthAi, …), move it, dock it, then float again: it +came back over the docked client spot instead of the last floating screen +position. `panel_state.txt` still held `FloatingLeft`/`FloatingTop` after redock +(`Floating=false`), but `StartPopOut` only restored those coords when +`fromSaved || Floating` — a manual Float after Dock skipped them, then +`PersistPopped` overwrote the saved floating spot with the docked-derived one. + +## Fix + +`ImGuiPanelHost.StartPopOut`: restore the last floating screen coords whenever +they exist (or the panel is still marked floating / reopen-from-saved), not only +when `Floating` is still true. + +## Files + +- `ImGui/ImGuiPanelHost.cs` diff --git a/Changelog/2026-10-16-port-sk-engine-work-2026.10.16.22.md b/Changelog/2026-10-16-port-sk-engine-work-2026.10.16.22.md new file mode 100644 index 0000000..f7b08a7 --- /dev/null +++ b/Changelog/2026-10-16-port-sk-engine-work-2026.10.16.22.md @@ -0,0 +1,25 @@ +# 2026.10.16.22 — sk-only engine work from 10-16 ported onto the test build + +**Kind:** Hot push (Engine). Cherry-pick of sk `ae6de53` onto `test/hotbuild-2026-10-16`. + +## Brought over + +- **In-world hot-reload hold** (`ReloadInWorldGate` + `tools/ReloadInWorldGateTests`): a + FileWatcher engine reload waits until logout / character select instead of tearing the engine + down mid-play; a manual ERl / RL / `/rc rl` in-world is held the same way (it applies on + logout). Needs loader 2.2 (`RynthCoreMayHotReload`; the installer builds it). `engine.json` + `AllowInWorldAutoHotReload: true` restores the old behaviour. Tonight's engine hot-copy crash + at 17:11 happened on a build without it. +- Progress tab Enlightenment calculator (`SkillsFace.Progression`, `ProgressionData`). +- Chat: combat standard filters and UBIT parity. +- Inventory: Item Count / GInv / RSort buttons, Mini Remote and GInv off the top bar. +- Loader/EntryPoint/settings changes the hold needs (`EngineSettings`, `Loader.c`). + +## Kept from the test build + +The Sense-under-RynthNav / Oracle companion strip bar layout and the Skills embed structure; +`SkillsFace.RequestTab` taken from sk (its chat command uses it). + +## Checks + +Engine builds; ReloadInWorldGateTests 14/14, EngineSettingsTests pass (213 assertions). diff --git a/Changelog/2026-10-16-progress-enl-calculator-2026.10.16.9.md b/Changelog/2026-10-16-progress-enl-calculator-2026.10.16.9.md new file mode 100644 index 0000000..dbe857b --- /dev/null +++ b/Changelog/2026-10-16-progress-enl-calculator-2026.10.16.9.md @@ -0,0 +1,18 @@ +# 2026.10.16.9 - Skills Progression: Enl calculator UI + +Previous: 2026.10.16.8. + +## Change + +Enlightenment on the Skills Progression tab now draws the ILT Enl calculator: +per-level cost rows (green while pack + character luminance cover the step), +still-need / have materials, and the 301–325 sigil craft chain. DTOs match +RynthILT's `AppendEnlCalculatorJson` (`levels`, `materials`, `chain`, ecoins). + +Augmentations already show character AvailableLuminance (not banked) via ILT's +`banked` summary line; this build only wires the Enl planner UI. + +## Files + +- UI/Data/ProgressionData.cs +- ImGui/Panels/SkillsFace.Progression.cs diff --git a/Changelog/2026-10-16-runtime-borderless-display-2026.10.5.70.md b/Changelog/2026-10-16-runtime-borderless-display-2026.10.5.70.md new file mode 100644 index 0000000..ac94694 --- /dev/null +++ b/Changelog/2026-10-16-runtime-borderless-display-2026.10.5.70.md @@ -0,0 +1,26 @@ +# 2026.10.5.70 - CoreCLR Runtime deploy: Settings > Display borderless / layout + +Previous release: 2026.10.5.69. + +## Why you could not see them + +Live clients load the engine from `C:\Games\RynthCore\Runtime\` (CoreCLR host), +not the NativeAOT `C:\Games\RynthCore\RynthCore.Engine.dll`. Earlier hotbuilds +only updated the AOT copy. Runtime was still **2026.10.15.7**, which had no +**Borderless Windowed**, **Remember Open Windows and Positions**, or **Save Layout Now**. + +## Fix + +Published the local engine as CoreCLR (`-p:EngineHost=coreclr`) and copied it to +`Runtime\RynthCore.Engine.dll` as **2026.10.5.70**, including the Display rows from +2026.10.5.65–.67. + +## Where to look + +**Settings > Display** (Advanced Settings > Display): + +- Borderless Windowed +- Remember Open Windows and Positions +- Save Layout Now + +Hot reload should pick up the new Runtime DLL; otherwise reinject. diff --git a/Changelog/2026-10-16-sense-rnav-vision-tracker-oracle-2026.10.16.16.md b/Changelog/2026-10-16-sense-rnav-vision-tracker-oracle-2026.10.16.16.md new file mode 100644 index 0000000..674f7fc --- /dev/null +++ b/Changelog/2026-10-16-sense-rnav-vision-tracker-oracle-2026.10.16.16.md @@ -0,0 +1,41 @@ +# 2026.10.16.16 — Sense → RynthNav; Vision / Tracker / ILT → Oracle + +**Previous:** 2026.10.16.15 (test-merge install). Hot push. + +## Summary + +Same pattern as Radar → RynthNav: remove top-bar icons, keep every open path +(`PanelRouter`, OverlayHost, `/rc …`, Char menu), and put header toggles on the +host panel. + +## Moves + +| Panel / icon | Was | Now | +|---|---|---| +| **Sense** | ImGui-only bar button | RynthNav header (with Radar / Mini / Map) + `/rc sense` | +| **Vision** | OverlayHost bar button | Oracle companion strip (above Oracle tabs) | +| **Tracker** | OverlayHost bar button | Oracle companion strip | +| **ILT leaf** (Bounties / Guardian) | Top-bar leaf button | Oracle companion strip (leaf + menu) | + +## Linkages kept + +- `PanelRouter.Toggle` / `/rc ui open …` / panel restore / Avalonia faces +- `/rc sense`, `/rc radar` unchanged +- Char menu: Sense under Nav family; Vision / Tracker / Bounties / Guardian listed +- Oracle Skills embed and Oracle bar button unchanged (Oracle stays on the bar) + +## Files + +- `ImGuiBar.cs` — LauncherOnly + Sense off ImGuiOnlyBarPanels; ILT leaf off bar +- `RynthNavFace.cs` — Sense header toggle +- `OracleCompanionStrip.cs` + `ScriptWindowFace.cs` — Vision / Tracker / ILT strip +- `RynthAiFace.cs` — Char menu entries + +## Note + +Engine hot-reload of this build crashed one client at 2026-10-16 17:11 (FileWatcher → +Engine.dll). Prefer a full relog over mid-session Engine copy when testing. + +## Deploy + +`dotnet publish` Engine `-p:Version=2026.10.16.16` → `C:\Games\RynthCore\Runtime\` diff --git a/Changelog/2026-10-16-test-build-full-install-2026.10.16.24.md b/Changelog/2026-10-16-test-build-full-install-2026.10.16.24.md new file mode 100644 index 0000000..ad83f09 --- /dev/null +++ b/Changelog/2026-10-16-test-build-full-install-2026.10.16.24.md @@ -0,0 +1,18 @@ +# 2026.10.16.24 — test build full install + +**Kind:** Hot push (test build installer). Previous installer `2026.10.16.22`. + +Built from `test/hotbuild-2026-10-16-on-aelrynth` (Core + Suite, current `aelrynth/main` merged in). + +## New since 2026.10.16.22 + +- **Chat:** Hide rules and standard filters keep lines out of AC's own chat window too + (option under Standard filters, on by default); clients re-read the shared + `rynthchat_settings.json` when another client saves it. +- **RynthILT 0.2.16:** follows RynthCore's server verdict again, so RynthAi's Mini Remote ILT + tabs use the engine's Active flag and the character override (`/rc server ilt on|off|auto`); + Vaulted Dungeons settings load and save in the NativeAOT build. + +## Install + +Close every AC client first (the loader and engine are replaced). diff --git a/Changelog/2026-10-16-test-hotbuild-installer-2026.10.16.18.md b/Changelog/2026-10-16-test-hotbuild-installer-2026.10.16.18.md new file mode 100644 index 0000000..6531879 --- /dev/null +++ b/Changelog/2026-10-16-test-hotbuild-installer-2026.10.16.18.md @@ -0,0 +1,21 @@ +# 2026.10.16.18 — test/hotbuild-2026-10-16 installer + +**Kind:** Hot push (test branch installer). Previous live tip `2026.10.16.17` (launcher/Ai/ILT/Oracle); Engine Games tip was `2026.10.16.16`. + +## Sources + +| Repo | Branch | Tip (at package time) | +|---|---|---| +| RynthCore | `test/hotbuild-2026-10-16` | Sense→RynthNav / Vision·Tracker·ILT→Oracle strip; launcher 0.1.9 scroll/DXVK | +| RynthSuite | `test/hotbuild-2026-10-16` | Ai 0.5.80 Handler evade + pet 45s; ILT 0.2.15 aug Refresh; Oracle 0.3.2 Fellowship | + +## Highlights + +- DXVK detect + launcher Enable DXVK toggle; server-list ScrollViewer fix (0.1.9) +- Oracle Skills embed; Sense off top bar into RynthNav; Vision/Tracker/ILT leaf into Oracle companion strip +- PullAway kite; Empyrean Handler lethal-ring back-jump evade; PetDevice 45s cooldown +- Progress Augments Refresh current; Oracle Fellowship ILT `/fship` features + +## Note + +Engine hot-reload of the bar-move build crashed one client (2026-10-16 17:11). Prefer a full relog after install over mid-session Engine hot-copy. diff --git a/Changelog/2026-10-16-test-merge-aelrynth-hotbuild-2026.10.16.15.md b/Changelog/2026-10-16-test-merge-aelrynth-hotbuild-2026.10.16.15.md new file mode 100644 index 0000000..9541bbb --- /dev/null +++ b/Changelog/2026-10-16-test-merge-aelrynth-hotbuild-2026.10.16.15.md @@ -0,0 +1,27 @@ +# 2026.10.16.15 — Test merge: daily hotbuild onto aelrynth/main + +**Branch:** `test/hotbuild-2026-10-16-on-aelrynth` +**Base:** aelrynth `2026.10.15.6` (`a57049d`) + Suite `2026.10.15.7` +**Incoming:** `test/hotbuild-2026-10-16` (today’s Core + Suite work) + +## What + +Local install of the resolved merge for in-game validation: + +- DXVK detect / software overlay; launcher DXVK toggle +- Mini Remote dock/undock + Options +- Oracle Skills embed (`/rc oracle-skills`), Inventory Count/GInv, Radar→RynthNav +- Chat combat standard filters +- RynthAi 0.5.79 PullAway kite + +## Conflicts resolved (Core) + +- `DatFileShareHooks.cs` — keep scoped IAT + private CreateFileW (hotbuild) +- `EngineSettings.cs` — Borderless/Remember + MaxHotReloads default 20 (aelrynth) + +Suite merge was clean. + +## Deploy + +`Publish-EngineCoreClr.ps1 -EngineOnly -AllowBehind -MsBuildArgs @('-p:Version=2026.10.16.15')` +Ai publish with `-p:Version=2026.10.16.15` → `C:\Games\RynthSuite\RynthAi\` diff --git a/Changelog/2026-10-16-updater-local-ahead-of-feed-2026.10.16.19.md b/Changelog/2026-10-16-updater-local-ahead-of-feed-2026.10.16.19.md new file mode 100644 index 0000000..1cf01fd --- /dev/null +++ b/Changelog/2026-10-16-updater-local-ahead-of-feed-2026.10.16.19.md @@ -0,0 +1,25 @@ +# 2026.10.16.19 — Updater: local install ahead of published feed is not an error + +**Kind:** Hot push (test branch + on-aelrynth merge rebuild). + +## Problem + +After installing a local test build (`2026.10.16.18`) newer than the public update +feed (`2026.10.15.7`), **Check for updates** showed **Couldn't check for updates**: +`the feed is older (2026101507) than one already seen (2026101618)`. + +## Cause + +The replay floor used `max(highestSeenFeed, InstalledCoreRelease)`. A local/test +`release.txt` ahead of the signed feed made every legitimate older feed look like a +replay attack. + +## Fix + +Replay guard uses only the highest *feed* already accepted. A local install ahead of +the published feed still checks successfully (no core update offered). + +## Also + +Installer rebuilt from `test/hotbuild-*-on-aelrynth` (test branch merged onto current +`aelrynth/main`), not from the divergent daily test tip alone. diff --git a/Changelog/2026-10-17-borderless-fill-monitor-2026.10.17.4.md b/Changelog/2026-10-17-borderless-fill-monitor-2026.10.17.4.md new file mode 100644 index 0000000..da559a9 --- /dev/null +++ b/Changelog/2026-10-17-borderless-fill-monitor-2026.10.17.4.md @@ -0,0 +1,34 @@ +# 2026.10.17.4 — Borderless windowed fills the monitor; `/rc window reset` + +**Kind:** Hot push (Engine). Previous `2026.10.17.3`. + +## Problem + +With Settings > Display > Borderless Windowed on (seen together with DXVK), the game sat at a +smaller resolution than the screen with no way to resize it. + +## Cause + +Borderless only removed the window frame (caption, sizing border, maximize box) and kept the +window at AC's resolution (for example 1760x990 on a 1920x1080 monitor). With no border to drag and +no maximize, nothing could make it bigger. AC also re-sizes its window to its own resolution after +a device reset, which DXVK triggers, so the window could shrink again later. Remember layout then +saved that frame-less rect as the window placement. + +## Fix + +- Borderless on now fills the monitor the window is on (borderless fullscreen). It remembers the + framed size and position first. +- If AC shrinks the borderless window again, it is stretched back to fill the monitor, up to 4 + times a minute. After that it is left alone, with a log line pointing at `/rc window reset`. +- Borderless off puts the frame back at the remembered size. With nothing remembered (after a hot + reload) the window comes back at three quarters of the monitor, centred and resizable. +- Remember layout no longer saves the window rect while it is frame-less, and it doesn't restore + a saved rect when borderless is on. +- New `/rc window reset` turns borderless off and gives a normal, framed, resizable window, + centred. New `/rc borderless on|off` does the same as the Settings toggle. + +## Files + +- `src/RynthCore.Engine/UI/AcWindowChrome.cs` +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs` diff --git a/Changelog/2026-10-17-chat-coord-links-arrow-clear-2026.10.17.2.md b/Changelog/2026-10-17-chat-coord-links-arrow-clear-2026.10.17.2.md new file mode 100644 index 0000000..1a5c268 --- /dev/null +++ b/Changelog/2026-10-17-chat-coord-links-arrow-clear-2026.10.17.2.md @@ -0,0 +1,31 @@ +# 2026.10.17.2 — Click coordinates in chat for RynthNav's arrow; Clear on the arrow + +**Kind:** Feature (Engine). Previous `2026.10.16.24`. + +## What + +- **Coordinates in RynthChat are links.** Any map coordinate in a chat line — the game's, + someone's tell, or one you pasted (`82.3n,34.2e`, `42.1N 33.6E`, `33.6E, 42.1N`) — is drawn + underlined in teal. Hover for the hand cursor and a tooltip. + - **Click:** RynthNav's floating arrow points there (its overlay opens: direction relative to + the way you face, distance, compass point; green within 30 yd). + - **Ctrl+click:** RynthNav walks there (portals and recalls when its routing is on). + - Right-click still has the line menu ("Arrow to" / "Go to" and the rule options); a drag still + selects and copies lines. +- **Clear on the arrow overlay** (eraser, top right): clears the target (`/rnav arrow clear`), + stops a walk to it, and hides the overlay. +- **The overlay closes itself** about 4 s after its target goes away — you arrived (RynthNav + counts 10 yd as arrived; `/rnav arrive <yd>` changes it) or it was cleared elsewhere. It shows + "Done: <target>" meanwhile. Opened empty to type coordinates, it stays open. +- Go (▶) on the overlay remains the "auto-nav to it" button; Plan shows the route first. + +## Notes + +- Needs the RynthNav plugin; without it the links say so instead of pointing anywhere. +- Coordinates are found when a line is measured (never per frame), with a cheap pre-check before + the parser. +- AC's own (retail) chat window can't be clicked; the links are in RynthChat. + +## Checks + +Engine builds; ChatCoordTests 49/49 (adds the lowercase / no-space forms). diff --git a/Changelog/2026-10-17-engine-settings-multiclient-2026.10.17.3.md b/Changelog/2026-10-17-engine-settings-multiclient-2026.10.17.3.md new file mode 100644 index 0000000..37214f9 --- /dev/null +++ b/Changelog/2026-10-17-engine-settings-multiclient-2026.10.17.3.md @@ -0,0 +1,27 @@ +# 2026.10.17.3 — In-game engine settings no longer reset by other clients + +**Kind:** Hot push (Engine). Previous `2026.10.17.2`. + +## Problem + +Engine options set in game (Settings > Display: borderless, remember layout; UI hooks, ImGui, +Auto-ID mode, close on disconnect, ILT names, plugin list) came back reset, notably after relaunching +clients for a DXVK change. + +## Cause + +Every client keeps the whole `%AppData%\RynthCore\engine.json` state in memory and, on any save, +wrote all of the engine's keys back from it. A client that never touched a setting put its stale +value over another client's change — last writer won. Relaunching some clients (DXVK on/off) while +others kept running made it show. (RynthChat had the same flaw; fixed in 2026.10.16.23.) + +## Fix + +The engine tracks which of its keys this client changed this session and writes only those; +every other key keeps what the file holds (`EngineSettingsFile.Merge` `changedKeys`). The launcher's +keys were already kept. + +## Checks + +EngineSettingsTests 224/224, including a two-client case: another client's change survives this +client saving a different setting. diff --git a/Changelog/2026-10-17-graphics-per-account-no-fight-2026.10.18.3.md b/Changelog/2026-10-17-graphics-per-account-no-fight-2026.10.18.3.md new file mode 100644 index 0000000..b0d695e --- /dev/null +++ b/Changelog/2026-10-17-graphics-per-account-no-fight-2026.10.18.3.md @@ -0,0 +1,55 @@ +# 2026.10.18.3 — Graphics profiles per account; the window never fights AC's resolution + +**Kind:** Hot push (Engine + Launcher). Previous `2026.10.18.2`. + +## Problem + +After the resolution was changed in AC's own settings, clients fought RynthAi's Graphics settings: +windows came back the wrong size, and clients sat in portal space. Every client shared the one +Settings > Graphics set (`graphics.json`). + +## Cause + +- The window was sized for the Resolution saved in RynthAi's Graphics settings, not for the + resolution AC was actually drawing at. After a change in AC's own options, the two disagreed and + RynthCore pushed the window back at every login. +- The size also came out 10 px too big each way (1770x1000 for 1760x990). It was worked out for a + resizable frame, but AC's window has a fixed one. +- Every client edited one shared set, and every client wrote it into the shared + `UserPreferences.ini` on each change. So one client's values landed on all the others. + +## Fix + +- **The window follows what AC really draws.** The engine samples AC's back-buffer size about once a + second and logs any change. Window sizing uses it, falling back to the resolution AC launched + with. This covers restoring at login, Reset Window Borders, turning borderless off, and + borderless at resolution size. The frame is taken from the window's real style, so a framed + window's game area is exactly AC's resolution. +- **A profile per account:** + - `graphics.json` holds a profile per `server|account`. Settings > Graphics edits only this + client's account, and each save re-reads the file so other accounts' entries are kept. + - The launcher writes the launching account's profile into `UserPreferences.ini` just before + it starts that account, under the prefs lock whenever any profile exists. + - The per-character rows are gone; the account profile replaces them. +- **Clients no longer write the shared INI on every change.** Only the launcher and the "Write to + AC's settings now" button do. +- Live changes are limited to the window mode, which is RynthCore's own window frame. Resolution and + every render setting apply at the next launch. +- The 2026.10.18.1 shared `graphics.json` is ignored. On this PC it was backed up to + `graphics.json.shared-2026.10.18.1.bak` and replaced with an empty per-account file. + +## Files + +- `src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs`: `AcGraphicsProfiles` and `AccountKey`. +- `src/RynthCore.Engine/Graphics/AcGraphics.cs`: account profile, draw size, no INI writes on edit. +- `src/RynthCore.Engine/ImGui/DX9Backend.cs`: `TryGetBackBufferSize`. +- `src/RynthCore.Engine/D3D9/EndSceneHook.cs`: samples the back buffer. +- `src/RynthCore.Engine/UI/AcWindowChrome.cs`: draw-size sizing; the real frame style. +- `src/RynthCore.Engine/UI/Data/SettingsData.cs`: per-account Graphics tab. +- `src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs`: comment only. +- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs`: launcher applies the account's profile. +- `tools/AcGraphicsPrefsTests`: 53 checks, per-account. + +## Checks + +Engine and launcher build clean; AcGraphicsPrefsTests 53/53. diff --git a/Changelog/2026-10-17-graphics-settings-panel-2026.10.18.1.md b/Changelog/2026-10-17-graphics-settings-panel-2026.10.18.1.md new file mode 100644 index 0000000..c4b4c75 --- /dev/null +++ b/Changelog/2026-10-17-graphics-settings-panel-2026.10.18.1.md @@ -0,0 +1,90 @@ +# 2026.10.18.1 — Settings > Graphics: AC's graphics options in RynthAi, enforced every launch + +**Kind:** Major feature (Engine + Launcher). Previous `2026.10.17.8`. + +## Asked for + +- Resetting the window size didn't respect AC's resolution setting. +- A graphics settings panel inside RynthAi's settings that covers everything on AC's own + graphics pages, and that RynthAi enforces whether the client is windowed, full screen, + framed or borderless. + +## New: Settings > Graphics (after Display) + +- **Window** + - **Window mode:** Windowed, Borderless (fill the monitor), Borderless (resolution size), or + Full screen (exclusive). + - **Resolution:** the monitor's modes. + - **Refresh rate:** Auto or a number of Hz. + - **Sync to display refresh.** +- **This character:** its own window mode and resolution. These win over the global ones, and the + launcher uses them when it starts that character. +- **Graphics:** every Render option from AC's own Graphics page: + - landscape and scenery draw distance; + - landscape and environment texture detail; + - texture filtering; + - landscape and building detail textures; + - multi-pass alpha; + - field of view; + - screen brightness; + - aspect ratio; + - adaptive degrade, degrade bias and degrade distance. +- Every setting starts on **AC's choice**, which means RynthAi doesn't touch it. +- **Write to AC's settings now** and **Reset all to AC's choice** buttons. +- The value lists come from `acclient.exe` itself: VeryLow…Extreme; Bilinear, Trilinear, Sharp + and Anisotropic; Normal and Wide. + +## How it is enforced + +- The settings are kept in `%APPDATA%\RynthCore\graphics.json`, shared by every client on the PC. + Clients pick up each other's edits within a few seconds. +- AC reads `UserPreferences.ini` only at startup and rewrites it itself. So the launcher writes + RynthAi's values into it just before every client starts, after any per-account prefs swap, so + RynthAi's values win. +- The engine also writes it when a setting changes. +- Both write the game folder's `UserPreferences.ini` (which this install's clients actually use) + and `Documents\Asheron's Call\UserPreferences.ini` when it exists. +- When per-character resolutions or window modes exist, launches take the prefs lock, so two + clients starting together each read their own values. + +## Window sizing follows the resolution + +- The window's size always comes from AC's resolution: Settings > Graphics, else what AC started + with. Only the window's position is remembered. This covers: + - restoring the window at launch; + - Reset Window Borders and `/rc window reset` (centred, the resolution's size plus the frame); + - turning borderless off; + - Borderless (resolution size). +- This also ends the "client starts small" class of bugs: a size saved at another resolution, or + at the login screen, can no longer shrink the window. +- Changing the window mode or resolution in the panel changes the window at once. AC draws at a + new resolution, and starts exclusive full screen, from the next launch. +- The Display toggles (Borderless Windowed, Borderless Fills Monitor, `/rc borderless`, + `/rc window fill`) still work. Using them hands the global window mode back to them. + +## Files + +- `src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs` (new): the model, `graphics.json`, and INI + editing. Shared with the launcher. +- `src/RynthCore.Engine/Graphics/AcGraphics.cs` (new): the engine side. Effective values, edits, + coalesced background writes, display mode lists. +- `src/RynthCore.Engine/UI/AcWindowChrome.cs`: resolution-based sizing; `ApplyGraphicsChanged`. +- `src/RynthCore.Engine/UI/Data/SettingsData.cs`: the Graphics tab; the Display toggles hand the + mode back. +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs`: `/rc borderless` and + `/rc window fill` hand the mode back. +- `src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs`: `ReadLaunchContext` is internal. +- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs` and `RynthCore.App.Avalonia.csproj`: apply + graphics before each launch, and the lock. +- `tools/AcGraphicsPrefsTests` (new): 52 checks. + +## Checks + +- Engine and launcher build clean. +- AcGraphicsPrefsTests 52/52: overrides, the FullScreen mapping, the JSON round-trip, in-place + INI edits, and no write when nothing changed. + +## Note + +The launcher half ships with the next installer. Until then the engine writes the INI when a +setting changes, but AC can overwrite it when the client exits. diff --git a/Changelog/2026-10-17-launcher-prefs-swap-live-ini-2026.10.18.2.md b/Changelog/2026-10-17-launcher-prefs-swap-live-ini-2026.10.18.2.md new file mode 100644 index 0000000..ef03e11 --- /dev/null +++ b/Changelog/2026-10-17-launcher-prefs-swap-live-ini-2026.10.18.2.md @@ -0,0 +1,35 @@ +# 2026.10.18.2 — Launcher: per-account prefs swap uses the UserPreferences.ini AC actually reads + +**Kind:** Hot push (Launcher). Previous `2026.10.18.1`. + +## Problem + +The launcher's per-account UserPreferences.ini swap, the multi-client flag (`ComputeUniquePort`), +the end-of-session snapshot, and the account dialog's Snapshot button all used +`Documents\Asheron's Call\UserPreferences.ini`. On this install AC reads and writes the copy in +the game folder: `C:\Turbine\Asheron's Call-ryn\UserPreferences.ini` changed every session, while +the Documents copy hadn't changed since April. So the per-account settings were swapped into a +file AC never read, and the snapshot saved a stale copy. + +## Fix + +- `AcClientLaunchSettingsService.LivePrefsPath(acclient path)`: the game folder's + `UserPreferences.ini` when it exists, else the Documents one. +- Used by: + - the swap, whose recovery undoes the same file it swapped; + - the end-of-session snapshot; + - the account dialog's Snapshot button. +- `ComputeUniquePort` is set in every copy that exists. +- Settings > Graphics (2026.10.18.1) already writes both copies; its tests now also check the + game folder's file comes first (AcGraphicsPrefsTests 55/55). + +## Files + +- `src/RynthCore.App/AcClientLaunchSettingsService.cs` +- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs` +- `src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs` +- `tools/AcGraphicsPrefsTests/Program.cs` + +## Checks + +Launcher builds clean; LauncherSettingsTests 163/163; AcGraphicsPrefsTests 55/55. diff --git a/Changelog/2026-10-17-test-build-full-install-2026.10.17.6.md b/Changelog/2026-10-17-test-build-full-install-2026.10.17.6.md new file mode 100644 index 0000000..b4f1e85 --- /dev/null +++ b/Changelog/2026-10-17-test-build-full-install-2026.10.17.6.md @@ -0,0 +1,45 @@ +# 2026.10.17.6 — test build full install + +**Kind:** Hot push (test build installer). Previous installer `2026.10.16.24`. + +Built from `test/hotbuild-2026-10-16-on-aelrynth` (Core `b0fda86`, Suite `7877c86`), with rynth's +release `2026.10.17.1` (`aelrynth/main` Core `8330793`, Suite `c7807b6`) merged in. + +## New since 2026.10.16.24 + +- **Window (engine 2026.10.17.4 / .5):** + - Borderless windowed fills the monitor, so it no longer gets stuck small (DXVK). + - Settings > Display gains **Reset Window Borders**, **Save Window Position**, and **Borderless + Fills Monitor** (off keeps the framed window's size and spot). + - The borderless position is remembered across launches. + - New commands: `/rc window reset|save|fill on|off` and `/rc borderless on|off`. +- **Engine settings (2026.10.17.3):** `engine.json` saves only the keys a client changed, so other + clients (relaunched for DXVK) no longer reset in-game engine options. +- **Chat / RynthNav (2026.10.17.2):** coordinates in RynthChat (`82.3n, 34.2e`) are links. Click to + point RynthNav's arrow, Ctrl+click to go there. The arrow overlay has Clear and closes itself on + arrival. +- **RynthAi 0.5.82:** a profile that can't be read falls back to its `.bak`, or keeps the + unreadable file aside, instead of being overwritten with defaults. Saves are atomic. +- **RynthOracle 0.4.0:** Legendary quests tab (what you have, what's missing, time left). + +## From rynth's 2026.10.17.1 (upstream) + +- Hotkeys, Damage panel and Items panel updates; RynthAi buff One-Touch heal, weapon planner, + mana stones, and the action pacer. +- Monster rules gain **Prefer** (preferred damage kind) alongside this branch's **Power** and + **Kite**. The merge kept all three in the rule copy, the change check, the detail view and the + VTank import. + +## Checks + +- Engine and RynthAi build clean after the merge. +- HotkeyTests 924/924; EngineSettingsTests 226/226. +- RynthAiHostTests 1087/1089. The 2 known failures are unchanged: map bake needs the dats, and the + mini remote help line. + +## Install + +Close every AC client first (the loader and engine are replaced). + +- `installer\Output\RynthCore-Setup-2026.10.17.6.exe` +- `installer\Output\RynthCore-2026.10.17.6-deploy.zip` diff --git a/Changelog/2026-10-17-test-build-full-install-2026.10.18.13.md b/Changelog/2026-10-17-test-build-full-install-2026.10.18.13.md new file mode 100644 index 0000000..bee501f --- /dev/null +++ b/Changelog/2026-10-17-test-build-full-install-2026.10.18.13.md @@ -0,0 +1,44 @@ +# 2026.10.18.13 — test build full install + +**Kind:** Test build installer. The previous installer was `2026.10.18.4`. + +Built from `test/hotbuild-2026-10-16-on-aelrynth`: the test branch with `aelrynth/main` merged in. +Upstream had nothing newer than snapshot 2026.10.17.1, which was already in. + +The fork's `sk` branch isn't merged. Its commits are the standing pull request's copies of this +same test-branch work. + +## New since 2026.10.18.4 + +**Engine (2026.10.18.10–.11):** +- **The Add to loot profile popup** has an attribute checklist: every attribute of the item, grouped, with a comparison and a value for each. +- **Graphics:** a warning when Adaptive degrade is off with a far draw distance. A client nearly out of address space right after it starts turns Adaptive degrade back on for its account. + +**RynthAi (0.5.86–0.5.88):** +- **ub-IT `/ub` coverage:** every ub-IT `/ub` verb is mapped, or accepted as a no-op. ub-IT's missing expression functions are added. +- **Loot attributes:** the attribute checklist for all gear, pet essences, and cantrip tiers. +- **Fixes from the sample metas:** + - `vtsetsetting[]` takes VTank distances. Attack and approach ranges used to stay at 50 yd. + - New `/ub close corpse|chest` and `/ub <expression>`. + - `/vt deletemonster` is accepted. + - Pet range, blacklist, rebuff and AutoAttackPower options are mapped. + - `/mt face` and `/ub face` take decimals and coordinates, and hold nav while turning. + +**Other plugins:** +- **ub-Rythai 3.1.15:** ub-IT's `/ub periodic add|remove|toggle|list|clear`. It no longer replies to RynthAi's verbs. +- **RynthSort 0.3.3:** takes commands from other plugins (`/ub packsort`). + +## Checks + +- **Versions in the package:** the engine, launcher (`RynthCore.exe`), RynthAi, RynthSort and RynthOracle are stamped `2026.10.18.13`; ub-Rythai is `3.1.15`. +- **Tests:** + - RynthAiHostTests: 1080 passed; the 2 known failures are unchanged (the map bake needs the game data files; the mini remote help line). + - LootSdkTests: 8240 assertions, 0 failed. + - AcGraphicsPrefsTests: 62 checks pass. + +## Install + +Close every AC client and the launcher first. The launcher, loader and engine are replaced. + +- `installer\Output\RynthCore-Setup-2026.10.18.13.exe` +- `installer\Output\RynthCore-2026.10.18.13-deploy.zip` diff --git a/Changelog/2026-10-17-test-build-full-install-2026.10.18.2.md b/Changelog/2026-10-17-test-build-full-install-2026.10.18.2.md new file mode 100644 index 0000000..a838bef --- /dev/null +++ b/Changelog/2026-10-17-test-build-full-install-2026.10.18.2.md @@ -0,0 +1,37 @@ +# 2026.10.18.2 — test build full install + +**Kind:** Test build installer (major feature). Previous installer `2026.10.17.6`. + +Built from `test/hotbuild-2026-10-16-on-aelrynth`. `aelrynth/main` (rynth's 2026.10.17.1) is +merged in; nothing newer upstream. + +## New since 2026.10.17.6 + +- **Settings > Graphics (2026.10.18.1):** + - AC's graphics options inside RynthAi's settings: window mode, resolution, refresh rate, + vsync, and every option on AC's Graphics page. + - A per-character resolution and window mode. + - The launcher writes them into AC's `UserPreferences.ini` before every start, so they hold + whatever AC last saved. + - The window's size always follows the resolution; only its position is remembered. +- **Launcher (2026.10.18.2):** the per-account prefs swap, the multi-client flag, and the + snapshots use the `UserPreferences.ini` in the game folder, which is the one AC reads on this + install. +- **Window fixes (2026.10.17.7 and .8):** + - The window position saves safely with many clients. + - Restored windows are kept on-screen, so AC's toolbar can't be pushed off. + - AC's 800x600 login-screen size is never saved or restored, so clients no longer start small. + +## Checks + +- Engine and launcher build clean. +- AcGraphicsPrefsTests 55/55; LauncherSettingsTests 163/163. +- The staged engine contains the Graphics tab; the staged launcher contains the graphics apply + and the live-prefs path. + +## Install + +Close every AC client and the launcher first (the launcher, loader and engine are replaced). + +- `installer\Output\RynthCore-Setup-2026.10.18.2.exe` +- `installer\Output\RynthCore-2026.10.18.2-deploy.zip` diff --git a/Changelog/2026-10-17-test-build-full-install-2026.10.18.4.md b/Changelog/2026-10-17-test-build-full-install-2026.10.18.4.md new file mode 100644 index 0000000..a7a3ff0 --- /dev/null +++ b/Changelog/2026-10-17-test-build-full-install-2026.10.18.4.md @@ -0,0 +1,32 @@ +# 2026.10.18.4 — test build full install + +**Kind:** Test build installer. Previous installer `2026.10.18.2`. + +Built from `test/hotbuild-2026-10-16-on-aelrynth` with `aelrynth/main` merged in (nothing newer +upstream). + +## New since 2026.10.18.2 + +- **Graphics profiles per account (2026.10.18.3):** + - Settings > Graphics edits only this client's account. + - The launcher writes the launching account's profile into AC's `UserPreferences.ini` just before + it starts the account, one account at a time. + - The old shared `graphics.json` is ignored. +- **The window never fights AC's resolution:** + - It is sized for what AC really draws at: the back buffer, else the launch resolution. + - The frame comes from the window's real style, so the game area is exactly AC's resolution, not + 10 px bigger. + - Clients no longer write AC's shared INI on every change. + +## Checks + +- Engine and launcher build clean; AcGraphicsPrefsTests 53/53. +- The staged engine has the back-buffer reader and the per-account profiles; the staged launcher + has the per-account profiles and the live-prefs path. + +## Install + +Close every AC client and the launcher first (the launcher, loader and engine are replaced). + +- `installer\Output\RynthCore-Setup-2026.10.18.4.exe` +- `installer\Output\RynthCore-2026.10.18.4-deploy.zip` diff --git a/Changelog/2026-10-17-window-not-saved-at-login-size-2026.10.17.8.md b/Changelog/2026-10-17-window-not-saved-at-login-size-2026.10.17.8.md new file mode 100644 index 0000000..4b9a6ce --- /dev/null +++ b/Changelog/2026-10-17-window-not-saved-at-login-size-2026.10.17.8.md @@ -0,0 +1,34 @@ +# 2026.10.17.8 — Clients no longer start at AC's 800x600 login size + +**Kind:** Hot push (Engine). Previous `2026.10.17.7`. + +## Problem + +Silentkelpie (and Silentstorm) started in a small window. + +## Cause (from the 08:40–08:44 logs) + +- At the login and character-select screens AC shrinks its window to an 800x600 game area + (806x629 with the frame). The placement saver ran on those screens too, for example while a + client sat at character select for a held engine reload. It wrote 806x629 to the shared + `%LOCALAPPDATA%\RynthCore\ac_window.txt`. +- Every client then restored 806x629 after entering the world: "restored AC window to (557,208) + 806x629" for both Kelpie (pid 37756) and Storm (pid 41444). +- They looked different because of when the restore landed: + - Kelpie's came 10 s after entering the world, while AC was still applying its 1760x990 + resolution, so AC laid out its 3D view for the smaller window (viewport 1514x870). + - Storm's came 26 s in, after AC had finished, so its 1760x990 picture was only scaled into the + small window (viewport 1759x990). +- Storm's in-world 800x600 window was then saved again (08:44:43), so the bad size kept coming back. + +## Fix + +- The placement is saved only in the world, and never when the game area is 800x600. +- A saved framed rect with an 800x600 game area is ignored at restore (logged), and so is an + 800x600 borderless rect. AC keeps its own size, so the 806x629 already in the file no longer + shrinks anyone. +- Save Window Position says "not in the world" when it can't save. + +## Files + +- `src/RynthCore.Engine/UI/AcWindowChrome.cs` diff --git a/Changelog/2026-10-17-window-placement-shared-file-2026.10.17.7.md b/Changelog/2026-10-17-window-placement-shared-file-2026.10.17.7.md new file mode 100644 index 0000000..bb4b3c3 --- /dev/null +++ b/Changelog/2026-10-17-window-placement-shared-file-2026.10.17.7.md @@ -0,0 +1,43 @@ +# 2026.10.17.7 — AC window placement: safe with many clients, never off-screen + +**Kind:** Hot push (Engine). Previous `2026.10.17.6` (test installer). + +## Problem + +A tester's AC toolbar was missing: the bar with the panel buttons, indicators and shortcut bar. +Windows still opened from their keys. Nothing in RynthCore hides the toolbar: + +- The radar and chat hiders capture only those elements. +- The vitals hider captures only the two vitals bars. +- The power-bar hider does nothing. + +The toolbar is anchored to the AC window's bottom-right corner, so a window placed partly +off-screen hides it. + +## Cause + +- `%LOCALAPPDATA%\RynthCore\ac_window.txt` is shared by every client on the PC. Since 2026.10.17.5 + each client reads it and rewrites it every 10 seconds. With several clients this clashed, and + the logs show "save placement failed — the file is being used by another process". A client + could also read a half-written file. +- A restored placement was only checked for its centre being on a monitor. A saved rect bigger + than the screen (another PC, a lower resolution, a bad read) could still put the window's + bottom-right corner, and with it AC's toolbar, off-screen. + +## Fix + +- Placement writes are skipped when nothing changed. When something did change, the file is + written to a temp file and swapped in, so it's never half-written; a clash is retried, then left + for the next save. Reads allow sharing. +- A restored window (framed, kept-size borderless, and the framed rect borderless returns to) is + moved, and shrunk if needed, to fit inside the monitor's work area. The log says when a saved + rect didn't fit. + +## If a toolbar is still missing + +Settings > Display > Reset Window Borders, or `/rc window reset`, gives a framed window sized to +the screen and replaces the saved placement. + +## Files + +- `src/RynthCore.Engine/UI/AcWindowChrome.cs` diff --git a/Changelog/2026-10-17-window-reset-borderless-position-2026.10.17.5.md b/Changelog/2026-10-17-window-reset-borderless-position-2026.10.17.5.md new file mode 100644 index 0000000..735b855 --- /dev/null +++ b/Changelog/2026-10-17-window-reset-borderless-position-2026.10.17.5.md @@ -0,0 +1,51 @@ +# 2026.10.17.5 — Reset Window Borders; borderless position saved + +**Kind:** Hot push (Engine). Previous `2026.10.17.4`. + +## Asked for + +A way to reset the window borders, and to save the window position in borderless mode. + +## Added + +Settings > Display: + +- **Reset Window Borders** (button): turns borderless off and puts the frame back as a normal, + resizable window, centred at three quarters of the monitor. It also replaces the saved window + position, so the next launch isn't stuck either. Same as `/rc window reset`. +- **Borderless Fills Monitor** (new `engine.json` key `BorderlessFillMonitor`, default on): + - On: borderless fills the whole monitor the game is on (as in 2026.10.17.4). + - Off: borderless keeps the game exactly where, and at the size, the framed window had it. To + set a custom borderless spot, turn Borderless Windowed off, move and size the window, then + turn it back on. + - Same as `/rc window fill on|off`. +- **Save Window Position** (button): saves where the window is now, framed or borderless, for the + next launch. Same as `/rc window save`. + +## Changed + +- `%LOCALAPPDATA%\RynthCore\ac_window.txt` keeps the borderless rect (`bl_left`, `bl_top`, + `bl_width`, `bl_height`) next to the framed rect (`left`, `top`, `width`, `height`). Both are + saved every 10 seconds while Remember Open Windows and Positions is on, each only in its own mode. +- At launch with borderless on, the saved borderless rect comes back. With Fills Monitor on, that + means the monitor it was on (multi-monitor). The saved framed rect is what you get when + borderless is turned off. +- The "keep it there" check after AC re-sizes the window (DXVK device reset) now restores the + chosen borderless rect, not only the full monitor. It still gives up after 4 tries a minute. + +## Note + +The placement file is shared by every client on this PC, as before, so all clients come back to +the same spot. + +## Files + +- `src/RynthCore.Engine/UI/AcWindowChrome.cs` +- `src/RynthCore.Engine/Plugins/EngineSettings.cs` +- `src/RynthCore.Engine/UI/Data/SettingsData.cs` +- `src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs` + +## Checks + +Engine build clean (no warnings in changed files); EngineSettingsTests 226/226, including the +OwnedKeys check for the new key. diff --git a/Changelog/2026-10-18-chat-link-probe-2026.10.18.25.md b/Changelog/2026-10-18-chat-link-probe-2026.10.18.25.md new file mode 100644 index 0000000..9f54e9d --- /dev/null +++ b/Changelog/2026-10-18-chat-link-probe-2026.10.18.25.md @@ -0,0 +1,36 @@ +# 2026.10.18.25: /rc chatlinkprobe (toward coordinate links in AC's own chat) (2026-10-18) + +**Kind:** Diagnostic (Engine). Previous: 2026.10.18.24 (test installer), 2026.10.18.15 (last engine hot build). + +## Why + +Coordinates are links in RynthChat (2026.10.17.2), but not in AC's own chat window. ub-IT and VirindiTank +do it through Decal, which wraps coordinates in AC's clickable-name markup and catches the click with its +`ChatNameClicked` hook. RynthCore must do this without Decal, and no public source names the acclient +function that handles a click on a chat link. This probe finds that function by watching the client. + +## What + +`/rc chatlinkprobe [seconds|off]` (default 60 s, at most 600). While it runs: + +- **Coordinates in AC's chat window become AC links.** Each pair is printed as + `<Tell:IIDString:110011:42.1N, 33.6E>42.1N, 33.6E<\Tell>`, using the same link id as GoArrow and + UtilityBelt. The rewrite happens only in what AC prints, through the engine's own chat hook (held + lines, and lines printed at once on AC's main thread). Plugins and RynthChat still get each line as + the server sent it. AC's own markup (players' names) is never rewritten. +- **Every message to `gmMainChatUI::ListenToElementMessage` is logged** (up to 400 per run): its + first 12 dwords, and any text they point at. + +Nothing changes while the probe is off. + +## How to use it + +1. `/rc chatlinkprobe 120` +2. Have coordinates appear in AC's chat, for example `/tell <yourself> 42.1N 33.6E`. +3. Click the coordinates in AC's chat window, then click a player's name. +4. Send the RynthCore log. The click's message tells the next build which call to hook so a click goes + to RynthNav (arrow, or with Ctrl held a walk), with no Decal. + +## Checks + +Engine builds; ChatHoldTests, ChatCoordTests 49/49, ChatTellTests and ChatFilterTests pass. diff --git a/Changelog/2026-10-18-graphics-low-memory-safeguard-2026.10.18.11.md b/Changelog/2026-10-18-graphics-low-memory-safeguard-2026.10.18.11.md new file mode 100644 index 0000000..379dfba --- /dev/null +++ b/Changelog/2026-10-18-graphics-low-memory-safeguard-2026.10.18.11.md @@ -0,0 +1,20 @@ +# Graphics: low-memory safeguard (engine 2026.10.18.11) + +## What happened + +A tester's client (test build 2026.10.18.4) died on every launch since 16:56: +- **The fill-up:** about 13 s after reaching the world (near Hebian-to), Asheron's Call's own memory climbed from 450 MB to 3.1 GB. The .NET heap stayed at 49 MB. +- **The end:** free address space fell to 66 MB with no free block left. The 32-bit client has 4 GB. RynthNav then failed with "Insufficient memory", the main thread froze, and the client closed. +- **The trigger:** that launch was the first to write the account's Adaptive degrade, scenery draw distance and Sync to display refresh into AC's settings. + +With Adaptive degrade off, AC loads every object in range at full detail. With a far draw distance in a busy town, that is more than a 32-bit client can hold. + +## The safeguard + +- **Settings > Graphics warns** when Adaptive degrade is off with a scenery or landscape draw distance of High or more. It uses this account's value, else AC's own. +- **The engine falls back on its own:** within 10 minutes of the client starting, when free address space drops under 200 MB or the largest free block under 128 MB, it checks Adaptive degrade. If AC runs with it off, the engine turns it on in this account's profile. The save is written at once, because the client may be about to die. +- **The next launch applies it:** the launcher writes the profile into UserPreferences.ini. The engine log and the Graphics panel say what was done. It happens at most once a session, and only when degrade is off, so a slow leak later in a session changes nothing. + +## Tests + +- `tools/AcGraphicsPrefsTests`: the risk rule (degrade off or on, near or far distances, AC's defaults). 62 checks pass. diff --git a/Changelog/2026-10-18-inventory-vault-button-2026.10.18.14.md b/Changelog/2026-10-18-inventory-vault-button-2026.10.18.14.md new file mode 100644 index 0000000..835a37f --- /dev/null +++ b/Changelog/2026-10-18-inventory-vault-button-2026.10.18.14.md @@ -0,0 +1,17 @@ +# Inventory: the Vault button shows again (engine 2026.10.18.14) + +On Aelrynth, the Classic Inventory's title bar has a **Vault** button: the account vault, from the +Aeshnidae.Mule mod. rynth's main shows it; the test branch didn't. + +**Why:** the test branch added four text buttons to the Classic title bar: Remote, Sort, Count and +GInv, about 185 px together. Vault went to the left of them. The bar is 300 px at 100 %, so Vault +started about 44 px left of the panel's edge and was clipped away. The "Inventory of <name>" title +had no room left either. + +**Now:** +- **Vault** is back next to the size buttons, where rynth's main has it. +- **The four related panels** (Mini Remote, RynthSort, Item Count, Global Inventory) share one "more" button (three dots). It opens a menu with a check against each panel that is open. +- **The title** has room again. + +The Modern look is unchanged: its header keeps its four icon buttons. Like rynth's main, it has +no Vault button; the Vault is in the Classic look. diff --git a/Changelog/2026-10-18-inventory-vault-modern-2026.10.18.15.md b/Changelog/2026-10-18-inventory-vault-modern-2026.10.18.15.md new file mode 100644 index 0000000..260ab04 --- /dev/null +++ b/Changelog/2026-10-18-inventory-vault-modern-2026.10.18.15.md @@ -0,0 +1,12 @@ +# Inventory: the Vault in the Modern look too (engine 2026.10.18.15) + +On Aelrynth, the Modern Inventory's header has a Vault button (a treasure chest), left of the +Mini Remote, RynthSort, Item Count and Global Inventory buttons. Before, only the Classic look had +the Vault, and rynth's main is the same. + +- **The view:** clicking the chest shows the account vault in place of the item grid, in the grid's own style. Each item has its icon and its stack count, and hovering shows its name. +- **Caption:** it says how full the vault is ("Aelrynth Vault: 12 of 50"), or the read's status before the first read, with a Refresh button. +- **Withdraw:** right-click an item, then Withdraw, the same as in the Classic look. +- **Back to the packs:** click the chest again, or pick a pack in the pack column. + +Both looks share the caption, the empty-vault text and the Withdraw menu. diff --git a/Changelog/2026-10-18-loot-add-attribute-checklist-2026.10.18.10.md b/Changelog/2026-10-18-loot-add-attribute-checklist-2026.10.18.10.md new file mode 100644 index 0000000..7a5ce71 --- /dev/null +++ b/Changelog/2026-10-18-loot-add-attribute-checklist-2026.10.18.10.md @@ -0,0 +1,14 @@ +# Add to loot profile: the attribute checklist (engine 2026.10.18.10) + +The "Add to loot profile" popup can show RynthAi's attribute checklist (RynthAi 0.5.87). It +appears from the Inventory panel's right-click and from the Loot Editor's "Add selected item". + +- **What you get:** every attribute the item has, grouped as Item, Weapon / Armor, Ratings, Spells, Pet essence, T11 and Requirements. Each row has a tick, a comparison (`>=`, `=`, `<=`, `not`; for spells "or better", "exact", "any tier") and a value box for numbers. +- **Choosing a comparison or typing a value** ticks the row. Each group header has "all" and "none". +- **Layout:** the list scrolls inside the popup, which is wider when the list shows (440 instead of 380). +- **What is sent:** only the rows you changed go to RynthAi with each preview; the rest keep RynthAi's defaults. The value box you're typing in isn't overwritten by a new preview. +- **An older RynthAi** answers without the checklist, and the popup shows its "Include T11 attributes" box as before. + +Wire: `LootEditItemRequestDto.Choices`, `LootEditItemDraftDto.AttributesSupported` / `Attributes` +(`LootEditItemChoiceDto`, `LootEditItemAttributeDto`, `LootAttrOps`), mirroring RynthSuite's +`LootEditWire.cs`. diff --git a/Changelog/2026-10-18-test-build-full-install-2026.10.18.24.md b/Changelog/2026-10-18-test-build-full-install-2026.10.18.24.md new file mode 100644 index 0000000..0e910a0 --- /dev/null +++ b/Changelog/2026-10-18-test-build-full-install-2026.10.18.24.md @@ -0,0 +1,68 @@ +# Test build 2026.10.18.24: full installer (2026-10-18) + +Previous installer: 2026.10.18.13. Previous engine hot build: 2026.10.18.15. + +Built from the local test merge `test/hotbuild-2026-10-16-on-aelrynth` in both repos. Upstream +(aelrynth `main`) was fetched first and has nothing new: it is still the 2026.10.17.1 release +snapshot (RynthCore `8330793`, RynthSuite `c7807b6`), which both merges already contain. + +## Stamps + +- **Launcher, engine, Loot Editor, Monster Editor:** 2026.10.18.24. +- **RynthAi, RynthOracle, RynthILT, RynthInventory, RynthSort:** 2026.10.18.24. +- **RynthNav, RynthChat, RynthTracker, RynthVision:** 2026.10.18.24. They used to ship as 1.0.0 (see Fixed below). +- **Keep their own versions:** RynthJuice 0.1.3-experimental, UbRythai 3.1.15. +- **Plugin versions:** + - RynthOracle 0.6.0 + - RynthILT 0.2.20 + - RynthNav 0.6.8 + - RynthAi 0.5.88-legacy-ui + +## Fixed: installer stamps + +`installer/Build-Installer.ps1` published every experimental plugin without `-p:Version`, on the +grounds that each "keeps its own semantic version". Only RynthJuice and UbRythai set a `<Version>`, +so RynthNav, RynthChat, RynthTracker and RynthVision shipped as 1.0.0. + +Now `Test-OwnVersion` checks each plugin's csproj: +- a plugin that sets its own `<Version>` keeps it; +- every other plugin gets the release calver, like the companion plugins. + +## In this installer since 2026.10.18.13 + +**RynthCore engine** +- 2026.10.18.14: the Aelrynth Vault button in the Classic inventory. +- 2026.10.18.15: the Aelrynth Vault in the Modern inventory. + +**RynthOracle 0.5.1 to 0.6.0** +- Dynamic Stamps route through RynthNav. +- A carried Parchment can be given to a stamp's NPC. +- Quests get Go to for coordinates in their notes. +- The quest trackers refresh like the Quests tab. +- **0.6.0:** the Legendary, Markers and Dynamic Stamps tabs and the Temple guardians are merged + into the Quests list: + - rows by server, with a "Trackers only" filter; + - RynthNav Go to on every kind of row; + - guardian auto hand-in and buy-if-missing controls. + +**RynthILT 0.2.17 to 0.2.20** +- Auto-chunk rules match ub-IT: + - unlevelled Coalesced Aetheria are chunked; + - two-handed weapons with cleave 2 are chunked; + - chunking can run while the client is busy in combat; + - corrupted-weapon keep rules. +- A rating-level threshold for aetheria chunking. +- A chunked item that leaves the pack counts as chunked. +- "RynthILT.Data" version 3 carries the Temple guardian data for Oracle. + +**RynthNav 0.6.8** +- `a || b || c` alternatives: RynthNav takes the first that is on its map. + +The details are in each RynthSuite `Changelog/2026-10-18-*.md` file. + +## Outputs + +- `installer/Output/RynthCore-Setup-2026.10.18.24.exe` +- `installer/Output/RynthCore-2026.10.18.24-deploy.zip` + +Close every AC client and the launcher before installing. diff --git a/Changelog/2026-10-19-automated-system-text-in-system-tab-2026.10.18.30.md b/Changelog/2026-10-19-automated-system-text-in-system-tab-2026.10.18.30.md new file mode 100644 index 0000000..027b3ed --- /dev/null +++ b/Changelog/2026-10-19-automated-system-text-in-system-tab-2026.10.18.30.md @@ -0,0 +1,44 @@ +# Engine 2026.10.18.30: automated system text shows in the System tab only (2026-10-19) + +Previous release: 2026.10.18.29 (incoming chat queue for 25,000-line quest replies). Goes with +RynthChat 0.3.4. + +## Why + +RynthChat's All tab filled up with system text nobody typed or asked for: the server's login +messages, the `/myquests` and `/qb list` replies the plugins request on their own (thousands of +lines on an Infinite Leaftide character), and the login probes' replies. RynthChat records every +line, including the ones a plugin hides from the retail chat, so those showed under All too. + +## Changed + +- **Automated system text shows in System only.** A line RynthChat marks automated (`"auto"`) + and that no rule or standard filter placed is routed to the System tab and left out of All and + its own channel tab. RynthChat marks: + - `/myquests` and `/qb list` lines, whoever sent the command; + - the login burst: system text from entering the world until 30 s after login completes + (welcome, MOTD, house and allegiance notices, the plugins' login probes); admin tells + never count; + - any line a plugin ate. +- **The engine reports eaten lines to RynthChat.** After every plugin has seen a line, the chat + dispatch calls RynthChat's new `RynthChatNoteEaten` when a plugin ate it (one lookup per batch). + With an older RynthChat, the export is missing and nothing happens. +- **Setting:** Chat filters > Standard filters > "Automated system text shows in System only". + It is on by default, saved as `automatedToSystem` in `rynthchat_settings.json`; files without + it load as on. Changing it re-routes the kept lines. +- The rule editor's test box names the step "Automated" when it applies. + +## Tests + +- `tools/ChatHistoryBench` (22/22): 8 new checks. + - An automated line shows in System only, from any channel. + - An unmarked line still shows under All. + - With the setting off, automated lines show under All. + - A rule that moves the line still decides first. + - RynthChat's classifier and buffer: login-burst, admin-tell and eaten-line handling. + - The bench also gets the standard-filter stub it lacked, so it builds again. +- The checks caught a crash before release. The new RynthChat regex read a timeout field that is + declared further down the file, so it was still zero at startup and RynthChat failed to start. + It is fixed in RynthChat 0.3.4. +- ChatFilterTests 1329/1329, ChatHoldTests 46/46, ChatTellTests 59/59; ChatDiscordTests and + ChatCoordTests pass. diff --git a/Changelog/2026-10-19-incoming-chat-queue-25000-lines-2026.10.18.29.md b/Changelog/2026-10-19-incoming-chat-queue-25000-lines-2026.10.18.29.md new file mode 100644 index 0000000..9f25f60 --- /dev/null +++ b/Changelog/2026-10-19-incoming-chat-queue-25000-lines-2026.10.18.29.md @@ -0,0 +1,20 @@ +# Engine 2026.10.18.29: incoming chat queue sized for 25,000-line quest replies (2026-10-19) + +Previous release: 2026.10.18.25 (chat link probe). + +## Why + +On ACECustom, `/myquests` and `/qb list` print one chat line per quest flag. Infinite Leaftide +characters hold more than 15,000 flags, and the lists should cope with at least 25,000. The +plugins' incoming-chat queue (`PluginManager.MaxPendingIncomingChats`) held 4,096 lines and +dropped the oldest past that. A slow plugin pump during a 25,000-line burst would have lost the +head of the reply. + +## Changed + +- `MaxPendingIncomingChats` is 65,536. A queued line is a short string, so a full queue costs a + few MB. Drops are still counted and logged at most every 10 s ("incoming chat line(s) dropped + before plugins heard them"). + +Goes with RynthILT 0.2.22, RynthOracle 0.6.1 and RynthAi 0.5.91 (RynthSuite changelog +`2026-10-19-quest-lists-25000-flags-...`). diff --git a/Changelog/2026-10-19-items-prismatic-damage-type-2026.10.19.3.md b/Changelog/2026-10-19-items-prismatic-damage-type-2026.10.19.3.md new file mode 100644 index 0000000..902519d --- /dev/null +++ b/Changelog/2026-10-19-items-prismatic-damage-type-2026.10.19.3.md @@ -0,0 +1,13 @@ +# Engine 2026.10.19.3: Items panel Prismatic damage type (2026-10-19) + +Previous release: 2026.10.19.2 (the merged test branch over rynth's 2026.10.19.1). Goes with +RynthAi 0.5.93, which treats Prismatic as universal damage. + +## Changed + +- **Prismatic damage type.** Missile weapons and ammo on the Items panel can be set to + "Prismatic", universal damage. RynthAi resolves it per target to the weakest element, or the + Monsters rule's damage type. Other kinds keep the eight elements. + - It works in both the ImGui and Avalonia faces. + - The list is `ItemsCommands.MissileElements`, chosen by `ItemsCommands.ElementsFor(kind)`. +- **Its colour** is a light rose (`DamageTypeColors.Prismatic`). diff --git a/Changelog/2026-10-19-merge-rynth-main-2026.10.19.1-into-test.md b/Changelog/2026-10-19-merge-rynth-main-2026.10.19.1-into-test.md new file mode 100644 index 0000000..5495773 --- /dev/null +++ b/Changelog/2026-10-19-merge-rynth-main-2026.10.19.1-into-test.md @@ -0,0 +1,61 @@ +# Merge rynth main (2026.10.18.1 and 2026.10.19.1 snapshots) into the test branch (2026-10-19) + +Brings rynth's two newest release snapshots (aelrynth main `605ec6f` and `44074df`) into +`test/hotbuild-2026-10-16`, by way of `test/hotbuild-2026-10-16-on-aelrynth`. The owner asked for a +careful merge, keeping both sides' changes. The plain merge had 38 conflicting files (139 sections). + +## How it was merged + +- **Files rynth built on our published `sk` code (85% or more of it adopted).** These were merged + against `upstream/sk` as the base, so his edits land on top of ours. Eight files. +- **Every other file.** Resolved section by section against the true merge base. + +## Taken from rynth + +- **Plugin contract v87/v88.** `GetWieldedItems` (EquipmentTracker); managed plugins find their + shared dependencies in `Runtime\PluginShared`. +- **Settings and Skills.** + - `SkillsRouting`: the Skills bar icon shows only while Oracle can't host the Skills tabs. + - The Oracle Skills embed lifecycle (`OracleSkillsEmbed.Bind`, `NoteDrawn` and `Sweep`). + - The hardened Enl calculator data (lenient row converters, preformatted row text) and its + drawing ("Show all", narrow-panel scaling). +- **Chat.** `ChatRetailVerdict`, `SharedFileWatch` for the settings file, and his coordinate-link + helpers in `ChatCoords`. The standard filters "Damage you deal / take" keep their original meaning. +- **Inventory.** Rynth's header layout for the related-panel buttons: icons, or a "more" menu when + short. The Vault is never dropped. This applies to both looks. +- **Reload hold.** `HoldReloadInWorld` (opt-in, default off) and `HoldReloadInWorldMaxMinutes`, + his reworked `ReloadInWorldGate`, and its tests. +- **Display.** `RememberAcWindowPosition`: game-window placement split from panel layout, opt-in. + It is shown in Settings > Display as "Remember Game Window Position". +- **Release pipeline.** `Publish-Update.ps1` builds the plugins managed by default (collectible, so + a reload frees them), collects `PluginShared`, and passes `-PluginSharedDir` and `-RynthAiDll` + to the installer. + +## Kept from the test branch + +- **`AcWindowChrome`.** + - Ours is kept: Fills Monitor, Reset Window Borders, Save Window Position, a separate borderless + rect, and the Graphics profiles. + - Its placement save and restore now follow `RememberAcWindowPosition`. + - Rynth's threading rework (window changes posted to the game WndProc, `AcWindowChromePolicy`) + is not ported yet. Follow-up. +- **`BorderlessFillMonitor`.** Added back to rynth's `EngineSettings`. +- **The loader gate.** `RynthCoreMayHotReload` and `RequestManualReload` are kept, now under + `HoldReloadInWorld` in place of the removed `AllowInWorldAutoHotReload`. With the hold on, the + loader waits in the world for every reload, a hand reload too (a mid-session CoreCLR re-init can + still crash). With it off (the default), reloads go ahead mid-session, as upstream does. +- **ImGui bar.** Sense stays under RynthNav and Item Count / Mini Remote under Inventory. Skills + uses rynth's conditional icon. The ILT bar section stays removed. +- **Installer.** Our full-installer `Build-Installer.ps1`, with rynth's managed-RynthAi and + `PluginShared` staging ported into it. Our optional Decal bridge, versioned installer copy, the + `RynthLevistras` server plugin, and server plugins in the zip. +- **Automated chat to System.** `AutomatedToSystem`; the Enl calculator's "How to get" column and + vendor-rate editors; the Augmentations STILL NEEDED row. +- **Items.** Weapon damage-type tints are combined with rynth's move up / down buttons. + +## Tests + +- **All 59 `tools/*Tests` and benches pass.** +- **`PluginManifestTests`.** Our "v86 slot last" opening was dropped; rynth's slot counts include + his v87 slot. +- **`EngineSettingsTests`.** No longer prints the removed `AllowInWorldAutoHotReload`. diff --git a/Changelog/2026-10-19-skills-aug-still-needed-sigil-how-to-get-2026.10.18.31.md b/Changelog/2026-10-19-skills-aug-still-needed-sigil-how-to-get-2026.10.18.31.md new file mode 100644 index 0000000..b76155e --- /dev/null +++ b/Changelog/2026-10-19-skills-aug-still-needed-sigil-how-to-get-2026.10.18.31.md @@ -0,0 +1,20 @@ +# Engine 2026.10.18.31: Skills panel shows luminance still needed and how to get chain items (2026-10-19) + +Previous release: 2026.10.18.30 (automated system text in the System tab). Goes with RynthILT 0.2.23. + +## Changed (Skills panel, Progression tab) + +- **Augmentations:** + - A STILL NEEDED row under TOTALS: the luminance still needed after banked and character + luminance, and the e-coins short. It is green when nothing is left. + - The line under the table that shows the subtraction. +- **Enlightenment, "Still need / have" and "Sigil craft chain":** + - A "How to get" column (dim, wrapped) with RynthILT's recipe or vendor trade for each row. + - With an older RynthILT, the chain keeps its "craft" marker and the materials table keeps three columns. +- **Vendor rates** under the chain: Extracts per Ascension Coin, and the Trophy trade (extracts + and Trophies). They are sent as `prog extractsperasc` / `trophyextracts` / `trophycount` and + shown only when RynthILT reports them. +- `ProgressionData`: + - `AugPlanner`: `stillLum`, `stillCoins`, `stillLine`. + - `EnlPlanner`: `extractsPerAsc`, `trophyExtracts`, `trophyCount` (-1 when absent). + - `EnlMaterialRow` and `EnlChainRow`: `how`. diff --git a/Changelog/2026-10-20-popout-plugin-imgui-context-crash-2026.10.20.4.md b/Changelog/2026-10-20-popout-plugin-imgui-context-crash-2026.10.20.4.md new file mode 100644 index 0000000..165a3f9 --- /dev/null +++ b/Changelog/2026-10-20-popout-plugin-imgui-context-crash-2026.10.20.4.md @@ -0,0 +1,46 @@ +# Engine: a plugin section in a popped-out window no longer kills the client (2026-10-20) + +RynthCore engine 2026.10.20.4. Previous release: 2026.10.19.3 (the live engine). + +## The crash (SK on DreamWeave, 2026-10-19 20:15:45 and 20:19:17) + +Opening the "DreamWeave server (RynthDreamWeave)" entry in a popped-out Mini Remote froze the +client and closed it about 20 seconds later. The same thing happened on a second DreamWeave client +(pid 43516). The engine logged a main-thread hang; its CLR dump shows what actually happened: + +- AC's main thread (0x7894, the one that draws the pop-outs) holds a + `System.ExecutionEngineException`, the runtime's fatal error, in + `ServerPackPlugin.RenderEmbeddedCard` -> `ImGuiNative.igGetCursorPosY()`, called from the + popped-out Mini Remote's frame. The "hang" was the runtime dying: writing the dump, then + terminating the client. +- That RynthDreamWeave is rynth's managed build (API v88): it loads into its own + AssemblyLoadContext with its own copy of ImGui.NET. The engine's DLL resolver only covers its own + ImGui.NET, so the plugin's copy loaded a second `cimgui.dll`: a second ImGui with its own + "current context". The dump has both modules, `RynthCore.cimgui.dll` (the engine's) and + `Runtime\cimgui.dll`. +- A pop-out draws in a context of its own, made current only in the engine's cimgui. The plugin + asked its own copy for the current context, got the main one (not in a frame then), and its first + call ran against a window that wasn't there: an access violation in native code, which no + try/catch stops. + +The docked Mini Remote worked by luck: there the main context is the one in a frame. Every +managed plugin loaded the same way (RynthLua, RynthNav, RynthTracker, RynthVision, RynthInventory, +RynthSort, RynthNet, RynthThreads and the server plugins), so any of their sections in a pop-out +could do the same, on any client. + +### Changed + +- **Managed plugins share the engine's ImGui.** A managed plugin's load context resolves `cimgui` + / `cimgui.dll` to the engine's own module (`ManagedPlugins.PluginLoadContext.LoadUnmanagedDll`): + one ImGui, one current context, so a pop-out's context is the one the plugin draws in. +- **Pop-outs set the context in a second cimgui too** (`Plugins/StrayImGuiContext.cs`). When a + `cimgui.dll` that isn't the engine's is loaded (a NativeAOT plugin that doesn't bind its ImGui.NET + to the engine's module), a plugin call made inside a pop-out + (`PluginManager.RenderEmbed`, ":popout" surfaces: Mini Remote sections, Guardian, RynthAi panels) + first makes the pop-out's context current in that copy, and puts the copy's own context back + afterwards. Logged once: `a second cimgui.dll is loaded ...`. + +## Tests + +- Engine builds clean. The fix is native interop with the game's ImGui, so it was checked against + the crash dump rather than a unit test: the faulting frame is exactly the call path changed. diff --git a/Changelog/2026-10-23-chat-filter-slow-rules-retry-2026.10.20.11.md b/Changelog/2026-10-23-chat-filter-slow-rules-retry-2026.10.20.11.md new file mode 100644 index 0000000..f614967 --- /dev/null +++ b/Changelog/2026-10-23-chat-filter-slow-rules-retry-2026.10.20.11.md @@ -0,0 +1,30 @@ +# Engine 2026.10.20.11: chat filter rules no longer switch off for good on long sessions + +## Fixed + +- Silentkelpie, about 48 hours into one session: the chat filter had "stopped working". Its rules + were being switched off one by one: "ChatModel: rule "^\[RynthNet] Silentstorm connected\.$" is + too slow (a match took over 15 ms) and is skipped until edited." That pattern takes + microseconds. The 15 ms regex timeout is wall-clock time, so a pause of the whole thread during + an easy match (a garbage collection, other processes scheduled in on a machine running several + clients) threw it, and the rule stayed off until someone edited it. Over days, rule after rule + went off. (The skip was never saved, so a restart brought them back, which is why it only + showed on long sessions.) + +## Changed + +- A rule match (and the "colour the match" scan) that times out is run once more before the rule + is judged slow: a pause doesn't repeat, a slow pattern does. +- A rule judged slow is skipped for 10 minutes and then tried again on its own; each further + strike doubles the wait (20, 40 minutes ...), at most 4 hours. Editing the pattern still clears + it at once. The log says when it is skipped (and for how long) and when it is tried again. +- The filter editor's status and test box say so ("skipped for a while ... tried again on its own"). +- Unchanged: the per-pass budget for genuinely slow rules (100 ms per 500 kept lines), which + already caps one reading at 30 ms so a single pause can't condemn a rule there. + +## Tests + +- tools/ChatFilterTests: "slow rules: a second chance, and tried again later" (the strike waits; + an easy rule matches; a pattern that always times out fails twice; the router skips a slow rule + and tries it again after its wait, then waits 20 minutes after a second strike; an edit clears + it; an easy rule hides its line again once tried again). 1484/1484 checks passed. diff --git a/Changelog/2026-10-24-chat-command-replies-in-typed-tab-2026.10.20.14.md b/Changelog/2026-10-24-chat-command-replies-in-typed-tab-2026.10.20.14.md new file mode 100644 index 0000000..37e5b73 --- /dev/null +++ b/Changelog/2026-10-24-chat-command-replies-in-typed-tab-2026.10.20.14.md @@ -0,0 +1,49 @@ +# Engine 2026.10.20.14: a command's reply shows in the RynthChat tab you typed it in + +Previous release: 2026.10.20.13. + +## Fixed + +- Silentkelpie: `/fship` and other server commands typed in RynthChat's box "don't show up" + in RynthChat. AC's own chat showed them. Nothing was lost or filtered: + - The server's reply to a command is system text (ACE's `ChatMessageType.Broadcast`, type 0), + so RynthChat files it under System, which shows only in the All and System tabs. The + seven `[FSHIP]: use /fship ...` lines were in All the whole time. + - The window was on another tab. + + How this was checked, so the same report can be ruled out quickly next time: + - This PC's rules and standard filters run through the engine's real router leave the + `[FSHIP]` lines in All and System. + - RynthChat's chat log showed all seven lines arriving at 09:42:53. + - No plugin eats them. + +## Changed + +- **A command's reply follows you** (`UI/Data/ChatReplyTab.cs`). When you send a slash or + `@` command from RynthChat's box, the tab you're on is marked for 5 s. The System lines (the + server's replies) and Rynth lines (plugin replies) that arrive in that time also show in + that tab, as well as in All and System. The mark is kept on the line itself + (`ChatLine.ReplyTab`, checked in `ChatModel.LineInTab`), so a re-route pass after a rule edit + keeps it. A rule that hides the line still hides it everywhere. +- Not for chat: `/say`, `/tell`, `/reply`, `/retell`, `/f`, `/a`, emotes and the channel + commands already land in Chat or a channel tab. Not for commands typed in All, which shows + everything. Not for automated lines (a plugin's own polls, the login burst). Not for other + channels, so combat in those seconds stays where it was. + +## Tests + +- `tools/ChatFilterTests`: "command replies: shown in the tab the command was typed in" covers: + - which commands count (`/fship`, `/bank d p 10k`, `@help` do; `/tell`, `/f`, `/a`, plain + text and a lone `/` don't); + - System and Rynth replies follow to the tab, and combat lines don't; + - automated lines aren't copied, and the 5 s window ends; + - typing in All or System marks nothing extra; + - a `/tell` marks nothing. + 1665/1665 checks passed. +- The engine and `tools/ChatHistoryBench` build with no new warnings. + +## Install + +Not hot deployed. Every engine hot reload since at least 2026-10-21 closes the running clients +(see the 2026.10.20.13 notes), so this needs the clients closed first, then +`scripts\Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs '-p:Version=2026.10.20.14' -AllowBehind`. diff --git a/Changelog/2026-10-24-chat-history-automated-budget-2026.10.20.18.md b/Changelog/2026-10-24-chat-history-automated-budget-2026.10.20.18.md new file mode 100644 index 0000000..0ec5599 --- /dev/null +++ b/Changelog/2026-10-24-chat-history-automated-budget-2026.10.20.18.md @@ -0,0 +1,25 @@ +# RynthChat: /myquests replies no longer wipe the chat history (2026.10.20.18) + +## Symptom +Every so often the chat looked reset: older lines under All vanished at once +(noticed around banking, but unrelated to it). + +## Cause +RynthAi's Meta Manager polls `/myquests` about every ten minutes. On a +well-played character the reply is about 2,200 lines (Silentkelpie's flight +dump of 21:51:29 shows bursts at 21:40:41 and 21:50:49). Those lines are +marked automated and shown only in the System tab, but they counted against +the same 2,000-line "Chat history" as everything else, so each reply pushed +every line under All out of the history. + +## Fix +- `ChatHistory.Keep` / `Merge(..., extra)`: automated lines (ChatLine.Automated: + /myquests and /qb replies, the login burst, lines a plugin ate) are kept on + their own budget of the same length; ordinary lines keep the full setting. + Order is kept. Worst case memory is twice the setting (about 3.6 MB at 2,000). +- `ChatSource`: the merge and the trim use it. +- `ChatFace.DropGone`: removes any shown line the source no longer keeps (from + the middle as well as the top), keeping the view in place while scrolled up. + +RynthChat's own ring (the plugin) still holds the newest lines of both kinds; +the engine reads it ten times a second, so it only matters on a bind or reload. diff --git a/Changelog/2026-10-24-chat-scroll-follow-and-keep-place-2026.10.20.18.md b/Changelog/2026-10-24-chat-scroll-follow-and-keep-place-2026.10.20.18.md new file mode 100644 index 0000000..a1e13c4 --- /dev/null +++ b/Changelog/2026-10-24-chat-scroll-follow-and-keep-place-2026.10.20.18.md @@ -0,0 +1,31 @@ +# RynthChat: following the newest line and keeping your place when scrolled up + +Reported: the chat "auto-scrolled to the top" instead of following the bottom, and a manual +scroll didn't keep its place: it skipped back to the top or the bottom. + +Seen live (2026-10-24): following stopped by itself as soon as the mouse rested over the chat, +without any wheel or click, and from then on the view crept up as a full buffer dropped its +oldest lines, until it sat at the top showing ten-minute-old lines. + +## Cause + +`ChatFace.DrawLines` decided "the player scrolled" from any change of the list's scroll between +frames, and also only moved the view itself when lines dropped off the top. Any scroll change +the player didn't make (a hover or focus change, a re-measure, ImGui clamping the scroll to new +content) therefore turned following off, or moved the view the player was reading. + +## Fix + +- Only the player moves the list: the wheel over it, a press on its scrollbar (held until the + button comes up), or a drag-select past its edges. Only those turn following off (wheel up, or + leaving the bottom) or back on (back at the bottom). +- Following: the view is put at the bottom every frame unless the player is scrolling. +- Not following: the view is put back where the player left it every frame, moved only by how + much the lines above it changed (dropped from a full buffer, re-measured after a resize or a + rule change), so nothing else can move it. +- Kept: the place is kept across a route rebuild (another client's settings, a rule edit) by + the line at the top of the view. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/ChatFace.cs` diff --git a/Changelog/2026-10-24-chat-settings-safe-saves-per-character-layout-2026.10.20.13.md b/Changelog/2026-10-24-chat-settings-safe-saves-per-character-layout-2026.10.20.13.md new file mode 100644 index 0000000..76d262d --- /dev/null +++ b/Changelog/2026-10-24-chat-settings-safe-saves-per-character-layout-2026.10.20.13.md @@ -0,0 +1,88 @@ +# Engine 2026.10.20.13: chat filters stop getting lost; each character keeps its own window layout + +Previous release: 2026.10.20.12, this change's first hot deploy, which was missing a log line. +Before that: 2026.10.20.11. + +## Fixed + +- Silentkelpie, running five clients: RynthChat "keeps losing" its filters, they "stop working", + and the chat window resets. The RynthChat plugin wasn't the cause. Every client on the machine + shares two files, and each wrote its whole state over the other clients': + - **Chat rules and standard filters** (`%AppData%\RynthCore\rynthchat_settings.json`). A client + re-read the file only while its chat window was open. A client with chat closed kept old rules + in memory and wrote them back at its next save, even from a tab click. Every other client then + reloaded that old copy, and each standard filter the file didn't list went off. On 2026-10-24 + between 08:43 and 08:46 one client saved 15 times and the four others reloaded every one. + - **Window positions** (`%LocalAppData%\RynthCore\panel_state.txt`, one `panel.Chat` row for + every client). A client read it at start and on an engine reload, then rewrote all of it on any + window move, open or close. So a client's chat window came back wherever the client that saved + last had its own, or closed. The file was also rewritten in place, so a client dying mid-write + could leave it cut off. + +## Changed + +- **Chat settings are checked all the time.** The engine's UI step (`UiDataHub`) now checks the + shared file every step, throttled to a timestamp check every 2 s, whether or not the chat window + is open. Before, only the chat window's data source did, while it was subscribed. +- **A save merges instead of overwriting** (`UI/Data/ChatSettingsMerge.cs`). When another client + changed the file since this client's base (what its settings in memory came from), each + top-level setting is decided on its own: + - a setting this client changed is saved from this client; + - a setting this client left alone keeps the file's value; + - a setting only the other client wrote is kept. + The client then picks up the merged result itself. A file that can't be read, or a merge that + doesn't load back, leaves the save as it was. The rule list and the standard filters are each + one setting, so if two clients edit rules at the same moment, the later save's list still wins. + The base is taken when the save is asked for, not when it is written, so a reload in between + can't make older settings look current. A merged result is applied only if no newer save has + been asked for since. +- **A tab click no longer saves.** The selected tab is this client's own; it is written with the + client's next real change and ignored by the others, as before. +- **Window layout is per character** (`UI/PanelStatePath.cs`, `UI/PanelStateStore.cs`). + `panel_state.<server>.<character>.txt` comes from this process's launch context + (`ServerName`, `TargetCharacter`). A character's first run starts from the shared + `panel_state.txt`, and its saves then go to its own file. A client started outside the launcher + still uses the shared file. Saves are written to a temp file and swapped in. +- **The log says which layout file is in use**, at the first save. In 2026.10.20.12 this line was + written at load, which runs during engine start before the log is up, so it never appeared; + 2026.10.20.13 moves it to the first save. + +## Tests + +- `tools/ChatFilterTests`: "settings merge: a save never undoes another client's rules" covers: + - a stale client changing only its font and tab keeps the other client's new rule and preset change; + - a client editing rules keeps its edit, and the other client's font stays; + - a setting only the other client wrote is kept, and one this client removed stays removed; + - no base, no file, a broken file, or nobody else saving all leave this client's text as is. + 1648/1648 checks passed. +- `tools/PanelStateTests` (new): file names from the server and character, with unsafe and + non-ASCII characters as `_`, long names cut, and case not making a second file. The shared name + is used when the character is unknown. The launch context is read, including broken, missing + and non-string values. 16/16 checks passed. +- The engine builds (`-c Release -p:EngineHost=coreclr`) with no new warnings. + +## Install + +Hot deployed with `scripts\Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs +'-p:Version=2026.10.20.13' -AllowBehind`. `-AllowBehind` is needed because this checkout has no +`status-export` branch for the script's safety check; it holds everything the live +2026.10.20.11 engine was built from. + +**Hot reload closed every running client, both times.** On each deploy, each client loaded the +new engine generation, logged `[loader] Hooks: 2 patch(es) applied in one freeze`, and its +process ended within a second: +- the .12 deploy: the five clients that were running (Silentkelpie's at 09:07:51, after waiting + for its fight to end); +- the .13 deploy: the five clients relaunched at 09:07. + +This is not from this change. Every hot reload in the logs since at least 2026-10-21 ends the +same way, including the 2026.10.20.11 deploy at 13:59 on 2026-10-23. The five clients started +fresh at 09:12 run 2026.10.20.13. Until the hot reload is fixed, deploy the engine with the +clients closed. + +After the 2026.10.20.12 deploy, four characters made their own layout files within two minutes, +each started from the shared layout: +`panel_state.aelrynth.sk.txt`, `panel_state.infiniteleaftide.silentstorm.txt`, +`panel_state.infiniteleaftide.silent_pack.txt` and +`panel_state.infiniteleaftide.slient_hoooooooe.txt`. Silentkelpie makes its own at its first +window save. The shared `panel_state.txt` is no longer written by launcher-started clients. diff --git a/Changelog/2026-10-24-inventory-filter-like-this.md b/Changelog/2026-10-24-inventory-filter-like-this.md new file mode 100644 index 0000000..4225510 --- /dev/null +++ b/Changelog/2026-10-24-inventory-filter-like-this.md @@ -0,0 +1,48 @@ +# Inventory: filter like this, and find like this in Global Inventory + +Two new lines in the Inventory panel's right-click menu, under "Add to loot profile...": + +- **Filter inventory like this...** opens the Add to loot profile popup in a filter mode: the + same Match choice (default "Items like this") and the same attribute checklist, but no + profile, action or name. **Filter** asks RynthAi to judge every item you carry and wear with + that rule (its looter's own evaluator), and the list shows only the matches. + - A bar under the tools row names the filter (hover: its conditions), offers + **Identify N** when some items can't be judged until identified, and clears it (X). + - The panel asks RynthAi again every 2 s while it shows (find_refresh), so new loot and + finished identifies show up; RynthAi only answers when the result changed. + - Clearing filters, closing the Classic tools row or hiding the panel clears it. In Classic + the bar is in the tools row, which opens when the filter is applied. +- **Find like this in Global Inventory...** (enabled when RynthInventory is loaded) uses the + same popup; **Search** sends the rule to RynthInventory as `/ginv like <spec>`, which opens + Global Inventory filtered to every character's matching items. + +Needs the matching RynthSuite (RynthAi item_find / find_refresh / find_close, RynthInventory +0.1.5). An older RynthAi gets a "too old" note in the popup. + +## Files + +- `ImGui/Panels/LootAddDialog.cs`: `LootAddMode` (AddRule, FilterInventory, FilterGlobal), + FilterBody, item_find and its answer (TakeFind), `NextSeq`. +- `ImGui/Panels/InventoryFace.LikeFilter.cs` (new): the filter state, refreshes and the bar. +- `ImGui/Panels/InventoryFace.cs`, `InventoryFace.Classic.cs`: menu lines, the list filter, the bar. +- `UI/Data/LootEditData.cs`: request Find / Scope / Candidates, draft Find, `LootEditItemFindDto`, + state ItemFind (mirrors LootSdk LootEditWire). + +## Follow-up: checklist filters and spell lists + +- **The Inventory panel's filter button** (the list-check icon in the tools row) now opens the + same checklist popup with no item: every attribute a loot rule can test, unticked, with a + value to fill in (named values such as material, skill, slayer, class pick from a list). + Filter judges your items the same way as "Filter inventory like this". The old rule list + editor no longer hides items (its saved rules are left in the settings file). +- **Global Inventory** gets the same checklist ("Attribute filter +" next to the search box): + one group open at a time, a ticked row shows its comparison and value; the search filters + every character's saved items as you tick. +- **Spell lists** in every checklist (Add to loot profile, both filters, Global Inventory): + - Add spell: Creature, Life or Item, a family from the spell table (buffs only: no debuffs, + war or void), a level I to VIII; "or better" by default (exact / any tier in its row). + Levels VII and VIII have their own names ("Might of the Lugians", "Incantation of Strength + Self"), so the rule lists the family's spells by name; Self and Other both count. + - Add cantrip: Minor, Major, Epic, Legendary or Paragon and a cantrip name. + - Cantrip "or better" and the tier counts now include Paragon ("Paragon" or "Paragon's"). +- Named values on an item's rows (material, wield skill...) can be changed from a list. diff --git a/Changelog/2026-10-25-inventory-add-to-damage-weapons-2026.10.20.19.md b/Changelog/2026-10-25-inventory-add-to-damage-weapons-2026.10.20.19.md new file mode 100644 index 0000000..bd4c71d --- /dev/null +++ b/Changelog/2026-10-25-inventory-add-to-damage-weapons-2026.10.20.19.md @@ -0,0 +1,14 @@ +# Inventory right-click: Add to Damage panel weapons (2026.10.20.19) + +Right-click a weapon, wand or shield in the Inventory panel and choose +**Add to Damage panel weapons**. It joins RynthAi's weapons list (Items), which is +what the Damage panel offers per monster and what combat may use. A shield goes in +as an off-hand item. RynthAi says in chat whether it was added or is already +listed (and refuses anything that is not a weapon, wand or shield). + +- RynthAi: `RynthPluginAddWeaponById(uint id)`; `LegacyWeaponsUi.AddWeapon(id)` is + the old Add Selected logic without needing the item selected first (Add Selected + now calls it). Saves the settings. +- Engine: `ItemsCommands.AddWeapon(id)` (refreshes the Items and Damage views); + the menu entry shows for items whose type is melee, missile or caster, or that + go in the shield slot. With a RynthAi that lacks the export, the click is logged. diff --git a/Changelog/2026-10-26-plugin-windows-keep-their-spot-per-character-api-91.md b/Changelog/2026-10-26-plugin-windows-keep-their-spot-per-character-api-91.md new file mode 100644 index 0000000..e4edf1b --- /dev/null +++ b/Changelog/2026-10-26-plugin-windows-keep-their-spot-per-character-api-91.md @@ -0,0 +1,23 @@ +# Plugin windows keep their spot per character (plugin API v91) + +Floating windows that plugins draw themselves (the Item HUD, the Mini Remote, the +Nav HUD, RynthAi's legacy settings windows, ub-Rythai's windows, RynthILT's pages, +the server packs' server window) kept their spot and size only in imgui.ini. Every +running client shares that one file and rewrites all of it, so a window moved or +resized in one client came back where another client's next save had it. + +The engine now keeps those spots per character, the way its own panels already +were: `%LocalAppData%\RynthCore\window_state.<server>.<character>.txt`, one line +per window (`<key>=x,y,width,height`). A window is saved when the player lets go +of the mouse after moving or resizing it; moves the code makes are not saved. + +- Engine: `UI/WindowPlacementStore.cs`; API v91 `GetWindowPlacement` / + `SetWindowPlacement` (`Plugins/WindowPlacementApi.cs`). SDK: + `RynthCoreHost.HasWindowPlacements`, `TryGetWindowPlacement`, `SetWindowPlacement`. +- Plugins: one shared control, `RynthSuite/Plugins/Shared/SavedWindow.cs` (linked + source). The plugin sets `SavedWindow.Host` at start; each window calls `Apply()` + right before `ImGui.Begin` and `Track()` inside it. +- RynthAi: the Item HUD and Mini Remote placement fields added to huds.json on + 2026-10-26 are gone (the shared control replaces them); place those two windows + once more after updating. +- On an engine older than v91 the windows behave as before (imgui.ini). diff --git a/Changelog/2026-11-11-dungeon-map-visited-per-floor.md b/Changelog/2026-11-11-dungeon-map-visited-per-floor.md new file mode 100644 index 0000000..9b73a9d --- /dev/null +++ b/Changelog/2026-11-11-dungeon-map-visited-per-floor.md @@ -0,0 +1,7 @@ +# 2026-11-11 — Dungeon Map: each shown floor draws its own walked cells + +The Dungeon Map drew the walked (visited) cells for the player's floor only, and RynthAi's snapshot +painted them by x/y, so the cells walked on other floors showed up too. RynthAi now paints the floor you +stand on, separately for each floor (RynthSuite 2026-11-11-dungeon-trail-stays-on-its-floor). The map draws +each shown floor's own walked cells: the player's floor in full, the other shown floors dimmed as their walls +are. Floors that aren't shown draw none. diff --git a/Changelog/2026-11-12-progress-tab-ilt-sections-only-on-ilt.md b/Changelog/2026-11-12-progress-tab-ilt-sections-only-on-ilt.md new file mode 100644 index 0000000..d68ff9e --- /dev/null +++ b/Changelog/2026-11-12-progress-tab-ilt-sections-only-on-ilt.md @@ -0,0 +1,6 @@ +# 2026-11-12 — Progress tab: the ILT sections only on Infinite Leaftide + +The Skills panel's Progress body (Oracle's Progress tab) still shows on every server. Off Infinite Leaftide +it shows only the retail attribute XP planner, without the infinite-attributes raiser, the augmentation and +enlightenment planners, or the "need RynthILT's ILT features" note. On Leaftide (IltInfo.IsIlt, or RynthILT's +progression snapshot) nothing changes. diff --git a/Changelog/2026-11-15-item-tool-give-amount-and-every.md b/Changelog/2026-11-15-item-tool-give-amount-and-every.md new file mode 100644 index 0000000..27e435f --- /dev/null +++ b/Changelog/2026-11-15-item-tool-give-amount-and-every.md @@ -0,0 +1,14 @@ +# 2026-11-15 — Item Tool: Quick give's Amount and Every fields + +Silentkelpie: "on item tool add in a option to give x number of a item and a timer of how often every x +seconds." + +- Item Tool > Quick give has two fields, side by side under the item and target picks: + - **Amount (0 = all)**: how many a round gives. + - **Every (s, 0 = once)**: the seconds between rounds; the give goes on until Stop. +- A value goes to RynthAi on Enter or a +/- click ("giveamount N", "giveevery N"). The field keeps the + sent value until RynthAi's data shows it back. +- With a RynthAi older than this, the fields are hidden and the description is the old one. +- ItemToolData reads RynthAi's new keys: amount, everySec, amountMax, everyMax, rounds, units, nextInSec. + +The giving itself is RynthAi's: RynthSuite/Changelog/2026-11-15-quick-give-amount-and-every.md. diff --git a/Changelog/2026-11-22-inventory-add-to-trade-shop.md b/Changelog/2026-11-22-inventory-add-to-trade-shop.md new file mode 100644 index 0000000..8191118 --- /dev/null +++ b/Changelog/2026-11-22-inventory-add-to-trade-shop.md @@ -0,0 +1,5 @@ +# Inventory — Add to Trade Shop (multi-select) + +Right-click a picked item (or a Ctrl/Shift multi-selection) → **Add to Trade Shop** / **Add N to Trade Shop**. + +Runs `/ra tradeshop addids …` and opens the Trade Shop window so prices can be edited. diff --git a/Changelog/2026-11-22-inventory-trade-shop-storefront.md b/Changelog/2026-11-22-inventory-trade-shop-storefront.md new file mode 100644 index 0000000..1edac8a --- /dev/null +++ b/Changelog/2026-11-22-inventory-trade-shop-storefront.md @@ -0,0 +1,8 @@ +# Inventory — Trade Shop Storefront button + +## What changed + +- Modern Inventory header always reserves a Storefront icon (left of Classic / Vault) that runs `/ra tradeshop ui`. +- Classic title bar places the same Storefront control next to Vault when there is room. +- Header declutter math reserves Trade Shop like Vault so related-panel icons / the “more” menu share what is left. +- BarDeclutterTests cover Shop geometry on Modern and Classic layouts. diff --git a/Changelog/2026-11-22-settings-game-client-vtank-import.md b/Changelog/2026-11-22-settings-game-client-vtank-import.md new file mode 100644 index 0000000..601887a --- /dev/null +++ b/Changelog/2026-11-22-settings-game-client-vtank-import.md @@ -0,0 +1,12 @@ +# Settings > Game Client: VirindiTank import (2026.11.22.42) + +Previous engine tip: 2026.11.22.40. + +## Change + +Game Client gains a **VirindiTank** section with **Import…**. It runs `/ra vtimport` through +RynthAi (confirm first). Available on every server — the import UI is no longer only on the ILT +Hub / Mini Remote Gear tab. + +RynthAi copies VirindiTank loot, nav maps and metas into LootProfiles / NavProfiles / MetaFiles and +merges MyMonsters from text `.usd` (see RynthSuite changelog for 0.5.100). diff --git a/Changelog/2026-11-22-sk-backlog-test-merge.md b/Changelog/2026-11-22-sk-backlog-test-merge.md new file mode 100644 index 0000000..5ac5d21 --- /dev/null +++ b/Changelog/2026-11-22-sk-backlog-test-merge.md @@ -0,0 +1,16 @@ +# SK backlog → aelrynth main (2026.11.22.48) + +Squash of `test/main-merge-2026-10-25` through stamp **2026.11.22.48** onto rynth main 2026.11.19.1. + +## Included (high level) + +- Trade Shop Storefront + inventory multi-add +- Loot Editor checklist / named pickers / Raw editor +- Inventory filter/checklist, imbue/slayer tooltips, Item Tool Amount/Every +- Chat command-reply routing, filter persistence, `/command` → `@command` +- Per-character window placements (plugin/pop-out) +- `/rc switchchar` and related window/radar command fixes +- Dungeon Map floor walked cells; ILT-gated Progress; RynthNav custom portals +- Tests and release stamps through 2026.11.22.48 + +Standing PR only — rynth cherry-picks / snapshots; not a merge of `sk` into main. diff --git a/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md b/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md new file mode 100644 index 0000000..bf3219a --- /dev/null +++ b/Changelog/changelog-installer-full-rynthsuite-setup-2026-04-22.md @@ -0,0 +1,19 @@ +## RynthCore Installer Update - Full RynthCore + RynthSuite Setup + +Date: 2026-04-22 + +### What changed +- Expanded `installer/Build-Installer.ps1` to package a full setup payload: + - Publishes launcher + engine. + - Discovers and publishes all default `RynthSuite` plugin projects (`RynthCore.Plugin.*`). + - Bundles `RynthCore.LootEditor` and `RynthCore.MonsterEditor` as self-contained tools. +- Updated installer staging to copy default plugin DLLs into `Runtime/Plugins` for automatic loading. +- ~~Added a mirrored `RynthAi` plugin copy under `Suite/RynthAi/` for data/profile adjacency.~~ **Removed in 0.4.8** — plugin lives only in `Runtime\Plugins\`; data stays under `C:\Games\RynthSuite\RynthAi\`. +- Updated `installer/RynthCore.iss`: + - Added `MonsterProfiles` data directory creation. + - Added Start Menu shortcuts for Loot Editor and Monster Editor when present. +- Updated `BUILD.md` installer documentation to reflect full setup behavior and default plugin autoload. + +### Why +- Provide one setup executable that installs both core runtime and suite defaults. +- Remove manual post-install steps for loading default plugins and installing suite tools. diff --git a/Plugins/RynthAi/Combat/BuffManager.cs b/Plugins/RynthAi/Combat/BuffManager.cs new file mode 100644 index 0000000..a4119c2 --- /dev/null +++ b/Plugins/RynthAi/Combat/BuffManager.cs @@ -0,0 +1,580 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class BuffManager : IDisposable + { + private CoreManager _core; + private UISettings _settings; + private SpellManager _spellManager; + + private DateTime _lastCastAttempt = DateTime.MinValue; + private bool _isForceRebuffing = false; + private int _pendingSpellId = 0; + + private class RamTimerInfo + { + public DateTime Expiration; + public int SpellLevel; + public string SpellName; // Added to make debug easier + } + private Dictionary<int, RamTimerInfo> _ramBuffTimers = new Dictionary<int, RamTimerInfo>(); + private string _buffTimerPath; + + private bool _isRechargingMana = false; + private bool _isRechargingStamina = false; + private bool _isHealingSelf = false; + + private readonly List<string> BaseCreatureBuffs = new List<string> + { + "Strength Self", "Endurance Self", "Coordination Self", + "Quickness Self", "Focus Self", "Willpower Self", + "Magic Resistance Self", "Invulnerability Self", "Impregnability Self" + }; + + private readonly Dictionary<CharFilterSkillType, string> CreatureSkillBuffs = new Dictionary<CharFilterSkillType, string> + { + { CharFilterSkillType.MeleeDefense, "Invulnerability Self" }, + { CharFilterSkillType.MissileDefense, "Impregnability Self" }, + { CharFilterSkillType.MagicDefense, "Magic Resistance Self" }, + { CharFilterSkillType.HeavyWeapons, "Heavy Weapon Mastery" }, + { CharFilterSkillType.LightWeapons, "Light Weapon Mastery" }, + { CharFilterSkillType.FinesseWeapons, "Finesse Weapon Mastery" }, + { CharFilterSkillType.TwoHandedCombat, "Two Handed Combat Mastery" }, + { CharFilterSkillType.Shield, "Shield Mastery" }, + { CharFilterSkillType.DualWield, "Dual Wield Mastery" }, + { CharFilterSkillType.Recklessness, "Recklessness Mastery" }, + { CharFilterSkillType.SneakAttack, "Sneak Attack Mastery" }, + { CharFilterSkillType.DirtyFighting, "Dirty Fighting Mastery" }, + { CharFilterSkillType.AssessCreature, "Monster Attunement" }, + { CharFilterSkillType.AssessPerson, "Person Attunement" }, + { CharFilterSkillType.ArcaneLore, "Arcane Enlightenment" }, + { CharFilterSkillType.ArmorTinkering, "Armor Tinkering Expertise" }, + { CharFilterSkillType.ItemTinkering, "Item Tinkering Expertise" }, + { CharFilterSkillType.MagicItemTinkering, "Magic Item Tinkering Expertise" }, + { CharFilterSkillType.WeaponTinkering, "Weapon Tinkering Expertise" }, + { CharFilterSkillType.Salvaging, "Arcanum Salvaging" }, + { CharFilterSkillType.Run, "Sprint" }, + { CharFilterSkillType.Jump, "Jumping Mastery" }, + { CharFilterSkillType.Loyalty, "Fealty" }, + { CharFilterSkillType.Leadership, "Leadership Mastery" }, + { CharFilterSkillType.Deception, "Deception Mastery" }, + { CharFilterSkillType.Healing, "Healing Mastery" }, + { CharFilterSkillType.Lockpick, "Lockpick Mastery" }, + { CharFilterSkillType.Cooking, "Cooking Mastery" }, + { CharFilterSkillType.Fletching, "Fletching Mastery" }, + { CharFilterSkillType.Alchemy, "Alchemy Mastery" }, + { CharFilterSkillType.ManaConversion, "Mana Conversion Mastery" }, + { CharFilterSkillType.CreatureEnchantment, "Creature Enchantment Mastery" }, + { CharFilterSkillType.ItemEnchantment, "Item Enchantment Mastery" }, + { CharFilterSkillType.LifeMagic, "Life Magic Mastery" }, + { CharFilterSkillType.WarMagic, "War Magic Mastery" }, + { CharFilterSkillType.VoidMagic, "Void Magic Mastery" }, + { CharFilterSkillType.Summoning, "Summoning Mastery" } + }; + + public BuffManager(CoreManager core, UISettings settings, SpellManager spellManager) + { + _core = core; + _settings = settings; + _spellManager = spellManager; + _core.ChatBoxMessage += OnChatMsg; + } + + /// <summary> + /// Set the path for persisting buff timers. Call after settings path is known. + /// Automatically loads any existing timers from disk. + /// </summary> + public void SetTimerPath(string charFolder) + { + _buffTimerPath = System.IO.Path.Combine(charFolder, "bufftimers.txt"); + LoadBuffTimers(); + } + + public void SaveBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + try + { + var lines = new System.Collections.Generic.List<string>(); + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + // Format: Family|Expiration(ticks)|SpellLevel|SpellName + lines.Add($"{kvp.Key}|{info.Expiration.Ticks}|{info.SpellLevel}|{info.SpellName}"); + } + 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(); + foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath)) + { + string[] parts = line.Split('|'); + if (parts.Length < 4) continue; + + int family = int.Parse(parts[0]); + DateTime expiration = new DateTime(long.Parse(parts[1])); + int level = int.Parse(parts[2]); + string name = parts[3]; + + // Only load if not expired + if (expiration > DateTime.Now) + { + _ramBuffTimers[family] = new RamTimerInfo + { + Expiration = expiration, + SpellLevel = level, + SpellName = name + }; + } + } + if (_ramBuffTimers.Count > 0) + _core.Actions.AddChatText($"[RynthAi] Restored {_ramBuffTimers.Count} buff timer(s) from last session.", 1); + } + catch { } + } + + public void Dispose() => _core.ChatBoxMessage -= OnChatMsg; + + public void ForceFullRebuff() + { + _isForceRebuffing = true; + _ramBuffTimers.Clear(); + SaveBuffTimers(); + _core.Actions.AddChatText("[RynthAi] Starting Force Rebuff...", 5); + } + + public void CancelBuffing() + { + _isForceRebuffing = false; + _isRechargingMana = false; + _isRechargingStamina = false; + _isHealingSelf = false; + _pendingSpellId = 0; + _core.Actions.AddChatText("[RynthAi] Sequence cancelled.", 5); + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + if (_core.CharacterFilter.LoginStatus != 3) return; + + // 1. Are we locked in a cast/equip animation? + if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < 1500) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 2. Do we need to heal/recharge? + if (CheckVitals()) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 3. Do we need to buff? + if (_settings.EnableBuffing) + { + if (CheckAndCastSelfBuffs()) + { + _settings.CurrentState = "Buffing"; + return; + } + + if (_isForceRebuffing) + { + _isForceRebuffing = false; + _core.Actions.AddChatText("[RynthAi] Force Rebuff Complete.", 1); + } + } + + // === THE FIX === + // 4. Only release the traffic light if WE were the ones holding it! + if (_settings.CurrentState == "Buffing") + { + _settings.CurrentState = "Idle"; + } + } + + private bool CheckVitals() + { + double maxHealth = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]; + double maxMana = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]; + double maxStam = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]; + + int curHealthPct = maxHealth > 0 ? (int)((_core.CharacterFilter.Health / maxHealth) * 100) : 100; + int curManaPct = maxMana > 0 ? (int)((_core.CharacterFilter.Mana / maxMana) * 100) : 100; + int curStamPct = maxStam > 0 ? (int)((_core.CharacterFilter.Stamina / maxStam) * 100) : 100; + + if (curHealthPct <= 30 && curStamPct > 20) return AttemptVitalCast("Stamina to Health Self"); + + if (curHealthPct <= _settings.HealAt) _isHealingSelf = true; + if (curHealthPct >= _settings.TopOffHP) _isHealingSelf = false; + if (curManaPct <= _settings.GetManaAt) _isRechargingMana = true; + if (curManaPct >= _settings.TopOffMana) _isRechargingMana = false; + if (curStamPct <= _settings.RestamAt) _isRechargingStamina = true; + if (curStamPct >= _settings.TopOffStam) _isRechargingStamina = false; + + if (_isHealingSelf) 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, CharFilterSkillType.LifeMagic); + if (spellId == 0) return false; + + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + + private bool CheckAndCastSelfBuffs() + { + List<string> desiredBuffs = BuildDynamicBuffList(); + + foreach (string buffBaseName in desiredBuffs) + { + CharFilterSkillType castSkill = SkillForBuff(buffBaseName); + if (!IsSkillUsable(castSkill)) continue; + + int spellId = FindBestSpellId(buffBaseName, castSkill); + if (spellId == 0) continue; + + if (!IsBuffActive(spellId)) + { + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _pendingSpellId = spellId; + + var fs = _core.Filter<FileService>(); + var spell = fs.SpellTable.GetById(spellId); + if (spell != null) _core.Actions.AddChatText($"[RynthAi] Casting: {spell.Name}", 5); + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + } + return false; + } + + private int FindBestSpellId(string baseName, CharFilterSkillType skill) + { + // GetDynamicSelfBuffId handles the correct priority: + // Incantation → Lore name → VII → VI → ... → I + return _spellManager.GetDynamicSelfBuffId(baseName, skill); + } + + private bool IsArmorEnchantment(string name) + { + string[] armorSpells = { + "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" + }; + + foreach (string s in armorSpells) + { + if (name.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private bool IsBuffActive(int spellId) + { + var fs = _core.Filter<FileService>(); + var targetSpell = fs.SpellTable.GetById(spellId); + if (targetSpell == null) return false; + + int targetLevel = GetSpellLevel(targetSpell); + + if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo timer)) + { + if (DateTime.Now < timer.Expiration.AddMinutes(-5)) + { + if (timer.SpellLevel >= targetLevel) return true; + } + } + + if (_isForceRebuffing) return false; + + if (IsArmorEnchantment(targetSpell.Name)) + { + return false; + } + + foreach (var ench in _core.CharacterFilter.Enchantments) + { + var activeSpell = fs.SpellTable.GetById(ench.SpellId); + if (activeSpell != null && activeSpell.Family == targetSpell.Family) + { + if (GetSpellLevel(activeSpell) < targetLevel) continue; + return ench.TimeRemaining > 300; + } + } + return false; + } + + private int GetSpellLevel(Spell spell) + { + if (spell == null) return 0; + string n = spell.Name; + if (n.StartsWith("Incantation")) return 8; + 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 GetArchmageEnduranceCount() + { + try + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + int count = me.Values((LongValueKey)238, 0); + return Math.Min(Math.Max(count, 0), 5); + } + } + catch { } + return 0; + } + + 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)); + } + + public void PrintBuffDebug() + { + int augs = GetArchmageEnduranceCount(); + _core.Actions.AddChatText($"[RynthAi] Archmage endurance count: {augs}", 1); + + if (_ramBuffTimers.Count == 0) + { + _core.Actions.AddChatText("[RynthAi] No RAM timers active.", 1); + return; + } + + 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; + + _core.Actions.AddChatText($"[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); + } + } + + private List<string> BuildDynamicBuffList() + { + List<string> step1_CreatureMastery = new List<string>(); + List<string> step2_Focus = new List<string>(); + List<string> step3_Willpower = new List<string>(); + List<string> step4_OtherCreature = new List<string>(); + List<string> step5_LifeAndItem = new List<string>(); + List<string> step6_WeaponAuras = new List<string>(); + List<string> step7_ArmorBanes = new List<string>(); + + 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<string> { + "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", "Impregnability Self" + }); + + step6_WeaponAuras.AddRange(new List<string> { + "Blood Drinker Self", "Hermetic Link Self", "Heart Seeker Self", + "Spirit Drinker Self", "Swift Killer Self", "Defender Self" + }); + + step7_ArmorBanes.AddRange(new List<string> { + "Impenetrability", "Acid Bane", "Blade Bane", "Bludgeoning Bane", + "Flame Bane", "Frost Bane", "Lightning Bane", "Piercing Bane" + }); + + List<string> final = new List<string>(); + 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; + } + + private void OnChatMsg(object sender, ChatTextInterceptEventArgs e) + { + string text = e.Text.ToLower(); + if (text.Contains("you cast ") || text.Contains("you say, ")) + { + if (_pendingSpellId != 0) + { + var fs = _core.Filter<FileService>(); + var spellInfo = fs.SpellTable.GetById(_pendingSpellId); + if (spellInfo != null) + { + int level = GetSpellLevel(spellInfo); + double dur = GetCustomSpellDuration(level); + + _ramBuffTimers[spellInfo.Family] = new RamTimerInfo + { + Expiration = DateTime.Now.AddSeconds(dur), + SpellLevel = level, + SpellName = spellInfo.Name + }; + SaveBuffTimers(); + } + _pendingSpellId = 0; + } + } + else if (text.Contains("fizzle") || text.Contains("fail") || text.Contains("component") || text.Contains("lack the mana")) + { + _lastCastAttempt = DateTime.MinValue; + _pendingSpellId = 0; + } + } + + private bool IsSkillUsable(CharFilterSkillType s) => (int)_core.CharacterFilter.Skills[s].Training >= 2; + + private CharFilterSkillType SkillForBuff(string name) + { + if (name.Contains("Impregnability") || 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 CharFilterSkillType.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 CharFilterSkillType.LifeMagic; + + return CharFilterSkillType.CreatureEnchantment; + } + + private bool EnsureMagicMode() + { + if (_core.Actions.CombatMode == CombatState.Magic) + return true; // We are in magic mode and ready to cast + + bool wandEquipped = false; + int wandToEquip = 0; + + // 1. Check ItemRules for a preferred wand + foreach (var rule in _settings.ItemRules) + { + var ruleItem = _core.WorldFilter[rule.Id]; + if (ruleItem != null && ruleItem.ObjectClass == ObjectClass.WandStaffOrb) + { + wandToEquip = ruleItem.Id; + if (ruleItem.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + } + break; // Found the preferred wand + } + } + + // 2. Fallback: Find any wand in inventory if no rule matches + if (wandToEquip == 0 && !wandEquipped) + { + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + if (wo.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + break; + } + if (wandToEquip == 0) wandToEquip = wo.Id; + } + } + } + + // 3. Equip the wand if we aren't holding one + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the server equip the item + } + + // 4. Safe to switch modes (we either have a wand equipped, or are empty-handed) + _core.Actions.SetCombatMode(CombatState.Magic); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the stance animation finish + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/CombatActionHelper.cs b/Plugins/RynthAi/Combat/CombatActionHelper.cs new file mode 100644 index 0000000..83f8ed0 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatActionHelper.cs @@ -0,0 +1,356 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Direct calls to acclient.exe CM_Combat functions for attack actions. + /// Derived entirely from Turbine's acclient.exe decompilation — no VTank code involved. + /// + /// Uses runtime pattern scanning to find function addresses in any client build. + /// Each CM_Combat::Event_* function writes a unique opcode DWORD into a packed buffer + /// before calling Proto_UI::SendToWeenie. We search acclient.exe's .text section for + /// these opcode write patterns, then walk backwards to find the function prologue. + /// + /// Source: acclient.exe CM_Combat namespace (IDA decompilation of Turbine's client) + /// Event_TargetedMeleeAttack — opcode 0x08, 3 args (targetID, height, power) + /// Event_TargetedMissileAttack — opcode 0x0A, 3 args (targetID, height, accuracy) + /// Event_ChangeCombatMode — opcode 0x53, 1 arg (combatMode) + /// Event_CancelAttack — opcode 0x1B7, 0 args + /// Event_QueryHealth — opcode 0x1BF, 1 arg (targetID) + /// + /// All functions are __cdecl with standard prologue: sub esp,0Ch; push ebx; push esi; push edi + /// Signature bytes: 83 EC 0C 53 56 57 E8 + /// </summary> + internal static class CombatActionHelper + { + // ── Delegate types matching __cdecl signatures ─────────────────────── + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMeleeAttack(uint targetID, int attackHeight, float powerLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMissileAttack(uint targetID, int attackHeight, float accuracyLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelChangeCombatMode(int combatMode); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelCancelAttack(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelQueryHealth(uint targetID); + + // ── Cached delegates (created once at init) ───────────────────────── + private static DelTargetedMeleeAttack _meleeAttack; + private static DelTargetedMissileAttack _missileAttack; + private static DelChangeCombatMode _changeCombatMode; + private static DelCancelAttack _cancelAttack; + private static DelQueryHealth _queryHealth; + + private static bool _initialized; + private static Action<string> _log; + + // ── ATTACK_HEIGHT enum values (from acclient.exe) ─────────────────── + public const int ATTACK_HEIGHT_HIGH = 1; + public const int ATTACK_HEIGHT_MEDIUM = 2; + public const int ATTACK_HEIGHT_LOW = 3; + + // ── COMBAT_MODE enum values (from acclient.exe) ───────────────────── + public const int COMBAT_MODE_NONCOMBAT = 1; + public const int COMBAT_MODE_MELEE = 2; + public const int COMBAT_MODE_MISSILE = 4; + public const int COMBAT_MODE_MAGIC = 8; + + // ── Shared function prologue for all CM_Combat::Event_* functions ─── + // sub esp, 0Ch; push ebx; push esi; push edi; call OrderHdr_ctor + private static readonly byte[] CM_COMBAT_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 }; + + /// <summary> + /// Scans acclient.exe's loaded image at runtime to find CM_Combat functions. + /// Call once at plugin startup. + /// </summary> + public static void Initialize(Action<string> chatLog = null) + { + _log = chatLog; + + try + { + // Find acclient.exe's base address in memory + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Pattern scan FAILED: acclient.exe module not found"); + return; + } + + Log($"acclient.exe base: 0x{baseAddr.ToInt32():X8}, size: 0x{imageSize:X}"); + + // Read the .text section into managed memory for scanning + // .text typically starts at offset 0x1000 from base + int textRva = 0x1000; + int textSize = imageSize - textRva; + if (textSize <= 0 || textSize > 0x500000) + { + Log($"Text section size suspect: 0x{textSize:X}, clamping"); + textSize = Math.Min(imageSize - textRva, 0x400000); + } + + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── Step 1: Find CancelAttack via unique opcode 0x1B7 ────── + // Pattern: C7 02 B7 01 00 00 (mov dword ptr [edx], 1B7h) + // This opcode value is unique in the entire binary. + byte[] cancelOpcode = { 0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00 }; + int cancelOpcodeOff = FindPattern(text, cancelOpcode); + if (cancelOpcodeOff < 0) + { + Log("Pattern scan FAILED: CancelAttack opcode 0x1B7 not found"); + return; + } + + int cancelFuncOff = FindPrologueBefore(text, cancelOpcodeOff); + if (cancelFuncOff < 0) + { + Log("Pattern scan FAILED: CancelAttack prologue not found"); + return; + } + + int cancelVA = textBaseVA + cancelFuncOff; + Log($"CancelAttack found at 0x{cancelVA:X8}"); + + // ── Step 2: Search near CancelAttack for the others ──────── + // All CM_Combat::Event_* functions cluster within ~0x500 bytes + int regionStart = Math.Max(0, cancelOpcodeOff - 0x500); + int regionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x500); + + // ChangeCombatMode: opcode 0x53 (unique in CM_Combat region) + byte[] changeModeOpcode = { 0xC7, 0x02, 0x53, 0x00, 0x00, 0x00 }; + int changeModeOff = FindPatternInRegion(text, changeModeOpcode, regionStart, regionEnd); + int changeModeFuncOff = changeModeOff >= 0 ? FindPrologueBefore(text, changeModeOff) : -1; + + // QueryHealth: opcode 0x1BF (unique in entire binary) + byte[] queryHealthOpcode = { 0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00 }; + int queryHealthOff = FindPatternInRegion(text, queryHealthOpcode, regionStart, regionEnd); + int queryHealthFuncOff = queryHealthOff >= 0 ? FindPrologueBefore(text, queryHealthOff) : -1; + + // MeleeAttack: opcode 0x08 (common globally, but unique in CM_Combat region) + byte[] meleeOpcode = { 0xC7, 0x02, 0x08, 0x00, 0x00, 0x00 }; + int meleeOff = FindPatternInRegion(text, meleeOpcode, regionStart, regionEnd); + int meleeFuncOff = meleeOff >= 0 ? FindPrologueBefore(text, meleeOff) : -1; + + // MissileAttack: opcode 0x0A (search in CM_Combat region only) + byte[] missileOpcode = { 0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00 }; + int missileOff = FindPatternInRegion(text, missileOpcode, regionStart, regionEnd); + int missileFuncOff = missileOff >= 0 ? FindPrologueBefore(text, missileOff) : -1; + + // ── Step 3: Verify all found ─────────────────────────────── + if (changeModeFuncOff < 0 || queryHealthFuncOff < 0 || + meleeFuncOff < 0 || missileFuncOff < 0) + { + Log($"Pattern scan INCOMPLETE: CancelAttack=OK, " + + $"ChangeCombatMode={changeModeFuncOff >= 0}, " + + $"QueryHealth={queryHealthFuncOff >= 0}, " + + $"MeleeAttack={meleeFuncOff >= 0}, " + + $"MissileAttack={missileFuncOff >= 0}"); + return; + } + + int changeModeVA = textBaseVA + changeModeFuncOff; + int queryHealthVA = textBaseVA + queryHealthFuncOff; + int meleeVA = textBaseVA + meleeFuncOff; + int missileVA = textBaseVA + missileFuncOff; + + Log($"ChangeCombatMode at 0x{changeModeVA:X8}"); + Log($"QueryHealth at 0x{queryHealthVA:X8}"); + Log($"MeleeAttack at 0x{meleeVA:X8}"); + Log($"MissileAttack at 0x{missileVA:X8}"); + + // Verify all have the expected prologue bytes + if (!VerifyPrologue(text, cancelFuncOff) || + !VerifyPrologue(text, changeModeFuncOff) || + !VerifyPrologue(text, queryHealthFuncOff) || + !VerifyPrologue(text, meleeFuncOff) || + !VerifyPrologue(text, missileFuncOff)) + { + Log("Pattern scan FAILED: prologue verification failed"); + return; + } + + // ── Step 4: Create delegates ─────────────────────────────── + _cancelAttack = (DelCancelAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(cancelVA), typeof(DelCancelAttack)); + _changeCombatMode = (DelChangeCombatMode)Marshal.GetDelegateForFunctionPointer( + new IntPtr(changeModeVA), typeof(DelChangeCombatMode)); + _queryHealth = (DelQueryHealth)Marshal.GetDelegateForFunctionPointer( + new IntPtr(queryHealthVA), typeof(DelQueryHealth)); + _meleeAttack = (DelTargetedMeleeAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(meleeVA), typeof(DelTargetedMeleeAttack)); + _missileAttack = (DelTargetedMissileAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(missileVA), typeof(DelTargetedMissileAttack)); + + _initialized = true; + Log("CombatActionHelper initialized — all 5 CM_Combat functions found via pattern scan"); + } + catch (Exception ex) + { + _initialized = false; + Log("CombatActionHelper init FAILED: " + ex.Message); + } + } + + public static bool IsInitialized => _initialized; + + // ══════════════════════════════════════════════════════════════════════ + // PUBLIC API + // ══════════════════════════════════════════════════════════════════════ + + public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel) + { + if (!_initialized) return false; + try + { + return _meleeAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, powerLevel))); + } + catch (Exception ex) { Log("MeleeAttack failed: " + ex.Message); return false; } + } + + public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel) + { + if (!_initialized) return false; + try + { + return _missileAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, accuracyLevel))); + } + catch (Exception ex) { Log("MissileAttack failed: " + ex.Message); return false; } + } + + public static bool ChangeCombatMode(int combatMode) + { + if (!_initialized) return false; + try { return _changeCombatMode(combatMode); } + catch (Exception ex) { Log("ChangeCombatMode failed: " + ex.Message); return false; } + } + + public static bool CancelAttack() + { + if (!_initialized) return false; + try { return _cancelAttack(); } + catch (Exception ex) { Log("CancelAttack failed: " + ex.Message); return false; } + } + + public static bool QueryHealth(uint targetId) + { + if (!_initialized) return false; + try { return _queryHealth(targetId); } + catch (Exception ex) { Log("QueryHealth failed: " + ex.Message); return false; } + } + + /// <summary> + /// Maps UISettings height (0=Low, 1=Medium, 2=High) to AC ATTACK_HEIGHT enum. + /// </summary> + public static int MapAttackHeight(int uiHeight) + { + switch (uiHeight) + { + case 0: return ATTACK_HEIGHT_LOW; + case 2: return ATTACK_HEIGHT_HIGH; + default: return ATTACK_HEIGHT_MEDIUM; + } + } + + // ══════════════════════════════════════════════════════════════════════ + // PATTERN SCANNER + // ══════════════════════════════════════════════════════════════════════ + + private static int FindPattern(byte[] data, byte[] pattern) + { + return FindPatternInRegion(data, pattern, 0, data.Length); + } + + private static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end) + { + int limit = Math.Min(end, data.Length) - pattern.Length; + for (int i = Math.Max(0, start); i <= limit; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) + { + match = false; + break; + } + } + if (match) return i; + } + return -1; + } + + /// <summary> + /// Walks backwards from an opcode write to find the CM_Combat function prologue. + /// Must be preceded by CC (int3), 90 (nop), or C3 (ret). + /// </summary> + private static int FindPrologueBefore(byte[] data, int opcodeOffset) + { + for (int back = 1; back < 300; back++) + { + int pos = opcodeOffset - back; + if (pos < 1 || pos + CM_COMBAT_PROLOGUE.Length > data.Length) + continue; + + bool match = true; + for (int j = 0; j < CM_COMBAT_PROLOGUE.Length; j++) + { + if (data[pos + j] != CM_COMBAT_PROLOGUE[j]) + { + match = false; + break; + } + } + + if (match) + { + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + } + return -1; + } + + private static bool VerifyPrologue(byte[] data, int offset) + { + if (offset < 0 || offset + CM_COMBAT_PROLOGUE.Length > data.Length) + return false; + for (int i = 0; i < CM_COMBAT_PROLOGUE.Length; i++) + { + if (data[offset + i] != CM_COMBAT_PROLOGUE[i]) + return false; + } + return true; + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/CombatManager.cs b/Plugins/RynthAi/Combat/CombatManager.cs new file mode 100644 index 0000000..d248ee7 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatManager.cs @@ -0,0 +1,1302 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using NexSuite.Plugins.RynthAi.Raycasting; + +namespace NexSuite.Plugins.RynthAi +{ + public class CombatManager : IDisposable + { + private CoreManager _coreManager; + private PluginHost _host; + private RynthAiUI _ui; + private UISettings _settings; + private SpellManager _spellManager; + + private MainLogic _raycastSystem; + public bool RaycastInitialized { get; private set; } + + public int activeTargetId = 0; + private DateTime lastAttackCmd = DateTime.MinValue; + private DateTime lastStanceAttempt = DateTime.MinValue; + private DateTime _lastPeaceAttempt = DateTime.MinValue; + private DateTime lastTargetSearchTime = DateTime.MinValue; + private const int TARGET_SEARCH_INTERVAL_MS = 500; + + // --- Magic Combat --- + private DateTime _lastSpellCast = DateTime.MinValue; + private const double SPELL_CAST_COOLDOWN_MS = 1500.0; // Debuff cast recovery + private const double ATTACK_SPELL_COOLDOWN_MS = 100.0; // War/void spam as fast as possible + + // Flag: when melee/missile needs debuffs, we temporarily switch to wand. + // After debuffs are done, switch back. + private bool _returnToPhysicalCombat = false; + private int _savedWeaponId = 0; // Weapon to re-equip after debuffs + + // Element vulnerability spell bases (used by V light) + private static readonly Dictionary<string, string[]> VulnSpells = new Dictionary<string, string[]>(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 Dictionary<int, BlacklistedTarget> blacklistedTargets = new Dictionary<int, BlacklistedTarget>(); + + // Configurable blacklist manager — uses UISettings.BlacklistAttempts/BlacklistTimeoutSec + private Raycasting.BlacklistManager _blacklistManager = new Raycasting.BlacklistManager(); + private DateTime _lastAttackFeedbackCheck = DateTime.MinValue; + private int _lastAttackedTargetId = 0; + + public int RaycastBlockCount { get; private set; } + public int RaycastCheckCount { get; private set; } + + + + private class BlacklistedTarget + { + public int TargetId { get; set; } + public DateTime BlacklistedTime { get; set; } + public bool IsLosBlocked { get; set; } + public bool IsExpired() + { + // LOS-blocked targets get a shorter blacklist (5s) since player moves + double duration = IsLosBlocked ? 5000 : 20000; + return (DateTime.Now - BlacklistedTime).TotalMilliseconds > duration; + } + } + + public CombatManager(CoreManager coreManager, UISettings settings, PluginHost host = null, SpellManager spellManager = null) + { + _coreManager = coreManager ?? throw new ArgumentNullException(nameof(coreManager)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _host = host; + _spellManager = spellManager; + } + + public void SetSpellManager(SpellManager spellManager) + { + _spellManager = spellManager; + } + + // --- Monster Weaknesses (from monsters.json) --- + private Dictionary<string, string> _monsterWeaknesses = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + + public void SetMonsterWeaknesses(Dictionary<string, string> weaknesses) + { + _monsterWeaknesses = weaknesses ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + } + + // --- Debuff tracking (chat-driven: spam until confirmed) --- + // Tracks which debuffs have been CONFIRMED on the current target via chat + // Key: "targetId_debuffKey" — only added on "You cast X" chat message + private HashSet<string> _confirmedDebuffs = new HashSet<string>(); + private int _lastDebuffTargetId = 0; + + // Pending debuff: cast sent, waiting for chat result + 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; // Safety: assume success after 3s + + // Debuff spell definitions — base name for tiered resolution, plus optional lore name + // Format: { key, (tieredBase, loreName) } + // Resolver order: Incantation of [base] → [lore] → [base] VII → VI → ... → I + private static readonly Dictionary<string, string[]> DebuffSpells = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // { key, { tieredBase, loreName } } + { "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" } }, + }; + + // Spell shape base names for war/void + // Arc spells: "X Arc" pattern + // Ring spells: "X Ring" pattern (+ lore names for T6/T7/T8) + // Streak spells: "X Streak" pattern + // Bolt spells: "X Bolt" pattern (default) + private static readonly Dictionary<string, string[]> SpellShapes = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // element → { Arc, Ring, Streak, Bolt } base patterns + { "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" } }, + }; + + // Ring spell LORE NAMES — AC ring spells use unique names at T6/T7 + // These don't follow the standard "Base VII" pattern + // Format: element → { T6 lore, T7 lore } + private static readonly Dictionary<string, string[]> RingLoreNames = new Dictionary<string, string[]>(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[] { "Nuhumudira's Spines", "Nuhumudira's Spines II" } }, + { "Bludgeon", new[] { "Tectonic Rifts", "Tectonic Rifts II" } }, + }; + + // Void Magic equivalents + private static readonly Dictionary<string, string[]> VoidSpellShapes = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + { "Nether", new[] { "Nether Arc", "Nether Ring", "Nether Streak", "Nether Bolt" } }, + { "Fire", new[] { "Corrosion Arc", "Corrosion Ring", "Corrosion Streak", "Nether Bolt" } }, + }; + + 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; } + } + + public void AttachUI(RynthAiUI ui) { _ui = ui; } + + /// <summary> + /// Called by PluginCore when chat messages arrive. Tracks debuff results: + /// "You cast X on Y" → SUCCESS → add to confirmed set, immediately ready for next + /// "Your spell fizzled" → FIZZLE → clear pending, recast same debuff + /// "Y resists your spell" → RESIST → clear pending, recast same debuff + /// </summary> + public void HandleChatForDebuffs(string text) + { + if (!_waitingForDebuffResult || string.IsNullOrEmpty(text)) return; + + // SUCCESS: "You cast Incantation of Imperil Other on Drudge Skulker" + if (text.StartsWith("You cast ", StringComparison.OrdinalIgnoreCase)) + { + string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; + _confirmedDebuffs.Add(key); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // FIZZLE: "Your spell fizzled." + if (text.IndexOf("fizzle", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Fizzled: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // RESIST: "X resists your spell" + if (text.IndexOf("resists your spell", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Resisted: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + } + + /// <summary> + /// Called by PluginCore when a health ratio update is received for a target. + /// Clears the blacklist failure counter since the mob is taking damage. + /// </summary> + public void ReportDamageOnTarget(int targetId) + { + _blacklistManager.ClearFailure(targetId); + } + + /// <summary> + /// Called internally after an attack command is sent. If no damage feedback + /// arrives within a window, the next attack attempt increments the failure count. + /// </summary> + private void TrackAttackAttempt(int targetId) + { + if (_lastAttackedTargetId != 0 && _lastAttackedTargetId == targetId) + { + // We attacked this same target last tick too — if no damage feedback + // was received since last attack, count it as a failure + if (_lastAttackFeedbackCheck != DateTime.MinValue && + (DateTime.Now - _lastAttackFeedbackCheck).TotalMilliseconds > 2500) + { + _blacklistManager.ReportFailure(targetId); + if (_blacklistManager.IsBlacklisted(targetId)) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Blacklisted mob (no damage feedback): id={targetId}", 2); } catch { } + } + } + } + _lastAttackedTargetId = targetId; + _lastAttackFeedbackCheck = DateTime.Now; + } + + public bool Think() + { + if (!_settings.EnableCombat) return false; + + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + CleanupExpiredBlacklist(); + + // Sync configurable blacklist settings from UI + _blacklistManager.AttemptThreshold = _settings.BlacklistAttempts; + _blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec; + + // Update raycast scan distance: MonsterRange + 40m buffer + // MonsterRange is in yards ≈ meters. Convert to actual meters for the scan radius. + if (_raycastSystem?.TargetingFSM != null) + _raycastSystem.TargetingFSM.MaxScanDistanceMeters = _settings.MonsterRange + 40.0f; + + // Validate current target + if (activeTargetId != 0) + { + var target = _coreManager.WorldFilter[activeTargetId]; + if (target == null || (int)target.ObjectClass != 5 || blacklistedTargets.ContainsKey(activeTargetId) || _blacklistManager.IsBlacklisted(activeTargetId)) + activeTargetId = 0; + // Target lock: don't drop a target we're actively fighting just because + // it moved slightly. Use 1.5x range for disengage so we finish the kill. + else if (_coreManager.WorldFilter.Distance(_coreManager.CharacterFilter.Id, activeTargetId) > acDistanceLimit * 1.5) + activeTargetId = 0; + } + + // Find a new target if we don't have one + if (activeTargetId == 0) + { + if ((DateTime.Now - lastTargetSearchTime).TotalMilliseconds > TARGET_SEARCH_INTERVAL_MS) + { + HandleCombatTrigger(); + lastTargetSearchTime = DateTime.Now; + } + + if (activeTargetId == 0 && _settings.PeaceModeWhenIdle) + { + if (_coreManager.Actions.CombatMode != Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 2000) + { + _coreManager.Actions.SetCombatMode(Decal.Adapter.Wrappers.CombatState.Peace); + _lastPeaceAttempt = DateTime.Now; + } + } + } + return true; + } + + var targetObj = _coreManager.WorldFilter[activeTargetId]; + if (targetObj == null) { activeTargetId = 0; return true; } + + // If still in Peace mode, force combat mode based on what's equipped + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 1500) + { + _lastPeaceAttempt = DateTime.Now; + EquipWeaponAndSetStance(targetObj, "Auto"); + + // If STILL in peace, scan equipped items and force the right stance + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + foreach (var inv in _coreManager.WorldFilter.GetInventory()) + { + if (inv.Values(LongValueKey.EquippedSlots, 0) <= 0) continue; + if (inv.ObjectClass == ObjectClass.WandStaffOrb) + { _coreManager.Actions.SetCombatMode(CombatState.Magic); break; } + else if (inv.ObjectClass == ObjectClass.MeleeWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Melee); break; } + else if (inv.ObjectClass == ObjectClass.MissileWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Missile); break; } + } + } + } + return true; // Yield this tick — let stance change process + } + + if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= 1000) + { + // LOS gate: verify EVERY shot + if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null) + { + // Determine attack type: weapon-based for melee/missile, shape-based for magic + TargetingFSM.AttackType attackType = DetermineAttackTypeForLOS(targetObj); + + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, targetObj, attackType)) + { + RaycastBlockCount++; + try { _host?.Actions?.AddChatText($"[RynthAi] LOS blocked: {targetObj.Name} — dropping", 1); } catch { } + activeTargetId = 0; + return true; + } + } + + FaceTarget(targetObj); + _coreManager.Actions.SelectItem(activeTargetId); + + // MAGIC COMBAT: If we're in magic mode with a wand, cast spells + if (_coreManager.Actions.CombatMode == CombatState.Magic && _spellManager != null) + { + AttackWithMagic(targetObj); + + // If we were in magic mode for debuffs only, check if done → switch back + if (_returnToPhysicalCombat) + { + var rule2 = GetRuleForTarget(targetObj); + string elem2 = GetPreferredElement(targetObj, rule2); + if (rule2 != null && !HasPendingDebuffs(rule2, elem2)) + { + // All debuffs confirmed — switch back to physical weapon + _returnToPhysicalCombat = false; + if (_savedWeaponId != 0) + { + _coreManager.Actions.UseItem(_savedWeaponId, 0); + _savedWeaponId = 0; + } + EquipWeaponAndSetStance(targetObj, "Auto"); + } + } + } + else + { + // Melee / Missile mode + var rule = GetRuleForTarget(targetObj); + + // Check if debuffs need casting before physical attack + if (rule != null && _spellManager != null && !_returnToPhysicalCombat) + { + string elem = GetPreferredElement(targetObj, rule); + if (HasPendingDebuffs(rule, elem)) + { + // Find wand in ItemRules to cast debuffs + int wandId = FindWandInItems(); + if (wandId != 0) + { + // Save current weapon, switch to wand for debuffs + var equipped = _coreManager.WorldFilter.GetInventory() + .FirstOrDefault(w => w.Values(LongValueKey.EquippedSlots, 0) > 0 && + (w.ObjectClass == ObjectClass.MeleeWeapon || w.ObjectClass == ObjectClass.MissileWeapon)); + _savedWeaponId = equipped?.Id ?? 0; + _returnToPhysicalCombat = true; + _coreManager.Actions.UseItem(wandId, 0); + _coreManager.Actions.SetCombatMode(CombatState.Magic); + lastAttackCmd = DateTime.Now; + return true; // Yield — next tick will be in magic mode + } + } + } + + bool anyAttackLight = (rule == null) || rule.UseArc || rule.UseBolt || rule.UseRing || rule.UseStreak; + if (!anyAttackLight) + { + // No attack shape selected — do not attack in melee/missile mode + } + else + { + AttackTarget(); + } + } + TrackAttackAttempt(activeTargetId); + lastAttackCmd = DateTime.Now; + } + return true; + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + + // === YIELD to any higher-priority system that has claimed the state === + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Combat") return; + + if (_settings.EnableCombat) + { + Think(); + + // If Think() found or maintained a target, we are in combat + if (activeTargetId != 0) + { + _settings.CurrentState = "Combat"; + var target = _coreManager.WorldFilter[activeTargetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + // If no target, leave state as-is (dispatcher resets to Idle each frame) + } + } + + public void HandleCombatTrigger() + { + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + + // For target SEARCH, use weapon/mode-based attack type (no specific rule yet) + TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear; + if (RaycastInitialized && _raycastSystem?.TargetingFSM != null) + attackType = _raycastSystem.GetAttackType(_coreManager); + + int targetId = FindBestVisibleTarget(acDistanceLimit, attackType); + if (targetId != 0 && targetId != activeTargetId) + { + activeTargetId = targetId; + + var target = _coreManager.WorldFilter[targetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + } + + private int FindBestVisibleTarget(double maxDist, TargetingFSM.AttackType attackType) + { + int foundId = 0; + int playerId = _coreManager.CharacterFilter.Id; + var candidates = new List<KeyValuePair<int, double>>(); + + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5 || blacklistedTargets.ContainsKey(wo.Id) || _blacklistManager.IsBlacklisted(wo.Id)) continue; + double dist = _coreManager.WorldFilter.Distance(playerId, wo.Id); + if (dist <= maxDist) candidates.Add(new KeyValuePair<int, double>(wo.Id, dist)); + } + + candidates.Sort((a, b) => a.Value.CompareTo(b.Value)); + + foreach (var candidate in candidates) + { + int id = candidate.Key; + if (_settings.EnableRaycasting && RaycastInitialized) + { + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, _coreManager.WorldFilter[id], attackType)) + { + RaycastBlockCount++; + continue; + } + } + foundId = id; + break; + } + return foundId; + } + + private DateTime _lastEquipTime = DateTime.MinValue; + private DateTime _lastStanceTime = DateTime.MinValue; + + private void EquipWeaponAndSetStance(WorldObject target, string monsterWeakness = "Auto") + { + if (target == null) return; + + int targetWeaponId = 0; + + // 1. Target Resolution + 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; + + if (rule != null && rule.WeaponId != 0) + { + targetWeaponId = rule.WeaponId; + } + else + { + var bestWeapon = _settings.ItemRules.FirstOrDefault(i => i.Element.Equals(desired, StringComparison.OrdinalIgnoreCase)) + ?? _settings.ItemRules.FirstOrDefault(); + if (bestWeapon != null) targetWeaponId = bestWeapon.Id; + } + + if (targetWeaponId == 0) return; + + var weaponObj = _coreManager.WorldFilter[targetWeaponId]; + if (weaponObj == null) return; + + // 2. Equipment Enforcement + bool isEquipped = weaponObj.Values(LongValueKey.EquippedSlots, 0) > 0; + + if (!isEquipped) + { + // Reverted to 1000ms (1 second) to prevent bare-hand attacks during slow animations + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 1000) + { + _coreManager.Actions.UseItem(targetWeaponId, 0); + _lastEquipTime = DateTime.Now; + _lastStanceTime = DateTime.Now; // Reset stance timer to sync with new equip + } + return; + } + + // 3. Stance Enforcement + // Increased to 1000ms to allow the server to finish the "Draw Weapon" animation + if ((DateTime.Now - _lastStanceTime).TotalMilliseconds > 1000) + { + bool changedStance = false; + + if (weaponObj.ObjectClass == ObjectClass.MeleeWeapon && _coreManager.Actions.CombatMode != CombatState.Melee) + { + _coreManager.Actions.SetCombatMode(CombatState.Melee); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.MissileWeapon && _coreManager.Actions.CombatMode != CombatState.Missile) + { + _coreManager.Actions.SetCombatMode(CombatState.Missile); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.WandStaffOrb && _coreManager.Actions.CombatMode != CombatState.Magic) + { + _coreManager.Actions.SetCombatMode(CombatState.Magic); + changedStance = true; + } + + if (changedStance) _lastStanceTime = DateTime.Now; + } + } + + 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<string> GetRaycastDiagLog() + { + var lines = new List<string>(); + if (_raycastSystem?.GeometryLoader?.DiagLog != null) + foreach (var line in _raycastSystem.GeometryLoader.DiagLog) lines.Add(line); + return lines; + } + + /// <summary> + /// Determines the correct LOS check type based on combat mode and spell shape. + /// - Magic + Arc spell shape → MagicArc (same trajectory as missiles) + /// - Magic + Bolt/Streak/Ring → Linear (straight line) + /// - Missile mode → delegates to FSM (BowArc, ThrownArc, or Linear for crossbow) + /// - Melee/Peace → Linear + /// </summary> + private TargetingFSM.AttackType DetermineAttackTypeForLOS(WorldObject target) + { + // Magic mode: check spell shape from monster rule + if (_coreManager.Actions.CombatMode == CombatState.Magic) + { + var rule = GetRuleForTarget(target); + if (rule != null && rule.UseArc) + return TargetingFSM.AttackType.MagicArc; + + // Bolts, Streaks, Rings = straight line + return TargetingFSM.AttackType.Linear; + } + + // Missile/Melee: use weapon-based detection + if (_raycastSystem?.TargetingFSM != null) + return _raycastSystem.GetAttackType(_coreManager); + + return TargetingFSM.AttackType.Linear; + } + + private void FaceTarget(WorldObject target) + { + try + { + var p = _coreManager.WorldFilter[_coreManager.CharacterFilter.Id]; + double dx = target.Coordinates().EastWest - p.Coordinates().EastWest; + double dy = target.Coordinates().NorthSouth - p.Coordinates().NorthSouth; + double heading = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (heading < 0) heading += 360.0; + _coreManager.Actions.Heading = (float)heading; + } + catch { } + } + + private void AttackTarget() + { + try + { + if (!CombatActionHelper.IsInitialized) return; + + bool isMissile = _coreManager.Actions.CombatMode == CombatState.Missile; + uint targetId = (uint)activeTargetId; + + // Resolve attack power (0.0–1.0) + int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower; + float power; + if (powerPct < 0) + { + // Auto mode: 100% unless Recklessness is enabled and trained + power = 1.0f; + if (_settings.UseRecklessness) + { + try + { + int reckTraining = (int)_coreManager.CharacterFilter + .Skills[CharFilterSkillType.Recklessness].Training; + if (reckTraining >= 2) // Trained or Specialized + power = 0.8f; + } + catch { } + } + } + else + { + power = powerPct / 100f; + } + + // Map UI height (0=Low,1=Med,2=High) → AC ATTACK_HEIGHT enum + int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight; + int acHeight = CombatActionHelper.MapAttackHeight(uiHeight); + + // Send attack directly via acclient.exe CM_Combat functions + if (isMissile) + CombatActionHelper.MissileAttack(targetId, acHeight, power); + else + CombatActionHelper.MeleeAttack(targetId, acHeight, power); + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // MAGIC COMBAT SYSTEM + // Supports: debuff lights (F/B/G/I/Y/V), spell shapes (A/R/S/B=default Bolt), + // monsters.json weakness lookup, War + Void magic + // If none of A/R/S/B are set → no attack (buff bot mode) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Resolves the MonsterRule for a target (specific rule first, then Default). + /// Cached per-target so we don't re-scan every frame. + /// </summary> + private MonsterRule GetRuleForTarget(WorldObject target) + { + if (target == null) return null; + // Specific name match first + var rule = _settings.MonsterRules.FirstOrDefault( + r => !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && + target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + if (rule != null) return rule; + // Fall back to Default + return _settings.MonsterRules.FirstOrDefault( + m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + private void AttackWithMagic(WorldObject target) + { + if (_spellManager == null || target == null) return; + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < SPELL_CAST_COOLDOWN_MS) return; + + // If waiting for debuff result, check timeout only + if (_waitingForDebuffResult) + { + if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS) + { + // Timed out — assume success, add to confirmed + _confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}"); + _waitingForDebuffResult = false; + } + else + { + return; // Still waiting for chat — don't cast anything + } + } + + // Clear confirmed debuffs if target changed + if (activeTargetId != _lastDebuffTargetId) + { + _confirmedDebuffs.Clear(); + _lastDebuffTargetId = activeTargetId; + } + + var rule = GetRuleForTarget(target); + string element = GetPreferredElement(target, rule); + + // ── Phase 1: Debuffs — spam until chat confirms each one ── + if (rule != null) + { + var pendingDebuffs = BuildDebuffList(rule, element); + + foreach (var debuffKey in pendingDebuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + + if (_confirmedDebuffs.Contains(key)) + continue; // Chat confirmed this one — move on + + 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 + { + _coreManager.Actions.CastSpell(spellId, activeTargetId); + _lastSpellCast = DateTime.Now; + _pendingDebuffKey = debuffKey; + _pendingDebuffTargetId = activeTargetId; + _pendingDebuffTier = castTier; + _waitingForDebuffResult = true; + _pendingDebuffCastTime = DateTime.Now; + try { _host?.Actions?.AddChatText($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5); } catch { } + } + catch { } + return; // Wait for chat result + } + } + + // ── Phase 2: War/Void spell spam — faster cooldown ── + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < ATTACK_SPELL_COOLDOWN_MS) return; + + if (rule != null && !rule.UseArc && !rule.UseRing && !rule.UseStreak && !rule.UseBolt) + return; + + int offensiveSpellId = FindBestShapedSpell(element, rule); + if (offensiveSpellId != 0) + { + try + { + _coreManager.Actions.CastSpell(offensiveSpellId, activeTargetId); + _lastSpellCast = DateTime.Now; + } + catch { } + } + else + { + AttackTarget(); + } + } + + private string GetPreferredElement(WorldObject target, MonsterRule rule) + { + // 1. Explicit element from rule + if (rule != null && !string.IsNullOrEmpty(rule.DamageType) && + !rule.DamageType.Equals("Auto", StringComparison.OrdinalIgnoreCase)) + { + return rule.DamageType; + } + + // 2. Auto: check monsters.json weakness database + if (target != null && _monsterWeaknesses != null && _monsterWeaknesses.Count > 0) + { + foreach (var entry in _monsterWeaknesses) + { + if (target.Name.IndexOf(entry.Key, StringComparison.OrdinalIgnoreCase) >= 0) + { + return entry.Value; + } + } + } + + // 3. Ultimate fallback + return "Fire"; + } + + // ── DEBUFF SYSTEM ──────────────────────────────────────────────────────── + + /// <summary> + /// Returns true if any debuff in the rule's list still needs casting on the active target. + /// </summary> + private bool HasPendingDebuffs(MonsterRule rule, string element) + { + if (rule == null) return false; + var debuffs = BuildDebuffList(rule, element); + foreach (var debuffKey in debuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + if (!_confirmedDebuffs.Contains(key)) + return true; + } + return false; + } + + /// <summary> + /// Finds the first wand/staff/orb in ItemRules for debuff casting. + /// </summary> + private int FindWandInItems() + { + foreach (var item in _settings.ItemRules) + { + var wo = _coreManager.WorldFilter[item.Id]; + if (wo != null && wo.ObjectClass == ObjectClass.WandStaffOrb) + return item.Id; + } + return 0; + } + + /// <summary> + /// Builds the ordered debuff list from a MonsterRule's lights. + /// </summary> + private List<string> BuildDebuffList(MonsterRule rule, string element) + { + var list = new List<string>(); + 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; + } + + // ── DEBUFF SPELL RESOLUTION (with tier output for duration tracking) ── + + private int FindBestDebuffSpellWithTier(string debuffType, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] spellInfo; + if (!DebuffSpells.TryGetValue(debuffType, out spellInfo) || spellInfo.Length < 2) + return 0; + + string tieredBase = spellInfo[0]; // e.g., "Imperil Other" + string loreName = spellInfo[1]; // e.g., "Gossamer Flesh" + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // 1. Tier 8: Incantation of [tieredBase] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {tieredBase}"); + if (id != 0) { tier = 8; return id; } + } + + // 2. Tier 7: Lore name (direct lookup) + if (maxTier >= 7 && !string.IsNullOrEmpty(loreName)) + { + int id = TrySpellByName(loreName); + if (id != 0) { tier = 7; return id; } + } + + // 3. Tier 7 numbered fallback, then VI → I + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + string numeral = GetRomanNumeral(t); + int id = TrySpellByName($"{tieredBase} {numeral}"); + if (id != 0) { tier = t; return id; } + } + + return 0; + } + + private int FindBestVulnSpellWithTier(string element, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] vulnBases; + if (!VulnSpells.TryGetValue(element, out vulnBases)) + return 0; + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + 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; + } + + /// <summary> + /// Tries to find a spell by exact name. Returns spell ID if known, 0 if not. + /// </summary> + private int TrySpellByName(string name) + { + int id; + if (_spellManager.SpellDictionary.TryGetValue(name, out id)) + { + if (_coreManager.CharacterFilter.IsSpellKnown(id)) + return id; + } + return 0; + } + + // ── SPELL SHAPE SELECTION (A/R/S/B lights) ────────────────────────── + + /// <summary> + /// Counts monsters within the given AC distance (yards/240). + /// </summary> + private int CountMonstersInRange(double rangeYards) + { + double acDist = rangeYards / 240.0; + int count = 0; + int playerId = _coreManager.CharacterFilter.Id; + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5) continue; + if (_coreManager.WorldFilter.Distance(playerId, wo.Id) <= acDist) + count++; + } + return count; + } + + /// <summary> + /// Finds the best offensive spell using the rule's shape lights. + /// A = Arc, R = Ring, S = Streak, B = Bolt. + /// RING OVERRIDE: If >= MinRingTargets monsters are within RingRange, forces Ring spells. + /// If none are set, returns 0 (no attack - buff bot mode). + /// Uses Void Magic for Nether element, War Magic for everything else. + /// </summary> + private int FindBestShapedSpell(string element, MonsterRule rule) + { + if (_spellManager == null) return 0; + + // Determine skill: Void or War + bool useVoid = element.Equals("Nether", StringComparison.OrdinalIgnoreCase); + // Also check if character has Void trained but not War (or vice versa) + bool warTrained = false, voidTrained = false; + try { warTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.WarMagic].Training >= 2; } catch { } + try { voidTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.VoidMagic].Training >= 2; } catch { } + + if (useVoid && !voidTrained && warTrained) useVoid = false; // fallback to war + if (!useVoid && !warTrained && voidTrained) useVoid = true; // fallback to void + + CharFilterSkillType skill = useVoid ? CharFilterSkillType.VoidMagic : CharFilterSkillType.WarMagic; + + // Determine shape index: 0=Arc, 1=Ring, 2=Streak, 3=Bolt + // Priority: A > R > S > B. If none set, caller already blocked attack. + int shapeIdx = 3; // default = Bolt + if (rule != null) + { + if (rule.UseArc) shapeIdx = 0; + else if (rule.UseRing) shapeIdx = 1; + else if (rule.UseStreak) shapeIdx = 2; + else if (rule.UseBolt) shapeIdx = 3; + else return 0; // No attack shape selected + } + + // RING OVERRIDE: only if R light is on for this rule, and enough monsters nearby + if (rule != null && rule.UseRing && _settings.MinRingTargets > 0 && _settings.RingRange > 0) + { + int nearbyCount = CountMonstersInRange(_settings.RingRange); + if (nearbyCount >= _settings.MinRingTargets) + shapeIdx = 1; // Force Ring + } + + // Look up shape patterns + var shapes = useVoid ? VoidSpellShapes : SpellShapes; + string[] elementShapes; + if (!shapes.TryGetValue(element, out elementShapes)) + { + // Fallback element + if (!SpellShapes.TryGetValue("Fire", out elementShapes)) + return 0; + skill = CharFilterSkillType.WarMagic; + } + + // Clamp index + if (shapeIdx >= elementShapes.Length) shapeIdx = elementShapes.Length - 1; + + // Try preferred shape first + // SPECIAL: Ring spells (shapeIdx==1) have unique lore names that don't follow "Base VII" pattern + if (shapeIdx == 1) + { + int ringId = FindBestRingSpell(element, skill); + if (ringId != 0) return ringId; + } + + // Standard resolution: try preferred shape, then fall back to others + int id = FindBestOffensiveSpellId(elementShapes[shapeIdx], skill); + if (id != 0) return id; + + // Fallback: try bolt (index 3), then any shape that works + for (int i = elementShapes.Length - 1; i >= 0; i--) + { + if (i == shapeIdx) continue; + id = FindBestOffensiveSpellId(elementShapes[i], skill); + if (id != 0) return id; + } + + return 0; + } + + // ── SPELL RESOLUTION ───────────────────────────────────────────────────── + + /// <summary> + /// Resolves ring spells using AC's unique lore names. + /// Order: Incantation of [lore] (T8) → [lore] II (T7) → [lore] (T6) → generic tiers V→I + /// </summary> + private int FindBestRingSpell(string element, CharFilterSkillType skill) + { + string[] loreNames; + if (!RingLoreNames.TryGetValue(element, out loreNames) || loreNames.Length < 2) + return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // T7: [lore name] II (try first — most likely to be known) + if (maxTier >= 7) + { + int id = TrySpellByName(loreNames[1]); + if (id != 0) return id; + // Try with smart apostrophe variants + id = TrySpellByName(loreNames[1].Replace("'", "\u2019")); + if (id != 0) return id; + id = TrySpellByName(loreNames[1].Replace("'", "`")); + if (id != 0) return id; + } + + // T6: [lore name] + 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; + } + + // T8: Incantation of [lore name] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {loreNames[0]}"); + if (id != 0) return id; + } + + // Fallback: try generic ring names (e.g., "Ring of Fire V") + string[] genericRingBases; + if (SpellShapes.TryGetValue(element, out genericRingBases) && genericRingBases.Length > 1) + { + string ringBase = genericRingBases[1]; // Index 1 = Ring + for (int t = Math.Min(maxTier, 5); t >= 1; t--) + { + int id = TrySpellByName($"{ringBase} {GetRomanNumeral(t)}"); + if (id != 0) return id; + } + } + + // Debug: if we get here, log what we tried + try { _host?.Actions?.AddChatText($"[RynthAi] Ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})", 2); } catch { } + return 0; + } + + /// <summary> + /// Searches for the highest tier of a spell the character knows. + /// Order: Incantation (8) → VII → VI → V → IV → III → II → I + /// Respects skill level — won't try tiers the character can't cast. + /// </summary> + private int FindBestOffensiveSpellId(string baseName, CharFilterSkillType skill) + { + if (_spellManager == null) return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // Tier 8: Incantation + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); + if (id != 0) return id; + id = TrySpellByName(baseName + " VIII"); + if (id != 0) return id; + } + + // Tiers 7 → 1 + for (int tier = Math.Min(maxTier, 7); tier >= 1; tier--) + { + string numeral = GetRomanNumeral(tier); + int id = TrySpellByName($"{baseName} {numeral}"); + if (id != 0) return id; + } + + return 0; + } + + private static string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + private void CleanupExpiredBlacklist() + { + var expired = new List<int>(); + foreach (var kvp in blacklistedTargets) if (kvp.Value.IsExpired()) expired.Add(kvp.Key); + foreach (var id in expired) blacklistedTargets.Remove(id); + // _confirmedDebuffs is cleared automatically when target changes + } + + + + public void Dispose() { _raycastSystem?.Dispose(); } + + /// <summary> + /// Diagnostic: runs a full LOS test against the currently selected target + /// and reports all coordinates, geometry volumes, and intersection results. + /// </summary> + public List<string> RunLosTestDiag(CoreManager core) + { + var lines = new List<string>(); + try + { + if (_raycastSystem == null || !RaycastInitialized) + { + lines.Add("Raycast system not initialized"); + return lines; + } + + int targetId = core.Actions.CurrentSelection; + if (targetId == 0) + { + lines.Add("No target selected — select a monster first"); + return lines; + } + + var target = core.WorldFilter[targetId]; + if (target == null) + { + lines.Add($"Target {targetId} not found in WorldFilter"); + return lines; + } + + lines.Add($"Target: {target.Name} (id={targetId})"); + + // Player position + uint landcell = (uint)core.Actions.Landcell; + uint blockX = (landcell >> 24) & 0xFF; + uint blockY = (landcell >> 16) & 0xFF; + float locX = (float)core.Actions.LocationX; + float locY = (float)core.Actions.LocationY; + float locZ = (float)core.Actions.LocationZ; + float playerGX = blockX * 192.0f + locX; + float playerGY = blockY * 192.0f + locY; + lines.Add($"Player Landcell=0x{landcell:X8} Block=({blockX},{blockY})"); + lines.Add($"Player Local=({locX:F1},{locY:F1},{locZ:F1})"); + lines.Add($"Player Global=({playerGX:F1},{playerGY:F1},{locZ:F1})"); + + // Target position + var coords = target.Coordinates(); + double ew = coords.EastWest; + double ns = coords.NorthSouth; + float targetGX = (float)((ew * 10.0 + 1019.5) * 24.0); + float targetGY = (float)((ns * 10.0 + 1019.5) * 24.0); + float targetZ = locZ; // approximate + try { targetZ = (float)target.RawCoordinates().Z; } catch { } + lines.Add($"Target EW={ew:F3} NS={ns:F3}"); + lines.Add($"Target Global=({targetGX:F1},{targetGY:F1},{targetZ:F1})"); + + float dx = targetGX - playerGX; + float dy = targetGY - playerGY; + float dist = (float)Math.Sqrt(dx * dx + dy * dy); + lines.Add($"Distance: {dist:F1}m, Delta=({dx:F1},{dy:F1})"); + + // Load geometry + var geometry = _raycastSystem.GeometryLoader.GetLandblockGeometry(landcell); + lines.Add($"Geometry: {geometry?.Count ?? 0} volumes loaded"); + + if (geometry != null && geometry.Count > 0) + { + var origin = new Raycasting.Vector3(playerGX, playerGY, locZ + 1.0f); + var targetPos = new Raycasting.Vector3(targetGX, targetGY, targetZ + 1.0f); + + var rayDir = targetPos - origin; + float rayLen = rayDir.Length(); + if (rayLen > 0.001f) rayDir = rayDir / rayLen; + + float pathMinX = Math.Min(playerGX, targetGX) - 15f; + float pathMaxX = Math.Max(playerGX, targetGX) + 15f; + float pathMinY = Math.Min(playerGY, targetGY) - 15f; + float pathMaxY = Math.Max(playerGY, targetGY) + 15f; + + int nearCount = 0; + int hitCount = 0; + var hitVolumes = new List<string>(); + var nearVolumes = new List<string>(); + + foreach (var vol in geometry) + { + bool nearPath = vol.Center.X >= pathMinX && vol.Center.X <= pathMaxX && + vol.Center.Y >= pathMinY && vol.Center.Y <= pathMaxY; + + float volDist; + bool hit = vol.RayIntersect(origin, rayDir, rayLen, out volDist); + + if (hit) hitCount++; + if (nearPath) nearCount++; + + // ALWAYS capture hitting volumes + if (hit && hitVolumes.Count < 10) + { + hitVolumes.Add($" ** HIT at {volDist:F2}yd: center=({vol.Center.X:F1},{vol.Center.Y:F1},{vol.Center.Z:F1}) " + + $"dim=({vol.Dimensions.X:F1},{vol.Dimensions.Y:F1},{vol.Dimensions.Z:F1}) type={vol.Type}"); + } + + if (nearPath && !hit && nearVolumes.Count < 10) + { + nearVolumes.Add($" NEAR: center=({vol.Center.X:F0},{vol.Center.Y:F0},{vol.Center.Z:F0}) " + + $"r={vol.Dimensions.X:F1} type={vol.Type}"); + } + } + + // Show hits first + if (hitVolumes.Count > 0) + { + lines.Add("=== BLOCKING VOLUMES ==="); + foreach (var hv in hitVolumes) lines.Add(hv); + } + + if (nearVolumes.Count > 0) + { + lines.Add($"=== NEAR (non-hit, showing {nearVolumes.Count} of {nearCount}) ==="); + foreach (var nv in nearVolumes) lines.Add(nv); + } + + if (hitVolumes.Count == 0 && nearVolumes.Count == 0) + lines.Add(" NO volumes found near path!"); + + lines.Add($"Summary: {geometry.Count} total, {nearCount} near path, {hitCount} ray hits"); + + bool nearby = Raycasting.RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry); + bool blocked = Raycasting.RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + lines.Add($"HasNearbyGeometry: {nearby}"); + lines.Add($"IsLinearPathBlocked: {blocked}"); + } + } + catch (Exception ex) + { + lines.Add($"Error: {ex.Message}"); + } + return lines; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthAi/Combat/FellowshipTracker.cs new file mode 100644 index 0000000..ab1a797 --- /dev/null +++ b/Plugins/RynthAi/Combat/FellowshipTracker.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Decal.Adapter; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Reads fellowship membership directly from AC client memory. + /// + /// Memory layout (from UB's AcClient structs / acclient.exe analysis): + /// + /// Static pointers: + /// 0x0087150C = ClientFellowshipSystem** s_pFellowshipSystem + /// 0x00844C08 = UInt32* player_iid (our character ID) + /// + /// ClientFellowshipSystem: + /// +0x10 = CFellowship* m_pFellowship (null if not in fellowship) + /// + /// CFellowship / Fellowship: + /// +0x0C = PackableHashData** _buckets (hash table bucket array) + /// +0x10 = UInt32 _table_size (number of buckets) + /// +0x14 = UInt32 _currNum (member count) + /// +0x18 = PStringBase _name (fellowship name, char*) + /// +0x1C = UInt32 _leader (leader character ID) + /// +0x20 = int _share_xp + /// +0x24 = int _even_xp_split + /// +0x28 = int _open_fellow + /// +0x2C = int _locked + /// + /// PackableHashData (hash table entry for each member): + /// +0x00 = UInt32 _key (member character ID) + /// +0x04 = Fellow _data: + /// +0x04 = Fellow.PackObj vtable (4 bytes) + /// +0x08 = Fellow._name (PStringBase = char*, 4 bytes) + /// +0x0C = Fellow._level (UInt32) + /// +0x1C = Fellow._share_loot (int) + /// +0x20 = Fellow._max_health (UInt32) + /// +0x28 = Fellow._max_mana (UInt32) + /// +0x2C = Fellow._current_health (UInt32) + /// +0x34 = PackableHashData* _next (next in chain, null = end) + /// </summary> + public class FellowshipTracker : IDisposable + { + // Static memory addresses in acclient.exe + private static readonly IntPtr ADDR_FELLOWSHIP_SYSTEM = new IntPtr(0x0087150C); + private static readonly IntPtr ADDR_PLAYER_IID = new IntPtr(0x00844C08); + + // Struct offsets + private const int OFF_SYS_FELLOWSHIP = 0x10; // ClientFellowshipSystem → m_pFellowship + private const int OFF_FEL_BUCKETS = 0x0C; // Fellowship → _buckets + private const int OFF_FEL_TABLE_SIZE = 0x10; // Fellowship → _table_size + private const int OFF_FEL_CURR_NUM = 0x14; // Fellowship → _currNum + private const int OFF_FEL_NAME = 0x18; // Fellowship → _name (char*) + private const int OFF_FEL_LEADER = 0x1C; // Fellowship → _leader + private const int OFF_FEL_SHARE_XP = 0x20; // Fellowship → _share_xp + private const int OFF_FEL_EVEN_SPLIT = 0x24; // Fellowship → _even_xp_split + private const int OFF_FEL_OPEN = 0x28; // Fellowship → _open_fellow + private const int OFF_FEL_LOCKED = 0x2C; // Fellowship → _locked + + // Hash entry offsets (PackableHashData<UInt32, Fellow>) + private const int OFF_ENTRY_KEY = 0x00; // _key (member character ID) + private const int OFF_ENTRY_NAME_PTR = 0x08; // Fellow._name (char*) + private const int OFF_ENTRY_LEVEL = 0x0C; // Fellow._level + private const int OFF_ENTRY_NEXT = 0x34; // _next pointer + + // Cached member data + private Dictionary<int, string> _memberCache = new Dictionary<int, string>(); + private DateTime _lastRefresh = DateTime.MinValue; + private const double REFRESH_INTERVAL_MS = 2000; + + private CoreManager _core; + + public FellowshipTracker(CoreManager core) + { + _core = core; + } + + public void Dispose() { } + + // ══════════════════════════════════════════════════════════════ + // PUBLIC API — matches the UB expression interface + // ══════════════════════════════════════════════════════════════ + + /// <summary>True if the player is currently in a fellowship.</summary> + public bool IsInFellowship + { + get + { + try { return GetFellowshipPtr() != IntPtr.Zero; } + catch { return false; } + } + } + + /// <summary>Number of members in the current fellowship.</summary> + public int MemberCount + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + } + catch { return 0; } + } + } + + /// <summary>Name of the current fellowship.</summary> + public string FellowshipName + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return ""; + return ReadPString(fel + OFF_FEL_NAME); + } + catch { return ""; } + } + } + + /// <summary>Character ID of the fellowship leader.</summary> + public int LeaderId + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_LEADER); + } + catch { return 0; } + } + } + + /// <summary>True if the player is the fellowship leader.</summary> + public bool IsLeader + { + get + { + try + { + int leader = LeaderId; + if (leader == 0) return false; + int myId = Marshal.ReadInt32(ADDR_PLAYER_IID); + return leader == myId; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is open for recruitment.</summary> + public bool IsOpen + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_OPEN) == 1; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is locked.</summary> + public bool IsLocked + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_LOCKED) == 1; + } + catch { return false; } + } + } + + /// <summary>True if the fellowship is sharing XP.</summary> + public bool ShareXP + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_SHARE_XP) == 1; + } + catch { return false; } + } + } + + /// <summary>Check if a character name is a fellowship member.</summary> + 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; + } + + /// <summary>Check if a character ID is a fellowship member.</summary> + public bool IsMember(int characterId) + { + RefreshIfNeeded(); + return _memberCache.ContainsKey(characterId); + } + + /// <summary>Get all member names.</summary> + public IEnumerable<string> GetMemberNames() + { + RefreshIfNeeded(); + return _memberCache.Values; + } + + /// <summary>Get member name by index (0-based).</summary> + public string GetMemberName(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Value; + i++; + } + return ""; + } + + /// <summary>Get member character ID by index (0-based).</summary> + public int GetMemberId(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Key; + i++; + } + return 0; + } + + // ══════════════════════════════════════════════════════════════ + // NATIVE MEMORY READING + // ══════════════════════════════════════════════════════════════ + + /// <summary> + /// Gets the CFellowship pointer. Returns IntPtr.Zero if not in a fellowship. + /// Chain: [s_pFellowshipSystem] → ClientFellowshipSystem → [+0x10] → CFellowship + /// </summary> + private IntPtr GetFellowshipPtr() + { + int sysPtr = Marshal.ReadInt32(ADDR_FELLOWSHIP_SYSTEM); + if (sysPtr == 0) return IntPtr.Zero; + + int felPtr = Marshal.ReadInt32(new IntPtr(sysPtr + OFF_SYS_FELLOWSHIP)); + if (felPtr == 0) return IntPtr.Zero; + + return new IntPtr(felPtr); + } + + /// <summary> + /// Refreshes the member cache by iterating the hash table in client memory. + /// Only refreshes every REFRESH_INTERVAL_MS to avoid overhead. + /// </summary> + 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; + + int bucketsPtr = Marshal.ReadInt32(fel + OFF_FEL_BUCKETS); + int tableSize = Marshal.ReadInt32(fel + OFF_FEL_TABLE_SIZE); + int currNum = Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + + if (bucketsPtr == 0 || tableSize == 0 || currNum == 0) return; + + // Safety: don't iterate more than 9 members (AC fellowship max) + int maxMembers = Math.Min(currNum, 9); + int found = 0; + + // Walk each bucket in the hash table + for (int b = 0; b < tableSize && found < maxMembers; b++) + { + // Read bucket pointer: _buckets[b] + int entryPtr = Marshal.ReadInt32(new IntPtr(bucketsPtr + b * 4)); + + // Walk the chain for this bucket + while (entryPtr != 0 && found < maxMembers) + { + // Read _key (member character ID) at entry + 0x00 + int memberId = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_KEY)); + + // Read _name pointer at entry + 0x08 (Fellow._name = char*) + string name = ReadPString(new IntPtr(entryPtr + OFF_ENTRY_NAME_PTR)); + + if (memberId != 0 && !string.IsNullOrEmpty(name)) + { + _memberCache[memberId] = name; + found++; + } + + // Follow _next pointer at entry + 0x34 + entryPtr = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_NEXT)); + } + } + } + catch { } + } + + /// <summary> + /// Reads a PStringBase<char> from a memory address. + /// + /// PStringBase contains a single m_buffer pointer to PSRefBuffer<char>. + /// PSRefBuffer layout (verified from acclient.exe binary analysis — + /// PStringBase ctor at 0x48C3E0 copies chars to buf+0x14, + /// allocation helper at 0x403560 initializes the header): + /// +0x00: vtable (ReferenceCountTemplate vftable, e.g. 0x7CAE34) + /// +0x04: m_cRef (int32 — reference count) + /// +0x08: m_Length (int32 — string length INCLUDING null terminator) + /// +0x0C: m_Capacity (int32 — allocated buffer capacity) + /// +0x10: m_Hash (int32 — initialized to 0xFFFFFFFF) + /// +0x14: char[] (actual string data, null-terminated) + /// </summary> + private string ReadPString(IntPtr addr) + { + try + { + // Step 1: Read PSRefBuffer* from PStringBase.m_buffer + int bufPtr = Marshal.ReadInt32(addr); + if (bufPtr == 0) return ""; + + // Step 2: Read string data from PSRefBuffer + 0x14 (after 20-byte header) + // Use null-terminated read with safety cap at 64 chars + string raw = Marshal.PtrToStringAnsi(new IntPtr(bufPtr + 0x14)); + if (raw == null) return ""; + if (raw.Length > 64) raw = raw.Substring(0, 64); + return raw; + } + catch { return ""; } + } + } +} diff --git a/Plugins/RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthAi/Combat/MissileCraftingManager.cs new file mode 100644 index 0000000..c62d735 --- /dev/null +++ b/Plugins/RynthAi/Combat/MissileCraftingManager.cs @@ -0,0 +1,521 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Automates missile ammunition management. + /// + /// Triggers when ammo slot is empty: + /// 1. Can craft better ammo than loose inventory? → Craft (up to 2x), then equip + /// 2. Loose ammo available? → Equip best one + /// 3. Can craft anything? → Craft, then equip + /// + /// Crafting is chat-driven: issues ApplyItem, waits for "You make" chat message, + /// then advances to next combine or equips. Retries every 2s if no response. + /// </summary> + public class MissileCraftingManager + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + + public enum CraftState + { + Idle, + Evaluating, + Combining, // ApplyItem issued, waiting for "You make" in chat + EquippingAmmo + } + + public CraftState State { get; private set; } = CraftState.Idle; + public bool IsCrafting => State != CraftState.Idle; + public string StatusMessage { get; private set; } = ""; + + // ── Timing ───────────────────────────────────────────────────────── + 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; + + // ── Current craft job ────────────────────────────────────────────── + private int _headBundleId = 0; + private int _shaftBundleId = 0; + private AmmoRecipe _currentRecipe = null; + private int _equipTargetId = 0; + private bool _allCombinesDone = false; + + // Pre-identified bundle pairs (up to 2). Populated before first combine. + private Queue<int[]> _pendingBundlePairs = new Queue<int[]>(); + private int _totalCombines = 0; + private int _combinesCompleted = 0; + + // ══════════════════════════════════════════════════════════════════ + // RECIPE DATABASE + // ══════════════════════════════════════════════════════════════════ + + public enum WeaponCategory { Bow, Crossbow, Atlatl } + + public class AmmoRecipe + { + public string HeadBundleName; + public string ShaftBundleName; + public string OutputName; + public WeaponCategory Category; + public bool RequiresSpecialized; + public int Priority; + } + + public static readonly List<AmmoRecipe> AllRecipes = new List<AmmoRecipe> + { + // ── ARROWS (Bow) ─────────────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Lethal Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Deadly Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Greater Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Armor Piercing Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Broad Head Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Blunt Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Frog Crotch Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Frog Crotch Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 3 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 1 }, + + // ── QUARRELS (Crossbow) ──────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Lethal Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Deadly Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Greater Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Armor Piercing Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Broad Head Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Blunt Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 1 }, + + // ── DARTS (Atlatl) ───────────────────────────────────────── + new AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { 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 AmmoRecipe { HeadBundleName = "Wrapped Bundle of Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 1 }, + }; + + // ══════════════════════════════════════════════════════════════════ + // CONSTRUCTOR + // ══════════════════════════════════════════════════════════════════ + + public MissileCraftingManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════ + // MAIN TICK + // ══════════════════════════════════════════════════════════════════ + + public void ProcessCrafting() + { + if (!_settings.EnableMissileCrafting) return; + if (_core.Actions.BusyState != 0) 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 PluginCore.OnChatBoxMessage + // Listens for "You make" to confirm a successful combine. + // ══════════════════════════════════════════════════════════════════ + + public void HandleChat(string text) + { + if (State != CraftState.Combining) return; + if (string.IsNullOrEmpty(text)) return; + + // AC craft success: "You make a big bundle of deadly prismatic arrows." + if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return; + + _combinesCompleted++; + ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})"); + + // More pairs to combine? + if (_pendingBundlePairs.Count > 0) + { + var pair = _pendingBundlePairs.Dequeue(); + _headBundleId = pair[0]; + _shaftBundleId = pair[1]; + _lastApplyAttempt = DateTime.MinValue; // Force immediate ApplyItem next tick + StatusMessage = $"Crafting {_currentRecipe.OutputName} (batch {_combinesCompleted + 1})..."; + } + else + { + // All combines done — signal ProcessCombining to transition + _allCombinesDone = true; + } + } + + // ══════════════════════════════════════════════════════════════════ + // IDLE — only triggers when ammo slot is empty + // ══════════════════════════════════════════════════════════════════ + + private void ProcessIdle() + { + if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return; + _lastAmmoCheck = DateTime.Now; + + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) return; + if (HasWieldedAmmo(category.Value)) return; + + ChatLog($"No {GetCategoryLabel(category.Value)}s equipped. Evaluating..."); + SetState(CraftState.Evaluating); + } + + // ══════════════════════════════════════════════════════════════════ + // EVALUATING — decide: craft or equip existing? + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEvaluating() + { + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) { Reset("No missile weapon equipped"); return; } + + int trainingLevel = 0; + try { trainingLevel = (int)_core.CharacterFilter.Skills[CharFilterSkillType.Fletching].Training; } catch { } + + var inv = _core.WorldFilter.GetInventory().ToList(); + + // Find best craftable recipe + AmmoRecipe bestCraftable = null; + foreach (var recipe in AllRecipes + .Where(r => r.Category == category.Value) + .OrderByDescending(r => r.Priority)) + { + if (recipe.RequiresSpecialized && trainingLevel < 3) continue; + if (!recipe.RequiresSpecialized && trainingLevel < 2) continue; + + bool hasHead = inv.Any(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)); + bool hasShaft = inv.Any(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)); + + if (hasHead && hasShaft) { bestCraftable = recipe; break; } + } + + // Find best loose ammo + int bestExistingPriority = 0; + WorldObject bestExistingAmmo = null; + foreach (var item in inv) + { + if (!IsLooseAmmo(item, category.Value)) continue; + int pri = GetAmmoPriority(item, category.Value); + if (pri > bestExistingPriority) { bestExistingPriority = pri; bestExistingAmmo = item; } + } + + // Can craft better? → Craft. + if (bestCraftable != null && bestCraftable.Priority > bestExistingPriority) + { StartCrafting(bestCraftable, inv); return; } + + // Loose ammo? → Equip. + if (bestExistingAmmo != null) + { + _equipTargetId = bestExistingAmmo.Id; + ChatLog($"Equipping {bestExistingAmmo.Name} (x{bestExistingAmmo.Values(LongValueKey.StackCount, 1)})"); + SetState(CraftState.EquippingAmmo); + return; + } + + // Can craft anything? → Craft. + if (bestCraftable != null) + { StartCrafting(bestCraftable, inv); return; } + + Reset("No ammo and no bundles available"); + } + + private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv) + { + _currentRecipe = recipe; + _pendingBundlePairs.Clear(); + _combinesCompleted = 0; + _allCombinesDone = false; + + // Enter Peace mode so the game client doesn't auto-fire arrows mid-craft + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + + // Find head and shaft bundles. Bundles are stackable — a single WorldObject + // can have StackCount=2+, meaning multiple combines from the same item ID. + var headItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + var shaftItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + + // Sum total available across all stacks + int totalHeads = 0; + foreach (var h in headItems) totalHeads += h.Values(LongValueKey.StackCount, 1); + int totalShafts = 0; + foreach (var s in shaftItems) totalShafts += s.Values(LongValueKey.StackCount, 1); + + int pairCount = Math.Min(2, Math.Min(totalHeads, totalShafts)); + if (pairCount <= 0) { Reset("No bundles available"); return; } + + // Queue up pairs. Each combine uses the same IDs if stacked — the server + // decrements the stack. Only need different IDs if we exhaust one stack. + int headIdx = 0, shaftIdx = 0; + int headRemaining = headItems[0].Values(LongValueKey.StackCount, 1); + int shaftRemaining = shaftItems[0].Values(LongValueKey.StackCount, 1); + + for (int i = 0; i < pairCount; i++) + { + // Advance to next stack if current one is exhausted + while (headRemaining <= 0 && headIdx < headItems.Count - 1) + { headIdx++; headRemaining = headItems[headIdx].Values(LongValueKey.StackCount, 1); } + while (shaftRemaining <= 0 && shaftIdx < shaftItems.Count - 1) + { shaftIdx++; shaftRemaining = shaftItems[shaftIdx].Values(LongValueKey.StackCount, 1); } + + _pendingBundlePairs.Enqueue(new[] { headItems[headIdx].Id, shaftItems[shaftIdx].Id }); + headRemaining--; + shaftRemaining--; + } + + _totalCombines = pairCount; + + // Pop first pair + 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 — issues ApplyItem, retries until "You make" in chat. + // HandleChat advances to next pair or signals done. + // ══════════════════════════════════════════════════════════════════ + + private void ProcessCombining() + { + // HandleChat flagged all combines done → equip + if (_allCombinesDone) + { + StatusMessage = $"Equipping {_currentRecipe.OutputName}..."; + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + return; + } + + // Timeout safety + 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; + } + + // Issue / retry ApplyItem every APPLY_RETRY_MS + if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS) + { + try + { + _host.Actions.ApplyItem(_headBundleId, _shaftBundleId); + _lastApplyAttempt = DateTime.Now; + StatusMessage = $"Combining → {_currentRecipe.OutputName} ({_combinesCompleted + 1}/{_totalCombines})..."; + } + catch (Exception ex) + { + Reset($"Combine failed: {ex.Message}"); + } + } + } + + // ══════════════════════════════════════════════════════════════════ + // EQUIPPING — UseItem on the ammo to wield it + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEquippingAmmo() + { + if ((DateTime.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return; + + try + { + int targetId = _equipTargetId; + + if (targetId == 0) + { + WeaponCategory? cat = GetEquippedMissileCategory(); + if (cat != null) + { + var ammo = FindBestAmmoInInventory(cat.Value); + if (ammo != null) targetId = ammo.Id; + } + } + + if (targetId != 0) + { + var ammoItem = _core.WorldFilter[targetId]; + if (ammoItem != null) + { + if (ammoItem.Values((LongValueKey)10, 0) > 0) + { + ChatLog($"Already equipped: {ammoItem.Name}"); + } + else + { + _host.Actions.UseItem(targetId, 0); + ChatLog($"Equipped {ammoItem.Name} (x{ammoItem.Values(LongValueKey.StackCount, 1)})"); + } + } + else + { + ChatLog("Ammo item no longer exists."); + } + } + else + { + ChatLog("Could not find ammo to equip."); + } + } + catch (Exception ex) + { + ChatLog($"Equip error: {ex.Message}"); + } + + Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}"); + } + + // ══════════════════════════════════════════════════════════════════ + // HELPERS + // ══════════════════════════════════════════════════════════════════ + + private bool HasWieldedAmmo(WeaponCategory category) + { + try + { + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Values((LongValueKey)10, 0) <= 0) continue; + if (IsLooseAmmo(item, category)) return true; + } + } + catch { } + return false; + } + + private bool IsLooseAmmo(WorldObject item, WeaponCategory category) + { + if (item.Name == null) return false; + string n = item.Name; + + if (n.Contains("Bundle") || n.Contains("Wrapped")) return false; + if (n.Contains("Arrowhead") || n.Contains("Arrowshaft")) return false; + if (n.Contains("Quarrelhead") || n.Contains("Quarrelshaft")) return false; + if (n.Contains("Dart Head") || n.Contains("Dart Shaft")) return false; + + switch (category) + { + case WeaponCategory.Bow: return n.Contains("Arrow"); + case WeaponCategory.Crossbow: return n.Contains("Quarrel") || n.Contains("Bolt"); + case WeaponCategory.Atlatl: return n.Contains("Dart"); + default: return false; + } + } + + private int GetAmmoPriority(WorldObject item, WeaponCategory category) + { + if (item.Name == null) 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) + { + int bestPri = 0; + WorldObject best = null; + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (!IsLooseAmmo(item, category)) continue; + int pri = GetAmmoPriority(item, category); + if (pri > bestPri) { bestPri = pri; best = item; } + } + return best; + } + + private WeaponCategory? GetEquippedMissileCategory() + { + try + { + foreach (var wo in _core.WorldFilter.GetInventory()) + { + if (wo.Values((LongValueKey)10, 0) <= 0) continue; + if (wo.ObjectClass != ObjectClass.MissileWeapon) continue; + string name = wo.Name?.ToLower() ?? ""; + if (name.Contains("crossbow")) return WeaponCategory.Crossbow; + if (name.Contains("atlatl")) return WeaponCategory.Atlatl; + return WeaponCategory.Bow; + } + } + catch { } + return null; + } + + private string GetCategoryLabel(WeaponCategory cat) + { + switch (cat) + { + case WeaponCategory.Bow: return "Arrow"; + case WeaponCategory.Crossbow: return "Quarrel"; + case WeaponCategory.Atlatl: return "Dart"; + default: return "Ammo"; + } + } + + private void SetState(CraftState newState) + { + State = newState; + _phaseStart = DateTime.Now; + } + + private void Reset(string 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.Actions.AddChatText($"[RynthAi Craft] {msg}", 1); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthAi/Combat/SpellDatabase.cs new file mode 100644 index 0000000..9e1ad05 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellDatabase.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Reflection; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class SpellDatabase + { + private static Dictionary<int, string> _spellNames = new Dictionary<int, string>(); + private static bool _loaded = false; + + private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string> + { + { 47, "Primary Portal Tie" }, { 48, "Primary Portal Recall" }, + { 157, "Summon Primary Portal I" }, { 158, "Summon Primary Portal II" }, + { 1634, "Portal Sending" }, { 1635, "Lifestone Recall" }, + { 1636, "Lifestone Sending" }, { 1637, "Summon Primary Portal III" }, + { 2023, "Recall the Sanctuary" }, { 2041, "Aerlinthe Recall" }, + { 2358, "Lyceum Recall" }, { 2644, "Lifestone Tie" }, + { 2645, "Portal Recall" }, { 2646, "Secondary Portal Tie" }, + { 2647, "Secondary Portal Recall" }, { 2648, "Summon Secondary Portal I" }, + { 2649, "Summon Secondary Portal II" }, { 2650, "Summon Secondary Portal III" }, + { 2813, "Mount Lethe Recall" }, { 2931, "Recall Aphus Lassel" }, + { 2941, "Ulgrim's Recall" }, { 2943, "Recall to the Singularity Caul" }, + { 3865, "Glenden Wood Recall" }, { 3929, "Rossu Morta Chapterhouse Recall" }, + { 3930, "Whispering Blade Chapterhouse Recall" }, { 4084, "Bur Recall" }, + { 4198, "Paradox-touched Olthoi Infested Area Recall" }, { 4213, "Colosseum Recall" }, + { 4907, "Celestial Hand Stronghold Recall" }, { 4908, "Eldrytch Web Stronghold Recall" }, + { 4909, "Radiant Blood Stronghold Recall" }, { 5175, "Facility Hub Recall" }, + { 5330, "Gear Knight Invasion Area Camp Recall" }, { 5541, "Lost City of Neftet Recall" }, + { 6150, "Rynthid Recall" }, { 6321, "Viridian Rise Recall" }, + { 6322, "Viridian Rise Great Tree Recall" }, + }; + + public static bool IsLoaded => _loaded; + + public static void Load(PluginHost host) + { + _spellNames.Clear(); + _loaded = false; + + try + { + Assembly assembly = Assembly.GetExecutingAssembly(); + string resourceName = "NexSuite.Plugins.RynthAi.Combat.Vtank spelldump.txt"; + + using (Stream stream = assembly.GetManifestResourceStream(resourceName)) + { + if (stream == null) + { + host.Actions.AddChatText($"[RynthAi] ERROR: Could not find embedded resource: {resourceName}", 2); + return; + } + + using (StreamReader reader = new StreamReader(stream, true)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + + // Split the line by tabs to isolate the columns + string[] columns = line.Split('\t'); + + // Column 0 is ID, Column 1 is Name + if (columns.Length >= 2) + { + if (int.TryParse(columns[0].Trim(), out int spellId)) + { + string spellName = columns[1].Trim(); + _spellNames[spellId] = spellName; + } + } + } + } + } + + _loaded = _spellNames.Count > 0; + + } + catch (Exception ex) + { + host.Actions.AddChatText($"[RynthAi] Spell Load Error: {ex.Message}", 2); + } + } + + 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(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/SpellManager.cs b/Plugins/RynthAi/Combat/SpellManager.cs new file mode 100644 index 0000000..1244dd7 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellManager.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class SpellManager + { + private CoreManager _core; + + public Dictionary<string, int> SpellDictionary { get; private set; } = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); + + // Map base spell names to their exact Level 7 Lore counterparts + private readonly Dictionary<string, string[]> LoreNames = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) + { + // Attributes (Using the exact AC names you provided) + { "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" } }, + + // Defenses + { "Invulnerability", new[] { "Aura of Defense" } }, + { "Impregnability", new[] { "Aura of Deflection" } }, + { "Magic Resistance", new[] { "Aura of Resistance" } }, + + // Life Magic + { "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" } }, + + // Vitals + { "Heal", new[] { "Adja's Intervention" } }, + { "Revitalize", new[] { "Robustification" } }, + { "Stamina to Mana", new[] { "Meditative Trance" } }, + { "Stamina to Health", new[] { "Rushed Recovery" } }, + + // Skills & Masteries + { "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" } }, + + // Weapon Auras (Item Enchantment) + { "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" } }, + + // Armor Banes (Item Enchantment) + { "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(CoreManager core) + { + _core = core; + } + + public void InitializeNatively() + { + try + { + var fs = _core.Filter<FileService>(); + if (fs == null) return; + + for (int i = 1; i <= 40000; i++) + { + try + { + var spell = fs.SpellTable.GetById(i); + if (spell != null && !string.IsNullOrWhiteSpace(spell.Name)) + { + SpellDictionary[spell.Name] = spell.Id; + } + } + catch { } + } + + _core.Actions.AddChatText($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1); + } + catch (Exception ex) { _core.Actions.AddChatText("[RynthAi] Native load error: " + ex.Message, 2); } + } + + public int GetHighestSpellTier(CharFilterSkillType skill) + { + try + { + int buffedSkill = _core.CharacterFilter.Skills[skill].Buffed; + if (buffedSkill >= 400) return 8; + if (buffedSkill >= 315) return 7; // Adjusted to common AC skill requirements + if (buffedSkill >= 250) return 6; + if (buffedSkill >= 200) return 5; + if (buffedSkill >= 150) return 4; + if (buffedSkill >= 100) return 3; + if (buffedSkill >= 50) return 2; + return 1; + } + catch { return 1; } + } + + private string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + // Spell resolution for self-buffs. Capped by skill level. + // Within each tier tries standard names first, then "Aura of" prefixed variants + // (weapon enchantments like Blood Drinker, Heart Seeker use "Aura of" prefix). + public int GetDynamicSelfBuffId(string baseSpellName, CharFilterSkillType magicSkill) + { + int maxTier = GetHighestSpellTier(magicSkill); + string cleanBase = baseSpellName.Replace(" Self", "").Trim(); + + for (int tier = maxTier; tier >= 1; tier--) + { + if (tier == 8) + { + // Standard: "Incantation of Focus Self" + if (TryGetId($"Incantation of {cleanBase} Self", out int id1)) return id1; + if (TryGetId($"Incantation of {cleanBase}", out int id2)) return id2; + // Aura variant: "Aura of Incantation of Blood Drinker Self" + 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) + { + // Lore names first (already includes "Aura of" where needed) + if (LoreNames.TryGetValue(cleanBase, out string[] lores)) + { + foreach (string lore in lores) + { + if (TryGetId(lore, out int idL)) return idL; + } + } + // Standard VII + if (TryGetId($"{cleanBase} Self VII", out int id7a)) return id7a; + if (TryGetId($"{cleanBase} VII", out int id7b)) return id7b; + // Aura variant VII + if (TryGetId($"Aura of {cleanBase} Self VII", out int id7c)) return id7c; + if (TryGetId($"Aura of {cleanBase} VII", out int id7d)) return id7d; + } + else + { + // Standard: "Focus Self VI" + string numeral = GetRomanNumeral(tier); + if (TryGetId($"{cleanBase} Self {numeral}", out int idNum1)) return idNum1; + if (TryGetId($"{cleanBase} {numeral}", out int idNum2)) return idNum2; + // Aura variant: "Aura of Blood Drinker Self VI" + 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; + } + + private bool TryGetId(string exactName, out int spellId) + { + if (SpellDictionary.TryGetValue(exactName, out spellId)) + { + if (_core.CharacterFilter.IsSpellKnown(spellId)) return true; + } + spellId = 0; + return false; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/Vtank spelldump.txt b/Plugins/RynthAi/Combat/Vtank spelldump.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6873ca371b9df38da60262fc761db616f634a4a GIT binary patch literal 912312 zcmd44S+iAD)~>s5JrU<WaCfdUVoNcBODss)DLXxhpT@pKL_{e}K=YFyzt8D!e^;~D zt>|N-D-7nGE*7&tqt&e!WBh;r=i`fyE*@RHyLfZ)^y1aUv-Ii5i)$DE%<oUrPp@4( zNWX#K!k?EHk1t-NKW{Fcq}TW9&(rk(_`5q7|0Dg!-@2cF>uvhGk1pn)|L=?c>*9L) z+i~Pa`5S*Y>$qPh-e1%AV$>UH)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S^YO+ZGHWEIJ6(FKEHdx;JVWo1_E6|PPEM4Vi#|tsL*pH9aY>yB<kslp{HpJ> zVRn2(^W`QZPM7I^-ea3Z=W$y-;B&INjBXa6$MVmHS+plT@$I^9UA~X}xr1&No9Em0 z^3#fDsU~E9gzj^_s~K61`d_dO<a7($IOgH<Vb|o>#~2(0-6fQ+jg0*ND#}@$uC0tB z!Wz!t<uz$KHWPOt+=`d87#-UI<7j8)k`EN;_?vK#@vMb_1g`d^bqPuE>lzlv4!{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`<FF zb>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>?<g`XOr9E-j?5~JH&docGbFy c8@zPi5P0DBB|KkmSq7E9++|C~@qSVM57`CD-2eap literal 0 HcmV?d00001 diff --git a/Plugins/RynthAi/DecalInspector.cs b/Plugins/RynthAi/DecalInspector.cs new file mode 100644 index 0000000..84b5ede --- /dev/null +++ b/Plugins/RynthAi/DecalInspector.cs @@ -0,0 +1,38 @@ +using System; +using System.Reflection; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class DecalInspector + { + public static void DumpType(Type t, CoreManager core) + { + core.Actions.AddChatText("====== " + t.FullName + " ======", 3); + + core.Actions.AddChatText("-- PROPERTIES --", 3); + foreach (var p in t.GetProperties()) + { + core.Actions.AddChatText(p.PropertyType.Name + " " + p.Name, 3); + } + + core.Actions.AddChatText("-- METHODS --", 3); + foreach (var m in t.GetMethods()) + { + core.Actions.AddChatText(m.ReturnType.Name + " " + m.Name, 3); + } + } + + public static void DumpDecalAPI(CoreManager core) + { + DumpType(typeof(WorldObject), core); + DumpType(typeof(CharacterFilter), core); + DumpType(typeof(CoreManager), core); + + // These are the important ones for navigation + DumpType(typeof(HooksWrapper), core); + DumpType(typeof(WorldFilter), core); + } + } +} diff --git a/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs new file mode 100644 index 0000000..d018b03 --- /dev/null +++ b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs @@ -0,0 +1,81 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi.Utility +{ + public class BackgroundFpsUnlocker : IDisposable + { + // --- THE FIX: Tell Windows to use the correct C++ memory standard --- + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] + private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong")] + private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + private static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong) + { + if (IntPtr.Size == 8) return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + return SetWindowLong32(hWnd, nIndex, dwNewLong); + } + + [DllImport("user32.dll")] + private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + private const int GWLP_WNDPROC = -4; + private const uint WM_ACTIVATEAPP = 0x001C; + + private WndProcDelegate _newWndProc; + private IntPtr _oldWndProc = IntPtr.Zero; + private IntPtr _acWindowHandle; + private PluginHost _host; + private bool _isUnlocked = false; + + public void Start(PluginHost host) + { + _host = host; + if (_isUnlocked) return; + + try + { + _acWindowHandle = Process.GetCurrentProcess().MainWindowHandle; + + _newWndProc = new WndProcDelegate(CustomWndProc); + IntPtr pNewWndProc = Marshal.GetFunctionPointerForDelegate(_newWndProc); + + _oldWndProc = SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, pNewWndProc); + + _isUnlocked = true; + _host.Actions.AddChatText("[RynthAi] Native Background FPS Unlocked.", 5); + } + catch (Exception ex) + { + _host.Actions.AddChatText("[RynthAi] Failed to unlock FPS: " + ex.Message, 1); + } + } + + public void Dispose() + { + if (_isUnlocked && _oldWndProc != IntPtr.Zero) + { + SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, _oldWndProc); + _isUnlocked = false; + } + } + + private IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + { + // When the game is told to sleep, we intercept it and tell it to stay awake + if (msg == WM_ACTIVATEAPP) + { + return CallWindowProc(_oldWndProc, hWnd, msg, (IntPtr)1, lParam); + } + + return CallWindowProc(_oldWndProc, hWnd, msg, wParam, lParam); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Logic/CommandProcessor.cs b/Plugins/RynthAi/Logic/CommandProcessor.cs new file mode 100644 index 0000000..7a9779b --- /dev/null +++ b/Plugins/RynthAi/Logic/CommandProcessor.cs @@ -0,0 +1,812 @@ +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public class CommandProcessor + { + private readonly PluginCore _plugin; + private readonly UISettings _settings; + private readonly MetaManager _meta; + private readonly NavigationManager _nav; + private readonly BuffManager _buff; + private readonly CombatManager _combat; + private readonly LootManager _loot; + private readonly LuaManager _lua; + private readonly RynthJumper _jumper; + private readonly SpellManager _spellManager; + private readonly FellowshipTracker _fellowship; + + public CommandProcessor(PluginCore plugin, UISettings settings, MetaManager meta, NavigationManager nav, BuffManager buff, CombatManager combat, LootManager loot, LuaManager lua, RynthJumper jumper, SpellManager spellManager, FellowshipTracker fellowship) + { + _plugin = plugin; + _settings = settings; + _meta = meta; + _nav = nav; + _buff = buff; + _combat = combat; + _loot = loot; + _lua = lua; + _jumper = jumper; + _spellManager = spellManager; + _fellowship = fellowship; + } + + public void Execute(string text, ChatParserInterceptEventArgs e) + { + try + { + string trimmed = text.Trim(); + bool isNA = trimmed.StartsWith("/na", StringComparison.OrdinalIgnoreCase); + bool isVT = trimmed.StartsWith("/vt", StringComparison.OrdinalIgnoreCase); + bool isLua = trimmed.StartsWith("/lua", StringComparison.OrdinalIgnoreCase); + + if (!isNA && !isVT && !isLua) return; + + string[] parts = trimmed.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + + // --- Handle Top-Level /lua command --- + if (isLua) + { + e.Eat = true; + if (parts.Length < 2) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /lua <script>", 1); + return; + } + string script = trimmed.Substring(5).Trim(); + _lua?.ExecuteString(script); + return; + } + + if (parts.Length < 2) + { + PrintHelp(); + e.Eat = true; + return; + } + + e.Eat = true; + string cmd = parts[1].ToLower(); + + switch (cmd) + { + // --- NEW COMMANDS --- + case "lua": + if (parts.Length >= 3) + { + string script = string.Join(" ", parts, 2, parts.Length - 2); + _lua?.ExecuteString(script); + } + break; + + case "opt": + HandleOptCommand(parts); + break; + + case "addnavpt": + HandleAddNavPoint(); + break; + + // --- CORE MACRO CONTROLS --- + case "start": + case "on": + _settings.IsMacroRunning = true; + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STARTED.", 5); + break; + + case "stop": + case "off": + _settings.IsMacroRunning = false; + _buff?.CancelBuffing(); + _nav?.Stop(); + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STOPPED.", 5); + break; + + case "status": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Macro: {(_settings.IsMacroRunning ? "ON" : "OFF")} | State: {_settings.CurrentState} | Nav: {Path.GetFileName(_settings.CurrentNavPath)} | Meta: {Path.GetFileName(_settings.CurrentMetaPath)}", 1); + break; + + // --- SUBSYSTEMS & PROFILES --- + case "settings": + HandleSettingsCommand(parts); + break; + + case "nav": + case "loot": + case "meta": + HandleSubsystemCommand(cmd, parts, text); + break; + + case "setmetastate": + if (parts.Length >= 3) + { + string newState = string.Join(" ", parts, 2, parts.Length - 2); + _settings.CurrentState = newState; + _settings.ForceStateReset = true; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Meta State forced to: {newState}", 5); + } + break; + + case "db": + case "debugbuffs": + _buff?.PrintBuffDebug(); + break; + + case "dn": + case "debugnav": + if (_nav != null) + { + _nav.DebugNav = !_nav.DebugNav; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Nav debug: {(_nav.DebugNav ? "ON" : "OFF")}", 5); + } + break; + + case "wd": + case "watchdog": + _meta?.PrintWatchdogStatus(); + break; + + case "fakedeath": + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Faking character death trigger...", 5); + _meta?.HandleChat("You have died."); + break; + + case "rebuff": + case "forcebuff": + _buff?.ForceFullRebuff(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence initiated.", 5); + break; + + case "cancelforcebuff": + _buff?.CancelBuffing(); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence cancelled.", 5); + break; + + case "raycast": + HandleRaycastCommand(parts); + break; + + case "lostest": + if (_combat != null) + { + var diagLines = _combat.RunLosTestDiag(_plugin.PluginCoreManager); + foreach (var line in diagLines) + _plugin.PluginHost.Actions.AddChatText("[RynthAi LOS] " + line, 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Combat manager not initialized", 1); + } + break; + + case "blacklist": + if (parts.Length >= 3 && parts[2].ToLower() == "clear") + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Blacklist cleared.", 5); + } + else + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Blacklist: attempts={_settings.BlacklistAttempts}, timeout={_settings.BlacklistTimeoutSec}s", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na blacklist clear", 1); + } + break; + + // --- COMBAT & UTILITY STUBS --- + case "deletemonster": + int targetId = _plugin.PluginHost.Actions.CurrentSelection; + if (targetId != 0) _plugin.PluginHost.Actions.AddChatText($"[RynthAi] DeleteMonster stubbed target: {targetId}", 5); + break; + + case "setattackbar": + if (parts.Length >= 3) + { + string target = "melee"; // default + float rawVal; + if (parts.Length >= 4 && float.TryParse(parts[3], out rawVal)) + { + target = parts[2].ToLower(); // "melee" or "missile" + } + else if (float.TryParse(parts[2], out rawVal)) + { + // /na setattackbar 0.5 → sets both + target = "both"; + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1); + break; + } + int pct = Math.Max(0, Math.Min(100, (int)(rawVal * 100))); + if (target == "missile") { _settings.MissileAttackPower = pct; } + else if (target == "melee") { _settings.MeleeAttackPower = pct; } + else { _settings.MeleeAttackPower = pct; _settings.MissileAttackPower = pct; } + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power ({target}): {pct}%", 5); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1); + } + break; + + case "autoattackpower": + if (parts.Length >= 3) + { + if (parts[2].Equals("auto", StringComparison.OrdinalIgnoreCase)) + { + _settings.MeleeAttackPower = -1; + _settings.MissileAttackPower = -1; + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Attack power set to AUTO (full power) for both modes", 5); + } + else if (int.TryParse(parts[2], out int pwr)) + { + pwr = Math.Max(0, Math.Min(100, pwr)); + _settings.MeleeAttackPower = pwr; + _settings.MissileAttackPower = pwr; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power set to {pwr}% for both modes", 5); + } + _plugin.SaveSettings(); + } + else + { + string mPwr = _settings.MeleeAttackPower < 0 ? "AUTO" : $"{_settings.MeleeAttackPower}%"; + string rPwr = _settings.MissileAttackPower < 0 ? "AUTO" : $"{_settings.MissileAttackPower}%"; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Melee: {mPwr}, Missile: {rPwr}. Usage: /na autoattackpower [auto|0-100]", 1); + } + break; + + case "tapjump": + if (_jumper != null) _jumper.TapJump(); + break; + + case "spelldump": + // /na spelldump Focus — shows all spells containing "Focus" + if (parts.Length >= 3 && _spellManager != null) + { + string keyword = string.Join(" ", parts, 2, parts.Length - 2).ToLower(); + int found = 0; + foreach (var kvp in _spellManager.SpellDictionary) + { + if (kvp.Key.ToLower().Contains(keyword)) + { + bool known = false; + try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(kvp.Value); } catch { } + _plugin.PluginHost.Actions.AddChatText($" {kvp.Key} (id={kvp.Value}) {(known ? "[KNOWN]" : "[unknown]")}", 1); + found++; + } + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Found {found} spells matching '{keyword}'", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na spelldump <keyword>", 1); + } + break; + + case "bufftest": + // /na bufftest Focus Self — traces the full buff lookup path + if (parts.Length >= 3 && _spellManager != null) + { + string buffName = string.Join(" ", parts, 2, parts.Length - 2); + string cleanBase = buffName.Replace(" Self", "").Trim(); + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] Input: '{buffName}' → cleanBase: '{cleanBase}'", 1); + + // Check what GetHighestSpellTier returns + var testSkills = new[] { + CharFilterSkillType.CreatureEnchantment, + CharFilterSkillType.LifeMagic, + CharFilterSkillType.ItemEnchantment + }; + foreach (var sk in testSkills) + { + int tier = _spellManager.GetHighestSpellTier(sk); + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] {sk} → maxTier={tier}", 1); + } + + // Trace the exact lookups + string[] tries = new[] { + $"Incantation of {cleanBase} Self", + $"Incantation of {cleanBase}", + }; + foreach (string tryName in tries) + { + bool inDict = _spellManager.SpellDictionary.ContainsKey(tryName); + int id = inDict ? _spellManager.SpellDictionary[tryName] : 0; + bool known = false; + if (id > 0) try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(id); } catch { } + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] Try '{tryName}' → inDict={inDict}, id={id}, known={known}", 1); + } + + // Now call the actual method + int result = _spellManager.GetDynamicSelfBuffId(buffName, CharFilterSkillType.CreatureEnchantment); + string resultName = "(none)"; + if (result > 0 && _spellManager.SpellDictionary.Values.Contains(result)) + { + foreach (var kvp in _spellManager.SpellDictionary) + { + if (kvp.Value == result) { resultName = kvp.Key; break; } + } + } + _plugin.PluginHost.Actions.AddChatText($"[BuffTest] GetDynamicSelfBuffId returned: {result} = '{resultName}'", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na bufftest Focus Self", 1); + } + break; + + case "fellow": + case "fellowship": + // /na fellow [subcommand] — fellowship info and actions + if (_fellowship == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Fellowship tracker not initialized.", 1); + break; + } + + string fellowSub = (parts.Length >= 3) ? parts[2].ToLower() : "status"; + + if (!_fellowship.IsInFellowship && fellowSub != "help") + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Not in a fellowship.", 1); + break; + } + + switch (fellowSub) + { + case "status": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship: \"{_fellowship.FellowshipName}\"", 1); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members: {_fellowship.MemberCount} | Leader: {(_fellowship.IsLeader ? "ME" : $"0x{_fellowship.LeaderId:X8}")} | Open: {_fellowship.IsOpen} | Locked: {_fellowship.IsLocked} | ShareXP: {_fellowship.ShareXP}", 1); + { + int fidx = 0; + foreach (string mName in _fellowship.GetMemberNames()) + { + int mId = _fellowship.GetMemberId(fidx); + bool isLdr = (mId == _fellowship.LeaderId); + _plugin.PluginHost.Actions.AddChatText($" [{fidx}] {mName} (0x{mId:X8}){(isLdr ? " [LEADER]" : "")}", 1); + fidx++; + } + } + break; + + case "leader": + { + int leaderId = _fellowship.LeaderId; + string leaderName = "(unknown)"; + int li = 0; + foreach (string mn in _fellowship.GetMemberNames()) + { + if (_fellowship.GetMemberId(li) == leaderId) { leaderName = mn; break; } + li++; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Leader: {leaderName} (0x{leaderId:X8}){(_fellowship.IsLeader ? " (you)" : "")}", 1); + } + break; + + case "count": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship member count: {_fellowship.MemberCount}", 1); + break; + + case "names": + { + var names = new List<string>(_fellowship.GetMemberNames()); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members ({names.Count}): {string.Join(", ", names)}", 1); + } + break; + + case "name": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship name: \"{_fellowship.FellowshipName}\"", 1); + break; + + case "open": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Open: {_fellowship.IsOpen}", 1); + break; + + case "locked": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Locked: {_fellowship.IsLocked}", 1); + break; + + case "sharexp": + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] ShareXP: {_fellowship.ShareXP}", 1); + break; + + case "ismember": + if (parts.Length >= 4) + { + string checkName = string.Join(" ", parts, 3, parts.Length - 3); + bool found = _fellowship.IsMember(checkName); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] IsMember(\"{checkName}\"): {found}", 1); + } + else + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na fellow ismember <name>", 1); + } + break; + + case "help": + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|open|locked|sharexp|ismember <name>]", 1); + break; + + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /na fellow help", 1); + break; + } + break; + + case "corpsedebug": + // /na corpsedebug — check the currently selected corpse's ownership info + { + int selId = _plugin.PluginHost.Actions.CurrentSelection; + if (selId == 0) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a corpse first.", 1); + break; + } + var wo = _plugin.PluginCoreManager.WorldFilter[selId]; + if (wo == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Selected object not found.", 1); + break; + } + string corpName = wo.Name ?? "(null)"; + string longDesc = ""; + try { longDesc = wo.Values((StringValueKey)16, ""); } catch { } + string myName = _plugin.PluginCoreManager.CharacterFilter.Name; + + // Extract killer + string killerName = "(unknown)"; + const string prefix = "Killed by "; + int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx >= 0) + { + killerName = longDesc.Substring(idx + prefix.Length).TrimEnd('.', ' ', '\n', '\r'); + } + + bool isMe = killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + bool isFellow = _fellowship != null && _fellowship.IsMember(killerName); + + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Name: {corpName}", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LongDesc: '{longDesc}'", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Killer: '{killerName}'", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] IsMe: {isMe}, IsFellow: {isFellow}", 1); + _plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LootOwnership: {_settings.LootOwnership} (0=Mine, 1=Fellow, 2=All)", 1); + } + break; + + // ── NATIVE JUMP SYSTEM ── + case "jump": + case "jumpsw": + case "jumpsx": + case "jumpswz": + case "jumpswx": + case "jumpswzx": + case "jumpswzxc": + HandleJumpCommand(cmd, parts); + break; + + case "face": + if (parts.Length >= 3 && double.TryParse(parts[2], out double faceHeading)) + { + _plugin.PluginCoreManager.Actions.Heading = (float)faceHeading; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Facing {faceHeading:F0}", 5); + } + break; + + case "reverseroute": + if (parts.Length >= 3) + { + bool rev = parts[2].ToLower() == "true"; + _nav?.SetReverse(rev); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route: {rev}", 5); + } + break; + + case "reverseroutequery": + bool isRev = _nav?.IsReversed ?? false; + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route is: {isRev}", 5); + break; + + case "mexec": + if (parts.Length >= 3) + { + string expr = text.Substring(text.IndexOf("mexec") + 5).Trim(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] MEXEC: {expr}", 5); + try { _plugin.PluginHost.Actions.InvokeChatParser($"/ub mexec {expr}"); } + catch (Exception ex) { _plugin.PluginHost.Actions.AddChatText($"[RynthAi] UB Error: {ex.Message}", 1); } + } + break; + + case "echo": + string echoText = string.Join(" ", parts, 2, parts.Length - 2); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] {echoText}", 5); + break; + + case "ui": + _plugin.ToggleUI(); + break; + + // ── COMBAT ACTION DIAGNOSTICS ── + case "probe": + // /na probe — show CombatActionHelper initialization status + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] CombatActionHelper initialized: {CombatActionHelper.IsInitialized}", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] (Check chat log at plugin load for detailed scan results)", 1); + if (!CombatActionHelper.IsInitialized) + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Pattern scan failed — CM_Combat functions not found in this acclient.exe build", 1); + } + break; + + case "testattack": + // /na testattack — attempts a single melee attack on current selection + // Use this with combat OFF to isolate the direct call + { + int selId = _plugin.PluginHost.Actions.CurrentSelection; + if (selId == 0) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a target first.", 1); + break; + } + if (!CombatActionHelper.IsInitialized) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] CombatActionHelper not initialized.", 1); + break; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Sending MeleeAttack to target 0x{selId:X8}, height=Medium, power=0.5...", 1); + bool ok = CombatActionHelper.MeleeAttack((uint)selId, CombatActionHelper.ATTACK_HEIGHT_MEDIUM, 0.5f); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] MeleeAttack returned: {ok}", 1); + } + break; + + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown command: {cmd}", 1); + break; + } + } + catch (Exception ex) + { + _plugin.PluginHost.Actions.AddChatText($"[RynthAi Cmd Error] {ex.Message}", 1); + } + } + + private void HandleOptCommand(string[] parts) + { + if (parts.Length < 5 || !parts[2].Equals("set", StringComparison.OrdinalIgnoreCase)) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na opt set <setting> <value>", 1); + return; + } + + string setting = parts[3].ToLower(); + string val = parts[4].ToLower(); + + switch (setting) + { + case "enablecombat": _settings.EnableCombat = (val == "true"); break; + case "enablenav": _settings.EnableNavigation = (val == "true"); break; + case "enablelooting": _settings.EnableLooting = (val == "true"); break; + case "summonpets": _settings.SummonPets = (val == "true"); break; + case "enablemeta": _settings.EnableMeta = (val == "true"); break; + case "attackdistance": + if (float.TryParse(val, out float dist)) _settings.FollowNavMin = dist; + break; + default: + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown option: {setting}", 1); + return; + } + + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Option {setting} set to {val}", 5); + _plugin.SaveSettings(); + } + + private void HandleAddNavPoint() + { + if (_settings.CurrentRoute == null) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Error: No route loaded.", 1); + return; + } + + var coords = _plugin.PluginCoreManager.WorldFilter[_plugin.PluginCoreManager.CharacterFilter.Id].Coordinates(); + + // FIX: Using Object Initializer to avoid constructor errors + var newPoint = new NavPoint + { + NS = (float)coords.NorthSouth, + EW = (float)coords.EastWest, + Z = (float)_plugin.PluginCoreManager.Actions.LocationZ + }; + + _settings.CurrentRoute.Points.Add(newPoint); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Added Nav Point at: {newPoint.NS:F2}N, {newPoint.EW:F2}E", 5); + _plugin.UI?.RouteTab?.UpdateRouteGraphics(); + } + + private void HandleSettingsCommand(string[] parts) + { + if (parts.Length < 3) return; + string sub = parts[2].ToLower(); + string fileName = (parts.Length >= 4) ? parts[3] : "default"; + if (!fileName.EndsWith(".json")) fileName += ".json"; + + string server = _plugin.PluginCoreManager.CharacterFilter.Server; + string name = _plugin.PluginCoreManager.CharacterFilter.Name; + string globalDir = @"C:\Games\DecalPlugins\NexSuite\RynthAi\GlobalSettings"; + string charDir = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", server, name); + + if (!Directory.Exists(globalDir)) Directory.CreateDirectory(globalDir); + if (!Directory.Exists(charDir)) Directory.CreateDirectory(charDir); + + string globalPath = Path.Combine(globalDir, fileName); + string charPath = Path.Combine(charDir, fileName); + + switch (sub) + { + case "save": _plugin.SaveSettings(globalPath); break; + case "load": _plugin.LoadSettings(globalPath); break; + case "savechar": _settings.MineOnly = true; _plugin.SaveSettings(charPath); break; + case "loadchar": _settings.MineOnly = true; _plugin.LoadSettings(charPath); break; + } + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Settings {sub} successful: {fileName}", 5); + } + + private void HandleSubsystemCommand(string type, string[] parts, string fullText) + { + if (parts.Length < 4) return; + string action = parts[2].ToLower(); + string fileName = string.Join(" ", parts, 3, parts.Length - 3); + + string folder = type == "nav" ? _plugin.NavFolder : (type == "meta" ? _plugin.MetaFolder : _plugin.LootFolder); + string ext = type == "nav" ? ".nav" : (type == "meta" ? ".met" : ".utl"); + + if (!fileName.EndsWith(ext)) fileName += ext; + string fullPath = Path.Combine(folder, fileName); + + if (action == "save") + { + if (!File.Exists(fullPath)) File.WriteAllText(fullPath, ""); + if (type == "nav") _settings.CurrentRoute?.Save(fullPath); + else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.SaveCurrentProfile(); } + else if (type == "loot") { _settings.EnableLooting = true; _loot?.SaveProfile(fullPath); } + } + else if (action == "load") + { + if (!File.Exists(fullPath)) + { + File.WriteAllText(fullPath, ""); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Created new {type} profile: {fileName}", 5); + } + + if (type == "nav") + { + _settings.CurrentNavPath = fullPath; + _settings.CurrentRoute = VTankNavParser.Load(fullPath); + _nav?.ResetRouteState(); + + // Find nearest waypoint for Circular/Linear routes + if (_settings.CurrentRoute.RouteType == NavRouteType.Circular || + _settings.CurrentRoute.RouteType == NavRouteType.Linear) + { + _settings.ActiveNavIndex = _nav != null ? _nav.FindNearestWaypoint(_settings.CurrentRoute) : 0; + } + else + { + _settings.ActiveNavIndex = 0; + } + + // Refresh route graphics + if (_plugin.UI?.RouteTab != null) + _plugin.UI.RouteTab.NeedsRouteGraphicsRefresh = true; + } + else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.LoadProfile(fullPath); } + else if (type == "loot") { _settings.EnableLooting = true; _loot?.LoadProfile(fullPath); } + } + + SyncUI(type, fileName, folder); + _plugin.SaveSettings(); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] {type.ToUpper()} {action} successful: {fileName}", 5); + } + + private void SyncUI(string type, string fileName, string folder) + { + if (_plugin.UI == null) return; + if (type == "nav") _plugin.UI.RefreshNavFiles(); + if (type != "meta") return; + + _plugin.UI.RefreshMetaFiles(); + if (Directory.Exists(folder)) + { + string[] files = Directory.GetFiles(folder, "*.met"); + Array.Sort(files); + for (int i = 0; i < files.Length; i++) + { + if (Path.GetFileName(files[i]).Equals(fileName, StringComparison.OrdinalIgnoreCase)) + { + _settings.MetaProfileIdx = i + 1; + break; + } + } + } + } + + private void HandleRaycastCommand(string[] parts) + { + if (parts.Length > 2) + { + _settings.EnableRaycasting = (parts[2].ToLower() == "on"); + _plugin.SaveSettings(); + } + else + { + string rayStatus = _combat?.GetRaycastStatus() ?? "No info"; + foreach (var line in rayStatus.Split('\n')) _plugin.PluginHost.Actions.AddChatText("[RynthAi] " + line.Trim(), 1); + } + } + + /// <summary> + /// Handles /na jump commands natively using RynthJumper. + /// Format: /na jump[swzxc] [heading] [holdtime] + /// - /na jump = tap jump + /// - /na jumpsw 180 500 = face south, jump forward with 500/1000 power + /// - /na jumpsx 300 = jump backward with 300/1000 power + /// </summary> + private void HandleJumpCommand(string cmd, string[] parts) + { + if (_jumper == null) return; + if (_jumper.IsJumping) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Already jumping — wait for completion", 1); + return; + } + + // Simple tap jump + if (cmd == "jump" && parts.Length <= 2) + { + _jumper.TapJump(); + return; + } + + // Parse hold time + int holdMs = 0; + double heading = -1; // -1 = use current heading + + if (parts.Length >= 4 && int.TryParse(parts[3], out int ht)) + holdMs = ht; + else if (parts.Length >= 3 && int.TryParse(parts[2], out int ht2)) + holdMs = ht2; + + if (parts.Length >= 3 && double.TryParse(parts[2], out double hd)) + { + heading = hd; + // If heading was parsed as first arg, holdtime is second + if (parts.Length >= 4 && int.TryParse(parts[3], out int ht3)) + holdMs = ht3; + } + + // Parse direction keys from command suffix + bool shift = cmd.Contains("s"); + bool forward = cmd.Contains("w"); + bool backward = cmd.Contains("x"); + bool slideLeft = cmd.Contains("z"); + bool slideRight = cmd.Contains("c"); + + _jumper.StartJump(heading, holdMs, shift, forward, backward, slideLeft, slideRight); + _plugin.PluginHost.Actions.AddChatText($"[RynthAi] Jumping: heading={heading:F0} hold={holdMs}ms keys={cmd.Replace("jump","")}", 5); + } + + private void PrintHelp() + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Commands: /na [start|stop|status], /na lostest, /na setattackbar 0-1, /na autoattackpower [auto|0-1]", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|ismember <n>], /na probe, /na testattack", 1); + _plugin.PluginHost.Actions.AddChatText("[RynthAi] /na jump[sw|sx|swz|swx|swzx|swzxc] [heading] [holdtime], /na blacklist [clear], /lua <script>", 1); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Logic/NavigationManager.cs b/Plugins/RynthAi/Logic/NavigationManager.cs new file mode 100644 index 0000000..921c055 --- /dev/null +++ b/Plugins/RynthAi/Logic/NavigationManager.cs @@ -0,0 +1,1154 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// VTank-faithful navigation engine. + /// + /// ARCHITECTURE: + /// Forward motion: SetAutorun(true/false) via Decal API. + /// - Player can toggle autorun off manually for immediate control. + /// - Re-asserted every 500ms as heartbeat. + /// + /// Steering while running: SetClientMotion(TurnRight/TurnLeft) via + /// AcClient command interpreter. These combine with autorun naturally + /// (like pressing W+A or W+D) without interrupting forward motion. + /// + /// Large turns (>60°): Stop autorun, snap Actions.Heading while + /// stopped, resume autorun once error is below 20°. + /// + /// Closest-approach detection prevents circling waypoints. + /// </summary> + public class NavigationManager + { + private readonly CoreManager _core; + private readonly UISettings _settings; + private readonly PluginHost _host; + + // ── Motion command constants (turns only — forward uses SetAutorun) ──── + private const uint MOTION_TURNRIGHT = 0x6500000D; + private const uint MOTION_TURNLEFT = 0x6500000E; + + // ── Nav tick ──────────────────────────────────────────────────────────── + private DateTime _lastNavTick = DateTime.MinValue; + private const double NAV_TICK_MS = 33.0; // ~30 Hz — smoother turn toggling + + // ── Stop debounce ─────────────────────────────────────────────────────── + private DateTime _stopRequestedAt = DateTime.MaxValue; + private const double STOP_DEBOUNCE_MS = 300.0; + + // ── Movement state ────────────────────────────────────────────────────── + private bool _isMovingForward = false; + private bool _hasStopped = true; + private bool _turnsStopped = true; + public bool DebugNav = false; + private DateTime _lastDebugPrint = DateTime.MinValue; + private double _lastGoodHeading = 0; + private bool _hasGoodHeading = false; // true = we've already stopped, don't repeat + + // ── W tap heartbeat — periodic safety tap ─────────────────────────────── + private DateTime _lastWTap = DateTime.MinValue; + private const double W_HEARTBEAT_MS = 500.0; + + // ── Turning state ─────────────────────────────────────────────────────── + private bool _isTurning = false; + + // ── Heading thresholds ────────────────────────────────────────────────── + private const double DEAD_ZONE = 4.0; // wider for indoor stability — frequent small corrections = smooth + private const double BIG_TURN_ENTER = 20.0; // stop and turn above this + private const double BIG_TURN_EXIT = 10.0; // resume running below this + + // ── Arrival / lookahead ───────────────────────────────────────────────── + private double ArrivalYards => Math.Max(1.5, _settings.FollowNavMin); + private double LookaheadYards => ArrivalYards * 0.1; + + // ── Closest approach tracking ─────────────────────────────────────────── + // Detects when we've passed a waypoint even if we never entered the + // arrival radius (turn radius at speed is too wide). If distance was + // decreasing and starts increasing, we've swept past — advance. + private double _prevDist = double.MaxValue; + + // ── Route bookkeeping ─────────────────────────────────────────────────── + private int _linearDir = 1; + private bool _inPause = false; + private DateTime _pauseUntil = DateTime.MinValue; + private bool _actionFired = false; + private DateTime _actionExpiry = DateTime.MinValue; + private const double ACTION_TIMEOUT_MS = 10000.0; + + // ── Portal/Recall state machine ───────────────────────────────────────── + private enum PortalState + { + None, + Settling, + EquippingWand, + EnteringMagicMode, + CastingSpell, + WaitingForPortalOrTeleport, + WaitingForPortalExit, + PostTeleportSettle // Brief pause after teleporting to cancel UseItem effects + } + private PortalState _portalState = PortalState.None; + private DateTime _portalStateStart = DateTime.MinValue; + private int _preCastLandblock = 0; + private int _prePortalLandblock = 0; + private double _prePortalNS = double.NaN; + private double _prePortalEW = double.NaN; + private const double PORTAL_STATE_TIMEOUT_MS = 15000.0; + private const double SETTLE_DELAY_MS = 600.0; + private const double WAND_EQUIP_DELAY_MS = 1000.0; + private const double MAGIC_MODE_DELAY_MS = 800.0; + private const double CAST_DELAY_MS = 500.0; + private const double PORTAL_WAIT_MS = 3000.0; + + // ── Stuck watchdog ────────────────────────────────────────────────────── + private double _watchdogNS = double.NaN; + private double _watchdogEW = double.NaN; + private DateTime _watchdogNext = DateTime.MinValue; + private int _stuckCount = 0; + private bool _inRecovery = false; + private DateTime _recoveryUntil = DateTime.MinValue; + private const double WATCHDOG_MS = 5000.0; + private const double STUCK_YD = 2.0; + private const double RECOVERY_MS = 1200.0; + + // ── Tier 2 state (MoveToPosition via MovementManager) ───────────────── + private int _tier2TargetIdx = -1; // waypoint index we last issued MoveToPosition for + private bool _tier2Active = false; // true while a Tier2 MoveToPosition is in flight + private DateTime _tier2IssuedAt = DateTime.MinValue; + private const double TIER2_REISSUE_MS = 2000.0; // re-issue if no progress for this long + private const double TIER2_ARRIVAL_YD = 1.5; // arrival radius (yards) + + // ── Win32 (focus detection only) ──────────────────────────────────────── + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + public bool IsReversed { get; set; } = false; + public void SetReverse(bool reverse) { IsReversed = reverse; } + + private IntPtr _gameHwnd = IntPtr.Zero; + private IntPtr GameHwnd + { + get + { + if (_gameHwnd == IntPtr.Zero) + _gameHwnd = Process.GetCurrentProcess().MainWindowHandle; + return _gameHwnd; + } + } + + private bool IsGameFocused() => GetForegroundWindow() == GameHwnd; + + public NavigationManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════════════ + // CLIENT MOTION + W TAP + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Direct client memory motion — same as UB's setmotion. + /// Used ONCE to establish forward motion state. + /// </summary> + private unsafe void SetClientMotion(uint motion, bool on) + { + try + { + ((ACCmdInterp*)(*SmartBox.smartbox)->cmdinterp)->SetMotion(motion, on); + } + catch { } + } + + private void StartForward() + { + if (!_isMovingForward) + { + try { _core.Actions.SetAutorun(true); } catch { } + _isMovingForward = true; + } + } + + private void StopForward() + { + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + } + + private void StopMovement() + { + _isTurning = false; + StopForward(); + ClearTurnMotions(); + CancelTier2(); + } + + private void CancelTier2() + { + if (_tier2Active) + { + try { Tier2MovementHelper.CancelMoveTo(); } catch { } + _tier2Active = false; + } + _tier2TargetIdx = -1; + } + + private void ClearTurnMotions() + { + SetClientMotion(MOTION_TURNRIGHT, false); + SetClientMotion(MOTION_TURNLEFT, false); + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC ENTRY POINT + // ══════════════════════════════════════════════════════════════════════════ + + public void ProcessNavigation(bool isFighting) + { + // The priority dispatcher in PluginCore already controls call order. + // Nav only needs to check: macro running, nav enabled, and state is available. + // "Idle" means no higher-priority system claimed this frame. + // "Navigating" means WE claimed it last frame and are still going. + bool shouldNav = _settings.IsMacroRunning + && _settings.EnableNavigation + && (_settings.CurrentState == "Idle" || _settings.CurrentState == "Navigating"); + + if (!shouldNav) + { + if (!_hasStopped && !_turnsStopped) + { try { ClearTurnMotions(); } catch { } _turnsStopped = true; } + if (_stopRequestedAt == DateTime.MaxValue) + _stopRequestedAt = DateTime.Now; + if ((DateTime.Now - _stopRequestedAt).TotalMilliseconds >= STOP_DEBOUNCE_MS) + { + if (!_hasStopped) + { + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + } + } + return; + } + _stopRequestedAt = DateTime.MaxValue; + _hasStopped = false; + _turnsStopped = false; + + var route = _settings.CurrentRoute; + if (route == null || route.Points.Count == 0) { StopMovement(); return; } + + // Claim the traffic light — we are actively navigating + _settings.CurrentState = "Navigating"; + + // Rate limit to ~15 Hz + if ((DateTime.Now - _lastNavTick).TotalMilliseconds < NAV_TICK_MS) return; + _lastNavTick = DateTime.Now; + + int idx = _settings.ActiveNavIndex; + if (!IndexValid(idx, route)) { HandleRouteEnd(route); return; } + + UpdateWatchdog(); + if (_inRecovery) + { + if (DateTime.Now >= _recoveryUntil) _inRecovery = false; + return; + } + + var pt = route.Points[idx]; + + // ── Pause ─────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Pause) + { + StopMovement(); + if (!_inPause) { _inPause = true; _pauseUntil = DateTime.Now.AddMilliseconds(pt.PauseTimeMs); } + if (DateTime.Now >= _pauseUntil) { _inPause = false; Advance(route); } + return; + } + + // ── Chat ──────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Chat) + { + StopMovement(); + if (!_actionFired) + { + _actionFired = true; + try { _core.Actions.InvokeChatParser(pt.ChatCommand); } catch { } + Advance(route); + } + return; + } + + // ── Recall / PortalNPC ────────────────────────────────────────────── + if (pt.Type == NavPointType.Recall || pt.Type == NavPointType.PortalNPC) + { + if (_portalState == PortalState.None) StopMovement(); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try { _host.Actions.AddChatText($"[NavDbg] PORTAL state={_portalState} elapsed={(DateTime.Now - _portalStateStart).TotalMilliseconds:F0}ms", 1); } catch { } + } + ProcessPortalAction(pt, route); + return; + } + + // ── Standard coordinate waypoint ──────────────────────────────────── + _actionFired = false; + _inPause = false; + + var pos = GetPos(); + if (pos == null) return; + + double dNS = pt.NS - pos.NorthSouth; + double dEW = pt.EW - pos.EastWest; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (dist < ArrivalYards) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + + // ── Tier 2: delegate to client physics engine ──────────────────── + // The client's MovementManager handles interpolation, heading, and + // speed internally — no frame-by-frame PD-controller needed. + // Falls through to Tier 0/1 steering if not mode 2, not initialized, + // or player is indoors (coordinate conversion is outdoor-only). + if (_settings.MovementMode == 2 && Tier2MovementHelper.IsInitialized + && (Tier2MovementHelper.GetPlayerCellId() & 0xFFFF) < 0x100) + { + ProcessTier2Waypoint(idx, pt, route, pos, dist); + return; + } + + // ── Closest approach detection (Tier 0/1 only) ─────────────────── + // If we were getting closer (within a reasonable range) and now + // we're moving away, we've swept past the waypoint. Advance. + // This handles the case where the turn radius at speed prevents + // the character from entering the arrival radius exactly. + if (_prevDist < ArrivalYards * 2.5 && dist > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + _prevDist = dist; + + // ── Lookahead blend ───────────────────────────────────────────────── + double tNS = pt.NS, tEW = pt.EW; + if (dist < LookaheadYards) + { + int ni = PeekNext(idx, route); + if (ni >= 0) + { + var np = route.Points[ni]; + double t = 1.0 - (dist / LookaheadYards); + tNS = Lerp(pt.NS, np.NS, t); + tEW = Lerp(pt.EW, np.EW, t); + } + } + + // ── Compute heading error ─────────────────────────────────────────── + double desiredDeg = Math.Atan2(tEW - pos.EastWest, tNS - pos.NorthSouth) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + double rawHeading = 0; + try { rawHeading = _core.Actions.Heading; } catch { } + double currentDeg; + if (rawHeading != 0.0) + { currentDeg = rawHeading; _lastGoodHeading = rawHeading; _hasGoodHeading = true; } + else if (_hasGoodHeading) + { currentDeg = _lastGoodHeading; } + else + { currentDeg = desiredDeg; } + double error = NormalizeAngle(desiredDeg - currentDeg); + double absError = Math.Abs(error); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + string turnDir = absError < DEAD_ZONE ? "NONE" : (error > 0 ? "RIGHT" : "LEFT"); + double ox = 0, oy = 0; + try { var me = _core.WorldFilter[_core.CharacterFilter.Id]; if (me != null) { var o = me.Offset(); ox = o.X; oy = o.Y; } } catch { } + try { _host.Actions.AddChatText($"[NavDbg] raw={rawHeading:F1} cur={currentDeg:F1} des={desiredDeg:F1} err={error:F1} turn={turnDir} dist={dist:F1}yd oX={ox:F2} oY={oy:F2}", 1); } catch { } + } + + // ═════════════════════════════════════════════════════════════════════ + // STEERING + // ═════════════════════════════════════════════════════════════════════ + + // ── STATE: Turning in place (big turn while stopped) ───────────────── + if (_isTurning) + { + if (absError > BIG_TURN_EXIT) + { + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + return; + } + + // Close enough — clear turn keys, start running + _isTurning = false; + ClearTurnMotions(); + StartForward(); + return; + } + + // ── BIG TURN (>60°): stop and face ────────────────────────────────── + if (absError > BIG_TURN_ENTER) + { + StopForward(); + ClearTurnMotions(); + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + _isTurning = true; + return; + } + + // ── Ensure we're moving forward ───────────────────────────────────── + StartForward(); + + // ── Near waypoint: stop turning, just run straight ─────────────────── + bool closeToWaypoint = dist < ArrivalYards * 3.0; + + // ── SMALL CORRECTION: use TurnRight/TurnLeft while running ────────── + // These combine with Forward at the command interpreter level — + // the character turns while running naturally, like pressing W+A or W+D. + // No Actions.Heading, no motion interrupt, no W tap needed. + if (absError > DEAD_ZONE && !closeToWaypoint) + { + if (error > 0) + { + // Need to turn right + SetClientMotion(MOTION_TURNRIGHT, true); + SetClientMotion(MOTION_TURNLEFT, false); + } + else + { + // Need to turn left + SetClientMotion(MOTION_TURNLEFT, true); + SetClientMotion(MOTION_TURNRIGHT, false); + } + } + else + { + // On course or close to waypoint — stop turning + ClearTurnMotions(); + } + + // ── HEARTBEAT: re-assert autorun periodically as safety net ───────── + if (_isMovingForward && (DateTime.Now - _lastWTap).TotalMilliseconds > W_HEARTBEAT_MS) + { + try { _core.Actions.SetAutorun(true); } catch { } + _lastWTap = DateTime.Now; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // ROUTE ADVANCEMENT + // ══════════════════════════════════════════════════════════════════════════ + + private void Advance(VTankNavParser route) + { + _actionFired = false; + _prevDist = double.MaxValue; + switch (route.RouteType) + { + case NavRouteType.Circular: + _settings.ActiveNavIndex = (_settings.ActiveNavIndex + 1) % route.Points.Count; + break; + case NavRouteType.Linear: + int n = _settings.ActiveNavIndex + _linearDir; + if (n < 0 || n >= route.Points.Count) { _linearDir = -_linearDir; n = _settings.ActiveNavIndex + _linearDir; } + _settings.ActiveNavIndex = n; + break; + case NavRouteType.Once: + _settings.ActiveNavIndex++; + if (_settings.ActiveNavIndex >= route.Points.Count) { _settings.EnableNavigation = false; StopMovement(); } + break; + case NavRouteType.Follow: + _settings.ActiveNavIndex = 0; + break; + } + } + + private void HandleRouteEnd(VTankNavParser route) + { + if (route.RouteType == NavRouteType.Circular) _settings.ActiveNavIndex = 0; + else StopMovement(); + } + + private int PeekNext(int cur, VTankNavParser route) + { + switch (route.RouteType) + { + case NavRouteType.Circular: return (cur + 1) % route.Points.Count; + case NavRouteType.Linear: int n = cur + _linearDir; return (n >= 0 && n < route.Points.Count) ? n : -1; + case NavRouteType.Once: return (cur + 1 < route.Points.Count) ? cur + 1 : -1; + default: return -1; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // TIER 2 MOVEMENT (CPhysicsObj::MoveToPosition via MovementManager) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tier 2 waypoint processor — issues a single MoveToPosition call to the + /// client's physics engine, then lets it handle all interpolation and heading. + /// Re-issues the call on waypoint change or if no progress after timeout. + /// </summary> + private void ProcessTier2Waypoint( + int idx, NavPoint pt, VTankNavParser route, + CoordsObject pos, double distYards) + { + // ── Closest approach detection (shared with Tier 0/1) ──────────── + if (_prevDist < ArrivalYards * 2.5 && distYards > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + CancelTier2(); + Advance(route); + return; + } + _prevDist = distYards; + + // ── Decide whether to issue / re-issue the MoveToPosition call ─── + bool needsIssue = false; + + if (idx != _tier2TargetIdx) + { + // Waypoint changed — cancel old movement, issue new + CancelTier2(); + needsIssue = true; + } + else if (_tier2Active && + (DateTime.Now - _tier2IssuedAt).TotalMilliseconds > TIER2_REISSUE_MS) + { + // Timeout — re-issue in case the client gave up + CancelTier2(); + needsIssue = true; + } + else if (!_tier2Active) + { + needsIssue = true; + } + + if (needsIssue) + { + IssueTier2Move(pt, pos); + _tier2TargetIdx = idx; + } + + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 idx={idx} dist={distYards:F1}yd active={_tier2Active} " + + $"age={(DateTime.Now - _tier2IssuedAt).TotalMilliseconds:F0}ms", 1); + } + catch { } + } + } + + /// <summary> + /// Converts Decal NS/EW to internal AC coordinates and calls MoveToPosition. + /// Works by adding the yard-delta to the player's known-good internal position, + /// then normalizing cell/landblock boundaries with Math.Floor (critical for + /// negative deltas — (int) rounds toward zero, not down, producing garbage cells). + /// </summary> + private void IssueTier2Move(NavPoint pt, CoordsObject decalPos) + { + try + { + // Read player's internal position for coordinate reference + uint playerCell; + float playerX, playerY, playerZ; + if (!Tier2MovementHelper.GetPlayerPosition( + out playerCell, out playerX, out playerY, out playerZ)) + return; + + // Indoor cells (objcell_id & 0xFFFF >= 0x100) — fall back to Tier 0/1 + if ((playerCell & 0xFFFF) >= 0x100) + return; + + // ── AC cell ID format: 0xEENNcccc ──────────────────────────── + // EE (bits 24-31) = EW landblock index (increases east) + // NN (bits 16-23) = NS landblock index (increases north) + // cccc = outdoor cell 1-64: (rowNS * 8 + colEW + 1) + // Internal Position.Frame: x = EW, y = NS + // Each landblock = 8×8 cells, each cell = 24×24 yards + + // ── Delta in yards from Decal coordinates ──────────────────── + // Decal: 1 unit = 240 yards. EW→x, NS→y. + double deltaEW = (pt.EW - decalPos.EastWest) * 240.0; + double deltaNS = (pt.NS - decalPos.NorthSouth) * 240.0; + + // ── Safety: clamp to 500 yards max ─────────────────────────── + // Beyond ~2 landblocks the target cell is likely unloaded. + double deltaDist = Math.Sqrt(deltaEW * deltaEW + deltaNS * deltaNS); + if (deltaDist > 500.0) + { + // Scale delta to 500 yards — we'll re-issue when closer + double scale = 500.0 / deltaDist; + deltaEW *= scale; + deltaNS *= scale; + } + + // ── Compute target global position from player's known-good pos ─ + int pLbEW = (int)((playerCell >> 24) & 0xFF); + int pLbNS = (int)((playerCell >> 16) & 0xFF); + int pCellIdx = (int)(playerCell & 0xFFFF) - 1; + if (pCellIdx < 0 || pCellIdx >= 64) return; // invalid outdoor cell + int pColEW = pCellIdx % 8; + int pRowNS = pCellIdx / 8; + + double globalEW = pLbEW * 192.0 + pColEW * 24.0 + playerX + deltaEW; + double globalNS = pLbNS * 192.0 + pRowNS * 24.0 + playerY + deltaNS; + + // ── Decompose to landblock + cell + local ──────────────────── + // Math.Floor is critical — (int) truncates toward zero, which + // produces wrong results for negative coordinates. + int tLbEW = (int)Math.Floor(globalEW / 192.0); + int tLbNS = (int)Math.Floor(globalNS / 192.0); + tLbEW = Math.Max(0, Math.Min(254, tLbEW)); + tLbNS = Math.Max(0, Math.Min(254, tLbNS)); + + double inLbEW = globalEW - tLbEW * 192.0; + double inLbNS = globalNS - tLbNS * 192.0; + + int tColEW = (int)Math.Floor(inLbEW / 24.0); + int tRowNS = (int)Math.Floor(inLbNS / 24.0); + tColEW = Math.Max(0, Math.Min(7, tColEW)); + tRowNS = Math.Max(0, Math.Min(7, tRowNS)); + + float localX = (float)(inLbEW - tColEW * 24.0); + float localY = (float)(inLbNS - tRowNS * 24.0); + float localZ = playerZ; + + // Clamp to valid range within cell (guard against float drift) + localX = Math.Max(0.5f, Math.Min(23.5f, localX)); + localY = Math.Max(0.5f, Math.Min(23.5f, localY)); + + int cellIdx = tRowNS * 8 + tColEW + 1; + uint targetCell = (uint)((tLbEW << 24) | (tLbNS << 16) | cellIdx); + + // ── Sanity: target landblock within 3 of player ────────────── + // If further, the cell is almost certainly not loaded → skip. + if (Math.Abs(tLbEW - pLbEW) > 3 || Math.Abs(tLbNS - pLbNS) > 3) + { + if (DebugNav) + try { _host.Actions.AddChatText($"[NavDbg] T2 SKIP: target lb ({tLbEW},{tLbNS}) too far from player ({pLbEW},{pLbNS})", 1); } catch { } + return; + } + + uint result = Tier2MovementHelper.MoveToPosition( + targetCell, localX, localY, localZ, + 1.0f, + (float)Math.Max(0.5, ArrivalYards * 0.5)); + + _tier2Active = (result == 0); + _tier2IssuedAt = DateTime.Now; + + if (DebugNav) + { + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 issued: cell=0x{targetCell:X8} lx={localX:F1} ly={localY:F1} " + + $"lz={localZ:F1} lb=({tLbEW},{tLbNS}) delta=({deltaEW:F0},{deltaNS:F0})yd result={result}", 1); + } + catch { } + } + } + catch (Exception ex) + { + if (DebugNav) + try { _host.Actions.AddChatText($"[NavDbg] T2 issue FAILED: {ex.Message}", 1); } catch { } + } + } + + private void ProcessPortalAction(NavPoint pt, VTankNavParser route) + { + // Timeout check - if we've been in this portal action too long, reset and advance + if (_portalState != PortalState.None) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_STATE_TIMEOUT_MS) + { + ResetPortalState(); + Advance(route); + return; + } + } + + // Initialize state machine — go to Settling first to let turns stop + if (_portalState == PortalState.None) + { + _portalState = PortalState.Settling; + _portalStateStart = DateTime.Now; + _preCastLandblock = GetCurrentLandblock(); + // Store position for teleport detection + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + // Aggressively clear ALL motion + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + return; + } + + switch (_portalState) + { + case PortalState.Settling: + // Keep clearing turns every frame until settled + try { ClearTurnMotions(); } catch { } + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > SETTLE_DELAY_MS) + { + _portalState = PortalState.EquippingWand; + _portalStateStart = DateTime.Now; + } + break; + + case PortalState.EquippingWand: + ProcessEquippingWand(pt); + break; + + case PortalState.EnteringMagicMode: + ProcessEnteringMagicMode(); + break; + + case PortalState.CastingSpell: + ProcessCastingSpell(pt); + break; + + case PortalState.WaitingForPortalOrTeleport: + ProcessWaitingForPortalOrTeleport(pt, route); + break; + + case PortalState.WaitingForPortalExit: + ProcessWaitingForPortalExit(route); + break; + + case PortalState.PostTeleportSettle: + // Hammer stop commands to cancel any lingering UseItem walk action + // UseItem walk persists through teleportation in the AC client — need + // to keep hammering for ~2s until it expires on its own + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > 4000) + { + ResetPortalState(); + Advance(route); + } + break; + } + } + + private void ProcessEquippingWand(NavPoint pt) + { + // Only equip wand for recall spells, not portal NPCs + if (pt.Type == NavPointType.PortalNPC) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + + // Use the portal NPC — partial name matching + try + { + WorldObject bestMatch = null; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.Name == pt.TargetName) { bestMatch = wo; break; } + if (wo.Name != null && pt.TargetName != null && + (wo.Name.Contains(pt.TargetName) || pt.TargetName.Contains(wo.Name))) + { bestMatch = wo; } + } + if (bestMatch != null) + _core.Actions.UseItem(bestMatch.Id, 0); + } + catch { } + return; + } + + // For recall spells, equip a wand if needed + double elapsed = (DateTime.Now - _portalStateStart).TotalMilliseconds; + + if (elapsed < 50) + { + try + { + // Check if wand already equipped — UseItem on equipped wand UNEQUIPS it + bool wandEquipped = false; + int wandToEquip = 0; + + // Scan all known objects for wands + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + int slots = wo.Values(LongValueKey.EquippedSlots, 0); + if (slots != 0) + { + wandEquipped = true; + break; + } + else if (wandToEquip == 0) + { + wandToEquip = wo.Id; // remember first unequipped wand + } + } + } + + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + if (DebugNav) try { _host.Actions.AddChatText($"[NavDbg] WAND equipping id={wandToEquip}", 1); } catch { } + } + else if (wandEquipped) + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND already equipped, skipping", 1); } catch { } + } + else + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND none found in inventory!", 1); } catch { } + } + } + catch { } + } + + // Wait for wand equip to complete, then proceed to magic mode + if (elapsed > WAND_EQUIP_DELAY_MS) + { + _portalState = PortalState.EnteringMagicMode; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessEnteringMagicMode() + { + // Enter magic casting mode + try + { + _core.Actions.SetCombatMode(CombatState.Magic); + } + catch { } + + // Wait a moment for mode change, then proceed + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > MAGIC_MODE_DELAY_MS) + { + _portalState = PortalState.CastingSpell; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessCastingSpell(NavPoint pt) + { + // Cast the recall spell + if ((DateTime.Now - _portalStateStart).TotalMilliseconds < 100) // Only cast once + { + try + { + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + } + catch { } + } + + // Wait a moment for cast, then proceed to waiting + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > CAST_DELAY_MS) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + } + } + + private void ProcessWaitingForPortalOrTeleport(NavPoint pt, VTankNavParser route) + { + // Detect teleport by checking if we moved far from pre-portal position + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (distFromStart > 50.0) // moved > 50 yards = definitely teleported + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Also check landblock as fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + + // For PortalNPC: no short timeout — let UseItem walk complete. + // The global PORTAL_STATE_TIMEOUT_MS (15s) handles overall timeout. + // For Recall: use shorter timeout since teleport should be instant. + if (pt.Type == NavPointType.Recall) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_WAIT_MS) + { + ResetPortalState(); + Advance(route); + } + } + } + + private void ProcessWaitingForPortalExit(VTankNavParser route) + { + // Distance-based teleport detection + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (distFromStart > 50.0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Landblock fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + } + } + + private void ResetPortalState() + { + _portalState = PortalState.None; + _portalStateStart = DateTime.MinValue; + _preCastLandblock = 0; + _prePortalLandblock = 0; + _prePortalNS = double.NaN; + _prePortalEW = double.NaN; + + // Return to peace mode after portal/recall + try + { + _core.Actions.SetCombatMode(CombatState.Peace); + } + catch { } + } + + private int GetCurrentLandblock() + { + try + { + var pos = GetPos(); + if (pos != null) + { + // Landblock is the high word of the location + // AC coordinates encode landblock in a specific way + // For simplicity, we'll use a combination of NS/EW rounded to detect changes + int nsBlock = (int)(pos.NorthSouth / 0.8); + int ewBlock = (int)(pos.EastWest / 0.8); + return (nsBlock << 16) | (ewBlock & 0xFFFF); + } + } + catch { } + return 0; + } + + private void FireSpecialAction(NavPoint pt) + { + // Legacy method - now mostly unused, kept for compatibility + try + { + if (pt.Type == NavPointType.Recall) + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + else if (pt.Type == NavPointType.PortalNPC) + { + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo != null && wo.Name == pt.TargetName) { _core.Actions.UseItem(wo.Id, 0); break; } + } + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // STUCK WATCHDOG + // ══════════════════════════════════════════════════════════════════════════ + + private void UpdateWatchdog() + { + if (DateTime.Now < _watchdogNext) return; + _watchdogNext = DateTime.Now.AddMilliseconds(WATCHDOG_MS); + + var pos = GetPos(); + if (pos == null) return; + + double curNS = pos.NorthSouth, curEW = pos.EastWest; + + if (!double.IsNaN(_watchdogNS) && _isMovingForward) + { + bool dataStale = Math.Abs(curNS - _watchdogNS) < 0.000001 + && Math.Abs(curEW - _watchdogEW) < 0.000001 + && !IsGameFocused(); + + if (!dataStale) + { + double dN = curNS - _watchdogNS, dE = curEW - _watchdogEW; + double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0; + if (moved < STUCK_YD) { _stuckCount++; BeginRecovery(); } + else _stuckCount = 0; + } + } + _watchdogNS = curNS; _watchdogEW = curEW; + } + + private void BeginRecovery() + { + _inRecovery = true; + _recoveryUntil = DateTime.Now.AddMilliseconds(RECOVERY_MS); + StopMovement(); + + // Jump to try to unstick + try + { + if (MovementActionHelper.IsInitialized) + { + // Tier 1: direct jump call — no keyboard/motion interpreter dependency + MovementActionHelper.JumpNonAutonomous(0.5f); + } + else + { + // Legacy: local motion command for jump + SetClientMotion(0x2500003b, true); + SetClientMotion(0x2500003b, false); + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC LIFECYCLE + // ══════════════════════════════════════════════════════════════════════════ + + public void Stop() + { + _inPause = false; _actionFired = false; _inRecovery = false; + _linearDir = 1; _stopRequestedAt = DateTime.MaxValue; + ResetPortalState(); + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + _turnsStopped = true; + } + + public void ResetRouteState() + { + Stop(); + _stuckCount = 0; + _prevDist = double.MaxValue; + _watchdogNS = double.NaN; _watchdogEW = double.NaN; + _hasGoodHeading = false; + } + + public int FindNearestWaypoint(VTankNavParser route) + { + if (route == null || route.Points == null || route.Points.Count == 0) + return 0; + + try + { + var pos = GetPos(); + if (pos == null) + return 0; + + double myNS = pos.NorthSouth; + double myEW = pos.EastWest; + + int nearestIdx = 0; + double nearestDist = double.MaxValue; + + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; + // Only consider regular waypoints, not special actions + if (pt.Type == NavPointType.Point) + { + double dNS = pt.NS - myNS; + double dEW = pt.EW - myEW; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW); + + if (dist < nearestDist) + { + nearestDist = dist; + nearestIdx = i; + } + } + } + + return nearestIdx; + } + catch + { + return 0; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // UTILITIES + // ══════════════════════════════════════════════════════════════════════════ + + private bool IndexValid(int i, VTankNavParser r) => r?.Points != null && i >= 0 && i < r.Points.Count; + + private CoordsObject GetPos() + { + try { return _core.WorldFilter[_core.CharacterFilter.Id].Coordinates(); } + catch { return null; } + } + + private static double NormalizeAngle(double a) + { + while (a > 180.0) a -= 360.0; + while (a < -180.0) a += 360.0; + return a; + } + + private static double Lerp(double a, double b, double t) => a + (b - a) * t; + } +} diff --git a/Plugins/RynthAi/Logic/RynthJumper.cs b/Plugins/RynthAi/Logic/RynthJumper.cs new file mode 100644 index 0000000..da30d5e --- /dev/null +++ b/Plugins/RynthAi/Logic/RynthJumper.cs @@ -0,0 +1,256 @@ +using System; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Native RynthAi jump system — no UB dependency. + /// Tier 1: Uses CM_Movement::Event_Jump_NonAutonomous for direct jump + /// commands when MovementActionHelper is initialized (no keyboard input). + /// Fallback: PostMessage keyboard simulation for legacy mode. + /// Direction keys (W/X/Z/C) still use PostMessage in Tier 1 since + /// they control local physics direction. Tier 2 will replace these. + /// Flow: Face heading → hold direction keys → jump → release → resume macro + /// </summary> + public class RynthJumper + { + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); + + private const uint WM_KEYDOWN = 0x0100; + private const uint WM_KEYUP = 0x0101; + + // AC key codes + private const uint VK_SPACE = 0x20; // Jump + private const uint VK_SHIFT = 0x10; // Run modifier + private const uint VK_W = 0x57; // Forward + private const uint VK_X = 0x58; // Backward + private const uint VK_Z = 0x5A; // Slide left + private const uint VK_C = 0x43; // Slide right + + private enum JumpState { Idle, Turning, HoldingKeys, Done } + private JumpState _state = JumpState.Idle; + + private PluginHost _host; + private UISettings _settings; + + // Jump parameters + private double _targetHeading; + private int _holdTimeMs; + private bool _addShift, _addW, _addX, _addZ, _addC; + private DateTime _stateStart; + private int _turnRetries; + private const int MAX_TURN_RETRIES = 50; // 50 * 100ms = 5 seconds + + public bool IsJumping => _state != JumpState.Idle; + + public RynthJumper(PluginHost host, UISettings settings) + { + _host = host; + _settings = settings; + } + + /// <summary> + /// Start a jump. Mirrors /ub jump[swzxc] [heading] [holdtime] + /// </summary> + /// <param name="heading">Heading to face (0-359), or -1 for current heading</param> + /// <param name="holdTimeMs">How long to hold jump key (0-1000ms)</param> + /// <param name="shift">S modifier — run</param> + /// <param name="forward">W — forward</param> + /// <param name="backward">X — backward</param> + /// <param name="slideLeft">Z — slide left</param> + /// <param name="slideRight">C — slide right</param> + public void StartJump(double heading, int holdTimeMs, bool shift, bool forward, bool backward, bool slideLeft, bool slideRight) + { + if (_state != JumpState.Idle) return; + + _holdTimeMs = Math.Max(0, Math.Min(1000, holdTimeMs)); + _addShift = shift; + _addW = forward; + _addX = backward; + _addZ = slideLeft; + _addC = slideRight; + _turnRetries = 0; + + // Pause macro during jump + _settings.IsMacroRunning = false; + + if (heading >= 0) + { + _targetHeading = heading; + _state = JumpState.Turning; + CoreManager.Current.Actions.Heading = (float)_targetHeading; + } + else + { + _targetHeading = CoreManager.Current.Actions.Heading; + // No turn needed — go straight to keys + _state = JumpState.HoldingKeys; + PressKeys(); + } + _stateStart = DateTime.Now; + } + + /// <summary> + /// Tap jump — no heading change, no hold time. + /// Uses CM_Movement::Event_Jump_NonAutonomous for a minimal jump + /// when available, falls back to PostMessage keyboard simulation. + /// </summary> + public void TapJump() + { + if (_state != JumpState.Idle) return; + + // Tier 1: direct acclient.exe call — no keyboard input needed + if (MovementActionHelper.IsInitialized) + { + MovementActionHelper.JumpNonAutonomous(0.01f); // minimal extent = tap + return; + } + + // Legacy fallback: keyboard simulation + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + if (hwnd == IntPtr.Zero) return; + + PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001); + PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001); + } + + /// <summary> + /// Called every frame by PluginCore. Drives the jump state machine. + /// </summary> + public void Think() + { + if (_state == JumpState.Idle) return; + + switch (_state) + { + case JumpState.Turning: + // Check if heading is close enough + double currentHeading = CoreManager.Current.Actions.Heading; + if (Math.Abs(_targetHeading - currentHeading) < 2.0 || + Math.Abs(_targetHeading - currentHeading) > 358.0) // Handle 0/360 wrap + { + // Heading matched — start the jump + _state = JumpState.HoldingKeys; + _stateStart = DateTime.Now; + PressKeys(); + } + else + { + _turnRetries++; + // Keep setting heading every 100ms + if (_turnRetries % 5 == 0) + CoreManager.Current.Actions.Heading = (float)_targetHeading; + + // Timeout after 5 seconds + if (_turnRetries > MAX_TURN_RETRIES) + { + try { _host?.Actions?.AddChatText("[RynthAi] Jump: turn timed out", 2); } catch { } + Finish(); + } + } + break; + + case JumpState.HoldingKeys: + // Tier 1: jump already fired with correct extent in PressKeys(). + // Direction keys only need ~100ms for physics to register direction. + // Legacy: space bar held to build power bar over holdTimeMs. + int effectiveHold = (MovementActionHelper.IsInitialized && _holdTimeMs > 100) + ? 100 // Tier 1: brief hold for direction registration + : _holdTimeMs; + + if ((DateTime.Now - _stateStart).TotalMilliseconds >= effectiveHold) + { + ReleaseKeys(); + _state = JumpState.Done; + _stateStart = DateTime.Now; + } + break; + + case JumpState.Done: + // Brief delay after releasing keys before resuming macro + if ((DateTime.Now - _stateStart).TotalMilliseconds >= 200) + { + Finish(); + } + break; + } + } + + private void PressKeys() + { + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + + // Tier 1: Use direct jump call for the jump itself. + // Direction keys (W/X/Z/C) still need PostMessage since they control + // local movement direction during the jump, which DoMovementCommand + // doesn't handle (it's server-side only). Tier 2 will replace these + // with CPhysicsObj movement calls. + if (MovementActionHelper.IsInitialized) + { + // Press direction modifiers via PostMessage (needed for local physics) + if (hwnd != IntPtr.Zero) + { + if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001); + if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001); + if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001); + if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001); + if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001); + } + + // Map holdTimeMs to jump extent (0.0–1.0) + // AC power bar fills over ~1000ms, so holdTime/1000 approximates extent + float extent = Math.Max(0.01f, Math.Min(1.0f, _holdTimeMs / 1000.0f)); + MovementActionHelper.JumpNonAutonomous(extent); + return; + } + + // Legacy fallback: all keyboard simulation + if (hwnd == IntPtr.Zero) return; + PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001); + if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001); + if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001); + if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001); + if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001); + if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001); + } + + private void ReleaseKeys() + { + IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero; + if (hwnd == IntPtr.Zero) return; + + // Legacy mode: release space bar (Tier 1 never pressed it) + if (!MovementActionHelper.IsInitialized) + PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001); + + // Release direction keys (used by both Tier 1 and Legacy) + if (_addShift) PostMessage(hwnd, WM_KEYUP, VK_SHIFT, 0xC02A0001); + if (_addW) PostMessage(hwnd, WM_KEYUP, VK_W, 0xC0110001); + if (_addX) PostMessage(hwnd, WM_KEYUP, VK_X, 0xC02D0001); + if (_addZ) PostMessage(hwnd, WM_KEYUP, VK_Z, 0xC02C0001); + if (_addC) PostMessage(hwnd, WM_KEYUP, VK_C, 0xC02E0001); + } + + private void Finish() + { + _state = JumpState.Idle; + _addShift = _addW = _addX = _addZ = _addC = false; + _turnRetries = 0; + // Resume macro + _settings.IsMacroRunning = true; + try { _host?.Actions?.AddChatText("[RynthAi] Jump complete", 5); } catch { } + } + + public void Cancel() + { + if (_state != JumpState.Idle) + { + ReleaseKeys(); + Finish(); + } + } + } +} diff --git a/Plugins/RynthAi/Loot/LootManager.cs b/Plugins/RynthAi/Loot/LootManager.cs new file mode 100644 index 0000000..b4171be --- /dev/null +++ b/Plugins/RynthAi/Loot/LootManager.cs @@ -0,0 +1,1150 @@ +using Decal.Adapter.Wrappers; +using Decal.Adapter; +using System.Collections.Generic; +using System.Linq; +using System; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + public class LootManager : IDisposable + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + private FellowshipTracker _fellowshipTracker; + + private VTClassic.LootCore _vtLootCore; + private VTankLootProfile _parsedLootProfile; + private string _loadedProfilePath = ""; + private DateTime _loadedProfileWriteTimeUtc = DateTime.MinValue; + private int _lastSelectedId = 0; + + // --- Auto Cram & Stack --- + private DateTime _nextInventoryActionTime = DateTime.MinValue; + private HashSet<string> _failedStackPairs = new HashSet<string>(); + private HashSet<int> _cramBlacklist = new HashSet<int>(); + private DateTime _lastBlacklistClear = DateTime.MinValue; + private const double BLACKLIST_CLEAR_INTERVAL_MS = 30000.0; // Clear every 30 seconds + private bool _inventoryDirty = true; // Start dirty so first scan happens + private int _lastInventoryCount = 0; // Track inventory count changes + + // --- Looting State Machine --- + private enum LootState { Idle, Approaching, WaitingForContents, Identifying, Looting, Closing } + private LootState _lootState = LootState.Idle; + private int _targetCorpseId = 0; + private DateTime _lootTimer = DateTime.MinValue; + private HashSet<int> _lootedCorpses = new HashSet<int>(); + + // --- Sequential Scanner Variables --- + private int _currentItemIdx = 0; + private int _itemsLootedFromCorpse = 0; + private List<int> _corpseItemsToCheck = new List<int>(); + private int _lootRetryCount = 0; + private int _assessingItemId = 0; + private DateTime _assessItemStart = DateTime.MinValue; + private DateTime _lastAssessRequest = DateTime.MinValue; + private DateTime _stateEnteredAt = DateTime.MinValue; + private DateTime _lastOpenAttemptAt = DateTime.MinValue; + private DateTime _openedContainerAt = DateTime.MinValue; + private DateTime _lastContentsCheckAt = DateTime.MinValue; + private DateTime _lastLootPickupTime = DateTime.MinValue; // Inter-item delay timer + // Loot timing now driven by _settings — see UISettings for defaults + private readonly string _debugLogPath = @"C:\Projects\NexSuite\Plugins\RynthAi\Loot\loot-debug.log"; + + // --- VTank-style Deferred Salvage System --- + // Items are picked up during looting, then salvaged during idle phase + // --- Single-Item Salvage System --- + // Items are picked up during looting, then salvaged one at a time during idle phase + // First item has longer delays (panel opening), subsequent items are faster + private bool _isSalvagingCurrentItem = false; + private Queue<int> _salvageQueue = new Queue<int>(); + private DateTime _nextSalvageAction = DateTime.MinValue; + private enum SalvagePhase { Idle, OpeningPanel, AddingItem, Salvaging, WaitingForResult, CombiningSalvage } + private SalvagePhase _salvagePhase = SalvagePhase.Idle; + private int _currentSalvageItemId = 0; + private bool _salvagePanelOpened = false; // True after first item — faster delays + private DateTime _salvagePhaseStart = DateTime.MinValue; + + public LootManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + try + { + _vtLootCore = new VTClassic.LootCore(); + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] VTClassic Load Error: {ex.Message}", 1); + } + } + + public void SetFellowshipTracker(FellowshipTracker tracker) + { + _fellowshipTracker = tracker; + } + + // Restored for PluginCore/CommandProcessor compatibility + public void ForceReload() + { + _loadedProfilePath = ""; + _loadedProfileWriteTimeUtc = DateTime.MinValue; + } + + // Restored for CommandProcessor compatibility + public void SaveProfile(string path) + { + // Placeholder: VTank profiles are typically managed within the VTank UI + } + + public void LoadProfile(string path) + { + _loadedProfilePath = path; + _loadedProfileWriteTimeUtc = DateTime.MinValue; + _parsedLootProfile = null; + + if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) + { + DebugLog($"LoadProfile skipped path='{path}' exists={System.IO.File.Exists(path)}"); + return; + } + + try + { + // DESTROY the old engine to clear the internal cache before reloading + if (_vtLootCore != null) + { + _vtLootCore.UnloadProfile(); + _vtLootCore = null; + } + + _vtLootCore = new VTClassic.LootCore(); + _vtLootCore.LoadProfile(path, false); + + _parsedLootProfile = VTankLootParser.Load(path); + _loadedProfileWriteTimeUtc = File.GetLastWriteTimeUtc(path); + + DebugLog($"LoadProfile ok path='{path}' parsedRules={(_parsedLootProfile?.Rules?.Count ?? 0)}"); + if (_parsedLootProfile?.Rules != null) + { + for (int i = 0; i < _parsedLootProfile.Rules.Count && i < 5; i++) + { + var r = _parsedLootProfile.Rules[i]; + if (r == null) continue; + DebugLog($"Rule[{i}] name='{r.Name}' action={r.Action} info='{r.RawInfoLine}'"); + } + } + _host.Actions.AddChatText($"[RynthAi] Loaded Loot Profile: {System.IO.Path.GetFileName(path)}", 1); + } + catch (Exception ex) + { + DebugLog($"LoadProfile error path='{path}' msg='{ex.Message}'"); + _host.Actions.AddChatText($"[RynthAi] Error loading {path}", 1); + } + } + + /// <summary> + /// Returns true if salvage has items queued or is actively processing. + /// </summary> + public bool IsSalvageActive => _salvageQueue.Count > 0 || _salvagePhase != SalvagePhase.Idle; + + /// <summary> + /// Returns true if salvage should block combat/nav. + /// True when: queue has items ready to salvage (not looting) OR panel is actively open. + /// </summary> + public bool IsSalvageProcessing + { + get + { + // Panel is actively open — always block + if (_salvagePhase != SalvagePhase.Idle) return true; + // Queue has items and we're not looting a corpse — about to start salvaging + if (_salvageQueue.Count > 0 && _lootState == LootState.Idle) return true; + return false; + } + } + + /// <summary> + /// Returns true if actively looting a corpse (don't block looting with salvage priority). + /// </summary> + public bool IsLootingCorpse => _lootState != LootState.Idle; + + /// <summary> + /// Process salvage queue — called every frame, highest priority. + /// Runs independently of loot state (items are already in inventory). + /// </summary> + public void ProcessSalvage() + { + if (!_settings.IsMacroRunning) return; + if (_salvageQueue.Count == 0 && _salvagePhase == SalvagePhase.Idle) return; + if (_lootState != LootState.Idle) return; // Don't salvage while looting a corpse + if (_core.Actions.BusyState != 0) return; + ProcessIdleSalvage(); + } + + /// <summary> + /// Process autostack — only when server is idle (not casting spells). + /// </summary> + public bool ProcessStack() + { + if (!_settings.IsMacroRunning) return false; + if (_core.Actions.BusyState != 0) return false; // Don't move items while casting + if (DateTime.Now < _nextInventoryActionTime) return false; + if (!_inventoryDirty) return false; + if (ProcessAutoStack()) { _nextInventoryActionTime = DateTime.Now.AddMilliseconds(500); return true; } + return false; + } + + /// <summary> + /// Process autocram — only when server is idle (not casting spells). + /// </summary> + public bool ProcessCram() + { + if (!_settings.IsMacroRunning) return false; + if (_core.Actions.BusyState != 0) return false; // Don't move items while casting + if (DateTime.Now < _nextInventoryActionTime) return false; + if (!_inventoryDirty) return false; + if (ProcessAutoCram()) { _nextInventoryActionTime = DateTime.Now.AddMilliseconds(500); return true; } + _inventoryDirty = false; + _nextInventoryActionTime = DateTime.Now.AddMilliseconds(2000); + return false; + } + + public void OnHeartbeat() + { + if (_settings.CurrentLootPath != _loadedProfilePath) + { + LoadProfile(_settings.CurrentLootPath); + } + else if (!string.IsNullOrEmpty(_settings.CurrentLootPath) && File.Exists(_settings.CurrentLootPath)) + { + var writeTime = File.GetLastWriteTimeUtc(_settings.CurrentLootPath); + if (writeTime > _loadedProfileWriteTimeUtc) + { + DebugLog($"Profile changed on disk, reloading path='{_settings.CurrentLootPath}'"); + LoadProfile(_settings.CurrentLootPath); + } + } + TestSelectionLogic(); + + if (!_settings.IsMacroRunning) return; + + // Periodically clear autostack/autocram blacklists + if ((DateTime.Now - _lastBlacklistClear).TotalMilliseconds >= BLACKLIST_CLEAR_INTERVAL_MS) + { + _failedStackPairs.Clear(); + _cramBlacklist.Clear(); + _lastBlacklistClear = DateTime.Now; + } + + // Dirty detection for inventory changes + int currentInvCount = 0; + try { currentInvCount = _core.WorldFilter.GetInventory().Count; } catch { } + if (currentInvCount != _lastInventoryCount) + { + _inventoryDirty = true; + _lastInventoryCount = currentInvCount; + } + + if (!_settings.EnableLooting) return; + + // Don't loot if a higher-priority system has claimed the state + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Looting") + { + if (_lootState != LootState.Idle) ResetLootingState(); + return; + } + + ProcessLootingState(); + } + + private void ProcessLootingState() + { + switch (_lootState) + { + case LootState.Idle: + // Don't start next corpse while salvage is running + if (_salvagePhase != SalvagePhase.Idle) return; + + int nearest = FindNearestCorpse(); + if (nearest != 0) + { + DebugLog($"Idle->Approaching corpse={nearest}"); + _targetCorpseId = nearest; + _currentItemIdx = 0; + _itemsLootedFromCorpse = 0; + _corpseItemsToCheck.Clear(); + _settings.CurrentState = "Looting"; + + // Open the corpse ONCE + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + + _lootState = LootState.Approaching; + _stateEnteredAt = DateTime.Now; + _lastOpenAttemptAt = DateTime.Now; + _lootTimer = DateTime.Now; + } + break; + + case LootState.Approaching: + // Check if corpse opened + if (_core.Actions.OpenedContainer == _targetCorpseId) + { + _lootState = LootState.WaitingForContents; + _stateEnteredAt = DateTime.Now; + _openedContainerAt = DateTime.Now; + _lootTimer = DateTime.Now; + DebugLog($"Approaching->WaitingForContents corpse={_targetCorpseId} (opened)"); + } + else + { + // NOT open yet — only retry UseItem after the configured delay + // UseItem is a TOGGLE — calling it again would close it + if ((DateTime.Now - _lastOpenAttemptAt).TotalMilliseconds >= _settings.LootOpenRetryMs) + { + // 8 seconds passed, corpse still not open — retry ONCE + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + _lastOpenAttemptAt = DateTime.Now; + DebugLog($"Approaching: retry open after 8s corpse={_targetCorpseId}"); + } + + // If close enough but not open, just wait — the server is processing + // Timeout after 10 seconds total + if ((DateTime.Now - _stateEnteredAt).TotalSeconds > 10) + { + DebugLog($"Approaching timeout corpse={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); + ResetLootingState(); + } + } + break; + + case LootState.WaitingForContents: + // Corpse is confirmed open — DO NOT call UseItem again (it would close it!) + if (_core.Actions.OpenedContainer == _targetCorpseId) + { + // Give server a moment to populate contents + if ((DateTime.Now - _openedContainerAt).TotalMilliseconds < _settings.LootContentSettleMs) return; + + var items = _core.WorldFilter.GetByContainer(_targetCorpseId); + if (items != null && items.Count > 0) + { + _corpseItemsToCheck = items.Select(i => i.Id).ToList(); + DebugLog($"Corpse contents loaded id={_targetCorpseId}, items={_corpseItemsToCheck.Count}"); + _lootState = LootState.Identifying; + _lootTimer = DateTime.Now; + } + else + { + // Empty — wait briefly for items to populate, then close + if ((DateTime.Now - _openedContainerAt).TotalMilliseconds > _settings.LootEmptyCorpseMs) + { + DebugLog($"Corpse confirmed empty id={_targetCorpseId}"); + _lootState = LootState.Closing; + } + } + } + else + { + // Container closed unexpectedly (server closed it, or something toggled it) + // Wait briefly then retry open ONCE + if ((DateTime.Now - _stateEnteredAt).TotalSeconds > 4) + { + DebugLog($"WaitingForContents: container closed, giving up on corpse={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); + ResetLootingState(); + } + else if ((DateTime.Now - _lastOpenAttemptAt).TotalMilliseconds >= _settings.LootOpenRetryMs) + { + // Retry open once after 3s + _host.Actions.SelectItem(_targetCorpseId); + _host.Actions.UseItem(_targetCorpseId, 0); + _lastOpenAttemptAt = DateTime.Now; + DebugLog($"WaitingForContents: re-opening corpse={_targetCorpseId}"); + } + } + break; + + case LootState.Identifying: + // Inter-item delay + if (_lastLootPickupTime != DateTime.MinValue && + (DateTime.Now - _lastLootPickupTime).TotalMilliseconds < _settings.LootInterItemDelayMs) + return; + + if (_currentItemIdx >= _corpseItemsToCheck.Count) + { + // Before closing: verify no lootable items are still on the corpse + var remaining = _core.WorldFilter.GetByContainer(_targetCorpseId); + if (remaining != null) + { + foreach (var rem in remaining) + { + string skipReason; + bool isSalv; + if (ShouldLootItem(rem.Id, rem, out skipReason, out isSalv)) + { + DebugLog($"Pre-close check: {rem.Name} still on corpse, looting"); + _host.Actions.MoveItem(rem.Id, _core.CharacterFilter.Id, 0, false); + _lootTimer = DateTime.Now; + _lootRetryCount = 0; + _lootState = LootState.Looting; + return; + } + } + } + _lootState = LootState.Closing; + if (_itemsLootedFromCorpse == 0) + { + try { _host.Actions.AddChatText($"[RynthAi] No items on corpse matched loot rules ({_corpseItemsToCheck.Count} scanned)", 5); } catch { } + } + return; + } + + int id = _corpseItemsToCheck[_currentItemIdx]; + var wo = _core.WorldFilter[id]; + if (wo == null || wo.Container != _targetCorpseId) + { + _currentItemIdx++; + _lootTimer = DateTime.Now; + return; + } + + // Assessment + if (_assessingItemId != id) + { + _assessingItemId = id; + _assessItemStart = DateTime.Now; + _lastAssessRequest = DateTime.MinValue; + } + + double assessMs = (DateTime.Now - _assessItemStart).TotalMilliseconds; + bool needsId = uTank2.PluginCore.PC.FLootPluginQueryNeedsID(id); + + if (needsId && (DateTime.Now - _lastAssessRequest).TotalMilliseconds >= 250) + { + _host.Actions.RequestId(id); + _lastAssessRequest = DateTime.Now; + } + + if (needsId && assessMs < _settings.LootAssessWindowMs) return; + + string decisionReason; + if (ShouldLootItem(id, wo, out decisionReason, out _isSalvagingCurrentItem)) + { + string actionStr = _isSalvagingCurrentItem ? "SALVAGE" : "KEEP"; + DebugLog($"Assess {actionStr} id={id} name='{wo.Name}' via={decisionReason}"); + _host.Actions.AddChatText($"[RynthAi] Scooping {wo.Name} (via {decisionReason})", 1); + _host.Actions.MoveItem(id, _core.CharacterFilter.Id, 0, false); + _lootState = LootState.Looting; _lootTimer = DateTime.Now; _lootRetryCount = 0; + return; + } + DebugLog($"Assess SKIP id={id} name='{wo.Name}' needsId={needsId} elapsedMs={assessMs:0} via={decisionReason}"); + _currentItemIdx++; + _assessingItemId = 0; + _lootTimer = DateTime.Now; + break; + + case LootState.Looting: + int vId = _corpseItemsToCheck[_currentItemIdx]; + var itemToVerify = _core.WorldFilter[vId]; + if (itemToVerify == null || itemToVerify.Container != _targetCorpseId) + { + DebugLog($"Looted/moved id={vId}"); + if (_isSalvagingCurrentItem) + { + _salvageQueue.Enqueue(vId); + DebugLog($"Queued for salvage id={vId} (queue={_salvageQueue.Count})"); + } + _isSalvagingCurrentItem = false; + _inventoryDirty = true; + _itemsLootedFromCorpse++; + _lastLootPickupTime = DateTime.Now; + _currentItemIdx++; _lootState = LootState.Identifying; + } + else if ((DateTime.Now - _lootTimer).TotalMilliseconds > _settings.LootRetryTimeoutMs) + { + _lootRetryCount++; + if (_lootRetryCount > 5) + { + DebugLog($"Loot retries exhausted id={vId}"); + _currentItemIdx++; _lootState = LootState.Identifying; + } + else + { + DebugLog($"Loot retry id={vId} attempt={_lootRetryCount}"); + _host.Actions.MoveItem(vId, _core.CharacterFilter.Id, 0, false); + _lootTimer = DateTime.Now; + } + } + break; + + case LootState.Closing: + // Brief settle before closing + if (_openedContainerAt != DateTime.MinValue && (DateTime.Now - _openedContainerAt).TotalMilliseconds < _settings.LootClosingDelayMs) + return; + + DebugLog($"Closing corpse id={_targetCorpseId}"); + _lootedCorpses.Add(_targetCorpseId); // Mark as done + // Close the corpse by using it (toggle) + _host.Actions.UseItem(_targetCorpseId, 0); + _host.Actions.SelectItem(0); + ResetLootingState(); + break; + } + } + + private int FindUST() + { + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Name == null) continue; + + // NEVER match actual salvage bags — they contain "Salvage" but are ObjectClass.Salvage + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Salvage) continue; + + // Match by exact name "Ust" or names containing "Salvaging Tool" + // The AC item is literally named "Ust" — exact match is safest + if (item.Name.Equals("Ust", StringComparison.OrdinalIgnoreCase)) + return item.Id; + + // Fallback: "Ust" as part of a longer name (e.g., custom servers) + // But exclude items that contain common false-positive substrings + if (item.Name.Equals("Salvaging Tool", StringComparison.OrdinalIgnoreCase) || + item.Name.Equals("Ust of Mhoire", StringComparison.OrdinalIgnoreCase)) + return item.Id; + } + return 0; + } + // ══════════════════════════════════════════════════════════════════════════ + // SINGLE-ITEM SALVAGE PROCESSOR (No UB dependency) + // Opens panel → adds ONE item → Salvage → repeat for next + // First item: full delays. Subsequent items: faster. + // ══════════════════════════════════════════════════════════════════════════ + + private void ProcessIdleSalvage() + { + if (_salvageQueue.Count == 0 && _salvagePhase == SalvagePhase.Idle) return; + if (_core.Actions.BusyState != 0) return; + + // SAFETY: Global timeout — re-queue item if stuck + if (_salvagePhase != SalvagePhase.Idle && (DateTime.Now - _salvagePhaseStart).TotalMilliseconds > 10000) + { + DebugLog($"IdleSalvage: TIMEOUT in phase {_salvagePhase}, re-queuing item {_currentSalvageItemId}"); + if (_currentSalvageItemId != 0 && IsItemInPlayerInventory(_currentSalvageItemId)) + { + var wo = _core.WorldFilter[_currentSalvageItemId]; + if (wo != null && wo.ObjectClass != Decal.Adapter.Wrappers.ObjectClass.Salvage) + _salvageQueue.Enqueue(_currentSalvageItemId); + } + _salvagePhase = SalvagePhase.Idle; + _currentSalvageItemId = 0; + return; + } + + // Delays: first item slower (panel opening), subsequent near-instant + double openDelay = _salvagePanelOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; + double addDelay = _salvagePanelOpened ? _settings.SalvageAddDelayFastMs : _settings.SalvageAddDelayFirstMs; + double salvageDelay = _settings.SalvageSalvageDelayMs; + double resultDelay = _salvagePanelOpened ? _settings.SalvageResultDelayFastMs : _settings.SalvageResultDelayFirstMs; + + switch (_salvagePhase) + { + case SalvagePhase.Idle: + // Dequeue next valid item + while (_salvageQueue.Count > 0) + { + _currentSalvageItemId = _salvageQueue.Dequeue(); + if (!IsItemInPlayerInventory(_currentSalvageItemId)) { _currentSalvageItemId = 0; continue; } + var wo = _core.WorldFilter[_currentSalvageItemId]; + if (wo == null || wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Salvage) + { _currentSalvageItemId = 0; continue; } + + _salvagePhase = SalvagePhase.OpeningPanel; + _salvagePhaseStart = DateTime.Now; + DebugLog($"IdleSalvage: Dequeued id={_currentSalvageItemId} name='{wo.Name}'"); + return; + } + // Queue empty — reset panel flag for next batch + _salvagePanelOpened = false; + break; + + case SalvagePhase.OpeningPanel: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < openDelay) return; + int ustId = FindUST(); + if (ustId == 0) + { + _host.Actions.AddChatText("[RynthAi] No Ust found — salvage cleared", 2); + _salvageQueue.Clear(); + _salvagePhase = SalvagePhase.Idle; + _currentSalvageItemId = 0; + return; + } + if (!IsItemInPlayerInventory(_currentSalvageItemId)) + { _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; } + + try { _host.Actions.UseItem(ustId, 0); } + catch + { + // Re-queue the item on failure + _salvageQueue.Enqueue(_currentSalvageItemId); + _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; + } + + _salvagePhase = SalvagePhase.AddingItem; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.AddingItem: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < addDelay) return; + + if (!IsItemInPlayerInventory(_currentSalvageItemId)) + { _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; } + + var salvItem = _core.WorldFilter[_currentSalvageItemId]; + _host.Actions.AddChatText($"[RynthAi] Salvaging {salvItem?.Name}", 1); + + try { _host.Actions.SalvagePanelAdd(_currentSalvageItemId); } + catch + { + _salvageQueue.Enqueue(_currentSalvageItemId); // Re-queue on failure + _salvagePhase = SalvagePhase.Idle; _currentSalvageItemId = 0; return; + } + + _salvagePhase = SalvagePhase.Salvaging; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.Salvaging: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < salvageDelay) return; + try { _host.Actions.SalvagePanelSalvage(); } catch { } + _salvagePhase = SalvagePhase.WaitingForResult; + _salvagePhaseStart = DateTime.Now; + break; + + case SalvagePhase.WaitingForResult: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < resultDelay) return; + if (_core.Actions.BusyState != 0) return; + + // VERIFY the item was actually salvaged + if (IsItemInPlayerInventory(_currentSalvageItemId)) + { + // Item still in inventory — salvage FAILED, re-queue it + var failItem = _core.WorldFilter[_currentSalvageItemId]; + if (failItem != null && failItem.ObjectClass != Decal.Adapter.Wrappers.ObjectClass.Salvage) + { + _salvageQueue.Enqueue(_currentSalvageItemId); + DebugLog($"IdleSalvage: Item {_currentSalvageItemId} still in inventory — re-queued ({failItem.Name})"); + } + } + else + { + DebugLog($"IdleSalvage: Item {_currentSalvageItemId} salvaged OK"); + } + + _salvagePanelOpened = true; + _currentSalvageItemId = 0; + _inventoryDirty = true; + + if (_settings.EnableCombineSalvage) + { _salvagePhase = SalvagePhase.CombiningSalvage; _salvagePhaseStart = DateTime.Now; } + else + { _salvagePhase = SalvagePhase.Idle; } + break; + + case SalvagePhase.CombiningSalvage: + if ((DateTime.Now - _salvagePhaseStart).TotalMilliseconds < 150) return; + CombineSalvageBags(); + _salvagePhase = SalvagePhase.Idle; // Next item picks up immediately + break; + } + } + + /// <summary> + /// Checks if an item is anywhere in the player's inventory (main pack or sub-packs). + /// AC inventory structure: Player → main items + sub-packs → items inside sub-packs. + /// </summary> + private bool IsItemInPlayerInventory(int itemId) + { + var item = _core.WorldFilter[itemId]; + if (item == null) return false; + + int playerId = _core.CharacterFilter.Id; + + // Direct child of player (main pack) + if (item.Container == playerId) return true; + + // Child of a sub-pack (pack.Container == playerId) + var container = _core.WorldFilter[item.Container]; + if (container != null && container.Container == playerId) return true; + + return false; + } + + /// <summary> + /// Finds salvage bags of the same material type and combines them. + /// AC allows combining bags via MoveItem (stack merge). + /// </summary> + private void CombineSalvageBags() + { + try + { + var salvageBags = _core.WorldFilter.GetInventory() + .Where(i => i.Name != null && i.Name.Contains("Salvage") && !i.Name.Contains("Tool")) + .ToList(); + + // Group by material name and combine bags of the same type + var groups = salvageBags.GroupBy(b => b.Name).Where(g => g.Count() > 1); + foreach (var group in groups) + { + var bags = group.OrderByDescending(b => b.Values(LongValueKey.StackCount, 1)).ToList(); + if (bags.Count >= 2) + { + DebugLog($"CombineSalvage: Merging {bags[1].Name} ({bags[1].Id}) into ({bags[0].Id})"); + _host.Actions.MoveItem(bags[1].Id, bags[0].Id, 0, false); + return; // One combine per tick + } + } + } + catch (Exception ex) + { + DebugLog($"CombineSalvage error: {ex.Message}"); + } + } + + private void ResetLootingState() + { + _lootState = LootState.Idle; + _settings.CurrentState = "Idle"; + _targetCorpseId = 0; + _currentItemIdx = 0; + _itemsLootedFromCorpse = 0; + _corpseItemsToCheck.Clear(); + _lootRetryCount = 0; + _assessingItemId = 0; + _assessItemStart = DateTime.MinValue; + _lastAssessRequest = DateTime.MinValue; + _stateEnteredAt = DateTime.MinValue; + _lastOpenAttemptAt = DateTime.MinValue; + _openedContainerAt = DateTime.MinValue; + _lastContentsCheckAt = DateTime.MinValue; + _lastLootPickupTime = DateTime.MinValue; + _isSalvagingCurrentItem = false; + // NOTE: Do NOT clear _salvageQueue here — items survive between corpses + } + + private int FindNearestCorpse() + { + int best = 0; double d = double.MaxValue; + foreach (var wo in _core.WorldFilter.GetLandscape()) + { + if (wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Corpse + && !_lootedCorpses.Contains(wo.Id) + && wo.Id != _targetCorpseId + && ShouldLootCorpse(wo)) + { + double dist = _core.WorldFilter.Distance(_core.CharacterFilter.Id, wo.Id); + if (dist <= _settings.CorpseApproachRangeMax && dist < d) { d = dist; best = wo.Id; } + } + } + return best; + } + + /// <summary> + /// Returns true if there are unlooted corpses within loot range OR we're actively looting. + /// Uses CorpseApproachRangeMax — only pause for corpses we can actually reach. + /// </summary> + public bool HasUnlootedCorpsesNearby() + { + if (!_settings.EnableLooting) return false; + + // If we're actively looting a corpse, nav must wait + if (_lootState != LootState.Idle) return true; + + // Check for unlooted corpses within actual loot range only + int playerId = _core.CharacterFilter.Id; + foreach (var wo in _core.WorldFilter.GetLandscape()) + { + if (wo.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Corpse + && !_lootedCorpses.Contains(wo.Id) + && ShouldLootCorpse(wo)) + { + double dist = _core.WorldFilter.Distance(playerId, wo.Id); + if (dist <= _settings.CorpseApproachRangeMax) return true; + } + } + return false; + } + + /// <summary> + /// Determines if a corpse should be looted based on ownership settings. + /// Reads the corpse's LongDesc property ("Killed by {name}.") to determine who killed it. + /// + /// LootOwnership: 0=MyKillsOnly, 1=FellowshipKills, 2=AllCorpses + /// + /// Fellowship mode relies on: + /// 1. Chat-based FellowshipTracker for known member names + /// 2. Server-enforced corpse permissions (you can't open corpses you don't have rights to) + /// Our existing approach timeout gracefully handles failed opens. + /// </summary> + private bool ShouldLootCorpse(WorldObject corpse) + { + if (corpse == null) return false; + + // AllCorpses mode — loot everything + if (_settings.LootOwnership >= 2) return true; + + string longDesc = ""; + try { longDesc = corpse.Values((StringValueKey)16, ""); } catch { } + + string killerName = ExtractKillerName(longDesc); + string myName = _core.CharacterFilter.Name; + + // MyKillsOnly — only loot corpses I killed + if (_settings.LootOwnership == 0) + { + if (string.IsNullOrEmpty(killerName)) return false; + return killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + } + + // FellowshipKills mode + if (_settings.LootOwnership == 1) + { + // Always loot my own kills + if (!string.IsNullOrEmpty(killerName) && killerName.Equals(myName, StringComparison.OrdinalIgnoreCase)) + return true; + + // If we're in a fellowship, check if the killer is a known member + if (_fellowshipTracker != null && _fellowshipTracker.IsInFellowship) + { + // If killer is a tracked fellow member, loot it + if (!string.IsNullOrEmpty(killerName) && _fellowshipTracker.IsMember(killerName)) + return true; + + // If we're in a fellowship but can't identify the killer or they're not tracked yet, + // still attempt to loot — the server enforces permissions and our timeout handles failures. + // This covers the case where members joined before us and aren't tracked by chat. + return true; + } + + // Not in a fellowship — only loot my kills + if (string.IsNullOrEmpty(killerName)) return false; + return killerName.Equals(myName, StringComparison.OrdinalIgnoreCase); + } + + return false; + } + + /// <summary> + /// Extracts the killer name from "Killed by {name}." format. + /// </summary> + private string ExtractKillerName(string longDesc) + { + if (string.IsNullOrEmpty(longDesc)) return null; + + const string prefix = "Killed by "; + int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx < 0) return null; + + string remainder = longDesc.Substring(idx + prefix.Length); + remainder = remainder.TrimEnd('.', ' ', '\n', '\r'); + return string.IsNullOrEmpty(remainder) ? null : remainder; + } + + private void TestSelectionLogic() + { + int sel = _core.Actions.CurrentSelection; + if (sel != _lastSelectedId && sel != 0) + { + _lastSelectedId = sel; + var info = uTank2.PluginCore.PC.FWorldTracker_GetWithID(sel); + if (info != null && _vtLootCore != null) + { + var dec = _vtLootCore.GetLootDecision(info); + if (dec != null && (dec.IsKeep || dec.IsSalvage)) + _host.Actions.AddChatText($"[RynthAi] Match: {_core.WorldFilter[sel].Name} ({dec.RuleName})", 5); + } + } + } + + private bool ShouldLootItem(int id, WorldObject wo, out string reason, out bool isSalvage) + { + reason = "none"; + isSalvage = false; + + if (wo == null) + { + reason = "null-worldobject"; + return false; + } + + bool needsId = uTank2.PluginCore.PC.FLootPluginQueryNeedsID(id); + + // 1. PRIMARY PATH: Local VTClassic Engine (Always up-to-date) + if (!needsId && _vtLootCore != null) + { + var info = uTank2.PluginCore.PC.FWorldTracker_GetWithID(id); + if (info != null) + { + var decision = _vtLootCore.GetLootDecision(info); + if (decision != null) + { + if (decision.IsKeep || decision.IsSalvage || decision.IsKeepUpTo) + { + isSalvage = decision.IsSalvage; + reason = $"vtclassic:{decision.RuleName}"; + return true; + } + else + { + reason = $"vtclassic-noloot:{decision.RuleName}"; + return false; + } + } + } + } + + // 2. SECONDARY PATH: Local Parsed Profile + if (_parsedLootProfile != null && _parsedLootProfile.Rules != null && _parsedLootProfile.Rules.Count > 0) + { + foreach (var rule in _parsedLootProfile.Rules) + { + if (rule == null) continue; + if (rule.IsMatch(wo)) + { + if (rule.Action == LootAction.Keep || rule.Action == LootAction.Salvage) + { + isSalvage = (rule.Action == LootAction.Salvage); + reason = $"parser:{rule.Name}"; + return true; + } + + reason = $"parser-noloot:{rule.Name}:{rule.Action}"; + return false; + } + } + } + + // 3. TERTIARY PATH: Global VTank + if (!needsId) + { + var immediate = uTank2.PluginCore.PC.FLootPluginClassifyImmediate(id); + if (immediate != null) + { + if (immediate.IsKeep || immediate.IsSalvage) + { + isSalvage = immediate.IsSalvage; + reason = $"vtank-immediate:{immediate.RuleName}"; + return true; + } + + if (immediate.IsKeepUpTo) + { + int heldCount = CountInventoryMatchesForRule(immediate.RuleName); + if (heldCount < immediate.Data1) + { + reason = $"vtank-keepupto:{immediate.RuleName} held={heldCount} max={immediate.Data1}"; + return true; + } + reason = $"vtank-keepupto-limit:{immediate.RuleName} held={heldCount} max={immediate.Data1}"; + return false; + } + } + } + + if (needsId) reason = "needsid-timeout"; + else if (_parsedLootProfile == null || _parsedLootProfile.Rules == null || _parsedLootProfile.Rules.Count == 0) + reason = "no-parser-rules"; + + return false; + } + + private int CountInventoryMatchesForRule(string ruleName) + { + if (string.IsNullOrEmpty(ruleName)) return 0; + int count = 0; + + foreach (var inv in _core.WorldFilter.GetInventory()) + { + if (uTank2.PluginCore.PC.FLootPluginQueryNeedsID(inv.Id)) continue; + var invDecision = uTank2.PluginCore.PC.FLootPluginClassifyImmediate(inv.Id); + if (invDecision == null || invDecision.RuleName != ruleName) continue; + + int stackMax = inv.Values(LongValueKey.StackMax, 0); + count += stackMax > 0 ? inv.Values(LongValueKey.StackCount, 1) : 1; + } + + return count; + } + + private void DebugLog(string message) + { + try + { + File.AppendAllText(_debugLogPath, $"{DateTime.Now:HH:mm:ss.fff} {message}{Environment.NewLine}"); + } + catch { } + } + + private bool ProcessAutoCram() + { + if (!_settings.EnableAutocram) return false; + + var inv = _core.WorldFilter.GetInventory().ToList(); + int playerId = _core.CharacterFilter.Id; + + int mainPackCount = 0; + foreach (var item in inv) + { + if (item.Container != playerId) continue; + if (item.Values(LongValueKey.EquippedSlots, 0) != 0) continue; + if (_settings.ItemRules.Any(r => r.Id == item.Id)) continue; + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container) continue; + if (item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Foci) continue; + if (item.Values(LongValueKey.ItemSlots, 0) > 0) continue; // Has pack slots = is a container + if (item.Values((LongValueKey)151, 0) > 0) continue; // Alt container capacity key + if (_cramBlacklist.Contains(item.Id)) continue; + if (_salvageQueue.Contains(item.Id)) continue; + if (item.Id == _currentSalvageItemId) continue; + // Salvage bags ARE crammable — don't skip them + mainPackCount++; + + int pack = FindOpenPack(inv, playerId); + if (pack != 0) + { + DebugLog($"AutoCram: Moving {item.Name} (id={item.Id}) to pack {pack}"); + try + { + _host.Actions.MoveItem(item.Id, pack, 0, false); + } + catch (Exception ex) + { + DebugLog($"AutoCram: MoveItem FAILED: {ex.Message}"); + } + _cramBlacklist.Add(item.Id); + return true; + } + else + { + DebugLog($"AutoCram: No open pack found for {item.Name}"); + } + break; // Only try one item per tick + } + // No debug log when nothing to cram — this fires every tick and floods the log + return false; + } + + private int FindOpenPack(List<WorldObject> inv, int playerId) + { + foreach (var p in inv) + { + if (p.Container != playerId) continue; + + // Must be a container — check both ObjectClass and capacity properties + bool isContainer = (p.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container); + if (!isContainer) continue; + + // Skip foci + if (p.Name != null && p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) continue; + + int itemsInPack = 0; + foreach (var item in inv) + { + if (item.Container == p.Id) itemsInPack++; + } + + // Get capacity + int cap = p.Values(LongValueKey.ItemSlots, 0); + if (cap <= 0) cap = p.Values((LongValueKey)151, 0); + if (cap <= 0) cap = 24; + + // 3-slot safety margin — prevents concurrent move conflicts + if (itemsInPack <= cap - 3) return p.Id; + } + return 0; + } + + private bool ProcessAutoStack() + { + if (!_settings.EnableAutostack) return false; + + int playerId = _core.CharacterFilter.Id; + var inv = _core.WorldFilter.GetInventory().ToList(); + + var playerItems = new List<WorldObject>(); + foreach (var item in inv) + { + if (item.Container == playerId) { playerItems.Add(item); continue; } + var container = inv.FirstOrDefault(c => c.Id == item.Container); + if (container != null && container.Container == playerId) playerItems.Add(item); + } + + var groups = playerItems + .Where(x => GetMaxStackSize(x) > 1 && !_salvageQueue.Contains(x.Id) && x.Id != _currentSalvageItemId) + .GroupBy(x => x.Name) + .Where(g => g.Count() > 1); + + foreach (var g in groups) + { + int max = GetMaxStackSize(g.First()); + var parts = g + .Where(x => x.Values(LongValueKey.StackCount, 1) < max) + .OrderByDescending(x => x.Values(LongValueKey.StackCount, 1)) + .ToList(); + + if (parts.Count < 2) continue; + + string pairKey = parts[0].Id + "_" + parts[parts.Count - 1].Id; + if (_failedStackPairs.Contains(pairKey)) continue; + + DebugLog($"AutoStack: Merging {parts[parts.Count - 1].Name} (count={parts[parts.Count - 1].Values(LongValueKey.StackCount, 1)}, id={parts[parts.Count - 1].Id}) into (count={parts[0].Values(LongValueKey.StackCount, 1)}, id={parts[0].Id}), max={max}"); + try + { + _host.Actions.MoveItem(parts[parts.Count - 1].Id, parts[0].Container, parts[0].Id, true); + } + catch (Exception ex) + { + DebugLog($"AutoStack: MoveItem FAILED: {ex.Message}"); + } + _failedStackPairs.Add(pairKey); + return true; + } + return false; + } + + private int GetMaxStackSize(WorldObject item) + { + // Primary: Use the standard Decal StackMax property + int max = item.Values(LongValueKey.StackMax, 0); + if (max > 1) return max; + + // Secondary: Some server emulators use a different key for certain items + int altMax = item.Values((LongValueKey)38, 0); + if (altMax > 1) return altMax; + + // Tertiary: Known AC item type fallbacks + if (item.Name != null) + { + if (item.Name.Contains("Pyreal")) return 25000; + if (item.Name.Contains("Trade Note")) return 100; + if (item.Name.Contains("Taper") || item.Name.Contains("Scarab") || + item.Name.Contains("Prismatic")) return 100; + if (item.Name.Contains("Arrow") || item.Name.Contains("Bolt") || + item.Name.Contains("Quarrel") || item.Name.Contains("Dart") || + item.Name.Contains("Throwing")) return 250; + if (item.Name.Contains("Pea") || item.Name.Contains("Grain") || + item.Name.Contains("Salvage")) return 100; + } + + return 1; // Not stackable + } + + public void Dispose() + { + if (_vtLootCore != null) { _vtLootCore.UnloadProfile(); _vtLootCore = null; } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Loot/VTankLootParser.cs b/Plugins/RynthAi/Loot/VTankLootParser.cs new file mode 100644 index 0000000..991bacb --- /dev/null +++ b/Plugins/RynthAi/Loot/VTankLootParser.cs @@ -0,0 +1,285 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Decal.Adapter.Wrappers; +using System.Text.RegularExpressions; + +namespace NexSuite.Plugins.RynthAi +{ + public enum LootAction + { + Keep = 0, + Salvage = 1, + Sell = 2, + Read = 3, + User1 = 4 + } + + public class LootRule + { + public string Name { get; set; } + public LootAction Action { get; set; } + public int KeepCount { get; set; } + public string RawInfoLine { get; set; } + public List<string> RawDataLines { get; set; } = new List<string>(); + + public bool IsMatch(WorldObject item) + { + if (item == null || string.IsNullOrEmpty(RawInfoLine)) return false; + + try + { + var parts = RawInfoLine.Split(';'); + if (parts.Length < 2) return false; + + // A rule with no requirement nodes (only Action;KeepCount) is unconditional. + // "Loot Everything" style profiles depend on this behavior. + if (parts.Length == 2) return true; + + var data = new Queue<string>(RawDataLines); + var stack = new Stack<bool>(); + + // VTank stores requirement nodes in POSTFIX notation (Reverse Polish Notation) + // We start at index 2 to skip the Action and KeepCount numbers + for (int i = 2; i < parts.Length; i++) + { + if (!int.TryParse(parts[i], out int type)) continue; + + if (type == 9998) // OR Operator + { + if (stack.Count < 2) return false; + bool right = stack.Pop(); + bool left = stack.Pop(); + stack.Push(left || right); + } + else if (type == 9999) // AND Operator + { + if (stack.Count < 2) return false; + bool right = stack.Pop(); + bool left = stack.Pop(); + stack.Push(left && right); + } + else + { + // Leaf Node: Dequeue its specific data, evaluate, and push to stack + bool result = false; + + switch (type) + { + case 1: // StringValueMatch (Consumes 2 lines) + int sKey = int.Parse(data.Dequeue()); + string sMatch = data.Dequeue(); + string sVal = item.Values((StringValueKey)sKey, ""); + result = Regex.IsMatch(sVal, sMatch, RegexOptions.IgnoreCase); + break; + + case 2: // LongValKeyLE (Consumes 2 lines) + int lKeyLE = int.Parse(data.Dequeue()); + int lValLE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyLE, 0) <= lValLE; + break; + + case 3: // LongValKeyGE (Consumes 2 lines) + int lKeyGE = int.Parse(data.Dequeue()); + int lValGE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyGE, 0) >= lValGE; + break; + + case 4: // DoubleValKeyLE (Consumes 2 lines) + int dKeyLE = int.Parse(data.Dequeue()); + double dValLE = double.Parse(data.Dequeue()); + result = item.Values((DoubleValueKey)dKeyLE, 0.0) <= dValLE; + break; + + case 5: // DoubleValKeyGE (Consumes 2 lines) + int dKeyGE = int.Parse(data.Dequeue()); + double dValGE = double.Parse(data.Dequeue()); + result = item.Values((DoubleValueKey)dKeyGE, 0.0) >= dValGE; + break; + + case 7: // ObjectClass (Consumes 1 line) + int objClass = int.Parse(data.Dequeue()); + result = (int)item.ObjectClass == objClass; + break; + + case 12: // LongValKeyE (Consumes 2 lines) + int lKeyE = int.Parse(data.Dequeue()); + int lValE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyE, 0) == lValE; + break; + + case 13: // LongValKeyNE (Consumes 2 lines) + int lKeyNE = int.Parse(data.Dequeue()); + int lValNE = int.Parse(data.Dequeue()); + result = item.Values((LongValueKey)lKeyNE, 0) != lValNE; + break; + + default: + // If we encounter a VTank node type we haven't mapped yet, we MUST abort the rule. + // If we don't know how many lines of data it consumes, we can't safely + // process the rest of the queue, so we fail safely and skip to the next rule. + return false; + } + + stack.Push(result); + } + } + + // The final result of the tree will be the only item left sitting in the stack. + // If nodes existed but did not produce a valid expression, fail safely. + return stack.Count == 1 && stack.Pop(); + } + catch + { + return false; // Failsafe for missing data or parsing exceptions + } + } + } + + public class VTankLootProfile + { + public List<LootRule> Rules { get; set; } = new List<LootRule>(); + } + + public static class VTankLootParser + { + public static VTankLootProfile Load(string filePath) + { + var profile = new VTankLootProfile(); + if (!File.Exists(filePath)) return profile; + + string[] lines = File.ReadAllLines(filePath); + if (lines.Length < 3 || lines[0].Trim() != "UTL") + throw new Exception("Invalid UTL file format."); + + int version = int.Parse(lines[1].Trim()); + int ruleCount = int.Parse(lines[2].Trim()); + + int lineIndex = 3; + + while (lineIndex < lines.Length && profile.Rules.Count < ruleCount) + { + LootRule rule = new LootRule(); + + // 1. Read Name (VTank sometimes leaves these blank, so we just trim the end) + rule.Name = lines[lineIndex++].TrimEnd(); + + // 2. Read the mandatory Empty Line VTank puts after names + if (lineIndex < lines.Length && string.IsNullOrWhiteSpace(lines[lineIndex])) + { + lineIndex++; + } + + // 3. Read the InfoLine (e.g., "0;1;1;12") + if (lineIndex < lines.Length) + { + rule.RawInfoLine = lines[lineIndex++].Trim(); + string[] parts = rule.RawInfoLine.Split(';'); + if (parts.Length >= 2 && int.TryParse(parts[0], out int act) && int.TryParse(parts[1], out int count)) + { + rule.Action = (LootAction)act; + rule.KeepCount = count; + } + } + + // 4. Read Requirement Data using node-token arity when possible. + // This is more reliable than heuristic rule boundary detection for complex profiles. + int requiredDataLines = TryGetRequiredDataLineCount(rule.RawInfoLine); + if (requiredDataLines >= 0) + { + for (int i = 0; i < requiredDataLines && lineIndex < lines.Length; i++) + { + rule.RawDataLines.Add(lines[lineIndex++].TrimEnd()); + } + } + else + { + // Fallback for unknown token types: heuristic boundary detection. + while (lineIndex < lines.Length) + { + if (IsStartOfNextRule(lines, lineIndex)) + { + break; + } + + rule.RawDataLines.Add(lines[lineIndex++].TrimEnd()); + } + } + + profile.Rules.Add(rule); + } + + return profile; + } + + private static bool IsStartOfNextRule(string[] lines, int index) + { + // We need at least 3 lines to form a valid rule start: [Name], [Empty Line], [InfoLine] + if (index + 2 >= lines.Length) return false; + + // lines[index] is the Name. It can be literally anything, so we skip checking it. + + // lines[index+1] MUST be an empty line in the VTank format + if (!string.IsNullOrWhiteSpace(lines[index + 1])) return false; + + // lines[index+2] MUST be an InfoLine containing semicolons + string infoLine = lines[index + 2].Trim(); + if (!infoLine.Contains(";")) return false; + + string[] parts = infoLine.Split(';'); + if (parts.Length >= 2) + { + // An InfoLine always starts with two integers (Action and KeepCount) + if (int.TryParse(parts[0], out int action) && int.TryParse(parts[1], out int _)) + { + // Valid VTank Actions are 0 to 4 (Allowing up to 10 just for forward compatibility) + if (action >= 0 && action <= 10) return true; + } + } + + return false; + } + + private static int TryGetRequiredDataLineCount(string rawInfoLine) + { + if (string.IsNullOrWhiteSpace(rawInfoLine)) return -1; + var parts = rawInfoLine.Split(';'); + if (parts.Length < 2) return -1; + if (parts.Length == 2) return 0; // unconditional rule + + int required = 0; + for (int i = 2; i < parts.Length; i++) + { + if (!int.TryParse(parts[i], out int type)) continue; + + int lines = GetDataLinesForNodeType(type); + if (lines < 0) return -1; + required += lines; + } + + return required; + } + + private static int GetDataLinesForNodeType(int type) + { + switch (type) + { + case 9998: // OR + case 9999: // AND + return 0; + case 1: // StringValueMatch + case 2: // LongValKeyLE + case 3: // LongValKeyGE + case 4: // DoubleValKeyLE + case 5: // DoubleValKeyGE + case 12: // LongValKeyE + case 13: // LongValKeyNE + return 2; + case 7: // ObjectClass + return 1; + default: + return -1; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Lua/LuaBridge.cs b/Plugins/RynthAi/Lua/LuaBridge.cs new file mode 100644 index 0000000..5aabf80 --- /dev/null +++ b/Plugins/RynthAi/Lua/LuaBridge.cs @@ -0,0 +1,115 @@ +using System; +using System.Text.RegularExpressions; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaBridge + { + private readonly PluginCore _core; + // Returns the actual North/South coordinate (e.g. 42.5) + public double GetPlayerNS() + { + return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().NorthSouth; + } + + // Returns the actual East/West coordinate (e.g. -33.7) + public double GetPlayerEW() + { + return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().EastWest; + } + + // Returns the altitude in meters + public double GetPlayerZ() + { + return Decal.Adapter.CoreManager.Current.Actions.LocationZ; + } + + public LuaBridge(PluginCore core) + { + _core = core; + } + + // --- MOVEMENT --- + public void GoTo(string ns, string ew) + { + double dNS = ParseCoord(ns); + double dEW = ParseCoord(ew); + + _core.UI.Settings.CurrentRoute.Points.Clear(); + _core.UI.Settings.CurrentRoute.Points.Add(new NavPoint { NS = dNS, EW = dEW, Type = NavPointType.Point }); + _core.UI.Settings.CurrentRoute.RouteType = NavRouteType.Once; + _core.UI.Settings.ActiveNavIndex = 0; + + _core.UI.Settings.IsMacroRunning = true; + _core.UI.Settings.EnableNavigation = true; + + if (_core.UI?.RouteTab != null) _core.UI.RouteTab.NeedsRouteGraphicsRefresh = true; + _core.PluginHost.Actions.AddChatText($"[RynthLua] Navigating to: {ns}, {ew}", 1); + } + + public void Stop() + { + _core.UI.Settings.IsMacroRunning = false; + _core.UI.Settings.EnableNavigation = false; + _core.PluginHost.Actions.AddChatText("[RynthLua] Macro Stopped.", 1); + } + + // --- INTERACTION --- + public void UsePortal(string portalName) + { + foreach (WorldObject wo in _core.PluginCoreManager.WorldFilter.GetLandscape()) + { + if (wo.Name.IndexOf(portalName, StringComparison.OrdinalIgnoreCase) >= 0) + { + if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc) + { + // The correct Decal API call: UseItem(GUID, ContainerID) + // We use 0 for the container because portals are in the world. + _core.PluginHost.Actions.UseItem(wo.Id, 0); + return; + } + } + } + } + + // --- UTILS --- + private double ParseCoord(string val) + { + if (string.IsNullOrEmpty(val)) return 0; + string clean = Regex.Replace(val, "[^0-9.-]", ""); + if (!double.TryParse(clean, out double result)) return 0; + return (val.ToUpper().Contains("S") || val.ToUpper().Contains("W")) ? -result : result; + } + + public bool IsPathClear(double startNS, double startEW, double startZ, double endNS, double endEW, double endZ) + { + try + { + // Use '_core' instead of '_plugin' + if (_core.Raycast == null || !_core.Raycast.IsInitialized) + return true; + + // Convert EW/NS to Global Meters + float startX = (float)((startEW * 10.0 + 1019.5) * 24.0); + float startY = (float)((startNS * 10.0 + 1019.5) * 24.0); + var origin = new RynthAi.Raycasting.Vector3(startX, startY, (float)startZ + 1.0f); + + float endX = (float)((endEW * 10.0 + 1019.5) * 24.0); + float endY = (float)((endNS * 10.0 + 1019.5) * 24.0); + var destination = new RynthAi.Raycasting.Vector3(endX, endY, (float)endZ + 1.0f); + + // Access Landcell safely via CoreManager + uint landcell = (uint)Decal.Adapter.CoreManager.Current.Actions.Landcell; + var geometry = _core.Raycast.GeometryLoader.GetLandblockGeometry(landcell); + + // Test the line + return !RynthAi.Raycasting.RaycastEngine.IsLinearPathBlocked(origin, destination, geometry); + } + catch + { + return true; // Default to assuming clear if it fails, to prevent the bot from freezing + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Lua/LuaManager.cs b/Plugins/RynthAi/Lua/LuaManager.cs new file mode 100644 index 0000000..37a88af --- /dev/null +++ b/Plugins/RynthAi/Lua/LuaManager.cs @@ -0,0 +1,154 @@ +using System; +using System.Text; +using NLua; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaManager : IDisposable + { + private Lua _lua; + private readonly PluginCore _core; + private bool _isDisposed; + public void Execute(string script) => ExecuteString(script); + + public LuaManager(PluginCore core) + { + _core = core; + Init(); + } + + public void Init() + { + try + { + // 1. Clean up old state if re-initializing to prevent memory leaks + _lua?.Dispose(); + + // 2. Initialize the fresh NLua state + _lua = new Lua(); + _lua.LoadCLRPackage(); + + // 3. Instantiate the Bridge + // This class acts as the middle-man, housing GoTo, Stop, and UsePortal logic + var bridge = new LuaBridge(_core); + + // --- THE API BRIDGE: Expose the Bridge as "RynthAi" --- + // Usage in Lua: RynthAi:GoTo("33.5N", "44.8E") + _lua["RynthAi"] = bridge; + + // --- SHORTCUTS: Direct manager access for advanced scripting --- + if (_core.UI != null) + { + _lua["Combat"] = _core.UI.CombatManager; + _lua["Settings"] = _core.UI.Settings; + _lua["Nav"] = _core.UI.Settings.CurrentRoute; + } + + // Expose the raw Decal CoreManager (e.g., Core.WorldFilter) + _lua["Core"] = _core.PluginCoreManager; + + // --- REDIRECT PRINT --- + // Replaces Lua's default print() with our custom C# method + // which sends text to both AC Chat and the UI Console. + _lua.RegisterFunction("print", this, typeof(LuaManager).GetMethod("LuaPrint")); + + LuaPrint("Lua Engine Initialized."); + } + catch (Exception ex) + { + LogError("Init Error: " + ex.Message); + } + } + + public void ExecuteString(string script) + { + try + { + if (string.IsNullOrEmpty(script) || _lua == null) return; + _lua.DoString(script); + } + catch (NLua.Exceptions.LuaException ex) + { + // This will now show you the EXACT line number and error in AC chat + LogError("Lua Script Error: " + ex.Message); + } + catch (Exception ex) + { + LogError("Engine Error: " + ex.Message); + } + } + public void LuaPrint(object msg) + { + // 1. Format the basic string and timestamp + string text = msg?.ToString() ?? "nil"; + string timestamp = DateTime.Now.ToString("HH:mm:ss"); + string formattedMsg = $"[{timestamp}] {text}"; + + // 2. Always output to Asheron's Call Chat (Green text) + // This is safe even if the UI window isn't open yet + _core.PluginHost.Actions.AddChatText($"[RynthLua] {text}", 5); + + // 3. Safely update the ImGui Console Tab + // We wrap everything in this check so the plugin doesn't crash + // if you try to print something before the UI is fully loaded. + if (_core.UI?.Settings != null) + { + // Append the new line to the console + _core.UI.Settings.LuaConsoleOutput += $"\n{formattedMsg}"; + + // Limit console size to roughly 10k characters to prevent memory bloat + if (_core.UI.Settings.LuaConsoleOutput.Length > 10000) + { + // Trims the oldest 5,000 characters + _core.UI.Settings.LuaConsoleOutput = _core.UI.Settings.LuaConsoleOutput.Substring(5000); + } + } + } + + public void LoadMainScript() + { + try + { + string scriptDir = Path.Combine(_core.AssemblyDirectory, "Scripts"); + if (!Directory.Exists(scriptDir)) Directory.CreateDirectory(scriptDir); + + string path = Path.Combine(scriptDir, "main.lua"); + + if (File.Exists(path)) + { + string code = File.ReadAllText(path); + ExecuteString(code); + LuaPrint("Main script loaded from: " + path); + } + else + { + // Create a dummy file so the user has a template + File.WriteAllText(path, "-- RynthAi Main Lua Script\nfunction OnBotTick()\nend"); + LuaPrint("Created template main.lua at: " + path); + } + } + catch (Exception ex) + { + LogError("LoadMainScript Error: " + ex.Message); + } + } + + private void LogError(string msg) + { + _core.PluginHost.Actions.AddChatText($"[RynthLua Error] {msg}", 2); + _core.UI.Settings.LuaConsoleOutput += $"\n[ERROR] {msg}"; + } + + public void Dispose() + { + if (!_isDisposed) + { + _lua?.Dispose(); + _isDisposed = true; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Meta/MetaManager.cs b/Plugins/RynthAi/Meta/MetaManager.cs new file mode 100644 index 0000000..1445495 --- /dev/null +++ b/Plugins/RynthAi/Meta/MetaManager.cs @@ -0,0 +1,684 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Newtonsoft.Json; +using NexSuite.Plugins.RynthAi; +using System.Numerics; +using System.Linq; + + +namespace RynthAi.Meta +{ + public class MetaManager + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + + private string _lastChatText = ""; + private DateTime _lastChatTime = DateTime.MinValue; + private System.Text.RegularExpressions.Match _lastChatMatch = null; + + // Timer tracking for "Seconds in State" + private DateTime _lastStateChange = DateTime.Now; + private string _previousState = ""; + + // Tracks if the meta was turned off so we can clean the slate when turned back on + private bool _wasMetaEnabled = false; + public Action OnRouteDynamicallyLoaded; + private Stack<string> _stateStack = new Stack<string>(); + private bool _watchdogActive = false; + private string _watchdogState = ""; + private float _watchdogMetersRequired = 0f; + private double _watchdogSecondsConfig = 0; + private DateTime _watchdogExpiration; + private Vector3 _lastWatchdogPos; // Requires 'using System.Numerics;' + private string _lastState = ""; + private DateTime _stateStartTime = DateTime.Now; + + + public MetaManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + public void OnHeartbeat() + { + // 1. If Meta is disabled, reset our tracker and do absolutely nothing + if (!_settings.IsMacroRunning || !_settings.EnableMeta || _settings.MetaRules == null) + { + _wasMetaEnabled = false; + return; + } + + // 2. If Meta was just turned on, we need a clean slate so old timers don't instantly trigger + if (!_wasMetaEnabled) + { + _wasMetaEnabled = true; + _lastStateChange = DateTime.Now; + _previousState = _settings.CurrentState; + + // Reset all rules so they can fire again + foreach (var r in _settings.MetaRules) r.HasFired = false; + } + + // 3. Normal State Change OR Forced Reset from UI + if (!string.Equals(_settings.CurrentState, _previousState, StringComparison.OrdinalIgnoreCase) || _settings.ForceStateReset) + { + _settings.ForceStateReset = false; // Consume the flag so it only resets once + _lastStateChange = DateTime.Now; + _previousState = _settings.CurrentState; + + // Reset all rules so they can fire again in the new/reset state + foreach (var r in _settings.MetaRules) + { + r.HasFired = false; + } + } + + // Calculate the time ONCE per heartbeat to pass into evaluations, + // saving CPU cycles on deep 'Any'/'All' recursive checks. + double currentSecondsInState = (DateTime.Now - _lastStateChange).TotalSeconds; + + // 4. Evaluate Rules + foreach (var rule in _settings.MetaRules) + { + // Case-insensitive check so "Default" and "default" don't break the meta + if (string.Equals(rule.State, _settings.CurrentState, StringComparison.OrdinalIgnoreCase)) + { + // Check our boolean to prevent chat/action spam + if (!rule.HasFired) + { + if (EvaluateCondition(rule, currentSecondsInState)) + { + ExecuteAction(rule); + + // Mark this specific rule as fired so it glows red in UI and stops spamming + rule.HasFired = true; + + break; // Process one successful rule per heartbeat + } + } + } + } + } + + private bool EvaluateCondition(MetaRule rule, double secondsInState) + { + try + { + // Explicitly using Decal.Adapter for Vitals + dynamic actions = _host.Actions; + + switch (rule.Condition) + { + case MetaConditionType.Always: return true; + case MetaConditionType.Never: return false; + + case MetaConditionType.All: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + foreach (var child in rule.Children) + if (!EvaluateCondition(child, secondsInState)) return false; + return true; + } + + case MetaConditionType.Any: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + foreach (var child in rule.Children) + if (EvaluateCondition(child, secondsInState)) return true; + return false; + } + + case MetaConditionType.Not: + { + if (rule.Children == null || rule.Children.Count == 0) return false; + return !EvaluateCondition(rule.Children[0], secondsInState); + } + + // --- VITAL CHECKS (Value) --- + case MetaConditionType.MainHealthLE: + { + if (int.TryParse(rule.ConditionData, out int hVal)) + return _core.CharacterFilter.Health <= hVal; + return false; + } + + case MetaConditionType.MainManaLE: + { + if (int.TryParse(rule.ConditionData, out int mVal)) + return _core.CharacterFilter.Mana <= mVal; + return false; + } + + case MetaConditionType.MainStamLE: + { + if (int.TryParse(rule.ConditionData, out int sVal)) + return _core.CharacterFilter.Stamina <= sVal; + return false; + } + + // --- VITAL CHECKS (Percentage) --- + case MetaConditionType.MainHealthPHE: + { + if (int.TryParse(rule.ConditionData, out int hPct)) + { + double cur = _core.CharacterFilter.Health; // Live HP + double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Health].Current; // Max HP + return max > 0 && (cur / max) * 100 <= hPct; + } + return false; + } + + case MetaConditionType.MainManaPHE: + { + if (int.TryParse(rule.ConditionData, out int mPct)) + { + double cur = _core.CharacterFilter.Mana; // Live MP + double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Mana].Current; // Max MP + return max > 0 && (cur / max) * 100 <= mPct; + } + return false; + } + + case MetaConditionType.CharacterDeath: + return _core.CharacterFilter.Health <= 0; + + // --- TIME & CHAT --- + case MetaConditionType.SecondsInState_GE: + case MetaConditionType.SecondsInStateP_GE: + { + if (double.TryParse(rule.ConditionData, out double reqSecs)) + return secondsInState >= reqSecs; + return false; + } + + case MetaConditionType.ChatMessage: + case MetaConditionType.ChatMessageCapture: + { + if ((DateTime.Now - _lastChatTime).TotalSeconds > 1.0) return false; + try + { + var regex = new System.Text.RegularExpressions.Regex(rule.ConditionData); + var match = regex.Match(_lastChatText); + if (match.Success) + { + if (rule.Condition == MetaConditionType.ChatMessageCapture) _lastChatMatch = match; + return true; + } + } + catch { } + return false; + } + + // --- WORLD & INVENTORY --- + case MetaConditionType.BurdenPercentage_GE: + { + if (int.TryParse(rule.ConditionData, out int targetB)) + return _core.CharacterFilter.Burden >= targetB; + return false; + } + + case MetaConditionType.PackSlots_LE: + { + if (int.TryParse(rule.ConditionData, out int targetSlots)) + { + int myId = _core.CharacterFilter.Id; + int usedGridSquares = 0; + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Container == myId) + { + int slot = item.Values(Decal.Adapter.Wrappers.LongValueKey.Slot, -1); + bool isEquipped = item.Values(Decal.Adapter.Wrappers.LongValueKey.EquippedSlots, 0) > 0; + bool isBag = item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container; + bool isFoci = item.Name != null && item.Name.Contains("Foci"); + + if (slot >= 0 && slot <= 101 && !isEquipped && !isBag && !isFoci) + usedGridSquares++; + } + } + int freeSlots = 102 - usedGridSquares; + return freeSlots <= targetSlots; + } + return false; + } + + case MetaConditionType.InventoryItemCount_LE: + case MetaConditionType.InventoryItemCount_GE: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] invParts = rule.ConditionData.Split(','); + if (invParts.Length >= 2) + { + string itemName = invParts[0].Trim(); + if (!int.TryParse(invParts[1], out int targetCount)) return false; + + int currentCount = 0; + int myId = _core.CharacterFilter.Id; + foreach (var item in _core.WorldFilter.GetInventory()) + { + bool isMine = (item.Container == myId); + if (!isMine) + { + var parentBag = _core.WorldFilter[item.Container]; + if (parentBag != null && parentBag.Container == myId) isMine = true; + } + + if (isMine && item.Name != null && item.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase)) + currentCount += item.Values(Decal.Adapter.Wrappers.LongValueKey.StackCount, 1); + } + + if (rule.Condition == MetaConditionType.InventoryItemCount_LE) + return currentCount <= targetCount; + else + return currentCount >= targetCount; + } + return false; + } + + case MetaConditionType.TimeLeftOnSpell_GE: + case MetaConditionType.TimeLeftOnSpell_LE: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] spellParts = rule.ConditionData.Split(','); + if (spellParts.Length >= 2) + { + if (int.TryParse(spellParts[0], out int spellId) && double.TryParse(spellParts[1], out double reqSecs)) + { + double remaining = 0; + bool found = false; + foreach (var ench in _core.CharacterFilter.Enchantments) + { + if (ench.SpellId == spellId) + { + remaining = ench.TimeRemaining; + found = true; + break; + } + } + if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE) + return found && remaining >= reqSecs; + else + return !found || remaining <= reqSecs; + } + } + return false; + } + + case MetaConditionType.MonsterNameCountWithinDistance: + { + if (string.IsNullOrEmpty(rule.ConditionData)) return false; + string[] mParts = rule.ConditionData.Split(','); + if (mParts.Length >= 3) + { + string pattern = mParts[0]; + if (!double.TryParse(mParts[1], out double dist) || !int.TryParse(mParts[2], out int count)) return false; + int matchCount = 0; + var regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); + foreach (var obj in _core.WorldFilter.GetLandscape()) + { + if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= dist) + if (regex.IsMatch(obj.Name)) matchCount++; + } + return matchCount >= count; + } + return false; + } + + case MetaConditionType.NoMonstersWithinDistance: + { + double maxD = 20.0; + double.TryParse(rule.ConditionData, out maxD); + foreach (var obj in _core.WorldFilter.GetLandscape()) + { + if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= maxD) + return false; + } + return true; + } + + case MetaConditionType.NavrouteEmpty: + if (_settings.CurrentRoute == null || _settings.CurrentRoute.Points.Count == 0) return true; + return _settings.ActiveNavIndex >= _settings.CurrentRoute.Points.Count; + + case MetaConditionType.AnyVendorOpen: + return actions.VendorId != 0; + + case MetaConditionType.PortalspaceEntered: + return (actions.Status & 0x1) != 0; + + case MetaConditionType.PortalspaceExited: + return (actions.Status & 0x1) == 0; + + default: + return false; + } + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] EvaluateCondition Error: {ex.Message}", 2); + } + return false; + } + + private void ExecuteAction(MetaRule rule) + { + dynamic actions = _host.Actions; + + // --- HELPER: Regex Variable Replacement --- + string ProcessData(string rawData) + { + if (string.IsNullOrEmpty(rawData)) return ""; + if (_lastChatMatch == null || !_lastChatMatch.Success) return rawData; + + string result = rawData; + for (int i = 0; i < _lastChatMatch.Groups.Count; i++) + { + result = result.Replace($"{{{i}}}", _lastChatMatch.Groups[i].Value); + } + return result; + } + + switch (rule.Action) + { + case MetaActionType.All: + if (rule.Children != null && rule.Children.Count > 0) + { + foreach (var childAction in rule.Children) ExecuteAction(childAction); + } + break; + + case MetaActionType.ChatCommand: + string finalCommand = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(finalCommand)) actions.InvokeChatParser(finalCommand); + break; + + case MetaActionType.SetMetaState: + string nextState = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(nextState)) + { + _settings.CurrentState = nextState; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Meta State -> {nextState}", 5); + } + break; + + case MetaActionType.CallMetaState: + string callState = ProcessData(rule.ActionData); + if (!string.IsNullOrEmpty(callState)) + { + _stateStack.Push(_settings.CurrentState); + _settings.CurrentState = callState; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Calling State -> {callState}", 5); + } + break; + + case MetaActionType.ReturnFromCall: + if (_stateStack.Count > 0) + { + string returnTo = _stateStack.Pop(); + _settings.CurrentState = returnTo; + _settings.ForceStateReset = true; + actions.AddChatText($"[RynthAi] Returning to -> {returnTo}", 5); + } + else { actions.AddChatText("[RynthAi] Error: Return From Call failed (Stack Empty)", 2); } + break; + + case MetaActionType.EmbeddedNavRoute: + if (string.IsNullOrWhiteSpace(rule.ActionData)) break; + string routeName = rule.ActionData.Split(';')[0]; + string navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + string fullPath = System.IO.Path.Combine(navFolder, routeName + ".nav"); + + if (System.IO.File.Exists(fullPath)) + { + try + { + _settings.CurrentNavPath = fullPath; + _settings.CurrentRoute = VTankNavParser.Load(fullPath); + _settings.ActiveNavIndex = 0; + actions.AddChatText($"[RynthAi Meta] Switched to route: {routeName}", 5); + OnRouteDynamicallyLoaded?.Invoke(); + } + catch (Exception ex) { actions.AddChatText($"[RynthAi Meta] Load Error: {ex.Message}", 2); } + } + else { actions.AddChatText($"[RynthAi Meta] Route file missing: {fullPath}", 2); } + break; + + case MetaActionType.SetWatchdog: + // IGNITION SWITCH: If it's already ticking, do absolutely nothing. + // This prevents the rule from resetting the timer every single frame! + if (_watchdogActive) break; + + string[] wdParts = (rule.ActionData ?? "").Split(';'); + if (wdParts.Length >= 3) + { + _watchdogState = wdParts[0].Trim(); + if (!float.TryParse(wdParts[1].Trim(), out _watchdogMetersRequired)) _watchdogMetersRequired = 5f; + if (!double.TryParse(wdParts[2].Trim(), out _watchdogSecondsConfig)) _watchdogSecondsConfig = 5.0; + + _watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig); + _lastWatchdogPos = new Vector3((float)actions.LocationX, (float)actions.LocationY, (float)actions.LocationZ); + + _watchdogActive = true; + + actions.AddChatText($"[RynthAi] Watchdog Started: To {_watchdogState} if not moved {_watchdogMetersRequired}m in {_watchdogSecondsConfig}s.", 5); + } + break; + + case MetaActionType.ClearWatchdog: + _watchdogActive = false; + actions.AddChatText("[RynthAi] Watchdog Cleared", 5); + break; + + case MetaActionType.SetNTOption: + string[] ntParts = (rule.ActionData ?? "").Split(';'); + if (ntParts.Length >= 2) actions.AddChatText($"[RynthAi] Option Set: {ntParts[0]} = {ntParts[1]}", 5); + break; + + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + case MetaActionType.CreateView: + case MetaActionType.DestroyView: + case MetaActionType.DestroyAllViews: + break; + } + } + + + + public void Think() + { + try + { + dynamic actions = _host.Actions; + + // 1. THE KILL SWITCH (State Entry/Exit) + if (_settings.CurrentState != _lastState || _settings.ForceStateReset) + { + _lastState = _settings.CurrentState; + _stateStartTime = DateTime.Now; + + _watchdogActive = false; + _settings.ForceStateReset = false; + + // --- THE FIX: Wipe the slate clean for the new state --- + // This ensures rules can fire again if we leave the state and come back later + if (_settings.MetaRules != null) + { + foreach (var r in _settings.MetaRules) + { + r.HasFired = false; + } + } + } + + double secondsInState = (DateTime.Now - _stateStartTime).TotalSeconds; + + // 2. THE WATCHDOG TIMER + if (_watchdogActive) + { + Vector3 currentPos = new Vector3( + (float)actions.LocationX, + (float)actions.LocationY, + (float)actions.LocationZ + ); + + float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos); + + if (distMoved < _watchdogMetersRequired) + { + if (DateTime.Now > _watchdogExpiration) + { + _watchdogActive = false; + _settings.CurrentState = _watchdogState; + _settings.ForceStateReset = true; + + actions.AddChatText($"[RynthAi] WATCHDOG TRIGGERED! Jumping to: {_watchdogState}", 5); + return; + } + } + else + { + _lastWatchdogPos = currentPos; + _watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig); + } + } + + // 3. RULE EVALUATION + if (!_settings.EnableMeta || _settings.MetaRules == null) return; + + var currentRules = _settings.MetaRules.Where(r => r.State == _settings.CurrentState).ToList(); + + foreach (var rule in currentRules) + { + // --- THE FIX: Skip this rule if it already successfully fired during this state visit --- + if (rule.HasFired) continue; + + if (EvaluateCondition(rule, secondsInState)) + { + rule.HasFired = true; // Lock it out from firing again + ExecuteAction(rule); + + if (_settings.CurrentState != _lastState || _settings.ForceStateReset) + { + break; + } + } + } + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] ENGINE CRASH in Think(): {ex.Message}", 5); + } + } + + public void PrintWatchdogStatus() + { + if (!_watchdogActive) + { + _host.Actions.AddChatText("[RynthAi] Watchdog Status: INACTIVE", 5); + return; + } + + // Grab current coordinates + Vector3 currentPos = new Vector3( + (float)_host.Actions.LocationX, + (float)_host.Actions.LocationY, + (float)_host.Actions.LocationZ + ); + + // Calculate real-time stats + float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos); + double secondsLeft = (_watchdogExpiration - DateTime.Now).TotalSeconds; + + // Print the diagnostic readout + _host.Actions.AddChatText($"[RynthAi] Watchdog Status: ACTIVE", 5); + _host.Actions.AddChatText($" -> Target State: {_watchdogState}", 5); + _host.Actions.AddChatText($" -> Distance Moved: {distMoved:F2}m / {_watchdogMetersRequired}m", 5); + _host.Actions.AddChatText($" -> Time Left: {Math.Max(0, secondsLeft):F1}s", 5); + } + + private Vector3 GetCurrentPosition() + { + // Accessing the host's actions coordinates directly + return new Vector3( + (float)_host.Actions.LocationX, + (float)_host.Actions.LocationY, + (float)_host.Actions.LocationZ + ); + } + + + + // --- PROFILE PERSISTENCE --- + + public void LoadProfile(string path) + { + try + { + if (string.IsNullOrEmpty(path) || !File.Exists(path)) + { + _settings.MetaRules = new List<MetaRule>(); + return; + } + + // Try VTank Parser first for .met files + if (path.EndsWith(".met", StringComparison.OrdinalIgnoreCase)) + { + var vtankRules = VTankMetaParser.IntelligentlyLoad(path); + if (vtankRules != null) + { + _settings.MetaRules = vtankRules; + _host.Actions.AddChatText($"[RynthAi] Imported VTank Profile: {Path.GetFileName(path)}", 5); + return; + } + } + + // Fallback to our native JSON loader + string json = File.ReadAllText(path); + var rules = JsonConvert.DeserializeObject<List<MetaRule>>(json); + if (rules != null) _settings.MetaRules = rules; + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] Meta Load Error: {ex.Message}", 1); + } + } + + + public void SaveCurrentProfile() + { + try + { + if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) return; + + string directory = Path.GetDirectoryName(_settings.CurrentMetaPath); + if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); + + string json = JsonConvert.SerializeObject(_settings.MetaRules, Formatting.Indented); + File.WriteAllText(_settings.CurrentMetaPath, json); + } + catch (Exception ex) + { + _host.Actions.AddChatText($"[RynthAi] Meta Save Error: {ex.Message}", 1); + } + } + + public void HandleChat(string text) + { + // TEMPORARY DEBUG: Uncomment this to see if text is hitting the manager + // _host.Actions.AddChatText($"[Meta Debug] Received: {text}", 5); + + _lastChatText = text; + _lastChatTime = DateTime.Now; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Meta/VTankMetaParser.cs b/Plugins/RynthAi/Meta/VTankMetaParser.cs new file mode 100644 index 0000000..4e8f40e --- /dev/null +++ b/Plugins/RynthAi/Meta/VTankMetaParser.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.IO; +using NexSuite.Plugins.RynthAi; + +namespace RynthAi.Meta +{ + public static class VTankMetaParser + { + public static List<MetaRule> IntelligentlyLoad(string path) + { + if (!File.Exists(path)) return new List<MetaRule>(); + + try + { + using (StreamReader reader = new StreamReader(path)) + { + string firstLine = reader.ReadLine(); + if (firstLine != "1") return null; // Not a valid VTank file format + + // Skip the 11-line header (CondAct schema metadata) + for (int i = 0; i < 11; i++) reader.ReadLine(); + + string countLine = reader.ReadLine(); + int ruleCount = int.Parse(countLine ?? "0"); + List<MetaRule> rules = new List<MetaRule>(); + + for (int i = 0; i < ruleCount; i++) + { + rules.Add(ParseCondAct(reader)); + } + return rules; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[RynthAi] Meta Load Error: {ex.Message}"); + return new List<MetaRule>(); + } + } + + private static MetaRule ParseCondAct(StreamReader reader) + { + MetaRule rule = new MetaRule(); + + // 1. CType (Condition Type - Integer) + reader.ReadLine(); // Consume 'i' type marker + rule.Condition = (MetaConditionType)int.Parse(reader.ReadLine()); + + // 2. AType (Action Type - Integer) + reader.ReadLine(); // Consume 'i' type marker + int vTankActionType = int.Parse(reader.ReadLine()); + + // Map VTank Action IDs to RynthAi Action Enums + if (vTankActionType == 1) rule.Action = MetaActionType.SetMetaState; + else if (vTankActionType == 2) rule.Action = MetaActionType.ChatCommand; + else if (vTankActionType == 3) rule.Action = MetaActionType.EmbeddedNavRoute; + + // 3. CData (Condition Data - Variant) + object cData = ReadVariant(reader); + + // Handle VTank Data Tables (Type 2) for complex conditions + if (cData is Dictionary<string, object> cDict) + { + // --- MONSTER COUNT TABLE --- + if (rule.Condition == MetaConditionType.MonsterNameCountWithinDistance) + { + string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : ""; + string dist = cDict.ContainsKey("d") ? cDict["d"].ToString() : "0"; + string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0"; + rule.ConditionData = $"{name},{dist},{count}"; + } + // --- INVENTORY COUNT TABLE --- + else if (rule.Condition == MetaConditionType.InventoryItemCount_LE || + rule.Condition == MetaConditionType.InventoryItemCount_GE) + { + string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : ""; + string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0"; + rule.ConditionData = $"{name},{count}"; + } + // --- SPELL TIME TABLE (NEW) --- + else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE) + { + string id = cDict.ContainsKey("s") ? cDict["s"].ToString() : "0"; + string time = cDict.ContainsKey("t") ? cDict["t"].ToString() : "0"; + rule.ConditionData = $"{id},{time}"; + } + else + { + rule.ConditionData = "TableData"; // Fallback for unsupported tables + } + } + else + { + rule.ConditionData = cData?.ToString() ?? ""; + } + + // 4. AData (Action Data - Variant) + object aData = ReadVariant(reader); + rule.ActionData = aData?.ToString() ?? ""; + + // 5. State (The State this rule belongs to - String) + reader.ReadLine(); // Consume 's' type marker + rule.State = reader.ReadLine(); + + // 6. Check for recursion (Children for Group conditions like All/Any/Not) + if (rule.Condition == MetaConditionType.All || rule.Condition == MetaConditionType.Any || rule.Condition == MetaConditionType.Not) + { + string nextType = reader.ReadLine(); + if (nextType == "2") // Marker for the children table + { + // Skip table metadata (k, v, n, n) + for (int j = 0; j < 4; j++) reader.ReadLine(); + + int childCount = int.Parse(reader.ReadLine() ?? "0"); + for (int j = 0; j < childCount; j++) + { + // Consume the table index key, then parse the child rule + ReadVariant(reader); + rule.Children.Add(ParseCondAct(reader)); + } + } + } + + return rule; + } + + /// <summary> + /// Reads a VTank "Variant" which includes a type marker (s, i, d, 2, etc.) + /// followed by the data. This allows the parser to stay synchronized. + /// </summary> + private static object ReadVariant(StreamReader reader) + { + string typeMarker = reader.ReadLine(); + if (typeMarker == null) return null; + + // Handle standard scalar types + switch (typeMarker) + { + case "s": // String + case "i": // Integer + case "d": // Double + case "b": // Boolean + case "u": // Unsigned Int + case "f": // Float + return reader.ReadLine(); + + case "2": // Table / Dictionary + // Skip table metadata headers + for (int i = 0; i < 4; i++) reader.ReadLine(); + + int pairCount = int.Parse(reader.ReadLine() ?? "0"); + Dictionary<string, object> table = new Dictionary<string, object>(); + + for (int j = 0; j < pairCount; j++) + { + object key = ReadVariant(reader); + object val = ReadVariant(reader); + + if (key != null) + { + table[key.ToString()] = val; + } + } + return table; + + default: + return null; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Nav/MovementActionHelper.cs b/Plugins/RynthAi/Nav/MovementActionHelper.cs new file mode 100644 index 0000000..8e6f8ef --- /dev/null +++ b/Plugins/RynthAi/Nav/MovementActionHelper.cs @@ -0,0 +1,310 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Direct calls to acclient.exe CM_Movement functions. + /// Derived entirely from Turbine's acclient.exe decompilation. + /// + /// Uses the same runtime pattern-scan approach as CombatActionHelper. + /// + /// ═══ TIER 1: CM_Movement server events (Proto_UI::SendToWeenie) ═══ + /// These send ordered game events to the server. They are __cdecl statics. + /// + /// Event_DoMovementCommand(motion, speed, hold_key) — opcode 0xF61E + /// Event_StopMovementCommand(motion, hold_key) — opcode 0xF661 + /// Event_Jump_NonAutonomous(extent) — opcode 0xF7C9 + /// Event_AutonomyLevel(level) — opcode 0xF752 + /// + /// All share the CM prologue: 83 EC 0C 53 56 57 E8 + /// Anchored by Event_StopMovementCommand (opcode 0xF661) which has a + /// unique-enough value in the CM_Movement cluster. + /// + /// ═══ TIER 2: CPhysicsObj::MoveToPosition (planned) ═══ + /// Client-side pathfinding via the player's physics object. + /// Requires tracing SmartBox::smartbox → player → MovementManager. + /// Would let the client handle all interpolation, heading, speed natively. + /// + /// ═══ TIER 3: MoveToManager queue (planned) ═══ + /// Direct movement node queue manipulation for maximum control. + /// + /// Motion constants (from acclient.exe motion tables): + /// 0x45000005 = MoveForward (WalkForward) + /// 0x45000006 = MoveBackward (WalkBackward) + /// 0x6500000D = TurnRight + /// 0x6500000E = TurnLeft + /// 0x41000003 = RunForward + /// + /// HoldKey values: + /// 0 = None + /// 1 = Run (hold shift) + /// 2 = AutoRun + /// </summary> + internal static class MovementActionHelper + { + // ── Motion constants ──────────────────────────────────────────────── + public const uint MOTION_WALK_FORWARD = 0x45000005; + public const uint MOTION_WALK_BACKWARD = 0x45000006; + public const uint MOTION_RUN_FORWARD = 0x41000003; + public const uint MOTION_TURN_RIGHT = 0x6500000D; + public const uint MOTION_TURN_LEFT = 0x6500000E; + public const uint MOTION_SIDESTEP_RIGHT = 0x6500000F; + public const uint MOTION_SIDESTEP_LEFT = 0x65000010; + + // ── HoldKey values ────────────────────────────────────────────────── + public const int HOLDKEY_NONE = 0; + public const int HOLDKEY_RUN = 1; + public const int HOLDKEY_AUTORUN = 2; + + // ── Delegate types ────────────────────────────────────────────────── + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelDoMovementCommand(uint motion, float speed, int holdKey); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelStopMovementCommand(uint motion, int holdKey); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelJumpNonAutonomous(float extent); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelAutonomyLevel(uint level); + + // ── Cached delegates ──────────────────────────────────────────────── + private static DelDoMovementCommand _doMovement; + private static DelStopMovementCommand _stopMovement; + private static DelJumpNonAutonomous _jumpNonAutonomous; + private static DelAutonomyLevel _autonomyLevel; + + private static bool _initialized; + private static Action<string> _log; + + // ── Shared prologue for CM_Movement functions ─────────────────────── + private static readonly byte[] CM_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 }; + + /// <summary> + /// Pattern-scans acclient.exe for CM_Movement functions at runtime. + /// Call once at plugin startup (after CombatActionHelper.Initialize). + /// </summary> + public static void Initialize(Action<string> chatLog = null) + { + _log = chatLog; + + try + { + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Movement scan FAILED: acclient.exe not found"); + return; + } + + int textRva = 0x1000; + int textSize = Math.Min(imageSize - textRva, 0x400000); + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── Anchor: StopMovementCommand via opcode 0xF661 ────────── + // This is unique enough in the CM_Movement region. + byte[] stopOpcode = { 0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00 }; + int stopOpcodeOff = FindPattern(text, stopOpcode); + if (stopOpcodeOff < 0) + { + Log("Movement scan FAILED: StopMovementCommand opcode 0xF661 not found"); + return; + } + + int stopFuncOff = FindPrologueBefore(text, stopOpcodeOff); + if (stopFuncOff < 0) + { + Log("Movement scan FAILED: StopMovementCommand prologue not found"); + return; + } + + int stopVA = textBaseVA + stopFuncOff; + Log($"StopMovementCommand at 0x{stopVA:X8}"); + + // ── Search near StopMovementCommand for the others ───────── + // CM_Movement functions cluster within ~0x700 bytes + int regionStart = Math.Max(0, stopOpcodeOff - 0x700); + int regionEnd = Math.Min(text.Length, stopOpcodeOff + 0x300); + + // DoMovementCommand: opcode 0xF61E (63006 decimal) + byte[] doOpcode = { 0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00 }; + int doOpcodeOff = FindPatternInRegion(text, doOpcode, regionStart, regionEnd); + int doFuncOff = doOpcodeOff >= 0 ? FindPrologueBefore(text, doOpcodeOff) : -1; + + // Jump_NonAutonomous: opcode 0xF7C9 (63433 decimal) + byte[] jumpNAOpcode = { 0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00 }; + int jumpNAOff = FindPatternInRegion(text, jumpNAOpcode, regionStart, regionEnd); + int jumpNAFuncOff = jumpNAOff >= 0 ? FindPrologueBefore(text, jumpNAOff) : -1; + + // AutonomyLevel: opcode 0xF752 (63314 decimal) + byte[] autoLevelOpcode = { 0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00 }; + int autoLevelOff = FindPatternInRegion(text, autoLevelOpcode, regionStart, regionEnd); + int autoLevelFuncOff = autoLevelOff >= 0 ? FindPrologueBefore(text, autoLevelOff) : -1; + + // ── Verify and create delegates ──────────────────────────── + if (doFuncOff < 0) + { + Log("Movement scan INCOMPLETE: DoMovementCommand not found"); + return; + } + + int doVA = textBaseVA + doFuncOff; + Log($"DoMovementCommand at 0x{doVA:X8}"); + + _stopMovement = (DelStopMovementCommand)Marshal.GetDelegateForFunctionPointer( + new IntPtr(stopVA), typeof(DelStopMovementCommand)); + _doMovement = (DelDoMovementCommand)Marshal.GetDelegateForFunctionPointer( + new IntPtr(doVA), typeof(DelDoMovementCommand)); + + if (jumpNAFuncOff >= 0) + { + int jumpNAVA = textBaseVA + jumpNAFuncOff; + _jumpNonAutonomous = (DelJumpNonAutonomous)Marshal.GetDelegateForFunctionPointer( + new IntPtr(jumpNAVA), typeof(DelJumpNonAutonomous)); + Log($"Jump_NonAutonomous at 0x{jumpNAVA:X8}"); + } + + if (autoLevelFuncOff >= 0) + { + int autoLevelVA = textBaseVA + autoLevelFuncOff; + _autonomyLevel = (DelAutonomyLevel)Marshal.GetDelegateForFunctionPointer( + new IntPtr(autoLevelVA), typeof(DelAutonomyLevel)); + Log($"AutonomyLevel at 0x{autoLevelVA:X8}"); + } + + _initialized = true; + Log("MovementActionHelper initialized — CM_Movement functions found via pattern scan"); + } + catch (Exception ex) + { + _initialized = false; + Log("MovementActionHelper init FAILED: " + ex.Message); + } + } + + public static bool IsInitialized => _initialized; + + // ══════════════════════════════════════════════════════════════════════ + // TIER 1 PUBLIC API — Server-side movement events + // ══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Sends a movement command to the server. + /// Replaces keyboard-driven movement for server authorization. + /// motion: one of MOTION_* constants + /// speed: 1.0 = normal, can scale + /// holdKey: HOLDKEY_NONE, HOLDKEY_RUN, or HOLDKEY_AUTORUN + /// </summary> + public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HOLDKEY_RUN) + { + if (!_initialized || _doMovement == null) return false; + try { return _doMovement(motion, speed, holdKey); } + catch (Exception ex) { Log("DoMovement failed: " + ex.Message); return false; } + } + + /// <summary> + /// Stops a specific movement command on the server. + /// motion: the motion to stop (same constant used in DoMovement) + /// holdKey: must match the holdKey used in the corresponding DoMovement + /// </summary> + public static bool StopMovement(uint motion, int holdKey = HOLDKEY_RUN) + { + if (!_initialized || _stopMovement == null) return false; + try { return _stopMovement(motion, holdKey); } + catch (Exception ex) { Log("StopMovement failed: " + ex.Message); return false; } + } + + /// <summary> + /// Non-autonomous jump with specified extent (0.0–1.0). + /// Replaces keyboard-simulated jump in RynthJumper. + /// </summary> + public static bool JumpNonAutonomous(float extent) + { + if (!_initialized || _jumpNonAutonomous == null) return false; + try { return _jumpNonAutonomous(Math.Max(0f, Math.Min(1f, extent))); } + catch (Exception ex) { Log("JumpNA failed: " + ex.Message); return false; } + } + + /// <summary> + /// Sets the autonomy level for the client. + /// 0 = server controls, 1 = client controls (normal play), 2 = full autonomy. + /// </summary> + public static bool SetAutonomyLevel(uint level) + { + if (!_initialized || _autonomyLevel == null) return false; + try { return _autonomyLevel(level); } + catch (Exception ex) { Log("AutonomyLevel failed: " + ex.Message); return false; } + } + + // ══════════════════════════════════════════════════════════════════════ + // PATTERN SCANNER (shared with CombatActionHelper design) + // ══════════════════════════════════════════════════════════════════════ + + private static int FindPattern(byte[] data, byte[] pattern) + { + return FindPatternInRegion(data, pattern, 0, data.Length); + } + + private static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end) + { + int limit = Math.Min(end, data.Length) - pattern.Length; + for (int i = Math.Max(0, start); i <= limit; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) { match = false; break; } + } + if (match) return i; + } + return -1; + } + + private static int FindPrologueBefore(byte[] data, int opcodeOffset) + { + for (int back = 1; back < 300; back++) + { + int pos = opcodeOffset - back; + if (pos < 1 || pos + CM_PROLOGUE.Length > data.Length) continue; + + bool match = true; + for (int j = 0; j < CM_PROLOGUE.Length; j++) + { + if (data[pos + j] != CM_PROLOGUE[j]) { match = false; break; } + } + + if (match) + { + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + } + return -1; + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/NavigationManager.cs b/Plugins/RynthAi/Nav/NavigationManager.cs new file mode 100644 index 0000000..2cf6290 --- /dev/null +++ b/Plugins/RynthAi/Nav/NavigationManager.cs @@ -0,0 +1,1139 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// VTank-faithful navigation engine. + /// + /// ARCHITECTURE: + /// Forward motion: SetAutorun(true/false) via Decal API. + /// - Player can toggle autorun off manually for immediate control. + /// - Re-asserted every 500ms as heartbeat. + /// + /// Steering while running: SetClientMotion(TurnRight/TurnLeft) via + /// AcClient command interpreter. These combine with autorun naturally + /// (like pressing W+A or W+D) without interrupting forward motion. + /// + /// Large turns (>60°): Stop autorun, snap Actions.Heading while + /// stopped, resume autorun once error is below 20°. + /// + /// Closest-approach detection prevents circling waypoints. + /// </summary> + public class NavigationManager + { + private readonly CoreManager _core; + private readonly UISettings _settings; + private readonly PluginHost _host; + + // ── Motion command constants (turns only — forward uses SetAutorun) ──── + private const uint MOTION_TURNRIGHT = 0x6500000D; + private const uint MOTION_TURNLEFT = 0x6500000E; + + // ── Nav tick ──────────────────────────────────────────────────────────── + private DateTime _lastNavTick = DateTime.MinValue; + private const double NAV_TICK_MS = 33.0; // ~30 Hz — smoother turn toggling + + // ── Stop debounce ─────────────────────────────────────────────────────── + private DateTime _stopRequestedAt = DateTime.MaxValue; + private const double STOP_DEBOUNCE_MS = 300.0; + + // ── Movement state ────────────────────────────────────────────────────── + private bool _isMovingForward = false; + private bool _hasStopped = true; + private bool _turnsStopped = true; + public bool DebugNav = false; + private DateTime _lastDebugPrint = DateTime.MinValue; + private double _lastGoodHeading = 0; + private bool _hasGoodHeading = false; // true = we've already stopped, don't repeat + + // ── W tap heartbeat — periodic safety tap ─────────────────────────────── + private DateTime _lastWTap = DateTime.MinValue; + private const double W_HEARTBEAT_MS = 500.0; + + // ── Turning state ─────────────────────────────────────────────────────── + private bool _isTurning = false; + + // ── Heading thresholds (from settings — tunable in Advanced → Navigation) ── + private double DeadZone => Math.Max(0.5, _settings.NavDeadZone); + private double BigTurnEnter => Math.Max(5.0, _settings.NavStopTurnAngle); + private double BigTurnExit => Math.Max(1.0, Math.Min(_settings.NavResumeTurnAngle, BigTurnEnter - 1)); + private double SweepMult => Math.Max(1.0, _settings.NavSweepMult); + + // ── Arrival / lookahead ───────────────────────────────────────────────── + private double ArrivalYards => Math.Max(1.5, _settings.FollowNavMin); + private double LookaheadYards => ArrivalYards * 0.1; + + // ── Closest approach tracking ─────────────────────────────────────────── + // Detects when we've passed a waypoint even if we never entered the + // arrival radius (turn radius at speed is too wide). If distance was + // decreasing and starts increasing, we've swept past — advance. + private double _prevDist = double.MaxValue; + + // ── Route bookkeeping ─────────────────────────────────────────────────── + private int _linearDir = 1; + private bool _inPause = false; + private DateTime _pauseUntil = DateTime.MinValue; + private bool _actionFired = false; + private DateTime _actionExpiry = DateTime.MinValue; + private const double ACTION_TIMEOUT_MS = 10000.0; + + // ── Portal/Recall state machine ───────────────────────────────────────── + private enum PortalState + { + None, + Settling, + EquippingWand, + EnteringMagicMode, + CastingSpell, + WaitingForPortalOrTeleport, + WaitingForPortalExit, + PostTeleportSettle // Brief pause after teleporting to cancel UseItem effects + } + private PortalState _portalState = PortalState.None; + private DateTime _portalStateStart = DateTime.MinValue; + private int _preCastLandblock = 0; + private int _prePortalLandblock = 0; + private double _prePortalNS = double.NaN; + private double _prePortalEW = double.NaN; + private const double PORTAL_STATE_TIMEOUT_MS = 15000.0; + private const double SETTLE_DELAY_MS = 600.0; + private const double WAND_EQUIP_DELAY_MS = 1000.0; + private const double MAGIC_MODE_DELAY_MS = 800.0; + private const double CAST_DELAY_MS = 500.0; + private const double PORTAL_WAIT_MS = 3000.0; + + // ── Stuck watchdog ────────────────────────────────────────────────────── + private double _watchdogNS = double.NaN; + private double _watchdogEW = double.NaN; + private DateTime _watchdogNext = DateTime.MinValue; + private int _stuckCount = 0; + private bool _inRecovery = false; + private DateTime _recoveryUntil = DateTime.MinValue; + private const double WATCHDOG_MS = 5000.0; + private const double STUCK_YD = 2.0; + private const double RECOVERY_MS = 1200.0; + + // ── Tier 2 state (MoveToPosition via MovementManager) ───────────────── + private int _tier2TargetIdx = -1; // waypoint index we last issued MoveToPosition for + private bool _tier2Active = false; // true while a Tier2 MoveToPosition is in flight + private DateTime _tier2IssuedAt = DateTime.MinValue; + + // ── Win32 (focus detection only) ──────────────────────────────────────── + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + public bool IsReversed { get; set; } = false; + public void SetReverse(bool reverse) { IsReversed = reverse; } + + private IntPtr _gameHwnd = IntPtr.Zero; + private IntPtr GameHwnd + { + get + { + if (_gameHwnd == IntPtr.Zero) + _gameHwnd = Process.GetCurrentProcess().MainWindowHandle; + return _gameHwnd; + } + } + + private bool IsGameFocused() => GetForegroundWindow() == GameHwnd; + + public NavigationManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════════════ + // CLIENT MOTION + W TAP + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Direct client memory motion — same as UB's setmotion. + /// Used ONCE to establish forward motion state. + /// </summary> + private unsafe void SetClientMotion(uint motion, bool on) + { + try + { + ((ACCmdInterp*)(*SmartBox.smartbox)->cmdinterp)->SetMotion(motion, on); + } + catch { } + } + + /// <summary> + private void StartForward() + { + if (!_isMovingForward) + { + try { _core.Actions.SetAutorun(true); } catch { } + _isMovingForward = true; + } + } + + private void StopForward() + { + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + } + + private void StopMovement() + { + _isTurning = false; + StopForward(); + ClearTurnMotions(); + CancelTier2(); + } + + private void CancelTier2() + { + if (_tier2Active) + { + try { Tier2MovementHelper.CancelMoveTo(); } catch { } + _tier2Active = false; + } + _tier2TargetIdx = -1; + } + + private void ClearTurnMotions() + { + SetClientMotion(MOTION_TURNRIGHT, false); + SetClientMotion(MOTION_TURNLEFT, false); + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC ENTRY POINT + // ══════════════════════════════════════════════════════════════════════════ + + private bool _tier2ModeLoggedOnce = false; + + public void ProcessNavigation(bool isFighting) + { + // One-shot: dump UB's SmartBox pointer chain vs our pattern-scanned one + if (_settings.MovementMode == 2 && !_tier2ModeLoggedOnce) + { + _tier2ModeLoggedOnce = true; + Tier2Log.Log($"MODE 2 ACTIVE: macro={_settings.IsMacroRunning} " + + $"nav={_settings.EnableNavigation} state={_settings.CurrentState}"); + } + // The priority dispatcher in PluginCore already controls call order. + // Nav only needs to check: macro running, nav enabled, and state is available. + // "Idle" means no higher-priority system claimed this frame. + // "Navigating" means WE claimed it last frame and are still going. + bool shouldNav = _settings.IsMacroRunning + && _settings.EnableNavigation + && (_settings.CurrentState == "Idle" || _settings.CurrentState == "Navigating"); + + if (!shouldNav) + { + if (!_hasStopped && !_turnsStopped) + { try { ClearTurnMotions(); } catch { } _turnsStopped = true; } + if (_stopRequestedAt == DateTime.MaxValue) + _stopRequestedAt = DateTime.Now; + if ((DateTime.Now - _stopRequestedAt).TotalMilliseconds >= STOP_DEBOUNCE_MS) + { + if (!_hasStopped) + { + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + } + } + return; + } + _stopRequestedAt = DateTime.MaxValue; + _hasStopped = false; + _turnsStopped = false; + + var route = _settings.CurrentRoute; + if (route == null || route.Points.Count == 0) { StopMovement(); return; } + + // Claim the traffic light — we are actively navigating + _settings.CurrentState = "Navigating"; + + // Rate limit to ~15 Hz + if ((DateTime.Now - _lastNavTick).TotalMilliseconds < NAV_TICK_MS) return; + _lastNavTick = DateTime.Now; + + int idx = _settings.ActiveNavIndex; + if (!IndexValid(idx, route)) { HandleRouteEnd(route); return; } + + UpdateWatchdog(); + if (_inRecovery) + { + if (DateTime.Now >= _recoveryUntil) _inRecovery = false; + return; + } + + var pt = route.Points[idx]; + + // ── Pause ─────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Pause) + { + StopMovement(); + if (!_inPause) { _inPause = true; _pauseUntil = DateTime.Now.AddMilliseconds(pt.PauseTimeMs); } + if (DateTime.Now >= _pauseUntil) { _inPause = false; Advance(route); } + return; + } + + // ── Chat ──────────────────────────────────────────────────────────── + if (pt.Type == NavPointType.Chat) + { + StopMovement(); + if (!_actionFired) + { + _actionFired = true; + try { _core.Actions.InvokeChatParser(pt.ChatCommand); } catch { } + Advance(route); + } + return; + } + + // ── Recall / PortalNPC ────────────────────────────────────────────── + if (pt.Type == NavPointType.Recall || pt.Type == NavPointType.PortalNPC) + { + if (_portalState == PortalState.None) StopMovement(); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try { _host.Actions.AddChatText($"[NavDbg] PORTAL state={_portalState} elapsed={(DateTime.Now - _portalStateStart).TotalMilliseconds:F0}ms", 1); } catch { } + } + ProcessPortalAction(pt, route); + return; + } + + // ── Standard coordinate waypoint ──────────────────────────────────── + _actionFired = false; + _inPause = false; + + var pos = GetPos(); + if (pos == null) return; + + double dNS = pt.NS - pos.NorthSouth; + double dEW = pt.EW - pos.EastWest; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (dist < ArrivalYards) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + + // ── Tier 2: delegate to client physics engine ──────────────────── + if (_settings.MovementMode == 2 && Tier2MovementHelper.IsInitialized) + { + try + { + Tier2Log.Log("T2 CHECK: calling GetPlayerCellId"); + uint _t2cell = Tier2MovementHelper.GetPlayerCellId(); + Tier2Log.Log($"T2 CHECK: cell=0x{_t2cell:X8} outdoor={(_t2cell & 0xFFFF) < 0x100}"); + Tier2MovementHelper.LogPointerChain(); // after cellId succeeds + if ((_t2cell & 0xFFFF) < 0x100) + { + ProcessTier2Waypoint(idx, pt, route, pos, dist); + return; + } + } + catch (Exception ex) + { + Tier2Log.Log($"T2 CHECK CRASHED: {ex}"); + // Fall through to Legacy + } + } + + // ── Closest approach detection (Tier 0/1 only) ─────────────────── + // If we were getting closer (within a reasonable range) and now + // we're moving away, we've swept past the waypoint. Advance. + // This handles the case where the turn radius at speed prevents + // the character from entering the arrival radius exactly. + if (_prevDist < ArrivalYards * SweepMult && dist > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + Advance(route); + return; + } + _prevDist = dist; + + // ── Lookahead blend ───────────────────────────────────────────────── + double tNS = pt.NS, tEW = pt.EW; + if (dist < LookaheadYards) + { + int ni = PeekNext(idx, route); + if (ni >= 0) + { + var np = route.Points[ni]; + double t = 1.0 - (dist / LookaheadYards); + tNS = Lerp(pt.NS, np.NS, t); + tEW = Lerp(pt.EW, np.EW, t); + } + } + + // ── Compute heading error ─────────────────────────────────────────── + double desiredDeg = Math.Atan2(tEW - pos.EastWest, tNS - pos.NorthSouth) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + + double rawHeading = 0; + try { rawHeading = _core.Actions.Heading; } catch { } + double currentDeg; + if (rawHeading != 0.0) + { currentDeg = rawHeading; _lastGoodHeading = rawHeading; _hasGoodHeading = true; } + else if (_hasGoodHeading) + { currentDeg = _lastGoodHeading; } + else + { currentDeg = desiredDeg; } + double error = NormalizeAngle(desiredDeg - currentDeg); + double absError = Math.Abs(error); + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + string turnDir = absError < DeadZone ? "NONE" : (error > 0 ? "RIGHT" : "LEFT"); + double ox = 0, oy = 0; + try { var me = _core.WorldFilter[_core.CharacterFilter.Id]; if (me != null) { var o = me.Offset(); ox = o.X; oy = o.Y; } } catch { } + try { _host.Actions.AddChatText($"[NavDbg] raw={rawHeading:F1} cur={currentDeg:F1} des={desiredDeg:F1} err={error:F1} turn={turnDir} dist={dist:F1}yd oX={ox:F2} oY={oy:F2}", 1); } catch { } + } + + // ═════════════════════════════════════════════════════════════════════ + // STEERING + // ═════════════════════════════════════════════════════════════════════ + + // ── STATE: Turning in place (big turn while stopped) ───────────────── + if (_isTurning) + { + if (absError > BigTurnExit) + { + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + return; + } + + // Close enough — clear turn keys, start running + _isTurning = false; + ClearTurnMotions(); + StartForward(); + return; + } + + // ── BIG TURN (>60°): stop and face ────────────────────────────────── + if (absError > BigTurnEnter) + { + StopForward(); + ClearTurnMotions(); + try { _core.Actions.Heading = (float)desiredDeg; } catch { } + _isTurning = true; + return; + } + + // ── Ensure we're moving forward ───────────────────────────────────── + StartForward(); + + // ── Near waypoint: stop turning, just run straight ─────────────────── + bool closeToWaypoint = dist < ArrivalYards * SweepMult; + + // ── SMALL CORRECTION: use TurnRight/TurnLeft while running ────────── + // These combine with Forward at the command interpreter level — + // the character turns while running naturally, like pressing W+A or W+D. + // No Actions.Heading, no motion interrupt, no W tap needed. + if (absError > DeadZone && !closeToWaypoint) + { + if (error > 0) + { + // Need to turn right + SetClientMotion(MOTION_TURNRIGHT, true); + SetClientMotion(MOTION_TURNLEFT, false); + } + else + { + // Need to turn left + SetClientMotion(MOTION_TURNLEFT, true); + SetClientMotion(MOTION_TURNRIGHT, false); + } + } + else + { + // On course or close to waypoint — stop turning + ClearTurnMotions(); + } + + // ── HEARTBEAT: re-assert autorun periodically as safety net ───────── + if (_isMovingForward && (DateTime.Now - _lastWTap).TotalMilliseconds > W_HEARTBEAT_MS) + { + try { _core.Actions.SetAutorun(true); } catch { } + _lastWTap = DateTime.Now; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // ROUTE ADVANCEMENT + // ══════════════════════════════════════════════════════════════════════════ + + private void Advance(VTankNavParser route) + { + _actionFired = false; + _prevDist = double.MaxValue; + switch (route.RouteType) + { + case NavRouteType.Circular: + _settings.ActiveNavIndex = (_settings.ActiveNavIndex + 1) % route.Points.Count; + break; + case NavRouteType.Linear: + int n = _settings.ActiveNavIndex + _linearDir; + if (n < 0 || n >= route.Points.Count) { _linearDir = -_linearDir; n = _settings.ActiveNavIndex + _linearDir; } + _settings.ActiveNavIndex = n; + break; + case NavRouteType.Once: + _settings.ActiveNavIndex++; + if (_settings.ActiveNavIndex >= route.Points.Count) { _settings.EnableNavigation = false; StopMovement(); } + break; + case NavRouteType.Follow: + _settings.ActiveNavIndex = 0; + break; + } + } + + private void HandleRouteEnd(VTankNavParser route) + { + if (route.RouteType == NavRouteType.Circular) _settings.ActiveNavIndex = 0; + else StopMovement(); + } + + private int PeekNext(int cur, VTankNavParser route) + { + switch (route.RouteType) + { + case NavRouteType.Circular: return (cur + 1) % route.Points.Count; + case NavRouteType.Linear: int n = cur + _linearDir; return (n >= 0 && n < route.Points.Count) ? n : -1; + case NavRouteType.Once: return (cur + 1 < route.Points.Count) ? cur + 1 : -1; + default: return -1; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // TIER 2 MOVEMENT (CPhysicsObj::MoveToPosition via MovementManager) + // ══════════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tier 2 waypoint processor — issues a single MoveToPosition call to the + /// client's physics engine, then lets it handle all interpolation and heading. + /// Re-issues the call on waypoint change or if no progress after timeout. + /// </summary> + private void ProcessTier2Waypoint( + int idx, NavPoint pt, VTankNavParser route, + CoordsObject pos, double distYards) + { + // ── Closest approach detection (shared with Tier 0/1) ──────────── + if (_prevDist < ArrivalYards * SweepMult && distYards > _prevDist + 0.3) + { + _prevDist = double.MaxValue; + CancelTier2(); + Advance(route); + return; + } + _prevDist = distYards; + + // ── Decide whether to issue / re-issue the MoveToPosition call ─── + bool needsIssue = false; + + if (idx != _tier2TargetIdx) + { + // Waypoint changed — cancel old movement, issue new + CancelTier2(); + needsIssue = true; + } + else if (_tier2Active && + (DateTime.Now - _tier2IssuedAt).TotalMilliseconds > _settings.T2ReissueMs) + { + // Timeout — re-issue in case the client gave up + CancelTier2(); + needsIssue = true; + } + else if (!_tier2Active) + { + needsIssue = true; + } + + if (needsIssue) + { + IssueTier2Move(pt, pos); + _tier2TargetIdx = idx; + } + + if (DebugNav && (DateTime.Now - _lastDebugPrint).TotalMilliseconds > 1000) + { + _lastDebugPrint = DateTime.Now; + try + { + _host.Actions.AddChatText( + $"[NavDbg] T2 idx={idx} dist={distYards:F1}yd active={_tier2Active} " + + $"age={(DateTime.Now - _tier2IssuedAt).TotalMilliseconds:F0}ms", 1); + } + catch { } + } + } + + /// <summary> + /// Converts Decal NS/EW to internal AC coordinates and calls MoveToPosition. + /// Works by adding the yard-delta to the player's known-good internal position, + /// then normalizing cell/landblock boundaries with Math.Floor (critical for + /// negative deltas — (int) rounds toward zero, not down, producing garbage cells). + /// </summary> + private void IssueTier2Move(NavPoint pt, CoordsObject decalPos) + { + try + { + uint playerCell; + float playerX, playerY, playerZ; + if (!Tier2MovementHelper.GetPlayerPosition( + out playerCell, out playerX, out playerY, out playerZ)) + return; + + if ((playerCell & 0xFFFF) >= 0x100) + return; // indoor — caller shouldn't have sent us here + + double deltaEW = (pt.EW - decalPos.EastWest) * 240.0; + double deltaNS = (pt.NS - decalPos.NorthSouth) * 240.0; + double deltaDist = Math.Sqrt(deltaEW * deltaEW + deltaNS * deltaNS); + double maxRange = Math.Max(10.0, _settings.T2MaxRangeYd); + if (deltaDist > maxRange) + { + double scale = maxRange / deltaDist; + deltaEW *= scale; + deltaNS *= scale; + } + + int pLbEW = (int)((playerCell >> 24) & 0xFF); + int pLbNS = (int)((playerCell >> 16) & 0xFF); + + // Player origin is LANDBLOCK-relative (0–192 yards), NOT cell-relative + double globalEW = pLbEW * 192.0 + playerX + deltaEW; + double globalNS = pLbNS * 192.0 + playerY + deltaNS; + + int tLbEW = (int)Math.Floor(globalEW / 192.0); + int tLbNS = (int)Math.Floor(globalNS / 192.0); + tLbEW = Math.Max(0, Math.Min(254, tLbEW)); + tLbNS = Math.Max(0, Math.Min(254, tLbNS)); + + // Target origin: landblock-relative (0–192), same as how AC stores it + double inLbEW = globalEW - tLbEW * 192.0; + double inLbNS = globalNS - tLbNS * 192.0; + + // Cell index is derived from position but origin stays landblock-relative + int tColEW = Math.Max(0, Math.Min(7, (int)Math.Floor(inLbEW / 24.0))); + int tRowNS = Math.Max(0, Math.Min(7, (int)Math.Floor(inLbNS / 24.0))); + + float localX = Math.Max(0.5f, Math.Min(191.5f, (float)inLbEW)); + float localY = Math.Max(0.5f, Math.Min(191.5f, (float)inLbNS)); + float localZ = playerZ; + + int cellIdx = tRowNS * 8 + tColEW + 1; + uint targetCell = (uint)((tLbEW << 24) | (tLbNS << 16) | cellIdx); + + int maxLb = Math.Max(1, _settings.T2MaxLandblocks); + if (Math.Abs(tLbEW - pLbEW) > maxLb || Math.Abs(tLbNS - pLbNS) > maxLb) + { + Tier2Log.Log($"SKIP: lb ({tLbEW},{tLbNS}) too far from ({pLbEW},{pLbNS})"); + return; + } + + Tier2Log.Log($"ISSUE: 0x{targetCell:X8} local=({localX:F1},{localY:F1},{localZ:F1}) " + + $"delta=({deltaEW:F0},{deltaNS:F0})yd spd={_settings.T2Speed} dist={_settings.T2DistanceTo} walk={_settings.T2WalkWithinYd}"); + + uint result = Tier2MovementHelper.MoveToPosition( + targetCell, localX, localY, localZ, + Math.Max(0.1f, _settings.T2Speed), + Math.Max(0.1f, _settings.T2DistanceTo), + Math.Max(0f, _settings.T2WalkWithinYd)); + + _tier2Active = (result == 0); + _tier2IssuedAt = DateTime.Now; + Tier2Log.Log($"RESULT: {result}"); + } + catch (Exception ex) + { + Tier2Log.Log($"ISSUE EXCEPTION: {ex}"); + } + } + + private void ProcessPortalAction(NavPoint pt, VTankNavParser route) + { + // Timeout check - if we've been in this portal action too long, reset and advance + if (_portalState != PortalState.None) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_STATE_TIMEOUT_MS) + { + ResetPortalState(); + Advance(route); + return; + } + } + + // Initialize state machine — go to Settling first to let turns stop + if (_portalState == PortalState.None) + { + _portalState = PortalState.Settling; + _portalStateStart = DateTime.Now; + _preCastLandblock = GetCurrentLandblock(); + // Store position for teleport detection + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + // Aggressively clear ALL motion + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + return; + } + + switch (_portalState) + { + case PortalState.Settling: + // Keep clearing turns every frame until settled + try { ClearTurnMotions(); } catch { } + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > SETTLE_DELAY_MS) + { + _portalState = PortalState.EquippingWand; + _portalStateStart = DateTime.Now; + } + break; + + case PortalState.EquippingWand: + ProcessEquippingWand(pt); + break; + + case PortalState.EnteringMagicMode: + ProcessEnteringMagicMode(); + break; + + case PortalState.CastingSpell: + ProcessCastingSpell(pt); + break; + + case PortalState.WaitingForPortalOrTeleport: + ProcessWaitingForPortalOrTeleport(pt, route); + break; + + case PortalState.WaitingForPortalExit: + ProcessWaitingForPortalExit(route); + break; + + case PortalState.PostTeleportSettle: + // Hammer stop commands to cancel any lingering UseItem walk action + // UseItem walk persists through teleportation in the AC client — need + // to keep hammering for ~2s until it expires on its own + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + _isMovingForward = false; + _isTurning = false; + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > 4000) + { + ResetPortalState(); + Advance(route); + } + break; + } + } + + private void ProcessEquippingWand(NavPoint pt) + { + // Only equip wand for recall spells, not portal NPCs + if (pt.Type == NavPointType.PortalNPC) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + try { var p = GetPos(); if (p != null) { _prePortalNS = p.NorthSouth; _prePortalEW = p.EastWest; } } catch { } + + // Use the portal NPC — partial name matching + try + { + WorldObject bestMatch = null; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.Name == pt.TargetName) { bestMatch = wo; break; } + if (wo.Name != null && pt.TargetName != null && + (wo.Name.Contains(pt.TargetName) || pt.TargetName.Contains(wo.Name))) + { bestMatch = wo; } + } + if (bestMatch != null) + _core.Actions.UseItem(bestMatch.Id, 0); + } + catch { } + return; + } + + // For recall spells, equip a wand if needed + double elapsed = (DateTime.Now - _portalStateStart).TotalMilliseconds; + + if (elapsed < 50) + { + try + { + // Check if wand already equipped — UseItem on equipped wand UNEQUIPS it + bool wandEquipped = false; + int wandToEquip = 0; + + // Scan all known objects for wands + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + int slots = wo.Values(LongValueKey.EquippedSlots, 0); + if (slots != 0) + { + wandEquipped = true; + break; + } + else if (wandToEquip == 0) + { + wandToEquip = wo.Id; // remember first unequipped wand + } + } + } + + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + if (DebugNav) try { _host.Actions.AddChatText($"[NavDbg] WAND equipping id={wandToEquip}", 1); } catch { } + } + else if (wandEquipped) + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND already equipped, skipping", 1); } catch { } + } + else + { + if (DebugNav) try { _host.Actions.AddChatText("[NavDbg] WAND none found in inventory!", 1); } catch { } + } + } + catch { } + } + + // Wait for wand equip to complete, then proceed to magic mode + if (elapsed > WAND_EQUIP_DELAY_MS) + { + _portalState = PortalState.EnteringMagicMode; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessEnteringMagicMode() + { + // Enter magic casting mode + try + { + _core.Actions.SetCombatMode(CombatState.Magic); + } + catch { } + + // Wait a moment for mode change, then proceed + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > MAGIC_MODE_DELAY_MS) + { + _portalState = PortalState.CastingSpell; + _portalStateStart = DateTime.Now; + } + } + + private void ProcessCastingSpell(NavPoint pt) + { + // Cast the recall spell + if ((DateTime.Now - _portalStateStart).TotalMilliseconds < 100) // Only cast once + { + try + { + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + } + catch { } + } + + // Wait a moment for cast, then proceed to waiting + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > CAST_DELAY_MS) + { + _portalState = PortalState.WaitingForPortalOrTeleport; + _portalStateStart = DateTime.Now; + _prePortalLandblock = GetCurrentLandblock(); + } + } + + private void ProcessWaitingForPortalOrTeleport(NavPoint pt, VTankNavParser route) + { + // Detect teleport by checking if we moved far from pre-portal position + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + if (distFromStart > 50.0) // moved > 50 yards = definitely teleported + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Also check landblock as fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + + // For PortalNPC: no short timeout — let UseItem walk complete. + // The global PORTAL_STATE_TIMEOUT_MS (15s) handles overall timeout. + // For Recall: use shorter timeout since teleport should be instant. + if (pt.Type == NavPointType.Recall) + { + if ((DateTime.Now - _portalStateStart).TotalMilliseconds > PORTAL_WAIT_MS) + { + ResetPortalState(); + Advance(route); + } + } + } + + private void ProcessWaitingForPortalExit(VTankNavParser route) + { + // Distance-based teleport detection + try + { + var pos = GetPos(); + if (pos != null && !double.IsNaN(_prePortalNS)) + { + double dNS = pos.NorthSouth - _prePortalNS; + double dEW = pos.EastWest - _prePortalEW; + double distFromStart = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (distFromStart > 50.0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + return; + } + } + } + catch { } + + // Landblock fallback + int currentLandblock = GetCurrentLandblock(); + if (currentLandblock != _prePortalLandblock && currentLandblock != 0 && _prePortalLandblock != 0) + { + _portalState = PortalState.PostTeleportSettle; + _portalStateStart = DateTime.Now; + } + } + + private void ResetPortalState() + { + _portalState = PortalState.None; + _portalStateStart = DateTime.MinValue; + _preCastLandblock = 0; + _prePortalLandblock = 0; + _prePortalNS = double.NaN; + _prePortalEW = double.NaN; + + // Return to peace mode after portal/recall + try + { + _core.Actions.SetCombatMode(CombatState.Peace); + } + catch { } + } + + private int GetCurrentLandblock() + { + try + { + var pos = GetPos(); + if (pos != null) + { + // Landblock is the high word of the location + // AC coordinates encode landblock in a specific way + // For simplicity, we'll use a combination of NS/EW rounded to detect changes + int nsBlock = (int)(pos.NorthSouth / 0.8); + int ewBlock = (int)(pos.EastWest / 0.8); + return (nsBlock << 16) | (ewBlock & 0xFFFF); + } + } + catch { } + return 0; + } + + private void FireSpecialAction(NavPoint pt) + { + // Legacy method - now mostly unused, kept for compatibility + try + { + if (pt.Type == NavPointType.Recall) + _core.Actions.CastSpell(pt.SpellId, _core.CharacterFilter.Id); + else if (pt.Type == NavPointType.PortalNPC) + { + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo != null && wo.Name == pt.TargetName) { _core.Actions.UseItem(wo.Id, 0); break; } + } + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // STUCK WATCHDOG + // ══════════════════════════════════════════════════════════════════════════ + + private void UpdateWatchdog() + { + if (DateTime.Now < _watchdogNext) return; + _watchdogNext = DateTime.Now.AddMilliseconds(WATCHDOG_MS); + + var pos = GetPos(); + if (pos == null) return; + + double curNS = pos.NorthSouth, curEW = pos.EastWest; + + if (!double.IsNaN(_watchdogNS) && _isMovingForward) + { + bool dataStale = Math.Abs(curNS - _watchdogNS) < 0.000001 + && Math.Abs(curEW - _watchdogEW) < 0.000001 + && !IsGameFocused(); + + if (!dataStale) + { + double dN = curNS - _watchdogNS, dE = curEW - _watchdogEW; + double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0; + if (moved < STUCK_YD) { _stuckCount++; BeginRecovery(); } + else _stuckCount = 0; + } + } + _watchdogNS = curNS; _watchdogEW = curEW; + } + + private void BeginRecovery() + { + _inRecovery = true; + _recoveryUntil = DateTime.Now.AddMilliseconds(RECOVERY_MS); + StopMovement(); + + // Jump to try to unstick + try + { + if (MovementActionHelper.IsInitialized) + { + // Tier 1: direct jump call — no keyboard/motion interpreter dependency + MovementActionHelper.JumpNonAutonomous(0.5f); + } + else + { + // Legacy: local motion command for jump + SetClientMotion(0x2500003b, true); + SetClientMotion(0x2500003b, false); + } + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // PUBLIC LIFECYCLE + // ══════════════════════════════════════════════════════════════════════════ + + public void Stop() + { + _inPause = false; _actionFired = false; _inRecovery = false; + _linearDir = 1; _stopRequestedAt = DateTime.MaxValue; + ResetPortalState(); + CancelTier2(); + try { _core.Actions.SetAutorun(false); } catch { } + try { ClearTurnMotions(); } catch { } + _isMovingForward = false; + _isTurning = false; + _hasStopped = true; + _turnsStopped = true; + } + + public void ResetRouteState() + { + Stop(); + _stuckCount = 0; + _prevDist = double.MaxValue; + _watchdogNS = double.NaN; _watchdogEW = double.NaN; + _hasGoodHeading = false; + } + + public int FindNearestWaypoint(VTankNavParser route) + { + if (route == null || route.Points == null || route.Points.Count == 0) + return 0; + + try + { + var pos = GetPos(); + if (pos == null) + return 0; + + double myNS = pos.NorthSouth; + double myEW = pos.EastWest; + + int nearestIdx = 0; + double nearestDist = double.MaxValue; + + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; + // Only consider regular waypoints, not special actions + if (pt.Type == NavPointType.Point) + { + double dNS = pt.NS - myNS; + double dEW = pt.EW - myEW; + double dist = Math.Sqrt(dNS * dNS + dEW * dEW); + + if (dist < nearestDist) + { + nearestDist = dist; + nearestIdx = i; + } + } + } + + return nearestIdx; + } + catch + { + return 0; + } + } + + // ══════════════════════════════════════════════════════════════════════════ + // UTILITIES + // ══════════════════════════════════════════════════════════════════════════ + + private bool IndexValid(int i, VTankNavParser r) => r?.Points != null && i >= 0 && i < r.Points.Count; + + private CoordsObject GetPos() + { + try { return _core.WorldFilter[_core.CharacterFilter.Id].Coordinates(); } + catch { return null; } + } + + private static double NormalizeAngle(double a) + { + while (a > 180.0) a -= 360.0; + while (a < -180.0) a += 360.0; + return a; + } + + private static double Lerp(double a, double b, double t) => a + (b - a) * t; + } +} diff --git a/Plugins/RynthAi/Nav/Tier2Log.cs b/Plugins/RynthAi/Nav/Tier2Log.cs new file mode 100644 index 0000000..e789f5c --- /dev/null +++ b/Plugins/RynthAi/Nav/Tier2Log.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Crash-safe file logger. Every write flushes immediately so the last + /// line survives a hard client crash. Writes to RynthAi\Logs\tier2.log, + /// rolls over at 1 MB. + /// </summary> + internal static class Tier2Log + { + private static readonly string LogDir = + @"C:\Games\DecalPlugins\NexSuite\RynthAi\Logs"; + private static readonly string LogPath = + Path.Combine(LogDir, "tier2.log"); + private const long MAX_SIZE = 1024 * 1024; // 1 MB rollover + + private static readonly object _lock = new object(); + private static bool _initialized; + + /// <summary> + /// Write a timestamped line to tier2.log. Safe to call from any thread. + /// </summary> + public static void Log(string msg) + { + try + { + lock (_lock) + { + EnsureDir(); + Rollover(); + using (var sw = new StreamWriter(LogPath, true)) + { + sw.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] {msg}"); + sw.Flush(); + } + } + } + catch { } + } + + /// <summary> + /// Write a separator + header for a new session. + /// </summary> + public static void StartSession() + { + Log("════════════════════════════════════════════════════════════"); + Log($"Session start — {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + } + + private static void EnsureDir() + { + if (!_initialized) + { + if (!Directory.Exists(LogDir)) + Directory.CreateDirectory(LogDir); + _initialized = true; + } + } + + private static void Rollover() + { + try + { + if (File.Exists(LogPath) && new FileInfo(LogPath).Length > MAX_SIZE) + { + string backup = LogPath + ".old"; + if (File.Exists(backup)) File.Delete(backup); + File.Move(LogPath, backup); + } + } + catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/Tier2MovementHelper.cs b/Plugins/RynthAi/Nav/Tier2MovementHelper.cs new file mode 100644 index 0000000..72b1c3b --- /dev/null +++ b/Plugins/RynthAi/Nav/Tier2MovementHelper.cs @@ -0,0 +1,942 @@ +using System; +using System.Diagnostics; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Security; + +namespace NexSuite.Plugins.RynthAi +{ + /// <summary> + /// Tier 2 movement: calls MovementManager::PerformMovement directly on the + /// player's CPhysicsObj. The client's own pathfinding handles interpolation, + /// heading, speed — producing smooth arcs instead of autorun + PD-controller + /// correction jitter. + /// + /// Pointer chain (all from acclient.exe decompilation + binary verification): + /// [SmartBox::smartbox] → SmartBox* + /// [SmartBox+0xF8] → CPhysicsObj* (player) + /// [player+0xC4] → MovementManager* + /// PerformMovement(__thiscall, const MovementStruct*) + /// + /// MovementTypes (from MovementStruct.type): + /// 6 = MoveToObject — approach a world object + /// 7 = MoveToPosition — walk/run to an (x,y,z) in a landblock cell + /// 8 = TurnToObject — face a world object + /// 9 = TurnToHeading — face a compass heading (degrees) + /// + /// All structs are stack-allocated in unmanaged memory, filled, passed to the + /// native function, then freed. No persistent allocations. + /// + /// Pattern scans (version-independent): + /// PerformMovement — anchored by its unique return-71 epilogue + /// CancelMoveTo — immediately follows PerformMovement (reads [ecx+4]) + /// Position vtable — found in CPhysicsObj::MoveToObject's stack init + /// MovParams vtable — found in MovementParameters constructor (writes speed=1.0) + /// </summary> + internal static class Tier2MovementHelper + { + // ═══════════════════════════════════════════════════════════════════════ + // MOVEMENT TYPE CONSTANTS + // ═══════════════════════════════════════════════════════════════════════ + + public const uint TYPE_MOVE_TO_OBJECT = 6; + public const uint TYPE_MOVE_TO_POSITION = 7; + public const uint TYPE_TURN_TO_OBJECT = 8; + public const uint TYPE_TURN_TO_HEADING = 9; + + // ═══════════════════════════════════════════════════════════════════════ + // STRUCT SIZES & OFFSETS + // ═══════════════════════════════════════════════════════════════════════ + + // ── SmartBox ────────────────────────────────────────────────────────── + private const int SB_PLAYER_ID = 0xF4; + private const int SB_PLAYER = 0xF8; + private const int SB_CMDINTERP = 0xB8; + + // ── CPhysicsObj ─────────────────────────────────────────────────────── + private const int PO_POSITION = 0x48; // Position (embedded, 72 bytes — starts at vtable) + private const int PO_MOVEMENT_MGR = 0xC4; // MovementManager* + + // ── MovementStruct (0x64 = 100 bytes) ──────────────────────────────── + private const int MS_SIZE = 0x64; + private const int MS_TYPE = 0x00; // uint MovementTypes::Type + private const int MS_MOTION = 0x04; // uint motion + private const int MS_OBJECT_ID = 0x08; // uint object_id + private const int MS_TOP_LEVEL_ID = 0x0C; // uint top_level_id + private const int MS_POS = 0x10; // Position (72 bytes, embedded) + private const int MS_RADIUS = 0x58; // float radius + private const int MS_HEIGHT = 0x5C; // float height + private const int MS_PARAMS = 0x60; // MovementParameters* (pointer) + + // ── Position (0x48 = 72 bytes, embedded inside MovementStruct) ─────── + // Relative to MS_POS: + // Frame layout: quaternion(16) → cache/matrix(36) → origin(12) + // (verified from binary: origin at Pos+0x3C, not Pos+0x18) + private const int POS_VTABLE = 0x00; // Position_vtbl* + private const int POS_OBJCELL_ID = 0x04; // uint32 landblock cell + private const int POS_QW = 0x08; // float Frame.qw (quaternion w) + private const int POS_QX = 0x0C; // float Frame.qx + private const int POS_QY = 0x10; // float Frame.qy + private const int POS_QZ = 0x14; // float Frame.qz + private const int POS_CACHE = 0x18; // float[9] (3×3 rotation matrix, 36 bytes) + private const int POS_ORIGIN_X = 0x3C; // float Frame.m_fOrigin.x + private const int POS_ORIGIN_Y = 0x40; // float Frame.m_fOrigin.y + private const int POS_ORIGIN_Z = 0x44; // float Frame.m_fOrigin.z + + // ── MovementParameters (0x2C = 44 bytes) ──────────────────────────── + private const int MP_SIZE = 0x2C; + private const int MP_VTABLE = 0x00; // MovementParameters_vtbl* + private const int MP_BITFIELD = 0x04; // uint flags + private const int MP_DIST_TO_OBJ = 0x08; // float distance_to_object + private const int MP_MIN_DIST = 0x0C; // float min_distance + private const int MP_HEADING = 0x10; // float desired_heading + private const int MP_SPEED = 0x14; // float speed + private const int MP_FAIL_DIST = 0x18; // float fail_distance + private const int MP_WR_THRESH = 0x1C; // float walk_run_threshhold + private const int MP_CONTEXT_ID = 0x20; // uint context_id + private const int MP_HOLD_KEY = 0x24; // int hold_key_to_apply + private const int MP_ACTION_STAMP = 0x28; // uint action_stamp + + // ── MovementParameters defaults (from acclient.exe statics) ────────── + private const uint MP_DEFAULT_BITFIELD = 0x0001EE1F; // 0x10 bit = always autorun speed + private const float MP_DEFAULT_DIST_OBJ = 0.6f; + private const float MP_DEFAULT_MIN_DIST = 0.0f; + private const float MP_DEFAULT_FAIL_DIST = float.MaxValue; + private const float MP_DEFAULT_WR_THRESH = 0.0f; // 0 = never walk, always run + private const float MP_DEFAULT_SPEED = 1.0f; + + // ═══════════════════════════════════════════════════════════════════════ + // NATIVE DELEGATES + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// MovementManager::PerformMovement(const MovementStruct*) + /// __thiscall — ECX = MovementManager*, stack arg = MovementStruct* + /// Returns 0 on success, non-zero error code on failure. + /// </summary> + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate uint DelPerformMovement(IntPtr thisPtr, IntPtr movementStruct); + + /// <summary> + /// MovementManager::CancelMoveTo(unsigned int err) + /// __thiscall — ECX = MovementManager*, stack arg = error code + /// Error 0 = cancelled by user. + /// </summary> + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void DelCancelMoveTo(IntPtr thisPtr, uint err); + + // ═══════════════════════════════════════════════════════════════════════ + // CACHED STATE + // ═══════════════════════════════════════════════════════════════════════ + + private static DelPerformMovement _performMovement; + private static DelCancelMoveTo _cancelMoveTo; + + private static IntPtr _smartboxStaticAddr; // Address of SmartBox::smartbox global + private static IntPtr _positionVtable; // Position::`vftable' address + private static IntPtr _movParamsVtable; // MovementParameters::`vftable' address + + private static bool _initialized; + private static Action<string> _log; + + public static bool IsInitialized => _initialized; + + // ═══════════════════════════════════════════════════════════════════════ + // INITIALIZATION (pattern scan) + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Scans acclient.exe at runtime for MovementManager functions and + /// struct vtable addresses. Call once at plugin startup, after + /// CombatActionHelper and MovementActionHelper have initialized. + /// + /// smartboxAddr: if non-zero, use this as SmartBox::smartbox static + /// address instead of pattern scanning (pass UB's SmartBox.smartbox + /// pointer address for guaranteed correctness). + /// </summary> + public static void Initialize(Action<string> chatLog = null, IntPtr smartboxAddr = default) + { + _log = chatLog; + + try + { + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Tier2 scan FAILED: acclient.exe not found"); + return; + } + + int textRva = 0x1000; + int textSize = Math.Min(imageSize - textRva, 0x400000); + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── 1. Find MovementManager::PerformMovement ───────────────── + // Unique epilogue: pop edi; mov eax, 71; pop esi; ret 4 + // Hex: 5F B8 47 00 00 00 5E C2 04 00 + byte[] pmEpilogue = { 0x5F, 0xB8, 0x47, 0x00, 0x00, 0x00, 0x5E, 0xC2, 0x04, 0x00 }; + int pmEpiOff = -1; + + // PerformMovement is in the MovementManager code region (~0x520000–0x530000) + // Narrow the search to avoid false positives in unrelated code. + for (int i = 0; i < text.Length - pmEpilogue.Length; i++) + { + if (!BytesMatch(text, i, pmEpilogue)) continue; + + // Verify: the function should start with push esi; push edi; mov esi, ecx + // (56 57 8B F1) preceded by CC/90/C3 padding. + int funcOff = FindFuncStartBefore(text, i, + new byte[] { 0x56, 0x57, 0x8B, 0xF1 }); + if (funcOff >= 0) + { + // Extra verify: function reads [esi+0x08] (physics_obj) then pushes 1 + // Pattern at funcOff+4: 8B 4E 08 6A 01 + if (funcOff + 9 < text.Length && + text[funcOff + 4] == 0x8B && + text[funcOff + 5] == 0x4E && + text[funcOff + 6] == 0x08 && + text[funcOff + 7] == 0x6A && + text[funcOff + 8] == 0x01) + { + pmEpiOff = funcOff; + break; + } + } + } + + if (pmEpiOff < 0) + { + Log("Tier2 scan FAILED: PerformMovement not found"); + return; + } + + int pmVA = textBaseVA + pmEpiOff; + Log($"PerformMovement at 0x{pmVA:X8}"); + _performMovement = (DelPerformMovement)Marshal.GetDelegateForFunctionPointer( + new IntPtr(pmVA), typeof(DelPerformMovement)); + + // ── 2. Find CancelMoveTo ───────────────────────────────────── + // Immediately after PerformMovement's ret — small function: + // 8B 49 04 mov ecx, [ecx+4] (moveto_manager at MM+0x04) + // 85 C9 test ecx, ecx + // 74 XX jz skip + // E9 XX jmp MoveToManager::CancelMoveTo + // C2 04 00 ret 4 + // Search forward from the epilogue for this pattern. + int cancelOff = -1; + int searchFrom = pmEpiOff + pmEpilogue.Length; + // Search up to 128 bytes past the epilogue — the switch jump table + // data sits between PerformMovement's ret and CancelMoveTo's start. + for (int i = searchFrom; i < Math.Min(searchFrom + 128, text.Length - 8); i++) + { + if (text[i] == 0x8B && text[i + 1] == 0x49 && text[i + 2] == 0x04 && + text[i + 3] == 0x85 && text[i + 4] == 0xC9 && text[i + 5] == 0x74) + { + cancelOff = i; + break; + } + } + + if (cancelOff < 0) + { + Log("Tier2 scan WARNING: CancelMoveTo not found (non-fatal)"); + } + else + { + int cancelVA = textBaseVA + cancelOff; + Log($"CancelMoveTo at 0x{cancelVA:X8}"); + _cancelMoveTo = (DelCancelMoveTo)Marshal.GetDelegateForFunctionPointer( + new IntPtr(cancelVA), typeof(DelCancelMoveTo)); + } + + // ── 3. Find SmartBox::smartbox static address ──────────────── + if (smartboxAddr != IntPtr.Zero) + { + // Caller provided the address (e.g. from UB's AcClient.SmartBox) + _smartboxStaticAddr = smartboxAddr; + Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (provided by caller)"); + } + else + { + // Fall back to pattern scan + _smartboxStaticAddr = FindSmartBoxStatic(text, textBaseVA, baseAddr.ToInt32()); + if (_smartboxStaticAddr == IntPtr.Zero) + { + Log("Tier2 scan FAILED: SmartBox::smartbox static not found"); + return; + } + Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (pattern scan)"); + } + + // ── 4. Find Position vtable ────────────────────────────────── + // CPhysicsObj movement functions init a stack Position with: + // C7 44 24 XX [vtable] ← .rdata pointer + // C7 44 24 XX 00 00 00 00 ← objcell_id = 0 + // C7 44 24 XX 00 00 80 3F ← qw = 1.0f + // Search callers of PerformMovement for this pattern. + _positionVtable = FindPositionVtable(text, textBaseVA, pmVA); + if (_positionVtable == IntPtr.Zero) + { + Log("Tier2 scan FAILED: Position vtable not found"); + return; + } + Log($"Position vtable at 0x{_positionVtable.ToInt32():X8}"); + + // ── 5. Find MovementParameters vtable ──────────────────────── + // MovementParameters constructor writes vtable then speed = 1.0: + // C7 00 [vtable] ← mov [eax], vtable + // ... + // C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f (speed) + _movParamsVtable = FindMovParamsVtable(text, textBaseVA); + if (_movParamsVtable == IntPtr.Zero) + { + Log("Tier2 scan FAILED: MovementParameters vtable not found"); + return; + } + Log($"MovParams vtable at 0x{_movParamsVtable.ToInt32():X8}"); + + _initialized = true; + Log("Tier2MovementHelper initialized — all addresses found via pattern scan"); + Tier2Log.StartSession(); + Tier2Log.Log($"PerformMovement=0x{pmVA:X8} SmartBox=0x{_smartboxStaticAddr.ToInt32():X8} " + + $"PosVT=0x{_positionVtable.ToInt32():X8} MpVT=0x{_movParamsVtable.ToInt32():X8}"); + } + catch (Exception ex) + { + _initialized = false; + Log("Tier2 init FAILED: " + ex.Message); + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // PUBLIC API + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Tells the client's physics engine to walk/run to a world position. + /// The client handles all interpolation, heading changes, and speed + /// internally — no frame-by-frame steering required. + /// + /// Parameters use AC's internal coordinate system: + /// objcell_id — landblock cell (e.g. 0xABCD0012 for outdoor cell) + /// x, y, z — local position within the cell (yards) + /// speed — movement speed multiplier (1.0 = normal) + /// distTo — stop this far from the target (yards, default 0.6) + /// + /// Returns 0 on success, non-zero error code on failure. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static uint MoveToPosition( + uint objcell_id, float x, float y, float z, + float speed = 1.0f, float distTo = 0.5f, float walkRunThreshold = 15f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + LogPointerChain(); // once — logs the full chain to file + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) + { + Tier2Log.Log("MoveToPosition: MovementManager is NULL — aborting"); + return uint.MaxValue; + } + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + // ── MovementParameters ──────────────────────────────────────── + WriteMovementParams(mpPtr, speed, distTo, 0f, walkRunThreshold); + + // ── MovementStruct ──────────────────────────────────────────── + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_POSITION); + WritePosition(msPtr + MS_POS, objcell_id, x, y, z, 1f, 0f, 0f, 0f); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + Tier2Log.Log($"MoveToPosition CALL: mm=0x{mm.ToInt32():X8} cell=0x{objcell_id:X8} " + + $"x={x:F2} y={y:F2} z={z:F2} speed={speed} distTo={distTo} wrTh={walkRunThreshold}"); + + uint result = _performMovement(mm, msPtr); + + Tier2Log.Log($"MoveToPosition RETURNED: {result}"); + return result; + } + catch (Exception ex) + { + Tier2Log.Log($"MoveToPosition EXCEPTION: {ex}"); + Log("MoveToPosition failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Tells the client's physics engine to approach a world object by ID. + /// The client tracks the object's position and adjusts the path. + /// </summary> + public static uint MoveToObject( + uint objectId, float speed = 1.0f, float distTo = 0.5f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return uint.MaxValue; + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + WriteMovementParams(mpPtr, speed, distTo, 0f); + + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_OBJECT); + Marshal.WriteInt32(msPtr + MS_OBJECT_ID, (int)objectId); + WriteIdentityPosition(msPtr + MS_POS); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + return _performMovement(mm, msPtr); + } + catch (Exception ex) + { + Log("MoveToObject failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Tells the client to turn the player to face a compass heading. + /// heading: 0 = North, 90 = East, 180 = South, 270 = West (degrees). + /// </summary> + public static uint TurnToHeading(float heading, float speed = 1.0f) + { + if (!_initialized || _performMovement == null) return uint.MaxValue; + + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return uint.MaxValue; + + IntPtr msPtr = IntPtr.Zero; + IntPtr mpPtr = IntPtr.Zero; + try + { + msPtr = Marshal.AllocHGlobal(MS_SIZE); + mpPtr = Marshal.AllocHGlobal(MP_SIZE); + ZeroMemory(msPtr, MS_SIZE); + ZeroMemory(mpPtr, MP_SIZE); + + // For TurnToHeading, the heading goes in MovementParameters.desired_heading + WriteMovementParams(mpPtr, speed, 0f, heading); + + Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_TURN_TO_HEADING); + WriteIdentityPosition(msPtr + MS_POS); + Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr); + + return _performMovement(mm, msPtr); + } + catch (Exception ex) + { + Log("TurnToHeading failed: " + ex.Message); + return uint.MaxValue; + } + finally + { + if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr); + if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr); + } + } + + /// <summary> + /// Cancels any in-progress MoveToPosition / MoveToObject / TurnToHeading. + /// Safe to call if nothing is in progress. + /// </summary> + public static void CancelMoveTo() + { + if (!_initialized || _cancelMoveTo == null) return; + try + { + IntPtr mm = GetMovementManager(); + if (mm != IntPtr.Zero) + _cancelMoveTo(mm, 0); + } + catch (Exception ex) + { + Log("CancelMoveTo failed: " + ex.Message); + } + } + + /// <summary> + /// Returns true if the player has a MovementManager and its MoveToManager + /// is non-null (meaning some Tier 2 movement is potentially active). + /// </summary> + public static bool IsMovingTo() + { + try + { + IntPtr mm = GetMovementManager(); + if (mm == IntPtr.Zero) return false; + // MoveToManager* at MovementManager+0x04 + IntPtr mtm = Marshal.ReadIntPtr(mm + 0x04); + return mtm != IntPtr.Zero; + } + catch { return false; } + } + + /// <summary> + /// Reads the player's current internal Position struct. + /// Uses Marshal.ReadInt32 + BitConverter (safe) instead of unsafe pointers + /// to avoid SEH crashes that bypass managed try/catch. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static bool GetPlayerPosition( + out uint objcell_id, out float x, out float y, out float z) + { + objcell_id = 0; x = y = z = 0; + try + { + IntPtr player = GetPlayerPtr(); + if (player == IntPtr.Zero) return false; + + IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION); + objcell_id = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID); + x = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X)); + y = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y)); + z = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z)); + return true; + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerPos EXCEPTION: {ex.Message}"); + return false; + } + } + + /// <summary>Reinterpret int32 bits as float (safe alternative to unsafe pointer cast).</summary> + private static float IntToFloat(int bits) + { + byte[] b = BitConverter.GetBytes(bits); + return BitConverter.ToSingle(b, 0); + } + + /// <summary> + /// Returns the player's current landblock cell ID, or 0 if unavailable. + /// HPCSE attribute required: Marshal.ReadInt32 is unsafe under the hood — + /// AccessViolationException is a Corrupted State Exception on .NET 4.8 + /// and bypasses normal try/catch without this attribute. + /// </summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static uint GetPlayerCellId() + { + try + { + IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr); + if (sb == IntPtr.Zero) return 0; + + IntPtr player = Marshal.ReadIntPtr(sb + SB_PLAYER); + if (player == IntPtr.Zero) return 0; + + return (uint)Marshal.ReadInt32(new IntPtr( + player.ToInt32() + PO_POSITION + POS_OBJCELL_ID)); + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerCellId CRASHED: {ex.GetType().Name}: {ex.Message}"); + return 0; + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // POINTER CHAIN HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetSmartBox() + { + try + { + if (_smartboxStaticAddr == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(_smartboxStaticAddr); + } + catch (Exception ex) + { + Tier2Log.Log($"GetSmartBox CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetPlayerPtr() + { + try + { + IntPtr sb = GetSmartBox(); + if (sb == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(sb + SB_PLAYER); + } + catch (Exception ex) + { + Tier2Log.Log($"GetPlayerPtr CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + [HandleProcessCorruptedStateExceptions, SecurityCritical] + private static IntPtr GetMovementManager() + { + try + { + IntPtr player = GetPlayerPtr(); + if (player == IntPtr.Zero) return IntPtr.Zero; + return Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR); + } + catch (Exception ex) + { + Tier2Log.Log($"GetMovementManager CRASHED: {ex.GetType().Name}"); + return IntPtr.Zero; + } + } + + /// <summary> + /// Logs the full pointer chain once. Call before first movement. + /// </summary> + private static bool _chainLogged; + [HandleProcessCorruptedStateExceptions, SecurityCritical] + public static void LogPointerChain() + { + if (_chainLogged) return; + _chainLogged = true; + try + { + IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr); + IntPtr player = (sb != IntPtr.Zero) ? Marshal.ReadIntPtr(sb + SB_PLAYER) : IntPtr.Zero; + IntPtr mm = (player != IntPtr.Zero) ? Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR) : IntPtr.Zero; + uint cell = 0; float px = 0, py = 0, pz = 0; + if (player != IntPtr.Zero) + { + IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION); + cell = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID); + px = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X)); + py = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y)); + pz = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z)); + } + Tier2Log.Log($"CHAIN: [0x{_smartboxStaticAddr.ToInt32():X8}]→sb=0x{sb.ToInt32():X8} " + + $"[sb+0x{SB_PLAYER:X2}]→player=0x{player.ToInt32():X8} " + + $"[player+0x{PO_MOVEMENT_MGR:X2}]→mm=0x{mm.ToInt32():X8}"); + Tier2Log.Log($"CHAIN: playerPos cell=0x{cell:X8} origin=({px:F2},{py:F2},{pz:F2})"); + } + catch (Exception ex) + { + Tier2Log.Log($"CHAIN FAILED: {ex.GetType().Name}: {ex.Message}"); + _chainLogged = false; // retry next time + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // STRUCT WRITERS + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Fills a 44-byte MovementParameters at the given unmanaged address. + /// walkRunThreshold: distance in yards at which to switch from run to walk. + /// 0 = always run. Default AC value is 15.0. + /// </summary> + private static void WriteMovementParams( + IntPtr ptr, float speed, float distTo, float heading, float walkRunThreshold = 15f) + { + Marshal.WriteIntPtr(ptr + MP_VTABLE, _movParamsVtable); + WriteInt(ptr + MP_BITFIELD, MP_DEFAULT_BITFIELD); + WriteFloat(ptr + MP_DIST_TO_OBJ, distTo); + WriteFloat(ptr + MP_MIN_DIST, MP_DEFAULT_MIN_DIST); + WriteFloat(ptr + MP_HEADING, heading); + WriteFloat(ptr + MP_SPEED, speed); + WriteFloat(ptr + MP_FAIL_DIST, MP_DEFAULT_FAIL_DIST); + WriteFloat(ptr + MP_WR_THRESH, walkRunThreshold); + WriteInt(ptr + MP_CONTEXT_ID, 0); + WriteInt(ptr + MP_HOLD_KEY, 0); // 0 = let walk_run_threshold decide + WriteInt(ptr + MP_ACTION_STAMP, 0); + } + + /// <summary> + /// Fills a 72-byte Position at the given unmanaged address. + /// Computes the Frame cache (3×3 rotation matrix from quaternion). + /// </summary> + private static void WritePosition( + IntPtr ptr, uint objcell_id, + float x, float y, float z, + float qw, float qx, float qy, float qz) + { + Marshal.WriteIntPtr(ptr + POS_VTABLE, _positionVtable); + WriteInt(ptr + POS_OBJCELL_ID, objcell_id); + WriteFloat(ptr + POS_QW, qw); + WriteFloat(ptr + POS_QX, qx); + WriteFloat(ptr + POS_QY, qy); + WriteFloat(ptr + POS_QZ, qz); + WriteFloat(ptr + POS_ORIGIN_X, x); + WriteFloat(ptr + POS_ORIGIN_Y, y); + WriteFloat(ptr + POS_ORIGIN_Z, z); + + // Frame::cache — quaternion → 3×3 rotation matrix (row-major) + float xx = qx * qx, yy = qy * qy, zz = qz * qz; + float xy = qx * qy, xz = qx * qz, yz = qy * qz; + float wx = qw * qx, wy = qw * qy, wz = qw * qz; + + IntPtr c = ptr + POS_CACHE; + WriteFloat(c + 0x00, 1f - 2f * (yy + zz)); // m00 + WriteFloat(c + 0x04, 2f * (xy - wz)); // m01 + WriteFloat(c + 0x08, 2f * (xz + wy)); // m02 + WriteFloat(c + 0x0C, 2f * (xy + wz)); // m10 + WriteFloat(c + 0x10, 1f - 2f * (xx + zz)); // m11 + WriteFloat(c + 0x14, 2f * (yz - wx)); // m12 + WriteFloat(c + 0x18, 2f * (xz - wy)); // m20 + WriteFloat(c + 0x1C, 2f * (yz + wx)); // m21 + WriteFloat(c + 0x20, 1f - 2f * (xx + yy)); // m22 + } + + /// <summary> + /// Writes an identity Position (objcell_id=0, identity quaternion). + /// </summary> + private static void WriteIdentityPosition(IntPtr ptr) + { + WritePosition(ptr, 0, 0f, 0f, 0f, 1f, 0f, 0f, 0f); + } + + // ═══════════════════════════════════════════════════════════════════════ + // PATTERN SCAN HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + /// <summary> + /// Finds SmartBox::smartbox by looking for the Cleanup pattern: + /// A1 [addr] ; load smartbox + /// 85 C0 ; test eax, eax + /// 74 XX ; jz skip + /// ... ; vtable destructor call + /// C7 05 [addr] 00 00 00 00 ; store 0 to smartbox + /// C3 ; ret + /// </summary> + private static IntPtr FindSmartBoxStatic(byte[] text, int textBaseVA, int imageBase) + { + int dataLo = imageBase + 0x400000; // rough .data start + int dataHi = imageBase + 0x510000; // rough .data end + + // Search for: C7 05 [addr] 00 00 00 00 C3 + // where [addr] is also loaded with A1 [addr] within 30 bytes before + for (int i = 0; i < text.Length - 12; i++) + { + if (text[i] != 0xC7 || text[i + 1] != 0x05) continue; + int addr = BitConverter.ToInt32(text, i + 2); + if (addr < dataLo || addr > dataHi) continue; + // Check imm32 = 0 and next byte = C3 (ret) + if (BitConverter.ToInt32(text, i + 6) != 0) continue; + if (text[i + 10] != 0xC3) continue; + + // Verify: A1 [same addr] appears within 40 bytes before + byte[] loadPat = new byte[5]; + loadPat[0] = 0xA1; + BitConverter.GetBytes(addr).CopyTo(loadPat, 1); + for (int back = 5; back < 40; back++) + { + int j = i - back; + if (j < 0) break; + if (BytesMatch(text, j, loadPat)) + { + // Also verify: 85 C0 (test eax,eax) appears after the load + for (int k = j + 5; k < j + 10 && k < text.Length - 1; k++) + { + if (text[k] == 0x85 && text[k + 1] == 0xC0) + { + // Extra verify: the load is near a vtable dtor call + // SmartBox::Cleanup does: lea ecx,[eax+4]; mov eax,[ecx]; + // push 1; call [eax] — the push 1 is the destructor flag, + // distinguishing this from other cleanup patterns. + bool hasDtorCall = false; + for (int m = k; m < i - 2 && m < text.Length - 3; m++) + { + if (text[m] == 0x6A && text[m + 1] == 0x01 && + text[m + 2] == 0xFF && text[m + 3] == 0x10) + { + hasDtorCall = true; // push 1; call [eax] + break; + } + } + if (hasDtorCall) + return new IntPtr(addr); + } + } + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Finds Position::`vftable' by scanning PerformMovement callers + /// for the stack-init pattern that writes a .rdata pointer followed + /// by objcell_id=0 then qw=1.0f. + /// </summary> + private static IntPtr FindPositionVtable(byte[] text, int textBaseVA, int pmVA) + { + int rdataLo = textBaseVA + 0x390000; // .rdata region + int rdataHi = rdataLo + 0x80000; + + // Find callers of PerformMovement (E8 relative calls) + for (int i = 0; i < text.Length - 5; i++) + { + if (text[i] != 0xE8) continue; + int rel = BitConverter.ToInt32(text, i + 1); + int target = textBaseVA + i + 5 + rel; + if (target != pmVA) continue; + + // Found a caller. Search backwards up to 300 bytes for: + // C7 44 24 XX [rdata_addr] (Position vtable) + // C7 44 24 YY 00 00 00 00 (objcell_id = 0) + // C7 44 24 ZZ 00 00 80 3F (qw = 1.0f) + int searchStart = Math.Max(0, i - 300); + for (int j = searchStart; j < i - 8; j++) + { + // Look for C7 44 24 XX followed by .rdata address + if (text[j] != 0xC7 || text[j + 1] != 0x44 || text[j + 2] != 0x24) + continue; + int val = BitConverter.ToInt32(text, j + 4); + if (val < rdataLo || val > rdataHi) continue; + + // Check: within 16 bytes, there should be C7 44 24 XX 00 00 80 3F (qw=1.0) + for (int k = j + 8; k < Math.Min(j + 40, i); k++) + { + if (text[k] == 0xC7 && text[k + 1] == 0x44 && text[k + 2] == 0x24 && + text[k + 4] == 0x00 && text[k + 5] == 0x00 && + text[k + 6] == 0x80 && text[k + 7] == 0x3F) + { + return new IntPtr(val); + } + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Finds MovementParameters::`vftable' by searching for the constructor + /// that writes a .rdata vtable to [eax+0] then speed=1.0 to [eax+0x14]: + /// C7 00 [vtable] ← mov [eax], vtable + /// ... (field inits) ... + /// C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f + /// </summary> + private static IntPtr FindMovParamsVtable(byte[] text, int textBaseVA) + { + int rdataLo = textBaseVA + 0x390000; + int rdataHi = rdataLo + 0x80000; + + // Search for: C7 40 14 00 00 80 3F (speed = 1.0f at +0x14) + byte[] speedPat = { 0xC7, 0x40, 0x14, 0x00, 0x00, 0x80, 0x3F }; + for (int i = 0; i < text.Length - speedPat.Length; i++) + { + if (!BytesMatch(text, i, speedPat)) continue; + + // Walk backwards up to 40 bytes for C7 00 [rdata_addr] + for (int back = 4; back < 40; back++) + { + int j = i - back; + if (j < 0) break; + if (text[j] == 0xC7 && text[j + 1] == 0x00) + { + int val = BitConverter.ToInt32(text, j + 2); + if (val >= rdataLo && val <= rdataHi) + return new IntPtr(val); + } + } + } + return IntPtr.Zero; + } + + /// <summary> + /// Walks backwards from an offset to find a function start. + /// The function must begin with the given prologue bytes, preceded + /// by CC/90/C3 alignment padding. + /// </summary> + private static int FindFuncStartBefore(byte[] data, int fromOffset, byte[] prologue) + { + for (int back = 1; back < 400; back++) + { + int pos = fromOffset - back; + if (pos < 1 || pos + prologue.Length > data.Length) continue; + + if (!BytesMatch(data, pos, prologue)) continue; + + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + return -1; + } + + // ═══════════════════════════════════════════════════════════════════════ + // LOW-LEVEL HELPERS + // ═══════════════════════════════════════════════════════════════════════ + + private static bool BytesMatch(byte[] data, int offset, byte[] pattern) + { + if (offset + pattern.Length > data.Length) return false; + for (int i = 0; i < pattern.Length; i++) + if (data[offset + i] != pattern[i]) return false; + return true; + } + + private static unsafe void WriteFloat(IntPtr addr, float value) + { + *(float*)addr.ToPointer() = value; + } + + private static unsafe float ReadFloat(IntPtr addr) + { + return *(float*)addr.ToPointer(); + } + + private static void WriteInt(IntPtr addr, uint value) + { + Marshal.WriteInt32(addr, (int)value); + } + + private static void ZeroMemory(IntPtr addr, int size) + { + byte[] zeros = new byte[size]; + Marshal.Copy(zeros, 0, addr, size); + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Nav/VTankNavParser.cs b/Plugins/RynthAi/Nav/VTankNavParser.cs new file mode 100644 index 0000000..61e9793 --- /dev/null +++ b/Plugins/RynthAi/Nav/VTankNavParser.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Globalization; + +namespace NexSuite.Plugins.RynthAi +{ + public enum NavRouteType + { + Circular = 1, + Linear = 2, + Follow = 3, + Once = 4 + } + + public enum NavPointType + { + Point = 0, + Recall = 2, + Pause = 3, + Chat = 4, + PortalNPC = 6 + } + + public 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; } + public string TargetName { get; set; } + public int ObjectClass { get; set; } + public bool IsTie { get; set; } + + // PortalNPC extra coordinate blocks (exit/destination coords) + public double PortalExitNS { get; set; } + public double PortalExitEW { get; set; } + public double PortalExitZ { get; set; } + public double PortalLandNS { get; set; } + public double PortalLandEW { get; set; } + public double PortalLandZ { get; set; } + + public override string ToString() + { + switch (Type) + { + // UI display converted to exact 3-decimal precision + case NavPointType.Point: return $"[Point] {NS:F3}, {EW:F3}"; + case NavPointType.Recall: + { + string spellName = SpellDatabase.GetSpellName(SpellId); + return $"[Recall] {spellName} ({SpellId})"; + } + case NavPointType.Pause: return $"[Pause] {PauseTimeMs / 1000.0}s"; + case NavPointType.Chat: return $"[Chat] {ChatCommand}"; + case NavPointType.PortalNPC: return $"[Portal] {TargetName}"; + default: return $"[Unknown] {Type}"; + } + } + } + + public class VTankNavParser + { + public NavRouteType RouteType { get; set; } + public List<NavPoint> Points { get; set; } = new List<NavPoint>(); + + public static VTankNavParser Load(string filePath) + { + var route = new VTankNavParser(); + string[] lines = File.ReadAllLines(filePath); + + if (lines.Length < 3) return route; + + if (!lines[0].Contains("uTank2 NAV 1.2")) + throw new Exception("Invalid or unsupported VTank .nav file format."); + + route.RouteType = (NavRouteType)int.Parse(lines[1]); + int pointCount = int.Parse(lines[2]); + + int idx = 3; + for (int i = 0; i < pointCount && idx < lines.Length; i++) + { + var pt = new NavPoint(); + pt.Type = (NavPointType)int.Parse(lines[idx++]); + + pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // First coord is EW + pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // Second coord is NS + pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + + idx++; // Skip the 0 spacer line + + switch (pt.Type) + { + case NavPointType.Point: break; + case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break; + case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break; + case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break; + case NavPointType.PortalNPC: + pt.TargetName = lines[idx++]; + pt.ObjectClass = int.Parse(lines[idx++]); + pt.IsTie = bool.Parse(lines[idx++]); + // Two extra coordinate blocks (exit + landing) - also EW/NS/Z format + pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + break; + } + + route.Points.Add(pt); + } + + return route; + } + + public void Save(string filePath) + { + using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, false)) + { + writer.WriteLine("uTank2 NAV 1.2"); + writer.WriteLine((int)RouteType); + writer.WriteLine(Points.Count); + + foreach (var pt in Points) + { + writer.WriteLine((int)pt.Type); + writer.WriteLine(pt.EW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.NS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.Z.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + + switch (pt.Type) + { + case NavPointType.Recall: writer.WriteLine(pt.SpellId); break; + case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break; + case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break; + case NavPointType.PortalNPC: + writer.WriteLine(pt.TargetName); + writer.WriteLine(pt.ObjectClass); + writer.WriteLine(pt.IsTie.ToString()); + writer.WriteLine(pt.PortalExitEW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitNS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitZ.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + writer.WriteLine(pt.PortalLandEW.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandNS.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandZ.ToString(System.Globalization.CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + break; + } + } + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/PluginCore.cs b/Plugins/RynthAi/PluginCore.cs new file mode 100644 index 0000000..6daba04 --- /dev/null +++ b/Plugins/RynthAi/PluginCore.cs @@ -0,0 +1,1115 @@ +using System; +using System.IO; +using System.Reflection; +using System.Collections.Generic; +using System.Numerics; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using UtilityBelt.Service; +using ImGuiNET; +using System.IO.Ports; +using UtilityBelt.Service.Lib.Settings; +using RynthAi.Meta; +using System.Runtime.InteropServices; +using System.Diagnostics; +using NexSuite.Plugins.RynthAi.Utility; +using AcClient; + +namespace NexSuite.Plugins.RynthAi +{ + [FriendlyName("RynthAi")] + public class PluginCore : PluginBase + { + // --- PRIVATE MANAGERS & UI --- + private RynthAiUI _ui; + private CombatManager _combatManager; + private NavigationManager _navigationManager; + private UISettings _settings; + private SpellManager _spellManager; + private LootManager _lootManager; + private BuffManager _buffManager; + private MetaManager _metaManager; + private MissileCraftingManager _missileCraftingManager; + private FellowshipTracker _fellowshipTracker; + private UtilityBelt.Service.Views.Hud _mainHud; + private BackgroundFpsUnlocker _fpsUnlocker; + + private string _settingsPath; + private CommandProcessor _commandProcessor; + + // --- PUBLIC FOLDERS (Exposed for CommandProcessor) --- + public string NavFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + public string LootFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LootProfiles"; + public string MetaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\MetaProfiles"; + public string LuaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LuaScripts"; + public string AssemblyDirectory => System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + + // --- EXPOSED DECAL HOOKS & UI (For CommandProcessor) --- + public RynthAiUI UI => _ui; + + // These create safe, public doorways for your CommandProcessor to access Decal + public Decal.Adapter.Wrappers.PluginHost PluginHost => base.Host; + public Decal.Adapter.CoreManager PluginCoreManager => base.Core; + + public void ToggleUI() + { + if (_mainHud != null) _mainHud.Visible = !_mainHud.Visible; + } + + //FPS Throttling System + private Stopwatch _frameTimer = Stopwatch.StartNew(); + private DateTime _nextLuaTick = DateTime.Now; + + + + // --- COMBAT & VITAL TRACKING --- + private Dictionary<int, float> healthRatioTracker = new Dictionary<int, float>(); + private Dictionary<int, int> maxHealthTracker = new Dictionary<int, int>(); + private Dictionary<string, string> monsterWeaknesses = new Dictionary<string, string>(); + + + private DateTime lastRequestTime = DateTime.MinValue; + private const double RETRY_INTERVAL_SEC = 0.75; + private const int MAX_RETRIES = 5; + + // --- STATE TRACKING --- + + public RynthAi.Raycasting.MainLogic Raycast { get; private set; } + + // LUA + private LuaManager _luaManager; + // Native Jumper + private RynthJumper _jumper; + + // ... (Your protected override void Startup() method starts here) ... + protected override void Startup() + { + try + { + // 1. Initialize Global Folders + if (!System.IO.Directory.Exists(NavFolder)) System.IO.Directory.CreateDirectory(NavFolder); + if (!System.IO.Directory.Exists(LootFolder)) System.IO.Directory.CreateDirectory(LootFolder); + if (!System.IO.Directory.Exists(MetaFolder)) System.IO.Directory.CreateDirectory(MetaFolder); + if (!System.IO.Directory.Exists(LuaFolder)) System.IO.Directory.CreateDirectory(LuaFolder); + + // 2. Load Databases + LoadWeaknesses(); + + // Path to the spell dump + string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + string spellDumpPath = System.IO.Path.Combine(dllPath, "Combat", "Vtank spelldump.txt"); + + + // 3. Subscribe to Core Events + Core.ChatBoxMessage += OnChatBoxMessage; + Core.RenderFrame += OnRenderFrame; + + // Wait for server login to finish before initializing character-specific data + Core.CharacterFilter.LoginComplete += CharacterFilter_LoginComplete; + + // Hook command line and server traffic + CommandLineText += OnChatCommand; + Core.EchoFilter.ServerDispatch += OnServerDispatch; + + System.Diagnostics.Debug.WriteLine("[RynthAi] Startup Complete."); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine("[RynthAi Startup Error] " + ex.Message); + } + } + + protected override void Shutdown() + { + try + { + SaveSettings(); + + // Safely dispose of the D3D graphics using the new RouteTab + if (_ui != null && _ui.RouteTab != null) + { + _ui.RouteTab.DisposeRouteGraphics(); + } + + if (_mainHud != null) _mainHud.Dispose(); + + // --- UNHOOK EVENTS --- + Core.RenderFrame -= OnRenderFrame; + Core.ChatBoxMessage -= OnChatBoxMessage; + Core.EchoFilter.ServerDispatch -= OnServerDispatch; + CommandLineText -= OnChatCommand; + Core.CharacterFilter.LoginComplete -= CharacterFilter_LoginComplete; + + // --- DISPOSE MANAGERS --- + if (_buffManager != null) _buffManager.Dispose(); + if (_combatManager != null) _combatManager.Dispose(); + if (_fellowshipTracker != null) _fellowshipTracker.Dispose(); + if (_navigationManager != null) _navigationManager.Stop(); + if (_luaManager != null) _luaManager.Dispose(); + if (Raycast != null) Raycast.Dispose(); + + + } + catch (Exception ex) + { + // Try to print to chat, but if the Host is already destroyed, just swallow it gracefully + try { Host.Actions.AddChatText($"[RynthAi Shutdown Error] {ex.Message}", 1); } catch { } + } + _fpsUnlocker?.Dispose(); + } + + private void LoadWeaknesses() + { + // Embedded fallback data — used if monsters.json is missing + var embedded = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) + { + { "Olthoi", "Cold" }, { "Tusker", "Fire" }, { "Lugian", "Lightning" }, + { "Drudge", "Fire" }, { "Skeleton", "Fire" }, { "Gromnie", "Acid" }, + { "Reedshark", "Fire" }, { "Armoredillo", "Lightning" }, { "Banderling", "Fire" }, + { "Bunny", "Fire" }, { "Carenzi", "Fire" }, { "Dire Wolf", "Fire" }, + { "Doll", "Fire" }, { "Eater", "Lightning" }, { "Golem", "Acid" }, + { "Grievver", "Cold" }, { "Lich", "Fire" }, { "Matredien", "Lightning" }, + { "Mimic", "Fire" }, { "Mite", "Fire" }, { "Monouga", "Fire" }, + { "Mosswart", "Fire" }, { "Mu-miyah", "Fire" }, { "Niffis", "Lightning" }, + { "Phantasm", "Fire" }, { "Rat", "Fire" }, { "Remoran", "Fire" }, + { "Ruschk", "Fire" }, { "Sclavus", "Cold" }, { "Shreth", "Fire" }, + { "Teth", "Lightning" }, { "Thrass", "Fire" }, { "Ursuin", "Fire" }, + { "Viamontian", "Lightning" }, { "Virindi", "Lightning" }, { "Wasp", "Fire" }, + { "Wight", "Fire" }, { "Zharalim", "Lightning" }, { "Impy", "Lightning" }, + }; + + // Start with embedded data + foreach (var kvp in embedded) monsterWeaknesses[kvp.Key] = kvp.Value; + + // Normalize map for shorthand → spell element names + var normalizeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) + { + { "Bludge", "Bludgeon" }, { "Bludgeon", "Bludgeon" }, + { "Pierce", "Pierce" }, { "Slash", "Slash" }, + { "Fire", "Fire" }, { "Cold", "Cold" }, + { "Lightning", "Lightning" }, { "Acid", "Acid" }, + { "Light", "Fire" }, { "Nether", "Nether" }, + }; + + try + { + string basePath = @"C:\Games\DecalPlugins\NexSuite\RynthAi"; + string path = System.IO.Path.Combine(basePath, "monsters.json"); + + if (System.IO.File.Exists(path)) + { + string content = System.IO.File.ReadAllText(path); + var lines = content.Split(new[] { ',', '{', '}', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + foreach (var line in lines) + { + var parts = line.Split(':'); + if (parts.Length == 2) + { + string name = parts[0].Trim().Trim('"'); + string rawWeakness = parts[1].Trim().Trim('"'); + + if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(rawWeakness)) continue; + + // Extract the MAGIC element: last entry in "Physical / Magic" format + // e.g., "Bludge / Pierce / Cold" → "Cold" + // e.g., "Slash / Fire" → "Fire" + string[] elements = rawWeakness.Split('/'); + string magicElement = elements[elements.Length - 1].Trim(); + + // Skip "(Varies)" entries + if (magicElement.Contains("Varies")) continue; + + // Normalize the element name + string normalized; + if (normalizeMap.TryGetValue(magicElement, out normalized)) + monsterWeaknesses[name] = normalized; + else + monsterWeaknesses[name] = magicElement; // Use as-is if unknown + } + } + } + } + catch { } + } + + private void CharacterFilter_LoginComplete(object sender, EventArgs e) + { + try + { + // --- 1. Load Spell Database with In-Game Debugging --- + string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + string spellDumpPath = System.IO.Path.Combine(dllPath, "Combat", "Vtank spelldump.txt"); + + // This will now print the "Raw Line" debug messages to your AC chat + SpellDatabase.Load(Host); + + // --- 2. Get Character & Server Name safely --- + string serverName = Core.CharacterFilter.Server; + string charName = Core.CharacterFilter.Name; + + if (string.IsNullOrEmpty(serverName)) serverName = "UnknownServer"; + if (string.IsNullOrEmpty(charName)) charName = "UnknownCharacter"; + + // --- 3. Build CUSTOM dynamic paths --- + string basePath = @"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles"; + string charFolder = System.IO.Path.Combine(basePath, serverName, charName); + + _settingsPath = System.IO.Path.Combine(charFolder, "settings.json"); + if (!System.IO.Directory.Exists(charFolder)) System.IO.Directory.CreateDirectory(charFolder); + + // --- 4. Load settings --- + LoadSettings(); + + // --- 5. Initialize Core Managers --- + _spellManager = new SpellManager(CoreManager.Current); + _buffManager = new BuffManager(CoreManager.Current, _settings, _spellManager); + _buffManager.SetTimerPath(charFolder); + _combatManager = new CombatManager(Core, _settings, Host, _spellManager); + _combatManager.SetMonsterWeaknesses(monsterWeaknesses); + _combatManager.InitializeRaycasting(@"C:\Turbine\Asheron's Call"); + _navigationManager = new NavigationManager(CoreManager.Current, _settings, Host); + _lootManager = new LootManager(CoreManager.Current, _settings, Host); + _metaManager = new MetaManager(Core, _settings, Host); + _missileCraftingManager = new MissileCraftingManager(CoreManager.Current, _settings, Host); + _fellowshipTracker = new FellowshipTracker(CoreManager.Current); + _lootManager.SetFellowshipTracker(_fellowshipTracker); + + // Initialize the Raycast Engine and let it auto-find the AC installation folder + Raycast = new RynthAi.Raycasting.MainLogic(); + Raycast.Initialize(); + + // --- 6. Initialize Command Processor --- + _jumper = new RynthJumper(Host, _settings); + _commandProcessor = new CommandProcessor(this, _settings, _metaManager, _navigationManager, _buffManager, _combatManager, _lootManager, _luaManager, _jumper, _spellManager, _fellowshipTracker); + + // --- 7. Initialize UI and HUD --- + _spellManager.InitializeNatively(); + _ui = new RynthAiUI(_settings, _combatManager, Core); + + // --- 8. LUA INITIALIZATION & WIRING --- + // Initialize AFTER _ui exists to prevent NullRef during bridge setup + _luaManager = new LuaManager(this); + + // Wire: Run Button (Routed through the new LuaUI tab class) + _luaManager.ExecuteString("OnBotTick()"); + + // Wire: Stop Button (Emergency Shutdown) + _ui.LuaTab.OnStopRequested = () => { + _settings.IsMacroRunning = false; + _settings.EnableNavigation = false; + _settings.EnableCombat = false; + _navigationManager?.Stop(); + Host.Actions.AddChatText("[RynthLua] Emergency Stop Triggered.", 1); + }; + + // Wire: Settings changes from the Lua tab + _ui.LuaTab.OnSettingsChanged = () => SaveSettings(); + + // --- 9. Wire standard UI Actions --- + _ui.OnSettingsChanged = () => SaveSettings(); + _ui.OnForceRebuffClicked = () => _buffManager?.ForceFullRebuff(); + _ui.OnLootProfileSelected = () => _lootManager?.ForceReload(); + _ui.OnMetaProfileSelected = () => _metaManager?.LoadProfile(_settings.CurrentMetaPath); + _ui.OnMetaRulesUpdated = () => _metaManager?.SaveCurrentProfile(); + + // Route refresh wire-up + _metaManager.OnRouteDynamicallyLoaded += () => { if (_ui?.RouteTab != null) _ui.RouteTab.NeedsRouteGraphicsRefresh = true; }; + + _combatManager.AttachUI(_ui); + _ui.SetMissileCraftingManager(_missileCraftingManager); + + // Initialize direct combat action calls (acclient.exe function pointers) + CombatActionHelper.Initialize(msg => { + try { Host.Actions.AddChatText(msg, 1); } catch { } + }); + + // Initialize direct movement action calls (acclient.exe CM_Movement functions) + MovementActionHelper.Initialize(msg => { + try { Host.Actions.AddChatText(msg, 1); } catch { } + }); + + // Initialize Tier 2 movement (MoveToPosition via MovementManager) + unsafe + { + Tier2MovementHelper.Initialize( + msg => { try { Host.Actions.AddChatText(msg, 1); } catch { } }, + (IntPtr)SmartBox.smartbox); + } + + // --- 10. Load Navigation Profile --- + if (!string.IsNullOrEmpty(_settings.CurrentNavPath) && System.IO.File.Exists(_settings.CurrentNavPath)) + { + try + { + // This loads the points into memory + _settings.CurrentRoute = VTankNavParser.Load(_settings.CurrentNavPath); + + // FIX: The following block overwrites the ActiveNavIndex you just loaded from settings.json. + // If you want to RESUME where you left off, comment this logic out. + /* + if (_settings.CurrentRoute.RouteType == NavRouteType.Once || _settings.CurrentRoute.RouteType == NavRouteType.Follow) + _settings.ActiveNavIndex = 0; + else if (_settings.CurrentRoute.RouteType == NavRouteType.Linear || _settings.CurrentRoute.RouteType == NavRouteType.Circular) + _settings.ActiveNavIndex = _navigationManager.FindNearestWaypoint(_settings.CurrentRoute); + */ + + _navigationManager.ResetRouteState(); + + // FIX: Tell the UI to draw the rings and dots on the floor now that data is loaded + if (_ui?.RouteTab != null) + { + _ui.RouteTab.UpdateRouteGraphics(); + } + + Host.Actions.AddChatText($"[RynthAi] Restored route: {System.IO.Path.GetFileName(_settings.CurrentNavPath)}", 1); + } + catch (Exception ex) + { + _settings.CurrentNavPath = ""; + Host.Actions.AddChatText($"[RynthAi] Failed to load route: {ex.Message}", 1); + } + } + + // --- 11. Initialize standalone Meta Profile --- + if (!string.IsNullOrEmpty(_settings.CurrentMetaPath) && System.IO.File.Exists(_settings.CurrentMetaPath)) + { + _metaManager?.LoadProfile(_settings.CurrentMetaPath); + } + + _ui.RefreshNavFiles(); + + // --- 12. Initialize the HUD --- + _mainHud = UBService.Huds.CreateHud("RynthAi"); + _mainHud.ShowInBar = true; + _mainHud.Visible = true; + _mainHud.OnRender += MainHud_OnRender; + + Host.Actions.AddChatText($"[RynthAi] v1.9.1 loaded for {charName} on {serverName}.", 1); + } + catch (Exception ex) + { + Host.Actions.AddChatText("[RynthAi Login Error] " + ex.Message, 1); + } + _fpsUnlocker = new BackgroundFpsUnlocker(); + _fpsUnlocker.Start(Host); + + + } + + private void MainHud_OnRender(object sender, EventArgs e) + { + try + { + // This single line safely renders your entire unified dashboard + // (and all its tabs) every frame without crashing! + if (_ui != null) + { + _ui.Render(); + } + } + catch (Exception ex) + { + // Replace this with however you normally log errors in your plugin, + // e.g., System.Diagnostics.Debug.WriteLine(ex.ToString()); + System.Diagnostics.Debug.WriteLine(ex.ToString()); + } + } + private void OnServerDispatch(object sender, NetworkMessageEventArgs e) + { + if (e.Message.Type == 0xF7B0) + { + int eventType = (int)e.Message[2]; + if (eventType == 0x1C0) + { + int targetId = (int)e.Message[3]; + object raw = e.Message[4]; + if (raw is float f) healthRatioTracker[targetId] = f; + else if (raw is double d) healthRatioTracker[targetId] = (float)d; + // Report damage feedback to blacklist system — mob is taking damage, so it's reachable + _combatManager?.ReportDamageOnTarget(targetId); + } + else if (eventType == 0xC9) TryExtractVitals(e.Message); + } + } + + private void TryExtractVitals(Decal.Adapter.Message msg) + { + try + { + MessageStruct ev = msg.Struct("event"); + if (ev != null) + { + int hm = 0; try { hm = ev.Value<int>("healthMax"); } catch { } + if (hm > 0) + { + int obj = ev.Value<int>("object"); + if (obj == 0) obj = _combatManager.activeTargetId; + if (obj != 0) { maxHealthTracker[obj] = hm; return; } + } + } + + int tId = (int)msg[3]; + if (healthRatioTracker.ContainsKey(tId)) + { + float currentRatio = healthRatioTracker[tId]; + for (int i = 4; i < msg.Count - 1; i++) + { + if (msg[i] is int h && msg[i + 1] is int hMax) + { + if (hMax >= 50 && hMax < 5000000 && h >= 0 && h <= hMax) + { + float checkRatio = (float)h / hMax; + float currentDiff = Math.Abs(currentRatio - checkRatio); + if (currentDiff < 0.05f) + { + maxHealthTracker[tId] = hMax; + return; + } + } + } + } + } + } + catch { } + } + + public void SaveSettings(string customPath = null) + { + // Use the custom path if provided (by CommandProcessor), otherwise use the default char path + string path = customPath ?? _settingsPath; + + try + { + using (StreamWriter sw = new StreamWriter(path)) + { + // Core state + sw.WriteLine("IsMacroRunning=" + _settings.IsMacroRunning); + sw.WriteLine("CurrentNavPath=" + _settings.CurrentNavPath); + sw.WriteLine("ActiveNavIndex=" + _settings.ActiveNavIndex); + + // Subsystem toggles + sw.WriteLine("EnableBuffing=" + _settings.EnableBuffing); + sw.WriteLine("EnableCombat=" + _settings.EnableCombat); + sw.WriteLine("EnableNavigation=" + _settings.EnableNavigation); + sw.WriteLine("EnableLooting=" + _settings.EnableLooting); + sw.WriteLine("EnableMeta=" + _settings.EnableMeta); + sw.WriteLine("EnableRaycasting=" + _settings.EnableRaycasting); + + // Vitals + sw.WriteLine("HealAt=" + _settings.HealAt); + sw.WriteLine("RestamAt=" + _settings.RestamAt); + sw.WriteLine("GetManaAt=" + _settings.GetManaAt); + sw.WriteLine("TopOffHP=" + _settings.TopOffHP); + sw.WriteLine("TopOffStam=" + _settings.TopOffStam); + sw.WriteLine("TopOffMana=" + _settings.TopOffMana); + sw.WriteLine("HealOthersAt=" + _settings.HealOthersAt); + sw.WriteLine("RestamOthersAt=" + _settings.RestamOthersAt); + sw.WriteLine("InfuseOthersAt=" + _settings.InfuseOthersAt); + + // Ranges + sw.WriteLine("MonsterRange=" + _settings.MonsterRange); + sw.WriteLine("RingRange=" + _settings.RingRange); + sw.WriteLine("MinRingTargets=" + _settings.MinRingTargets); + sw.WriteLine("ApproachRange=" + _settings.ApproachRange); + sw.WriteLine("FollowNavMin=" + _settings.FollowNavMin); + sw.WriteLine("CorpseApproachRangeMax=" + _settings.CorpseApproachRangeMax); + sw.WriteLine("CorpseApproachRangeMin=" + _settings.CorpseApproachRangeMin); + + // Advanced toggles + sw.WriteLine("BoostNavPriority=" + _settings.BoostNavPriority); + sw.WriteLine("BoostLootPriority=" + _settings.BoostLootPriority); + sw.WriteLine("LootOnlyRareCorpses=" + _settings.LootOnlyRareCorpses); + sw.WriteLine("LootOwnership=" + _settings.LootOwnership); + sw.WriteLine("PeaceModeWhenIdle=" + _settings.PeaceModeWhenIdle); + sw.WriteLine("RebuffWhenIdle=" + _settings.RebuffWhenIdle); + + // Blacklist + sw.WriteLine("BlacklistAttempts=" + _settings.BlacklistAttempts); + sw.WriteLine("BlacklistTimeoutSec=" + _settings.BlacklistTimeoutSec); + + // FPS Throttling + sw.WriteLine("EnableFPSLimit=" + _settings.EnableFPSLimit); + sw.WriteLine("TargetFPSFocused=" + _settings.TargetFPSFocused); + sw.WriteLine("TargetFPSBackground=" + _settings.TargetFPSBackground); + + // Attack Power + sw.WriteLine("MeleeAttackPower=" + _settings.MeleeAttackPower); + sw.WriteLine("MissileAttackPower=" + _settings.MissileAttackPower); + sw.WriteLine("UseRecklessness=" + _settings.UseRecklessness); + sw.WriteLine("MeleeAttackHeight=" + _settings.MeleeAttackHeight); + sw.WriteLine("MissileAttackHeight=" + _settings.MissileAttackHeight); + + // Automation toggles + sw.WriteLine("EnableAutostack=" + _settings.EnableAutostack); + sw.WriteLine("EnableAutocram=" + _settings.EnableAutocram); + sw.WriteLine("EnableCombineSalvage=" + _settings.EnableCombineSalvage); + // Missile crafting + sw.WriteLine("EnableMissileCrafting=" + _settings.EnableMissileCrafting); + sw.WriteLine("MissileCraftAmmoThreshold=" + _settings.MissileCraftAmmoThreshold); + // Loot timers + sw.WriteLine("LootInterItemDelayMs=" + _settings.LootInterItemDelayMs); + sw.WriteLine("LootContentSettleMs=" + _settings.LootContentSettleMs); + sw.WriteLine("LootEmptyCorpseMs=" + _settings.LootEmptyCorpseMs); + sw.WriteLine("LootClosingDelayMs=" + _settings.LootClosingDelayMs); + sw.WriteLine("LootAssessWindowMs=" + _settings.LootAssessWindowMs); + sw.WriteLine("LootRetryTimeoutMs=" + _settings.LootRetryTimeoutMs); + sw.WriteLine("LootOpenRetryMs=" + _settings.LootOpenRetryMs); + // Salvage timers + sw.WriteLine("SalvageOpenDelayFirstMs=" + _settings.SalvageOpenDelayFirstMs); + sw.WriteLine("SalvageOpenDelayFastMs=" + _settings.SalvageOpenDelayFastMs); + sw.WriteLine("SalvageAddDelayFirstMs=" + _settings.SalvageAddDelayFirstMs); + sw.WriteLine("SalvageAddDelayFastMs=" + _settings.SalvageAddDelayFastMs); + sw.WriteLine("SalvageSalvageDelayMs=" + _settings.SalvageSalvageDelayMs); + sw.WriteLine("SalvageResultDelayFirstMs=" + _settings.SalvageResultDelayFirstMs); + sw.WriteLine("SalvageResultDelayFastMs=" + _settings.SalvageResultDelayFastMs); + sw.WriteLine("UseDispelItems=" + _settings.UseDispelItems); + sw.WriteLine("CastDispelSelf=" + _settings.CastDispelSelf); + sw.WriteLine("AutoFellowMgmt=" + _settings.AutoFellowMgmt); + sw.WriteLine("MChargesWhenOff=" + _settings.MChargesWhenOff); + + // Pets + sw.WriteLine("SummonPets=" + _settings.SummonPets); + sw.WriteLine("CustomPetRange=" + _settings.CustomPetRange); + sw.WriteLine("PetMinMonsters=" + _settings.PetMinMonsters); + + // Profile indices + sw.WriteLine("MacroSettingsIdx=" + _settings.MacroSettingsIdx); + sw.WriteLine("NavProfileIdx=" + _settings.NavProfileIdx); + sw.WriteLine("LootProfileIdx=" + _settings.LootProfileIdx); + sw.WriteLine("MetaProfileIdx=" + _settings.MetaProfileIdx); + + // UI state + sw.WriteLine("AdvancedOptions=" + _settings.AdvancedOptions); + sw.WriteLine("MineOnly=" + _settings.MineOnly); + sw.WriteLine("ShowEditor=" + _settings.ShowEditor); + + // Item rules (with GUID) + sw.WriteLine("ItemCount=" + _settings.ItemRules.Count); + for (int i = 0; i < _settings.ItemRules.Count; i++) + { + var r = _settings.ItemRules[i]; + sw.WriteLine($"Item_{i}={r.Id}|{r.Name}|{r.Element}|{r.KeepBuffed}|{r.Action}"); + } + + // Monster rules — saved to separate TSV file for easy Excel editing + // Also write count to settings for backwards compat detection + sw.WriteLine("MonsterCount=" + _settings.MonsterRules.Count); + SaveMonsterRulesTSV(path); + + // Meta Rules + sw.WriteLine("MetaCount=" + _settings.MetaRules.Count); + for (int i = 0; i < _settings.MetaRules.Count; i++) + { + var r = _settings.MetaRules[i]; + sw.WriteLine($"Meta_{i}={r.State}|{(int)r.Condition}|{r.ConditionData}|{(int)r.Action}|{r.ActionData}"); + } + } + } + catch (Exception ex) + { + Host.Actions.AddChatText($"[RynthAi] Save Error: {ex.Message}", 2); + } + } + + public void LoadSettings(string customPath = null) + { + string path = customPath ?? _settingsPath; + _settings = new UISettings(); + + try + { + if (System.IO.File.Exists(path)) + { + foreach (string line in System.IO.File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq < 1) continue; + string k = line.Substring(0, eq).Trim(); + string v = line.Substring(eq + 1).Trim(); + + // Core state + if (k == "IsMacroRunning") _settings.IsMacroRunning = bool.Parse(v); + else if (k == "CurrentNavPath") _settings.CurrentNavPath = v; + else if (k == "ActiveNavIndex") _settings.ActiveNavIndex = int.Parse(v); + + // Subsystem toggles + else if (k == "EnableBuffing") _settings.EnableBuffing = bool.Parse(v); + else if (k == "EnableCombat") _settings.EnableCombat = bool.Parse(v); + else if (k == "EnableNavigation") _settings.EnableNavigation = bool.Parse(v); + else if (k == "EnableLooting") _settings.EnableLooting = bool.Parse(v); + else if (k == "EnableMeta") _settings.EnableMeta = bool.Parse(v); + else if (k == "EnableRaycasting") _settings.EnableRaycasting = bool.Parse(v); + + // Vitals + else if (k == "HealAt") _settings.HealAt = int.Parse(v); + else if (k == "RestamAt") _settings.RestamAt = int.Parse(v); + else if (k == "GetManaAt") _settings.GetManaAt = int.Parse(v); + else if (k == "TopOffHP") _settings.TopOffHP = int.Parse(v); + else if (k == "TopOffStam") _settings.TopOffStam = int.Parse(v); + else if (k == "TopOffMana") _settings.TopOffMana = int.Parse(v); + else if (k == "HealOthersAt") _settings.HealOthersAt = int.Parse(v); + else if (k == "RestamOthersAt") _settings.RestamOthersAt = int.Parse(v); + else if (k == "InfuseOthersAt") _settings.InfuseOthersAt = int.Parse(v); + + // Ranges + else if (k == "MonsterRange") _settings.MonsterRange = int.Parse(v); + else if (k == "RingRange") _settings.RingRange = int.Parse(v); + else if (k == "MinRingTargets") _settings.MinRingTargets = int.Parse(v); + else if (k == "ApproachRange") _settings.ApproachRange = int.Parse(v); + else if (k == "FollowNavMin") _settings.FollowNavMin = float.Parse(v); + else if (k == "CorpseApproachRangeMax") _settings.CorpseApproachRangeMax = double.Parse(v); + else if (k == "CorpseApproachRangeMin") _settings.CorpseApproachRangeMin = double.Parse(v); + + // Advanced toggles + else if (k == "BoostNavPriority") _settings.BoostNavPriority = bool.Parse(v); + else if (k == "BoostLootPriority") _settings.BoostLootPriority = bool.Parse(v); + else if (k == "LootOnlyRareCorpses") _settings.LootOnlyRareCorpses = bool.Parse(v); + else if (k == "LootOwnership") _settings.LootOwnership = int.Parse(v); + else if (k == "PeaceModeWhenIdle") _settings.PeaceModeWhenIdle = bool.Parse(v); + else if (k == "RebuffWhenIdle") _settings.RebuffWhenIdle = bool.Parse(v); + + // Blacklist + else if (k == "BlacklistAttempts") _settings.BlacklistAttempts = int.Parse(v); + else if (k == "BlacklistTimeoutSec") _settings.BlacklistTimeoutSec = int.Parse(v); + + // FPS Throttling + else if (k == "EnableFPSLimit") _settings.EnableFPSLimit = bool.Parse(v); + else if (k == "TargetFPSFocused") _settings.TargetFPSFocused = int.Parse(v); + else if (k == "TargetFPSBackground") _settings.TargetFPSBackground = int.Parse(v); + + // Attack Power + else if (k == "MeleeAttackPower") _settings.MeleeAttackPower = int.Parse(v); + else if (k == "MissileAttackPower") _settings.MissileAttackPower = int.Parse(v); + else if (k == "UseRecklessness") _settings.UseRecklessness = bool.Parse(v); + else if (k == "MeleeAttackHeight") _settings.MeleeAttackHeight = int.Parse(v); + else if (k == "MissileAttackHeight") _settings.MissileAttackHeight = int.Parse(v); + // Backwards compat: old float AttackPower → both + else if (k == "AttackPower") { float old = float.Parse(v); int pct = old < 0 ? -1 : (int)(old * 100); _settings.MeleeAttackPower = pct; _settings.MissileAttackPower = pct; } + + // Automation toggles + else if (k == "EnableAutostack") _settings.EnableAutostack = bool.Parse(v); + else if (k == "EnableAutocram") _settings.EnableAutocram = bool.Parse(v); + else if (k == "EnableCombineSalvage") _settings.EnableCombineSalvage = bool.Parse(v); + // Missile crafting + else if (k == "EnableMissileCrafting") _settings.EnableMissileCrafting = bool.Parse(v); + else if (k == "MissileCraftAmmoThreshold") _settings.MissileCraftAmmoThreshold = int.Parse(v); + // Loot timers + else if (k == "LootInterItemDelayMs") _settings.LootInterItemDelayMs = int.Parse(v); + else if (k == "LootContentSettleMs") _settings.LootContentSettleMs = int.Parse(v); + else if (k == "LootEmptyCorpseMs") _settings.LootEmptyCorpseMs = int.Parse(v); + else if (k == "LootClosingDelayMs") _settings.LootClosingDelayMs = int.Parse(v); + else if (k == "LootAssessWindowMs") _settings.LootAssessWindowMs = int.Parse(v); + else if (k == "LootRetryTimeoutMs") _settings.LootRetryTimeoutMs = int.Parse(v); + else if (k == "LootOpenRetryMs") _settings.LootOpenRetryMs = int.Parse(v); + // Salvage timers + else if (k == "SalvageOpenDelayFirstMs") _settings.SalvageOpenDelayFirstMs = int.Parse(v); + else if (k == "SalvageOpenDelayFastMs") _settings.SalvageOpenDelayFastMs = int.Parse(v); + else if (k == "SalvageAddDelayFirstMs") _settings.SalvageAddDelayFirstMs = int.Parse(v); + else if (k == "SalvageAddDelayFastMs") _settings.SalvageAddDelayFastMs = int.Parse(v); + else if (k == "SalvageSalvageDelayMs") _settings.SalvageSalvageDelayMs = int.Parse(v); + else if (k == "SalvageResultDelayFirstMs") _settings.SalvageResultDelayFirstMs = int.Parse(v); + else if (k == "SalvageResultDelayFastMs") _settings.SalvageResultDelayFastMs = int.Parse(v); + else if (k == "UseDispelItems") _settings.UseDispelItems = bool.Parse(v); + else if (k == "CastDispelSelf") _settings.CastDispelSelf = bool.Parse(v); + else if (k == "AutoFellowMgmt") _settings.AutoFellowMgmt = bool.Parse(v); + else if (k == "MChargesWhenOff") _settings.MChargesWhenOff = bool.Parse(v); + + // Pets + else if (k == "SummonPets") _settings.SummonPets = bool.Parse(v); + else if (k == "CustomPetRange") _settings.CustomPetRange = int.Parse(v); + else if (k == "PetMinMonsters") _settings.PetMinMonsters = int.Parse(v); + + // Profile indices + else if (k == "MacroSettingsIdx") _settings.MacroSettingsIdx = int.Parse(v); + else if (k == "NavProfileIdx") _settings.NavProfileIdx = int.Parse(v); + else if (k == "LootProfileIdx") _settings.LootProfileIdx = int.Parse(v); + else if (k == "MetaProfileIdx") _settings.MetaProfileIdx = int.Parse(v); + + // UI state + else if (k == "AdvancedOptions") _settings.AdvancedOptions = bool.Parse(v); + else if (k == "MineOnly") _settings.MineOnly = bool.Parse(v); + else if (k == "ShowEditor") _settings.ShowEditor = bool.Parse(v); + + // Item rules + else if (k.StartsWith("Item_")) + { + var bits = v.Split('|'); + if (bits.Length >= 5) + { + _settings.ItemRules.Add(new ItemRule { Id = int.Parse(bits[0]), Name = bits[1], Element = bits[2], KeepBuffed = bool.Parse(bits[3]), Action = bits[4] }); + } + } + + // Monster rules + else if (k.StartsWith("Monster_")) + { + var bits = v.Split('|'); + if (bits.Length >= 4) + { + var mr = new MonsterRule { Name = bits[0], Priority = int.Parse(bits[1]), DamageType = bits[2], WeaponId = int.Parse(bits[3]) }; + // Load debuff/spell type flags if present (backwards compat) + if (bits.Length >= 13) + { + mr.Fester = bool.Parse(bits[4]); + mr.Broadside = bool.Parse(bits[5]); + mr.GravityWell = bool.Parse(bits[6]); + mr.Imperil = bool.Parse(bits[7]); + mr.Yield = bool.Parse(bits[8]); + mr.Vuln = bool.Parse(bits[9]); + mr.UseArc = bool.Parse(bits[10]); + mr.UseRing = bool.Parse(bits[11]); + mr.UseStreak = bool.Parse(bits[12]); + } + // Load ExVuln, OffhandId, PetDamage if present + if (bits.Length >= 16) + { + mr.ExVuln = bits[13]; + mr.OffhandId = int.Parse(bits[14]); + mr.PetDamage = bits[15]; + } + // Load UseBolt if present (backwards compat: defaults to true) + if (bits.Length >= 17) + { + mr.UseBolt = bool.Parse(bits[16]); + } + _settings.MonsterRules.Add(mr); + } + } + + // Meta Rules + else if (k.StartsWith("Meta_")) + { + var bits = v.Split('|'); + if (bits.Length >= 5) + { + _settings.MetaRules.Add(new MetaRule { State = bits[0], Condition = (MetaConditionType)int.Parse(bits[1]), ConditionData = bits[2], Action = (MetaActionType)int.Parse(bits[3]), ActionData = bits[4] }); + } + } + } + } + } + catch (Exception ex) + { + Host.Actions.AddChatText($"[RynthAi] Load Error: {ex.Message}", 2); + } + + _settings.IsMacroRunning = false; + + // Try loading monster rules from TSV file (preferred) — overrides any inline Monster_ lines + string tsvPath = GetMonsterRulesTSVPath(path); + if (System.IO.File.Exists(tsvPath)) + { + var tsvRules = LoadMonsterRulesTSV(tsvPath); + if (tsvRules.Count > 0) + { + _settings.MonsterRules = tsvRules; + } + } + + _settings.EnsureDefaultRule(); + } + + private string GetMonsterRulesTSVPath(string settingsPath) + { + string dir = System.IO.Path.GetDirectoryName(settingsPath); + return System.IO.Path.Combine(dir, "monsters.tsv"); + } + + private void SaveMonsterRulesTSV(string settingsPath) + { + string tsvPath = GetMonsterRulesTSVPath(settingsPath); + string tmpPath = tsvPath + ".tmp"; + + try + { + // Write to temp file first to avoid lock conflicts + using (var fs = new FileStream(tmpPath, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var sw = new StreamWriter(fs)) + { + sw.WriteLine("Name\tPriority\tDmgType\tWeaponId\tFester\tBroadside\tGravity\tImperil\tYield\tVuln\tArc\tRing\tStreak\tBolt\tExVuln\tOffhandId\tPetDamage"); + foreach (var r in _settings.MonsterRules) + { + sw.WriteLine($"{r.Name}\t{r.Priority}\t{r.DamageType}\t{r.WeaponId}\t{r.Fester}\t{r.Broadside}\t{r.GravityWell}\t{r.Imperil}\t{r.Yield}\t{r.Vuln}\t{r.UseArc}\t{r.UseRing}\t{r.UseStreak}\t{r.UseBolt}\t{r.ExVuln}\t{r.OffhandId}\t{r.PetDamage}"); + } + } + + // Atomic replace — if the main file is locked, this will fail gracefully + try + { + if (File.Exists(tsvPath)) File.Delete(tsvPath); + File.Move(tmpPath, tsvPath); + } + catch + { + // Main file is locked (e.g., open in Excel) — leave tmp for next attempt + // Don't spam chat about it, it's not critical + } + } + catch (Exception ex) + { + try { Host.Actions.AddChatText($"[RynthAi] Monster TSV save error: {ex.Message}", 2); } catch { } + } + } + + private List<MonsterRule> LoadMonsterRulesTSV(string tsvPath) + { + var rules = new List<MonsterRule>(); + try + { + var lines = System.IO.File.ReadAllLines(tsvPath); + // Skip header row + for (int i = 1; i < lines.Length; i++) + { + string line = lines[i]; + if (string.IsNullOrWhiteSpace(line)) continue; + var c = line.Split('\t'); + if (c.Length < 4) continue; + + var mr = new MonsterRule + { + Name = c[0], + Priority = int.Parse(c[1]), + DamageType = c[2], + WeaponId = int.Parse(c[3]) + }; + if (c.Length >= 14) + { + mr.Fester = bool.Parse(c[4]); + mr.Broadside = bool.Parse(c[5]); + mr.GravityWell = bool.Parse(c[6]); + mr.Imperil = bool.Parse(c[7]); + mr.Yield = bool.Parse(c[8]); + mr.Vuln = bool.Parse(c[9]); + mr.UseArc = bool.Parse(c[10]); + mr.UseRing = bool.Parse(c[11]); + mr.UseStreak = bool.Parse(c[12]); + mr.UseBolt = bool.Parse(c[13]); + } + if (c.Length >= 17) + { + mr.ExVuln = c[14]; + mr.OffhandId = int.Parse(c[15]); + mr.PetDamage = c[16]; + } + rules.Add(mr); + } + } + catch (Exception ex) + { + try { Host.Actions.AddChatText($"[RynthAi] Monster TSV load error: {ex.Message}", 2); } catch { } + } + return rules; + } + + private void OnChatCommand(object sender, ChatParserInterceptEventArgs e) + { + _commandProcessor?.Execute(e.Text, e); + } + + // --- API Imports for FPS Governor --- + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + + private int _fpsDebugCounter = 0; + + private void OnRenderFrame(object sender, EventArgs e) + { + // === 1. FPS GOVERNOR (ThwargLauncher Safe PID Version) === + // This manages CPU usage by throttling frames when the window is in the background. + if (_settings.EnableFPSLimit) + { + // Get the window currently on top of everything + IntPtr foregroundWindow = GetForegroundWindow(); + + // Get the Process ID of that foreground window + GetWindowThreadProcessId(foregroundWindow, out uint foregroundPid); + + // Get the Process ID of THIS specific AC client + uint thisPid = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; + + // If the PIDs match, this specific client is the one being looked at + bool isFocused = (foregroundPid == thisPid); + int targetFPS = isFocused ? _settings.TargetFPSFocused : _settings.TargetFPSBackground; + + // --- THE SPY (Debug logging to chat) --- + _fpsDebugCounter++; + if (_fpsDebugCounter >= (isFocused ? 200 : 50)) + { + _fpsDebugCounter = 0; + // Uncomment the line below if you need to debug FPS stability + // Host.Actions.AddChatText($"[RynthFPS] PID: {thisPid} | Mode: {(isFocused ? "FOCUSED" : "BACKGROUND")} | Target: {targetFPS} FPS", 1); + } + + // Calculate timing: 1000ms / Target + double minFrameTimeMs = 1000.0 / Math.Max(targetFPS, 1); + + while (_frameTimer.Elapsed.TotalMilliseconds < minFrameTimeMs) + { + // Use Sleep(1) for background to save massive CPU; Sleep(0) for focus to maintain responsiveness + System.Threading.Thread.Sleep(isFocused ? 0 : 1); + } + _frameTimer.Restart(); + } + + // === 2. DEFENSIVE LUA HEARTBEAT === + // Ensures the Lua environment stays alive and ticks the OnBotTick() function. + if (DateTime.Now > _nextLuaTick) + { + _nextLuaTick = DateTime.Now.AddMilliseconds(250); + if (_luaManager != null && _settings.IsMacroRunning) + { + // Safety check to prevent "nil value" crashes if the user hasn't defined OnBotTick + _luaManager.ExecuteString("if OnBotTick ~= nil then OnBotTick() end"); + } + } + + // === 2.5 NATIVE JUMPER === + // Ticks the jump state machine (runs even when macro is paused for jumping) + _jumper?.Think(); + + // === 3. CORE BOT LOGIC === + // If the macro is off, we stop here. + // Note: UI Rendering should stay in MainHud_OnRender to keep the ImGui lifecycle clean. + if (!_settings.IsMacroRunning) return; + + // 3a. Meta System (Decides what the bot should be doing) + _metaManager?.Think(); + + // 3b. Maintenance (Buffs, Vitals, Recharging) — ALWAYS runs first regardless of priority + _buffManager?.OnHeartbeat(); + + // If buffing claimed the state, yield everything else this frame + if (_settings.CurrentState == "Buffing") return; + + // 3c. INVENTORY MANAGEMENT + // Salvage blocks everything until complete — prevents items piling up. + if (_lootManager != null && _settings.IsMacroRunning) + { + _lootManager.ProcessSalvage(); + + if (_lootManager.IsSalvageProcessing) + return; // Block combat, nav, AND looting until salvage finishes + + // Missile crafting runs after salvage, before stack/cram. + if (_missileCraftingManager != null) + { + _missileCraftingManager.ProcessCrafting(); + if (_missileCraftingManager.IsCrafting) + return; // Block combat, nav, looting until crafting finishes + } + + _lootManager.ProcessStack(); + _lootManager.ProcessCram(); + } + + // 3d. PRIORITY DISPATCHER + // Reset the traffic light to Idle at the start of each frame. + // Each subsystem will claim the state if it has active work to do. + // This prevents stale states from previous frames blocking subsystems + // (e.g., "Looting" state lingering and preventing Navigation from running). + _settings.CurrentState = "Idle"; + + // Determines the order that Combat, Navigation, and Looting run in. + // + // Default: Combat → Loot → Nav + // NavPriorityBoost ON: Nav → Combat → Loot + // LootPriorityBoost ON: Loot → Combat → Nav + // Both boosts ON: Nav → Loot → Combat + // + // Each subsystem checks _settings.CurrentState as a traffic light. + // The FIRST system to claim the state blocks the others. + + bool navBoost = _settings.BoostNavPriority; + bool lootBoost = _settings.BoostLootPriority; + + if (navBoost && lootBoost) + { + RunNavigation(); + RunLooting(); + RunCombat(); + } + else if (navBoost) + { + RunNavigation(); + RunCombat(); + RunLooting(); + } + else if (lootBoost) + { + RunLooting(); + RunCombat(); + RunNavigation(); + } + else + { + RunCombat(); + RunLooting(); + RunNavigation(); + } + } + + // ── Priority Dispatcher Helpers ────────────────────────────────────── + // Each checks if the state is still "Idle" before claiming it. + // Once a system claims the state, later systems in the priority chain yield. + + private void RunCombat() + { + if (!_settings.EnableCombat) return; + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle") return; + _combatManager?.OnHeartbeat(); + } + + private void RunNavigation() + { + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle") return; + // Pause nav if there are unlooted corpses nearby — let looting finish first + if (_settings.EnableLooting && (_lootManager?.HasUnlootedCorpsesNearby() ?? false)) return; + bool isFighting = _settings.EnableCombat && (_combatManager?.activeTargetId ?? 0) != 0; + _navigationManager?.ProcessNavigation(isFighting); + } + + private void RunLooting() + { + // Yield if a higher-priority system already claimed the state this frame + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Looting") return; + _lootManager?.OnHeartbeat(); + } + + private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e) + { + try + { + // Feed the chat text to your sub-managers + _metaManager?.HandleChat(e.Text); + _combatManager?.HandleChatForDebuffs(e.Text); + _missileCraftingManager?.HandleChat(e.Text); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.ToString()); + } + } + + + + private double ParseCoord(string val) + { + if (string.IsNullOrEmpty(val)) return 0; + + // Remove letters and whitespace, then parse the number + string clean = System.Text.RegularExpressions.Regex.Replace(val, "[^0-9.-]", ""); + if (!double.TryParse(clean, out double result)) return 0; + + // If it contains S or W, it must be negative for the coordinate system + if (val.ToUpper().Contains("S") || val.ToUpper().Contains("W")) + return -result; + + return result; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/BlacklistManager.cs b/Plugins/RynthAi/Raycasting/BlacklistManager.cs new file mode 100644 index 0000000..3b60488 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/BlacklistManager.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + public class BlacklistManager + { + /// <summary> + /// Tracks consecutive failures for specific WorldObjects. + /// Incremented when an attack on a target produces no server feedback. + /// </summary> + private readonly Dictionary<int, int> _failureCounts = new Dictionary<int, int>(); + + /// <summary> + /// Tracks the expiration time for blacklisted targets. + /// Targets are temporarily ignored if they're stuck in walls or ghosts. + /// </summary> + private readonly Dictionary<int, DateTime> _blacklistExpirations = new Dictionary<int, DateTime>(); + + /// <summary> + /// Number of consecutive attack failures before a target is blacklisted. + /// Default: 3 attempts (adjustable for different difficulty settings). + /// </summary> + public int AttemptThreshold { get; set; } = 3; + + /// <summary> + /// Duration in seconds that a target remains blacklisted after threshold is breached. + /// Default: 30 seconds (allows time for stuck/ghost detection to resolve). + /// </summary> + public int TimeoutSeconds { get; set; } = 30; + + /// <summary> + /// Increments the failure count for a target. + /// Call this if an attack is launched but yields no server feedback (damage, XP, etc.). + /// If the failure count reaches the threshold, the target is automatically blacklisted. + /// </summary> + public void ReportFailure(int targetId) + { + if (!_failureCounts.ContainsKey(targetId)) + _failureCounts[targetId] = 0; + + _failureCounts[targetId]++; + + // Log the failure for debugging + System.Diagnostics.Debug.WriteLine($"Target {targetId} failure count: {_failureCounts[targetId]}/{AttemptThreshold}"); + + // If the threshold is breached, blacklist the target + if (_failureCounts[targetId] >= AttemptThreshold) + { + BlacklistTarget(targetId); + } + } + + /// <summary> + /// Immediately blacklists a target for the configured timeout duration. + /// </summary> + private void BlacklistTarget(int targetId) + { + DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds); + _blacklistExpirations[targetId] = expirationTime; + + System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklisted until {expirationTime:HH:mm:ss}"); + } + + /// <summary> + /// Checks if a target should be ignored by the targeting system. + /// Returns true if the target is currently blacklisted (timeout not expired). + /// Returns false if the target is not blacklisted or if its timeout has expired. + /// </summary> + public bool IsBlacklisted(int targetId) + { + if (!_blacklistExpirations.TryGetValue(targetId, out var expiration)) + return false; // Target not in blacklist + + // Check if blacklist timeout has expired + if (DateTime.Now >= expiration) + { + // Timeout expired - remove from blacklist and allow re-evaluation + _blacklistExpirations.Remove(targetId); + _failureCounts.Remove(targetId); + System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklist expired, re-evaluating"); + return false; + } + + // Target still blacklisted + return true; + } + + /// <summary> + /// Clears the failure count and blacklist status for a target. + /// Call this when a target successfully takes damage or shows other server feedback. + /// This allows the target to be re-engaged if it becomes blocked again later. + /// </summary> + public void ClearFailure(int targetId) + { + _failureCounts.Remove(targetId); + _blacklistExpirations.Remove(targetId); + System.Diagnostics.Debug.WriteLine($"Target {targetId} failure cleared"); + } + + /// <summary> + /// Completely clears all blacklist and failure tracking data. + /// Useful when transitioning between combat zones or resetting the bot state. + /// </summary> + public void ClearAll() + { + _failureCounts.Clear(); + _blacklistExpirations.Clear(); + System.Diagnostics.Debug.WriteLine("All blacklist data cleared"); + } + + /// <summary> + /// Returns the number of currently blacklisted targets. + /// Useful for debugging and monitoring bot behavior. + /// </summary> + public int GetBlacklistCount() + { + int count = 0; + var expiredKeys = new List<int>(); + + foreach (var kvp in _blacklistExpirations) + { + if (DateTime.Now < kvp.Value) + { + count++; + } + else + { + expiredKeys.Add(kvp.Key); + } + } + + // Clean up expired entries while we're here + foreach (var key in expiredKeys) + { + _blacklistExpirations.Remove(key); + _failureCounts.Remove(key); + } + + return count; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/BoundingVolume.cs b/Plugins/RynthAi/Raycasting/BoundingVolume.cs new file mode 100644 index 0000000..d51cfaf --- /dev/null +++ b/Plugins/RynthAi/Raycasting/BoundingVolume.cs @@ -0,0 +1,245 @@ +using System; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Bounding volume for collision detection + /// Supports ray-volume intersection testing for raycasting + /// </summary> + public class BoundingVolume + { + public enum VolumeType + { + Sphere = 1, + Cylinder = 2, + Ellipsoid = 3, + Polygon = 4, + AxisAlignedBox = 5, + Torus = 6 + } + + public VolumeType Type { get; set; } + public Vector3 Center { get; set; } // X, Y, Z + public Vector3 Dimensions { get; set; } // Radius, Height, etc + public Vector3[] Vertices { get; set; } // For polygons + + // Additional properties for geometry loading + public Vector3 Min { get; set; } // Minimum bounds + public Vector3 Max { get; set; } // Maximum bounds + public bool IsDoor { get; set; } // Whether this is a door (passable) + + public BoundingVolume() + { + Center = new Vector3(0, 0, 0); + Dimensions = new Vector3(0, 0, 0); + Min = new Vector3(0, 0, 0); + Max = new Vector3(0, 0, 0); + IsDoor = false; + } + + /// <summary> + /// Test if a ray intersects this volume + /// Returns true if collision detected + /// </summary> + public bool RayIntersect(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + try + { + switch (Type) + { + case VolumeType.Sphere: + return RayIntersectSphere(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.Cylinder: + return RayIntersectCylinder(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.AxisAlignedBox: + return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist); + case VolumeType.Polygon: + return RayIntersectPolygon(rayStart, rayDir, maxDist, out hitDist); + default: + return false; + } + } + catch + { + return false; + } + } + + /// <summary> + /// Overload to accept float arrays for backwards compatibility + /// </summary> + public bool RayIntersect(float[] rayStart, float[] rayDir, float maxDist, out float hitDist) + { + return RayIntersect( + Vector3.FromArray(rayStart), + Vector3.FromArray(rayDir), + maxDist, + out hitDist + ); + } + + /// <summary> + /// Ray-Sphere intersection + /// </summary> + private bool RayIntersectSphere(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + Vector3 oc = rayStart - Center; + + float a = Vector3.Dot(rayDir, rayDir); + float b = 2.0f * Vector3.Dot(oc, rayDir); + float c = Vector3.Dot(oc, oc) - (Dimensions.X * Dimensions.X); + + float discriminant = b * b - 4 * a * c; + if (discriminant < 0) + return false; + + float sqrt_disc = (float)Math.Sqrt(discriminant); + float t1 = (-b - sqrt_disc) / (2 * a); + float t2 = (-b + sqrt_disc) / (2 * a); + + if (t1 > 0 && t1 < maxDist) + { + hitDist = t1; + return true; + } + + // Ray starts inside sphere (t1 < 0, t2 > 0) + if (t1 <= 0 && t2 > 0 && t2 < maxDist) + { + hitDist = 0; + return true; + } + + return false; + } + + /// <summary> + /// Ray-Cylinder intersection + /// </summary> + private bool RayIntersectCylinder(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + return false; + } + + /// <summary> + /// Ray-AABB intersection + /// </summary> + private bool RayIntersectAABB(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + + float tmin = 0, tmax = maxDist; + + for (int i = 0; i < 3; i++) + { + float rayStartCoord = i == 0 ? rayStart.X : (i == 1 ? rayStart.Y : rayStart.Z); + float rayDirCoord = i == 0 ? rayDir.X : (i == 1 ? rayDir.Y : rayDir.Z); + float minCoord = i == 0 ? Min.X : (i == 1 ? Min.Y : Min.Z); + float maxCoord = i == 0 ? Max.X : (i == 1 ? Max.Y : Max.Z); + + if (Math.Abs(rayDirCoord) < 0.00001f) + { + if (rayStartCoord < minCoord || rayStartCoord > maxCoord) + return false; + } + else + { + float t1 = (minCoord - rayStartCoord) / rayDirCoord; + float t2 = (maxCoord - rayStartCoord) / rayDirCoord; + + if (t1 > t2) + { + float temp = t1; + t1 = t2; + t2 = temp; + } + + tmin = Math.Max(tmin, t1); + tmax = Math.Min(tmax, t2); + + if (tmin > tmax) + return false; + } + } + + if (tmin > 0 && tmin < maxDist) + { + hitDist = tmin; + return true; + } + + // Ray starts inside the box (tmin <= 0 but tmax > 0) + // This means the player is inside/overlapping the obstacle + if (tmin <= 0 && tmax > 0 && tmax < maxDist) + { + hitDist = 0; + return true; + } + + return false; + } + + /// <summary> + /// Ray-Polygon intersection + /// </summary> + private bool RayIntersectPolygon(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist) + { + hitDist = float.MaxValue; + if (Vertices == null || Vertices.Length < 3) + return false; + + for (int i = 0; i < Vertices.Length - 2; i++) + { + if (RayIntersectTriangle(rayStart, rayDir, Vertices[0], Vertices[i + 1], Vertices[i + 2], out float t)) + { + if (t >= 0 && t < maxDist && t < hitDist) + { + hitDist = t; + return true; + } + } + } + + return false; + } + + /// <summary> + /// Ray-Triangle intersection (Möller-Trumbore algorithm) + /// </summary> + private bool RayIntersectTriangle(Vector3 rayStart, Vector3 rayDir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = float.MaxValue; + const float EPSILON = 0.0000001f; + + Vector3 edge1 = v1 - v0; + Vector3 edge2 = v2 - v0; + + Vector3 h = Vector3.Cross(rayDir, edge2); + float a = Vector3.Dot(edge1, h); + + if (a > -EPSILON && a < EPSILON) + return false; + + float f = 1.0f / a; + Vector3 s = rayStart - v0; + + float u = f * Vector3.Dot(s, h); + if (u < 0 || u > 1) + return false; + + Vector3 q = Vector3.Cross(s, edge1); + float v = f * Vector3.Dot(rayDir, q); + + if (v < 0 || u + v > 1) + return false; + + t = f * Vector3.Dot(edge2, q); + return t >= 0; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/DatDatabase.cs b/Plugins/RynthAi/Raycasting/DatDatabase.cs new file mode 100644 index 0000000..cd93aa0 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/DatDatabase.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// AC .dat file reader — ported directly from ACEmulator's DatLoader. + /// + /// Key format details (from ACE source): + /// - Header at file offset 0x140 + /// - Block chain: FIRST 4 bytes of each block = next block address (byte offset) + /// Remaining (BlockSize - 4) bytes = data + /// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total + /// - All pointers (BTree root, chain pointers, file offsets) are byte offsets + /// </summary> + public class DatDatabase : IDisposable + { + private FileStream _stream; + private readonly object _lock = new object(); + + private const uint DAT_HEADER_OFFSET = 0x140; + + // B-tree geometry (from ACE DatDirectoryHeader.cs): + // 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes + // ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716 + private const int BTREE_BRANCH_COUNT = 0x3E; // 62 + private const int BTREE_MAX_ENTRIES = 0x3D; // 61 + private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32 + private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716 + + // Header fields + public uint FileType { get; private set; } + public uint BlockSize { get; private set; } + public uint FileSize { get; private set; } + public uint DataSet { get; private set; } + public uint BTreeRoot { get; private set; } // Byte offset + + public bool IsLoaded { get; private set; } + public string FilePath { get; private set; } + public int RecordCount { get; private set; } + + // All files indexed by ObjectId (populated during Open) + private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>(); + + public List<string> DiagLog { get; } = new List<string>(); + + public bool Open(string path) + { + try + { + if (!File.Exists(path)) + { + Log($"File not found: {path}"); + return false; + } + + FilePath = path; + _stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + + Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes"); + + if (!ReadHeader()) + { + Close(); + return false; + } + + // Read the entire B-tree directory and index all files + ReadDirectory(BTreeRoot); + + RecordCount = _allFiles.Count; + IsLoaded = true; + + Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}"); + + return true; + } + catch (Exception ex) + { + Log($"Error: {ex.Message}"); + Close(); + return false; + } + } + + /// <summary> + /// Reads the dat header from offset 0x140. + /// Format matches ACE's DatDatabaseHeader.Unpack(). + /// </summary> + private bool ReadHeader() + { + if (_stream.Length < DAT_HEADER_OFFSET + 64) + { + Log("File too small"); + return false; + } + + _stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin); + using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true)) + { + FileType = reader.ReadUInt32(); + BlockSize = reader.ReadUInt32(); + FileSize = reader.ReadUInt32(); + DataSet = reader.ReadUInt32(); + uint dataSubset = reader.ReadUInt32(); + + uint freeHead = reader.ReadUInt32(); + uint freeTail = reader.ReadUInt32(); + uint freeCount = reader.ReadUInt32(); + BTreeRoot = reader.ReadUInt32(); + } + + Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}"); + + if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length) + { + Log("Invalid header values"); + return false; + } + + return true; + } + + /// <summary> + /// Reads data from the dat file following the block chain. + /// Matches ACE's DatReader.ReadDat() exactly. + /// + /// Block format: + /// [4 bytes: next block address] [BlockSize - 4 bytes: data] + /// + /// The FIRST 4 bytes of each block are the chain pointer (next block address). + /// If 0, this is the last block. + /// </summary> + private byte[] ReadDatData(uint offset, int size) + { + if (offset + BlockSize > (uint)_stream.Length || size <= 0) + return null; + + byte[] buffer = new byte[size]; + + _stream.Seek(offset, SeekOrigin.Begin); + + // Read first 4 bytes = next block address + byte[] addrBuf = new byte[4]; + _stream.Read(addrBuf, 0, 4); + uint nextAddress = BitConverter.ToUInt32(addrBuf, 0); + + int bufferOffset = 0; + int remaining = size; + + while (remaining > 0) + { + if (nextAddress == 0) + { + // Last block — read remaining data directly + int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position)); + if (toRead <= 0) break; + _stream.Read(buffer, bufferOffset, toRead); + remaining = 0; + } + else + { + // Read data portion of this block (BlockSize - 4 bytes) + int dataInBlock = (int)BlockSize - 4; + int toRead = Math.Min(dataInBlock, remaining); + _stream.Read(buffer, bufferOffset, toRead); + bufferOffset += toRead; + remaining -= toRead; + + if (remaining > 0) + { + // Follow chain to next block + if (nextAddress >= (uint)_stream.Length) break; + _stream.Seek(nextAddress, SeekOrigin.Begin); + + // Read next block's chain pointer + _stream.Read(addrBuf, 0, 4); + nextAddress = BitConverter.ToUInt32(addrBuf, 0); + } + } + } + + return buffer; + } + + /// <summary> + /// Recursively reads the B-tree directory and indexes all files. + /// Matches ACE's DatDirectory.Read() + AddFilesToList(). + /// </summary> + private void ReadDirectory(uint sectorOffset) + { + if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length) + return; + + // Read the directory header (B-tree node) + byte[] nodeData; + lock (_lock) + { + nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE); + } + + if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE) + return; + + // Parse branches (62 × uint32) + uint[] branches = new uint[BTREE_BRANCH_COUNT]; + for (int i = 0; i < BTREE_BRANCH_COUNT; i++) + branches[i] = BitConverter.ToUInt32(nodeData, i * 4); + + // Parse entry count + int countOffset = BTREE_BRANCH_COUNT * 4; // 248 + uint entryCount = BitConverter.ToUInt32(nodeData, countOffset); + + if (entryCount > BTREE_MAX_ENTRIES) + return; // Invalid node + + // Parse entries + int entriesOffset = countOffset + 4; // 252 + var entries = new DatBTreeEntry[entryCount]; + + for (int i = 0; i < entryCount; i++) + { + int eOff = entriesOffset + i * BTREE_ENTRY_SIZE; + entries[i] = new DatBTreeEntry + { + BitFlags = BitConverter.ToUInt32(nodeData, eOff), + ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4), + FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8), + FileSize = BitConverter.ToUInt32(nodeData, eOff + 12) + }; + } + + // Recurse into child directories (if branches[0] != 0, node has children) + if (branches[0] != 0) + { + for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++) + { + if (branches[i] != 0) + ReadDirectory(branches[i]); + } + } + + // Add entries to the file index + for (int i = 0; i < entryCount; i++) + { + if (entries[i].ObjectId != 0) + _allFiles[entries[i].ObjectId] = entries[i]; + } + } + + /// <summary> + /// Finds a file by ID. O(1) lookup from the pre-built index. + /// </summary> + public DatBTreeEntry FindFile(uint fileId) + { + if (!IsLoaded) return null; + _allFiles.TryGetValue(fileId, out var entry); + return entry; + } + + /// <summary> + /// Reads file data for a given entry. + /// </summary> + public byte[] ReadFileData(DatBTreeEntry entry) + { + if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null) + return null; + + lock (_lock) + { + return ReadDatData(entry.FileOffset, (int)entry.FileSize); + } + } + + public byte[] GetFileData(uint fileId) + { + var entry = FindFile(fileId); + return entry != null ? ReadFileData(entry) : null; + } + + /// <summary> + /// Returns sample file IDs from the index for diagnostics. + /// </summary> + public List<uint> GetSampleIds(int maxCount = 20) + { + var ids = new List<uint>(); + foreach (var kvp in _allFiles) + { + ids.Add(kvp.Key); + if (ids.Count >= maxCount) break; + } + return ids; + } + + public void Close() + { + _stream?.Dispose(); + _stream = null; + IsLoaded = false; + _allFiles.Clear(); + } + + public void Dispose() { Close(); } + + private void Log(string msg) + { + string line = $"[DatDB] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 100) DiagLog.Add(line); + } + } + + public class DatBTreeEntry + { + public uint BitFlags; + public uint ObjectId; + public uint FileOffset; // Byte offset into file + public uint FileSize; + } +} diff --git a/Plugins/RynthAi/Raycasting/DungeonLOS.cs b/Plugins/RynthAi/Raycasting/DungeonLOS.cs new file mode 100644 index 0000000..cb84bca --- /dev/null +++ b/Plugins/RynthAi/Raycasting/DungeonLOS.cs @@ -0,0 +1,658 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Extracts dungeon wall geometry from cell.dat Environment files for raycasting. + /// + /// Pipeline: + /// EnvCell (0xXXYY01nn) → EnvironmentId (0x0Dxxxx) + CellStructure index + /// Environment (0x0Dxxxx) → CellStruct at index → Vertices + Polygons + /// Transform polygon vertices by cell position → BoundingVolumes for raycasting + /// + /// Binary formats (from ACE source): + /// SWVertex: ushort numUVs, float3 Origin, float3 Normal, Vec2Duv[numUVs] + /// CVertexArray: int32 type=1, uint32 count, (ushort key + SWVertex)[count] + /// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf, + /// short[numPts] vertexIds, byte[numPts] posUV (if !NoPos), byte[numPts] negUV (if clockwise+!NoNeg) + /// CellStruct: uint32 numPolygons, uint32 numPhysicsPolygons, uint32 numPortals, + /// CVertexArray, Dictionary{ushort,Polygon}[numPolygons], ... + /// </summary> + public class DungeonLOS + { + private DatDatabase _portalDat; + private DatDatabase _cellDat; + + // Cache: EnvironmentId → parsed CellStruct geometry per structure index + private readonly Dictionary<uint, Dictionary<uint, CellGeometry>> _envCache = + new Dictionary<uint, Dictionary<uint, CellGeometry>>(); + + // Cache: landblock → dungeon wall volumes + private readonly Dictionary<uint, List<BoundingVolume>> _wallCache = + new Dictionary<uint, List<BoundingVolume>>(); + + private const int MAX_ENV_CACHE = 50; + private const int MAX_WALL_CACHE = 20; + + public void Initialize(DatDatabase portalDat, DatDatabase cellDat) + { + _portalDat = portalDat; + _cellDat = cellDat; + } + + /// <summary> + /// Gets dungeon wall collision volumes for a landblock. + /// Returns empty list for outdoor-only landblocks. + /// </summary> + public List<BoundingVolume> GetDungeonWalls(uint landblockKey) + { + if (_wallCache.TryGetValue(landblockKey, out var cached)) + return cached; + + var walls = LoadDungeonWalls(landblockKey); + + if (_wallCache.Count >= MAX_WALL_CACHE) + { + foreach (var key in _wallCache.Keys) { _wallCache.Remove(key); break; } + } + _wallCache[landblockKey] = walls; + return walls; + } + + private List<BoundingVolume> LoadDungeonWalls(uint landblockKey) + { + var volumes = new List<BoundingVolume>(); + if (_cellDat == null || _portalDat == null) return volumes; + + uint baseId = landblockKey << 16; + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f; + float globalOffsetY = (landblockKey & 0xFF) * 192.0f; + + int consecutiveMisses = 0; + for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++) + { + uint cellId = baseId | cellNum; + byte[] cellData = _cellDat.GetFileData(cellId); + if (cellData == null) + { + consecutiveMisses++; + if (consecutiveMisses > 10) break; + continue; + } + consecutiveMisses = 0; + if (cellData.Length < 20) continue; + + try + { + var envCell = ParseEnvCellHeader(cellData); + if (envCell == null) continue; + + var cellGeo = GetCellGeometry(envCell.EnvironmentId, envCell.CellStructureIndex); + if (cellGeo == null || cellGeo.Polygons.Count == 0) continue; + + foreach (var poly in cellGeo.Polygons) + { + if (poly.Vertices.Count < 3) continue; + + // Transform vertices to world space + var worldVerts = new List<Vector3>(); + foreach (var localVert in poly.Vertices) + worldVerts.Add(TransformVertex(localVert, envCell, globalOffsetX, globalOffsetY)); + + // Compute AABB from all vertices of the polygon + var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + var max = new Vector3(float.MinValue, float.MinValue, float.MinValue); + foreach (var wv in worldVerts) + { + min = Vector3.Min(min, wv); + max = Vector3.Max(max, wv); + } + + var size = max - min; + if (size.X < 0.01f && size.Y < 0.01f && size.Z < 0.01f) continue; + + // Thicken walls to seal corner gaps. Where two perpendicular walls meet, + // we may be missing one wall's geometry (unparsed CellStruct). + // 0.5 yards ensures the existing walls overlap at corners. + // Portal polygons are excluded so doorways stay open. + // 1.0 yard skin on thin axes — creates 2 yard total thickness. + // Seals corner jut-outs where perpendicular walls meet. + // Portal polygons are excluded so doorways stay open. + float wallSkin = 0.5f; + if (size.X < wallSkin) { min.X -= wallSkin; max.X += wallSkin; } + if (size.Y < wallSkin) { min.Y -= wallSkin; max.Y += wallSkin; } + + volumes.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (min + max) * 0.5f, + Dimensions = max - min, + Min = min, + Max = max, + IsDoor = false + }); + } + } + catch { } + } + + if (volumes.Count > 0) + Log($"Landblock 0x{landblockKey:X4}: {volumes.Count} dungeon wall volumes"); + + return volumes; + } + + private Vector3 TransformVertex(Vector3 local, EnvCellHeader cell, float gx, float gy) + { + Vector3 rotated = RotateByQuat(local, cell.RotW, cell.RotX, cell.RotY, cell.RotZ); + return new Vector3( + rotated.X + cell.PosX + gx, + rotated.Y + cell.PosY + gy, + rotated.Z + cell.PosZ + ); + } + + private Vector3 RotateByQuat(Vector3 v, float qw, float qx, float qy, float qz) + { + float cx = qy * v.Z - qz * v.Y; + float cy = qz * v.X - qx * v.Z; + float cz = qx * v.Y - qy * v.X; + float cx2 = qy * cz - qz * cy; + float cy2 = qz * cx - qx * cz; + float cz2 = qx * cy - qy * cx; + return new Vector3( + v.X + 2f * (qw * cx + cx2), + v.Y + 2f * (qw * cy + cy2), + v.Z + 2f * (qw * cz + cz2) + ); + } + + // =================================================================== + // EnvCell header parsing + // =================================================================== + + private class EnvCellHeader + { + public uint EnvironmentId; + public uint CellStructureIndex; + public float PosX, PosY, PosZ; + public float RotW, RotX, RotY, RotZ; + } + + private EnvCellHeader ParseEnvCellHeader(byte[] data) + { + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint flags = reader.ReadUInt32(); + reader.ReadUInt32(); // duplicate CellId + + byte numSurfaces = reader.ReadByte(); + byte numPortals = reader.ReadByte(); + ushort numVisibleCells = reader.ReadUInt16(); + + ms.Seek(numSurfaces * 2, SeekOrigin.Current); + + ushort envIdShort = reader.ReadUInt16(); + ushort cellStructure = reader.ReadUInt16(); + + return new EnvCellHeader + { + EnvironmentId = 0x0D000000u | envIdShort, + CellStructureIndex = cellStructure, + PosX = reader.ReadSingle(), + PosY = reader.ReadSingle(), + PosZ = reader.ReadSingle(), + RotW = reader.ReadSingle(), + RotX = reader.ReadSingle(), + RotY = reader.ReadSingle(), + RotZ = reader.ReadSingle() + }; + } + } + catch { return null; } + } + + // =================================================================== + // Environment + CellStruct parsing + // =================================================================== + + private class CellGeometry + { + public List<CellPolygon> Polygons = new List<CellPolygon>(); + } + + private class CellPolygon + { + public List<Vector3> Vertices = new List<Vector3>(); + } + + private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex) + { + if (_envCache.TryGetValue(environmentId, out var envCells)) + { + if (envCells.TryGetValue(cellStructIndex, out var cached)) + return cached; + } + + byte[] envData = _portalDat.GetFileData(environmentId); + if (envData == null || envData.Length < 8) return null; + + if (envCells == null) + { + envCells = ParseEnvironment(envData); + if (_envCache.Count >= MAX_ENV_CACHE) + { + foreach (var key in _envCache.Keys) { _envCache.Remove(key); break; } + } + _envCache[environmentId] = envCells; + } + + envCells.TryGetValue(cellStructIndex, out var result); + return result; + } + + private Dictionary<uint, CellGeometry> ParseEnvironment(byte[] data) + { + var result = new Dictionary<uint, CellGeometry>(); + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + + // Dictionary<uint, CellStruct> + uint numCells = reader.ReadUInt32(); + if (numCells > 200) return result; + + for (uint i = 0; i < numCells; i++) + { + if (ms.Position + 4 > ms.Length) break; + uint key = reader.ReadUInt32(); + + var geo = ParseCellStruct(reader, ms); + if (geo != null) + result[key] = geo; + else + { + Log($"Environment 0x{id:X8}: failed parsing CellStruct {i} (key={key}), stopping"); + break; // Stream position unknown — can't continue + } + } + } + } + catch (Exception ex) + { + Log($"Environment parse error: {ex.Message}"); + } + + if (result.Count > 0) + Log($"Environment: parsed {result.Count} CellStructs successfully"); + + return result; + } + + /// <summary> + /// Parses CellStruct: vertices + rendering polygons + portal indices. + /// NOW ALSO SKIPS BSP trees so we can continue to the next CellStruct. + /// </summary> + private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms) + { + var geo = new CellGeometry(); + + try + { + uint numPolygons = reader.ReadUInt32(); + uint numPhysicsPolygons = reader.ReadUInt32(); + uint numPortals = reader.ReadUInt32(); + + if (numPolygons > 5000 || numPhysicsPolygons > 5000) return null; + + var vertices = ParseVertexArray(reader, ms); + if (vertices == null) return null; + + var polygons = ParsePolygons(reader, ms, numPolygons); + if (polygons == null) return null; + + // Read portal polygon indices + var portalIndices = new HashSet<ushort>(); + for (uint p = 0; p < numPortals && ms.Position + 2 <= ms.Length; p++) + portalIndices.Add(reader.ReadUInt16()); + + // Align to 4-byte boundary + long aligned = (ms.Position + 3) & ~3L; + if (aligned <= ms.Length) ms.Position = aligned; + + // BUILD polygon geometry NOW, before BSP skip attempt. + // If BSP skip fails we still have the wall data. + for (int i = 0; i < polygons.Count; i++) + { + var poly = polygons[i]; + if (portalIndices.Contains(poly.Key)) continue; + if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue; + + var cellPoly = new CellPolygon(); + foreach (var vid in poly.VertexIds) + { + if (vertices.ContainsKey(vid)) + cellPoly.Vertices.Add(vertices[vid]); + } + + if (cellPoly.Vertices.Count >= 3) + geo.Polygons.Add(cellPoly); + } + + // Now attempt to skip BSP trees so ParseEnvironment can read the next CellStruct. + // If this fails, we still have this CellStruct's geometry — we just can't parse further. + bool canContinue = true; + + // Skip CellBSP + if (!SkipBSPTree(reader, ms, BSPTreeType.Cell)) + canContinue = false; + + // Skip PhysicsPolygons + if (canContinue && !SkipPolygons(reader, ms, numPhysicsPolygons)) + canContinue = false; + + // Skip PhysicsBSP + if (canContinue && !SkipBSPTree(reader, ms, BSPTreeType.Physics)) + canContinue = false; + + // Skip optional DrawingBSP + if (canContinue && ms.Position + 4 <= ms.Length) + { + uint hasDrawingBSP = reader.ReadUInt32(); + if (hasDrawingBSP != 0) + { + if (!SkipBSPTree(reader, ms, BSPTreeType.Drawing)) + canContinue = false; + } + } + + // Final alignment + if (canContinue) + { + aligned = (ms.Position + 3) & ~3L; + if (aligned <= ms.Length) ms.Position = aligned; + } + + // Return geometry. If canContinue is false, ParseEnvironment will break + // at the next iteration (stream position wrong), but we keep this CellStruct's data. + return geo; + } + catch + { + return geo.Polygons.Count > 0 ? geo : null; + } + } + + // =================================================================== + // BSP Tree Skipping — matches ACE BSPNode/BSPLeaf exactly + // =================================================================== + + private enum BSPTreeType { Cell, Physics, Drawing } + + // ACE's uint32 constants for BSP node types (read as LE uint32, stored reversed in file) + private const uint BSP_PORT = 0x504F5254; + private const uint BSP_LEAF = 0x4C454146; + private const uint BSP_BPnn = 0x42506E6E; + private const uint BSP_BPIn = 0x4250496E; + private const uint BSP_BpIN = 0x4270494E; + private const uint BSP_BpnN = 0x42706E4E; + private const uint BSP_BPIN = 0x4250494E; + private const uint BSP_BPnN = 0x42506E4E; + + private bool SkipBSPTree(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + return SkipBSPNode(reader, ms, treeType); + } + + private bool SkipBSPNode(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + if (ms.Position + 4 > ms.Length) return false; + uint typeTag = reader.ReadUInt32(); + + if (typeTag == BSP_LEAF) + { + return SkipBSPLeaf(reader, ms, treeType); + } + + if (typeTag == BSP_PORT) + { + // Portal node — same as leaf for our purposes + return SkipBSPLeaf(reader, ms, treeType); + } + + // Internal node: read splitting plane (float3 normal + float dist = 16 bytes) + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // Read children based on type — matches ACE's switch exactly + switch (typeTag) + { + case BSP_BPnn: + case BSP_BPIn: + // Pos child only + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + case BSP_BpIN: + case BSP_BpnN: + // Neg child only + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + case BSP_BPIN: + case BSP_BPnN: + // Both children: Pos then Neg + if (!SkipBSPNode(reader, ms, treeType)) return false; + if (!SkipBSPNode(reader, ms, treeType)) return false; + break; + default: + return false; // Unknown type + } + + // Cell BSP internal nodes have NO sphere — done + if (treeType == BSPTreeType.Cell) + return true; + + // Physics and Drawing: read Sphere (float3 center + float radius = 16 bytes) + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // Physics: done after sphere + if (treeType == BSPTreeType.Physics) + return true; + + // Drawing: also read InPolys (uint32 count + ushort[count]) + if (ms.Position + 4 > ms.Length) return false; + uint numPolys = reader.ReadUInt32(); + if (numPolys > 100000) return false; + long skip = numPolys * 2L; // ushort per poly + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + + return true; + } + + /// <summary> + /// BSPLeaf: uint32 type + int32 leafIndex + (Physics only: int32 solid + Sphere(16) + uint32 numPolys + ushort[numPolys]) + /// Note: Physics leaf ALWAYS reads Sphere even when solid=0 (per ACE source). + /// Cell and Drawing leaves are just type + leafIndex. + /// </summary> + private bool SkipBSPLeaf(BinaryReader reader, MemoryStream ms, BSPTreeType treeType) + { + // Type tag already read by caller. Read leafIndex. + if (ms.Position + 4 > ms.Length) return false; + reader.ReadInt32(); // leafIndex + + if (treeType == BSPTreeType.Physics) + { + // int32 Solid + if (ms.Position + 4 > ms.Length) return false; + reader.ReadInt32(); + + // Sphere: ALWAYS read (16 bytes), even when solid=0 + if (ms.Position + 16 > ms.Length) return false; + ms.Seek(16, SeekOrigin.Current); + + // uint32 numPolys + ushort[numPolys] + if (ms.Position + 4 > ms.Length) return false; + uint numPolys = reader.ReadUInt32(); + if (numPolys > 100000) return false; + long skip = numPolys * 2L; + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + } + // Cell and Drawing leaves: nothing more after leafIndex + + return true; + } + + /// <summary> + /// Skips a Dictionary{ushort, Polygon} block — same format as ParsePolygons + /// but doesn't store results. + /// </summary> + private bool SkipPolygons(BinaryReader reader, MemoryStream ms, uint count) + { + for (uint i = 0; i < count; i++) + { + if (ms.Position + 12 > ms.Length) return false; + ushort polyKey = reader.ReadUInt16(); + byte numPts = reader.ReadByte(); + byte stippling = reader.ReadByte(); + int sidesType = reader.ReadInt32(); + ms.Seek(4, SeekOrigin.Current); // posSurf + negSurf + + if (numPts == 0 || numPts > 50) return false; + + // Vertex IDs + long vertBytes = numPts * 2L; + if (ms.Position + vertBytes > ms.Length) return false; + ms.Seek(vertBytes, SeekOrigin.Current); + + // PosUV + if ((stippling & 0x04) == 0) + { + if (ms.Position + numPts > ms.Length) return false; + ms.Seek(numPts, SeekOrigin.Current); + } + + // NegUV + if (sidesType == 2 && (stippling & 0x08) == 0) + { + if (ms.Position + numPts > ms.Length) return false; + ms.Seek(numPts, SeekOrigin.Current); + } + } + return true; + } + + /// <summary> + /// CVertexArray: int32 type(=1) + uint32 count + (ushort key + SWVertex)[count] + /// SWVertex: ushort numUVs + float3 Origin(12) + float3 Normal(12) + numUVs × 8 bytes + /// </summary> + private Dictionary<ushort, Vector3> ParseVertexArray(BinaryReader reader, MemoryStream ms) + { + var verts = new Dictionary<ushort, Vector3>(); + + int vertexType = reader.ReadInt32(); + if (vertexType != 1) return null; + + uint numVerts = reader.ReadUInt32(); + if (numVerts > 50000) return null; + + for (uint i = 0; i < numVerts; i++) + { + if (ms.Position + 28 > ms.Length) break; // key(2) + numUVs(2) + origin(12) + normal(12) + ushort key = reader.ReadUInt16(); + ushort numUVs = reader.ReadUInt16(); + + float ox = reader.ReadSingle(); + float oy = reader.ReadSingle(); + float oz = reader.ReadSingle(); + reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // normal + + long uvBytes = numUVs * 8L; + if (uvBytes > 0 && ms.Position + uvBytes <= ms.Length) + ms.Seek(uvBytes, SeekOrigin.Current); + + verts[key] = new Vector3(ox, oy, oz); + } + + return verts.Count > 0 ? verts : null; + } + + /// <summary> + /// Dictionary{ushort, Polygon}: count × (ushort key + Polygon) + /// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf, + /// short[numPts] vertexIds, optional UV index arrays + /// </summary> + private List<ParsedPolygon> ParsePolygons(BinaryReader reader, MemoryStream ms, uint count) + { + var polys = new List<ParsedPolygon>(); + + for (uint i = 0; i < count; i++) + { + if (ms.Position + 12 > ms.Length) return polys; // key(2) + header(10 min) + ushort polyKey = reader.ReadUInt16(); + + byte numPts = reader.ReadByte(); + byte stippling = reader.ReadByte(); + int sidesType = reader.ReadInt32(); + short posSurf = reader.ReadInt16(); + short negSurf = reader.ReadInt16(); + + if (numPts == 0 || numPts > 50) return polys; + + var poly = new ParsedPolygon { Key = polyKey, VertexIds = new List<ushort>() }; + + for (int v = 0; v < numPts; v++) + { + if (ms.Position + 2 > ms.Length) return polys; + poly.VertexIds.Add((ushort)reader.ReadInt16()); + } + + // Skip PosUVIndices (byte per point) unless NoPos flag (0x04) + if ((stippling & 0x04) == 0) + { + if (ms.Position + numPts > ms.Length) return polys; + ms.Seek(numPts, SeekOrigin.Current); + } + + // Skip NegUVIndices if Clockwise(2) and not NoNeg(0x08) + if (sidesType == 2 && (stippling & 0x08) == 0) + { + if (ms.Position + numPts > ms.Length) return polys; + ms.Seek(numPts, SeekOrigin.Current); + } + + polys.Add(poly); + } + + return polys; + } + + private class ParsedPolygon + { + public ushort Key; + public List<ushort> VertexIds; + } + + public void FlushCache() + { + _wallCache.Clear(); + _envCache.Clear(); + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}"); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthAi/Raycasting/GeometryLoader.cs new file mode 100644 index 0000000..dada214 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/GeometryLoader.cs @@ -0,0 +1,1112 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Loads collision geometry from Asheron's Call's .dat files for raycasting. + /// + /// Pipeline: + /// 1. cell.dat → LandblockInfo (0xXXYYFFFF) → list of static objects + placements + /// 2. portal.dat → Setup (0x02xxxxxx) → bounding sphere + collision volumes + /// 3. portal.dat → GfxObj (0x01xxxxxx) → vertex AABB (fallback if Setup has no bounds) + /// 4. Transform collision volumes by placement frame → BoundingVolume list for raycasting + /// </summary> + public class GeometryLoader : IDisposable + { + private DatDatabase _portalDat; + private DatDatabase _cellDat; + private bool _initialized; + + /// <summary> + /// Public accessor for the cell.dat database, used by DungeonLOS. + /// </summary> + public DatDatabase CellDat => _cellDat; + + /// <summary> + /// Public accessor for the portal.dat database, used by DungeonLOS. + /// </summary> + public DatDatabase PortalDat => _portalDat; + + /// <summary> + /// Cache for loaded landblock geometry. + /// Key: Landblock ID (upper 16 bits, e.g., 0xXXYY), Value: BoundingVolumes. + /// </summary> + private readonly Dictionary<uint, List<BoundingVolume>> _landblockCache = + new Dictionary<uint, List<BoundingVolume>>(); + + /// <summary> + /// Cache for parsed Setup files to avoid re-reading portal.dat. + /// </summary> + private readonly Dictionary<uint, SetupInfo> _setupCache = + new Dictionary<uint, SetupInfo>(); + + private const int MAX_LANDBLOCK_CACHE = 20; + private const int MAX_SETUP_CACHE = 1000; + + /// <summary> + /// Scatter system for procedurally placed terrain objects (trees, rocks, etc.) + /// </summary> + private ScatterSystem _scatterSystem; + + /// <summary> + /// Dungeon wall geometry extractor. + /// </summary> + private DungeonLOS _dungeonLOS; + + // Statistics + public int LandblocksCached => _landblockCache.Count; + public int SetupsCached => _setupCache.Count; + public bool IsInitialized => _initialized; + public string StatusMessage { get; private set; } = "Not initialized"; + public List<string> DiagLog { get; } = new List<string>(); + + /// <summary> + /// Initializes the geometry loader by opening the .dat files. + /// Call this once during plugin startup. + /// </summary> + public bool Initialize(string acFolderPath = null) + { + try + { + string folder = acFolderPath ?? FindACFolder(); + if (string.IsNullOrEmpty(folder)) + { + StatusMessage = "AC installation folder not found"; + Log(StatusMessage); + return false; + } + + Log($"Using AC folder: {folder}"); + + // Find portal.dat — try all known filenames + string portalPath = FindDatFile(folder, new[] { + "client_portal.dat", "portal.dat", "client_portal_dat" + }); + string cellPath = FindDatFile(folder, new[] { + "client_cell_1.dat", "cell.dat", "client_cell_1_dat" + }); + + if (portalPath == null) + { + // List what files ARE in the folder for diagnostics + string files = ""; + try + { + foreach (var f in Directory.GetFiles(folder, "*.dat")) + files += Path.GetFileName(f) + ", "; + } + catch { } + StatusMessage = $"No portal.dat found in {folder}. Files: {files}"; + Log(StatusMessage); + return false; + } + + if (cellPath == null) + { + StatusMessage = $"No cell.dat found in {folder}"; + Log(StatusMessage); + return false; + } + + Log($"Portal: {portalPath}"); + Log($"Cell: {cellPath}"); + + // Open portal.dat + _portalDat = new DatDatabase(); + if (!_portalDat.Open(portalPath)) + { + StatusMessage = $"Failed to open {Path.GetFileName(portalPath)}"; + // Include ALL diagnostic info so user can report it + foreach (var msg in _portalDat.DiagLog) + Log(msg); + if (_portalDat.DiagLog.Count > 0) + StatusMessage += " — " + string.Join(" | ", _portalDat.DiagLog); + Log(StatusMessage); + return false; + } + + // Open cell.dat + _cellDat = new DatDatabase(); + if (!_cellDat.Open(cellPath)) + { + StatusMessage = $"Failed to open {Path.GetFileName(cellPath)}"; + if (_cellDat.DiagLog.Count > 0) + StatusMessage += " — " + _cellDat.DiagLog[_cellDat.DiagLog.Count - 1]; + Log(StatusMessage); + _portalDat.Dispose(); + return false; + } + + _initialized = true; + StatusMessage = $"portal={_portalDat.RecordCount} entries (BS={_portalDat.BlockSize}), " + + $"cell={_cellDat.RecordCount} entries (BS={_cellDat.BlockSize})"; + Log($"SUCCESS: {StatusMessage}"); + Log($"Portal root=0x{_portalDat.BTreeRoot:X8}, Cell root=0x{_cellDat.BTreeRoot:X8}"); + + // Initialize scatter system for procedural terrain objects + _scatterSystem = new ScatterSystem(); + if (_scatterSystem.Initialize(_portalDat, _cellDat)) + Log("Scatter system initialized"); + else + Log("Scatter system failed to initialize (tree/rock LOS may be limited)"); + + // Initialize dungeon wall geometry extractor + _dungeonLOS = new DungeonLOS(); + _dungeonLOS.Initialize(_portalDat, _cellDat); + Log("Dungeon wall system initialized"); + + // Copy scatter diagnostic logs + if (_scatterSystem.DiagLog.Count > 0) + foreach (var line in _scatterSystem.DiagLog) + Log("[Scatter] " + line); + + return true; + } + catch (Exception ex) + { + StatusMessage = $"Init error: {ex.Message}"; + Log(StatusMessage); + return false; + } + } + + /// <summary> + /// Finds a .dat file by trying multiple possible filenames. + /// </summary> + private string FindDatFile(string folder, string[] names) + { + foreach (var name in names) + { + string path = Path.Combine(folder, name); + if (File.Exists(path)) + return path; + } + return null; + } + + /// <summary> + /// Retrieves collision geometry for a landblock AND its 8 neighbors (3x3 grid). + /// This ensures obstacles near landblock boundaries are always loaded. + /// The landblockId should be the Decal Landcell value (format: 0xXXYYnnnn). + /// </summary> + public List<BoundingVolume> GetLandblockGeometry(uint landcellId) + { + uint landblockKey = (landcellId >> 16) & 0xFFFF; + uint cellPart = landcellId & 0xFFFF; + bool isDungeon = cellPart >= 0x0100; + + if (_landblockCache.TryGetValue(landblockKey, out var cached)) + return cached; + + var volumes = new List<BoundingVolume>(); + + if (isDungeon) + { + // Dungeons: only load the current landblock (walls contain everything) + var lbVolumes = LoadLandblockGeometry(landblockKey); + volumes.AddRange(lbVolumes); + } + else + { + // Outdoors: load 3×3 grid for boundary coverage + uint blockX = (landblockKey >> 8) & 0xFF; + uint blockY = landblockKey & 0xFF; + + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + int nx = (int)blockX + dx; + int ny = (int)blockY + dy; + if (nx < 0 || nx > 0xFE || ny < 0 || ny > 0xFE) continue; + + uint neighborKey = (uint)((nx << 8) | ny); + var neighborVolumes = LoadLandblockGeometry(neighborKey); + volumes.AddRange(neighborVolumes); + } + } + } + + Log($"{(isDungeon ? "Dungeon" : "3x3 grid")} for 0x{landblockKey:X4}: {volumes.Count} total collision volumes"); + + if (_landblockCache.Count >= MAX_LANDBLOCK_CACHE) + EvictOldestLandblock(); + + _landblockCache[landblockKey] = volumes; + return volumes; + } + + /// <summary> + /// Loads collision geometry for a landblock from cell.dat and portal.dat. + /// </summary> + private List<BoundingVolume> LoadLandblockGeometry(uint landblockKey) + { + var volumes = new List<BoundingVolume>(); + + if (!_initialized) + { + Log("LoadLandblockGeometry called but not initialized!"); + return volumes; + } + + try + { + Log($"--- Loading landblock 0x{landblockKey:X4} ---"); + + // Dump sample IDs from cell.dat root to understand the ID format (first time only) + if (_landblockCache.Count <= 1 && _cellDat.IsLoaded) + { + DumpSampleCellIds(); + } + + // LandblockInfo is always 0xXXYYFFFE — this is where static objects live + // 0xXXYYFFFF is just terrain heightmap data (no objects) + uint landblockInfoId = (landblockKey << 16) | 0xFFFE; + + byte[] landblockData = _cellDat.GetFileData(landblockInfoId); + uint foundId = landblockInfoId; + + if (landblockData == null || landblockData.Length <= 8) + { + Log($"No LandblockInfo found for 0x{landblockInfoId:X8}"); + + // Some landblocks legitimately have no FFFE entry (empty ocean tiles etc.) + landblockData = null; + } + + if (landblockData != null) + { + DumpBytes(landblockData, $"Landblock 0x{foundId:X8}"); + int objectCount = ParseLandblockObjects(landblockData, landblockKey, volumes); + Log($"Parsed: {objectCount} static objects -> {volumes.Count} collision volumes"); + } + else + { + Log($"No LandblockInfo data for 0x{landblockKey:X4}"); + + // Pull search diagnostics from cell.dat + foreach (var msg in _cellDat.DiagLog) + { + if (msg.Contains("FindFile") || msg.Contains("depth=") || msg.Contains("Block[") || msg.Contains("Winner")) + Log($" cell.dat: {msg}"); + } + } + + // Also try loading indoor cells (static objects in dungeon rooms) + LoadIndoorCells(landblockKey, volumes); + + // Load dungeon wall geometry (EnvCell → Environment → CellStruct polygons) + if (_dungeonLOS != null) + { + var wallVolumes = _dungeonLOS.GetDungeonWalls(landblockKey); + volumes.AddRange(wallVolumes); + } + + // Load scatter objects (trees, rocks) — always load for outdoor terrain + if (_scatterSystem != null && _scatterSystem.IsInitialized) + { + var scatterVolumes = _scatterSystem.GetScatterVolumes(landblockKey, this); + volumes.AddRange(scatterVolumes); + } + + Log($"Landblock 0x{landblockKey:X4}: TOTAL {volumes.Count} collision volumes"); + } + catch (Exception ex) + { + Log($"Error loading landblock 0x{landblockKey:X4}: {ex.Message}"); + } + + return volumes; + } + + /// <summary> + /// Dumps sample file IDs from the cell.dat B-tree root node for diagnostics. + /// This tells us what format the IDs use. + /// </summary> + private bool _cellIdsDumped = false; + private void DumpSampleCellIds() + { + if (_cellIdsDumped) return; + _cellIdsDumped = true; + + try + { + Log("=== Sampling cell.dat file IDs ==="); + + var sampleIds = _cellDat.GetSampleIds(30); + if (sampleIds.Count > 0) + { + string idList = $"Cell.dat samples ({sampleIds.Count}): "; + foreach (uint id in sampleIds) + idList += $"0x{id:X8} "; + Log(idList); + + uint first = sampleIds[0]; + uint last = sampleIds[sampleIds.Count - 1]; + Log($"ID range: 0x{first:X8} to 0x{last:X8}"); + Log($"First: high=0x{(first >> 16):X4} low=0x{(first & 0xFFFF):X4}"); + } + else + { + Log("WARNING: No sample IDs from cell.dat B-tree!"); + } + + var portalSamples = _portalDat.GetSampleIds(10); + if (portalSamples.Count > 0) + { + string pList = "Portal.dat samples: "; + foreach (uint id in portalSamples) + pList += $"0x{id:X8} "; + Log(pList); + } + } + catch (Exception ex) + { + Log($"Cell sampling error: {ex.Message}"); + } + } + + /// <summary> + /// Dumps first bytes of data for diagnostics. + /// </summary> + private void DumpBytes(byte[] data, string label) + { + int len = Math.Min(64, data.Length); + string vals = $"{label} uint32s: "; + for (int i = 0; i < len; i += 4) + { + uint v = BitConverter.ToUInt32(data, i); + vals += $"[{i}]=0x{v:X8} "; + if (i == 28) + { + Log(vals); + vals = $"{label} +32: "; + } + } + Log(vals); + } + + /// <summary> + /// Parses static object placements from a LandblockInfo (0xFFFE) file. + /// + /// Exact format from ACE.DatLoader.FileTypes.LandblockInfo: + /// uint32 Id (file ID, e.g. 0xAAB3FFFE) + /// uint32 NumCells (number of EnvCells in landblock) + /// uint32 NumObjects (count of Stab entries) + /// Stab[NumObjects]: (static object placements) + /// uint32 Id (Setup/model ID, e.g. 0x02xxxxxx or 0x01xxxxxx) + /// Frame: (7 floats = 28 bytes) + /// float OriginX, OriginY, OriginZ + /// float RotW, RotX, RotY, RotZ + /// ushort NumBuildings + /// ushort PackMask + /// BuildInfo[NumBuildings]: + /// uint32 ModelId + /// Frame (7 floats) + /// uint32 NumLeaves + /// List{CBldPortal} Portals + /// if (PackMask & 1): + /// PackedHashTable RestrictionTables + /// + /// Each Stab = 32 bytes (4 + 28). NO InstanceId field. + /// </summary> + private int ParseLandblockObjects(byte[] data, uint landblockKey, List<BoundingVolume> volumes) + { + if (data == null || data.Length < 12) + { + Log($"Landblock data too small ({data?.Length ?? 0} bytes)"); + return 0; + } + + // --- Parse header --- + // [0] uint32 Id + // [4] uint32 NumCells + // [8] uint32 NumObjects (count for List<Stab>) + uint fileId = BitConverter.ToUInt32(data, 0); + uint numCells = BitConverter.ToUInt32(data, 4); + uint numObjects = BitConverter.ToUInt32(data, 8); + + Log($"LandblockInfo 0x{fileId:X8}: NumCells={numCells}, NumObjects={numObjects}"); + + if (numObjects == 0) + { + Log("No static objects in this landblock"); + return 0; + } + + if (numObjects > 5000) + { + Log($"Suspicious NumObjects={numObjects}, clamping to 5000"); + numObjects = 5000; + } + + // --- Parse Stab entries --- + // Each Stab = uint32 Id (4) + Frame (7 floats = 28) = 32 bytes + const int STAB_SIZE = 32; // 4 + 28 + int stabStart = 12; // After Id + NumCells + NumObjects + long neededBytes = stabStart + (long)numObjects * STAB_SIZE; + + if (neededBytes > data.Length) + { + Log($"Data too small for {numObjects} Stabs: need {neededBytes}, have {data.Length}"); + // Parse as many as we can fit + numObjects = (uint)((data.Length - stabStart) / STAB_SIZE); + if (numObjects == 0) return 0; + Log($"Adjusted to {numObjects} Stabs"); + } + + // Global offset for world coordinates + uint blockX = (landblockKey >> 8) & 0xFF; + uint blockY = landblockKey & 0xFF; + float globalOffsetX = blockX * 192.0f; + float globalOffsetY = blockY * 192.0f; + + int parsedCount = 0; + + for (uint i = 0; i < numObjects; i++) + { + int off = stabStart + (int)i * STAB_SIZE; + if (off + STAB_SIZE > data.Length) break; + + // Stab.Unpack: Id then Frame + uint stabId = BitConverter.ToUInt32(data, off); + + int frameOff = off + 4; + float px = BitConverter.ToSingle(data, frameOff); + float py = BitConverter.ToSingle(data, frameOff + 4); + float pz = BitConverter.ToSingle(data, frameOff + 8); + float rw = BitConverter.ToSingle(data, frameOff + 12); + float rx = BitConverter.ToSingle(data, frameOff + 16); + float ry = BitConverter.ToSingle(data, frameOff + 20); + float rz = BitConverter.ToSingle(data, frameOff + 24); + + // Validate position + if (float.IsNaN(px) || float.IsInfinity(px) || Math.Abs(px) > 50000) + { + Log($" Obj[{i}]: SKIPPED invalid position ({px},{py},{pz})"); + continue; + } + + // Log first few for verification + if (parsedCount < 5) + Log($" Obj[{i}]: Id=0x{stabId:X8} Pos=({px:F1},{py:F1},{pz:F1}) Rot=({rw:F3},{rx:F3},{ry:F3},{rz:F3})"); + + var frame = new Frame + { + OriginX = px, OriginY = py, OriginZ = pz, + RotW = rw, RotX = rx, RotY = ry, RotZ = rz + }; + + var setupVolumes = GetSetupBoundingVolumes(stabId); + foreach (var vol in setupVolumes) + { + var transformed = TransformVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + + parsedCount++; + } + + // --- Also parse Buildings --- + int buildingOffset = stabStart + (int)numObjects * STAB_SIZE; + if (buildingOffset + 4 <= data.Length) + { + ushort numBuildings = BitConverter.ToUInt16(data, buildingOffset); + ushort packMask = BitConverter.ToUInt16(data, buildingOffset + 2); + Log($"Buildings: {numBuildings}, PackMask=0x{packMask:X4}"); + + int bOff = buildingOffset + 4; + for (int b = 0; b < numBuildings && bOff + 36 <= data.Length; b++) + { + // BuildInfo: uint32 ModelId + Frame(28) + uint32 NumLeaves + List<CBldPortal> + uint modelId = BitConverter.ToUInt32(data, bOff); + float bpx = BitConverter.ToSingle(data, bOff + 4); + float bpy = BitConverter.ToSingle(data, bOff + 8); + float bpz = BitConverter.ToSingle(data, bOff + 12); + float brw = BitConverter.ToSingle(data, bOff + 16); + float brx = BitConverter.ToSingle(data, bOff + 20); + float bry = BitConverter.ToSingle(data, bOff + 24); + float brz = BitConverter.ToSingle(data, bOff + 28); + + if (b < 3) + Log($" Building[{b}]: Model=0x{modelId:X8} Pos=({bpx:F1},{bpy:F1},{bpz:F1})"); + + var bFrame = new Frame + { + OriginX = bpx, OriginY = bpy, OriginZ = bpz, + RotW = brw, RotX = brx, RotY = bry, RotZ = brz + }; + + var bVolumes = GetSetupBoundingVolumes(modelId); + foreach (var vol in bVolumes) + { + var transformed = TransformVolume(vol, bFrame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + + // Skip past: ModelId(4) + Frame(28) + NumLeaves(4) = 36 + uint numLeaves = BitConverter.ToUInt32(data, bOff + 32); + bOff += 36; + + // Skip portal list: uint32 count, then count × portal entries + if (bOff + 4 <= data.Length) + { + uint numPortals = BitConverter.ToUInt32(data, bOff); + bOff += 4; + // Each CBldPortal is variable size; skip conservatively + // We got the building model, which is the main thing we need + // Portal data is complex (flags + cell lists); skip the rest + // for now by breaking out of building loop if we can't parse further + for (uint p = 0; p < numPortals && bOff + 8 <= data.Length; p++) + { + ushort portalFlags = BitConverter.ToUInt16(data, bOff); + bOff += 2; + // Skip remaining portal data (OtherCellId + OtherPortalId + StabList) + // This is complex; break if we hit something unexpected + if (bOff + 6 <= data.Length) + { + bOff += 6; // Approximate skip for simple portal entries + } + } + } + + parsedCount++; + } + } + + if (parsedCount == 0) + Log($"No static objects found in landblock data ({data.Length} bytes)"); + + return parsedCount; + } + + /// <summary> + /// Loads static objects from the LandblockInfo entry in cell.dat. + /// These are outdoor objects: buildings, trees, rocks, terrain features. + /// </summary> + private void LoadOutdoorObjects(uint landblockInfoId, uint landblockKey, List<BoundingVolume> volumes) + { + // This method is now unused - logic moved into LoadLandblockGeometry + // Kept for API compatibility + } + + /// <summary> + /// Loads static objects from dungeon/interior cells in cell.dat. + /// Indoor cells are numbered 0xXXYY0100 through 0xXXYYFFFD. + /// Uses ACE's EnvCell format for correct parsing. + /// </summary> + private void LoadIndoorCells(uint landblockKey, List<BoundingVolume> volumes) + { + uint baseId = landblockKey << 16; + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f; + float globalOffsetY = (landblockKey & 0xFF) * 192.0f; + + // EnvCells start at 0x0100 + int consecutiveMisses = 0; + for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++) + { + uint cellId = baseId | cellNum; + byte[] data = _cellDat.GetFileData(cellId); + if (data == null) + { + consecutiveMisses++; + if (consecutiveMisses > 10) break; // No more cells after 10 gaps + continue; + } + consecutiveMisses = 0; + if (data.Length < 20) continue; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint flags = reader.ReadUInt32(); + reader.ReadUInt32(); // duplicate CellId + + byte numSurfaces = reader.ReadByte(); + byte numPortals = reader.ReadByte(); + ushort numVisibleCells = reader.ReadUInt16(); + + // Skip surfaces + for (int i = 0; i < numSurfaces; i++) + reader.ReadUInt16(); + + ushort envId = reader.ReadUInt16(); + ushort cellStructure = reader.ReadUInt16(); + + // Cell Position (Frame) + float cellX = reader.ReadSingle(); + float cellY = reader.ReadSingle(); + float cellZ = reader.ReadSingle(); + reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // rotation + + // Skip portals (8 bytes each) + for (int i = 0; i < numPortals; i++) + { + if (ms.Position + 8 > ms.Length) break; + reader.ReadUInt64(); // 4 × ushort + } + + // Skip visible cells + for (int i = 0; i < numVisibleCells; i++) + { + if (ms.Position + 2 > ms.Length) break; + reader.ReadUInt16(); + } + + // Read static objects if present (flag 0x02 = HasStaticObjs) + if ((flags & 0x02) != 0 && ms.Position + 4 <= ms.Length) + { + uint numStabs = reader.ReadUInt32(); + if (numStabs > 500) numStabs = 500; + + for (uint i = 0; i < numStabs; i++) + { + if (ms.Position + 32 > ms.Length) break; + + uint setupId = reader.ReadUInt32(); + float px = reader.ReadSingle(); + float py = reader.ReadSingle(); + float pz = reader.ReadSingle(); + float rw = reader.ReadSingle(); + float rx = reader.ReadSingle(); + float ry = reader.ReadSingle(); + float rz = reader.ReadSingle(); + + var frame = new Frame + { + // Static object position is in cell-local space + // Cell position is already in landblock-local space + OriginX = px + cellX, + OriginY = py + cellY, + OriginZ = pz + cellZ, + RotW = rw, RotX = rx, RotY = ry, RotZ = rz + }; + + var objVolumes = GetSetupBoundingVolumes(setupId); + foreach (var vol in objVolumes) + { + var transformed = TransformVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + volumes.Add(transformed); + } + } + } + } + } + catch { } + } + } + + /// <summary> + /// Retrieves bounding volumes for a model ID from portal.dat. + /// Handles both 0x02xxxxxx (Setup) and 0x01xxxxxx (GfxObj) IDs. + /// Falls back through: collision spheres → cylinders → SortingSphere → Height+Radius cylinder → GfxObj AABB. + /// </summary> + private int _setupLogCount = 0; + + /// <summary> + /// Public accessor for use by ScatterSystem. + /// </summary> + public List<BoundingVolume> GetSetupBoundingVolumesPublic(uint modelId) + { + return GetSetupBoundingVolumes(modelId); + } + + private List<BoundingVolume> GetSetupBoundingVolumes(uint modelId) + { + var result = new List<BoundingVolume>(); + + // If it's a GfxObj (0x01xxxxxx), try to get bounds from it directly + if ((modelId & 0xFF000000) == 0x01000000) + { + var gfxVol = GetGfxObjBounds(modelId); + if (gfxVol != null) + { + result.Add(gfxVol); + } + else + { + // GfxObj parse failed — use a default building bounding box. + // Buildings are solid structures; better to have an approximate volume + // than no volume (which lets rays pass through walls). + float defaultR = 5.0f; + float defaultH = 8.0f; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = new Vector3(0, 0, defaultH * 0.5f), + Dimensions = new Vector3(defaultR * 2, defaultR * 2, defaultH), + Min = new Vector3(-defaultR, -defaultR, 0), + Max = new Vector3(defaultR, defaultR, defaultH), + IsDoor = false + }); + } + return result; + } + + // Check cache first + if (!_setupCache.TryGetValue(modelId, out var setup)) + { + // Load and parse the Setup file + byte[] data = _portalDat.GetFileData(modelId); + if (data == null) + { + if (_setupLogCount < 5) + { + Log($"Setup 0x{modelId:X8}: NOT FOUND in portal.dat"); + _setupLogCount++; + } + return result; + } + + if (_setupLogCount < 5) + { + Log($"Setup 0x{modelId:X8}: {data.Length} bytes loaded"); + _setupLogCount++; + } + + setup = new SetupInfo(); + if (!setup.Unpack(data)) + { + if (_setupLogCount < 10) + Log($"Setup 0x{modelId:X8}: PARSE FAILED"); + + // Even if parse failed, try GfxObj from Parts if we got them + if (setup.PartIds != null && setup.PartIds.Length > 0) + { + var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + if (gfxVol != null) + result.Add(gfxVol); + } + return result; + } + + if (_setupLogCount < 10) + Log($"Setup 0x{modelId:X8}: {setup.NumParts} parts, radius={setup.BoundingSphereRadius:F2}, " + + $"{setup.Spheres.Count} spheres, {setup.Cylinders.Count} cylinders"); + + // Cache it + if (_setupCache.Count >= MAX_SETUP_CACHE) + _setupCache.Clear(); + _setupCache[modelId] = setup; + } + + // Priority 1: Use collision spheres from Setup + if (setup.Spheres.Count > 0) + { + foreach (var sphere in setup.Spheres) + { + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = sphere.Center, + Dimensions = new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + Min = sphere.Center - new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + Max = sphere.Center + new Vector3(sphere.Radius, sphere.Radius, sphere.Radius), + IsDoor = false + }); + } + return result; + } + + // Priority 2: Use collision cylinders from Setup + if (setup.Cylinders.Count > 0) + { + foreach (var cyl in setup.Cylinders) + { + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Cylinder, + Center = new Vector3( + cyl.BottomCenter.X, + cyl.BottomCenter.Y, + cyl.BottomCenter.Z + cyl.Height * 0.5f + ), + Dimensions = new Vector3(cyl.Radius, cyl.Radius, cyl.Height), + Min = new Vector3( + cyl.BottomCenter.X - cyl.Radius, + cyl.BottomCenter.Y - cyl.Radius, + cyl.BottomCenter.Z + ), + Max = new Vector3( + cyl.BottomCenter.X + cyl.Radius, + cyl.BottomCenter.Y + cyl.Radius, + cyl.BottomCenter.Z + cyl.Height + ), + IsDoor = false + }); + } + return result; + } + + // Priority 3: Use bounding sphere from Setup + if (setup.BoundingSphereRadius > 0.1f) + { + float r = setup.BoundingSphereRadius; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = setup.BoundingSphereCenter, + Dimensions = new Vector3(r, r, r), + Min = setup.BoundingSphereCenter - new Vector3(r, r, r), + Max = setup.BoundingSphereCenter + new Vector3(r, r, r), + IsDoor = false + }); + return result; + } + + // Priority 4: Use Height + Radius from Setup to create a cylinder + if (setup.Radius > 0.1f && setup.Height > 0.1f) + { + float r = setup.Radius; + float h = setup.Height; + result.Add(new BoundingVolume + { + Type = BoundingVolume.VolumeType.Cylinder, + Center = new Vector3(0, 0, h * 0.5f), + Dimensions = new Vector3(r, r, h), + Min = new Vector3(-r, -r, 0), + Max = new Vector3(r, r, h), + IsDoor = false + }); + return result; + } + + // Priority 5: Fall back to GfxObj bounding data from first part + if (setup.PartIds != null && setup.PartIds.Length > 0) + { + var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + if (gfxVol != null) + result.Add(gfxVol); + } + + return result; + } + + /// <summary> + /// Loads a GfxObj from portal.dat and extracts its bounding volume. + /// </summary> + private BoundingVolume GetGfxObjBounds(uint gfxObjId) + { + byte[] data = _portalDat.GetFileData(gfxObjId); + if (data == null) return null; + + var gfxObj = new GfxObjInfo(); + if (!gfxObj.Unpack(data) || !gfxObj.HasBounds) + return null; + + if (gfxObj.SortingRadius > 0.1f) + { + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = gfxObj.SortingCenter, + Dimensions = new Vector3(gfxObj.SortingRadius, gfxObj.SortingRadius, gfxObj.SortingRadius), + Min = gfxObj.BoundsMin, + Max = gfxObj.BoundsMax, + IsDoor = false + }; + } + + // Use AABB from vertices + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (gfxObj.BoundsMin + gfxObj.BoundsMax) * 0.5f, + Dimensions = gfxObj.BoundsMax - gfxObj.BoundsMin, + Min = gfxObj.BoundsMin, + Max = gfxObj.BoundsMax, + IsDoor = false + }; + } + + /// <summary> + /// Transforms a local-space bounding volume by a placement frame, + /// producing a world-space AABB for raycasting. + /// </summary> + private BoundingVolume TransformVolume(BoundingVolume localVol, Frame placement, + float globalOffsetX, float globalOffsetY) + { + if (localVol == null) return null; + + try + { + // For spheres: rotate center, keep radius (spheres are rotation-invariant) + if (localVol.Type == BoundingVolume.VolumeType.Sphere) + { + Vector3 worldCenter = placement.TransformPoint(localVol.Center); + worldCenter.X += globalOffsetX; + worldCenter.Y += globalOffsetY; + + float r = localVol.Dimensions.X; // Radius + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = worldCenter, + Dimensions = localVol.Dimensions, + Min = worldCenter - new Vector3(r, r, r), + Max = worldCenter + new Vector3(r, r, r), + IsDoor = localVol.IsDoor + }; + } + + // For AABBs and other types: transform the 8 corners and compute new AABB + Vector3[] corners = new Vector3[8] + { + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z), + }; + + Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue); + + for (int i = 0; i < 8; i++) + { + Vector3 world = placement.TransformPoint(corners[i]); + world.X += globalOffsetX; + world.Y += globalOffsetY; + + newMin = Vector3.Min(newMin, world); + newMax = Vector3.Max(newMax, world); + } + + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (newMin + newMax) * 0.5f, + Dimensions = newMax - newMin, + Min = newMin, + Max = newMax, + IsDoor = localVol.IsDoor + }; + } + catch (Exception ex) + { + Log($"Error transforming volume: {ex.Message}"); + return null; + } + } + + /// <summary> + /// Searches common installation paths for Asheron's Call. + /// </summary> + private string FindACFolder() + { + string[] searchPaths = new string[] + { + @"C:\Turbine\Asheron's Call", // User's known path + @"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", + @"C:\Games\AC", + @"D:\Turbine\Asheron's Call", + @"D:\Games\Asheron's Call", + @"D:\AC", + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Turbine", "Asheron's Call"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Turbine", "Asheron's Call"), + }; + + // Check for both original (portal.dat) and ToD (client_portal.dat) filenames + string[] portalNames = { "client_portal.dat", "portal.dat" }; + string[] cellNames = { "client_cell_1.dat", "cell.dat" }; + + foreach (var path in searchPaths) + { + try + { + if (!Directory.Exists(path)) continue; + + bool hasPortal = false, hasCell = false; + foreach (var pn in portalNames) + if (File.Exists(Path.Combine(path, pn))) { hasPortal = true; break; } + foreach (var cn in cellNames) + if (File.Exists(Path.Combine(path, cn))) { hasCell = true; break; } + + if (hasPortal && hasCell) + { + Log($"Found AC folder: {path}"); + return path; + } + else if (hasPortal || hasCell) + { + Log($"Partial match at {path} (portal={hasPortal}, cell={hasCell})"); + } + } + catch { } + } + + // Also try to find via registry + try + { + using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Turbine\Asheron's Call")) + { + if (key != null) + { + string installPath = key.GetValue("InstallPath") as string; + if (!string.IsNullOrEmpty(installPath) && Directory.Exists(installPath)) + return installPath; + } + } + } + catch { } + + Log("Could not find Asheron's Call installation"); + return null; + } + + private void EvictOldestLandblock() + { + if (_landblockCache.Count == 0) return; + + // Simple eviction: remove the first key + foreach (var key in _landblockCache.Keys) + { + _landblockCache.Remove(key); + break; + } + } + + public void FlushCache() + { + _landblockCache.Clear(); + _setupCache.Clear(); + Log("All caches flushed"); + } + + public void FlushLandblock(uint landblockKey) + { + _landblockCache.Remove(landblockKey); + } + + public void Dispose() + { + _portalDat?.Dispose(); + _cellDat?.Dispose(); + _landblockCache.Clear(); + _setupCache.Clear(); + _initialized = false; + } + + private void Log(string msg) + { + string line = $"[GeoLoader] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 200) DiagLog.Add(msg); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/LandblockStructs.cs b/Plugins/RynthAi/Raycasting/LandblockStructs.cs new file mode 100644 index 0000000..c7d4e87 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/LandblockStructs.cs @@ -0,0 +1,751 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// A position + rotation in AC's 3D world. + /// Position is in local landblock meters (0-192 for outdoors). + /// Rotation is a quaternion (W, X, Y, Z). + /// </summary> + public class Frame + { + public float OriginX, OriginY, OriginZ; + public float RotW, RotX, RotY, RotZ; + + public Frame() + { + RotW = 1.0f; // Identity quaternion + } + + public void Unpack(BinaryReader reader) + { + OriginX = reader.ReadSingle(); + OriginY = reader.ReadSingle(); + OriginZ = reader.ReadSingle(); + RotW = reader.ReadSingle(); + RotX = reader.ReadSingle(); + RotY = reader.ReadSingle(); + RotZ = reader.ReadSingle(); + } + + /// <summary> + /// Rotates a point by this frame's quaternion. + /// q * v * q^-1 (for unit quaternion, q^-1 = conjugate) + /// </summary> + public Vector3 RotatePoint(Vector3 point) + { + // Quaternion rotation: v' = q * v * q* + float qw = RotW, qx = RotX, qy = RotY, qz = RotZ; + + // Cross product of quaternion xyz with point + float cx = qy * point.Z - qz * point.Y; + float cy = qz * point.X - qx * point.Z; + float cz = qx * point.Y - qy * point.X; + + // Result = point + 2 * (qw * cross + qxyz x cross) + float cx2 = qy * cz - qz * cy; + float cy2 = qz * cx - qx * cz; + float cz2 = qx * cy - qy * cx; + + return new Vector3( + point.X + 2.0f * (qw * cx + cx2), + point.Y + 2.0f * (qw * cy + cy2), + point.Z + 2.0f * (qw * cz + cz2) + ); + } + + /// <summary> + /// Transforms a point: rotate then translate. + /// </summary> + public Vector3 TransformPoint(Vector3 localPoint) + { + Vector3 rotated = RotatePoint(localPoint); + return new Vector3( + rotated.X + OriginX, + rotated.Y + OriginY, + rotated.Z + OriginZ + ); + } + + public override string ToString() + { + return $"Pos({OriginX:F2}, {OriginY:F2}, {OriginZ:F2}) Rot({RotW:F3}, {RotX:F3}, {RotY:F3}, {RotZ:F3})"; + } + } + + /// <summary> + /// A static object placed on a landblock (building, tree, rock, structure, etc.) + /// </summary> + public class StaticObject + { + public uint InstanceId; // Unique placement ID + public uint SetupId; // Reference to 0x02xxxxxx Setup in portal.dat + public Frame Placement; // Position and rotation in landblock space + + public StaticObject() + { + Placement = new Frame(); + } + } + + /// <summary> + /// Parsed landblock info from cell.dat (file ID = 0xXXYYFFFE). + /// Contains static object placements (Stabs) and building info for an outdoor landblock. + /// + /// Format (from ACE.DatLoader.FileTypes.LandblockInfo): + /// uint32 Id + /// uint32 NumCells + /// uint32 NumObjects (List<Stab> count) + /// Stab[NumObjects]: + /// uint32 Id (model/setup reference, 0x01xx or 0x02xx) + /// Frame (7 floats: pos.xyz + rot.wxyz = 28 bytes) + /// ushort NumBuildings + /// ushort PackMask + /// BuildInfo[NumBuildings]: + /// uint32 ModelId + /// Frame (28 bytes) + /// uint32 NumLeaves + /// List<CBldPortal> Portals + /// if (PackMask & 1): + /// PackedHashTable RestrictionTables + /// </summary> + public class LandblockInfo + { + public uint Id; + public uint NumCells; + public List<StaticObject> StaticObjects = new List<StaticObject>(); + public bool HasObjects; + + /// <summary> + /// Parse landblock info from raw .dat file data using the ACE format. + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + NumCells = reader.ReadUInt32(); + + // Read List<Stab> — uint32 count + count × Stab entries + uint numObjects = reader.ReadUInt32(); + + if (numObjects > 5000) numObjects = 5000; // Sanity + + for (uint i = 0; i < numObjects; i++) + { + if (ms.Position + 32 > ms.Length) break; // Need 4 (Id) + 28 (Frame) + + var obj = new StaticObject(); + obj.SetupId = reader.ReadUInt32(); + obj.Placement.Unpack(reader); + StaticObjects.Add(obj); + } + + HasObjects = StaticObjects.Count > 0; + Log($"Landblock 0x{Id:X8}: {StaticObjects.Count} static objects"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing landblock 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}"); + } + } + + /// <summary> + /// Parsed environment cell from cell.dat (file ID = 0xXXYY0001 to 0xXXYYFFFE). + /// Represents an indoor dungeon room with walls, portals, and static objects. + /// </summary> + public class EnvCellInfo + { + public uint Id; + public uint Flags; + public List<Vector3> Vertices = new List<Vector3>(); + public List<CellPolygon> Polygons = new List<CellPolygon>(); + public List<ushort> PortalPolygonIndices = new List<ushort>(); + public List<StaticObject> StaticObjects = new List<StaticObject>(); + public List<uint> ConnectedCells = new List<uint>(); + public uint EnvironmentId; // Reference to portal.dat environment + public uint StructureId; // Reference to portal.dat cell structure + + /// <summary> + /// Parse environment cell from raw data. + /// + /// Format (simplified): + /// uint32 id + /// uint32 flags + /// uint32 environmentId (0x0Dxxxxxx) + /// uint16 cellStructId + /// uint16 position (index into structure) + /// Frame placement + /// uint32 numPortals + /// for each portal: + /// uint16 polygonId (portal polygon index) + /// uint16 flags + /// uint32 connectedCell + /// uint32 numStaticObjects + /// for each static object: + /// uint32 setupId + /// Frame placement + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + // Read environment/structure references + if (ms.Position + 8 > ms.Length) return false; + + // The exact format depends on flags, but typically: + EnvironmentId = reader.ReadUInt32(); + + if (ms.Position + 4 > ms.Length) return false; + StructureId = reader.ReadUInt32(); + + // Read cell frame (position + rotation) + if ((Flags & 0x02) != 0 && ms.Position + 28 <= ms.Length) + { + var frame = new Frame(); + frame.Unpack(reader); + } + + // Read portals + if ((Flags & 0x04) != 0 || ms.Position + 4 <= ms.Length) + { + if (ms.Position + 4 <= ms.Length) + { + uint numPortals = reader.ReadUInt32(); + if (numPortals > 1000) numPortals = 0; // Sanity + + for (uint i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++) + { + ushort polyId = reader.ReadUInt16(); + ushort portalFlags = reader.ReadUInt16(); + uint connCell = reader.ReadUInt32(); + + PortalPolygonIndices.Add(polyId); + ConnectedCells.Add(connCell); + } + } + } + + // Read static objects + if (ms.Position + 4 <= ms.Length) + { + uint numObjects = reader.ReadUInt32(); + if (numObjects > 10000) numObjects = 0; + + for (uint i = 0; i < numObjects && ms.Position + 32 <= ms.Length; i++) + { + var obj = new StaticObject(); + obj.SetupId = reader.ReadUInt32(); + obj.Placement.Unpack(reader); + StaticObjects.Add(obj); + } + } + + Log($"EnvCell 0x{Id:X8}: {StaticObjects.Count} objects, " + + $"{PortalPolygonIndices.Count} portals"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing EnvCell 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}"); + } + } + + /// <summary> + /// A polygon in a cell structure (wall, floor, ceiling). + /// </summary> + public class CellPolygon + { + public ushort[] VertexIndices; + public bool IsPortal; // Portal polygons are openings, not solid walls + } + + /// <summary> + /// Parsed Setup file from portal.dat (file ID = 0x02xxxxxx). + /// Matches ACE.DatLoader.FileTypes.SetupModel.Unpack() exactly. + /// + /// Format: + /// uint32 Id + /// uint32 Flags (SetupFlags) + /// uint32 numParts + /// uint32[numParts] Parts (GfxObj references, 0x01xxxxxx) + /// if (Flags & 0x01): uint32[numParts] ParentIndex + /// if (Flags & 0x02): Vector3[numParts] DefaultScale + /// Dictionary<int,LocationType> HoldingLocations (uint32 count + entries) + /// Dictionary<int,LocationType> ConnectionPoints (uint32 count + entries) + /// int32 placementsCount + /// PlacementType[placementsCount]: key(int32) + AnimFrame(numParts × Frame(28) + uint32 numHooks + hooks) + /// List<CylSphere> CylSpheres (uint32 count + count × 20 bytes) + /// List<Sphere> Spheres (uint32 count + count × 16 bytes) + /// float Height, Radius, StepUpHeight, StepDownHeight + /// Sphere SortingSphere (Vector3 + float = 16 bytes) + /// Sphere SelectionSphere (16 bytes) + /// Dictionary<int,LightInfo> Lights + /// uint32 × 5 defaults + /// </summary> + public class SetupInfo + { + public uint Id; + public uint Flags; + public int NumParts; + public uint[] PartIds; + + // Bounding sphere (from SortingSphere) + public float BoundingSphereRadius; + public Vector3 BoundingSphereCenter; + + // Physics dimensions + public float Height; + public float Radius; // Physics collision radius + + // Collision spheres + public List<CollisionSphere> Spheres = new List<CollisionSphere>(); + + // Collision cylinders + public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>(); + + public bool HasBounds; + + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 16) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + // --- Header --- + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + uint numParts = reader.ReadUInt32(); + if (numParts > 500) return false; + NumParts = (int)numParts; + + PartIds = new uint[numParts]; + for (int i = 0; i < numParts; i++) + PartIds[i] = reader.ReadUInt32(); + + // --- Optional arrays based on flags --- + // HasParent = 0x01 + if ((Flags & 0x01) != 0) + ms.Seek(numParts * 4, SeekOrigin.Current); + + // HasDefaultScale = 0x02 + if ((Flags & 0x02) != 0) + ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes + + // --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) --- + if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); + + // --- Skip ConnectionPoints: same format --- + if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); + + // --- Skip PlacementFrames --- + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + int placementsCount = reader.ReadInt32(); + if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data); + + for (int p = 0; p < placementsCount; p++) + { + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + reader.ReadInt32(); // key + + // AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks + for (int part = 0; part < numParts; part++) + { + if (ms.Position + 28 > ms.Length) return TryFallbackParse(data); + ms.Seek(28, SeekOrigin.Current); // Skip Frame + } + + if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + uint numHooks = reader.ReadUInt32(); + if (numHooks > 0) + { + // AnimationHooks are variable-size; can't easily skip + // Fall back to tail scanning + return TryFallbackParse(data); + } + } + + // --- NOW we're at the good stuff! --- + return ReadBoundsData(reader, ms, data); + } + } + catch + { + return TryFallbackParse(data); + } + } + + /// <summary> + /// Reads CylSpheres, Spheres, Height, Radius, SortingSphere from current position. + /// </summary> + private bool ReadBoundsData(BinaryReader reader, MemoryStream ms, byte[] data) + { + try + { + // CylSpheres: uint32 count + count × (Vector3 origin(12) + float radius(4) + float height(4) = 20) + if (ms.Position + 4 > ms.Length) return false; + uint numCylSpheres = reader.ReadUInt32(); + if (numCylSpheres > 50) return TryFallbackParse(data); + + for (uint i = 0; i < numCylSpheres; i++) + { + if (ms.Position + 20 > ms.Length) break; + var cyl = new CollisionCylinder(); + cyl.BottomCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + cyl.Radius = reader.ReadSingle(); + cyl.Height = reader.ReadSingle(); + if (cyl.Radius > 0 && cyl.Height > 0 && !float.IsNaN(cyl.Radius)) + Cylinders.Add(cyl); + } + + // Spheres: uint32 count + count × (Vector3 origin(12) + float radius(4) = 16) + if (ms.Position + 4 > ms.Length) return false; + uint numSpheres = reader.ReadUInt32(); + if (numSpheres > 50) return TryFallbackParse(data); + + for (uint i = 0; i < numSpheres; i++) + { + if (ms.Position + 16 > ms.Length) break; + var sphere = new CollisionSphere(); + sphere.Center = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + sphere.Radius = reader.ReadSingle(); + if (sphere.Radius > 0 && !float.IsNaN(sphere.Radius)) + Spheres.Add(sphere); + } + + // Height, Radius, StepUpHeight, StepDownHeight + if (ms.Position + 16 > ms.Length) return false; + Height = reader.ReadSingle(); + Radius = reader.ReadSingle(); + float stepUp = reader.ReadSingle(); + float stepDown = reader.ReadSingle(); + + // SortingSphere: Vector3 center + float radius + if (ms.Position + 16 > ms.Length) return false; + float sx = reader.ReadSingle(), sy = reader.ReadSingle(), sz = reader.ReadSingle(); + float sr = reader.ReadSingle(); + + BoundingSphereCenter = new Vector3(sx, sy, sz); + BoundingSphereRadius = sr; + HasBounds = sr > 0.001f || Radius > 0.001f; + + // If SortingSphere radius is 0, use the physics Radius + if (BoundingSphereRadius < 0.001f && Radius > 0.001f) + BoundingSphereRadius = Radius; + + Log($"Setup 0x{Id:X8}: bounds OK — radius={BoundingSphereRadius:F2}, height={Height:F2}, " + + $"{Cylinders.Count} cyls, {Spheres.Count} spheres"); + return true; + } + catch + { + return TryFallbackParse(data); + } + } + + /// <summary> + /// Skip a hash table: uint32 count + count × entries of entrySize bytes. + /// </summary> + private bool SkipHashTable(BinaryReader reader, MemoryStream ms, int entrySize) + { + if (ms.Position + 4 > ms.Length) return false; + uint count = reader.ReadUInt32(); + if (count > 1000) return false; + long skip = (long)count * entrySize; + if (ms.Position + skip > ms.Length) return false; + ms.Seek(skip, SeekOrigin.Current); + return true; + } + + /// <summary> + /// Fallback: scan from the end of the file for the known tail structure. + /// The tail is always: + /// ... SortingSphere(16) + SelectionSphere(16) + Lights(uint32 count + entries) + 5×uint32(20) + /// If Lights is empty (count=0 → 4 bytes), tail is 56 bytes from end. + /// </summary> + private bool TryFallbackParse(byte[] data) + { + try + { + // Read header to get PartIds at minimum + if (PartIds == null && data.Length >= 16) + { + using (var ms2 = new MemoryStream(data)) + using (var r2 = new BinaryReader(ms2)) + { + Id = r2.ReadUInt32(); + Flags = r2.ReadUInt32(); + uint np = r2.ReadUInt32(); + if (np <= 500) + { + NumParts = (int)np; + PartIds = new uint[np]; + for (int i = 0; i < np && ms2.Position + 4 <= ms2.Length; i++) + PartIds[i] = r2.ReadUInt32(); + } + } + } + + // Try to find SortingSphere by scanning from end + // Known tail (if Lights empty): 5×uint32(20) + Lights(4) + SelectionSphere(16) + SortingSphere(16) + 4×float(16) + // = 72 bytes from end for start of Height/Radius/StepUp/StepDown + + int[] tailOffsets = { 72, 78, 84 }; // Try different Lights sizes (4, 10, 16 bytes) + + foreach (int tailOff in tailOffsets) + { + int offset = data.Length - tailOff; + if (offset < 16 || offset + 48 > data.Length) continue; + + float h = BitConverter.ToSingle(data, offset); + float r = BitConverter.ToSingle(data, offset + 4); + float sx = BitConverter.ToSingle(data, offset + 16); + float sy = BitConverter.ToSingle(data, offset + 20); + float sz = BitConverter.ToSingle(data, offset + 24); + float sr = BitConverter.ToSingle(data, offset + 28); + + // Validate: Height and Radius should be positive, sphere radius positive, center reasonable + if (h >= 0 && h < 100 && r > 0 && r < 200 && + sr > 0 && sr < 500 && + !float.IsNaN(h) && !float.IsNaN(r) && !float.IsNaN(sr) && + Math.Abs(sx) < 1000 && Math.Abs(sy) < 1000 && Math.Abs(sz) < 1000) + { + Height = h; + Radius = r; + BoundingSphereCenter = new Vector3(sx, sy, sz); + BoundingSphereRadius = sr; + HasBounds = true; + + Log($"Setup 0x{Id:X8}: FALLBACK found bounds at tailOff={tailOff} — radius={sr:F2}, height={h:F2}"); + return true; + } + } + + Log($"Setup 0x{Id:X8}: FALLBACK failed, no valid bounds found"); + return false; + } + catch + { + return false; + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[Setup] {msg}"); + } + } + + /// <summary> + /// Parsed GfxObj from portal.dat (file ID = 0x01xxxxxx). + /// Contains 3D mesh data. We extract the bounding sphere and AABB. + /// </summary> + public class GfxObjInfo + { + public uint Id; + public uint Flags; + + // Bounding data (what we need for raycasting) + public Vector3 SortingCenter; + public float SortingRadius; + public Vector3 BoundsMin; + public Vector3 BoundsMax; + public bool HasBounds; + + // Vertex data (for precise bounds calculation) + public List<Vector3> Vertices = new List<Vector3>(); + + /// <summary> + /// Parse GfxObj to extract bounding information. + /// We don't need the full mesh/texture data for raycasting. + /// + /// Format (simplified): + /// uint32 id + /// uint32 flags + /// -- surface data (skip) -- + /// uint32 numVertices + /// for each vertex: + /// float3 position + /// float3 normal + /// (optional UV data based on flags) + /// -- polygon data (skip) -- + /// -- BSP data (skip for now) -- + /// float3 sortingCenter + /// float sortingRadius + /// </summary> + public bool Unpack(byte[] data) + { + if (data == null || data.Length < 12) + return false; + + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + Id = reader.ReadUInt32(); + Flags = reader.ReadUInt32(); + + // Skip surface references + if (ms.Position + 4 > ms.Length) return false; + uint numSurfaces = reader.ReadUInt32(); + if (numSurfaces > 10000) return false; + ms.Seek(numSurfaces * 4, SeekOrigin.Current); // uint32 per surface + + // Read vertex count + if (ms.Position + 4 > ms.Length) return false; + uint numVertices = reader.ReadUInt32(); + if (numVertices > 100000) return false; + + // Read vertices and compute AABB + float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue; + float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue; + + for (uint i = 0; i < numVertices; i++) + { + if (ms.Position + 12 > ms.Length) break; + + float x = reader.ReadSingle(); + float y = reader.ReadSingle(); + float z = reader.ReadSingle(); + + if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)) continue; + + Vertices.Add(new Vector3(x, y, z)); + + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + minZ = Math.Min(minZ, z); maxZ = Math.Max(maxZ, z); + + // Skip normal (3 floats) + UV data + if (ms.Position + 12 <= ms.Length) + ms.Seek(12, SeekOrigin.Current); // Skip normal + + // UV data varies; skip based on flags + if ((Flags & 0x04) != 0 && ms.Position + 8 <= ms.Length) + ms.Seek(8, SeekOrigin.Current); // Skip UV + } + + if (Vertices.Count > 0) + { + BoundsMin = new Vector3(minX, minY, minZ); + BoundsMax = new Vector3(maxX, maxY, maxZ); + HasBounds = true; + + // Compute bounding sphere from AABB + SortingCenter = new Vector3( + (minX + maxX) * 0.5f, + (minY + maxY) * 0.5f, + (minZ + maxZ) * 0.5f + ); + SortingRadius = (BoundsMax - SortingCenter).Length(); + } + + // Also try to find the explicit sorting sphere at the end of file + TryReadSortingSphere(data); + + Log($"GfxObj 0x{Id:X8}: {Vertices.Count} verts, radius={SortingRadius:F2}"); + return true; + } + } + catch (Exception ex) + { + Log($"Error parsing GfxObj 0x{Id:X8}: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Scans the end of the file for the sorting sphere data. + /// The sorting center + radius are typically near the end of the GfxObj. + /// </summary> + private void TryReadSortingSphere(byte[] data) + { + // The last 16 bytes before any trailing data often contain the sorting sphere + if (data.Length < 20) return; + + // Try reading from the last 16 bytes + for (int offset = data.Length - 16; offset >= Math.Max(0, data.Length - 64); offset -= 4) + { + if (offset + 16 > data.Length) continue; + + float cx = BitConverter.ToSingle(data, offset); + float cy = BitConverter.ToSingle(data, offset + 4); + float cz = BitConverter.ToSingle(data, offset + 8); + float r = BitConverter.ToSingle(data, offset + 12); + + if (r > 0.01f && r < 500f && !float.IsNaN(r) && !float.IsInfinity(r) && + !float.IsNaN(cx) && !float.IsNaN(cy) && !float.IsNaN(cz) && + Math.Abs(cx) < 1000 && Math.Abs(cy) < 1000 && Math.Abs(cz) < 1000) + { + SortingCenter = new Vector3(cx, cy, cz); + SortingRadius = r; + break; + } + } + } + + private static void Log(string msg) + { + System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}"); + } + } + + /// <summary> + /// A spherical collision volume from a Setup file. + /// </summary> + public class CollisionSphere + { + public Vector3 Center; + public float Radius; + } + + /// <summary> + /// A cylindrical collision volume from a Setup file. + /// </summary> + public class CollisionCylinder + { + public Vector3 BottomCenter; + public float Radius; + public float Height; + } +} diff --git a/Plugins/RynthAi/Raycasting/MainLogic.cs b/Plugins/RynthAi/Raycasting/MainLogic.cs new file mode 100644 index 0000000..c534bfd --- /dev/null +++ b/Plugins/RynthAi/Raycasting/MainLogic.cs @@ -0,0 +1,98 @@ +using System; +using Decal.Adapter; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Main integration point for the raycasting system. + /// Initializes the .dat file parsers, geometry loader, and targeting FSM. + /// + /// Usage: + /// var raycast = new MainLogic(); + /// raycast.Initialize(acFolderPath); // Call once at startup + /// + /// // During combat: + /// bool blocked = raycast.IsTargetBlocked(core, targetWorldObject, attackType); + /// </summary> + public class MainLogic : IDisposable + { + private GeometryLoader _geoLoader; + private BlacklistManager _blacklist; + private TargetingFSM _targetingFSM; + private bool _disposed; + + public GeometryLoader GeometryLoader => _geoLoader; + public BlacklistManager Blacklist => _blacklist; + public TargetingFSM TargetingFSM => _targetingFSM; + public bool IsInitialized => _geoLoader?.IsInitialized ?? false; + public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created"; + + public MainLogic() + { + _geoLoader = new GeometryLoader(); + _blacklist = new BlacklistManager(); + _targetingFSM = new TargetingFSM(_geoLoader, _blacklist); + } + + /// <summary> + /// Initializes the raycasting system by loading portal.dat and cell.dat. + /// + /// acFolderPath: Optional explicit path to AC installation folder. + /// If null, will search common installation paths automatically. + /// + /// Returns true if initialization succeeded (both .dat files loaded). + /// </summary> + public bool Initialize(string acFolderPath = null) + { + try + { + bool result = _geoLoader.Initialize(acFolderPath); + if (result) + { + System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic initialized successfully"); + } + else + System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init failed: {_geoLoader.StatusMessage}"); + + return result; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init error: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Quick check: is a specific target blocked by geometry? + /// Call this from CombatManager before engaging a target. + /// </summary> + public bool IsTargetBlocked(CoreManager core, Decal.Adapter.Wrappers.WorldObject target, + TargetingFSM.AttackType attackType) + { + if (!IsInitialized || _targetingFSM == null) + return false; + + return _targetingFSM.IsTargetBlocked(core, target, attackType); + } + + /// <summary> + /// Determines the attack type from the currently wielded weapon. + /// </summary> + public TargetingFSM.AttackType GetAttackType(CoreManager core) + { + return _targetingFSM?.DetermineAttackType(core) ?? TargetingFSM.AttackType.Linear; + } + + public void Dispose() + { + if (_disposed) return; + + _geoLoader?.Dispose(); + _blacklist?.ClearAll(); + + _disposed = true; + System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic disposed"); + } + } +} diff --git a/Plugins/RynthAi/Raycasting/RaycastEngine.cs b/Plugins/RynthAi/Raycasting/RaycastEngine.cs new file mode 100644 index 0000000..25a4db6 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/RaycastEngine.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Core raycasting engine for line-of-sight checks. + /// Tests linear (spell/bolt) and parabolic (bow/thrown) trajectories + /// against the loaded collision geometry. + /// + /// NOTE: Uses custom Vector3 from this namespace, NOT System.Numerics. + /// </summary> + public static class RaycastEngine + { + /// <summary> + /// Gravity constant for parabolic trajectory calculations. + /// AC's gravity is approximately 9.81 m/s² but may need empirical tuning. + /// </summary> + private const float GRAVITY = 9.81f; + + /// <summary> + /// Number of sample points along an arc trajectory for collision testing. + /// Higher = more accurate but slower. 10 is a good balance. + /// </summary> + private const int ARC_SAMPLE_COUNT = 10; + + /// <summary> + /// Tests if a straight-line path (magic spells, crossbow bolts) is blocked + /// by any collision geometry. + /// + /// Returns true if the path IS blocked (an obstacle exists between origin and target). + /// Returns false if the path is clear. + /// </summary> + public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry) + { + if (geometry == null || geometry.Count == 0) + return false; + + // Validate inputs + if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) || + float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z)) + return false; + + // Calculate direction and distance + Vector3 delta = target - origin; + float distanceToTarget = delta.Length(); + + // Origin and target are the same point — no obstruction possible + if (distanceToTarget < 1e-4f) + return false; + + // Normalize direction + Vector3 direction = delta / distanceToTarget; + + // Test ray against each bounding volume + foreach (var volume in geometry) + { + // Skip doors (state is unreliable, as per VTank's approach) + if (volume.IsDoor) + continue; + + // Test intersection + float hitDist; + if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist)) + { + // Ignore geometry within 2m of the player — prevents false blocks + // from walls/floors the player is standing on or touching. + // Only count geometry that's actually BETWEEN the player and target. + if (hitDist >= 2.0f && hitDist < distanceToTarget) + { + return true; // Path is blocked + } + } + } + + return false; // Path is clear + } + + /// <summary> + /// Tests if a parabolic arc path (bows, thrown weapons) is blocked by geometry. + /// + /// This allows attacks to arc over low obstacles like walls and rocks. + /// The arc is sampled at discrete points and each segment is tested for + /// intersection with geometry. + /// + /// Returns true if the arc IS blocked. + /// Returns false if the arc clears all obstacles. + /// </summary> + public static bool IsArcPathBlocked(Vector3 origin, Vector3 target, float initialVelocity, + List<BoundingVolume> geometry) + { + if (geometry == null || geometry.Count == 0) + return false; + + if (initialVelocity <= 0) + return true; // Can't fire with no velocity + + // Validate inputs + if (float.IsNaN(origin.X) || float.IsNaN(target.X)) + return true; + + Vector3 delta = target - origin; + float horizontalDist = delta.Length2D(); + float verticalDist = delta.Z; + + // Check maximum range: v² / g + float maxRange = (initialVelocity * initialVelocity) / GRAVITY; + if (horizontalDist > maxRange) + return true; // Out of range + + if (horizontalDist < 0.1f) + return false; // Basically on top of target + + // Calculate launch angle for the desired range + // Using the optimal angle that clears obstacles + // θ = 0.5 * arcsin(g * d / v²) for flat terrain + float sinArg = (GRAVITY * horizontalDist) / (initialVelocity * initialVelocity); + sinArg = Math.Min(sinArg, 1.0f); // Clamp for float precision + + // Use the high arc (π/2 - θ) for better obstacle clearance + float launchAngle = (float)(0.5 * Math.Asin(sinArg)); + if (launchAngle < 0.1f) + launchAngle = (float)(Math.PI / 4); // Default to 45° if calculation fails + + float cosAngle = (float)Math.Cos(launchAngle); + float sinAngle = (float)Math.Sin(launchAngle); + + // Calculate time of flight + float vHorizontal = initialVelocity * cosAngle; + float vVertical = initialVelocity * sinAngle; + + if (vHorizontal < 0.01f) + return true; // Basically firing straight up + + float totalTime = horizontalDist / vHorizontal; + + // Horizontal direction (unit vector in XY plane) + float hdx = delta.X / horizontalDist; + float hdy = delta.Y / horizontalDist; + + // Sample the arc at discrete points and test each segment + Vector3 prevPoint = origin; + + for (int i = 1; i <= ARC_SAMPLE_COUNT; i++) + { + float t = (float)i / ARC_SAMPLE_COUNT; + float time = t * totalTime; + + // Kinematic equations + float hDist = vHorizontal * time; + float height = origin.Z + vVertical * time - 0.5f * GRAVITY * time * time; + + // Adjust height to interpolate between origin.Z and target.Z + // (accounts for height difference between origin and target) + float heightAdjust = verticalDist * t; + + Vector3 arcPoint = new Vector3( + origin.X + hdx * hDist, + origin.Y + hdy * hDist, + height + heightAdjust * (1.0f - t) // Blend in height difference + ); + + // Test this segment for collisions + if (IsSegmentBlocked(prevPoint, arcPoint, geometry)) + return true; + + prevPoint = arcPoint; + } + + // Test final segment to target + if (IsSegmentBlocked(prevPoint, target, geometry)) + return true; + + return false; // Arc clears all obstacles + } + + /// <summary> + /// Tests if a line segment between two points intersects any geometry. + /// Used internally for arc sampling. + /// </summary> + private static bool IsSegmentBlocked(Vector3 start, Vector3 end, List<BoundingVolume> geometry) + { + Vector3 delta = end - start; + float dist = delta.Length(); + + if (dist < 0.01f) return false; + + Vector3 dir = delta / dist; + + foreach (var volume in geometry) + { + if (volume.IsDoor) continue; + + float hitDist; + if (volume.RayIntersect(start, dir, dist, out hitDist)) + { + if (hitDist > 0.05f && hitDist < dist - 0.05f) + return true; + } + } + + return false; + } + + /// <summary> + /// Quick distance-based pre-filter: checks if ANY geometry exists near the line + /// between origin and target. Used to skip the full raycast for wide-open areas. + /// Returns true if there is nearby geometry worth testing. + /// </summary> + public static bool HasNearbyGeometry(Vector3 origin, Vector3 target, List<BoundingVolume> geometry, float margin = 5.0f) + { + if (geometry == null || geometry.Count == 0) + return false; + + // Compute a rough bounding box for the path + Vector3 pathMin = Vector3.Min(origin, target) - new Vector3(margin, margin, margin); + Vector3 pathMax = Vector3.Max(origin, target) + new Vector3(margin, margin, margin); + + foreach (var vol in geometry) + { + if (vol.IsDoor) continue; + + // Quick AABB overlap test + if (vol.Max.X >= pathMin.X && vol.Min.X <= pathMax.X && + vol.Max.Y >= pathMin.Y && vol.Min.Y <= pathMax.Y && + vol.Max.Z >= pathMin.Z && vol.Min.Z <= pathMax.Z) + { + return true; + } + } + + return false; + } + } +} diff --git a/Plugins/RynthAi/Raycasting/ScatterSystem.cs b/Plugins/RynthAi/Raycasting/ScatterSystem.cs new file mode 100644 index 0000000..bb8785f --- /dev/null +++ b/Plugins/RynthAi/Raycasting/ScatterSystem.cs @@ -0,0 +1,948 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Implements AC's deterministic scatter placement system for terrain objects (trees, rocks, etc). + /// Ported from ACE's Landblock.get_land_scenes() + ObjectDesc.Displace/Rotate/Scale. + /// + /// Pipeline: + /// 1. Parse RegionDesc (0x13000000) from portal.dat → terrain-to-scene mapping tables + /// 2. Parse CellLandblock (0xXXYYFFFF) from cell.dat → 81 terrain values + 81 heights + /// 3. For each terrain cell, deterministically select and place scatter objects + /// 4. Look up bounding volumes for each placed object + /// </summary> + public class ScatterSystem + { + // LandDefs constants (from ACE) + private const int VertexDim = 9; // 9×9 vertices per landblock + private const int BlockSide = 8; // 8×8 cells per landblock + private const float CellLength = 24.0f; // Each cell is 24m + private const float BlockLength = 192.0f; + + // RegionDesc data (parsed once) + private List<ScatterTerrainType> _terrainTypes; + private List<ScatterSceneType> _sceneTypes; + private float[] _landHeightTable; + private bool _initialized; + + // Scene cache (portal.dat scenes) + private Dictionary<uint, List<ScatterObjectDesc>> _sceneCache = new Dictionary<uint, List<ScatterObjectDesc>>(); + + // Reference to dat files + private DatDatabase _portalDat; + private DatDatabase _cellDat; + + public bool IsInitialized => _initialized; + public List<string> DiagLog { get; } = new List<string>(); + + public bool Initialize(DatDatabase portalDat, DatDatabase cellDat) + { + _portalDat = portalDat; + _cellDat = cellDat; + + try + { + // Parse RegionDesc (0x13000000) from portal.dat + byte[] regionData = portalDat.GetFileData(0x13000000); + if (regionData == null || regionData.Length < 100) + { + Log($"RegionDesc 0x13000000 not found in portal.dat (data={regionData?.Length ?? 0})"); + return false; + } + + Log($"RegionDesc: {regionData.Length} bytes loaded"); + + // Dump first few uint32s for debugging + string header = "RegionDesc header: "; + for (int i = 0; i < Math.Min(32, regionData.Length); i += 4) + header += $"0x{BitConverter.ToUInt32(regionData, i):X8} "; + Log(header); + + if (!ParseRegionDesc(regionData)) + { + Log("Failed to parse RegionDesc"); + return false; + } + + _initialized = true; + Log($"Scatter system ready: {_terrainTypes?.Count ?? 0} terrain types, {_sceneTypes?.Count ?? 0} scene types"); + return true; + } + catch (Exception ex) + { + Log($"Scatter init error: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Generates scatter object bounding volumes for a landblock. + /// Replicates ACE's Landblock.get_land_scenes() algorithm. + /// </summary> + public List<BoundingVolume> GetScatterVolumes(uint landblockKey, GeometryLoader geoLoader) + { + var volumes = new List<BoundingVolume>(); + if (!_initialized || _terrainTypes == null || _sceneTypes == null) + return volumes; + + try + { + // Read CellLandblock (0xXXYYFFFF) from cell.dat + uint cellLandblockId = (landblockKey << 16) | 0xFFFF; + byte[] data = _cellDat.GetFileData(cellLandblockId); + if (data == null || data.Length < 170) // Minimum: 4+4+81*2+81*1 = 255 + return volumes; + + // Parse terrain and height arrays + ushort[] terrain = new ushort[81]; + byte[] height = new byte[81]; + + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); + uint hasObjects = reader.ReadUInt32(); + + for (int i = 0; i < 81; i++) + terrain[i] = reader.ReadUInt16(); + + for (int i = 0; i < 81; i++) + height[i] = reader.ReadByte(); + } + + // Compute block offsets (global cell coordinates) + uint blockX = ((landblockKey >> 8) & 0xFF) * 8; + uint blockY = (landblockKey & 0xFF) * 8; + + float globalOffsetX = ((landblockKey >> 8) & 0xFF) * BlockLength; + float globalOffsetY = (landblockKey & 0xFF) * BlockLength; + + int scatterCount = 0; + + // Iterate all 81 terrain cells (matching ACE's get_land_scenes) + for (uint i = 0; i < 81; i++) + { + ushort t = terrain[i]; + int terrainType = (t >> 2) & 0x1F; // 5 bits, 0-31 + int sceneType = t >> 11; // 5 bits, 0-31 + + if (terrainType >= _terrainTypes.Count) continue; + var tt = _terrainTypes[terrainType]; + if (sceneType >= tt.SceneTypeIndices.Count) continue; + + int sceneInfoIdx = (int)tt.SceneTypeIndices[sceneType]; + if (sceneInfoIdx >= _sceneTypes.Count) continue; + + var scenes = _sceneTypes[sceneInfoIdx].SceneFileIds; + if (scenes.Count == 0) continue; + + uint cellX = i / (uint)VertexDim; + uint cellY = i % (uint)VertexDim; + + uint globalCellX = (uint)(cellX + blockX); + uint globalCellY = (uint)(cellY + blockY); + + // Deterministic scene selection — uses uint32 overflow arithmetic + // matching AC client's C++ unsigned int behavior + uint cellMat = (uint)((long)globalCellY * (712977289L * globalCellX + 1813693831L) - 1109124029L * globalCellX + 2139937281L); + double offset = cellMat * 2.3283064e-10; + int sceneIdx = (int)(scenes.Count * offset); + if (sceneIdx < 0 || sceneIdx >= scenes.Count) sceneIdx = 0; + + uint sceneId = scenes[sceneIdx]; + + // Load the Scene file + var sceneObjects = LoadScene(sceneId); + if (sceneObjects == null || sceneObjects.Count == 0) continue; + + // Per-object noise seeds — uint32 overflow + uint cellXMat = (uint)(-1109124029L * globalCellX); + uint cellYMat = (uint)(1813693831L * globalCellY); + uint cellMat2 = (uint)(1360117743L * globalCellX * globalCellY + 1888038839L); + + for (uint j = 0; j < sceneObjects.Count; j++) + { + var obj = sceneObjects[(int)j]; + + // Frequency check — uint32 overflow + double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399 + j)) * 2.3283064e-10; + if (noise >= obj.Freq || obj.WeenieObj != 0) + continue; + + // Displace + var position = Displace(obj, globalCellX, globalCellY, j); + + float lx = cellX * CellLength + position.X; + float ly = cellY * CellLength + position.Y; + + // Bounds check + if (lx < 0 || ly < 0 || lx >= BlockLength || ly >= BlockLength) + continue; + + // Get terrain height at this position + float z = GetTerrainHeight(height, lx, ly); + + // World coordinates + float worldX = globalOffsetX + lx; + float worldY = globalOffsetY + ly; + + // Get bounding volume for this object + var setupVolumes = geoLoader.GetSetupBoundingVolumesPublic(obj.ObjId); + foreach (var vol in setupVolumes) + { + // Create a frame for the scatter object + var frame = new Frame + { + OriginX = lx, OriginY = ly, OriginZ = z, + RotW = 1, RotX = 0, RotY = 0, RotZ = 0 + }; + + // Apply rotation from scatter algorithm + ApplyScatterRotation(frame, obj, globalCellX, globalCellY, j); + + var transformed = TransformScatterVolume(vol, frame, globalOffsetX, globalOffsetY); + if (transformed != null) + { + // Extend scatter volumes vertically to account for: + // 1. Terrain height imprecision (nearest-vertex vs polygon, can be 10-15m off) + // 2. Trees/rocks extend upward from ground level + // Use generous range to ensure ray intersection works + float extendBelow = 20.0f; + float extendAbove = 20.0f; + transformed.Min = new Vector3(transformed.Min.X, transformed.Min.Y, transformed.Min.Z - extendBelow); + transformed.Max = new Vector3(transformed.Max.X, transformed.Max.Y, transformed.Max.Z + extendAbove); + transformed.Center = new Vector3(transformed.Center.X, transformed.Center.Y, + (transformed.Min.Z + transformed.Max.Z) * 0.5f); + // Force AABB type so Min/Max Z extension is used by ray intersection + transformed.Type = BoundingVolume.VolumeType.AxisAlignedBox; + transformed.Dimensions = transformed.Max - transformed.Min; + + volumes.Add(transformed); + } + } + scatterCount++; + } + } + + if (scatterCount > 0) + Log($"Landblock 0x{landblockKey:X4}: {scatterCount} scatter objects -> {volumes.Count} volumes"); + } + catch (Exception ex) + { + Log($"Scatter error for 0x{landblockKey:X4}: {ex.Message}"); + } + + return volumes; + } + + // =================================================================== + // ObjectDesc.Displace — pseudo-random placement from ACE + // =================================================================== + + private Vector3 Displace(ScatterObjectDesc obj, uint ix, uint iy, uint iq) + { + float x, y, z; + float locX = obj.BaseLocX, locY = obj.BaseLocY, locZ = obj.BaseLocZ; + + // uint32 overflow arithmetic matching AC client C++ unsigned int + if (obj.DisplaceX <= 0) + x = locX; + else + x = (float)((uint)(1813693831L * iy - (iq + 45773) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix) + * 2.3283064e-10 * obj.DisplaceX + locX); + + if (obj.DisplaceY <= 0) + y = locY; + else + y = (float)((uint)(1813693831L * iy - (iq + 72719) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix) + * 2.3283064e-10 * obj.DisplaceY + locY); + + z = locZ; + + double quadrant = (uint)(1813693831L * iy - ix * (1870387557L * iy + 1109124029L) - 402451965L) * 2.3283064e-10; + + if (quadrant >= 0.75) return new Vector3(y, -x, z); + if (quadrant >= 0.5) return new Vector3(-x, -y, z); + if (quadrant >= 0.25) return new Vector3(-y, x, z); + return new Vector3(x, y, z); + } + + private void ApplyScatterRotation(Frame frame, ScatterObjectDesc obj, uint x, uint y, uint k) + { + if (obj.MaxRotation > 0.0f) + { + float degrees = (float)((uint)(1813693831L * y - (k + 63127) * (1360117743L * y * x + 1888038839L) - 1109124029L * x) * 2.3283064e-10 * obj.MaxRotation); + float radians = degrees * (float)(Math.PI / 180.0); + float halfRad = radians * 0.5f; + frame.RotW = (float)Math.Cos(halfRad); + frame.RotZ = (float)Math.Sin(halfRad); + } + } + + private float GetTerrainHeight(byte[] heights, float lx, float ly) + { + // Bilinear interpolation of height values + // LandHeightTable already contains actual in-game Z heights + // (the *2 factor from CellLandblock comments refers to raw bytes, not table values) + int ix = Math.Min((int)(lx / CellLength), BlockSide); + int iy = Math.Min((int)(ly / CellLength), BlockSide); + + int idx = ix * VertexDim + iy; + if (idx >= 0 && idx < 81 && _landHeightTable != null) + { + byte h = heights[idx]; + if (h < _landHeightTable.Length) + return _landHeightTable[h]; + } + return 0; + } + + private BoundingVolume TransformScatterVolume(BoundingVolume localVol, Frame placement, + float globalOffsetX, float globalOffsetY) + { + if (localVol == null) return null; + + try + { + Vector3 worldCenter = placement.TransformPoint(localVol.Center); + worldCenter.X += globalOffsetX; + worldCenter.Y += globalOffsetY; + + if (localVol.Type == BoundingVolume.VolumeType.Sphere) + { + float r = localVol.Dimensions.X; + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.Sphere, + Center = worldCenter, + Dimensions = localVol.Dimensions, + Min = worldCenter - new Vector3(r, r, r), + Max = worldCenter + new Vector3(r, r, r), + IsDoor = false + }; + } + + // For non-sphere: transform corners to get new AABB + Vector3[] corners = { + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z), + new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z), + new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z), + new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z), + }; + + Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue); + + for (int c = 0; c < 8; c++) + { + Vector3 w = placement.TransformPoint(corners[c]); + w.X += globalOffsetX; + w.Y += globalOffsetY; + newMin = Vector3.Min(newMin, w); + newMax = Vector3.Max(newMax, w); + } + + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (newMin + newMax) * 0.5f, + Dimensions = newMax - newMin, + Min = newMin, + Max = newMax, + IsDoor = false + }; + } + catch { return null; } + } + + // =================================================================== + // Scene loading + // =================================================================== + + private List<ScatterObjectDesc> LoadScene(uint sceneId) + { + if (_sceneCache.TryGetValue(sceneId, out var cached)) + return cached; + + var objects = new List<ScatterObjectDesc>(); + + try + { + byte[] data = _portalDat.GetFileData(sceneId); + if (data == null || data.Length < 8) + { + _sceneCache[sceneId] = objects; + return objects; + } + + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); // Scene ID + + // List<ObjectDesc>: uint32 count + count × ObjectDesc + uint numObjects = reader.ReadUInt32(); + if (numObjects > 200) numObjects = 200; + + for (uint i = 0; i < numObjects; i++) + { + if (ms.Position + 72 > ms.Length) break; // ObjectDesc is 72 bytes + + var obj = new ScatterObjectDesc(); + obj.ObjId = reader.ReadUInt32(); + + // Frame (BaseLoc): 7 floats + obj.BaseLocX = reader.ReadSingle(); + obj.BaseLocY = reader.ReadSingle(); + obj.BaseLocZ = reader.ReadSingle(); + obj.BaseLocW = reader.ReadSingle(); + obj.BaseLocRX = reader.ReadSingle(); + obj.BaseLocRY = reader.ReadSingle(); + obj.BaseLocRZ = reader.ReadSingle(); + + obj.Freq = reader.ReadSingle(); + obj.DisplaceX = reader.ReadSingle(); + obj.DisplaceY = reader.ReadSingle(); + obj.MinScale = reader.ReadSingle(); + obj.MaxScale = reader.ReadSingle(); + obj.MaxRotation = reader.ReadSingle(); + obj.MinSlope = reader.ReadSingle(); + obj.MaxSlope = reader.ReadSingle(); + obj.Align = reader.ReadUInt32(); + obj.Orient = reader.ReadUInt32(); + obj.WeenieObj = reader.ReadUInt32(); + + objects.Add(obj); + } + } + } + catch (Exception ex) + { + Log($"Scene 0x{sceneId:X8} parse error: {ex.Message}"); + } + + _sceneCache[sceneId] = objects; + return objects; + } + + // =================================================================== + // RegionDesc parsing (0x13000000) + // =================================================================== + + private bool ParseRegionDesc(byte[] data) + { + try + { + using (var ms = new MemoryStream(data)) + using (var reader = new BinaryReader(ms)) + { + uint id = reader.ReadUInt32(); // 0x13000000 + uint regionNumber = reader.ReadUInt32(); + uint version = reader.ReadUInt32(); + + Log($"RegionDesc: id=0x{id:X8}, region={regionNumber}, version={version}"); + + // PString RegionName ("Dereth") + SkipPString(reader, ms); + Log($"After RegionName: pos={ms.Position}"); + + // LandDefs + if (!ParseLandDefs(reader, ms)) + { + Log($"LandDefs parse failed at pos={ms.Position}"); + return ScanForTables(data); + } + Log($"After LandDefs: pos={ms.Position}"); + + // GameTime + if (!SkipGameTime(reader, ms)) + { + Log($"GameTime skip failed at pos={ms.Position}"); + return ScanForTables(data); + } + Log($"After GameTime: pos={ms.Position}"); + + // PartsMask + uint partsMask = reader.ReadUInt32(); + Log($"PartsMask=0x{partsMask:X8}, pos={ms.Position}"); + + // Skip SkyDesc if present + if ((partsMask & 0x10) != 0) + { + Log("Skipping SkyDesc..."); + if (!SkipSkyDesc(reader, ms)) + { + Log($"SkyDesc skip failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SkyDesc: pos={ms.Position}"); + } + + // Skip SoundDesc if present + if ((partsMask & 0x01) != 0) + { + Log("Skipping SoundDesc..."); + if (!SkipSoundDesc(reader, ms)) + { + Log($"SoundDesc skip failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SoundDesc: pos={ms.Position}"); + } + + // Parse SceneDesc + if ((partsMask & 0x02) != 0) + { + Log("Parsing SceneDesc..."); + if (!ParseSceneDesc(reader, ms)) + { + Log($"SceneDesc parse failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + Log($"After SceneDesc: pos={ms.Position}"); + } + + // Parse TerrainDesc + Log("Parsing TerrainDesc..."); + if (!ParseTerrainDesc(reader, ms)) + { + Log($"TerrainDesc parse failed at pos={ms.Position}, trying fallback"); + return ScanForTables(data); + } + + Log($"RegionDesc parsed: {_terrainTypes?.Count} terrainTypes, {_sceneTypes?.Count} sceneTypes"); + return _terrainTypes != null && _sceneTypes != null; + } + } + catch (Exception ex) + { + Log($"RegionDesc parse error at unknown pos: {ex.Message}"); + return ScanForTables(data); + } + } + + private bool ParseLandDefs(BinaryReader reader, MemoryStream ms) + { + if (ms.Position + 1056 > ms.Length) return false; + + reader.ReadInt32(); // NumBlockLength + reader.ReadInt32(); // NumBlockWidth + reader.ReadSingle(); // SquareLength + reader.ReadInt32(); // LBlockLength + reader.ReadInt32(); // VertexPerCell + reader.ReadSingle(); // MaxObjHeight + reader.ReadSingle(); // SkyHeight + reader.ReadSingle(); // RoadWidth + + _landHeightTable = new float[256]; + for (int i = 0; i < 256; i++) + _landHeightTable[i] = reader.ReadSingle(); + + return true; + } + + private bool SkipGameTime(BinaryReader reader, MemoryStream ms) + { + try + { + reader.ReadDouble(); // ZeroTimeOfYear + reader.ReadUInt32(); // ZeroYear + reader.ReadSingle(); // DayLength + reader.ReadUInt32(); // DaysPerYear + SkipPString(reader, ms); // YearSpec + + // List<TimeOfDay> — uint32 count + entries + uint numTOD = reader.ReadUInt32(); + if (numTOD > 100) return false; + for (uint i = 0; i < numTOD; i++) + { + reader.ReadSingle(); // Begin time + reader.ReadUInt32(); // IsNight flag + SkipPString(reader, ms); // Name + } + + // DaysOfTheWeek — uint32 count + PStrings + uint numDays = reader.ReadUInt32(); + if (numDays > 20) return false; + for (uint i = 0; i < numDays; i++) + SkipPString(reader, ms); + + // List<Season> — uint32 count + entries + uint numSeasons = reader.ReadUInt32(); + if (numSeasons > 20) return false; + for (uint i = 0; i < numSeasons; i++) + { + reader.ReadUInt32(); // StartDate + SkipPString(reader, ms); // Name + } + + return true; + } + catch + { + return false; + } + } + + private bool SkipSkyDesc(BinaryReader reader, MemoryStream ms) + { + // SkyDesc is complex (sky objects, colors, etc). Skip by searching for next recognizable section. + // Store position and try to skip it. + try + { + // SkyDesc format: TickSize(double) + LightTickSize(double) + DayGroup(SkyObjectReplace) + NightGroup + ... + // This is very complex. We'll use a heuristic: skip forward looking for SceneDesc signature. + // For now, try to skip a known minimum size + reader.ReadDouble(); // TickSize + reader.ReadDouble(); // LightTickSize + + // DayGroup + SkipSkyObjectGroup(reader, ms); + // NightGroup + SkipSkyObjectGroup(reader, ms); + + return true; + } + catch + { + return false; + } + } + + private void SkipSkyObjectGroup(BinaryReader reader, MemoryStream ms) + { + // SkyObjectReplace: uint32 count + entries + uint count = reader.ReadUInt32(); + for (uint i = 0; i < count && ms.Position < ms.Length; i++) + { + reader.ReadUInt32(); // object index + reader.ReadUInt32(); // GfxObj ID + reader.ReadSingle(); // rotate + reader.ReadSingle(); // transparent + reader.ReadSingle(); // luminosity + reader.ReadSingle(); // max bright + } + } + + private bool SkipSoundDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // SoundDesc: List<AmbientSoundDesc> + uint count = reader.ReadUInt32(); + if (count > 200) return false; + for (uint i = 0; i < count && ms.Position < ms.Length; i++) + { + reader.ReadUInt32(); // SType + reader.ReadSingle(); // Volume + reader.ReadSingle(); // BaseChance + reader.ReadSingle(); // MinRate + reader.ReadSingle(); // MaxRate + } + return true; + } + catch + { + return false; + } + } + + private bool ParseSceneDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // SceneDesc: List<SceneType> + uint numSceneTypes = reader.ReadUInt32(); + if (numSceneTypes > 500) return false; + + _sceneTypes = new List<ScatterSceneType>(); + + for (uint i = 0; i < numSceneTypes; i++) + { + var st = new ScatterSceneType(); + st.StbIndex = reader.ReadUInt32(); + + // List<uint> Scenes + uint numScenes = reader.ReadUInt32(); + if (numScenes > 500) return false; + + st.SceneFileIds = new List<uint>(); + for (uint s = 0; s < numScenes; s++) + st.SceneFileIds.Add(reader.ReadUInt32()); + + _sceneTypes.Add(st); + } + + Log($"SceneDesc: {_sceneTypes.Count} scene types parsed"); + return true; + } + catch + { + return false; + } + } + + private bool ParseTerrainDesc(BinaryReader reader, MemoryStream ms) + { + try + { + // TerrainDesc: List<TerrainType> + LandSurf + uint numTerrainTypes = reader.ReadUInt32(); + if (numTerrainTypes > 100) return false; + + _terrainTypes = new List<ScatterTerrainType>(); + + for (uint i = 0; i < numTerrainTypes; i++) + { + var tt = new ScatterTerrainType(); + + // PString TerrainName + SkipPString(reader, ms); + + // uint32 TerrainColor + reader.ReadUInt32(); + + // List<uint> SceneTypes + uint numSceneTypes = reader.ReadUInt32(); + if (numSceneTypes > 200) return false; + + tt.SceneTypeIndices = new List<uint>(); + for (uint s = 0; s < numSceneTypes; s++) + tt.SceneTypeIndices.Add(reader.ReadUInt32()); + + _terrainTypes.Add(tt); + } + + Log($"TerrainDesc: {_terrainTypes.Count} terrain types parsed"); + return true; + } + catch + { + return false; + } + } + + // =================================================================== + // Fallback: scan RegionDesc data for recognizable table patterns + // =================================================================== + + private bool ScanForTables(byte[] data) + { + Log("Attempting fallback scan for scatter tables..."); + + // Strategy: Scan for SceneDesc (uint32 count followed by entries with 0x12xxxxxx scene IDs) + // The real AC SceneDesc has ~89 entries. We require at least 20 to avoid false positives. + // TerrainDesc (~32 entries with PString names) follows right after SceneDesc. + + for (int pos = 100; pos < data.Length - 100; pos += 4) + { + uint count = BitConverter.ToUInt32(data, pos); + if (count < 20 || count > 200) continue; + + // Validate: try to read all entries as SceneType { uint32 StbIndex, uint32 numScenes, uint32[] sceneIds } + bool valid = true; + int scanPos = pos + 4; + int totalSceneIds = 0; + + for (int i = 0; i < count && valid; i++) + { + if (scanPos + 8 > data.Length) { valid = false; break; } + + uint stbIndex = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + uint numScenes = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + if (numScenes > 200) { valid = false; break; } + + for (int s = 0; s < numScenes && valid; s++) + { + if (scanPos + 4 > data.Length) { valid = false; break; } + uint sceneId = BitConverter.ToUInt32(data, scanPos); + scanPos += 4; + + // Scene files are 0x12xxxxxx + if ((sceneId & 0xFF000000) != 0x12000000) { valid = false; break; } + totalSceneIds++; + } + } + + if (!valid || totalSceneIds < 10) continue; + + // We found a candidate SceneDesc! Parse it fully. + _sceneTypes = new List<ScatterSceneType>(); + int fullPos = pos + 4; + + for (int i = 0; i < count; i++) + { + if (fullPos + 8 > data.Length) break; + uint stbIdx = BitConverter.ToUInt32(data, fullPos); + fullPos += 4; + uint nScenes = BitConverter.ToUInt32(data, fullPos); + fullPos += 4; + + var st = new ScatterSceneType { StbIndex = stbIdx, SceneFileIds = new List<uint>() }; + for (int s = 0; s < nScenes; s++) + { + if (fullPos + 4 > data.Length) break; + st.SceneFileIds.Add(BitConverter.ToUInt32(data, fullPos)); + fullPos += 4; + } + _sceneTypes.Add(st); + } + + Log($"Fallback found SceneDesc at offset {pos}: {_sceneTypes.Count} types, {totalSceneIds} total scene IDs"); + + // Now parse TerrainDesc starting right after SceneDesc + if (fullPos + 4 < data.Length) + { + if (ParseTerrainDescFromOffset(data, fullPos)) + { + Log($"Fallback TerrainDesc succeeded: {_terrainTypes.Count} terrain types"); + return true; + } + else + { + Log($"TerrainDesc failed at offset {fullPos}, continuing scan..."); + _sceneTypes = null; + continue; // Try finding another SceneDesc + } + } + } + + Log("Fallback scan failed to find scatter tables"); + return false; + } + + private bool ParseTerrainDescFromOffset(byte[] data, int startPos) + { + try + { + _terrainTypes = new List<ScatterTerrainType>(); + int pos = startPos; + + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + uint count = BitConverter.ToUInt32(data, pos); + pos += 4; + + if (count < 5 || count > 100) { _terrainTypes = null; return false; } + + for (int i = 0; i < count; i++) + { + var tt = new ScatterTerrainType(); + + // PString: ushort length + chars + align to 4 + if (pos + 2 > data.Length) { _terrainTypes = null; return false; } + ushort strLen = BitConverter.ToUInt16(data, pos); + pos += 2; + + if (strLen > 200 || pos + strLen > data.Length) { _terrainTypes = null; return false; } + + // Verify it looks like a text string (ASCII printable) + if (i < 3 && strLen > 0) + { + bool isPrintable = true; + for (int c = 0; c < Math.Min((int)strLen, 10); c++) + { + byte b = data[pos + c]; + if (b < 32 || b > 126) { isPrintable = false; break; } + } + if (!isPrintable) { _terrainTypes = null; return false; } + + string name = System.Text.Encoding.ASCII.GetString(data, pos, strLen); + Log($" TerrainType[{i}]: \"{name}\""); + } + + pos += strLen; + pos = (pos + 3) & ~3; // Align to 4 + + // uint32 TerrainColor + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + pos += 4; + + // List<uint> SceneTypes + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + uint numST = BitConverter.ToUInt32(data, pos); + pos += 4; + + if (numST > 200) { _terrainTypes = null; return false; } + + tt.SceneTypeIndices = new List<uint>(); + for (int s = 0; s < numST; s++) + { + if (pos + 4 > data.Length) { _terrainTypes = null; return false; } + tt.SceneTypeIndices.Add(BitConverter.ToUInt32(data, pos)); + pos += 4; + } + + _terrainTypes.Add(tt); + } + + return _terrainTypes.Count >= 5; + } + catch + { + _terrainTypes = null; + return false; + } + } + + // =================================================================== + // Helpers + // =================================================================== + + private void SkipPString(BinaryReader reader, MemoryStream ms) + { + ushort len = reader.ReadUInt16(); + if (len > 0 && ms.Position + len <= ms.Length) + ms.Seek(len, SeekOrigin.Current); + // Align to 4 bytes + long alignedPos = (ms.Position + 3) & ~3L; + if (alignedPos <= ms.Length) + ms.Position = alignedPos; + } + + private void Log(string msg) + { + string line = $"[Scatter] {msg}"; + System.Diagnostics.Debug.WriteLine(line); + if (DiagLog.Count < 100) DiagLog.Add(msg); + } + } + + // =================================================================== + // Data structures for scatter system + // =================================================================== + + public class ScatterTerrainType + { + public List<uint> SceneTypeIndices = new List<uint>(); + } + + public class ScatterSceneType + { + public uint StbIndex; + public List<uint> SceneFileIds = new List<uint>(); + } + + public class ScatterObjectDesc + { + public uint ObjId; + public float BaseLocX, BaseLocY, BaseLocZ; + public float BaseLocW, BaseLocRX, BaseLocRY, BaseLocRZ; + public float Freq; + public float DisplaceX, DisplaceY; + public float MinScale, MaxScale; + public float MaxRotation; + public float MinSlope, MaxSlope; + public uint Align, Orient, WeenieObj; + } +} diff --git a/Plugins/RynthAi/Raycasting/TargetingFSM.cs b/Plugins/RynthAi/Raycasting/TargetingFSM.cs new file mode 100644 index 0000000..c925764 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/TargetingFSM.cs @@ -0,0 +1,364 @@ +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using System; +using System.Collections.Generic; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Provides line-of-sight checking for the combat system. + /// Converts Decal API coordinates to global meter space and + /// performs raycasting against loaded landblock geometry. + /// + /// Coordinate system: + /// AC uses a landblock grid where each block is 192×192 meters. + /// Landcell ID format: 0xXXYYnnnn where XX=east-west block, YY=north-south block. + /// LocationX/Y are local offsets within the landblock (0-192 meters). + /// + /// We convert everything to "global meters" for raycasting: + /// GlobalX = (XX * 192) + LocationX + /// GlobalY = (YY * 192) + LocationY + /// GlobalZ = LocationZ (altitude, 0 = sea level) + /// </summary> + public class TargetingFSM + { + private readonly GeometryLoader _geoLoader; + private readonly BlacklistManager _blacklist; + + // Attack type determines which raycast to use + public enum AttackType + { + Linear, // Bolts, streaks, crossbow bolts, melee + BowArc, // Bows — moderate arc, arrows go higher than you'd think + ThrownArc, // Thrown weapons, atlatls — similar arc to bows + MagicArc // War/Void magic Arc spells — same trajectory as missile weapons + } + + // AC arrows arc noticeably — they go HIGH. A lower velocity = higher arc. + // At 70 yard range, arrows visibly arc 3-4 meters above the direct line. + // This must match the actual game trajectory to detect ceiling hits in dungeons. + public float BowArcVelocity { get; set; } = 25.0f; + + // Thrown weapons arc similarly to bows + public float ThrownArcVelocity { get; set; } = 22.0f; + + // Magic arc spells (War/Void Arc) have the same trajectory as missile weapons + public float MagicArcVelocity { get; set; } = 25.0f; + + // If true, use arc checks for missile weapons. If false, treat all as linear. + public bool UseArcs { get; set; } = true; + + // Max scan distance in meters. Only check LOS for targets within this range. + // Set from CombatManager based on MonsterRange + buffer. + public float MaxScanDistanceMeters { get; set; } = 120.0f; + + public TargetingFSM(GeometryLoader geoLoader, BlacklistManager blacklist) + { + _geoLoader = geoLoader ?? throw new ArgumentNullException(nameof(geoLoader)); + _blacklist = blacklist ?? throw new ArgumentNullException(nameof(blacklist)); + } + + /// <summary> + /// Checks if line-of-sight to a target is blocked by geometry. + /// + /// Returns true if the target IS blocked (should skip this target). + /// Returns false if the target is clear to attack. + /// </summary> + public bool IsTargetBlocked(CoreManager core, WorldObject target, AttackType attackType) + { + if (core == null || target == null) + return false; + + if (!_geoLoader.IsInitialized) + return false; + + try + { + Vector3 origin = GetPlayerPosition(core); + if (origin == Vector3.Zero) + return false; + + Vector3 targetPos = GetObjectPosition(target, core); + if (targetPos == Vector3.Zero) + return false; + + // Early-out: skip raycast if target is beyond scan distance + float dx = targetPos.X - origin.X; + float dy = targetPos.Y - origin.Y; + float flatDist = (float)Math.Sqrt(dx * dx + dy * dy); + if (flatDist > MaxScanDistanceMeters) + return false; // Too far to bother checking, let combat handle range + + // Offset to chest height + origin.Z += 1.0f; + targetPos.Z += 1.0f; + + uint landcell = GetPlayerLandcell(core); + uint cellPart = landcell & 0xFFFF; + bool isDungeon = cellPart >= 0x0100; + + // Force linear checks indoors — arc trajectories hit ceilings + if (isDungeon) + attackType = AttackType.Linear; + + var geometry = _geoLoader.GetLandblockGeometry(landcell); + + if (geometry == null || geometry.Count == 0) + return false; + + // Pre-filter: skip full ray test if no geometry near the path + float margin = Math.Min(flatDist * 0.3f, 15.0f); + margin = Math.Max(margin, 3.0f); + if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin)) + return false; + + switch (attackType) + { + case AttackType.Linear: + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.BowArc: + if (UseArcs) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.ThrownArc: + if (UseArcs) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, ThrownArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + case AttackType.MagicArc: + // Magic Arc spells have the same trajectory as missile weapons + if (UseArcs && !isDungeon) // Don't arc-check in dungeons (ceiling clips) + { + if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry)) + return false; + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + } + return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + + default: + return false; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}"); + return false; + } + } + + /// <summary> + /// Finds the best unblocked target from a list of candidates. + /// Returns the target ID, or 0 if no clear target is found. + /// </summary> + public int FindBestTarget(CoreManager core, List<WorldObject> candidates, AttackType attackType) + { + if (core == null || candidates == null || candidates.Count == 0) + return 0; + + foreach (var candidate in candidates) + { + try + { + int id = candidate.Id; + + // Skip blacklisted targets + if (_blacklist.IsBlacklisted(id)) + continue; + + // Skip blocked targets + if (IsTargetBlocked(core, candidate, attackType)) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Target {id} blocked by geometry, skipping"); + continue; + } + + return id; // Found a clear target + } + catch + { + continue; + } + } + + return 0; // No clear targets + } + + /// <summary> + /// Gets the player's position in global meter coordinates. + /// Uses Decal's HooksWrapper (accessed via CoreManager.Actions). + /// + /// Landcell format: 0xXXYYnnnn + /// XX = east-west block index (0-254) + /// YY = north-south block index (0-254) + /// + /// LocationX/Y = offset within landblock (0-192 meters for outdoors) + /// LocationZ = altitude in meters (0 = sea level) + /// + /// Global conversion: + /// GlobalX = XX * 192 + LocationX + /// GlobalY = YY * 192 + LocationY + /// GlobalZ = LocationZ + /// </summary> + private Vector3 GetPlayerPosition(CoreManager core) + { + try + { + uint landcell = (uint)core.Actions.Landcell; + + uint blockX = (landcell >> 24) & 0xFF; + uint blockY = (landcell >> 16) & 0xFF; + + float localX = (float)core.Actions.LocationX; + float localY = (float)core.Actions.LocationY; + float localZ = (float)core.Actions.LocationZ; + + float globalX = blockX * 192.0f + localX; + float globalY = blockY * 192.0f + localY; + + return new Vector3(globalX, globalY, localZ); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error getting player pos: {ex.Message}"); + return Vector3.Zero; + } + } + + /// <summary> + /// Gets a world object's position in global meter coordinates. + /// Uses Decal's CoordsObject (EastWest/NorthSouth) and converts to meters. + /// + /// From Decal docs: + /// EW = ((Landcell >> 24) + LocationX / 24.0 - 1019.5) / 10.0 + /// NS = (((Landcell >> 16) & 0xFF) + LocationY / 24.0 - 1019.5) / 10.0 + /// + /// Reverse conversion (EW/NS → global meters): + /// GlobalX = (EW * 10.0 + 1019.5) * 24.0 + /// GlobalY = (NS * 10.0 + 1019.5) * 24.0 + /// </summary> + private Vector3 GetObjectPosition(WorldObject obj, CoreManager core) + { + try + { + var coords = obj.Coordinates(); + if (coords == null) + return Vector3.Zero; + + double ew = coords.EastWest; + double ns = coords.NorthSouth; + + float globalX = (float)((ew * 10.0 + 1019.5) * 24.0); + float globalY = (float)((ns * 10.0 + 1019.5) * 24.0); + + // Z coordinate: MUST come from RawCoordinates. + // If unavailable, return Zero to skip LOS (safer than guessing wrong Z). + float z = 0; + try + { + var raw = obj.RawCoordinates(); + if (raw != null) + z = (float)raw.Z; + else + return Vector3.Zero; // Can't determine Z — skip LOS + } + catch + { + return Vector3.Zero; // Can't determine Z — skip LOS + } + + return new Vector3(globalX, globalY, z); + } + catch + { + return Vector3.Zero; + } + } + + /// <summary> + /// Gets the player's current Landcell value for geometry lookup. + /// </summary> + private uint GetPlayerLandcell(CoreManager core) + { + try + { + return (uint)core.Actions.Landcell; + } + catch + { + return 0; + } + } + + /// <summary> + /// Determines the attack type based on combat mode and wielded weapon. + /// Magic mode ALWAYS returns Linear (spells travel straight). + /// Bows get a flat arc (high velocity). Thrown weapons arc more. + /// Melee and crossbows are Linear. + /// </summary> + public AttackType DetermineAttackType(CoreManager core) + { + try + { + // MAGIC MODE: Always linear — spells (bolts, streaks, arcs, rings) + // all use straight-line LOS in AC, regardless of equipped weapon + if (core.Actions.CombatMode == CombatState.Magic) + return AttackType.Linear; + + // PEACE MODE: Default to linear + if (core.Actions.CombatMode == CombatState.Peace) + return AttackType.Linear; + + // MELEE MODE: Linear (range check only, no projectile arc) + if (core.Actions.CombatMode == CombatState.Melee) + return AttackType.Linear; + + // MISSILE MODE: Check the actual weapon for bow vs crossbow vs thrown + foreach (var wo in core.WorldFilter.GetInventory()) + { + if (wo.Values((LongValueKey)10, 0) > 0) // CurrentWieldedLocation + { + if (wo.ObjectClass == ObjectClass.MissileWeapon) + { + string name = wo.Name?.ToLower() ?? ""; + + // Crossbows fire bolts in a straight line + if (name.Contains("crossbow")) + return AttackType.Linear; + + // Atlatls and thrown weapons arc more + if (name.Contains("atlatl") || name.Contains("thrown") || name.Contains("dart")) + return UseArcs ? AttackType.ThrownArc : AttackType.Linear; + + // Regular bows — fast, flat arc + if (name.Contains("bow")) + return UseArcs ? AttackType.BowArc : AttackType.Linear; + + // Unknown missile weapon — treat as bow arc + return UseArcs ? AttackType.BowArc : AttackType.Linear; + } + + // Wand in missile mode? Shouldn't happen, but treat as linear + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + return AttackType.Linear; + } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[Targeting] Error determining attack type: {ex.Message}"); + } + + return AttackType.Linear; // Default to linear + } + } +} diff --git a/Plugins/RynthAi/Raycasting/Vector3Helper.cs b/Plugins/RynthAi/Raycasting/Vector3Helper.cs new file mode 100644 index 0000000..40bfe81 --- /dev/null +++ b/Plugins/RynthAi/Raycasting/Vector3Helper.cs @@ -0,0 +1,143 @@ +using System; + +namespace NexSuite.Plugins.RynthAi.Raycasting +{ + /// <summary> + /// Custom Vector3 for the raycasting system. + /// + /// IMPORTANT: This replaces System.Numerics.Vector3 in the Raycasting namespace. + /// All Raycasting/*.cs files must NOT import System.Numerics to avoid type conflicts. + /// </summary> + public struct Vector3 + { + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + + public static readonly Vector3 Zero = new Vector3(0, 0, 0); + public static readonly Vector3 One = new Vector3(1, 1, 1); + public static readonly Vector3 Up = new Vector3(0, 0, 1); + + public Vector3(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + } + + // --- Conversion --- + + public static Vector3 FromNumerics(System.Numerics.Vector3 v) + => new Vector3(v.X, v.Y, v.Z); + + public System.Numerics.Vector3 ToNumerics() + => new System.Numerics.Vector3(X, Y, Z); + + public float[] ToArray() + => new float[] { X, Y, Z }; + + public static Vector3 FromArray(float[] arr) + { + if (arr == null || arr.Length < 3) return Zero; + return new Vector3(arr[0], arr[1], arr[2]); + } + + // --- Arithmetic operators --- + + public static Vector3 operator +(Vector3 a, Vector3 b) + => new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); + + public static Vector3 operator -(Vector3 a, Vector3 b) + => new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); + + public static Vector3 operator -(Vector3 v) + => new Vector3(-v.X, -v.Y, -v.Z); + + public static Vector3 operator *(Vector3 v, float s) + => new Vector3(v.X * s, v.Y * s, v.Z * s); + + public static Vector3 operator *(float s, Vector3 v) + => new Vector3(v.X * s, v.Y * s, v.Z * s); + + public static Vector3 operator /(Vector3 v, float s) + { + float inv = 1.0f / s; + return new Vector3(v.X * inv, v.Y * inv, v.Z * inv); + } + + // --- Vector math --- + + public static float Dot(Vector3 a, Vector3 b) + => a.X * b.X + a.Y * b.Y + a.Z * b.Z; + + public static Vector3 Cross(Vector3 a, Vector3 b) + => new Vector3( + a.Y * b.Z - a.Z * b.Y, + a.Z * b.X - a.X * b.Z, + a.X * b.Y - a.Y * b.X + ); + + public float Length() + => (float)Math.Sqrt(X * X + Y * Y + Z * Z); + + public float LengthSquared() + => X * X + Y * Y + Z * Z; + + public Vector3 Normalize() + { + float len = Length(); + if (len < 1e-8f) return Zero; + return this * (1.0f / len); + } + + public float Distance(Vector3 other) + => (this - other).Length(); + + public static Vector3 Min(Vector3 a, Vector3 b) + => new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z)); + + public static Vector3 Max(Vector3 a, Vector3 b) + => new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z)); + + public static Vector3 Lerp(Vector3 a, Vector3 b, float t) + => a + (b - a) * t; + + public float Length2D() + => (float)Math.Sqrt(X * X + Y * Y); + + // --- Equality --- + + public override bool Equals(object obj) + { + if (obj is Vector3 other) + return X == other.X && Y == other.Y && Z == other.Z; + return false; + } + + public override int GetHashCode() + => X.GetHashCode() ^ (Y.GetHashCode() << 8) ^ (Z.GetHashCode() << 16); + + public static bool operator ==(Vector3 a, Vector3 b) + => a.X == b.X && a.Y == b.Y && a.Z == b.Z; + + public static bool operator !=(Vector3 a, Vector3 b) + => !(a == b); + + public override string ToString() + => $"({X:F3}, {Y:F3}, {Z:F3})"; + + public float this[int i] + { + get + { + switch (i) + { + case 0: return X; + case 1: return Y; + case 2: return Z; + default: throw new IndexOutOfRangeException(); + } + } + } + } +} diff --git a/Plugins/RynthAi/RynthAi.csproj b/Plugins/RynthAi/RynthAi.csproj new file mode 100644 index 0000000..e7ee08f --- /dev/null +++ b/Plugins/RynthAi/RynthAi.csproj @@ -0,0 +1,174 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">x86</Platform> + <ProjectGuid>{AA060CDA-5478-4BFD-8CC3-B24827E19FC7}</ProjectGuid> + <OutputType>Library</OutputType> + <RootNamespace>NexSuite.Plugins.RynthAi</RootNamespace> + <AssemblyName>RynthAi</AssemblyName> + <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> + <LangVersion>8.0</LangVersion> + <FileAlignment>512</FileAlignment> + <NuGetPackageImportStamp> + </NuGetPackageImportStamp> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + <ItemGroup> + <Reference Include="Decal.Adapter"> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.Adapter.dll</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="Decal.FileService"> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.FileService.dll</HintPath> + </Reference> + <Reference Include="Decal.Interop.D3DService, Version=2.9.8.3, Culture=neutral, PublicKeyToken=481f17d392f1fb65, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <EmbedInteropTypes>False</EmbedInteropTypes> + <HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="KeraLua, Version=1.4.9.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL"> + <HintPath>..\..\packages\KeraLua.1.4.9\lib\net46\KeraLua.dll</HintPath> + </Reference> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> + <HintPath>..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath> + </Reference> + <Reference Include="NLua, Version=1.7.8.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL"> + <HintPath>..\..\packages\NLua.1.7.8\lib\net46\NLua.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Drawing" /> + <Reference Include="System.Numerics" /> + <Reference Include="System.Windows.Forms" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Xml.Serialization" /> + <Reference Include="utank2-i"> + <HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTank\utank2-i.dll</HintPath> + </Reference> + <Reference Include="UtilityBelt.Scripting"> + <HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Scripting.dll</HintPath> + </Reference> + <Reference Include="UtilityBelt.Service"> + <HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Service.dll</HintPath> + <Private>False</Private> + </Reference> + <Reference Include="VTClassic"> + <HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTankClassicLooter\VTClassic.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Shared\NexSuite.Shared.csproj"> + <Project>{11111111-1111-1111-1111-111111111111}</Project> + <Name>NexSuite.Shared</Name> + </ProjectReference> + <ProjectReference Include="..\..\Core\NexSuite.Core.csproj"> + <Project>{22222222-2222-2222-2222-222222222222}</Project> + <Name>NexSuite.Core</Name> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <Compile Include="Combat\BuffManager.cs" /> + <Compile Include="Combat\SpellDatabase.cs" /> + <Compile Include="Combat\SpellManager.cs" /> + <Compile Include="DecalInspector.cs" /> + <Compile Include="Logic\BackgroundFpsUnlocker.cs" /> + <Compile Include="Logic\CommandProcessor.cs" /> + <Compile Include="Logic\RynthJumper.cs" /> + <Compile Include="Loot\LootManager.cs" /> + <Compile Include="Loot\VTankLootParser.cs" /> + <Compile Include="Lua\LuaBridge.cs" /> + <Compile Include="Lua\LuaManager.cs" /> + <Compile Include="Meta\MetaManager.cs" /> + <Compile Include="Meta\VTankMetaParser.cs" /> + <Compile Include="Nav\NavigationManager.cs" /> + <Compile Include="Nav\MovementActionHelper.cs" /> + <Compile Include="Nav\Tier2Log.cs" /> + <Compile Include="Nav\Tier2MovementHelper.cs" /> + <Compile Include="Nav\VTankNavParser.cs" /> + <Compile Include="Combat\CombatManager.cs" /> + <Compile Include="Combat\MissileCraftingManager.cs" /> + <Compile Include="Combat\CombatActionHelper.cs" /> + <Compile Include="Combat\FellowshipTracker.cs" /> + <Compile Include="PluginCore.cs" /> + <Compile Include="Raycasting\DatDatabase.cs" /> + <Compile Include="Raycasting\DungeonLOS.cs" /> + <Compile Include="Raycasting\LandblockStructs.cs" /> + <Compile Include="Raycasting\ScatterSystem.cs" /> + <Compile Include="Raycasting\Vector3Helper.cs" /> + <Compile Include="UI\AdvancedSettingsUI.cs" /> + <Compile Include="UI\LuaUI.cs" /> + <Compile Include="UI\MetaUI.cs" /> + <Compile Include="UI\MonstersUI.cs" /> + <Compile Include="UI\RynthAiUI.cs"> + <SubType>Form</SubType> + </Compile> + <Compile Include="UI\RynthAiUI.Rendering.cs" /> + <Compile Include="Raycasting\RaycastEngine.cs" /> + <Compile Include="Raycasting\BoundingVolume.cs" /> + <Compile Include="Raycasting\TargetingFSM.cs" /> + <Compile Include="Raycasting\BlacklistManager.cs" /> + <Compile Include="Raycasting\GeometryLoader.cs" /> + <Compile Include="Raycasting\MainLogic.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="UI\RouteUI.cs" /> + <Compile Include="UI\UISettings.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="app.config" /> + <None Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="Combat\Vtank spelldump.txt" /> + </ItemGroup> + <ItemGroup> + <COMReference Include="Decal"> + <Guid>{FF7F5F6D-34E0-4B6F-B3BB-8141DE2EF732}</Guid> + <VersionMajor>2</VersionMajor> + <VersionMinor>0</VersionMinor> + <Lcid>0</Lcid> + <WrapperTool>primary</WrapperTool> + <Isolated>False</Isolated> + <EmbedInteropTypes>True</EmbedInteropTypes> + </COMReference> + <COMReference Include="DecalNet"> + <Guid>{572B87C4-93BD-46B3-A291-CD58181D25DC}</Guid> + <VersionMajor>2</VersionMajor> + <VersionMinor>0</VersionMinor> + <Lcid>0</Lcid> + <WrapperTool>primary</WrapperTool> + <Isolated>False</Isolated> + <EmbedInteropTypes>True</EmbedInteropTypes> + </COMReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets" Condition="Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" /> + <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets'))" /> + </Target> +</Project> \ No newline at end of file diff --git a/Plugins/RynthAi/UI/AdvancedSettingsUI.cs b/Plugins/RynthAi/UI/AdvancedSettingsUI.cs new file mode 100644 index 0000000..fead046 --- /dev/null +++ b/Plugins/RynthAi/UI/AdvancedSettingsUI.cs @@ -0,0 +1,483 @@ +using System; +using System.Numerics; +using ImGuiNET; + +namespace NexSuite.Plugins.RynthAi +{ + public class AdvancedSettingsUI + { + private readonly UISettings _settings; + private MissileCraftingManager _missileCraftingManager; + public Action OnSettingsChanged; + + 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 AdvancedSettingsUI(UISettings settings) + { + _settings = settings; + } + + public void SetMissileCraftingManager(MissileCraftingManager mgr) + { + _missileCraftingManager = mgr; + } + + public void Render() + { + if (!_settings.ShowAdvancedWindow) return; + + // Set a default size for the popup window + ImGui.SetNextWindowSize(new Vector2(600, 400), ImGuiCond.FirstUseEver); + + if (ImGui.Begin("RynthAi Advanced Settings", ref _settings.ShowAdvancedWindow)) + { + // --- LEFT COLUMN (Sidebar) --- + ImGui.BeginChild("AdvancedSidebar", new Vector2(150, 0), true); + 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(); + + // --- RIGHT COLUMN (Content) --- + ImGui.BeginGroup(); + ImGui.BeginChild("AdvancedContent", new Vector2(0, -ImGui.GetFrameHeightWithSpacing()), true); + + RenderTabContent(_settings.SelectedAdvancedTab); + + ImGui.EndChild(); + + // Bottom Buttons + 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 System.Numerics.Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}"); + ImGui.Separator(); + ImGui.Spacing(); + + // Note: Ensure your AdvancedSettingsUI class has an 'Action OnSettingsChanged' + // property that you set in the RynthAiUI constructor to handle auto-saving. + + switch (tabName) + { + case "Misc": + // --- FPS THROTTLING --- + if (ImGui.Checkbox("Enable FPS Limit", ref _settings.EnableFPSLimit)) OnSettingsChanged?.Invoke(); + if (_settings.EnableFPSLimit) + { + ImGui.Indent(); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Focused FPS", ref _settings.TargetFPSFocused, 10, 240)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Background FPS", ref _settings.TargetFPSBackground, 5, 60)) OnSettingsChanged?.Invoke(); + ImGui.Unindent(); + } + + ImGui.Separator(); + ImGui.Spacing(); + + // --- INVENTORY MANAGEMENT --- + // Uses EnableAutocram from UISettings + if (ImGui.Checkbox("Auto Cram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Automatically moves items from your main pack into side packs.\n" + + "Note: Recently used weapons will stay in the main pack for quick access."); + } + + ImGui.Spacing(); + + // --- GENERAL BEHAVIOR --- + if (ImGui.Checkbox("Peace Mode When Idle", ref _settings.PeaceModeWhenIdle)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting)) OnSettingsChanged?.Invoke(); + + ImGui.Separator(); + ImGui.Spacing(); + + // --- COMBAT BLACKLIST --- + ImGui.Text("Monster Blacklist"); + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Attempts Before Blacklist", ref _settings.BlacklistAttempts, 1, 20)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("How many failed attack attempts on a mob before it gets blacklisted.\n" + + "Helps avoid getting stuck on mobs clipped into walls or geometry."); + } + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Blacklist Timeout (sec)", ref _settings.BlacklistTimeoutSec, 5, 120)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("How long (seconds) a blacklisted mob is ignored before re-trying."); + } + break; + + case "Recharge": + ImGui.Text("Self Vitals (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Top-Off Vitals (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top HP", ref _settings.TopOffHP, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top Stam", ref _settings.TopOffStam, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Top Mana", ref _settings.TopOffMana, 0, 100)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Helper Settings (%)"); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Heal Others", ref _settings.HealOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Re-stam Others", ref _settings.RestamOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Infuse Others", ref _settings.InfuseOthersAt, 0, 100)) OnSettingsChanged?.Invoke(); + break; + + case "Melee Combat": + ImGui.Text("Attack Power & Height"); + ImGui.Separator(); + + // --- USE RECKLESSNESS --- + if (ImGui.Checkbox("Use Recklessness", ref _settings.UseRecklessness)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When enabled and Recklessness is trained,\nauto power is set to 80% instead of 100%.\nThis activates the Recklessness damage bonus."); + + ImGui.Spacing(); + + // --- MELEE ATTACK POWER --- + bool meleeAuto = _settings.MeleeAttackPower < 0; + if (ImGui.Checkbox("Melee Auto Power", ref meleeAuto)) + { + _settings.MeleeAttackPower = meleeAuto ? -1 : 100; + OnSettingsChanged?.Invoke(); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on."); + if (!meleeAuto) + { + ImGui.Indent(); + int mPwr = _settings.MeleeAttackPower; + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Melee Power %", ref mPwr, 0, 100)) + { + _settings.MeleeAttackPower = mPwr; + OnSettingsChanged?.Invoke(); + } + ImGui.Unindent(); + } + + // --- MELEE ATTACK HEIGHT --- + ImGui.SetNextItemWidth(120); + if (ImGui.Combo("Melee Attack Height", ref _settings.MeleeAttackHeight, _attackHeights, _attackHeights.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down"); + + ImGui.Spacing(); + + // --- MISSILE ATTACK POWER --- + bool missileAuto = _settings.MissileAttackPower < 0; + if (ImGui.Checkbox("Missile Auto Power", ref missileAuto)) + { + _settings.MissileAttackPower = missileAuto ? -1 : 100; + OnSettingsChanged?.Invoke(); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on."); + if (!missileAuto) + { + ImGui.Indent(); + int rPwr = _settings.MissileAttackPower; + ImGui.SetNextItemWidth(150); + if (ImGui.SliderInt("Missile Power %", ref rPwr, 0, 100)) + { + _settings.MissileAttackPower = rPwr; + OnSettingsChanged?.Invoke(); + } + ImGui.Unindent(); + } + + // --- MISSILE ATTACK HEIGHT --- + ImGui.SetNextItemWidth(120); + if (ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, _attackHeights, _attackHeights.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down"); + + ImGui.Separator(); + ImGui.Spacing(); + + // You can add weapon-specific toggles here later + if (ImGui.Checkbox("Summon Pets", ref _settings.SummonPets)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Pet Min Monsters", ref _settings.PetMinMonsters)) OnSettingsChanged?.Invoke(); + break; + + case "Spell Combat": + ImGui.Text("War/Void Casting Settings"); + ImGui.Separator(); + if (ImGui.Checkbox("Cast Dispel Self", ref _settings.CastDispelSelf)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Ring Spell Override"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Min Ring Targets", ref _settings.MinRingTargets)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("If this many monsters are within Ring Range,\nring spells are used instead of arc/bolt/streak.\nSet to 0 to disable the override.\nDefault: 4"); + } + break; + + case "Ranges": + ImGui.Text("Standard Ranges (Yards)"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Monster Range", ref _settings.MonsterRange)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Detection range in yards. Same units as VTank.\n" + + "Max bow range ≈ 70 yards. Magic ≈ 68 yards.\n" + + "AC internal = yards / 240"); + } + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Ring Range", ref _settings.RingRange)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("Distance at which Ring spells are used instead of other shapes."); + } + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Approach Range", ref _settings.ApproachRange)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Corpse Acquisition (AC Units)"); + ImGui.Separator(); + // MOVED FROM MAIN TAB + ImGui.SetNextItemWidth(180); + if (ImGui.InputDouble("Corpse Max", ref _settings.CorpseApproachRangeMax, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(180); + if (ImGui.InputDouble("Corpse Min", ref _settings.CorpseApproachRangeMin, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke(); + break; + + case "Navigation": + if (ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputFloat("Follow/Nav Min", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f")) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Movement Engine"); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Mode", ref _settings.MovementMode, _movementModes, _movementModes.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Legacy: SetAutorun + TurnLeft/TurnRight (VTank-style)\n" + + "Tier 1: Direct CM_Movement server events\n" + + "Tier 2: Client physics MoveToPosition (smooth arcs, experimental)"); + if (_settings.MovementMode == 2 && !Tier2MovementHelper.IsInitialized) + { + ImGui.SameLine(); + ImGui.TextColored(new Vector4(1, 0.4f, 0.4f, 1), "(not initialized)"); + } + + // ── Steering (all modes) ───────────────────────────────── + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Steering"); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Stop & Turn Angle", ref _settings.NavStopTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop forward motion and turn in place when heading error exceeds this many degrees.\nLower = more precise but stop-start. Higher = wider arcs."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Resume Run Angle", ref _settings.NavResumeTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Resume running once the turn-in-place error drops below this.\nMust be less than Stop & Turn Angle."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Dead Zone", ref _settings.NavDeadZone, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Ignore heading corrections smaller than this.\nSmaller = tighter line but more twitchy. Larger = smoother but wider path."); + + ImGui.SetNextItemWidth(80); + if (ImGui.InputFloat("Sweep Detect Mult", ref _settings.NavSweepMult, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Closest-approach detection radius = Arrival Radius * this.\nIf distance was decreasing and starts increasing within this radius, advance to next waypoint.\nHigher = more forgiving on tight turns. Lower = must pass closer."); + + // ── Tier 2 tuning (only visible when mode 2 selected) ──── + if (_settings.MovementMode == 2) + { + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Tier 2 Tuning"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Speed##t2", ref _settings.T2Speed, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Movement speed multiplier (1.0 = normal run speed)"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Walk Within (yd)", ref _settings.T2WalkWithinYd, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Switch from run to walk when within this many yards of the waypoint.\n0 = always run."); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Stop Distance (yd)", ref _settings.T2DistanceTo, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop this far from the target position (yards)"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Reissue Timeout (ms)", ref _settings.T2ReissueMs, 100f, 500f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-send MoveToPosition if no progress after this many ms"); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputFloat("Max Range (yd)", ref _settings.T2MaxRangeYd, 50f, 100f, "%.0f")) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Clamp waypoint distance to this. Will re-issue as you get closer."); + + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Max Landblock Dist", ref _settings.T2MaxLandblocks, 1)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Skip MoveToPosition if target is more than N landblocks away"); + } + break; + + case "Buffing": + if (ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle)) OnSettingsChanged?.Invoke(); + break; + + case "Looting": + if (ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses)) OnSettingsChanged?.Invoke(); + + ImGui.Spacing(); + ImGui.Text("Corpse Ownership"); + ImGui.SetNextItemWidth(180); + if (ImGui.Combo("Loot From", ref _settings.LootOwnership, _lootOwnershipModes, _lootOwnershipModes.Length)) + OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("My Kills Only: Only loot corpses you killed.\nFellowship Kills: Loot kills by any fellowship member.\nAll Corpses: Loot everything within range."); + + ImGui.Spacing(); + ImGui.Text("Inventory Management"); + if (ImGui.Checkbox("Enable Autostack", ref _settings.EnableAutostack)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Enable Autocram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke(); + if (ImGui.Checkbox("Combine Salvage Bags", ref _settings.EnableCombineSalvage)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + { + ImGui.SetTooltip("When enabled, salvage bags of the same material type\nare automatically combined after salvaging."); + } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Loot Timers (ms)"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Inter-Item Delay", ref _settings.LootInterItemDelayMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay between picking up each item from a corpse."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Content Settle", ref _settings.LootContentSettleMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Wait for corpse contents to populate after opening."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("How long to wait before declaring a corpse empty."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Closing Delay", ref _settings.LootClosingDelayMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay before closing corpse after all items looted."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Assess Window", ref _settings.LootAssessWindowMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Max time to wait for item ID data from server."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Retry picking up an item after this many ms."); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Corpse Open Retry", ref _settings.LootOpenRetryMs)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("If corpse doesn't open, retry UseItem after this many ms.\nLower = faster but may toggle-close an already-opening corpse."); + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Salvage Timers (ms) — First / Fast"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Open (First)", ref _settings.SalvageOpenDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Open (Fast)", ref _settings.SalvageOpenDelayFastMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Add Item (First)", ref _settings.SalvageAddDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Add Item (Fast)", ref _settings.SalvageAddDelayFastMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Salvage Click", ref _settings.SalvageSalvageDelayMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Result (First)", ref _settings.SalvageResultDelayFirstMs)) OnSettingsChanged?.Invoke(); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Result (Fast)", ref _settings.SalvageResultDelayFastMs)) OnSettingsChanged?.Invoke(); + break; + + case "Crafting": + ImGui.Text("Missile Ammo Crafting"); + ImGui.Separator(); + ImGui.Spacing(); + + if (ImGui.Checkbox("Enable Missile Crafting", ref _settings.EnableMissileCrafting)) OnSettingsChanged?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto-manage missile ammo when the ammo slot is empty:\n\n1. If better ammo can be crafted from bundles → craft it\n2. Otherwise equip the best loose ammo in inventory\n3. If no ammo exists → craft from bundles, then equip\n\nRequires Fletching skill (Trained or Specialized).\nEach combine: 1 head bundle + 1 shaft bundle = 1000 ammo."); + + if (!_settings.EnableMissileCrafting) { ImGui.TextDisabled("(Disabled)"); break; } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Spacing(); + + if (_missileCraftingManager != null) + { + string stateLabel = _missileCraftingManager.State.ToString(); + Vector4 stateColor = _missileCraftingManager.IsCrafting + ? new Vector4(0.2f, 1.0f, 0.4f, 1.0f) + : new Vector4(0.6f, 0.6f, 0.6f, 1.0f); + + ImGui.TextColored(stateColor, "State: " + stateLabel); + + if (!string.IsNullOrEmpty(_missileCraftingManager.StatusMessage)) + ImGui.TextWrapped(_missileCraftingManager.StatusMessage); + } + else + { + ImGui.TextDisabled("Crafting manager not initialized."); + } + + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Spacing(); + + ImGui.TextDisabled("Ammo Types (by priority, highest first):"); + ImGui.BulletText("Lethal Prismatic (Specialized)"); + ImGui.BulletText("Deadly Prismatic (Specialized)"); + ImGui.BulletText("Greater Prismatic (Trained)"); + ImGui.BulletText("Prismatic (Trained)"); + ImGui.BulletText("Armor Piercing, Broad, Blunt, etc. (Trained)"); + ImGui.Spacing(); + ImGui.TextDisabled("Weapon → Ammo:"); + ImGui.BulletText("Bow → Arrows (arrowheads + arrowshafts)"); + ImGui.BulletText("Crossbow → Quarrels (quarrelheads + quarrelshafts)"); + ImGui.BulletText("Atlatl → Darts (dart heads + dart shafts)"); + break; + + default: + ImGui.Text($"Settings for {tabName} are currently under development."); + break; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/LuaUI.cs b/Plugins/RynthAi/UI/LuaUI.cs new file mode 100644 index 0000000..ed34586 --- /dev/null +++ b/Plugins/RynthAi/UI/LuaUI.cs @@ -0,0 +1,157 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class LuaUI + { + private readonly UISettings _settings; + private readonly Decal.Adapter.CoreManager _core; + + // Delegates for PluginCore to hook into + public Action OnSettingsChanged; + public Action<string> OnExecuteRequested; + public Action OnStopRequested; + + // Internal State + private string _luaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LuaScripts"; + private string _newLuaFileName = "MyScript"; + private int _selectedLuaIdx = 0; + public List<string> LuaFiles = new List<string>(); + + private string _selectedSnippetKey = "--- Select Snippet ---"; + private Dictionary<string, string> _luaSnippets = new Dictionary<string, string> + { + { "--- 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 LuaUI(UISettings settings, Decal.Adapter.CoreManager core) + { + _settings = settings; + _core = core; + RefreshLuaFiles(); + } + + public void RefreshLuaFiles() + { + LuaFiles.Clear(); + LuaFiles.Add("None"); + if (Directory.Exists(_luaFolder)) + { + foreach (var file in Directory.GetFiles(_luaFolder, "*.lua")) + LuaFiles.Add(Path.GetFileNameWithoutExtension(file)); + } + } + + public void Render() + { + // Safety Checks + if (_settings.LuaScript == null) _settings.LuaScript = ""; + if (_settings.LuaConsoleOutput == null) _settings.LuaConsoleOutput = ""; + + // 1. File & Snippet Bar + RenderTopBar(); + + ImGui.Separator(); + + // 2. Toolbar (Run, Stop, Clear) + RenderToolbar(); + + ImGui.Separator(); + + // 3. Editor & Console + RenderEditorAndConsole(); + } + + 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); + 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), true, 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/RynthAi/UI/MetaUI.cs b/Plugins/RynthAi/UI/MetaUI.cs new file mode 100644 index 0000000..d1937d2 --- /dev/null +++ b/Plugins/RynthAi/UI/MetaUI.cs @@ -0,0 +1,650 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Linq; +using ImGuiNET; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public class MetaUI + { + private readonly UISettings _settings; + private readonly List<string> _navFiles; // Passed in so we can embed routes + + public Action OnSettingsChanged; + public Action OnMetaRulesUpdated; + + // --- META STATE --- + private bool _showMetaEditor = false; + private MetaRule _editingRule = new MetaRule(); + private int _editingRuleIndex = -1; + private string _newStateName = ""; + + // --- META DICTIONARIES --- + private readonly string[] _metaConditionNames = { + "Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=", + "Seconds in State >=", "Character Death", "Any Vendor Open", + "Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=", + "Monster Name Count Within Distance", "Monster Priority Count Within Distance", + "Need To Buff", "No Monsters Within Distance", "Landblock ==", + "Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not", + "Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=", + "Burden Percentage >=", "Dist Any Route PT >=", "Expression", + "Chat Message Capture", "Navroute Empty" + }; + + private readonly string[] _metaActionNames = { + "None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All", + "Call Meta State", "Return From Call", "Expression Action", "Chat Expression", + "Set Watchdog", "Clear Watchdog", "Get NT Option", "Set NT Option", + "Create View", "Destroy View", "Destroy All Views" + }; + + public MetaUI(UISettings settings, List<string> navFiles) + { + _settings = settings; + _navFiles = navFiles; + } + + public void Render() + { + if (ImGui.BeginTable("MetaRulesTable", 6, ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, -35))) + { + ImGui.TableSetupColumn("Up", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Dn", ImGuiTableColumnFlags.WidthFixed, 20); + ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 25); + ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Condition", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableHeadersRow(); + + var groupedRules = _settings.MetaRules + .GroupBy(r => r.State) + .OrderBy(g => g.Key) + .ToList(); + + foreach (var group in groupedRules) + { + ImGui.TableNextRow(); + ImGui.TableSetColumnIndex(3); + ImGui.TextColored(new Vector4(0, 1, 1, 1), $"--- State: {group.Key} ---"); + + var stateRules = group.ToList(); + for (int i = 0; i < stateRules.Count; i++) + { + var rule = stateRules[i]; + int globalIdx = _settings.MetaRules.IndexOf(rule); + + ImGui.TableNextRow(); + + bool isFired = rule.HasFired; + if (isFired) ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.2f, 0.2f, 1f)); + + ImGui.TableNextColumn(); + if (i > 0 && ImGui.Button($"^##up{globalIdx}")) + { + var prevRule = stateRules[i - 1]; + int prevGlobalIdx = _settings.MetaRules.IndexOf(prevRule); + _settings.MetaRules[globalIdx] = prevRule; + _settings.MetaRules[prevGlobalIdx] = rule; + OnSettingsChanged?.Invoke(); + } + + ImGui.TableNextColumn(); + if (i < stateRules.Count - 1 && ImGui.Button($"v##dn{globalIdx}")) + { + var nextRule = stateRules[i + 1]; + int nextGlobalIdx = _settings.MetaRules.IndexOf(nextRule); + _settings.MetaRules[globalIdx] = nextRule; + _settings.MetaRules[nextGlobalIdx] = rule; + OnSettingsChanged?.Invoke(); + } + + ImGui.TableNextColumn(); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1, 0, 0, 1)); + if (ImGui.Button($"X##delm{globalIdx}")) { _settings.MetaRules.Remove(rule); OnSettingsChanged?.Invoke(); } + ImGui.PopStyleColor(); + + ImGui.TableNextColumn(); + if (ImGui.Selectable($"{rule.State}##edit{globalIdx}", false, ImGuiSelectableFlags.SpanAllColumns)) + { + _editingRule = new MetaRule { State = rule.State, Condition = rule.Condition, ConditionData = rule.ConditionData, Action = rule.Action, ActionData = rule.ActionData }; + if (rule.Children != null) + { + string json = Newtonsoft.Json.JsonConvert.SerializeObject(rule.Children); + _editingRule.Children = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MetaRule>>(json); + } + _editingRuleIndex = globalIdx; + _showMetaEditor = true; + } + + ImGui.TableNextColumn(); + ImGui.Text(rule.Condition.ToString() + (string.IsNullOrEmpty(rule.ConditionData) ? "" : $": {rule.ConditionData}")); + + ImGui.TableNextColumn(); + if (rule.Action == MetaActionType.All) + { + int childCount = rule.Children?.Count ?? 0; + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions]"); + } + 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)"); + } + else + { + ImGui.Text(rule.Action.ToString() + (string.IsNullOrEmpty(rule.ActionData) ? "" : $": {rule.ActionData}")); + } + + if (isFired) ImGui.PopStyleColor(); + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + + bool isMetaEnabled = _settings.EnableMeta; + if (ImGui.Checkbox("Enable Meta", ref isMetaEnabled)) + { + _settings.EnableMeta = isMetaEnabled; + OnSettingsChanged?.Invoke(); + } + + ImGui.SameLine(); + ImGui.Text("Current State:"); + ImGui.SameLine(); + + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##CurrentStateDropdown", _settings.CurrentState)) + { + if (ImGui.Selectable("< Create New State >")) + { + ImGui.OpenPopup("CreateStatePopup"); + } + + 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; + OnSettingsChanged?.Invoke(); + } + } + ImGui.EndCombo(); + } + + if (ImGui.BeginPopupModal("CreateStatePopup", ref _showMetaEditor, 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 = ""; + OnSettingsChanged?.Invoke(); + } + 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(); + } + + private void RenderMetaEditorPopup() + { + if (_showMetaEditor) ImGui.OpenPopup("Edit Meta Rule"); + + ImGui.SetNextWindowSize(new Vector2(650, 450), ImGuiCond.Appearing); + + if (ImGui.BeginPopupModal("Edit Meta Rule", ref _showMetaEditor, ImGuiWindowFlags.NoCollapse)) + { + 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), true); + + 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), true); + 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))) + { + if (_editingRuleIndex == -1) _settings.MetaRules.Add(_editingRule); + else _settings.MetaRules[_editingRuleIndex] = _editingRule; + + OnSettingsChanged?.Invoke(); + OnMetaRulesUpdated?.Invoke(); + + _showMetaEditor = false; + } + + ImGui.SameLine(); + if (ImGui.Button("Cancel", new Vector2(100, 25))) { _showMetaEditor = false; } + + ImGui.EndPopup(); + } + } + + 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(-1); + if (ImGui.InputText("##InvName", ref itemName, 64)) + rule.ConditionData = $"{itemName},{itemCount}"; + + 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.NoMonstersWithinDistance: + 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; + } + } + + if (needsData) + { + float availableSpace = ImGui.GetWindowWidth() - ImGui.GetCursorPosX() - 40f; + ImGui.SetNextItemWidth(Math.Max(50f, availableSpace)); + + string cData = rule.ConditionData ?? ""; + if (ImGui.InputTextWithHint("##Data", condHint, ref cData, 256)) + rule.ConditionData = 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 if (rule.Children != null) rule.Children.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.Children.Add(new MetaRule { Action = MetaActionType.ChatCommand }); + } + ImGui.PopStyleColor(); + + ImGui.Indent(20f); + for (int i = 0; i < rule.Children.Count; i++) + { + var child = rule.Children[i]; + ImGui.PushID($"act_child_{i}"); + + if (ImGui.Button("X")) + { + rule.Children.RemoveAt(i); + i--; + } + else + { + ImGui.SameLine(); + RenderRuleActionNode(child, $"child_node_{i}"); + } + + ImGui.PopID(); + if (i < rule.Children.Count - 1) ImGui.Separator(); + } + ImGui.Unindent(20f); + } + else + { + switch (rule.Action) + { + case MetaActionType.ChatCommand: + string cmd = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##Cmd", "e.g. /tell {1} hello!", ref cmd, 256)) + rule.ActionData = cmd; + break; + + case MetaActionType.SetMetaState: + case MetaActionType.CallMetaState: + string state = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##State", "Target State Name...", ref state, 64)) + rule.ActionData = state; + break; + + case MetaActionType.EmbeddedNavRoute: + if (ImGui.BeginCombo("##NavSelect", string.IsNullOrEmpty(rule.ActionData) ? "Select Route..." : rule.ActionData)) + { + foreach (var navFile in _navFiles) + { + if (navFile == "None") 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.SetNTOption: + string[] ntParts = (rule.ActionData ?? "EnableBuffing;False").Split(';'); + string ntO = ntParts[0]; + string ntV = ntParts.Length > 1 ? ntParts[1] : "False"; + + ImGui.Text("Option:"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputText("##NTOpt", ref ntO, 64)) rule.ActionData = $"{ntO};{ntV}"; + + ImGui.SameLine(); + ImGui.Text("Val:"); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##NTVal", ref ntV, 64)) rule.ActionData = $"{ntO};{ntV}"; + break; + + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + string expr = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputTextWithHint("##Expr", "Expression (e.g. [SlotCount] < 5)", ref expr, 256)) + rule.ActionData = expr; + break; + + case MetaActionType.GetNTOption: + case MetaActionType.CreateView: + case MetaActionType.DestroyView: + string vData = rule.ActionData ?? ""; + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText("##ViewData", ref vData, 128)) + rule.ActionData = 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(); + } + + // ── Floating window wrapper (called from dashboard) ────────────────── + public void RenderAsWindow(ref bool open) + { + ImGui.SetNextWindowSize(new Vector2(600, 460), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Macro Rules##RynthAiMeta", ref open)) + Render(); + ImGui.End(); + } + + private void ClearConditionDataIfNeeded(MetaRule rule) + { + switch (rule.Condition) + { + case MetaConditionType.Always: + case MetaConditionType.Never: + case MetaConditionType.CharacterDeath: + case MetaConditionType.AnyVendorOpen: + case MetaConditionType.VendorClosed: + case MetaConditionType.PortalspaceEntered: + case MetaConditionType.PortalspaceExited: + case MetaConditionType.NavrouteEmpty: + rule.ConditionData = ""; + break; + + case MetaConditionType.All: + case MetaConditionType.Any: + case MetaConditionType.Not: + rule.ConditionData = ""; + break; + } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/MonstersUI.cs b/Plugins/RynthAi/UI/MonstersUI.cs new file mode 100644 index 0000000..0a838c3 --- /dev/null +++ b/Plugins/RynthAi/UI/MonstersUI.cs @@ -0,0 +1,282 @@ +using System; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class MonstersUI + { + private readonly UISettings _settings; + private readonly CoreManager _core; + + public Action OnSettingsChanged; + + // Local state just for this tab + private string _newMonsterName = ""; + private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + public MonstersUI(UISettings settings, CoreManager core) + { + _settings = settings; + _core = core; + } + + public void Render() + { + if (ImGui.BeginTable("MonstersGrid", 18, ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, 300))) + { + 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, 25); + 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("Del", ImGuiTableColumnFlags.WidthFixed, 30); + + ImGui.TableHeadersRow(); + + uint checkColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 1.0f, 0.2f, 1.0f)); + uint offColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 0.3f, 0.3f, 1.0f)); + + for (int i = 0; i < _settings.MonsterRules.Count; i++) + { + var rule = _settings.MonsterRules[i]; + bool isDefault = rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase); + + ImGui.TableNextRow(); + + // --- 9 Toggle Lights --- + ImGui.TableNextColumn(); + if (DrawToggleLight($"##F{i}", rule.Fester, checkColor, offColor, "F: Fester (Decrepitude's Grasp / Fester Other I-VIII)")) + { rule.Fester = !rule.Fester; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##B{i}", rule.Broadside, checkColor, offColor, "B: Broadside (Broadside of a Barn / Missile Weapons Ineptitude I-VIII)")) + { rule.Broadside = !rule.Broadside; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##G{i}", rule.GravityWell, checkColor, offColor, "G: Gravity Well (Vulnerability Other I-VIII)")) + { rule.GravityWell = !rule.GravityWell; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##I{i}", rule.Imperil, checkColor, offColor, "I: Imperil (Gossamer Flesh / Imperil Other I-VIII)")) + { rule.Imperil = !rule.Imperil; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##Y{i}", rule.Yield, checkColor, offColor, "Y: Yield (Magic Yield Other I-VIII)")) + { rule.Yield = !rule.Yield; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##V{i}", rule.Vuln, checkColor, offColor, "V: Vulnerability (element-matched)")) + { rule.Vuln = !rule.Vuln; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##A{i}", rule.UseArc, checkColor, offColor, "A: Arc spells (War/Void magic)\nFor Melee/Missile: Attack toggle")) + { rule.UseArc = !rule.UseArc; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##Bl{i}", rule.UseBolt, checkColor, offColor, "Bl: Bolt spells (War/Void magic, default)\nIf none of A/Bl/R/S set in magic = no attack (buff bot)")) + { rule.UseBolt = !rule.UseBolt; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##R{i}", rule.UseRing, checkColor, offColor, "R: Ring spells (uses Ring Range)")) + { rule.UseRing = !rule.UseRing; OnSettingsChanged?.Invoke(); } + + ImGui.TableNextColumn(); + if (DrawToggleLight($"##S{i}", rule.UseStreak, checkColor, offColor, "S: Streak spells (War/Void magic)")) + { rule.UseStreak = !rule.UseStreak; OnSettingsChanged?.Invoke(); } + + // --- Name --- + ImGui.TableNextColumn(); + if (isDefault) ImGui.TextColored(new Vector4(1, 1, 0, 1), rule.Name); + else ImGui.Text(rule.Name); + + // --- Priority --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(25); + int p = rule.Priority; + if (ImGui.InputInt($"##P{i}", ref p, 0)) { rule.Priority = p; OnSettingsChanged?.Invoke(); } + + // --- Dmg type --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(80); + if (ImGui.BeginCombo($"##Dmg{i}", rule.DamageType, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("Auto", rule.DamageType == "Auto")) { rule.DamageType = "Auto"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.DamageType == el)) + { rule.DamageType = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Ex Vuln (extra vulnerability element) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(80); + if (ImGui.BeginCombo($"##Vuln{i}", rule.ExVuln, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("None", rule.ExVuln == "None")) { rule.ExVuln = "None"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.ExVuln == el)) + { rule.ExVuln = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Weapon Dropdown --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + string currentWeaponName = "<AUTO>"; + if (rule.WeaponId != 0) + { + var matchedWep = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.WeaponId); + if (matchedWep != null) currentWeaponName = matchedWep.Name; + } + if (ImGui.BeginCombo($"##Wep{i}", currentWeaponName, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("<AUTO>", rule.WeaponId == 0)) + { rule.WeaponId = 0; OnSettingsChanged?.Invoke(); } + foreach (var itemRule in _settings.ItemRules) + { + if (ImGui.Selectable(itemRule.Name, rule.WeaponId == itemRule.Id)) + { rule.WeaponId = itemRule.Id; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Offhand Dropdown (shield or dual-wield weapon from ItemRules) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + string currentOffhandName = "<AUTO>"; + if (rule.OffhandId != 0) + { + var matchedOff = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.OffhandId); + if (matchedOff != null) currentOffhandName = matchedOff.Name; + } + if (ImGui.BeginCombo($"##Off{i}", currentOffhandName, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("<AUTO>", rule.OffhandId == 0)) + { rule.OffhandId = 0; OnSettingsChanged?.Invoke(); } + foreach (var itemRule in _settings.ItemRules) + { + if (ImGui.Selectable(itemRule.Name + "##off", rule.OffhandId == itemRule.Id)) + { rule.OffhandId = itemRule.Id; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- PetDmg (pet damage element) --- + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(70); + if (ImGui.BeginCombo($"##PetDmg{i}", rule.PetDamage, ImGuiComboFlags.NoArrowButton)) + { + if (ImGui.Selectable("PAuto", rule.PetDamage == "PAuto")) { rule.PetDamage = "PAuto"; OnSettingsChanged?.Invoke(); } + foreach (var el in _elements) + { + if (ImGui.Selectable(el, rule.PetDamage == el)) + { rule.PetDamage = el; OnSettingsChanged?.Invoke(); } + } + ImGui.EndCombo(); + } + + // --- Delete --- + ImGui.TableNextColumn(); + if (isDefault) + { + ImGui.TextDisabled("-"); + } + else + { + if (ImGui.Button($"X##del{i}")) + { + _settings.MonsterRules.RemoveAt(i); + OnSettingsChanged?.Invoke(); + } + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + + if (ImGui.BeginTable("AddTable", 3)) + { + ImGui.TableSetupColumn("NameIn", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("AddBtn", ImGuiTableColumnFlags.WidthFixed, 60); + ImGui.TableSetupColumn("AddSelBtn", ImGuiTableColumnFlags.WidthFixed, 80); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + ImGui.InputTextWithHint("##NewMonName", "Enter monster name to add...", ref _newMonsterName, 64); + + ImGui.TableNextColumn(); + if (ImGui.Button("Add", new Vector2(60, 22))) + { + if (!string.IsNullOrWhiteSpace(_newMonsterName) && !_settings.MonsterRules.Any(m => m.Name.Equals(_newMonsterName, StringComparison.OrdinalIgnoreCase))) + { + _settings.MonsterRules.Add(new MonsterRule { Name = _newMonsterName, DamageType = "Auto", WeaponId = 0 }); + _newMonsterName = ""; + OnSettingsChanged?.Invoke(); + } + } + + ImGui.TableNextColumn(); + if (ImGui.Button("Add Sel", new Vector2(80, 22))) + { + int selectedId = _core.Actions.CurrentSelection; + if (selectedId != 0) + { + var obj = _core.WorldFilter[selectedId]; + if (obj != null && !_settings.MonsterRules.Any(m => m.Name.Equals(obj.Name, StringComparison.OrdinalIgnoreCase))) + { + _settings.MonsterRules.Add(new MonsterRule { Name = obj.Name, DamageType = "Auto", WeaponId = 0 }); + OnSettingsChanged?.Invoke(); + } + } + } + + ImGui.EndTable(); + } + } + + // ── Floating window wrapper (called from dashboard) ────────────────── + public void RenderAsWindow(ref bool open) + { + ImGui.SetNextWindowSize(new Vector2(700, 400), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Monster Config##RynthAiMonsters", ref open)) + Render(); + ImGui.End(); + } + + private bool DrawToggleLight(string id, bool isOn, uint onColor, uint offColor, string tooltip = null) + { + var 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(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RouteUI.cs b/Plugins/RynthAi/UI/RouteUI.cs new file mode 100644 index 0000000..0efd9cf --- /dev/null +++ b/Plugins/RynthAi/UI/RouteUI.cs @@ -0,0 +1,337 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public class RouteUI + { + private readonly UISettings _settings; + private readonly CoreManager _core; + + public Action OnSettingsChanged; + + // --- ROUTE STATE --- + private readonly string[] _routeTypes = { "Once", "Circular", "Linear", "Follow" }; + private readonly string[] _addModes = { "End", "Above", "Below" }; + private int _addModeIdx = 0; + private int _selectedRouteIndex = -1; + + // --- GRAPHICS STATE --- + public bool NeedsRouteGraphicsRefresh = false; + private List<D3DObj> _routeGraphics = new List<D3DObj>(); + public List<D3DObj> TestD3DObjects = new List<D3DObj>(); + + public RouteUI(UISettings settings, CoreManager core) + { + _settings = settings; + _core = core; + } + + public void Render() + { + string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath); + ImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}"); + 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))) + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var newPt = new NavPoint + { + NS = me.Coordinates().NorthSouth, + EW = me.Coordinates().EastWest, + Z = me.Offset().Z + }; + InsertPoint(newPt); + } + } + + ImGui.SameLine(); + if (ImGui.Button("Add Portal", new Vector2(100, 25))) + { + try + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var myPos = me.Coordinates(); + WorldObject best = null; + double bestDist = double.MaxValue; + foreach (WorldObject wo in _core.WorldFilter.GetLandscape()) + { + if (wo == null) continue; + if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc || wo.ObjectClass == ObjectClass.Vendor) + { + try + { + double dNS = wo.Coordinates().NorthSouth - myPos.NorthSouth; + double dEW = wo.Coordinates().EastWest - myPos.EastWest; + double d = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + if (d < bestDist) { bestDist = d; best = wo; } + } + catch { } + } + } + if (best != null && bestDist < 20.0) + { + var newPt = new NavPoint + { + Type = NavPointType.PortalNPC, + NS = myPos.NorthSouth, + EW = myPos.EastWest, + Z = me.Offset().Z, + TargetName = best.Name, + ObjectClass = (int)best.ObjectClass, + IsTie = false + }; + InsertPoint(newPt); + _core.Actions.AddChatText($"[RynthAi] Added Portal/NPC: {best.Name} ({bestDist:F1}yd)", 1); + } + else + { + _core.Actions.AddChatText("[RynthAi] No portal/NPC found within 20 yards.", 1); + } + } + } + catch (Exception ex) { _core.Actions.AddChatText($"[RynthAi] Error: {ex.Message}", 1); } + } + + 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 = SpellDatabase.GetSpellName(ids[ri]); + if (ImGui.Selectable($"{name} ({ids[ri]})")) + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + var newPt = new NavPoint + { + Type = NavPointType.Recall, + NS = me.Coordinates().NorthSouth, + EW = me.Coordinates().EastWest, + Z = me.Offset().Z, + SpellId = ids[ri] + }; + InsertPoint(newPt); + _core.Actions.AddChatText($"[RynthAi] Added Recall: {name} ({ids[ri]})", 1); + } + } + } + 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); _core.Actions.AddChatText("[RynthAi] Route saved.", 1); } catch { } + } + } + + if (ImGui.BeginListBox("##RoutePoints", new Vector2(-1, 200))) + { + for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++) + { + // Push a unique ID so ImGui doesn't confuse the 50 different "X" buttons + ImGui.PushID($"route_pt_{i}"); + + // Draw the red "X" button + ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.2f, 0.2f, 1f)); + if (ImGui.Button("X", new Vector2(20, 20))) + { + // 1. Remove the point + _settings.CurrentRoute.Points.RemoveAt(i); + + // 2. Safely shift our selected/active indexes so we don't crash + if (_selectedRouteIndex == i) _selectedRouteIndex = -1; + else if (_selectedRouteIndex > i) _selectedRouteIndex--; + + if (_settings.ActiveNavIndex == i) _settings.ActiveNavIndex = 0; + else if (_settings.ActiveNavIndex > i) _settings.ActiveNavIndex--; + + // 3. Save, update 3D graphics, and notify the plugin + TryAutoSaveNav(); + UpdateRouteGraphics(); + OnSettingsChanged?.Invoke(); + + // 4. Pop the styles and break the loop for this single frame to prevent index out-of-range errors + ImGui.PopStyleColor(); + ImGui.PopID(); + break; + } + ImGui.PopStyleColor(); + + ImGui.SameLine(); + + // Draw the selectable row text + 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(); + } + } + + 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() + { + DisposeRouteGraphics(); + + if (_settings.CurrentRoute?.Points == null || _settings.CurrentRoute.Points.Count == 0) + return; + + if (_core?.D3DService == null) + return; + + int colorAqua = unchecked((int)0xFF00FFFF); + int colorBlue = unchecked((int)0xFF0088FF); + int colorRed = unchecked((int)0xFFFF2222); + + float ringScale = Math.Max(0.5f, (float)_settings.FollowNavMin); + + try + { + for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++) + { + var pt = _settings.CurrentRoute.Points[i]; + int wpColor = (i == _settings.ActiveNavIndex) ? colorRed : colorAqua; + + var ring = _core.D3DService.MarkCoordsWithShape( + (float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f, + Decal.Adapter.Wrappers.D3DShape.Ring, wpColor); + ring.Visible = true; + ring.ScaleX = ringScale; + ring.ScaleY = ringScale; + ring.ScaleZ = 0.1f; + try { ring.Anchor((float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f); } catch { } + _routeGraphics.Add(ring); + + int nextIdx = i + 1; + if (nextIdx >= _settings.CurrentRoute.Points.Count) + { + if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) nextIdx = 0; + else continue; + } + + var nextPt = _settings.CurrentRoute.Points[nextIdx]; + double dNS = nextPt.NS - pt.NS; + double dEW = nextPt.EW - pt.EW; + double dZ = nextPt.Z - pt.Z; + double dist2D = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; + + int dots = Math.Min(150, Math.Max(2, (int)dist2D)); + + for (int d = 1; d < dots; d++) + { + double f = (double)d / dots; + var dot = _core.D3DService.MarkCoordsWithShape( + (float)(pt.NS + dNS * f), + (float)(pt.EW + dEW * f), + (float)(pt.Z + dZ * f) + 0.5f, + Decal.Adapter.Wrappers.D3DShape.Sphere, colorBlue); + dot.Visible = true; + dot.Scale(0.15f); + _routeGraphics.Add(dot); + } + } + } + catch { } + } + + public void DisposeRouteGraphics() + { + foreach (var o in _routeGraphics) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } } + _routeGraphics.Clear(); + foreach (var o in TestD3DObjects) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } } + TestD3DObjects.Clear(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs b/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs new file mode 100644 index 0000000..b9445ea --- /dev/null +++ b/Plugins/RynthAi/UI/RynthAiUI.Rendering.cs @@ -0,0 +1,9 @@ +namespace NexSuite.Plugins.RynthAi +{ + // This file intentionally left blank. + // The old "Unified Tabs" UI has been retired in favor of the clean Advanced Settings menu. + public partial class RynthAiUI + { + + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/RynthAiUI.cs b/Plugins/RynthAi/UI/RynthAiUI.cs new file mode 100644 index 0000000..a04e594 --- /dev/null +++ b/Plugins/RynthAi/UI/RynthAiUI.cs @@ -0,0 +1,997 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Numerics; +using System.Linq; +using ImGuiNET; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public static class DashWindows + { + public static bool ShowMacroRules = false; + public static bool ShowMonsters = false; + public static bool ShowNavigation = false; + public static bool ShowWeapons = false; + public static bool ShowLua = false; + } + + public partial class RynthAiUI : IDisposable + { + public UISettings Settings { get; set; } + public CombatManager CombatManager { get; set; } + public CoreManager Core { get; set; } + public MetaManager MetaManager { get; set; } + + public Action OnSettingsChanged; + public Action OnForceRebuffClicked; + public Action OnLootProfileSelected; + public Action OnMetaProfileSelected; + public Action OnMetaRulesUpdated; + + public LuaUI LuaTab; + public MetaUI MetaTab; + public MonstersUI MonstersTab; + public RouteUI RouteTab; + + private readonly AdvancedSettingsUI _advancedUI; + + public List<string> Profiles = new List<string>(); + public List<string> NavFiles = new List<string>(); + public List<string> LootFiles = new List<string>(); + public List<string> MetaFiles = new List<string>(); + + private int _selectedNavIdx = 0; + private string _navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles"; + private string _lootFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LootProfiles"; + private string _metaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\MetaProfiles"; + + private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + // ── Colour palette ─────────────────────────────────────────────────── + private static readonly Vector4 ColTeal = new Vector4(0.15f, 0.85f, 0.90f, 1.00f); + private static readonly Vector4 ColAmber = new Vector4(0.91f, 0.70f, 0.20f, 1.00f); + private static readonly Vector4 ColRed = new Vector4(0.85f, 0.25f, 0.25f, 1.00f); + private static readonly Vector4 ColGreen = new Vector4(0.25f, 0.85f, 0.45f, 1.00f); + private static readonly Vector4 ColTextDim = new Vector4(0.85f, 0.90f, 0.95f, 1.00f); + private static readonly Vector4 ColTextMute = new Vector4(0.55f, 0.65f, 0.75f, 1.00f); + private static readonly Vector4 ColHp = new Vector4(0.85f, 0.20f, 0.20f, 1.00f); + private static readonly Vector4 ColStam = new Vector4(0.20f, 0.80f, 0.35f, 1.00f); + private static readonly Vector4 ColMana = new Vector4(0.15f, 0.55f, 0.95f, 1.00f); + private static readonly Vector4 ColBarBg = new Vector4(0.08f, 0.12f, 0.16f, 1.00f); + private static readonly Vector4 ColPanelBg = new Vector4(0.04f, 0.07f, 0.10f, 0.95f); + + private static readonly Vector4 ColBtnOn = new Vector4(0.15f, 0.30f, 0.35f, 1.00f); + private static readonly Vector4 ColBtnFill = new Vector4(0.06f, 0.12f, 0.18f, 1.00f); + private static readonly Vector4 ColBtnHov = new Vector4(0.10f, 0.18f, 0.25f, 1.00f); + private static readonly Vector4 ColBtnAct = new Vector4(0.08f, 0.15f, 0.22f, 1.00f); + private static readonly Vector4 ColBtnBord = new Vector4(0.15f, 0.25f, 0.35f, 1.00f); + + // ── DRAKHUD HEALTH ENGINE ──────────────────────────────────────────── + private Dictionary<int, float> _healthRatioTracker = new Dictionary<int, float>(); + private Dictionary<int, int> _maxHealthTracker = new Dictionary<int, int>(); + private int _lastTargetId = 0; + private int _retryTargetId = 0; + private int _retryCount = 0; + private DateTime _lastRequestTime = DateTime.MinValue; + + // ── UI STATE ───────────────────────────────────────────────────────── + private bool _isMinimized = false; + private bool _isLocked = false; + private float _bgOpacity = 0.95f; + private Vector2 _expandedSize = new Vector2(430, 420); + private bool _wasMinimized = false; + + public RynthAiUI(UISettings settings, CombatManager combatManager, CoreManager core) + { + Settings = settings; + CombatManager = combatManager; + Core = core; + + LuaTab = new LuaUI(settings, core); + _advancedUI = new AdvancedSettingsUI(settings) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + MetaTab = new MetaUI(settings, NavFiles) { OnSettingsChanged = () => OnSettingsChanged?.Invoke(), OnMetaRulesUpdated = () => OnMetaRulesUpdated?.Invoke() }; + MonstersTab = new MonstersUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + RouteTab = new RouteUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() }; + + RefreshProfilesList(); RefreshNavFiles(); RefreshLootFiles(); RefreshMetaFiles(); + + try { Core.EchoFilter.ServerDispatch += OnServerDispatch; } catch { } + } + + public void Dispose() + { + try { Core.EchoFilter.ServerDispatch -= OnServerDispatch; } catch { } + } + + public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedUI.SetMissileCraftingManager(mgr); + + public void Render() + { + UpdateTargetAppraisal(); + + if (RouteTab != null && RouteTab.NeedsRouteGraphicsRefresh) + { RouteTab.NeedsRouteGraphicsRefresh = false; RouteTab.UpdateRouteGraphics(); } + + RenderDashboard(); + + // Render all active popup windows based on the button toggles + try { if (Settings.ShowAdvancedWindow) _advancedUI?.Render(); } catch { Settings.ShowAdvancedWindow = false; } + try { if (DashWindows.ShowMacroRules) MetaTab?.RenderAsWindow(ref DashWindows.ShowMacroRules); } catch { DashWindows.ShowMacroRules = false; } + try { if (DashWindows.ShowMonsters) MonstersTab?.RenderAsWindow(ref DashWindows.ShowMonsters); } catch { DashWindows.ShowMonsters = false; } + try { if (DashWindows.ShowWeapons) RenderWeaponsWindow(); } catch { DashWindows.ShowWeapons = false; } + try { if (DashWindows.ShowNavigation) RenderNavigationWindow(); } catch { DashWindows.ShowNavigation = false; } + try { if (DashWindows.ShowLua) RenderLuaWindow(); } catch { DashWindows.ShowLua = false; } + } + + 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; + + if (_wasMinimized) + { + ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.Always); + _wasMinimized = false; + } + } + + ImGui.SetNextWindowSizeConstraints(new Vector2(400, 0), new Vector2(1200, 2000)); + + if (!_wasMinimized && !_isMinimized && !_isLocked) + { + ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.FirstUseEver); + } + + if (ImGui.Begin("RynthAi Dashboard##Main", flags)) + { + if (!_isMinimized && !_isLocked && !_wasMinimized) + { + _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, 154), true, ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)) + { + RenderCombatPanel(); + ImGui.Dummy(new Vector2(0, 4)); + } + ImGui.EndChild(); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(2); + + if (!_isMinimized) + { + ImGui.Spacing(); ImGui.Spacing(); + RenderLauncherGrid(); + } + } + ImGui.End(); + ImGui.PopStyleColor(); + ImGui.PopStyleVar(3); + } + + private void RenderDashHeader() + { + float W = ImGui.GetContentRegionAvail().X; + float startY = ImGui.GetCursorPosY(); + + ImGui.SetWindowFontScale(1.4f); + ImGui.TextColored(ColTeal, "N"); ImGui.SameLine(0, 2); + ImGui.TextColored(new Vector4(1, 1, 1, 1), "NEXAI DASHBOARD"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.SameLine(); + ImGui.SetCursorPosY(startY + 5); + ImGui.TextColored(ColTextMute, "v4.0"); + + ImGui.SameLine(W - 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; } + + ImGui.SameLine(); + if (ImGui.SmallButton("X")) { Settings.IsMacroRunning = false; } + + ImGui.Dummy(new Vector2(0, 2)); + + if (!_isMinimized) + { + if (ImGui.BeginTable("HeaderGrid", 2)) + { + ImGui.TableSetupColumn("Left", ImGuiTableColumnFlags.WidthFixed, W * 0.40f); + ImGui.TableSetupColumn("Right", ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetWindowFontScale(1.3f); + ImGui.TextColored(ColTextMute, "Macro Status:"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 2); + ImGui.TextColored(ColTextMute, "Profile:"); + ImGui.SameLine(60); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo("##ProfCombo", TruncateName(Settings.SelectedProfile, 16))) + { + foreach (var p in Profiles) + { + if (ImGui.Selectable(p, p == Settings.SelectedProfile)) + { + Settings.SelectedProfile = p; OnSettingsChanged?.Invoke(); + } + } + ImGui.EndCombo(); + } + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + uint color = Settings.IsMacroRunning ? ImGui.ColorConvertFloat4ToU32(ColGreen) : ImGui.ColorConvertFloat4ToU32(ColTextMute); + + dl.AddCircleFilled(pos + new Vector2(8, 12), 6, color); + if (Settings.IsMacroRunning) dl.AddCircle(pos + new Vector2(8, 12), 9, color, 12, 1.5f); + + ImGui.SetCursorScreenPos(pos + new Vector2(24, 0)); + if (ImGui.InvisibleButton("ToggleMacro", new Vector2(100, 24))) + { + Settings.IsMacroRunning = !Settings.IsMacroRunning; + OnSettingsChanged?.Invoke(); + } + + ImGui.SetCursorScreenPos(pos + new Vector2(26, 2)); + ImGui.SetWindowFontScale(1.3f); + ImGui.TextColored(Settings.IsMacroRunning ? ColGreen : ColTextMute, Settings.IsMacroRunning ? "RUNNING" : "STOPPED"); + ImGui.SetWindowFontScale(1.0f); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + 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.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextMute, "State:"); ImGui.SameLine(0, 8); + ImGui.TextColored(ColAmber, Settings.CurrentState ?? "Idle"); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 6); + 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) ? "" : Path.Combine(_lootFolder, LootFiles[i] + ".utl"); + OnSettingsChanged?.Invoke(); OnLootProfileSelected?.Invoke(); + } + } + ImGui.EndCombo(); + } + + ImGui.EndTable(); + } + ImGui.Spacing(); + } + } + + private void RenderCombatPanel() + { + if (ImGui.BeginTable("CombatInnerTable", 2, ImGuiTableFlags.None)) + { + ImGui.TableSetupColumn("Toggles", ImGuiTableColumnFlags.WidthFixed, 68); + ImGui.TableSetupColumn("Vitals", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableNextRow(); + + // --- COLUMN 1: TOGGLES --- + ImGui.TableNextColumn(); + var tPos = ImGui.GetCursorScreenPos() + new Vector2(2, 28); + + // 2x2 Grid + DrawSquareToggle("sword", ref Settings.EnableCombat, tPos, "CombatTgl"); + DrawSquareToggle("buff", ref Settings.EnableBuffing, tPos + new Vector2(34, 0), "BuffTgl"); + DrawSquareToggle("shoe", ref Settings.EnableNavigation, tPos + new Vector2(0, 34), "NavTgl"); + DrawSquareToggle("bag", ref Settings.EnableLooting, tPos + new Vector2(34, 34), "LootTgl"); + + // Wide MACRO Button + DrawWideToggle("MACRO", "gear", ref Settings.EnableMeta, tPos + new Vector2(0, 68), "MetaTgl", 64f, 20f); + + // --- COLUMN 2: MOB + PLAYER VITALS --- + ImGui.TableNextColumn(); + + string targetName = "NO TARGET"; + float targetHpPct = 0f; + string mobHpDisplay = "0%"; + int currentTarget = Core.Actions.CurrentSelection; + + if (currentTarget != 0) + { + try + { + var wo = Core.WorldFilter[currentTarget]; + if (wo != null) + { + targetName = wo.Name; + + if (_healthRatioTracker.ContainsKey(currentTarget)) + { + targetHpPct = _healthRatioTracker[currentTarget]; + } + else + { + targetHpPct = (float)wo.Values((DoubleValueKey)0x92, 0.0); + } + + if (_maxHealthTracker.ContainsKey(currentTarget) && _maxHealthTracker[currentTarget] > 0) + { + int maxHp = _maxHealthTracker[currentTarget]; + int curHp = (int)Math.Round(targetHpPct * maxHp); + mobHpDisplay = $"{(int)(targetHpPct * 100)}% ({curHp}/{maxHp})"; + } + else + { + mobHpDisplay = $"{(int)(targetHpPct * 100)}%"; + } + } + } + catch { } + } + + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4); + ImGui.TextColored(ColTextDim, TruncateName(targetName, 32).ToUpper()); + + float textWidth = ImGui.CalcTextSize(mobHpDisplay).X; + ImGui.SameLine(ImGui.GetContentRegionAvail().X - textWidth); + ImGui.TextColored(new Vector4(1, 1, 1, 1), mobHpDisplay); + + DrawSegmentedBar(targetHpPct, ImGui.GetContentRegionAvail().X - 4); + + ImGui.Spacing(); + ImGui.TextColored(ColTextMute, "PLAYER VITALS"); + + int hp = 0, hpMax = 1, st = 0, stMax = 1, mn = 0, mnMax = 1; + try + { + if (Core?.CharacterFilter != null) + { + hp = Core.CharacterFilter.Health; hpMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]); + st = Core.CharacterFilter.Stamina; stMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]); + mn = Core.CharacterFilter.Mana; mnMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]); + } + } + catch { } + + float hpPct = (float)hp / hpMax; float stPct = (float)st / stMax; float mnPct = (float)mn / mnMax; + + DrawVitalRow("heart", "HP", hpPct, ColHp, $"{hp}/{hpMax}"); + DrawVitalRow("run", "ST", stPct, ColGreen, $"{st}/{stMax}"); + DrawVitalRow("drop", "MN", mnPct, ColMana, $"{mn}/{mnMax}"); + + ImGui.EndTable(); + } + } + + private void RenderLauncherGrid() + { + if (ImGui.BeginTable("LauncherGridTable", 3, ImGuiTableFlags.SizingStretchSame)) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); GridBtn("Macro Rules", "gear", ref DashWindows.ShowMacroRules); + ImGui.TableNextColumn(); GridBtn("Monsters", "target", ref DashWindows.ShowMonsters); + ImGui.TableNextColumn(); GridBtn("Settings", "wrench", ref Settings.ShowAdvancedWindow); + + ImGui.TableNextRow(); + ImGui.TableNextColumn(); GridBtn("Navigation", "map", ref DashWindows.ShowNavigation); + ImGui.TableNextColumn(); GridBtn("Weapons", "shield", ref DashWindows.ShowWeapons); + ImGui.TableNextColumn(); GridBtn("Lua Scripts", "code", ref DashWindows.ShowLua); + + ImGui.EndTable(); + } + } + + private void GridBtn(string label, string icon, ref bool flag) + { + bool wasOn = flag; + float bH = 30f; + float bW = -1f; + + ImGui.PushStyleColor(ImGuiCol.Button, ColBtnFill); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColBtnHov); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColBtnAct); + ImGui.PushStyleColor(ImGuiCol.Border, wasOn ? ColTeal : ColBtnBord); + + ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f); + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4f); + + var startPos = ImGui.GetCursorScreenPos(); + if (ImGui.Button($"##{label}", new Vector2(bW, bH))) flag = !flag; + + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(4); + + float actualWidth = ImGui.GetItemRectSize().X; + var textSize = ImGui.CalcTextSize(label); + + DrawIcon(icon, startPos + new Vector2(8, 6), wasOn ? ColTeal : ColTextMute, 16f); + + ImGui.SetCursorScreenPos(startPos + new Vector2(30, (bH - textSize.Y) / 2)); + ImGui.TextColored(wasOn ? ColTeal : ColTextDim, label); + + ImGui.SetCursorScreenPos(startPos + new Vector2(0, bH + 2)); + ImGui.Dummy(new Vector2(actualWidth, 0)); + } + + // ═════════════════════════════════════════════════════════════════════ + // WEAPONS & ITEMS WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderWeaponsWindow() + { + ImGui.SetNextWindowSize(new Vector2(480, 300), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Weapons & Items##RynthAiWeapons", ref DashWindows.ShowWeapons)) + { + ImGui.TextColored(ColAmber, "Weapons / Wands / Shields / Pets"); + + if (ImGui.BeginTable("ItemsTable", 3, + ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable)) + { + ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Element", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Actions", ImGuiTableColumnFlags.WidthFixed, 60); + ImGui.TableHeadersRow(); + + for (int i = 0; i < Settings.ItemRules.Count; i++) + { + var rule = Settings.ItemRules[i]; + ImGui.TableNextRow(); + + ImGui.TableNextColumn(); + var wo = Core?.WorldFilter[rule.Id]; + if (wo != null) + ImGui.Text(rule.Name); + else + { + ImGui.TextColored(ColRed, rule.Name); + ImGui.SameLine(); + ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 0.8f), "(Gone)"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Weapon not in inventory!\nBot cannot equip this item.\nRemove and re-add the correct weapon."); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + if (ImGui.BeginCombo($"##Elem{i}", rule.Element, ImGuiComboFlags.NoArrowButton)) + { + foreach (var el in _elements) + if (ImGui.Selectable(el, rule.Element == el)) + { rule.Element = el; OnSettingsChanged?.Invoke(); } + ImGui.EndCombo(); + } + + ImGui.TableNextColumn(); + if (ImGui.Button($"Del##{i}", new Vector2(-1, 0))) + { + foreach (var mr in Settings.MonsterRules) + { + if (mr.WeaponId == rule.Id) mr.WeaponId = 0; + if (mr.OffhandId == rule.Id) mr.OffhandId = 0; + } + Settings.ItemRules.RemoveAt(i); + OnSettingsChanged?.Invoke(); + } + } + ImGui.EndTable(); + } + + ImGui.Separator(); + if (ImGui.Button("Add Selected Item", new Vector2(150, 24))) + { + int sel = Core.Actions.CurrentSelection; + if (sel != 0) + { + var item = Core.WorldFilter[sel]; + if (item != null) + { + if (IsValidEquipment(item)) + { + if (!Settings.ItemRules.Any(x => x.Id == item.Id)) + { + Settings.ItemRules.Add(new ItemRule + { + Id = item.Id, + Name = item.Name, + Element = GetElement(item), + KeepBuffed = true + }); + OnSettingsChanged?.Invoke(); + } + else Core.Actions.AddChatText($"[RynthAi] Item ID {item.Id} already in list.", 1); + } + else Core.Actions.AddChatText("[RynthAi] Selected item must be a weapon, wand, or shield.", 1); + } + } + } + ImGui.SameLine(); + ImGui.TextDisabled("(Select item in-game first)"); + } + ImGui.End(); + } + + // ═════════════════════════════════════════════════════════════════════ + // NAVIGATION WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderNavigationWindow() + { + ImGui.SetNextWindowSize(new Vector2(360, 400), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Navigation##RynthAiNav", ref DashWindows.ShowNavigation)) + RouteTab?.Render(); + ImGui.End(); + } + + // ═════════════════════════════════════════════════════════════════════ + // LUA SCRIPTS WINDOW + // ═════════════════════════════════════════════════════════════════════ + private void RenderLuaWindow() + { + ImGui.SetNextWindowSize(new Vector2(400, 300), ImGuiCond.FirstUseEver); + if (ImGui.Begin("Lua Scripts##RynthAiLua", ref DashWindows.ShowLua)) + { + if (LuaTab != null) + { + LuaTab.Render(); + } + else + { + ImGui.TextColored(ColTextDim, "Lua Engine is currently unavailable."); + } + } + ImGui.End(); + } + + // ── DRAKHUD LOGIC (Embedded) ────────────────────────────────────────── + private void UpdateTargetAppraisal() + { + int currentTarget = Core.Actions.CurrentSelection; + bool isMonster = false; + + if (currentTarget != 0) + { + try + { + WorldObject wo = Core.WorldFilter[currentTarget]; + if (wo != null && wo.ObjectClass == ObjectClass.Monster) + isMonster = true; + } + catch { } + } + + if (currentTarget != _lastTargetId) + { + _lastTargetId = currentTarget; + _retryTargetId = currentTarget; + _retryCount = 0; + if (currentTarget != 0 && isMonster) + { + try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; } catch { } + } + } + + if (currentTarget != 0 && isMonster && currentTarget == _retryTargetId && _retryCount < 3 && + !_maxHealthTracker.ContainsKey(currentTarget) && (DateTime.Now - _lastRequestTime).TotalSeconds >= 0.75) + { + try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; _retryCount++; } catch { } + } + } + + private void OnServerDispatch(object sender, NetworkMessageEventArgs e) + { + try + { + if (e.Message.Type == 0xF7B0) + { + int eventType = (int)e.Message[2]; + if (eventType == 0x1C0) + { + int targetId = (int)e.Message[3]; + object rawHealth = e.Message[4]; + float ratio = 1.0f; + if (rawHealth is float) ratio = (float)rawHealth; + else if (rawHealth is double) ratio = (float)(double)rawHealth; + else if (rawHealth is Single) ratio = (Single)rawHealth; + _healthRatioTracker[targetId] = ratio; + } + else if (eventType == 0xC9) + { + TryExtractVitals(e.Message); + } + } + } + catch { } + } + + private void TryExtractVitals(Decal.Adapter.Message msg) + { + try + { + Decal.Adapter.MessageStruct eventStruct = msg.Struct("event"); + if (eventStruct != null) + { + int health = 0, healthMax = 0; + try { health = eventStruct.Value<int>("health"); } catch { } + try { healthMax = eventStruct.Value<int>("healthMax"); } catch { } + + if (healthMax > 0) + { + int objectId = 0; + try { objectId = eventStruct.Value<int>("object"); } catch { } + if (objectId == 0) objectId = Core.Actions.CurrentSelection; + + if (objectId != 0) + { + _maxHealthTracker[objectId] = healthMax; + if (healthMax > 0) _healthRatioTracker[objectId] = (float)health / (float)healthMax; + return; + } + } + } + } + catch { } + + try + { + int health = 0, healthMax = 0; + try { health = msg.Value<int>("health"); } catch { } + try { healthMax = msg.Value<int>("healthMax"); } catch { } + + if (healthMax > 0) + { + int objectId = Core.Actions.CurrentSelection; + if (objectId != 0) + { + _maxHealthTracker[objectId] = healthMax; + _healthRatioTracker[objectId] = (float)health / (float)healthMax; + return; + } + } + } + catch { } + } + + // ── Drawing Math & Custom Shapes ────────────────────────────────────── + private void DrawIcon(string type, Vector2 pos, Vector4 color, float s) + { + var 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 * ((float)Math.PI * 2f / 8f); + dl.AddLine(pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 3, s / 2 + (float)Math.Sin(a) * s / 3), + pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 2, s / 2 + (float)Math.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; + } + } + + private void DrawSquareToggle(string icon, ref bool state, Vector2 pos, string id) + { + var dl = ImGui.GetWindowDrawList(); + float s = 30f; + + Vector4 bgColor = state ? ColBtnOn : ColBarBg; + Vector4 iconColor = state ? ColTeal : ColTextMute; + + dl.AddRectFilled(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(bgColor), 4f); + if (state) dl.AddRect(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f); + + DrawIcon(icon, pos + new Vector2(6, 6), iconColor, 18f); + + ImGui.SetCursorScreenPos(pos); + if (ImGui.InvisibleButton($"##{id}", new Vector2(s, s))) + { + state = !state; + OnSettingsChanged?.Invoke(); + } + } + + private void DrawWideToggle(string label, string icon, ref bool state, Vector2 pos, string id, float width, float height) + { + var dl = ImGui.GetWindowDrawList(); + + Vector4 bgColor = state ? ColBtnOn : ColBarBg; + Vector4 iconColor = state ? ColTeal : ColTextMute; + + dl.AddRectFilled(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(bgColor), 4f); + if (state) dl.AddRect(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f); + + DrawIcon(icon, pos + new Vector2(4, (height - 12) / 2), iconColor, 12f); + + var textSize = ImGui.CalcTextSize(label); + dl.AddText(pos + new Vector2(18, (height - textSize.Y) / 2), ImGui.ColorConvertFloat4ToU32(state ? ColTeal : ColTextDim), label); + + ImGui.SetCursorScreenPos(pos); + if (ImGui.InvisibleButton($"##{id}", new Vector2(width, height))) + { + state = !state; + OnSettingsChanged?.Invoke(); + } + } + + private Vector4 GetGradientCol(float t) + { + if (t < 0.33f) { float f = t / 0.33f; return new Vector4(1f, f, 0f, 1f); } + else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; return new Vector4(1f - f, 1f, 0f, 1f); } + else { float f = (t - 0.66f) / 0.34f; return new Vector4(0f, 1f, f, 1f); } + } + + private void DrawSegmentedBar(float pct, float width) + { + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + float h = 10f; int segments = 15; float gap = 2f; + float segW = (width - (segments - 1) * gap) / segments; + + for (int i = 0; i < segments; i++) + { + float t = (float)i / (segments - 1); + Vector4 drawCol = (i / (float)segments <= pct) ? GetGradientCol(t) : ColBarBg; + dl.AddRectFilled(pos + new Vector2(i * (segW + gap), 0), pos + new Vector2(i * (segW + gap) + segW, h), ImGui.ColorConvertFloat4ToU32(drawCol), 1f); + } + ImGui.Dummy(new Vector2(width, h + 2)); + } + + private void DrawVitalRow(string icon, string label, float pct, Vector4 color, string valText) + { + float width = ImGui.GetContentRegionAvail().X - 4f; + var pos = ImGui.GetCursorScreenPos(); + var dl = ImGui.GetWindowDrawList(); + float h = 16f; + + dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(ColBarBg), 4f); + float safePct = Math.Max(0, Math.Min(1, pct)); + dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 4f); + + DrawIcon(icon, pos + new Vector2(4, 1), ColTextDim, 14f); + string display = $"{label}: {(int)(safePct * 100)}% ({valText})"; + dl.AddText(pos + new Vector2(24, 0), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 1)), display); + + ImGui.Dummy(new Vector2(width, h)); + ImGui.Spacing(); + } + + private static string TruncateName(string s, int max) => s != null && s.Length > max ? s.Substring(0, max - 1) + "..." : (s ?? ""); + + // ── Backend Helpers ─────────────────────────────────────── + public void LoadSelectedNav() + { + if (_selectedNavIdx < 0 || _selectedNavIdx >= NavFiles.Count) return; + string sel = NavFiles[_selectedNavIdx]; + if (sel == "None") { Settings.CurrentNavPath = ""; Settings.CurrentRoute.Points.Clear(); Settings.ActiveNavIndex = 0; } + else + { + string fp = Path.Combine(_navFolder, sel + ".nav"); + Settings.CurrentNavPath = fp; Settings.CurrentRoute = VTankNavParser.Load(fp); + Settings.ActiveNavIndex = (Settings.CurrentRoute.RouteType == NavRouteType.Once || Settings.CurrentRoute.RouteType == NavRouteType.Follow) ? 0 : FindNearestWaypoint(Settings.CurrentRoute); + } + if (RouteTab != null) RouteTab.NeedsRouteGraphicsRefresh = true; OnSettingsChanged?.Invoke(); + } + + private int FindNearestWaypoint(VTankNavParser route) + { + if (route?.Points == null || route.Points.Count == 0) return 0; + try + { + var me = Core.WorldFilter[Core.CharacterFilter.Id]; if (me == null) return 0; + var pos = me.Coordinates(); int best = 0; double bestD = double.MaxValue; + for (int i = 0; i < route.Points.Count; i++) + { + var pt = route.Points[i]; if (pt.Type != NavPointType.Point) continue; + double d = Math.Sqrt(Math.Pow(pt.NS - pos.NorthSouth, 2) + Math.Pow(pt.EW - pos.EastWest, 2)); + if (d < bestD) { bestD = d; best = i; } + } + return best; + } + catch { return 0; } + } + + private bool IsValidEquipment(WorldObject item) + { + if (item.ObjectClass == ObjectClass.MeleeWeapon || + item.ObjectClass == ObjectClass.MissileWeapon || + item.ObjectClass == ObjectClass.WandStaffOrb) return true; + if (item.ObjectClass == ObjectClass.Armor && + (item.Name.IndexOf("Shield", StringComparison.OrdinalIgnoreCase) >= 0 || + item.Name.IndexOf("Defender", StringComparison.OrdinalIgnoreCase) >= 0)) return true; + return false; + } + + private string GetElement(WorldObject item) + { + switch (item.Values(LongValueKey.DamageType, 0)) + { + case 1: return "Slash"; + case 2: return "Pierce"; + case 4: return "Bludgeon"; + case 8: return "Cold"; + case 16: return "Fire"; + case 32: return "Acid"; + case 64: return "Lightning"; + default: return "Slash"; + } + } + + public void RefreshNavFiles() + { + NavFiles.Clear(); NavFiles.Add("None"); _selectedNavIdx = 0; + if (!Directory.Exists(_navFolder)) return; + foreach (var f in Directory.GetFiles(_navFolder, "*.nav")) + { + NavFiles.Add(Path.GetFileNameWithoutExtension(f)); + if (f.Equals(Settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) _selectedNavIdx = NavFiles.Count - 1; + } + } + + public void RefreshLootFiles() + { + LootFiles.Clear(); LootFiles.Add("None"); + if (!Directory.Exists(_lootFolder)) return; + foreach (var f in Directory.GetFiles(_lootFolder, "*.utl")) + { + LootFiles.Add(Path.GetFileNameWithoutExtension(f)); + if (f.Equals(Settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase)) Settings.LootProfileIdx = LootFiles.Count - 1; + } + } + + public void RefreshMetaFiles() + { + try + { + MetaFiles.Clear(); MetaFiles.Add("None"); + if (!Directory.Exists(_metaFolder)) Directory.CreateDirectory(_metaFolder); + foreach (var f in Directory.GetFiles(_metaFolder, "*.met")) MetaFiles.Add(Path.GetFileNameWithoutExtension(f)); + } + catch { } + } + + private void RefreshProfilesList() + { + try + { + Profiles.Clear(); + string srv = Core.CharacterFilter.Server ?? "UnknownServer"; + string chr = Core.CharacterFilter.Name ?? "UnknownCharacter"; + string path = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", srv, chr); + Directory.CreateDirectory(path); + foreach (string f in Directory.GetFiles(path, "*.json")) + { + string n = Path.GetFileNameWithoutExtension(f); + if (n.ToLower() != "settings") Profiles.Add(n); + } + if (Profiles.Count == 0) Profiles.Add("Default"); + } + catch { Profiles.Add("Default"); } + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/UI/UISettings.cs b/Plugins/RynthAi/UI/UISettings.cs new file mode 100644 index 0000000..0602da7 --- /dev/null +++ b/Plugins/RynthAi/UI/UISettings.cs @@ -0,0 +1,314 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using Newtonsoft.Json; + +namespace NexSuite.Plugins.RynthAi +{ + public class UISettings + { + // Core macro state + public bool IsMacroRunning = false; + public string CurrentState = "Default"; + public bool IsRecordingNav = false; + + // Subsystem Toggles + public bool EnableBuffing = true; + public bool EnableCombat = false; + public bool EnableNavigation = false; + public bool EnableLooting = false; + public bool EnableMeta = false; + public bool EnableRaycasting = true; + + // Movement Mode: 0 = Legacy (SetAutorun/SetClientMotion), + // 1 = Tier1 (CM_Movement direct calls), + // 2 = Tier2 (CPhysicsObj::MoveToPosition — planned), + // 3 = Tier3 (MoveToManager queue — planned) + public int MovementMode = 0; + + // ── Navigation Steering (all modes) ─────────────────────────────── + public float NavStopTurnAngle = 20f; // Stop and turn in place when error > X° + public float NavResumeTurnAngle = 10f; // Resume running when error < X° (must be < StopTurn) + public float NavDeadZone = 4f; // Ignore corrections smaller than X° + public float NavSweepMult = 2.5f; // Closest-approach detect radius = ArrivalYards * this + + // ── Tier 2 Tuning ───────────────────────────────────────────────── + public float T2Speed = 1.0f; // Movement speed multiplier + public float T2DistanceTo = 0.5f; // Stop this far from target (yards) + public float T2ReissueMs = 2000f; // Re-issue MoveToPosition if no progress (ms) + public float T2MaxRangeYd = 500f; // Clamp waypoint distance to this (yards) + public int T2MaxLandblocks = 3; // Skip if target is more than N landblocks away + public float T2WalkWithinYd = 5f; // Walk (not run) when within X yards of waypoint + + // Persistence + public string CurrentNavPath = ""; + public string CurrentLootPath = ""; + public string CurrentMetaPath = ""; + + + // Profile Selection Indices + public int MacroSettingsIdx = 1; + public int NavProfileIdx = 1; + public int LootProfileIdx = 0; + public int MetaProfileIdx = 1; + + // Automation Toggles + public bool EnableAutostack = true; + public bool EnableAutocram = true; + public bool EnableCombineSalvage = true; // If true, combine salvage bags of same material + + // --- Missile Crafting --- + public bool EnableMissileCrafting = false; // Master toggle for auto-crafting ammo from bundles + public int MissileCraftAmmoThreshold = 1000; // Craft when ammo count drops below this + + // --- Loot Timing (ms) — tunable in Advanced Settings → Looting --- + public int LootInterItemDelayMs = 100; // Delay between picking up items + public int LootContentSettleMs = 100; // Wait for corpse contents to populate + public int LootEmptyCorpseMs = 400; // Wait before declaring corpse empty + public int LootClosingDelayMs = 200; // Delay before closing corpse + public int LootAssessWindowMs = 800; // Max time to wait for item ID data + public int LootRetryTimeoutMs = 800; // Retry pickup after this long + public int LootOpenRetryMs = 3000; // Retry opening corpse if no response + + // --- Salvage Timing (ms) — first item / subsequent item --- + public int SalvageOpenDelayFirstMs = 400; // Panel open delay (first item) + public int SalvageOpenDelayFastMs = 50; // Panel open delay (subsequent) + public int SalvageAddDelayFirstMs = 600; // Add item delay (first) + public int SalvageAddDelayFastMs = 50; // Add item delay (subsequent) + public int SalvageSalvageDelayMs = 50; // Click salvage button delay + public int SalvageResultDelayFirstMs = 1000; // Wait for result (first) + public int SalvageResultDelayFastMs = 250; // Wait for result (subsequent) + public bool UseDispelItems = false; + public bool CastDispelSelf = false; + public bool AutoFellowMgmt = false; + public bool MChargesWhenOff = false; + + // Vitals (0-100) + 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; + + // Ranges & Misc + public int MonsterRange = 50; + public int RingRange = 5; + public int ApproachRange = 4; + public int MinRingTargets = 4; // Minimum monsters in ring range to use ring spells + public float FollowNavMin = 1.5f; + public double MaxMonRange = 12.0; + public bool SummonPets = false; + public int CustomPetRange = 5; + public int PetMinMonsters = 1; + public bool AdvancedOptions = false; + public bool MineOnly = true; + public bool ShowEditor = false; + public double CorpseApproachRangeMax = 0.04166667; // ~10 yards (10 / 240) + public double CorpseApproachRangeMin = 0.00833333; // ~2 yards (2 / 240) + + // Advanced Toggles + public bool BoostNavPriority = false; + public bool BoostLootPriority = false; + // Loot Ownership: 0=MyKillsOnly (default), 1=FellowshipKills, 2=AllCorpses + public int LootOwnership = 0; + public bool LootOnlyRareCorpses = false; + public bool PeaceModeWhenIdle = true; + public bool RebuffWhenIdle = false; + + // Blacklist Settings (Combat) + public int BlacklistAttempts = 3; // How many failed attacks before blacklisting + public int BlacklistTimeoutSec = 30; // How long a mob stays blacklisted (seconds) + + // Attack Power (0-100 percent, or -1 for auto) + // Auto: 100% power, or 80% if UseRecklessness is enabled and Recklessness is trained + public int MeleeAttackPower = -1; // -1 = auto, 0-100 = manual percent + public int MissileAttackPower = -1; // -1 = auto, 0-100 = manual percent + public bool UseRecklessness = false; // When true + Recklessness trained, auto power = 80% + + // Attack Height: 0=Low (Delete), 1=Medium (End), 2=High (Page Down) + public int MeleeAttackHeight = 1; // Default: Medium + public int MissileAttackHeight = 1; // Default: Medium + + //FPS Limits + public bool EnableFPSLimit = true; + public int TargetFPSFocused = 60; + public int TargetFPSBackground = 30; + + // Data Lists + public List<MonsterRule> MonsterRules = new List<MonsterRule>(); + public List<ItemRule> ItemRules = new List<ItemRule>(); + public List<BuffRule> BuffRules = new List<BuffRule>(); + public List<MetaRule> MetaRules = new List<MetaRule>(); // <--- NEW META LIST + public string LuaScript = "-- Enter your Lua script here\nprint('RynthAi Lua Loaded')"; + public string LuaConsoleOutput = "--- RynthAi Lua Console ---"; + + public string SelectedProfile = "Default"; + public VTankNavParser CurrentRoute = new VTankNavParser(); // Uncomment if you still use this + public int ActiveNavIndex = 0; + + // Advanced Settings Popup + // Inside UISettings.cs + public bool ShowAdvancedWindow = false; // Toggle this with your button + public int SelectedAdvancedTab = 0; // Tracks the left-hand selection + + // Define your tabs in an array for easy rendering + [JsonIgnore] + public readonly string[] AdvancedTabs = { + "Misc", "Recharge", "Melee Combat", "Spell Combat", + "Ranges", "Navigation", "Buffing", "Crafting", "Looting" +}; + + //Refresh state when selected + [JsonIgnore] + public bool ForceStateReset { get; set; } = false; + + public UISettings() + { + // REMOVED EnsureDefaultRule() from here to stop JSON deserialization from duplicating it. + } + + public void EnsureDefaultRule() + { + // Find any existing Default rules + var existingDefaults = MonsterRules.Where(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)).ToList(); + MonsterRule trueDefault; + + if (existingDefaults.Count > 0) + { + // Keep the first one (it contains your saved weapon settings) + trueDefault = existingDefaults.First(); + // Erase all of them from the list to clean up any duplicates + MonsterRules.RemoveAll(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + else + { + // If it truly doesn't exist, make a brand new one + trueDefault = new MonsterRule { Name = "Default", Priority = 1, DamageType = "Auto", WeaponId = 0 }; + } + + // Insert the one true Default safely at the very top + MonsterRules.Insert(0, trueDefault); + } + } + + public class MonsterRule + { + public string Name { get; set; } = "New Monster"; + public int Priority { get; set; } = 1; + public string DamageType { get; set; } = "Auto"; + public int WeaponId { get; set; } = 0; + + // Debuff Lights (cast on target before attacking) + public bool Fester { get; set; } = false; // F - Festering Curse + public bool Broadside { get; set; } = false; // B - Broadside of a Barn + public bool GravityWell { get; set; } = false; // G - Gravity Well + public bool Imperil { get; set; } = false; // I - Imperil + public bool Yield { get; set; } = false; // Y - Yield + public bool Vuln { get; set; } = false; // V - Vulnerability (element-matched) + + // Spell Type Lights (how to attack) + public bool UseArc { get; set; } = false; // A - Arc spells (war/void) + public bool UseRing { get; set; } = false; // R - Ring spells (uses RingRange) + public bool UseStreak { get; set; } = false; // S - Streak spells (war/void) + public bool UseBolt { get; set; } = true; // B - Bolt spells (default on) + // If none of A/R/S/B are set in magic mode = don't attack (buff bot) + + // Extra Vulnerability element (cast in addition to the V light) + public string ExVuln { get; set; } = "None"; + // Offhand weapon/shield ID (from ItemRules, for dual wield or shield) + public int OffhandId { get; set; } = 0; + // Pet damage element + public string PetDamage { get; set; } = "PAuto"; + } + + public class BuffRule { public string SpellName { get; set; } public int SpellId { get; set; } public bool Enabled { get; set; } = true; } + + public class ItemRule + { + public int Id { get; set; } + public string Name { get; set; } + public string Action { get; set; } = "Loot"; + public string Element { get; set; } = "Slash"; + public bool KeepBuffed { get; set; } = true; + } + + // ==================================================================== + // NEW META SYSTEM MODELS + // ==================================================================== + 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 + } + + public enum MetaActionType + { + None, + ChatCommand, + SetMetaState, + EmbeddedNavRoute, + All, + CallMetaState, // New + ReturnFromCall, // New + ExpressionAction, // New + ChatExpression, // New + SetWatchdog, // New + ClearWatchdog, // New + GetNTOption, // New + SetNTOption, // New + CreateView, // New + DestroyView, // New + DestroyAllViews // New + } + + public class MetaRule + { + public string State { get; set; } = "Default"; + public MetaConditionType Condition { get; set; } + public string ConditionData { get; set; } = ""; + public MetaActionType Action { get; set; } + public string ActionData { get; set; } = ""; + public List<MetaRule> Children { get; set; } = new List<MetaRule>(); + + // NEW: Temporary flag for the UI. JsonIgnore prevents it from saving to the file. + [JsonIgnore] + public bool HasFired { get; set; } = false; + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/app.config b/Plugins/RynthAi/app.config new file mode 100644 index 0000000..7c6760c --- /dev/null +++ b/Plugins/RynthAi/app.config @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<configuration> + <runtime> + <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> + <dependentAssembly> + <assemblyIdentity name="Decal.Adapter" publicKeyToken="bd1c8ce002ce221e" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="Decal.FileService" publicKeyToken="bd1c8ce002ce221e" culture="neutral" /> + <bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" /> + </dependentAssembly> + </assemblyBinding> + </runtime> +</configuration> \ No newline at end of file diff --git a/Plugins/RynthAi/packages.config b/Plugins/RynthAi/packages.config new file mode 100644 index 0000000..2a81485 --- /dev/null +++ b/Plugins/RynthAi/packages.config @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="KeraLua" version="1.4.9" targetFramework="net48" /> + <package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" /> + <package id="NLua" version="1.7.8" targetFramework="net48" /> +</packages> \ No newline at end of file diff --git a/Plugins/RynthAi/properties/AssemblyInfo.cs b/Plugins/RynthAi/properties/AssemblyInfo.cs new file mode 100644 index 0000000..b0b49ae --- /dev/null +++ b/Plugins/RynthAi/properties/AssemblyInfo.cs @@ -0,0 +1,16 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("RynthAi")] +[assembly: AssemblyDescription("Combat bot plugin for NexSuite")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("NexSuite")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: Guid("33333333-3333-3333-3333-333333333333")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs new file mode 100644 index 0000000..2800a97 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Nav/VTankNavParser.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Plugin.RynthAi.Nav; + +public enum NavRouteType +{ + Once = 4, + Circular = 1, + Linear = 2, + Follow = 3 +} + +public enum NavPointType +{ + Point = 0, + Recall = 2, + Pause = 3, + Chat = 4, + PortalNPC = 6 +} + +public 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; } = ""; + public string TargetName { get; set; } = ""; + public int ObjectClass { get; set; } + public bool IsTie { get; set; } + + public double PortalExitNS { get; set; } + public double PortalExitEW { get; set; } + public double PortalExitZ { get; set; } + 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}s", + NavPointType.Chat => $"[Chat] {ChatCommand}", + NavPointType.PortalNPC => $"[Portal] {TargetName}", + _ => $"[Unknown] {Type}" + }; + } +} + +public class VTankNavParser +{ + public NavRouteType RouteType { get; set; } + public List<NavPoint> Points { get; set; } = new(); + + public static VTankNavParser Load(string filePath) + { + var route = new VTankNavParser(); + string[] lines = File.ReadAllLines(filePath); + + if (lines.Length < 3) return route; + if (!lines[0].Contains("uTank2 NAV 1.2")) + return route; + + route.RouteType = (NavRouteType)int.Parse(lines[1]); + int pointCount = int.Parse(lines[2]); + + int idx = 3; + for (int i = 0; i < pointCount && idx < lines.Length; i++) + { + var pt = new NavPoint(); + pt.Type = (NavPointType)int.Parse(lines[idx++]); + pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + + switch (pt.Type) + { + case NavPointType.Point: break; + case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break; + case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break; + case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break; + case NavPointType.PortalNPC: + pt.TargetName = lines[idx++]; + pt.ObjectClass = int.Parse(lines[idx++]); + pt.IsTie = bool.Parse(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); + idx++; // spacer + pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture); + idx++; // spacer + break; + } + + route.Points.Add(pt); + } + + return route; + } + + public void Save(string filePath) + { + using var writer = new StreamWriter(filePath, false); + writer.WriteLine("uTank2 NAV 1.2"); + writer.WriteLine((int)RouteType); + writer.WriteLine(Points.Count); + + foreach (var pt in Points) + { + writer.WriteLine((int)pt.Type); + writer.WriteLine(pt.EW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.NS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.Z.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + + switch (pt.Type) + { + case NavPointType.Recall: writer.WriteLine(pt.SpellId); break; + case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break; + case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break; + case NavPointType.PortalNPC: + writer.WriteLine(pt.TargetName); + writer.WriteLine(pt.ObjectClass); + writer.WriteLine(pt.IsTie.ToString()); + writer.WriteLine(pt.PortalExitEW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitNS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalExitZ.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + writer.WriteLine(pt.PortalLandEW.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandNS.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine(pt.PortalLandZ.ToString(CultureInfo.InvariantCulture)); + writer.WriteLine("0"); + break; + } + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs new file mode 100644 index 0000000..b06b189 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() => Runtime.Shutdown(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr Name() => RynthAiPlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr Version() => RynthAiPlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUIInitialized() => Runtime.OnUIInitialized(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountIncremented", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBusyCountIncremented() => Runtime.OnBusyCountIncremented(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountDecremented", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBusyCountDecremented() => Runtime.OnBusyCountDecremented(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnBarAction() => Runtime.OnBarAction(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() => Runtime.OnRender(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => + Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => + Runtime.OnChatBarEnter(textUtf16, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => + Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) => + Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSmartBoxEvent", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnSmartBoxEvent(uint opcode, uint blobSize, uint status) => + Runtime.OnSmartBoxEvent(opcode, blobSize, status); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) => + Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => + Runtime.OnEnchantmentAdded(spellId, durationSeconds); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentRemoved(uint enchantmentId) => + Runtime.OnEnchantmentRemoved(enchantmentId); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs new file mode 100644 index 0000000..7212a2d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -0,0 +1,429 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthAi.Nav; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public sealed unsafe class RynthAiPlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0"); + + private const float NavPointElevationOffset = 0.5f; + private const float UnitsPerCoord = 240.0f; + private const int RingSegments = 32; + private const float RingRadius = 3.0f; // game units (~1.25 yards) + + // ImGui colors (ABGR format for ImGui native) + private const uint ColorCyan = 0xFFFFFF00; // nav point rings + private const uint ColorRed = 0xFF2222FF; // active waypoint ring + private const uint ColorBlueLine = 0xFFFF8800; // lines between points + + private static RynthCoreApiNative _api; + private static RynthCoreHost _host; + private static bool _initialized; + private static bool _loginComplete; + private static bool _windowVisible; + private static bool _showRoute = true; + + // Route state + private static VTankNavParser? _currentRoute; + private static string _currentNavPath = ""; + private static int _activeNavIndex; + private static readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + + // Nav file browser state + private static string[] _navFiles = Array.Empty<string>(); + + // Cached cimgui function pointers + private static delegate* unmanaged[Cdecl]<IntPtr, void> _igSetCurrentContext; + private static delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void> _igSetNextWindowPos; + private static delegate* unmanaged[Cdecl]<ImVec2, int, void> _igSetNextWindowSize; + private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte> _igBegin; + private static delegate* unmanaged[Cdecl]<void> _igEnd; + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte> _igButton; + private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _igTextUnformatted; + private static delegate* unmanaged[Cdecl]<void> _igSeparator; + private static delegate* unmanaged[Cdecl]<IntPtr, byte*, byte> _igCheckbox; + private static delegate* unmanaged[Cdecl]<IntPtr> _igGetForegroundDrawList; + // ImDrawList_AddCircle(self, center, radius, col, num_segments, thickness) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void> _igDrawListAddCircle; + // ImDrawList_AddLine(self, p1, p2, col, thickness) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void> _igDrawListAddLine; + // ImDrawList_AddCircleFilled(self, center, radius, col, num_segments) + private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void> _igDrawListAddCircleFilled; + private static bool _imguiBound; + + public override int Initialize() + { + _api = Api; + _host = Host; + + if (_api.ImGuiContext == IntPtr.Zero) + return 11; + + if (!TryBindImGui(out string error)) + { + Log($"RynthAi: failed to bind cimgui ({error})"); + return 12; + } + + _initialized = true; + _loginComplete = false; + _windowVisible = false; + _showRoute = true; + _currentRoute = null; + _currentNavPath = ""; + _activeNavIndex = 0; + + RefreshNavFiles(); + Log("RynthAi: initialized."); + return 0; + } + + public override void Shutdown() + { + Log("RynthAi: shutting down."); + _initialized = false; + _loginComplete = false; + _currentRoute = null; + } + + public override void OnLoginComplete() + { + if (!_initialized) return; + _loginComplete = true; + } + + public override void OnBarAction() + { + if (!_initialized || !_loginComplete) return; + _windowVisible = !_windowVisible; + } + + public override void OnRender() + { + if (!_initialized || !_loginComplete || !_imguiBound || _api.ImGuiContext == IntPtr.Zero) + return; + + _igSetCurrentContext(_api.ImGuiContext); + + // Draw the 3D nav route overlay (always, even if UI window is hidden) + if (_showRoute && _currentRoute != null && _currentRoute.Points.Count > 0) + RenderNavRoute(); + + // Draw the UI panel + if (_windowVisible) + RenderNavPanel(); + } + + // ─── Precomputed ring geometry (unit circle on ground plane) ──────── + + private static readonly float[] _cosTable = new float[RingSegments]; + private static readonly float[] _sinTable = new float[RingSegments]; + private static bool _trigReady; + + private static void EnsureTrigTables() + { + if (_trigReady) return; + for (int i = 0; i < RingSegments; i++) + { + double angle = 2.0 * Math.PI * i / RingSegments; + _cosTable[i] = (float)Math.Cos(angle); + _sinTable[i] = (float)Math.Sin(angle); + } + _trigReady = true; + } + + // ─── 3D Nav Route Rendering ────────────────────────────────────────── + + private static void RenderNavRoute() + { + if (!_host.HasWorldToScreen || !_host.HasGetPlayerPose || !_host.HasGetCurCoords) + return; + + if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz, + out float _, out float _, out float _, out float _)) + return; + + if (!_host.TryGetCurCoords(out double playerNS, out double playerEW)) + return; + + IntPtr drawList = _igGetForegroundDrawList(); + if (drawList == IntPtr.Zero) + return; + + EnsureTrigTables(); + + var route = _currentRoute!; + int count = route.Points.Count; + + // Project center of each nav point for line drawing + Span<float> centerSx = stackalloc float[count]; + Span<float> centerSy = stackalloc float[count]; + Span<bool> centerOnScreen = stackalloc bool[count]; + + for (int i = 0; i < count; i++) + { + var pt = route.Points[i]; + float wx = px + (float)((pt.EW - playerEW) * UnitsPerCoord); + float wy = py + (float)((pt.NS - playerNS) * UnitsPerCoord); + float wz = (float)pt.Z + NavPointElevationOffset; + + centerOnScreen[i] = _host.WorldToScreen(wx, wy, wz, out centerSx[i], out centerSy[i]); + } + + // Draw lines between consecutive waypoints + for (int i = 0; i < count; i++) + { + int nextIdx = i + 1; + if (nextIdx >= count) + { + if (route.RouteType == NavRouteType.Circular) + nextIdx = 0; + else + continue; + } + + if (!centerOnScreen[i] && !centerOnScreen[nextIdx]) + continue; + + _igDrawListAddLine( + drawList, + new ImVec2(centerSx[i], centerSy[i]), + new ImVec2(centerSx[nextIdx], centerSy[nextIdx]), + ColorBlueLine, + 2.0f); + } + + // Draw 3D rings on the ground at each waypoint + // Each ring is a circle of world-space points projected to screen space + Span<float> ringSx = stackalloc float[RingSegments]; + Span<float> ringSy = stackalloc float[RingSegments]; + Span<bool> ringVis = stackalloc bool[RingSegments]; + + for (int i = 0; i < count; i++) + { + var pt = route.Points[i]; + float cx = px + (float)((pt.EW - playerEW) * UnitsPerCoord); + float cy = py + (float)((pt.NS - playerNS) * UnitsPerCoord); + float cz = (float)pt.Z + NavPointElevationOffset; + + // Project each vertex of the ring (lying flat on the ground plane) + int visCount = 0; + for (int s = 0; s < RingSegments; s++) + { + float wx = cx + _cosTable[s] * RingRadius; + float wy = cy + _sinTable[s] * RingRadius; + + ringVis[s] = _host.WorldToScreen(wx, wy, cz, out ringSx[s], out ringSy[s]); + if (ringVis[s]) visCount++; + } + + // Skip if no part of the ring is visible + if (visCount == 0) + continue; + + uint color = (i == _activeNavIndex) ? ColorRed : ColorCyan; + float thickness = (i == _activeNavIndex) ? 3.0f : 2.0f; + + // Draw the ring as connected line segments + for (int s = 0; s < RingSegments; s++) + { + int next = (s + 1) % RingSegments; + + // Draw segment if at least one end projected successfully + if (ringVis[s] || ringVis[next]) + { + _igDrawListAddLine( + drawList, + new ImVec2(ringSx[s], ringSy[s]), + new ImVec2(ringSx[next], ringSy[next]), + color, + thickness); + } + } + } + } + + // ─── Nav Control Panel ─────────────────────────────────────────────── + + private static void RenderNavPanel() + { + _igSetNextWindowPos(new ImVec2(48f, 140f), 1 << 2 /* ImGuiCond_FirstUseEver */, default); + _igSetNextWindowSize(new ImVec2(380f, 320f), 1 << 2); + + bool open = _igBegin( + Marshal.StringToHGlobalAnsi("RynthAi Nav##RynthAiNav"), + IntPtr.Zero, + 0) != 0; + + if (open) + { + // Show route toggle + byte showByte = _showRoute ? (byte)1 : (byte)0; + if (_igCheckbox(Marshal.StringToHGlobalAnsi("Show Route"), &showByte) != 0) + _showRoute = showByte != 0; + + _igSeparator(); + + // Current route info + string info = _currentRoute != null + ? $"Route: {Path.GetFileName(_currentNavPath)} ({_currentRoute.Points.Count} pts, {_currentRoute.RouteType})" + : "No route loaded"; + TextTemp(info); + + if (_currentRoute != null) + TextTemp($"Active waypoint: {_activeNavIndex}"); + + _igSeparator(); + + // Nav file list + TextTemp("Nav Files:"); + + for (int i = 0; i < _navFiles.Length; i++) + { + string fileName = Path.GetFileName(_navFiles[i]); + bool isCurrent = string.Equals(_navFiles[i], _currentNavPath, StringComparison.OrdinalIgnoreCase); + string label = isCurrent ? $">> {fileName}" : $" {fileName}"; + + IntPtr labelPtr = Marshal.StringToHGlobalAnsi($"{label}##{i}"); + try + { + if (_igButton(labelPtr, new ImVec2(340f, 0f)) != 0) + { + LoadNavFile(_navFiles[i]); + } + } + finally + { + Marshal.FreeHGlobal(labelPtr); + } + } + + _igSeparator(); + + if (_igButton(Marshal.StringToHGlobalAnsi("Refresh Files"), default) != 0) + RefreshNavFiles(); + } + + _igEnd(); + } + + // ─── Nav File Management ───────────────────────────────────────────── + + private static void RefreshNavFiles() + { + try + { + if (Directory.Exists(_navFolder)) + _navFiles = Directory.GetFiles(_navFolder, "*.nav"); + else + _navFiles = Array.Empty<string>(); + } + catch + { + _navFiles = Array.Empty<string>(); + } + } + + private static void LoadNavFile(string path) + { + try + { + _currentRoute = VTankNavParser.Load(path); + _currentNavPath = path; + _activeNavIndex = 0; + _host.Log($"RynthAi: Loaded route '{Path.GetFileName(path)}' with {_currentRoute.Points.Count} points"); + } + catch (Exception ex) + { + _host.Log($"RynthAi: Failed to load nav file: {ex.Message}"); + } + } + + // ─── ImGui Helpers ─────────────────────────────────────────────────── + + private static void TextTemp(string text) + { + IntPtr ptr = Marshal.StringToHGlobalAnsi(text); + try { _igTextUnformatted(ptr, IntPtr.Zero); } + finally { Marshal.FreeHGlobal(ptr); } + } + + private static bool TryBindImGui(out string error) + { + if (_imguiBound) { error = ""; return true; } + + IntPtr mod = GetModuleHandleA("RynthCore.cimgui.dll"); + if (mod == IntPtr.Zero) mod = GetModuleHandleA("cimgui.dll"); + if (mod == IntPtr.Zero) { error = "no cimgui module"; return false; } + + if (!TryGetProc(mod, "igSetCurrentContext", out IntPtr p)) { error = "missing igSetCurrentContext"; return false; } + _igSetCurrentContext = (delegate* unmanaged[Cdecl]<IntPtr, void>)p; + + if (!TryGetProc(mod, "igSetNextWindowPos", out p)) { error = "missing igSetNextWindowPos"; return false; } + _igSetNextWindowPos = (delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void>)p; + + if (!TryGetProc(mod, "igSetNextWindowSize", out p)) { error = "missing igSetNextWindowSize"; return false; } + _igSetNextWindowSize = (delegate* unmanaged[Cdecl]<ImVec2, int, void>)p; + + if (!TryGetProc(mod, "igBegin", out p)) { error = "missing igBegin"; return false; } + _igBegin = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte>)p; + + if (!TryGetProc(mod, "igEnd", out p)) { error = "missing igEnd"; return false; } + _igEnd = (delegate* unmanaged[Cdecl]<void>)p; + + if (!TryGetProc(mod, "igButton", out p)) { error = "missing igButton"; return false; } + _igButton = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte>)p; + + if (!TryGetProc(mod, "igTextUnformatted", out p)) { error = "missing igTextUnformatted"; return false; } + _igTextUnformatted = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)p; + + if (!TryGetProc(mod, "igSeparator", out p)) { error = "missing igSeparator"; return false; } + _igSeparator = (delegate* unmanaged[Cdecl]<void>)p; + + if (!TryGetProc(mod, "igCheckbox", out p)) { error = "missing igCheckbox"; return false; } + _igCheckbox = (delegate* unmanaged[Cdecl]<IntPtr, byte*, byte>)p; + + if (!TryGetProc(mod, "igGetForegroundDrawList_Nil", out p)) { error = "missing igGetForegroundDrawList"; return false; } + _igGetForegroundDrawList = (delegate* unmanaged[Cdecl]<IntPtr>)p; + + if (!TryGetProc(mod, "ImDrawList_AddCircle", out p)) { error = "missing ImDrawList_AddCircle"; return false; } + _igDrawListAddCircle = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void>)p; + + if (!TryGetProc(mod, "ImDrawList_AddLine", out p)) { error = "missing ImDrawList_AddLine"; return false; } + _igDrawListAddLine = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void>)p; + + if (!TryGetProc(mod, "ImDrawList_AddCircleFilled", out p)) { error = "missing ImDrawList_AddCircleFilled"; return false; } + _igDrawListAddCircleFilled = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void>)p; + + _imguiBound = true; + error = ""; + return true; + } + + private static bool TryGetProc(IntPtr module, string exportName, out IntPtr address) + { + address = GetProcAddress(module, exportName); + return address != IntPtr.Zero; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] + private static extern IntPtr GetModuleHandleA(string lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + + [StructLayout(LayoutKind.Sequential)] + private readonly struct ImVec2 + { + public readonly float X; + public readonly float Y; + public ImVec2(float x, float y) { X = x; Y = y; } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj new file mode 100644 index 0000000..d18b071 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -0,0 +1,57 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <OutputType>Library</OutputType> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <Nullable>enable</Nullable> + <PublishAot>true</PublishAot> + <NativeLib>Shared</NativeLib> + <InvariantGlobalization>true</InvariantGlobalization> + <IlcOptimizationPreference>Size</IlcOptimizationPreference> + <StripSymbols>false</StripSymbols> + <RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace> + <AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName> + <Platforms>x86</Platforms> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" /> + <ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" /> + </ItemGroup> + + <Target Name="CopyPublishedPluginToEngineOutputs" AfterTargets="Publish" Condition="'$(PublishDir)' != ''"> + <ItemGroup> + <_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\Plugins\" /> + <_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\Plugins\" /> + <_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" /> + <_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" /> + </ItemGroup> + + <MakeDir Directories="@(_EnginePluginDir)" /> + <MakeDir Directories="@(_EnginePluginPublishDir)" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).dll" + DestinationFolder="%(_EnginePluginDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).dll')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).pdb" + DestinationFolder="%(_EnginePluginDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).dll" + DestinationFolder="%(_EnginePluginPublishDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).dll')" /> + <Copy + SourceFiles="$(PublishDir)$(AssemblyName).pdb" + DestinationFolder="%(_EnginePluginPublishDir.Identity)" + SkipUnchangedFiles="true" + Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" /> + </Target> + +</Project> diff --git a/docs/ACCLIENT_HOOK_INVENTORY.md b/docs/ACCLIENT_HOOK_INVENTORY.md new file mode 100644 index 0000000..0251747 --- /dev/null +++ b/docs/ACCLIENT_HOOK_INVENTORY.md @@ -0,0 +1,91 @@ +# ACClient Hook Inventory + +This file tracks RynthCore hook targets against the user's real AC client binary, with the AC client decompile used for semantics and the live binary used as the source of truth for hook placement. + +## Client Fingerprint + +- Path: `C:\Turbine\Asheron's Call\acclient.exe` +- File size: `4,841,472` bytes +- SHA256: `BCA95BBEBED4B9ED1FF09D0DA83144E2FC4208F63AD7ADA5CB47C3CA207CCBA9` +- PE machine: `0x014C` (`x86`) +- PE image size: `0x0056D000` + +## Rules For This Inventory + +- Use the decompile to understand semantics, call order, and callback behavior. +- Use the live `acclient.exe` to derive patterns, validate uniqueness, and choose the real hook address. +- Do not ship fixed RVAs from the decompile unless they have been validated against the live binary. +- Prefer hooking the AC client function that already implements the desired behavior over lower-level memory access. +- Every production hook should eventually have: + - a primary binary pattern + - at least one fallback pattern or alternate seam when practical + - runtime validation + - an explicit unsupported-state log/UI message + +## Priority Inventory + +### Lifecycle And UI + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnLoginComplete` | `CPlayerSystem::SendLoginCompleteNotification` in `CPlayerSystem.cpp:4017-4031` | Pattern-scan the containing function using the unique `SetDisplayInventory(1)` plus `BroadcastGlobalMessage(..., 0xB, 0)` sequence, then hook the containing `thiscall` function. | Live in RynthCore | P0 | +| `OnUIInitialized` | `ClientUISystem::OnStartup` in `ClientUISystem.cpp:48` and `APIManager::SetUIReady(1)` in `APIManager.cpp:134` | Hook the tiny `OnStartup -> SetUIReady(1)` wrapper or the `SetUIReady(1)` transition path. Prefer the wrapper if the pattern is unique in the live binary. | Not implemented | P0 | +| `OnBusyCountIncremented` | `ClientUISystem::IncrementBusyCount` in `ClientUISystem.cpp:630` | Hook the wrapper that increments `m_cBusy` and updates cursor state when crossing `0 -> 1`. | Not implemented | P1 | +| `OnBusyCountDecremented` | `ClientUISystem::DecrementBusyCount` in `ClientUISystem.cpp:641` | Hook the wrapper that decrements `m_cBusy` and updates cursor state when crossing `1 -> 0`. | Not implemented | P1 | + +### Chat And Command + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnChatWindowText` | `ClientSystem.cpp:108` | Hook the function that allocates a BSTR from `i_text`, calls `GetACPlugin()->OnChatWindowText`, then checks `bEat` before continuing UI output. | Ready for binary patterning | P0 | +| `OnChatBarEnter` | `ClientCommunicationSystem.cpp:14407` | Hook the function that allocates a BSTR from the entered line, calls `GetACPlugin()->OnChatBarEnter`, and returns early when the plugin consumes the line. | Ready for binary patterning | P0 | + +### World, Target, And Object Flow + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnDeleteObject` | `ACCObjectMaint::DeleteObject` in `ACCObjectMaint.cpp:73-85` | Hook the clean wrapper that checks `APIIsReady`, calls `OnDeleteObject`, then calls `ACCWeenieObject::SetCorpseDeleted` and `CObjectMaint::DeleteObject`. | Ready for binary patterning | P0 | +| `OnSelectedTargetChange` | `ACCWeenieObject.cpp:710` and `ACCWeenieObject.cpp:1997` | Hook the selected-target setter path after `CM_UI::SendNotice_SelectionChanged` and before the direct plugin callback. | Ready for binary patterning | P0 | +| World/object dispatch | `ACSmartBox::DispatchSmartBoxEvent` in `ACSmartBox.cpp:37-171` | Hook the SmartBox dispatch seam as the high-value world/object/network filter layer. This is the likely replacement for many WorldFilter-style surfaces. | Ready for binary patterning | P0 | +| Object creation | `ACCObjectMaint::CreateObject` in `ACCObjectMaint.cpp:196` | Hook the object creation wrapper for higher-level object lifecycle callbacks when we need richer data than a raw SmartBox event. | Ready for binary patterning | P1 | +| Object inventory updates | `ACCObjectMaint::UpdateObjectInventory` in `ACCObjectMaint.cpp:377` | Hook the inventory update path for container/item-change compatibility events. | Ready for binary patterning | P1 | +| Update/create/delete server dispatch | `CM_Physics::DispatchSB_CreateObject`, `DispatchSB_UpdateObject`, `DispatchSB_DeleteObject` in `CM_Physics.cpp` | Use as fallback seams if the outer SmartBox dispatcher proves too broad or unstable. | Decompile-confirmed | P1 | + +### Combat And Trade + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnCombatModeChange` | `ClientCombatSystem.cpp:1564` | Hook the branch that invokes the plugin callback after the combat mode change resolves and auto-targeting logic runs. | Ready for binary patterning | P1 | +| Trade window opened | `ClientTradeSystem.cpp:525` | Hook `Handle_Trade__Recv_RegisterTrade` after `CM_Trade::SendNotice_RegisterTrade` and before the internal attempt-to-trade follow-up. | Ready for binary patterning | P1 | +| Trade item added | `ClientTradeSystem::Handle_Trade__Recv_AddToTrade` in `ClientTradeSystem.cpp:560+` | Hook the direct wrapper that calls `CM_Trade::SendNotice_AddItemToTrade` and then `OnTradeWindowItemAdded`. | Ready for binary patterning | P1 | +| Trade completed | `ClientCommunicationSystem.cpp:3106` | Hook the message-switch case for `0x529` (`Trade Complete!`) that directly invokes `OnTradeCompleted`. | Ready for binary patterning | P1 | +| Trade accept/decline/close/clear | `ClientTradeSystem.cpp` | Hook the direct trade-system wrappers that invoke the corresponding plugin callback. | Decompiled seam confirmed, binary anchor still needed | P1 | + +## Host Call Surface To Expose Through RynthCore + +These are not plugin callback hooks, but they are part of the host API surface we should expose once the callback layer is in place. + +| API surface | Decompiled seam | Notes | Priority | +| --- | --- | --- | --- | +| `WriteToChat` | `APIManager__IAsheronsCallImpl.cpp` | Safe early host helper. | P0 | +| Selection get/set | `APIManager__IAsheronsCallImpl.cpp` | Pairs naturally with target-change callbacks. | P0 | +| `UseObject`, `UseObjectOn`, `UseEquippedItem` | `APIManager__IAsheronsCallImpl.cpp` | Good interaction helpers once lifecycle is stable. | P1 | +| `MoveItemExternal`, `MoveItemInternal` | `APIManager__IAsheronsCallImpl.cpp` | Useful once inventory callbacks exist. | P1 | +| `IsStandingStill`, `StopCompletely`, `TurnToHeading`, `SetAutoRun` | `APIManager__IAsheronsCallImpl.cpp` | Movement helper layer. Some of this already overlaps with existing RynthCore action hooks. | P0 | +| `GetCurCoords`, `GetPlayerID`, `GetGroundContainerID` | `APIManager__IAsheronsCallImpl.cpp` | Good basic state helpers. | P0 | +| `GetScreenDimensions`, `ItemIsKnown`, `GetItemName` | `APIManager__IAsheronsCallImpl.cpp` | Low-risk host helpers. | P1 | +| `IssueChatBarCommand` | `APIManager__IAsheronsCallImpl.cpp` | Treat as stub-like until runtime behavior is validated against the live client. | Hold | +| `GetCombatMode`, `GetBusyCount`, salvage panel APIs | `APIManager__IAsheronsCallImpl_vtbl.cpp` | Declared but not yet fully validated in the split. | Hold | + +## Implementation Waves + +1. Finish lifecycle/UI: `OnLoginComplete`, `OnUIInitialized`, busy count. +2. Add chat interception: `OnChatWindowText`, `OnChatBarEnter`. +3. Add world/object seams: SmartBox dispatch, delete/create/inventory, selected target. +4. Add combat/trade callbacks. +5. Expose the confirmed `IAsheronsCall` subset through RynthCore-native host APIs. + +## Notes + +- The split decompile is still very useful, but the login-complete work already showed that its function RVAs do not always line up with the user's live client binary. +- For this reason, future hook work should be tracked here first against the fingerprint above, then implemented in RynthCore with pattern scanning rather than fixed addresses. diff --git a/docs/DXVK_TEXTURE_SMOKE.md b/docs/DXVK_TEXTURE_SMOKE.md new file mode 100644 index 0000000..376f489 --- /dev/null +++ b/docs/DXVK_TEXTURE_SMOKE.md @@ -0,0 +1,85 @@ +# DXVK drop-in smoke checklist (textures / overlay) + +Preferred path: launcher **Launch Behavior → Enable DXVK** (opt-in) plus **Fetch / update DXVK**. That copies x86 `d3d9.dll` from `<RynthCore>\Runtime\dxvk\` next to `acclient.exe` (and removes it when unchecked). Installer seeds the same cache; `scripts\Fetch-Dxvk.ps1` can refresh it. + +Manual drop-in still works the same for smoke without the launcher toggle. + +Live AC installs used for this checklist: +- `C:\Turbine\Asheron's Call-ryn\` (Rynth-launched clients; cwd in recent logs) +- `C:\Turbine\Asheron's Call\` (retail copy; same drop-in applied) + +Engine logs: `C:\Games\RynthCore\Logs\RynthCore.<pid>.log` +Cache / drop-in: **DXVK 3.1.1** `x32/d3d9.dll` (+ `dxvk.conf`). + +## 0. Prerequisites + +- [ ] **32-bit (x86) DXVK** (AC is 32-bit). Launcher Fetch / installer seed handle this. +- [ ] Decal **off** for first pass (fewer moving parts). +- [ ] Optional: set `DXVK_HUD=1` or `DXVK_LOG_LEVEL=info` in the environment to confirm Vulkan is active. + +## 1. Files to place (beside `acclient.exe`) + +| File | Required | Notes | +|---|---|---| +| `d3d9.dll` | Yes | From DXVK `x32` / win32 package | +| `dxvk.conf` | Optional | See sample below | +| `d3d11.dll` / `dxgi.dll` | No | AC only needs d3d9 | + +Sample `dxvk.conf` (conservative for old clients): + +```ini +# dxvk.conf — Asheron's Call / Rynth smoke +dxgi.deferSurfaceCreation = True +d3d9.maxFrameLatency = 1 +d3d9.presentInterval = 1 +``` + +## 2. AC alone (no Rynth) + +1. Launch AC from the folder that has the drop-in `d3d9.dll`. +2. Log in to world. +3. Pass if: world renders, no black screen, FPS roughly sane, optional DXVK HUD visible. +4. Fail if: crash on device create, pure software fallback, or no Vulkan device. + +## 3. AC + Rynth (no Decal) + +1. With DXVK still in place, launch via Rynth as usual. +2. Open `C:\Games\RynthCore\Logs\RynthCore.<pid>.log` and grep: + +| Look for | Meaning | +|---|---| +| `DxvkDetection: DXVK detected` | Harness saw DXVK version resource / `dxvk.conf` | +| `forcing software overlay textures` | Shared-HANDLE path disabled; LockRect path forced | +| `D3D9Bootstrapper: d3d9.dll loaded` | Bootstrap saw the module | +| `EndSceneHook: INSTALLED successfully` | Hook installed | +| `EndSceneHook: Warmup complete - initializing ImGui` | First backbuffer frames OK | +| `DX9Backend: CreateTexture failed` | **Fail** — font/icon upload broken | +| `OverlayTextureRenderer: CreateTexture` / `Created … overlay texture` | Software overlay upload working | +| `D3D9Ex shared-texture consumption is unavailable` | Expected under DXVK if Angle path still probed | +| `EndSceneHook: FAILED` / `vtable discovery returned null` | **Fail** — PE/NULLREF discovery needs work | + +3. In-game pass criteria: + - [ ] ImGui / Rynth panels draw + - [ ] Script / DAT icons visible (not solid magenta or blank) + - [ ] Avalonia HUD / Mini Remote readable (may be slightly blurrier on software path) + - [ ] Pop-outs: optional; `GetRenderTargetData` can flake — note fail, don’t block Phase 0 + +## 4. Env overrides (no rebuild) + +| Variable | Effect | +|---|---| +| `RYNTHCORE_DISABLE_ANGLE_BRIDGE=1` | Force software overlay even without DXVK | +| `DXVK_HUD=1` | Confirm DXVK is the active D3D9 | +| `DXVK_LOG_PATH=<dir>` | DXVK’s own log next to game | + +## 5. Rollback + +1. Quit AC + Rynth. +2. Delete or rename game-dir `d3d9.dll` (and `dxvk.conf`). +3. Relaunch — logs should show `DxvkDetection: stock system d3d9.dll`. + +## 6. Known non-goals for this smoke + +- D3D9Ex **shared HANDLE** Avalonia interop (expected broken / forced off). +- Decal coexistence under DXVK (second pass only if alone+Rynth passes). +- Shipping DXVK inside the Rynth installer. diff --git a/docs/ub-hub-merge-playbook.md b/docs/ub-hub-merge-playbook.md new file mode 100644 index 0000000..780b48e --- /dev/null +++ b/docs/ub-hub-merge-playbook.md @@ -0,0 +1,117 @@ +# UB Hub → RynthCore / RynthSuite — Implementation Playbook + +**Audience:** George Blankenship +**Purpose:** Working checklist for the ILT Hub merge — what landed, what is still open. Assessment detail lives in the Cursor project store (`ub-hub-merge-plan.md`, `repo-remote-sync.md`). +**Hub code lives in RynthSuite** (`feat/ilt-hub`). This Core copy is tracking only. +**Repo tracking homes (keep uniform):** +- Suite: `Docs/ub-hub-merge-playbook.md` on **`feat/ilt-hub`** and **`SK-local`** +- Core: `docs/ub-hub-merge-playbook.md` on **`SK-local`** (Core has no `feat/ilt-hub`) +Do **not** put the playbook only on a docs-only PR branch — keep it with the Hub / SK worktrees. +**This doc does not implement more product code.** + +--- + +## Status (2026-10-04) + +| Track | State | +|-------|--------| +| Assessment + playbook | **Done** — plan + this playbook (Pet: SummonPets mechanics + breeding) | +| Remotes / aelrynth overlay | **Done on `main`** — Core [#1](https://github.com/BlankenshipG/RynthCore/pull/1), Suite [#1](https://github.com/BlankenshipG/RynthSuite/pull/1) | +| ILT Hub P0–P2 | **On Suite `feat/ilt-hub`** — `ad61194` (0.5.1 Hub) + `18b4579` (0.5.2 diagnostics/security). **Not on `main`. No Hub PR yet.** | +| SK-local unified (2026-10-04) | **Done** — Core + Suite `SK-local` contain `main`, `feat/full-installer`, `feat/ilt-hub`, `SK`, PR #2. RynthAi **0.6.10** fixes Hub creation on late settings load and the world-name wait in the login probe. ub-Rythai 3.1.10 is an optional installer component. | +| Pet: SummonPets / breeding | **Partial** — picker/charms/HealingBuddy/rosters + hardened empty-summon. **Still open:** deepen PetManager; bond/potency UI; **breeding** if `pet_breeding_enabled` | +| ACECustom `/ilt features` | **Not done** — still “Coming Soon” | +| In-AC smoke | **Not done in this project** | +| AutoXp / AutoTinker | **Out of scope** | + +**Next:** PR Suite `feat/ilt-hub` → `main`, smoke, then Pet follow-on (SummonPets + breeding). Keep this file current on **`feat/ilt-hub`** and **`SK-local`**. + +**Home:** Suite `Plugins/RynthCore.Plugin.RynthAi/IltHub/` + `Combat/PetManager.cs`. ACECustom breeding: `PET_BREEDING_PLAYER_GUIDE.md` / `PET_BREEDING_REFERENCE.md`. + +--- + +## When to use / desired result + +**Use when** reviewing, merging, or finishing leftover Hub work. + +**Desired result:** ImGui **ILT Hub** (Character · Pet · Banking · Gear · Games), server-option gated, per-char Hub state. Pet tab **updates** `SummonPets` / pet mechanics and adds **breeding only when `pet_breeding_enabled`**. + +--- + +## Prerequisites (locked) + +| Repo | Branches for this playbook | Notes | +|------|----------------------------|--------| +| **RynthSuite** | **`feat/ilt-hub`**, **`SK-local`** | Hub code + `Docs/ub-hub-merge-playbook.md` | +| **RynthCore** | **`SK-local`** | Tracking copy only (`docs/…`); no Hub product code | +| **UB** | `ILT_Customizations` (source) | Read-only for Hub | +| **ACECustom** | — | `/ilt features`, bond, potency, `pet_breeding_*` | + +**Locked decisions:** ImGui not Avalonia/VVS; `IltServerOptions` per feature; Hub state ≠ `/ra settings`; Games greenfield; Pet = update SummonPets + picker + item-check + breeding if server on; Guardian Hand on Gear. + +--- + +## Done vs remaining + +### Phase 1 — Shell + state + IltServerOptions — **coded** (PR + `/ilt features` dump open) + +### Phase 2 — Banking — **coded** (smoke open) + +### Phase 3 — Pet — **partial** + +| | | +|--|--| +| **Landed** | Essence picker → Pet rules; SummonPets / min-mobs / spirit refill; refill + mastery charms; hardened `AllowSummonOnEmpty`; HoldSummons; HealingBuddy; `/pets` `/shinies` | +| **Still to do** | Deepen PetManager (range UI, mastery usability, bond/potency columns); breeding panel iff `pet_breeding_enabled` (appraisal readiness, annex hint, dance QoL — no client litter math); smoke | + +### Phases 4–6 — Character / Gear / Games — **coded** (smoke, Guardian Hand WCID, quests.xml open) + +### Phase 7 — Hardening — **0.5.2 on branch** (diagnostics + security); ship/verify open + +--- + +## Remaining work + +1. PR Suite **`feat/ilt-hub`** → `main` +2. In-AC smoke on ILT +3. Pet follow-on: SummonPets mechanics + breeding when enabled → bump **0.5.3** +4. ACECustom `/ilt features` (include pet_breeding / bond / potency / refill) +5. Guardian Hand WCID when published +6. Optional: quests.xml, UB settings import, USD smoke +7. Keep playbook identical on Suite `feat/ilt-hub` + `SK-local` and Core `SK-local` + +--- + +## Explicit non-goals + +- Second pet summon system (update PetManager instead) +- Client breeding math when `pet_breeding_enabled` is false +- VVS XML / AutoXp / AutoTinker / Avalonia RynthAiPanel / force-replace `main` + +--- + +## Version / changelog + +- **0.5.1** — Hub landing · **0.5.2** — diagnostics + Hub security (on `feat/ilt-hub`) +- Next Pet wave: **0.5.3** + `Changelog/` note. Don’t bump Core API unless host APIs change. + +--- + +## Gate cheat sheet + +| Surface | Enable when | Keep off when | +|---------|-------------|----------------| +| Whole Hub | ILT-like or Force **and** ≥1 bit | Retail, Force off | +| Pet breeding | `pet_breeding_enabled` | Off / Unknown | +| Pet bond / potency | `pet_bond_enabled` / `pet_potency_enabled` | Flags false | +| Pet empty-summon | Charm + confirmed `pet_refill` | Not confirmed | +| Banking / Powerball / Quests / Clap | Per existing IltServerOptions rules | Unknown / Off | + +--- + +## Pointers + +- Plan/remotes (project store): `ub-hub-merge-plan.md`, `repo-remote-sync.md` +- Suite Hub branch: **`feat/ilt-hub`** @ `18b4579` (0.5.2) · also **`SK-local`** +- Changelogs: `Changelog/RynthAi-0.5.1-ilt-hub.md`, `Changelog/RynthAi-0.5.2-diagnostics-security.md` +- ACECustom: `pet_breeding_enabled`, `PetDevice_Breeding.cs` diff --git a/find_bytes.cs b/find_bytes.cs new file mode 100644 index 0000000..a60420b --- /dev/null +++ b/find_bytes.cs @@ -0,0 +1,20 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +public class Program { + public static void Main() { + byte[] pe = File.ReadAllBytes(@"C:\Games\NexCore\acclient.exe"); + int peOffset = BitConverter.ToInt32(pe, 0x3C); + int numSections = BitConverter.ToInt16(pe, peOffset + 6); + int sectionHeaders = peOffset + 24 + BitConverter.ToInt16(pe, peOffset + 20); + for (int i = 0; i < numSections; i++) { + int rva = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 12); + int size = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 16); + int ptr = BitConverter.ToInt32(pe, sectionHeaders + i * 40 + 20); + if (rva <= 0x1583F0 && rva + size > 0x1583F0) { + int fileOffset = ptr + (0x1583F0 - rva); + Console.WriteLine("Bytes at GetWeenieObject: " + BitConverter.ToString(pe, fileOffset, 32)); + } + } + } +} diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index b982d4d..8d0ca13 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -1,38 +1,82 @@ #Requires -Version 5.1 <# .SYNOPSIS - Builds all RynthCore components and produces RynthCore-Setup.exe via Inno Setup. + Builds RynthCore + RynthSuite from source and produces the full installer + (RynthCore-Setup-<version>.exe) via Inno Setup. .DESCRIPTION + 0. Makes sure a .NET 10 SDK is available; installs one per-user when missing (see -NoDotNetInstall) 1. Publishes the Avalonia launcher (self-contained, x86) - 2+3. The engine and the loader. By default the unloadable engine - (docs/UNLOADABLE_ENGINE_PLAN.md): scripts\Publish-EngineCoreClr.ps1 stages the native - loader (native\Loader), RynthCore.Shim, the CoreCLR engine (ReadyToRun) and the - app-local .NET runtime (Runtime\dotnet) straight into staging\app\Runtime. - -NativeAot builds the old NativeAOT engine + loader instead. - 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86: the release plugins stay NativeAOT - - the CoreCLR engine loads them - until the update feed can carry a managed plugin's - dependency DLLs) - 5. Publishes the Loot Editor - 5b. The headless client (docs/HEADLESS.md, experimental): rynth-headless.exe, a self-contained - win-x64 publish of src\RynthCore.Headless.Cli, into {app}\Headless, and the 64-bit managed - RynthAi it runs into {app}\Headless\plugins\RynthAi (with its dependencies beside it). The - launcher loads those when its HeadlessPluginPaths list is empty. Nothing here touches the - x86 plugins in C:\Games\RynthSuite. - 6. Stages all output under installer\staging\app\, plus the hand-built - RynthCore.SehTrampoline.dll and the Decal bridge (DecalBridge\RynthCore.DecalBridge.dll, - built here against Decal's reference assemblies), and checks every required file is there - 7. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup.exe + 2+3. The engine and the loader (the DLL the launcher injects). By default the unloadable + engine (docs/UNLOADABLE_ENGINE_PLAN.md): scripts\Publish-EngineCoreClr.ps1 stages the + native loader (native\Loader), RynthCore.Shim, the CoreCLR engine (ReadyToRun) and the + app-local .NET runtime (Runtime\dotnet) into staging\core\Runtime; needs Visual Studio's + C++ tools. -NativeAot publishes the NativeAOT engine + loader instead (~2 min). + 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) from RynthSuite + 5. Publishes the Loot Editor (self-contained, x86) + 6. Publishes the Monster Editor (self-contained, x86) from RynthSuite + 7. Publishes the experimental plugins (RynthChat, RynthJuice, RynthNav, RynthTracker, + RynthVision, UbRythai; NativeAOT, x86) -- optional components in the installer + 8. Stages RynthCore under installer\staging\core\ and RynthSuite under + installer\staging\suite\, plus the hand-built RynthCore.SehTrampoline.dll and the + Decal bridge (staging\core\DecalBridge, built against Decal's reference assemblies when + Decal is installed), and checks every required runtime file is there + 9. Archives the previous installer (installer\previous-release\) when -Version changes + 10. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup-<version>.exe + (and a RynthCore-Setup.exe copy) + 11. With -Version: assembles the deployment package installer\Output\Release-<version>\ + (installer, SHA256SUMS.txt, release-manifest.json with commits + component versions, + RELEASE-NOTES.md built from both repos' Changelog folders) and zips it to + installer\Output\RynthCore-<version>-deploy.zip, then re-verifies the hashes. + Release builds refuse uncommitted changes (see -AllowDirty) so a package always maps + to exact commits. + + The installer lets the user choose both the RynthCore and the RynthSuite folders; the + code resolves them at runtime from HKA\Software\Rynth (see src\RynthCore.App\RynthInstallPaths.cs). .PARAMETER Configuration Build configuration. Default: Release .PARAMETER IsccPath - Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 location. + Path to ISCC.exe (Inno Setup compiler). Default looks in the standard Inno Setup 6 locations. Install Inno Setup from: https://jrsoftware.org/isdl.php +.PARAMETER RynthSuiteRoot + RynthSuite repo root. Default: the sibling ..\RynthSuite next to this RynthCore repo. + +.PARAMETER Version + Release version yyyy.m.d.n (e.g. 2026.10.4.2). Stamped into the launcher/engine/tools, + release.txt and the installer. Omit for a dev build. + .PARAMETER SkipBuild - Skip dotnet publish steps and just re-run ISCC against the existing staging directory. + Skip dotnet publish steps and just re-stage + re-run ISCC against existing publish output. + +.PARAMETER NoDotNetInstall + Fail instead of auto-installing when no .NET 10 SDK is found. By default a missing SDK is + installed per-user (no admin) to %LOCALAPPDATA%\Microsoft\dotnet via Microsoft's signed + dotnet-install.ps1, and used for this build. + +.PARAMETER AllowDirty + Build a -Version release even when RynthCore or RynthSuite has uncommitted changes to tracked + files. The package is still produced but its manifest and notes are flagged "dirty". + +.PARAMETER NoPackage + With -Version, stop after the installer .exe (skip the Release-<version> package and zip). + +.PARAMETER NativeAot + Build the NativeAOT engine + loader instead of the default unloadable CoreCLR engine. + +.PARAMETER SkipDecalBridge + Leave the Decal bridge out even when Decal is installed. + +.PARAMETER IncludeDecalBridge + Require the Decal bridge: a missing Decal install fails the build instead of skipping it. + +.PARAMETER DecalDir + Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. + +.EXAMPLE + .\Build-Installer.ps1 -Version 2026.10.4.7 #> param( [string]$Configuration = "Release", @@ -40,19 +84,25 @@ param( # Explicit path to the RynthSuite repo root. When omitted, defaults to the # sibling directory of RynthCore (i.e. ..\RynthSuite relative to this repo). [string]$RynthSuiteRoot = "", - # Version string injected into the installer (e.g. "0.3"). When omitted, + # Explicit path to the RynthServers repo root (rynth's server plugins: RynthILT and one per + # server). When omitted, defaults to the sibling directory ..\RynthServers. + [string]$RynthServersRoot = "", + # Version string injected into the installer (yyyy.m.d.n). When omitted, # the version defined in RynthCore.iss is used as-is. [string]$Version = "", [switch]$SkipBuild, + [switch]$NoDotNetInstall, + [switch]$AllowDirty, + [switch]$NoPackage, # The old NativeAOT engine + loader (a hot reload leaks every engine generation). [switch]$NativeAot, # The Decal bridge (src\RynthCore.DecalBridge, docs/DECAL_BRIDGE_PLAN.md) is staged into - # {app}\DecalBridge by default: every release ships it (experimental, opt-in per account; - # nothing registers it unless the player picks "Decal + RynthCore"). Building it needs - # Decal installed (its public reference assemblies); without Decal this script fails. - # -SkipDecalBridge leaves it out (dev builds on a machine without Decal; never a release). + # {app}\DecalBridge when Decal is installed (experimental, opt-in per account; nothing + # registers it unless the player picks "Decal + RynthCore"). Building it needs Decal's + # public reference assemblies; without Decal it is skipped with a warning. + # -SkipDecalBridge leaves it out even when Decal is present. [switch]$SkipDecalBridge, - # Old opt-in switch, kept so existing command lines still work; the bridge is the default now. + # Makes the bridge mandatory: no Decal means a failed build rather than a skipped bridge. [switch]$IncludeDecalBridge, # Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. [string]$DecalDir = "", @@ -80,11 +130,66 @@ if ($Version) { $release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3] } -# Stamp every build with the release, so the launcher, the engine log and the in-game -# Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit. +# Stamp the core builds and tools with the release, so the launcher, the engine log and the +# in-game Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit. +# The RynthAi plugin keeps its own semantic version (RynthCore.Plugin.RynthAi.csproj), so it +# is published WITHOUT these args. $VersionArgs = @() if ($Version) { $VersionArgs = @("-p:Version=$Version") } +# ── .NET 10 SDK check (auto-install when missing) ─────────────────────────── +# Every project targets net10.0, so publishing needs a .NET 10 SDK. Returns $true when the +# 'dotnet' on PATH lists a 10.x SDK. +function Test-DotNet10Sdk { + $cmd = Get-Command dotnet -ErrorAction SilentlyContinue + if (-not $cmd) { return $false } + $sdks = & $cmd.Source --list-sdks 2>$null + return [bool]($sdks | Where-Object { $_ -match '^10\.' }) +} + +# Makes a .NET 10 SDK available for this build: uses the one on PATH, else a previous per-user +# auto-install, else installs one per-user (no admin) with Microsoft's dotnet-install.ps1, whose +# Authenticode signature must verify as Microsoft before it is run. +function Initialize-DotNet10Sdk { + if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found ($((Get-Command dotnet).Source))"; return } + + $userDotNet = Join-Path $env:LOCALAPPDATA "Microsoft\dotnet" + if (Test-Path (Join-Path $userDotNet "dotnet.exe")) { + $env:DOTNET_ROOT = $userDotNet + $env:PATH = "$userDotNet;$env:PATH" + if (Test-DotNet10Sdk) { Write-Host ".NET 10 SDK: found per-user install ($userDotNet)"; return } + } + + if ($NoDotNetInstall) { + throw "No .NET 10 SDK found. Install it from https://dotnet.microsoft.com/download/dotnet/10.0 or re-run without -NoDotNetInstall." + } + + Write-Host "" + Write-Host ".NET 10 SDK not found -- installing it per-user to $userDotNet ..." -ForegroundColor Yellow + $installScript = Join-Path $env:TEMP "dotnet-install.ps1" + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + Invoke-WebRequest -Uri "https://dot.net/v1/dotnet-install.ps1" -OutFile $installScript -UseBasicParsing + $sig = Get-AuthenticodeSignature $installScript + if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notmatch 'O=Microsoft Corporation') { + Remove-Item $installScript -Force -ErrorAction SilentlyContinue + throw "dotnet-install.ps1 signature check failed ($($sig.Status)); not running it." + } + + # Separate process so the script runs under Bypass regardless of this session's execution policy. + & powershell -NoProfile -ExecutionPolicy Bypass -File $installScript -Channel 10.0 -InstallDir $userDotNet + $installExit = $LASTEXITCODE + Remove-Item $installScript -Force -ErrorAction SilentlyContinue + if ($installExit -ne 0) { throw "dotnet-install.ps1 failed (exit $installExit)" } + + $env:DOTNET_ROOT = $userDotNet + $env:PATH = "$userDotNet;$env:PATH" + if (-not (Test-DotNet10Sdk)) { throw ".NET 10 SDK install finished but 'dotnet --list-sdks' still shows no 10.x SDK." } + Write-Host ".NET 10 SDK: installed ($userDotNet)" -ForegroundColor Green +} + +# Only the publish steps need the SDK; -SkipBuild just re-stages and re-runs ISCC. +if (-not $SkipBuild) { Initialize-DotNet10Sdk } + $ScriptDir = $PSScriptRoot $RepoRoot = Split-Path $ScriptDir -Parent # e.g. C:\Projects\RynthCore $ProjectsRoot = Split-Path $RepoRoot -Parent # e.g. C:\Projects @@ -93,31 +198,95 @@ $ProjectsRoot = Split-Path $RepoRoot -Parent # e.g. C:\Projects if (-not $RynthSuiteRoot) { $RynthSuiteRoot = "$ProjectsRoot\RynthSuite" } +# RynthServers root (server plugins since 2026-10-21): explicit param, else the sibling convention. +if (-not $RynthServersRoot) { + $RynthServersRoot = "$ProjectsRoot\RynthServers" +} -$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" -$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" -$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj" -$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" -$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" -$HeadlessProject = "$RepoRoot\src\RynthCore.Headless.Cli\RynthCore.Headless.Cli.csproj" +# ── Source state (release builds) ─────────────────────────────────────────── +# A deployment package must map to exact commits. Tracked changes outside +# installer\previous-release\ (whose version marker this script rewrites) block a -Version +# build unless -AllowDirty; untracked files are ignored, as in Publish-Update.ps1. +function Get-RepoState([string]$Repo) { + $ErrorActionPreference = 'Continue' # native stderr must not become a terminating error on 5.1 + $dirty = @(git -C $Repo status --porcelain --untracked-files=no 2>$null | + Where-Object { $_ -and $_.Substring(3) -notlike 'installer/previous-release/*' }) + [ordered]@{ + path = $Repo + branch = (git -C $Repo rev-parse --abbrev-ref HEAD 2>$null) + commit = (git -C $Repo rev-parse HEAD 2>$null) + dirty = ($dirty.Count -gt 0) + changes = $dirty + } +} +$CoreState = Get-RepoState $RepoRoot +$SuiteState = Get-RepoState $RynthSuiteRoot +if ($Version -and -not $NoPackage) { + foreach ($s in $CoreState, $SuiteState) { + if (-not $s.commit) { throw "Not a git checkout: $($s.path) (a release package records exact commits)." } + if ($s.dirty -and -not $AllowDirty) { + throw "$($s.path) has uncommitted changes -- commit them or pass -AllowDirty:`n $($s.changes -join "`n ")" + } + } + Write-Host "Source: RynthCore $($CoreState.branch)@$($CoreState.commit.Substring(0,7)), RynthSuite $($SuiteState.branch)@$($SuiteState.commit.Substring(0,7))$(if ($CoreState.dirty -or $SuiteState.dirty) { ' (DIRTY)' })" +} -$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" -$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" -$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish" -$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" -$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish" -# The headless builds (x64) keep their intermediates in their own artifacts folders, apart from the -# x86 builds of the same projects (RynthCore.PluginSdk, RynthAi), and publish here (artifacts\ is ignored). -$HeadlessBuildRoot = "$RepoRoot\artifacts\headless" -$HeadlessPublish = "$HeadlessBuildRoot\rynth-headless" -$HeadlessPluginsPublish = "$HeadlessBuildRoot\plugins" -# The 64-bit plugins the headless client gets: <Name> -> project. Only RynthAi for now. -$HeadlessPlugins = [ordered]@{ RynthAi = $PluginProject } +$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" +$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" +$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj" +$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" +$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" +$MonsterEditorProject = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\RynthCore.MonsterEditor.csproj" -$StagingDir = "$ScriptDir\staging\app" +$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" +$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" +$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish" +$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" +$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish" +$MonsterEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.MonsterEditor\bin\$Configuration\net10.0\win-x86\publish" + +# Experimental RynthSuite plugins (optional installer components). Each installs to +# <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll. One with a <Version> in its csproj keeps that +# semantic version; the rest take the release calver (Test-OwnVersion). +$ExperimentalPlugins = @('RynthChat', 'RynthJuice', 'RynthNav', 'RynthTracker', 'RynthVision', 'UbRythai') +# Project folders that don't follow Plugins\RynthCore.Plugin.<Name>\ (ub-Rythai keeps its own sub-tree). +$ExperimentalProjectDirs = @{ 'UbRythai' = "$RynthSuiteRoot\Plugins\ub-Rythai\RynthCore.Plugin.UbRythai" } +function Get-ExperimentalDir([string]$Name) { + if ($ExperimentalProjectDirs.ContainsKey($Name)) { return $ExperimentalProjectDirs[$Name] } + # RynthILT and the per-server plugins live in RynthServers (rynth, 2026-10-21). + if ($Name -eq 'RynthILT' -or $ServerPlugins -contains $Name) { return "$RynthServersRoot\Plugins\RynthCore.Plugin.$Name" } + return "$RynthSuiteRoot\Plugins\RynthCore.Plugin.$Name" +} +function Get-ExperimentalProject([string]$Name) { "$(Get-ExperimentalDir $Name)\RynthCore.Plugin.$Name.csproj" } +# Only a plugin whose csproj sets its own <Version> (RynthJuice, UbRythai) keeps it; the others +# (RynthNav, RynthChat, RynthTracker, RynthVision) would read 1.0.0, so they get the release calver. +function Test-OwnVersion([string]$Name) { [bool](Select-String -Path (Get-ExperimentalProject $Name) -Pattern '<Version>' -Quiet) } +function Get-ExperimentalPublish([string]$Name) { "$(Get-ExperimentalDir $Name)\bin\$Configuration\net10.0-windows\win-x86\publish" } + +# RynthSuite companion plugins (installer components, on in a Full install). Same layout as the +# experimental ones: <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll, from Plugins\RynthCore.Plugin.<Name>\. +# They carry no <Version> of their own, so they get the release calver (-p:Version) like the engine. +# Server plugins (RynthServers): installed with the suite and registered with the launcher; RynthCore +# loads only the one for the server you connect to (PluginManifestGate), so each one's features show +# only on its own server. RynthILT is the Infinite Leaftide one. +$ServerPlugins = @('RynthAChard', 'RynthAelrynth', 'RynthColdeve', 'RynthConquest', 'RynthDerptide', 'RynthDreamWeave', 'RynthEversong', 'RynthFrostACE', 'RynthFrostcull', 'RynthLeafDawn', 'RynthLeafdawning', 'RynthLevistras', 'RynthPortalStorm', 'RynthReefcull', 'RynthSundering', 'RynthThistlecrown', 'RynthThreads') +$SuitePlugins = @('RynthOracle', 'RynthILT', 'RynthInventory', 'RynthSort') + $ServerPlugins +# RynthNav's starter portal list (shipped into <RynthCore>\NavData, never overwritten). +$NavPortalsTsv = "$RynthSuiteRoot\Tools\RynthNav.PortalGraph\Data\portals.tsv" + +# staging\core → {app} (user-chosen RynthCore folder) +# staging\suite → {code:GetSuiteDir} (user-chosen RynthSuite folder) +$StagingRoot = "$ScriptDir\staging" +$CoreStaging = "$StagingRoot\core" +$SuiteStaging = "$StagingRoot\suite" # ── Validate projects ─────────────────────────────────────────────────────── -foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject, $HeadlessProject) + @(if ($NativeAot) { $LoaderProject })) { +# The managed loader project is only built for -NativeAot; the default uses the native C loader. +$allProjects = @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject, $MonsterEditorProject) + + @(if ($NativeAot) { $LoaderProject }) + + @($ExperimentalPlugins | ForEach-Object { Get-ExperimentalProject $_ }) + + @($SuitePlugins | ForEach-Object { Get-ExperimentalProject $_ }) +foreach ($p in $allProjects) { if (-not (Test-Path $p)) { throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs." } @@ -126,54 +295,71 @@ foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorPr if (-not $SkipBuild) { # ── 1. Launcher (self-contained Avalonia WinExe) ───────────────────────── Write-Host "" - Write-Host "[1/5] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan + Write-Host "[1/7] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" } if ($NativeAot) { # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────── Write-Host "" - Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan + Write-Host "[2/7] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan dotnet publish $EngineProject -c $Configuration @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } # ── 3. Loader (NativeAOT, small) ────────────────────────────────────── Write-Host "" - Write-Host "[3/5] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan + Write-Host "[3/7] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan dotnet publish $LoaderProject -c $Configuration @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } } # (Default: the CoreCLR engine and native loader are built straight into staging below.) - # ── 4. Plugin (NativeAOT; a managed RynthAi from Publish-Update replaces it) ── + # ── 4. RynthAi plugin (NativeAOT; keeps its own version; a managed RynthAi from Publish-Update replaces it) ── if (-not $RynthAiDll) { Write-Host "" - Write-Host "[4/5] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan + Write-Host "[4/7] Publishing RynthAi plugin (NativeAOT)..." -ForegroundColor Cyan + # Its plugin version is RynthAiVersionCommand.HandWrittenVersion; the DLL's ProductVersion + # takes the release calver so an installed file never reads 1.0.0. dotnet publish $PluginProject -c $Configuration @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" } } # ── 5. Loot Editor (self-contained Avalonia tool) ───────────────────────── Write-Host "" - Write-Host "[5/5] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan + Write-Host "[5/7] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan dotnet publish $LootEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Loot Editor publish failed (exit $LASTEXITCODE)" } - # ── 5b. Headless client (self-contained x64) + its 64-bit plugins ───────── - # rynth-headless is a 64-bit process with its own .NET runtime (Runtime\dotnet is x86). The - # plugins it hosts are managed x64 builds of the release plugins, made with command-line - # overrides only (docs/HEADLESS.md, "Running RynthAi"); each gets its dependencies beside it. + # ── 6. Monster Editor (self-contained Avalonia tool) ────────────────────── Write-Host "" - Write-Host "[5b/5] Publishing the headless client (self-contained, x64) and its x64 plugins..." -ForegroundColor Cyan - if (Test-Path $HeadlessBuildRoot) { Remove-Item $HeadlessBuildRoot -Recurse -Force } - dotnet publish $HeadlessProject -c $Configuration -r win-x64 --self-contained true ` - --artifacts-path "$HeadlessBuildRoot\art-cli" -o $HeadlessPublish -nologo -v q @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Headless client publish failed (exit $LASTEXITCODE)" } - foreach ($name in $HeadlessPlugins.Keys) { - dotnet publish $HeadlessPlugins[$name] -c $Configuration "-p:PublishAot=false" "-p:NativeLib=" "-p:SelfContained=false" ` - "-p:PlatformTarget=x64" "-p:RuntimeIdentifier=win-x64" "-p:Platforms=x64" "-p:GenerateRuntimeConfigurationFiles=false" ` - "-p:RynthPluginSharedSdk=true" --artifacts-path "$HeadlessBuildRoot\art-$name" -o "$HeadlessPluginsPublish\$name" -nologo -v q @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Headless (x64) $name publish failed (exit $LASTEXITCODE)" } + Write-Host "[6/7] Publishing Monster Editor (self-contained, x86)..." -ForegroundColor Cyan + dotnet publish $MonsterEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Monster Editor publish failed (exit $LASTEXITCODE)" } + + # ── 7. Experimental plugins (NativeAOT; optional components) ────────────── + # RynthJuice/RynthNav/RynthVision set <PublishDir> to the live C:\Games\RynthSuite\<Name>\ + # folder for dev hot-reload; override it so an installer build never touches a live install. + # A trailing '/' (not '\') keeps the argument intact when the path contains spaces. + Write-Host "" + Write-Host "[7/7] Publishing experimental plugins (NativeAOT)..." -ForegroundColor Cyan + foreach ($name in $ExperimentalPlugins) { + $ownVersion = Test-OwnVersion $name + Write-Host " $name$(if ($ownVersion) { ' (own version)' } else { '' })" + $publishDir = (Get-ExperimentalPublish $name) + '/' + # @(...) keeps it an array: a bare if/else unrolls one item to a string, which splats char by char. + $pluginVersionArgs = @(if (-not $ownVersion) { $VersionArgs }) + dotnet publish (Get-ExperimentalProject $name) -c $Configuration "-p:PublishDir=$publishDir" @pluginVersionArgs + if ($LASTEXITCODE -ne 0) { throw "$name publish failed (exit $LASTEXITCODE)" } + } + + # ── 7b. RynthSuite companion plugins (NativeAOT; release calver) ────────── + Write-Host "" + Write-Host "[7b/7] Publishing RynthSuite plugins (NativeAOT)..." -ForegroundColor Cyan + foreach ($name in $SuitePlugins) { + Write-Host " $name" + $publishDir = (Get-ExperimentalPublish $name) + '/' + dotnet publish (Get-ExperimentalProject $name) -c $Configuration "-p:PublishDir=$publishDir" @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "$name publish failed (exit $LASTEXITCODE)" } } } @@ -181,32 +367,38 @@ if (-not $SkipBuild) { Write-Host "" Write-Host "Staging files..." -ForegroundColor Cyan -if (Test-Path "$ScriptDir\staging") { - Remove-Item "$ScriptDir\staging" -Recurse -Force +if (Test-Path $StagingRoot) { + Remove-Item $StagingRoot -Recurse -Force +} +New-Item -ItemType Directory -Path "$CoreStaging\Runtime\Native" -Force | Out-Null +New-Item -ItemType Directory -Path "$CoreStaging\Tools\LootEditor" -Force | Out-Null +New-Item -ItemType Directory -Path "$SuiteStaging\RynthAi\MonsterEditor" -Force | Out-Null + +# Copies a publish folder (files + subfolders) without .pdb files. +function Copy-PublishTree([string]$Source, [string]$Dest) { + if (-not (Test-Path $Source)) { throw "Publish output not found: $Source" } + foreach ($file in (Get-ChildItem $Source -File)) { + if ($file.Extension -eq '.pdb') { continue } + Copy-Item $file.FullName (Join-Path $Dest $file.Name) -Force + } + foreach ($dir in (Get-ChildItem $Source -Directory)) { + Copy-Item $dir.FullName $Dest -Recurse -Force + Get-ChildItem (Join-Path $Dest $dir.Name) -Recurse -File -Filter '*.pdb' | Remove-Item -Force + } } -New-Item -ItemType Directory -Path "$StagingDir\Runtime\Native" -Force | Out-Null -New-Item -ItemType Directory -Path "$StagingDir\Tools\LootEditor" -Force | Out-Null -# Plugin DLLs are staged into a separate top-level folder (not under -# Runtime\) because the engine no longer auto-scans Runtime\Plugins\. -# The .iss file installs this folder to C:\Games\RynthSuite\<PluginName>\ -# (an absolute destination outside {app}) so the plugin lives next to its -# data dirs and the user adds the path via the launcher's Plugins tab. -$pluginStagingDir = "$ScriptDir\staging\plugins" -if (Test-Path $pluginStagingDir) { Remove-Item $pluginStagingDir -Recurse -Force } -New-Item -ItemType Directory -Path "$pluginStagingDir\RynthAi" -Force | Out-Null # Launcher root files (rename .exe → RynthCore.exe; drop .pdb) foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) { if ($file.Extension -eq '.pdb') { continue } $destName = if ($file.Name -eq 'RynthCore.App.Avalonia.exe') { 'RynthCore.exe' } else { $file.Name } - Copy-Item $file.FullName "$StagingDir\$destName" -Force + Copy-Item $file.FullName "$CoreStaging\$destName" -Force } if ($NativeAot) { # Engine runtime files (into Runtime\, skip .pdb) foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force + Copy-Item $file.FullName "$CoreStaging\Runtime\$($file.Name)" -Force } # Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it @@ -214,17 +406,17 @@ if ($NativeAot) { # launcher can't auto-find an engine to inject. $loaderDll = "$LoaderPublish\RynthCore.Loader.dll" if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } - Copy-Item $loaderDll "$StagingDir\Runtime\" -Force + Copy-Item $loaderDll "$CoreStaging\Runtime\" -Force } else { # The unloadable engine: native loader (same RynthCoreInit contract with the launcher's # injector), RynthCore.Shim, the CoreCLR engine (ReadyToRun) + its dependencies, and # Runtime\dotnet (the app-local x86 .NET runtime). Needs Visual Studio's C++ tools (cl.exe) # for the loader, like the SEH trampoline. Write-Host "" - Write-Host "[2+3/5] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan - & "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$StagingDir\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs + Write-Host "[2+3/7] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan + & "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$CoreStaging\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs # Keep the engine's pdb (its stack traces get line numbers); drop the loader's and shim's. - Remove-Item "$StagingDir\Runtime\RynthCore.Loader.pdb", "$StagingDir\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue + Remove-Item "$CoreStaging\Runtime\RynthCore.Loader.pdb", "$CoreStaging\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue } # SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1), @@ -235,82 +427,113 @@ if ($NativeAot) { $sehDll = "$RepoRoot\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" $sehSrc = "$RepoRoot\native\SehTrampoline\SehTrampoline.c" if (-not (Test-Path $sehDll)) { throw "SEH trampoline not found at: $sehDll`nBuild it with native\SehTrampoline\Build-SehTrampoline.ps1" } -if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $sehDll).LastWriteTime) { +# Source "age": checkouts and merges rewrite SehTrampoline.c and bump its mtime without changing it, +# so when the file matches HEAD its last commit time is used; local edits fall back to the mtime. +function Get-SehSourceTime { + $ErrorActionPreference = 'Continue' + $srcTime = (Get-Item $sehSrc).LastWriteTime + git -C $RepoRoot diff --quiet HEAD -- "native/SehTrampoline/SehTrampoline.c" 2>$null + if ($LASTEXITCODE -eq 0) { + $ct = git -C $RepoRoot log -1 --format=%ct -- "native/SehTrampoline/SehTrampoline.c" 2>$null + if ($ct -match '^\d+$') { $srcTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$ct).LocalDateTime } + } + $srcTime +} +if ((Test-Path $sehSrc) -and (Get-SehSourceTime) -gt (Get-Item $sehDll).LastWriteTime) { throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c is newer). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1" } -Copy-Item $sehDll "$StagingDir\Runtime\" -Force +Copy-Item $sehDll "$CoreStaging\Runtime\" -Force + +# DXVK x32 cache (optional launcher "Enable DXVK"): seed Runtime\dxvk so a fresh +# install can toggle without GitHub. Prefer a local drop-in stage, else fetch latest. +$dxvkDest = "$CoreStaging\Runtime\dxvk" +$dxvkBuild = "C:\Games\RynthCore\build\dxvk-dropin\extract" +Write-Host "Seeding Runtime\dxvk (x32 d3d9 for launcher Enable DXVK)..." -ForegroundColor Cyan +New-Item -ItemType Directory -Force -Path $dxvkDest | Out-Null +$seeded = $false +if (Test-Path "$dxvkBuild") { + $localDll = Get-ChildItem $dxvkBuild -Recurse -Filter "d3d9.dll" -ErrorAction SilentlyContinue | + Where-Object { $_.Directory.Name -eq "x32" } | Select-Object -First 1 + if ($localDll) { + $verFile = Join-Path $localDll.Directory.Parent.FullName ".." # unused; read from folder name + $folderVer = if ($localDll.Directory.Parent.Name -match 'dxvk-(\d+\.\d+\.\d+)') { $Matches[1] } else { "local" } + Copy-Item $localDll.FullName "$dxvkDest\d3d9.dll" -Force + $utf8 = New-Object System.Text.UTF8Encoding $false + [IO.File]::WriteAllText("$dxvkDest\version.txt", $folderVer, $utf8) + $seeded = $true + Write-Host " Seeded from build drop-in ($folderVer)." + } +} +if (-not $seeded -and (Test-Path "C:\Games\RynthCore\Runtime\dxvk\d3d9.dll")) { + Copy-Item "C:\Games\RynthCore\Runtime\dxvk\*" $dxvkDest -Force + $seeded = $true + Write-Host " Seeded from live Runtime\dxvk." +} +if (-not $seeded) { + try { + & "$RepoRoot\scripts\Fetch-Dxvk.ps1" -Target $dxvkDest + $seeded = $true + } + catch { + Write-Warning "DXVK seed skipped (fetch failed): $($_.Exception.Message). Launcher can still Fetch at runtime." + } +} # Engine Native subfolder (NativeAOT layout) if ($NativeAot -and (Test-Path "$EnginePublish\Native")) { foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) { if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$StagingDir\Runtime\Native\$($file.Name)" -Force + Copy-Item $file.FullName "$CoreStaging\Runtime\Native\$($file.Name)" -Force } } -# Plugin DLL only — staged separately so the .iss file can install it to an -# absolute path outside {app}. The engine no longer auto-scans Runtime\Plugins\; -# the user explicitly adds the plugin path via the launcher's Plugins tab. +# Loot Editor → <RynthCore>\Tools\LootEditor (the launcher/engine look for it there) +Copy-PublishTree $LootEditorPublish "$CoreStaging\Tools\LootEditor" + +# RynthAi plugin DLL → <RynthSuite>\RynthAi (next to its data dirs; the installer hands the +# path to the launcher via HKA\Software\Rynth\PendingPluginRegistration). $pluginDll = if ($RynthAiDll) { $RynthAiDll } else { "$PluginPublish\RynthCore.Plugin.RynthAi.dll" } if (-not (Test-Path $pluginDll)) { throw "Plugin DLL not found at: $pluginDll" } -Copy-Item $pluginDll "$pluginStagingDir\RynthAi\" -Force +Copy-Item $pluginDll "$SuiteStaging\RynthAi\" -Force # The managed plugins' common dependencies (engine API 88: ManagedPlugins looks in Runtime\PluginShared). if ($PluginSharedDir) { if (-not (Test-Path $PluginSharedDir)) { throw "PluginShared folder not found at: $PluginSharedDir" } - New-Item -ItemType Directory -Path "$StagingDir\Runtime\PluginShared" -Force | Out-Null - Copy-Item "$PluginSharedDir\*" "$StagingDir\Runtime\PluginShared\" -Force - Write-Host " Runtime\PluginShared: $((Get-ChildItem "$StagingDir\Runtime\PluginShared" -File).Count) file(s)" + New-Item -ItemType Directory -Path "$CoreStaging\Runtime\PluginShared" -Force | Out-Null + Copy-Item "$PluginSharedDir\*" "$CoreStaging\Runtime\PluginShared\" -Force + Write-Host " Runtime\PluginShared: $((Get-ChildItem "$CoreStaging\Runtime\PluginShared" -File).Count) file(s)" } -# Loot Editor (self-contained — copy everything from publish, drop pdbs) -if (-not (Test-Path $LootEditorPublish)) { throw "Loot Editor publish not found at: $LootEditorPublish" } -foreach ($file in (Get-ChildItem "$LootEditorPublish" -File)) { - if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$StagingDir\Tools\LootEditor\$($file.Name)" -Force -} -foreach ($dir in (Get-ChildItem "$LootEditorPublish" -Directory)) { - Copy-Item $dir.FullName "$StagingDir\Tools\LootEditor\" -Recurse -Force - # Drop pdbs from copied subdirs - Get-ChildItem "$StagingDir\Tools\LootEditor\$($dir.Name)" -Recurse -File -Filter '*.pdb' | Remove-Item -Force +# Monster Editor → <RynthSuite>\RynthAi\MonsterEditor (RynthAi's dashboard launches it from there) +Copy-PublishTree $MonsterEditorPublish "$SuiteStaging\RynthAi\MonsterEditor" + +# Experimental plugins → <RynthSuite>\<Name>\RynthCore.Plugin.<Name>.dll (the NativeAOT DLL is self-contained; +# cimgui.dll is provided by the engine's Runtime folder). +foreach ($name in @($ExperimentalPlugins) + @($SuitePlugins)) { + $dll = Join-Path (Get-ExperimentalPublish $name) "RynthCore.Plugin.$name.dll" + if (-not (Test-Path $dll)) { throw "$name DLL not found at: $dll" } + New-Item -ItemType Directory -Path "$SuiteStaging\$name" -Force | Out-Null + Copy-Item $dll "$SuiteStaging\$name\" -Force } -# Headless client (experimental, docs/HEADLESS.md): {app}\Headless\rynth-headless.exe with its own -# x64 runtime, and {app}\Headless\plugins\<Name>\ (RynthCore.Plugin.<Name>.dll and its dependencies), -# which the launcher's HeadlessLaunch.DefaultPluginPaths finds. The publish folders are copied whole -# (the plugins' Data\ subfolders too); pdbs stay, for line numbers in the headless logs. -if (-not (Test-Path "$HeadlessPublish\rynth-headless.exe")) { throw "Headless client publish not found at: $HeadlessPublish" } -New-Item -ItemType Directory -Path "$StagingDir\Headless\plugins" -Force | Out-Null -Copy-Item "$HeadlessPublish\*" "$StagingDir\Headless\" -Recurse -Force -foreach ($name in $HeadlessPlugins.Keys) { - $src = "$HeadlessPluginsPublish\$name" - if (-not (Test-Path "$src\RynthCore.Plugin.$name.dll")) { throw "Headless (x64) $name publish not found at: $src" } - Copy-Item $src "$StagingDir\Headless\plugins\" -Recurse -Force -} -# The plugin builds must really be 64-bit: an x86 one (wrong overrides, a stale publish) fails to load -# in rynth-headless with BadImageFormatException, only once a player launches. -# The PE header's machine field: an IL assembly built for x64 says AMD64 (0x8664); x86 and AnyCPU say I386 (0x14C). -function Get-PeMachine([string]$path) { - $b = [System.IO.File]::ReadAllBytes($path) - return [BitConverter]::ToUInt16($b, [BitConverter]::ToInt32($b, 0x3C) + 4) -} -foreach ($name in $HeadlessPlugins.Keys) { - $machine = Get-PeMachine "$StagingDir\Headless\plugins\$name\RynthCore.Plugin.$name.dll" - if ($machine -ne 0x8664) { throw ("Headless plugin {0} is not an x64 build (PE machine 0x{1:X})" -f $name, $machine) } -} -if ((Get-PeMachine "$StagingDir\Headless\rynth-headless.exe") -ne 0x8664) { throw "rynth-headless.exe is not an x64 build" } -# The players' guide to Headless mode, beside the exe. -Copy-Item "$ScriptDir\HEADLESS-README.md" "$StagingDir\Headless\README.md" -Force -$headlessMb = [math]::Round((Get-ChildItem "$StagingDir\Headless" -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) -Write-Host " Headless: $((Get-ChildItem "$StagingDir\Headless" -Recurse -File).Count) file(s), ${headlessMb} MB (plugins: $($HeadlessPlugins.Keys -join ', '))" +# RynthNav starter data → <RynthCore>\NavData (staged apart from core so it is only installed with RynthNav). +if (-not (Test-Path $NavPortalsTsv)) { throw "RynthNav portals.tsv not found at: $NavPortalsTsv" } +New-Item -ItemType Directory -Path "$StagingRoot\navdata" -Force | Out-Null +Copy-Item $NavPortalsTsv "$StagingRoot\navdata\" -Force # Decal bridge (docs/DECAL_BRIDGE_PLAN.md, experimental): the net48 x86 Decal network filter # goes to {app}\DecalBridge\, the folder the launcher registers for "Decal + RynthCore" # accounts (and only for those). Built against Decal's public reference assemblies, so the # build machine needs Decal; -p:RequireDecal=true turns "no Decal" into a build error rather # than the empty assembly a plain solution build makes. Never ships any Decal file. +# Same probe as the bridge csproj (DecalAvailable): Decal.Adapter.dll in the Decal folder. +$decalProbeDir = if ($DecalDir) { $DecalDir } else { "${env:ProgramFiles(x86)}\Decal 3.0" } +$decalInstalled = Test-Path (Join-Path $decalProbeDir "Decal.Adapter.dll") +$buildDecalBridge = -not $SkipDecalBridge -and ($decalInstalled -or $IncludeDecalBridge) if ($SkipDecalBridge) { - Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. Not for a release." + Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it." +} elseif (-not $buildDecalBridge) { + Write-Warning "Decal not found in '$decalProbeDir': this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. (-DecalDir for another folder, -IncludeDecalBridge to make this an error.)" } else { Write-Host "" Write-Host "Building the Decal bridge (net48 x86, against Decal's reference assemblies)..." -ForegroundColor Cyan @@ -322,22 +545,22 @@ if ($SkipDecalBridge) { Remove-Item $bridgeDll -Force -ErrorAction SilentlyContinue if (Test-Path $bridgeDll) { throw "Could not remove the old $bridgeDll (in use by a Decal client?)" } dotnet build $bridgeProject -c $Configuration -nologo -v q @decalArgs @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge for a dev build)" } + if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge to leave it out)" } if (-not (Test-Path $bridgeDll)) { throw "Decal bridge not built at $bridgeDll" } # The real bridge has its filter type; the no-Decal build is an empty assembly. $bridgeBytes = [System.IO.File]::ReadAllBytes($bridgeDll) if ([System.Text.Encoding]::ASCII.GetString($bridgeBytes).IndexOf("BridgeFilter") -lt 0) { throw "$bridgeDll has no BridgeFilter type - it was built without Decal's reference assemblies." } - New-Item -ItemType Directory -Path "$StagingDir\DecalBridge" -Force | Out-Null - Copy-Item $bridgeDll "$StagingDir\DecalBridge\" -Force - $staleDecal = @(Get-ChildItem "$StagingDir\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" }) + New-Item -ItemType Directory -Path "$CoreStaging\DecalBridge" -Force | Out-Null + Copy-Item $bridgeDll "$CoreStaging\DecalBridge\" -Force + $staleDecal = @(Get-ChildItem "$CoreStaging\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" }) if ($staleDecal.Count -gt 0) { throw "Unexpected files in the staged DecalBridge folder: $($staleDecal.Name -join ', ')" } Write-Host " RynthCore.DecalBridge.dll $((Get-Item $bridgeDll).VersionInfo.FileVersion)" } # release.txt — which core release this install is ($release, from -Version at the top). -Set-Content -Path "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII +Set-Content -Path "$CoreStaging\release.txt" -Value @($release, $Version) -Encoding ASCII # The PE machine field of a DLL (e_lfanew at 0x3C, then the COFF Machine at PE offset + 4). The game is # 32-bit, so the web panel's native loader must be the x86 one (0x14C): the NuGet package also carries @@ -353,46 +576,86 @@ function Assert-PeMachine([string]$Path, [int]$Expected) { # Everything a working install needs. The 2026-09-25 public installer went out # without the Loader and the SEH trampoline because nothing checked. $required = @( - "$StagingDir\RynthCore.exe", - "$StagingDir\Runtime\RynthCore.Loader.dll", - "$StagingDir\Runtime\RynthCore.Engine.dll", - "$StagingDir\Runtime\RynthCore.SehTrampoline.dll", - "$StagingDir\Runtime\minhook.x86.dll", - "$StagingDir\Runtime\cimgui.dll", - "$pluginStagingDir\RynthAi\RynthCore.Plugin.RynthAi.dll", - "$StagingDir\Headless\rynth-headless.exe", - "$StagingDir\Headless\rynth-headless.dll", - "$StagingDir\Headless\coreclr.dll", - "$StagingDir\Headless\RynthCore.Headless.dll" -) -foreach ($name in $HeadlessPlugins.Keys) { $required += "$StagingDir\Headless\plugins\$name\RynthCore.Plugin.$name.dll" } + "$CoreStaging\RynthCore.exe", + "$CoreStaging\RynthCore.App.Avalonia.dll", + "$CoreStaging\RynthCore.App.Avalonia.deps.json", + "$CoreStaging\RynthCore.App.Avalonia.runtimeconfig.json", + "$CoreStaging\Runtime\RynthCore.Loader.dll", + "$CoreStaging\Runtime\RynthCore.Engine.dll", + "$CoreStaging\Runtime\RynthCore.SehTrampoline.dll", + "$CoreStaging\Runtime\minhook.x86.dll", + "$CoreStaging\Runtime\cimgui.dll", + "$CoreStaging\Tools\LootEditor\RynthCore.LootEditor.exe", + "$SuiteStaging\RynthAi\RynthCore.Plugin.RynthAi.dll", + "$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe", + "$StagingRoot\navdata\portals.tsv" +) + @(@($ExperimentalPlugins) + @($SuitePlugins) | ForEach-Object { "$SuiteStaging\$_\RynthCore.Plugin.$_.dll" }) +# The unloadable engine also needs its shim and the app-local CoreCLR runtime. if (-not $NativeAot) { $required += @( - "$StagingDir\Runtime\RynthCore.Shim.dll", - "$StagingDir\Runtime\dotnet\coreclr.dll", - "$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll", - "$StagingDir\Runtime\Microsoft.Web.WebView2.Core.dll", - "$StagingDir\Runtime\WebView2Loader.dll" + "$CoreStaging\Runtime\RynthCore.Shim.dll", + "$CoreStaging\Runtime\dotnet\coreclr.dll", + "$CoreStaging\Runtime\dotnet\System.Private.CoreLib.dll", + "$CoreStaging\Runtime\Microsoft.Web.WebView2.Core.dll", + "$CoreStaging\Runtime\WebView2Loader.dll" ) } -if (-not $SkipDecalBridge) { - $required += "$StagingDir\DecalBridge\RynthCore.DecalBridge.dll" +if ($buildDecalBridge) { + $required += "$CoreStaging\DecalBridge\RynthCore.DecalBridge.dll" } $missing = @($required | Where-Object { -not (Test-Path $_) }) if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" } if (-not $NativeAot) { - Assert-PeMachine "$StagingDir\Runtime\WebView2Loader.dll" 0x14C + Assert-PeMachine "$CoreStaging\Runtime\WebView2Loader.dll" 0x14C } + +# Every assembly the launcher's deps.json lists must be staged next to it — a launcher DLL whose +# deps.json doesn't match is exactly the "Could not load RynthCore.DesktopLog" failure of 2026-10-04. +$depsJson = Get-Content "$CoreStaging\RynthCore.App.Avalonia.deps.json" -Raw | ConvertFrom-Json +$projectLibs = $depsJson.libraries.PSObject.Properties | Where-Object { $_.Value.type -eq 'project' } | ForEach-Object { ($_.Name -split '/')[0] } +$missingLibs = @($projectLibs | Where-Object { -not (Test-Path "$CoreStaging\$_.dll") }) +if ($missingLibs.Count -gt 0) { throw "Launcher deps.json references project assemblies that were not staged:`n $($missingLibs -join "`n ")" } + # Report staged sizes -$engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll" +$engineDll = "$CoreStaging\Runtime\RynthCore.Engine.dll" if (Test-Path $engineDll) { $sizeMb = [math]::Round((Get-Item $engineDll).Length / 1MB, 1) Write-Host " Engine.dll: ${sizeMb} MB" } -$totalMb = [math]::Round((Get-ChildItem "$StagingDir" -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) -Write-Host " Total staged: ${totalMb} MB" +$coreMb = [math]::Round((Get-ChildItem $CoreStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) +$suiteMb = [math]::Round((Get-ChildItem $SuiteStaging -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1) +Write-Host " Staged: RynthCore ${coreMb} MB, RynthSuite ${suiteMb} MB" -Write-Host "Staging complete: $StagingDir" -ForegroundColor Green +Write-Host "Staging complete: $StagingRoot" -ForegroundColor Green + +# ── Archive the previous installer when -Version bumps ───────────────────── +# installer\previous-release\last-built-version.txt records the last version built; when a new +# -Version is built, that version's installer is copied to previous-release\ first. +# Inno stamps AppVersion as the setup exe's ProductVersion, padded with spaces/NULs. +function Get-InstallerVersion([string]$Exe) { "$((Get-Item $Exe).VersionInfo.ProductVersion)".Trim([char[]]" `0") } + +$previousReleaseDir = Join-Path $ScriptDir "previous-release" +$lastVersionFile = Join-Path $previousReleaseDir "last-built-version.txt" +if ($Version) { + New-Item -ItemType Directory -Path $previousReleaseDir -Force | Out-Null + $lastVer = if (Test-Path $lastVersionFile) { (Get-Content $lastVersionFile -Raw).Trim() } else { "" } + if ($lastVer -and $lastVer -ne $Version) { + $prevExe = Join-Path $ScriptDir "Output\RynthCore-Setup-$lastVer.exe" + if (-not (Test-Path $prevExe)) { + # The canonical copy may be an older build (e.g. the previous version was built in + # another checkout); only archive it when its stamped ProductVersion really is $lastVer. + $canonical = Join-Path $ScriptDir "Output\RynthCore-Setup.exe" + $prevExe = $null + if ((Test-Path $canonical) -and ((Get-InstallerVersion $canonical) -eq $lastVer)) { $prevExe = $canonical } + elseif (Test-Path $canonical) { Write-Warning "Previous installer $lastVer not found in Output\ (RynthCore-Setup.exe is $(Get-InstallerVersion $canonical)); nothing archived." } + } + if ($prevExe -and (Test-Path $prevExe)) { + $archive = Join-Path $previousReleaseDir "RynthCore-Setup-$lastVer.exe" + Write-Host "Archiving previous installer ($lastVer) -> $archive" -ForegroundColor Cyan + Copy-Item $prevExe $archive -Force + } + } +} # No file we ship may carry the ReadOnly attribute (a read-only source - a git checkout on a # read-only share, a file copied off an ISO - would otherwise land read-only on the player's PC, @@ -429,8 +692,13 @@ $issSource = "$ScriptDir\RynthCore.iss" # Source, staging\) still resolve from the installer\ directory. $issTmp = "$ScriptDir\RynthCore.tmp.iss" $issContent = Get-Content $issSource -Raw +$outputName = "RynthCore-Setup" if ($Version) { + # Versioned .exe avoids Inno error 32 when Output\RynthCore-Setup.exe is open in Explorer or AV. + $outputName = "RynthCore-Setup-$Version" $issContent = $issContent -replace 'AppVersion=0\.0\.0', "AppVersion=$Version" + $issContent = $issContent -replace 'AppVerName=RynthCore \+ RynthSuite 0\.0\.0', "AppVerName=RynthCore + RynthSuite $Version" + $issContent = $issContent -replace 'OutputBaseFilename=RynthCore-Setup', "OutputBaseFilename=$outputName" Write-Host " Version override: $Version" } Set-Content -Path $issTmp -Value $issContent -Encoding UTF8 @@ -442,6 +710,203 @@ try { Remove-Item $issTmp -Force -ErrorAction SilentlyContinue } +$builtInstaller = "$ScriptDir\Output\$outputName.exe" +if ($Version) { + # Canonical name for the launcher updater / docs; best effort if the file is locked. + try { Copy-Item $builtInstaller "$ScriptDir\Output\RynthCore-Setup.exe" -Force } + catch { Write-Warning "Could not refresh Output\RynthCore-Setup.exe (in use?). Primary artifact: $builtInstaller" } +} + +# ── Deployment package (-Version builds) ──────────────────────────────────── +# installer\Output\Release-<version>\ holds everything a deployment needs, and +# RynthCore-<version>-deploy.zip is that folder zipped: +# RynthCore-Setup-<version>.exe the installer +# release-manifest.json version, commits, component versions, installer hash +# RELEASE-NOTES.md install steps + Changelog entries since the previous release +# SHA256SUMS.txt hashes of the three files above (sha256sum format) +# previous-release\last-release-manifest.json keeps the manifest so the next build can list only +# the Changelog files added or changed since this release's commits. + +# UTF-8 without BOM (Windows PowerShell's Set-Content -Encoding UTF8 writes a BOM). +function Write-Utf8([string]$Path, [string]$Text) { + [IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.UTF8Encoding($false))) +} +function Get-Sha256([string]$Path) { (Get-FileHash $Path -Algorithm SHA256).Hash.ToLowerInvariant() } + +# Changelog\*.md files added/modified in $Repo since $SinceCommit (when that commit exists), +# else since $SinceDate (yyyy-mm-dd). Returns repo-relative paths that still exist. +function Get-ChangelogFiles([string]$Repo, [string]$SinceCommit, [string]$SinceDate) { + $ErrorActionPreference = 'Continue' # git writes "fatal:" to stderr for unknown commits + $names = @() + $known = $false + if ($SinceCommit) { + git -C $Repo cat-file -e "$SinceCommit^{commit}" 2>$null + $known = ($LASTEXITCODE -eq 0) + } + if ($known) { + $names = @(git -C $Repo diff --name-only --diff-filter=AM $SinceCommit HEAD -- Changelog 2>$null) + } elseif ($SinceDate) { + $names = @(git -C $Repo log "--since=$SinceDate 00:00" --name-only --diff-filter=AM --format= -- Changelog 2>$null) + } + @($names | Where-Object { $_ -like '*.md' -and (Test-Path (Join-Path $Repo $_)) } | Sort-Object -Unique) +} + +if ($Version -and -not $NoPackage) { + Write-Host "" + Write-Host "Assembling deployment package..." -ForegroundColor Cyan + + # The installer must carry this release's version (Inno stamps AppVersion as ProductVersion). + $stamped = Get-InstallerVersion $builtInstaller + if ($stamped -ne $Version) { throw "Installer ProductVersion is '$stamped', expected '$Version'." } + + $pkgName = "Release-$Version" + $pkgDir = Join-Path $ScriptDir "Output\$pkgName" + $zipPath = Join-Path $ScriptDir "Output\RynthCore-$Version-deploy.zip" + if (Test-Path $pkgDir) { Remove-Item $pkgDir -Recurse -Force } + if (Test-Path $zipPath) { Remove-Item $zipPath -Force } + New-Item -ItemType Directory -Path $pkgDir -Force | Out-Null + + $setupName = "RynthCore-Setup-$Version.exe" + Copy-Item $builtInstaller (Join-Path $pkgDir $setupName) -Force + $setupHash = Get-Sha256 (Join-Path $pkgDir $setupName) + + # Versions of what the installer ships, read from the staged files' version resources. + $componentFiles = [ordered]@{ + 'Launcher (RynthCore.exe)' = "$CoreStaging\RynthCore.exe" + 'Engine' = "$CoreStaging\Runtime\RynthCore.Engine.dll" + 'Loader' = "$CoreStaging\Runtime\RynthCore.Loader.dll" + 'Loot Editor' = "$CoreStaging\Tools\LootEditor\RynthCore.LootEditor.exe" + 'RynthAi plugin' = "$SuiteStaging\RynthAi\RynthCore.Plugin.RynthAi.dll" + 'Monster Editor' = "$SuiteStaging\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe" + } + foreach ($name in $SuitePlugins) { $componentFiles["$name plugin"] = "$SuiteStaging\$name\RynthCore.Plugin.$name.dll" } + foreach ($name in $ExperimentalPlugins) { $componentFiles["$name (experimental)"] = "$SuiteStaging\$name\RynthCore.Plugin.$name.dll" } + $components = foreach ($kv in $componentFiles.GetEnumerator()) { + $vi = (Get-Item $kv.Value).VersionInfo + $ver = if ($vi.ProductVersion) { $vi.ProductVersion } else { $vi.FileVersion } + [ordered]@{ name = $kv.Key; file = $kv.Value.Substring($StagingRoot.Length + 1); version = "$ver".Trim([char[]]" `0") } + } + + # Changelog entries since the previous release (its manifest's commits, else its build date). + $lastManifestFile = Join-Path $previousReleaseDir "last-release-manifest.json" + $prevManifest = $null + if (Test-Path $lastManifestFile) { + try { $prevManifest = Get-Content $lastManifestFile -Raw | ConvertFrom-Json } catch { $prevManifest = $null } + } + # Baseline for "changes since": a rebuild of the same version reuses that build's baseline; + # otherwise the previous release's commits, or (no manifest yet) the previous version's date. + function ConvertTo-SinceDate([string]$Ver) { + $vp = "$Ver".Split('.') + if ($vp.Count -eq 4) { return '{0:D4}-{1:D2}-{2:D2}' -f [int]$vp[0], [int]$vp[1], [int]$vp[2] } + return "" + } + $prevRelease = if ($lastVer -ne $Version) { $lastVer } else { "" } + $coreSince = ""; $suiteSince = ""; $sinceDate = "" + if ($prevManifest -and $prevManifest.version -eq $Version) { + $prevRelease = "$($prevManifest.previous)" + if ($prevManifest.changelogSince) { + $coreSince = "$($prevManifest.changelogSince.rynthCore)" + $suiteSince = "$($prevManifest.changelogSince.rynthSuite)" + $sinceDate = "$($prevManifest.changelogSince.date)" + } else { $sinceDate = ConvertTo-SinceDate $prevRelease } + } elseif ($prevManifest) { + $coreSince = "$($prevManifest.source.rynthCore.commit)" + $suiteSince = "$($prevManifest.source.rynthSuite.commit)" + } else { + $sinceDate = ConvertTo-SinceDate $prevRelease + } + $notesFrom = @( + @{ Repo = 'RynthCore'; Root = $RepoRoot; Files = (Get-ChangelogFiles $RepoRoot $coreSince $sinceDate) }, + @{ Repo = 'RynthSuite'; Root = $RynthSuiteRoot; Files = (Get-ChangelogFiles $RynthSuiteRoot $suiteSince $sinceDate) } + ) + + $manifest = [ordered]@{ + schema = 1 + product = 'RynthCore + RynthSuite' + version = $Version + release = $release + builtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + previous = $prevRelease + installer = [ordered]@{ file = $setupName; size = (Get-Item (Join-Path $pkgDir $setupName)).Length; sha256 = $setupHash } + source = [ordered]@{ + rynthCore = [ordered]@{ branch = $CoreState.branch; commit = $CoreState.commit; dirty = $CoreState.dirty } + rynthSuite = [ordered]@{ branch = $SuiteState.branch; commit = $SuiteState.commit; dirty = $SuiteState.dirty } + } + components = @($components) + changelog = @($notesFrom | ForEach-Object { $r = $_.Repo; $_.Files | ForEach-Object { "$r/$_" } }) + # Baseline the notes were built from (reused when this version is rebuilt). + changelogSince = [ordered]@{ rynthCore = $coreSince; rynthSuite = $suiteSince; date = $sinceDate } + } + $manifestJson = $manifest | ConvertTo-Json -Depth 6 + Write-Utf8 (Join-Path $pkgDir 'release-manifest.json') $manifestJson + + # RELEASE-NOTES.md: install/verify steps, component table, then the Changelog entries + # (their headings demoted two levels so they nest under "Changes"). + $sb = New-Object System.Text.StringBuilder + $short = { param($s) if ($s.commit) { "$($s.branch)@$($s.commit.Substring(0,7))$(if ($s.dirty) { ' (uncommitted changes!)' })" } else { 'unknown' } } + [void]$sb.AppendLine("# RynthCore + RynthSuite $Version") + [void]$sb.AppendLine() + [void]$sb.AppendLine("Release $release, built $($manifest.builtUtc). Previous release: $(if ($prevRelease) { $prevRelease } else { 'none recorded' }).") + [void]$sb.AppendLine("Source: RynthCore $(& $short $CoreState), RynthSuite $(& $short $SuiteState).") + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Install") + [void]$sb.AppendLine("- Close Asheron's Call clients and the RynthCore launcher, then run ``$setupName``. It upgrades earlier RynthCore / RynthBundle installs in place.") + [void]$sb.AppendLine("- The installer asks for the RynthCore and RynthSuite folders; RynthAi, the Loot Editor and the Monster Editor are included, experimental plugins are optional components.") + [void]$sb.AppendLine("- When the .NET 10 Desktop Runtime (x86) is missing it is downloaded from Microsoft during setup.") + [void]$sb.AppendLine("- Silent install: ``$setupName /VERYSILENT /DIR=""C:\Games\RynthCore"" /SUITEDIR=""C:\Games\RynthSuite""``") + [void]$sb.AppendLine("- Verify the download: ``(Get-FileHash .\$setupName).Hash`` must equal ``$setupHash`` (also in SHA256SUMS.txt).") + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Components") + [void]$sb.AppendLine("| Component | Version |") + [void]$sb.AppendLine("|---|---|") + foreach ($c in $components) { [void]$sb.AppendLine("| $($c.name) | $($c.version) |") } + [void]$sb.AppendLine() + [void]$sb.AppendLine("## Changes$(if ($prevRelease) { " since $prevRelease" })") + $anyNotes = $false + foreach ($src in $notesFrom) { + foreach ($rel in $src.Files) { + $anyNotes = $true + [void]$sb.AppendLine() + [void]$sb.AppendLine("### $($src.Repo): $([IO.Path]::GetFileName($rel))") + $text = [IO.File]::ReadAllText((Join-Path $src.Root $rel)) # UTF-8 (Get-Content would read ANSI on 5.1) + foreach ($line in ($text -split "`r?`n")) { + if ($line -match '^#') { [void]$sb.AppendLine("##$line") } else { [void]$sb.AppendLine($line) } + } + } + } + if (-not $anyNotes) { [void]$sb.AppendLine(); [void]$sb.AppendLine("_No Changelog entries were added since the previous release._") } + Write-Utf8 (Join-Path $pkgDir 'RELEASE-NOTES.md') $sb.ToString() + + # SHA256SUMS.txt in sha256sum format ("<hash> *<file>"), covering every other package file. + $sumLines = Get-ChildItem $pkgDir -File | Sort-Object Name | ForEach-Object { "$(Get-Sha256 $_.FullName) *$($_.Name)" } + Write-Utf8 (Join-Path $pkgDir 'SHA256SUMS.txt') (($sumLines -join "`n") + "`n") + + Compress-Archive -Path (Join-Path $pkgDir '*') -DestinationPath $zipPath -CompressionLevel Optimal + + # Re-verify: extract the zip and check every file against SHA256SUMS.txt. + $verifyDir = Join-Path $env:TEMP "RynthCore-deploy-verify-$([guid]::NewGuid().ToString('N'))" + try { + Expand-Archive -Path $zipPath -DestinationPath $verifyDir -Force + foreach ($line in $sumLines) { + $expected, $file = $line -split ' \*', 2 + $actual = Get-Sha256 (Join-Path $verifyDir $file) + if ($actual -ne $expected) { throw "Deployment zip verification failed for ${file}: $actual != $expected" } + } + } finally { + Remove-Item $verifyDir -Recurse -Force -ErrorAction SilentlyContinue + } + + Write-Utf8 $lastManifestFile $manifestJson + $zipMb = [math]::Round((Get-Item $zipPath).Length / 1MB, 1) + Write-Host " Package: $pkgDir" -ForegroundColor Green + Write-Host " Zip: $zipPath (${zipMb} MB, verified)" -ForegroundColor Green + Write-Host " Changelog entries: $($manifest.changelog.Count)" +} + +# Record the version last, so a failed package step is retried (not skipped) on the next run. +if ($Version) { [IO.File]::WriteAllText($lastVersionFile, $Version) } + Write-Host "" Write-Host "SUCCESS" -ForegroundColor Green -Write-Host "Installer: $ScriptDir\Output\RynthCore-Setup.exe" +Write-Host "Installer: $builtInstaller" +if ($Version -and -not $NoPackage) { Write-Host "Deploy: $zipPath" } diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 9efbaa2..b877130 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -362,28 +362,27 @@ if (-not $NativeAotPlugins) { } & (Join-Path $ScriptDir "Build-Installer.ps1") @installerArgs if (-not $?) { throw "Build-Installer.ps1 failed" } -# The Decal bridge ships in every release (experimental, opt-in per account): the installer -# carries it, so a launcher that updates through this feed gets it as a fresh install does. -# Build-Installer.ps1 fails without Decal; this guards against a -SkipDecalBridge staging. -$bridgeStaged = Join-Path $ScriptDir "staging\app\DecalBridge\RynthCore.DecalBridge.dll" -if (-not (Test-Path $bridgeStaged)) { throw "The installer was built without the Decal bridge ($bridgeStaged missing) - not publishing." } -Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" -# The headless client ships in every release too (experimental, opt-in per account): rynth-headless with its -# own x64 runtime, and the x64 RynthAi it loads when the launcher's HeadlessPluginPaths is empty. Its -# plugins come with the core installer only; the feed's plugin entries stay the x86 game-client builds. -foreach ($f in "Headless\rynth-headless.exe", "Headless\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") { - if (-not (Test-Path (Join-Path $ScriptDir "staging\app\$f"))) { throw "The installer was built without $f - not publishing." } +# The Decal bridge (experimental, opt-in per account) is only in installers built where Decal is +# installed; a launcher updating through this feed without it can't run "Decal + RynthCore" accounts. +$bridgeStaged = Join-Path $ScriptDir "staging\core\DecalBridge\RynthCore.DecalBridge.dll" +if (Test-Path $bridgeStaged) { + Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" +} else { + Write-Warning "This installer has no Decal bridge ($bridgeStaged missing); 'Decal + RynthCore' accounts won't work from it." } -foreach ($f in "Headless\rynth-headless.dll", "Headless\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") { - $fv = (Get-Item (Join-Path $ScriptDir "staging\app\$f")).VersionInfo.FileVersion - if ($fv -ne $Version) { throw "The installer's $f is version $fv, not $Version (stale build?) - not publishing." } -} -Write-Host " headless client in the installer: rynth-headless and the x64 RynthAi, both $Version" -Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe" -Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" +# The versioned installer is the primary artifact (the RynthCore-Setup.exe copy is best effort). +Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup-$Version.exe") "$rel\RynthCore-Setup.exe" +# RynthAi: the managed build when plugins are managed, else the NativeAOT one Build-Installer.ps1 +# staged under staging\suite\RynthAi\. +$rynthAiFeed = if ($NativeAotPlugins) { Join-Path $ScriptDir "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll" } + else { "$rel\build\RynthAi\RynthCore.Plugin.RynthAi.dll" } +Copy-Item $rynthAiFeed "$rel\plugins\" foreach ($name in $suitePlugins + $serverPlugins) { Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" } +# Server plugins also go in RynthSuite-Plugins.zip: RynthCore loads only the one whose manifest hosts +# claim the client's connect host, so installing all of them costs disk, not memory. +$suitePlugins += $serverPlugins Step "Packing RynthSuite-Plugins.zip" $zipRoot = "$rel\build\zip" @@ -559,10 +558,27 @@ $pluginDescriptions = @{ RynthOracle = "Quests, character and titles." RynthInventory = "Search every character's items." RynthSort = "Keeps your packs sorted: new loot goes to the pack its rule names." - RynthILT = "Infinite Leaftide only: the ILT Hub (the Mini Remote's banking, gear, charms and games tabs), the Guardian, bounty tracking and progression planning." + RynthILT = "Infinite Leaftide only: the ILT Hub (the Mini Remote's banking, gear, charms and games tabs), the Guardian, bounty tracking, progression planning, ILT settings and the /fship fellowship commands." RynthThreads = "DreamWeave only: records Fragment Press results and works out what each component brings." RynthNet = "Links your characters on this PC: broadcast commands (/ub bc), shared vitals and the Characters panel." RynthDefective = "A shortcut bar with AC's own keys, buttons for AC's panels and the Selection, in place of the retail toolbar." + # Server plugins: only the one for the server you connect to loads. + RynthAChard = "AChard's server plugin: server facts, PvP rules and commands. Loads only on AChard." + RynthAelrynth = "Aelrynth's server plugin: server facts, mods and commands. Loads only on Aelrynth." + RynthColdeve = "Coldeve's server plugin: server facts, rules and commands. Loads only on Coldeve." + RynthConquest = "Conquest's server plugin: server facts, rules and commands. Loads only on Conquest." + RynthDerptide = "Derptide's server plugin: server facts, rules and commands. Loads only on Derptide." + RynthDreamWeave = "DreamWeave's server plugin: server facts, rules, commands and wiki link. Loads only on DreamWeave." + RynthEversong = "Eversong's server plugin: server facts, rules and commands. Loads only on Eversong." + RynthFrostACE = "FrostACE's server plugin: server facts, rules and commands. Loads only on FrostACE." + RynthFrostcull = "Frostcull's server plugin: server facts, rates and commands. Loads only on Frostcull." + RynthLeafDawn = "LeafDawn's server plugin: server facts, rules and commands. Loads only on LeafDawn." + RynthLeafdawning = "Leafdawning's server plugin: server facts, account limit and commands. Loads only on Leafdawning." + RynthLevistras = "Levistras's server plugin: server facts and rules (botting is not allowed there). Loads only on Levistras." + RynthPortalStorm = "PortalStorm's server plugin: server facts, rules and commands. Loads only on PortalStorm." + RynthReefcull = "Reefcull's server plugin (GDLE): server facts, rules and commands. Loads only on Reefcull." + RynthSundering = "Sundering's server plugin: server facts, character limit and commands. Loads only on Sundering." + RynthThistlecrown = "Thistlecrown's server plugin: server facts, account limit and commands. Loads only on Thistlecrown." } # Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi # goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index 1c21008..393ffa8 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -1,7 +1,18 @@ -; RynthCore + RynthAi Installer -; Build with: Build-Installer.ps1 (requires Inno Setup 6) +; RynthCore + RynthSuite full installer +; Build with: Build-Installer.ps1 (requires Inno Setup 6) — it builds every component from source +; (launcher, engine, loader, RynthAi plugin, Loot Editor, Monster Editor) and stages them under +; installer\staging\core and installer\staging\suite before invoking ISCC on this file. ; Source: https://jrsoftware.org/isdl.php ; +; Install locations are user-defined: +; * RynthCore folder ({app}) — the standard "Select Destination Location" page +; * RynthSuite folder ({code:GetSuiteDir}) — a second folder page right after it +; Both are recorded under HKA\Software\Rynth (CoreDir / SuiteDir); the engine, launcher and plugins +; resolve every path from there (RynthInstallPaths.cs), so neither folder has to be under C:\Games. +; Silent installs: /DIR="<core folder>" /SUITEDIR="<suite folder>". +; Prerequisite: when the .NET 10 Desktop Runtime (x86) is missing, the "installdotnet" task (on by default) +; downloads it from Microsoft and installs it before the files are copied. A failure is reported, never fatal. +; ; NOTE: No ISPP (#define / {#...}) macros are used in this file. ; Build-Installer.ps1 replaces the AppVersion placeholder via text substitution ; before invoking ISCC, so the preprocessor has nothing to expand. @@ -9,13 +20,17 @@ ; APPVERSION_PLACEHOLDER=0.0.0 [Setup] +; Same AppId as every earlier RynthCore / RynthBundle installer, so this upgrades them in place. AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678} AppName=RynthCore +AppVerName=RynthCore + RynthSuite 0.0.0 AppVersion=0.0.0 AppPublisher=RynthCore -AppPublisherURL=https://aelrynth.com/git/rynth/RynthCore +AppPublisherURL=https://aelrynth.com/rynth.html +UninstallDisplayName=RynthCore + RynthSuite DefaultDirName=C:\Games\RynthCore DisableDirPage=no +UsePreviousAppDir=yes DefaultGroupName=RynthCore DisableProgramGroupPage=yes OutputDir=Output @@ -28,62 +43,172 @@ WizardStyle=modern ; the chosen install folder requires it (e.g. C:\Games\). PrivilegesRequired=lowest PrivilegesRequiredOverridesAllowed=dialog -; 32-bit app; works on 32/64-bit Windows -ArchitecturesAllowed=x86 x64 arm64 +; Close a running launcher / editors before replacing their files. +CloseApplications=yes +; 32-bit app; works on 32/64-bit Windows (HKA registry writes land in the 32-bit view, +; which is exactly where RynthInstallPaths reads HKLM from). +ArchitecturesAllowed=x86compatible ArchitecturesInstallIn64BitMode= [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" +[Types] +Name: "full"; Description: "Full install (RynthCore + RynthSuite)" +Name: "core"; Description: "RynthCore only" +Name: "custom"; Description: "Custom"; Flags: iscustom + +[Components] +Name: "core"; Description: "RynthCore launcher, engine and Loot Editor"; Types: full core custom; Flags: fixed +Name: "rynthai"; Description: "RynthSuite: RynthAi plugin (installed and registered with the launcher)"; Types: full +Name: "monstereditor"; Description: "RynthSuite: Monster Editor"; Types: full +; RynthSuite companion plugins: on in a Full install, each registered with the launcher like RynthAi. +Name: "suite"; Description: "RynthSuite: Companion plugins"; Types: full +Name: "suite\rynthoracle"; Description: "RynthOracle - quests, quest timers, markers, character, fellowship"; Types: full +Name: "suite\rynthilt"; Description: "RynthILT - Infinite Leaftide features (hub, progression, banking, bounties)"; Types: full +Name: "suite\rynthinventory"; Description: "RynthInventory - inventory, item counts and global manage"; Types: full +Name: "suite\rynthsort"; Description: "RynthSort - inventory sorting"; Types: full +; Server plugins (RynthServers): RynthCore loads only the one for the server you connect to. +Name: "suite\rynthachard"; Description: "RynthAChard - server plugin for AChard (loads only on that server)"; Types: full +Name: "suite\rynthaelrynth"; Description: "RynthAelrynth - server plugin for Aelrynth (loads only on that server)"; Types: full +Name: "suite\rynthcoldeve"; Description: "RynthColdeve - server plugin for Coldeve (loads only on that server)"; Types: full +Name: "suite\rynthconquest"; Description: "RynthConquest - server plugin for Conquest (loads only on that server)"; Types: full +Name: "suite\rynthderptide"; Description: "RynthDerptide - server plugin for Derptide (loads only on that server)"; Types: full +Name: "suite\rynthdreamweave"; Description: "RynthDreamWeave - server plugin for DreamWeave (loads only on that server)"; Types: full +Name: "suite\ryntheversong"; Description: "RynthEversong - server plugin for Eversong (loads only on that server)"; Types: full +Name: "suite\rynthfrostace"; Description: "RynthFrostACE - server plugin for FrostACE (loads only on that server)"; Types: full +Name: "suite\rynthfrostcull"; Description: "RynthFrostcull - server plugin for Frostcull (loads only on that server)"; Types: full +Name: "suite\rynthleafdawn"; Description: "RynthLeafDawn - server plugin for LeafDawn (loads only on that server)"; Types: full +Name: "suite\rynthleafdawning"; Description: "RynthLeafdawning - server plugin for Leafdawning (loads only on that server)"; Types: full +Name: "suite\rynthlevistras"; Description: "RynthLevistras - server plugin for Levistras (loads only on that server)"; Types: full +Name: "suite\rynthportalstorm"; Description: "RynthPortalStorm - server plugin for PortalStorm (loads only on that server)"; Types: full +Name: "suite\rynthreefcull"; Description: "RynthReefcull - server plugin for Reefcull (loads only on that server)"; Types: full +Name: "suite\rynthsundering"; Description: "RynthSundering - server plugin for Sundering (loads only on that server)"; Types: full +Name: "suite\rynththistlecrown"; Description: "RynthThistlecrown - server plugin for Thistlecrown (loads only on that server)"; Types: full +Name: "suite\rynththreads"; Description: "RynthThreads - server plugin for DreamWeave's Threads (loads only on that server)"; Types: full +; Experimental plugins: unchecked by default in every install type (ticking one switches to Custom). +Name: "experimental"; Description: "RynthSuite: Experimental plugins (work in progress)" +Name: "experimental\rynthchat"; Description: "RynthChat - replacement chat window (classifies and owns game chat)" +Name: "experimental\rynthjuice"; Description: "RynthJuice - floating damage/heal numbers and kill bursts" +Name: "experimental\rynthnav"; Description: "RynthNav - navmesh pathing and portal routing (needs baked NavData tiles)" +Name: "experimental\rynthtracker"; Description: "RynthTracker - per-session kill tracker" +Name: "experimental\rynthvision"; Description: "RynthVision - unclimbable slope, water and radar-range overlays" +Name: "experimental\ubrythai"; Description: "ub-Rythai - Utility Belt tools ported to RynthCore (XP meter, portal gems, chat automation)" + [Tasks] Name: desktopicon; Description: "Create a &desktop shortcut"; GroupDescription: "Additional icons:" +; Only offered when the runtime is missing. RynthCore and its tools are self-contained / NativeAOT and run +; without it; it is installed for framework-dependent add-ons and tools. Skip silently with /MERGETASKS="!installdotnet". +Name: installdotnet; Description: "Download and install the Microsoft .NET 10 Desktop Runtime (x86, about 55 MB; may ask for administrator approval)"; GroupDescription: "Prerequisites:"; Check: DotNet10DesktopMissing + +; Files left by older layouts (the 0.4.x RynthBundle put a framework-dependent launcher, the engine +; and plugins straight into {app}). Mixing those with a newer launcher is what broke 2026-10-04's +; reinstall (RynthCore.App.Avalonia.dll from 0.4.7 + a newer deps.json → missing DesktopLog). +; Only loose top-level binaries/metadata are removed; every file the new build needs is copied back +; by [Files] right after. User data (Logs, AcClient, NavData, DecalBridge, ...) is never touched. +[InstallDelete] +Type: files; Name: "{app}\*.dll" +Type: files; Name: "{app}\*.json" +Type: files; Name: "{app}\*.pdb" +Type: files; Name: "{app}\*.exp" +Type: files; Name: "{app}\*.lib" +Type: files; Name: "{app}\*.previous" +Type: files; Name: "{app}\RynthCore.App.Avalonia.exe" +Type: files; Name: "{app}\RynthCore-Prerequisites.txt" +Type: files; Name: "{app}\Runtime\*.dll" +Type: files; Name: "{app}\Runtime\*.json" +Type: files; Name: "{app}\Runtime\*.pdb" +Type: files; Name: "{app}\Runtime\RynthCore.Injector.exe" +Type: filesandordirs; Name: "{app}\Runtime\Plugins" -; Program files [Files] -; Launcher + engine runtime + Loot Editor go to {app} (default C:\Games\RynthCore\) -; overwritereadonly: a file left read-only on the player's PC is replaced without a question -; (a /SILENT update can't answer one); the build clears ReadOnly on everything staged, and Setup -; doesn't give installed files any attributes, so nothing lands read-only. -; This includes {app}\Headless (experimental): rynth-headless.exe with its own 64-bit .NET runtime and -; Headless\plugins\<Name>\ (the 64-bit plugin builds it runs), staged by Build-Installer.ps1. Nothing -; there is ever loaded by a game client; the x86 plugins below are unchanged. -Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs overwritereadonly +; overwritereadonly (every line): a file left read-only on the player's PC is replaced without a +; question (a /SILENT update can't answer one); the build clears ReadOnly on everything staged, and +; Setup doesn't give installed files any attributes, so nothing lands read-only. +; RynthCore: launcher, Runtime\ (engine, loader, native deps), Tools\LootEditor, release.txt +Source: "staging\core\*"; DestDir: "{app}"; Components: core; Flags: ignoreversion recursesubdirs createallsubdirs overwritereadonly -; Plugin DLL goes to its canonical home next to plugin data dirs. -; Engine does NOT auto-scan this folder — user adds the full DLL path in the -; launcher's Plugins tab to enable the plugin. See BUILD.md "Deploy RynthAi Plugin". -Source: "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "C:\Games\RynthSuite\RynthAi"; Flags: ignoreversion overwritereadonly +; RynthSuite: the RynthAi plugin lives next to its data folders in the chosen Suite folder. +Source: "staging\suite\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Flags: ignoreversion overwritereadonly +; Monster Editor: RynthAi's dashboard launches it from <RynthAi>\MonsterEditor\. +Source: "staging\suite\RynthAi\MonsterEditor\*"; DestDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Flags: ignoreversion recursesubdirs createallsubdirs overwritereadonly -; Data directories (created once; never removed on uninstall) +; Companion plugins: each in its own <RynthSuite>\<Name>\ folder, like the experimental ones below. +Source: "staging\suite\RynthOracle\RynthCore.Plugin.RynthOracle.dll"; DestDir: "{code:GetSuiteDir}\RynthOracle"; Components: suite\rynthoracle; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthILT\RynthCore.Plugin.RynthILT.dll"; DestDir: "{code:GetSuiteDir}\RynthILT"; Components: suite\rynthilt; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthInventory\RynthCore.Plugin.RynthInventory.dll"; DestDir: "{code:GetSuiteDir}\RynthInventory"; Components: suite\rynthinventory; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthSort\RynthCore.Plugin.RynthSort.dll"; DestDir: "{code:GetSuiteDir}\RynthSort"; Components: suite\rynthsort; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthAChard\RynthCore.Plugin.RynthAChard.dll"; DestDir: "{code:GetSuiteDir}\RynthAChard"; Components: suite\rynthachard; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthAelrynth\RynthCore.Plugin.RynthAelrynth.dll"; DestDir: "{code:GetSuiteDir}\RynthAelrynth"; Components: suite\rynthaelrynth; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthColdeve\RynthCore.Plugin.RynthColdeve.dll"; DestDir: "{code:GetSuiteDir}\RynthColdeve"; Components: suite\rynthcoldeve; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthConquest\RynthCore.Plugin.RynthConquest.dll"; DestDir: "{code:GetSuiteDir}\RynthConquest"; Components: suite\rynthconquest; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthDerptide\RynthCore.Plugin.RynthDerptide.dll"; DestDir: "{code:GetSuiteDir}\RynthDerptide"; Components: suite\rynthderptide; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthDreamWeave\RynthCore.Plugin.RynthDreamWeave.dll"; DestDir: "{code:GetSuiteDir}\RynthDreamWeave"; Components: suite\rynthdreamweave; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthEversong\RynthCore.Plugin.RynthEversong.dll"; DestDir: "{code:GetSuiteDir}\RynthEversong"; Components: suite\ryntheversong; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthFrostACE\RynthCore.Plugin.RynthFrostACE.dll"; DestDir: "{code:GetSuiteDir}\RynthFrostACE"; Components: suite\rynthfrostace; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthFrostcull\RynthCore.Plugin.RynthFrostcull.dll"; DestDir: "{code:GetSuiteDir}\RynthFrostcull"; Components: suite\rynthfrostcull; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthLeafDawn\RynthCore.Plugin.RynthLeafDawn.dll"; DestDir: "{code:GetSuiteDir}\RynthLeafDawn"; Components: suite\rynthleafdawn; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthLeafdawning\RynthCore.Plugin.RynthLeafdawning.dll"; DestDir: "{code:GetSuiteDir}\RynthLeafdawning"; Components: suite\rynthleafdawning; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthLevistras\RynthCore.Plugin.RynthLevistras.dll"; DestDir: "{code:GetSuiteDir}\RynthLevistras"; Components: suite\rynthlevistras; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthPortalStorm\RynthCore.Plugin.RynthPortalStorm.dll"; DestDir: "{code:GetSuiteDir}\RynthPortalStorm"; Components: suite\rynthportalstorm; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthReefcull\RynthCore.Plugin.RynthReefcull.dll"; DestDir: "{code:GetSuiteDir}\RynthReefcull"; Components: suite\rynthreefcull; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthSundering\RynthCore.Plugin.RynthSundering.dll"; DestDir: "{code:GetSuiteDir}\RynthSundering"; Components: suite\rynthsundering; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthThistlecrown\RynthCore.Plugin.RynthThistlecrown.dll"; DestDir: "{code:GetSuiteDir}\RynthThistlecrown"; Components: suite\rynththistlecrown; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthThreads\RynthCore.Plugin.RynthThreads.dll"; DestDir: "{code:GetSuiteDir}\RynthThreads"; Components: suite\rynththreads; Flags: ignoreversion overwritereadonly + +; Experimental plugins: each in its own <RynthSuite>\<Name>\ folder (the layout the launcher already uses). +Source: "staging\suite\RynthChat\RynthCore.Plugin.RynthChat.dll"; DestDir: "{code:GetSuiteDir}\RynthChat"; Components: experimental\rynthchat; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthJuice\RynthCore.Plugin.RynthJuice.dll"; DestDir: "{code:GetSuiteDir}\RynthJuice"; Components: experimental\rynthjuice; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthNav\RynthCore.Plugin.RynthNav.dll"; DestDir: "{code:GetSuiteDir}\RynthNav"; Components: experimental\rynthnav; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthTracker\RynthCore.Plugin.RynthTracker.dll"; DestDir: "{code:GetSuiteDir}\RynthTracker"; Components: experimental\rynthtracker; Flags: ignoreversion overwritereadonly +Source: "staging\suite\RynthVision\RynthCore.Plugin.RynthVision.dll"; DestDir: "{code:GetSuiteDir}\RynthVision"; Components: experimental\rynthvision; Flags: ignoreversion overwritereadonly +Source: "staging\suite\UbRythai\RynthCore.Plugin.UbRythai.dll"; DestDir: "{code:GetSuiteDir}\UbRythai"; Components: experimental\ubrythai; Flags: ignoreversion overwritereadonly +; RynthNav reads <RynthCore>\NavData. Starter portal list only; a newer one from RynthNav.PortalGraph is kept. +Source: "staging\navdata\portals.tsv"; DestDir: "{app}\NavData"; Components: experimental\rynthnav; Flags: onlyifdoesntexist uninsneveruninstall + +; RynthAi data directories (created once; never removed on uninstall - they hold user profiles) ; -; Permissions: users-modify (2026-10-13). The game client never runs elevated, and RynthAi saves +; Permissions: users-modify (upstream 2026-10-13). The game client never runs elevated, and RynthAi saves ; metas, navs, loot and settings profiles in these folders. An "install for all users" (elevated) ; Setup creates them as an administrator; on a PC whose C:\ permissions aren't Windows' defaults, ; such folders are read-only for everyone else and RynthAi's saves failed. users-modify gives the -; Users group Modify, inherited by everything inside, every time Setup runs (also on an update, so -; it repairs older installs when that update runs elevated). A non-elevated Setup can only change -; folders its user owns; where it can't, Setup logs "Failed to set permissions" and carries on -; (not an error), and the launcher's Recovery Actions > Fix folder permissions does it instead. +; Users group Modify, inherited by everything inside, every time Setup runs. A non-elevated Setup +; can only change folders its user owns; where it can't, Setup logs "Failed to set permissions" +; and carries on, and the launcher's Recovery Actions > Fix folder permissions does it instead. [Dirs] -Name: "{app}"; Permissions: users-modify -Name: "C:\Games\RynthSuite"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\NavProfiles"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\LootProfiles"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\MetaFiles"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\MetaProfiles"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\SettingsProfiles\ACEmulator"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\LuaScripts"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\Logs"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\pvars"; Permissions: users-modify; Flags: uninsneveruninstall -Name: "C:\Games\RynthSuite\RynthAi\ItemGiver"; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{app}"; Permissions: users-modify +Name: "{code:GetSuiteDir}"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\NavProfiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\LootProfiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MetaFiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MetaProfiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\SettingsProfiles\ACEmulator"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\MonsterProfiles"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\LuaScripts"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\Logs"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\pvars"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\ItemGiver"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +Name: "{code:GetSuiteDir}\RynthAi\AutoVendor"; Components: rynthai; Permissions: users-modify; Flags: uninsneveruninstall +; RynthNav tiles baked by RynthNav.Baker (default --out) go here; kept on uninstall. +Name: "{app}\NavData"; Components: experimental\rynthnav; Permissions: users-modify; Flags: uninsneveruninstall + +; Install locations for the engine / launcher / plugins (see RynthInstallPaths.cs), plus a one-shot +; hand-off the launcher consumes on next start to add the plugin to its Plugins list. +; HKA = HKCU for a per-user install, HKLM for an all-users (elevated) install. +[Registry] +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "CoreDir"; ValueData: "{app}"; Flags: uninsdeletevalue uninsdeletekeyifempty +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "SuiteDir"; ValueData: "{code:GetSuiteDir}"; Flags: uninsdeletevalue uninsdeletekeyifempty +Root: HKA; Subkey: "Software\Rynth"; ValueType: string; ValueName: "PendingPluginRegistration"; ValueData: "{code:GetPendingPlugins}"; Check: HasPendingPlugins; Flags: uninsdeletevalue ; Shortcuts [Icons] ; Start Menu Name: "{group}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Comment: "Launch RynthCore and inject into Asheron's Call" Name: "{group}\Loot Editor"; Filename: "{app}\Tools\LootEditor\RynthCore.LootEditor.exe"; WorkingDir: "{app}\Tools\LootEditor"; Comment: "Edit VTank-style loot profiles" +Name: "{group}\Monster Editor"; Filename: "{code:GetSuiteDir}\RynthAi\MonsterEditor\RynthCore.MonsterEditor.exe"; WorkingDir: "{code:GetSuiteDir}\RynthAi\MonsterEditor"; Components: monstereditor; Comment: "Edit RynthAi monster profiles" +Name: "{group}\RynthSuite Folder"; Filename: "{code:GetSuiteDir}"; Components: rynthai Name: "{group}\Uninstall RynthCore"; Filename: "{uninstallexe}" ; Optional Desktop shortcut (created only when the desktopicon task is checked) @@ -112,6 +237,28 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasorigina Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister" [Code] +const + DefaultSuiteDir = 'C:\Games\RynthSuite'; + { One pinned .NET 10 Desktop Runtime build (x86 to match RynthCore's x86 binaries), checked against its + SHA-256 before it runs: a download swapped on the way (or at a mirror) is refused, not run elevated. + A moving "latest" link can't be pinned. To move to a newer build, take the url from + https://builds.dotnet.microsoft.com/dotnet/release-metadata/10.0/releases.json (windowsdesktop, + win-x86 .exe), check the download against the SHA-512 listed there, and put its SHA-256 here. + Any 10.x already installed is kept (IsDotNet10DesktopX86Installed); Microsoft Update patches it later. } + DotNetDesktopUrl = 'https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/10.0.12/windowsdesktop-runtime-10.0.12-win-x86.exe'; + DotNetDesktopSha256 = '57c1d40967b73785b9ef95de5f0878e9264423228971a71eb362c03ae01937f5'; + DotNetDesktopFile = 'windowsdesktop-runtime-10.0.12-win-x86.exe'; + DotNetManualUrl = 'https://dotnet.microsoft.com/download/dotnet/10.0'; + +var + SuiteDirPage: TInputDirWizardPage; + DotNetDownloadPage: TDownloadWizardPage; + { Set once the .NET step ran (interactive: on leaving the Ready page; silent: in PrepareToInstall). } + DotNetHandled: Boolean; + { True once the user (or /SUITEDIR / a previous install) chose the Suite folder explicitly; + until then it follows the RynthCore folder as a sibling "RynthSuite" folder. } + SuiteDirPinned: Boolean; + function CmdLineParamExists(const Value: string): Boolean; var I: Integer; @@ -125,6 +272,353 @@ begin end; end; +{ Returns the value of a /NAME=value command-line switch, or '' when absent. } +function CmdLineParamValue(const Name: string): string; +var + I: Integer; + Prefix: string; +begin + Result := ''; + Prefix := '/' + Name + '='; + for I := 1 to ParamCount do + if CompareText(Copy(ParamStr(I), 1, Length(Prefix)), Prefix) = 0 then + begin + Result := RemoveQuotes(Copy(ParamStr(I), Length(Prefix) + 1, MaxInt)); + Exit; + end; +end; + +{ Suite folder recorded by an earlier install in the SAME install mode (HKA: HKCU per-user, HKLM all-users), + or ''. Never adopt the other mode's folder: two installs sharing a Suite folder would delete each other's + files on uninstall. } +function RegisteredSuiteDir: string; +begin + Result := ''; + if not RegQueryStringValue(HKA, 'Software\Rynth', 'SuiteDir', Result) then + Result := ''; +end; + +{ Default Suite folder for a given RynthCore folder: its sibling "RynthSuite". } +function SiblingSuiteDir(const CoreDir: string): string; +begin + Result := AddBackslash(ExtractFileDir(RemoveBackslashUnlessRoot(CoreDir))) + 'RynthSuite'; +end; + +// {code:GetSuiteDir}: the chosen RynthSuite folder, without a trailing backslash. +function GetSuiteDir(Param: string): string; +begin + if SuiteDirPage = nil then + Result := DefaultSuiteDir + else if WizardSilent and not SuiteDirPinned then + { Silent installs never run NextButtonClick: follow /DIR= with a sibling RynthSuite folder. } + Result := SiblingSuiteDir(WizardDirValue) + else + Result := RemoveBackslashUnlessRoot(Trim(SuiteDirPage.Values[0])); +end; + +// Number of entries in ExperimentalPluginName; keep in sync with the [Components]/[Files] experimental rows. +const + ExperimentalCount = 6; + +// Experimental plugin names; component "experimental\<lowercase name>" installs <Suite>\<Name>\RynthCore.Plugin.<Name>.dll. +function ExperimentalPluginName(Index: Integer): string; +begin + case Index of + 0: Result := 'RynthChat'; + 1: Result := 'RynthJuice'; + 2: Result := 'RynthNav'; + 3: Result := 'RynthTracker'; + 4: Result := 'RynthVision'; + 5: Result := 'UbRythai'; + else + Result := ''; + end; +end; + +function ExperimentalSelected(Index: Integer): Boolean; +begin + Result := WizardIsComponentSelected('experimental\' + Lowercase(ExperimentalPluginName(Index))); +end; + +// Number of entries in SuitePluginName; keep in sync with the [Components]/[Files] suite rows. +const + SuitePluginCount = 21; + +// Companion plugin names; component "suite\<lowercase name>" installs <Suite>\<Name>\RynthCore.Plugin.<Name>.dll. +function SuitePluginName(Index: Integer): string; +begin + case Index of + 0: Result := 'RynthOracle'; + 1: Result := 'RynthILT'; + 2: Result := 'RynthInventory'; + 3: Result := 'RynthSort'; + 4: Result := 'RynthAChard'; + 5: Result := 'RynthAelrynth'; + 6: Result := 'RynthColdeve'; + 7: Result := 'RynthConquest'; + 8: Result := 'RynthDerptide'; + 9: Result := 'RynthDreamWeave'; + 10: Result := 'RynthEversong'; + 11: Result := 'RynthFrostACE'; + 12: Result := 'RynthFrostcull'; + 13: Result := 'RynthLeafDawn'; + 14: Result := 'RynthLeafdawning'; + 15: Result := 'RynthLevistras'; + 16: Result := 'RynthPortalStorm'; + 17: Result := 'RynthReefcull'; + 18: Result := 'RynthSundering'; + 19: Result := 'RynthThistlecrown'; + 20: Result := 'RynthThreads'; + else + Result := ''; + end; +end; + +function SuitePluginSelected(Index: Integer): Boolean; +begin + Result := WizardIsComponentSelected('suite\' + Lowercase(SuitePluginName(Index))); +end; + +{ True when anything is going into the RynthSuite folder (controls the Suite folder page / memo line). } +function AnySuiteComponentSelected: Boolean; +var + I: Integer; +begin + Result := WizardIsComponentSelected('rynthai') or WizardIsComponentSelected('monstereditor'); + for I := 0 to SuitePluginCount - 1 do + if SuitePluginSelected(I) then + Result := True; + for I := 0 to ExperimentalCount - 1 do + if ExperimentalSelected(I) then + Result := True; +end; + +// {code:GetPendingPlugins}: ';'-separated plugin DLLs for the launcher to add to its Plugins list on next start. +function GetPendingPlugins(Param: string): string; +var + I: Integer; + Name: string; +begin + Result := ''; + if WizardIsComponentSelected('rynthai') then + Result := GetSuiteDir('') + '\RynthAi\RynthCore.Plugin.RynthAi.dll'; + for I := 0 to SuitePluginCount - 1 do + if SuitePluginSelected(I) then + begin + Name := SuitePluginName(I); + if Result <> '' then + Result := Result + ';'; + Result := Result + GetSuiteDir('') + '\' + Name + '\RynthCore.Plugin.' + Name + '.dll'; + end; + for I := 0 to ExperimentalCount - 1 do + if ExperimentalSelected(I) then + begin + Name := ExperimentalPluginName(I); + if Result <> '' then + Result := Result + ';'; + Result := Result + GetSuiteDir('') + '\' + Name + '\RynthCore.Plugin.' + Name + '.dll'; + end; +end; + +function HasPendingPlugins: Boolean; +begin + Result := GetPendingPlugins('') <> ''; +end; + +{ ── .NET 10 Desktop Runtime (x86) ─────────────────────────────────────────── } + +{ True when Root (a ...\shared\Microsoft.WindowsDesktop.App folder) holds a 10.x version folder. } +function HasVersion10Folder(const Root: string): Boolean; +var + FindRec: TFindRec; +begin + Result := False; + if FindFirst(AddBackslash(Root) + '10.*', FindRec) then + try + repeat + if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY <> 0 then + begin + Result := True; + Exit; + end; + until not FindNext(FindRec); + finally + FindClose(FindRec); + end; +end; + +{ Detects the x86 Desktop Runtime 10.x the way the .NET host does: the shared framework folder under + Program Files (x86)\dotnet, or the installer's registration in the 32-bit registry view. } +function IsDotNet10DesktopX86Installed: Boolean; +var + Names: TArrayOfString; + I: Integer; +begin + Result := HasVersion10Folder(ExpandConstant('{commonpf32}\dotnet\shared\Microsoft.WindowsDesktop.App')); + if Result then Exit; + if RegGetValueNames(HKLM32, 'SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.WindowsDesktop.App', Names) then + for I := 0 to GetArrayLength(Names) - 1 do + if Copy(Names[I], 1, 3) = '10.' then + begin + Result := True; + Exit; + end; +end; + +// Check function for the installdotnet task: offer it only when the runtime is missing. +function DotNet10DesktopMissing: Boolean; +begin + Result := not IsDotNet10DesktopX86Installed; +end; + +function OnDotNetDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean; +begin + Result := True; { never cancel from code; the download page has its own Abort button } +end; + +{ Downloads and runs the .NET 10 Desktop Runtime installer when the task is selected and the runtime is + still missing. Returns '' on success / nothing to do, else a reason. Never blocks the RynthCore install. } +function InstallDotNetRuntime(UsePage: Boolean): string; +var + SetupPath: string; + ResultCode: Integer; +begin + Result := ''; + DotNetHandled := True; + if not WizardIsTaskSelected('installdotnet') or IsDotNet10DesktopX86Installed then + Exit; + + Log('.NET 10 Desktop Runtime (x86) missing; downloading ' + DotNetDesktopUrl); + try + if UsePage then + begin + DotNetDownloadPage.Clear; + DotNetDownloadPage.Add(DotNetDesktopUrl, DotNetDesktopFile, DotNetDesktopSha256); + DotNetDownloadPage.Show; + try + DotNetDownloadPage.Download; + finally + DotNetDownloadPage.Hide; + end; + end + else + DownloadTemporaryFile(DotNetDesktopUrl, DotNetDesktopFile, DotNetDesktopSha256, @OnDotNetDownloadProgress); + except + Result := 'the download failed (' + GetExceptionMessage + ')'; + Exit; + end; + + { The runtime's own bundle asks for elevation (UAC) itself when this setup is not elevated. } + SetupPath := ExpandConstant('{tmp}\' + DotNetDesktopFile); + Log('Running ' + SetupPath + ' /install /quiet /norestart'); + if not ShellExec('', SetupPath, '/install /quiet /norestart', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then + Result := 'its installer could not be started (' + SysErrorMessage(ResultCode) + ')' + { 0 = installed, 3010/1641 = installed (restart pending/started), 1638 = a newer version is already installed } + else if (ResultCode <> 0) and (ResultCode <> 3010) and (ResultCode <> 1641) and (ResultCode <> 1638) then + Result := 'its installer exited with code ' + IntToStr(ResultCode) + ' (1602 = cancelled)' + else + Log('.NET 10 Desktop Runtime installer finished, exit code ' + IntToStr(ResultCode)); +end; + +{ Runs the .NET step and reports (but never fails on) a problem. } +procedure HandleDotNetRuntime(UsePage: Boolean); +var + Problem: string; +begin + Problem := InstallDotNetRuntime(UsePage); + if Problem = '' then Exit; + Log('.NET 10 Desktop Runtime was not installed: ' + Problem); + if not WizardSilent then + MsgBox('The Microsoft .NET 10 Desktop Runtime could not be installed: ' + Problem + '.' + #13#10#13#10 + + 'RynthCore will still be installed and works without it (it is self-contained). ' + + 'You can install the runtime later from:' + #13#10 + DotNetManualUrl, mbInformation, MB_OK); +end; + +procedure InitializeWizard; +var + Initial: string; +begin + { After the Components page, so ShouldSkipPage knows whether any Suite component was picked. } + SuiteDirPage := CreateInputDirPage(wpSelectComponents, + 'Select RynthSuite Location', + 'Where should the RynthSuite plugins and their data be installed?', + 'RynthAi, the Monster Editor, the companion plugins and any experimental plugins you picked will be installed into the RynthSuite folder below, and your ' + + 'profiles (nav, loot, meta, settings) are kept there. To continue, click Next. ' + + 'If you would like to select a different folder, click Browse.', + False, 'RynthSuite'); + SuiteDirPage.Add(''); + + { Priority: /SUITEDIR= → previous install of this setup → registry → C:\Games\RynthSuite. } + Initial := CmdLineParamValue('SUITEDIR'); + if Initial = '' then Initial := GetPreviousData('SuiteDir', ''); + if Initial = '' then Initial := RegisteredSuiteDir; + SuiteDirPinned := Initial <> ''; + if Initial = '' then Initial := DefaultSuiteDir; + SuiteDirPage.Values[0] := Initial; + + { Progress page for the optional .NET 10 Desktop Runtime download (shown only when that task runs). } + DotNetDownloadPage := CreateDownloadPage('Downloading Prerequisites', + 'Downloading the Microsoft .NET 10 Desktop Runtime (x86)...', @OnDotNetDownloadProgress); +end; + +procedure RegisterPreviousData(PreviousDataKey: Integer); +begin + SetPreviousData(PreviousDataKey, 'SuiteDir', GetSuiteDir('')); +end; + +function ShouldSkipPage(PageID: Integer): Boolean; +begin + { No Suite components selected → no Suite folder to choose. } + Result := (SuiteDirPage <> nil) and (PageID = SuiteDirPage.ID) and not AnySuiteComponentSelected; +end; + +function NextButtonClick(CurPageID: Integer): Boolean; +var + Dir: string; +begin + Result := True; + + { Leaving the RynthCore folder page: keep an un-pinned Suite folder beside the chosen Core folder. } + if (CurPageID = wpSelectDir) and not SuiteDirPinned then + SuiteDirPage.Values[0] := SiblingSuiteDir(WizardDirValue); + + if (SuiteDirPage <> nil) and (CurPageID = SuiteDirPage.ID) then + begin + Dir := GetSuiteDir(''); + { Require an absolute local or UNC path (e.g. D:\Games\RynthSuite or \\server\share\RynthSuite). } + if (Length(Dir) < 3) or not ((Copy(Dir, 2, 2) = ':\') or (Copy(Dir, 1, 2) = '\\')) then + begin + MsgBox('Please choose a full folder path for RynthSuite, for example D:\Games\RynthSuite.', mbError, MB_OK); + Result := False; + Exit; + end; + SuiteDirPinned := True; + end; + + { Leaving the Ready page: fetch/install the .NET runtime first (with a progress page) if that task is on. } + if CurPageID = wpReady then + HandleDotNetRuntime(True); +end; + +// Silent installs skip the wizard pages, so the .NET step runs here instead (no progress page). Never blocks. +function PrepareToInstall(var NeedsRestart: Boolean): String; +begin + if not DotNetHandled then + HandleDotNetRuntime(False); + Result := ''; +end; + +function UpdateReadyMemo(Space, NewLine, MemoUserInfoInfo, MemoDirInfo, MemoTypeInfo, + MemoComponentsInfo, MemoGroupInfo, MemoTasksInfo: String): String; +begin + Result := MemoDirInfo + NewLine; + if AnySuiteComponentSelected then + Result := Result + 'RynthSuite location:' + NewLine + Space + GetSuiteDir('') + NewLine; + Result := Result + NewLine + MemoComponentsInfo; + if MemoTasksInfo <> '' then + Result := Result + NewLine + MemoTasksInfo; +end; + (* ------------------------------------------------------------------------------------- Decal + RynthCore (experimental), strictly opt-in (since 2026-10-10): on install and on every update (the launcher's updater runs this installer with /SILENT), the RynthCore diff --git a/installer/previous-release/last-built-version.txt b/installer/previous-release/last-built-version.txt new file mode 100644 index 0000000..692225b --- /dev/null +++ b/installer/previous-release/last-built-version.txt @@ -0,0 +1 @@ +2026.11.22.48 \ No newline at end of file diff --git a/installer/previous-release/last-release-manifest.json b/installer/previous-release/last-release-manifest.json new file mode 100644 index 0000000..5b24a19 --- /dev/null +++ b/installer/previous-release/last-release-manifest.json @@ -0,0 +1,124 @@ +{ + "schema": 1, + "product": "RynthCore + RynthSuite", + "version": "2026.10.18.13", + "release": 2026101813, + "builtUtc": "2026-10-18T03:51:03Z", + "previous": "2026.10.18.11", + "installer": { + "file": "RynthCore-Setup-2026.10.18.13.exe", + "size": 138670467, + "sha256": "db6ab30f1e5bedcc6832525883f6a3b88e0675cfe10e9b9e3dfb8d2a8a0f2eb2" + }, + "source": { + "rynthCore": { + "branch": "test/hotbuild-2026-10-16-on-aelrynth", + "commit": "6b6442faa23bea6b2ede9a377406c8e5abddf058", + "dirty": false + }, + "rynthSuite": { + "branch": "test/hotbuild-2026-10-16-on-aelrynth", + "commit": "85c2e4f17bf7882b9420f787cdec94bf8e4508e1", + "dirty": false + } + }, + "components": [ + { + "name": "Launcher (RynthCore.exe)", + "file": "core\\RynthCore.exe", + "version": "2026.10.18.13+6b6442faa23bea6b2ede9a377406c8e5abddf058" + }, + { + "name": "Engine", + "file": "core\\Runtime\\RynthCore.Engine.dll", + "version": "2026.10.18.13+6b6442faa23bea6b2ede9a377406c8e5abddf058" + }, + { + "name": "Loader", + "file": "core\\Runtime\\RynthCore.Loader.dll", + "version": "" + }, + { + "name": "Loot Editor", + "file": "core\\Tools\\LootEditor\\RynthCore.LootEditor.exe", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthAi plugin", + "file": "suite\\RynthAi\\RynthCore.Plugin.RynthAi.dll", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "Monster Editor", + "file": "suite\\RynthAi\\MonsterEditor\\RynthCore.MonsterEditor.exe", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthOracle plugin", + "file": "suite\\RynthOracle\\RynthCore.Plugin.RynthOracle.dll", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthILT plugin", + "file": "suite\\RynthILT\\RynthCore.Plugin.RynthILT.dll", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthInventory plugin", + "file": "suite\\RynthInventory\\RynthCore.Plugin.RynthInventory.dll", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthSort plugin", + "file": "suite\\RynthSort\\RynthCore.Plugin.RynthSort.dll", + "version": "2026.10.18.13+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthChat (experimental)", + "file": "suite\\RynthChat\\RynthCore.Plugin.RynthChat.dll", + "version": "1.0.0+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthJuice (experimental)", + "file": "suite\\RynthJuice\\RynthCore.Plugin.RynthJuice.dll", + "version": "0.1.3-experimental+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthNav (experimental)", + "file": "suite\\RynthNav\\RynthCore.Plugin.RynthNav.dll", + "version": "1.0.0+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthTracker (experimental)", + "file": "suite\\RynthTracker\\RynthCore.Plugin.RynthTracker.dll", + "version": "1.0.0+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "RynthVision (experimental)", + "file": "suite\\RynthVision\\RynthCore.Plugin.RynthVision.dll", + "version": "1.0.0+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + }, + { + "name": "UbRythai (experimental)", + "file": "suite\\UbRythai\\RynthCore.Plugin.UbRythai.dll", + "version": "3.1.15+85c2e4f17bf7882b9420f787cdec94bf8e4508e1" + } + ], + "changelog": [ + "RynthCore/Changelog/2026-10-17-test-build-full-install-2026.10.18.4.md", + "RynthCore/Changelog/2026-10-18-graphics-low-memory-safeguard-2026.10.18.11.md", + "RynthCore/Changelog/2026-10-18-loot-add-attribute-checklist-2026.10.18.10.md", + "RynthSuite/Changelog/2026-10-17-chaser-ring-evade-0.5.84.md", + "RynthSuite/Changelog/2026-10-17-handler-ring-run-away-0.5.83.md", + "RynthSuite/Changelog/2026-10-17-oracle-dynamic-stamps-tab-0.5.0.md", + "RynthSuite/Changelog/2026-10-17-vt-mt-commands-port-0.5.85.md", + "RynthSuite/Changelog/2026-10-18-loot-add-attribute-checklist-0.5.87.md", + "RynthSuite/Changelog/2026-10-18-meta-samples-compat-0.5.88.md", + "RynthSuite/Changelog/2026-10-18-ub-it-meta-compat-0.5.86.md" + ], + "changelogSince": { + "rynthCore": "28fede68151c65934949d19edfa4c7efc4e15a1e", + "rynthSuite": "7877c869e77d3c251bdd3e7fb72030e979cf0e18", + "date": "" + } +} \ No newline at end of file diff --git a/installer/previous-release/previous-version.txt b/installer/previous-release/previous-version.txt new file mode 100644 index 0000000..d13755e --- /dev/null +++ b/installer/previous-release/previous-version.txt @@ -0,0 +1 @@ +2026.11.22.47 \ No newline at end of file diff --git a/last-built-version.txt b/last-built-version.txt new file mode 100644 index 0000000..fb633a7 --- /dev/null +++ b/last-built-version.txt @@ -0,0 +1 @@ +2026.10.20.14 diff --git a/loot-port-plan.txt b/loot-port-plan.txt new file mode 100644 index 0000000..9c2ab1c --- /dev/null +++ b/loot-port-plan.txt @@ -0,0 +1,204 @@ +# Plan: Port Loot System from NexSuite2 NexAi to NexCore NexAi + +## Context + +Porting the Loot subsystem (LootManager + VTankLootParser) from the old Decal-dependent NexAi at C:\Projects\NexSuite2\Plugins\NexAi\Loot\ to the new NexCore-based NexAi at C:\Projects\NexSuite\Plugins\NexCore.Plugin.NexAi\. The goal is to copy the files and adapt them to use NexCore's API instead of Decal's. + +### Decisions +- Salvage: Implement now — find VAs for SalvagePanelAdd/SalvagePanelSalvage in acclient.exe +- Loot evaluation: VTankLootParser IS the reimplemented VTank loot engine (handles UTL rule trees). Remove VTClassic/uTank2 code — our parser is the sole evaluator. Can add more VTank node types later if profiles need them. +- NeedsID: Always call RequestId on corpse items, wait up to assess window + +--- + +## Files to Copy + +Source (NexSuite2) -> Destination (NexSuite) +Plugins\NexAi\Loot\VTankLootParser.cs (284 ln) -> Plugins\NexCore.Plugin.NexAi\Loot\VTankLootParser.cs +Plugins\NexAi\Loot\LootManager.cs (1149 ln) -> Plugins\NexCore.Plugin.NexAi\Loot\LootManager.cs + +--- + +## Gap Analysis: What NexCore Has vs. What Loot Needs + +### Already Available (no engine work needed) + +Loot Requirement -> NexCore Equivalent +WorldObject.Id, .Name, .ObjectClass -> WorldObjectCache[id] returns WorldObject +WorldObject.Values(LongValueKey, default) -> WorldObject.Values() -> WorldObjectCache.GetIntProperty() -> TryGetObjectIntProperty() +WorldFilter.GetInventory() -> WorldObjectCache.GetInventory() +WorldFilter.GetLandscape() -> WorldObjectCache.GetLandscape() +WorldFilter.Distance(id1, id2) -> WorldObjectCache.Distance(id1, id2) +Actions.SelectItem(id) -> Host.SelectItem(uint) +Actions.UseItem(id, param) -> Host.UseObject(uint) +Actions.RequestId(id) -> Host.RequestId(uint) +Actions.MoveItem(...) -> Host.MoveItemExternal() + Host.MoveItemInternal() +CharacterFilter.Id -> Host.GetPlayerId() +AddChatText(text, color) -> Host.WriteToChat(text, chatType) +OnCreateObject / OnDeleteObject -> NexPluginBase virtual methods +OnUpdateObjectInventory -> NexPluginBase virtual method +OnViewObjectContents / OnStopViewing -> NexPluginBase virtual methods +OnBusyCountIncremented/Decremented -> NexPluginBase virtual methods +FellowshipTracker -> Already in NexCore.Plugin.NexAi/Combat/FellowshipTracker.cs + +### Plugin-Side Tracking (no engine changes) + +BusyState (is player idle?) -> Track _busyCount via OnBusyCountIncremented/Decremented events +OpenedContainer (which corpse is open?) -> Track _openedContainerId via OnViewObjectContents/OnStopViewing events + +--- + +## Must Add to NexCore Engine + SDK + +### 1. InqString — String Property Reading +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs + +Why: VTank rule type 1 (StringValueMatch) reads string properties. Corpse ownership reads StringValueKey 16 (LongDesc = "Killed by {name}."). + +- Find VA for CBaseQualities::InqString (near InqInt 0x00590C20 / InqBool 0x00590CA0) +- Add delegate: int InqString(IntPtr qualitiesPtr, uint stype, IntPtr* retval) (ThisCall) +- Add method: TryGetObjectStringProperty(uint objectId, uint stype, out string value) +- Wire through NexCoreApiNative.GetObjectStringPropertyFn -> NexCoreHost.TryGetObjectStringProperty() + +### 2. InqFloat — Float/Double Property Reading +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs + +Why: VTank rule types 4 & 5 (DoubleValKeyLE/GE) compare double properties (weapon damage variance, attack mod, etc.). + +- Find VA for CBaseQualities::InqFloat (near InqInt/InqBool) +- Add delegate + method: TryGetObjectFloatProperty(uint objectId, uint stype, out double value) +- Wire through SDK + +### 3. Container Contents API +File: src/NexCore.Engine/Compatibility/ClientObjectHooks.cs or UpdateObjectInventoryHooks.cs + +Why: After opening a corpse, need to enumerate items inside via GetByContainer(corpseId). + +- Expose existing GetExhaustiveContainedItemsList as SDK function: GetContainerContents(uint containerId, uint* outIds, int maxCount) -> int +- Wire through NexCoreApiNative.GetContainerContentsFn -> NexCoreHost.GetContainerContents() + +### 4. Salvage Panel APIs +File: New src/NexCore.Engine/Compatibility/SalvagePanelHooks.cs (or add to ClientHelperHooks) + +Why: Auto-salvage system needs SalvagePanelAdd(itemId) and SalvagePanelSalvage(). + +- Find VAs in acclient.exe APIManager__IAsheronsCallImpl_vtbl (documented as "declared but not yet validated") +- Implement as direct function calls via delegates +- Wire through SDK + +### 5. ObjectClass Expansion +File: Plugins/NexCore.Plugin.NexAi/Combat/AcStubs.cs + WorldObjectCache.cs + +Why: Loot system checks ObjectClass.Corpse, .Salvage, .Container, .Foci. + +- Expand AcObjectClass enum with Corpse, Container, Salvage, Foci values +- Add ITEM_TYPE constants: TYPE_CORPSE=0x00000020, TYPE_CONTAINER=0x00000040 +- Update WorldObjectCache.ClassifyByItemType() to detect these types + +### 6. String + Double Property Access on WorldObject +File: Plugins/NexCore.Plugin.NexAi/Combat/AcStubs.cs + +- Add StringValueKey enum (at minimum key 16 = LongDesc) +- Add DoubleValueKey enum +- Add WorldObject.Values(StringValueKey, default) -> delegates to cache -> SDK +- Add WorldObject.Values(DoubleValueKey, default) -> delegates to cache -> SDK +- Add WorldObjectCache.GetStringProperty() and WorldObjectCache.GetFloatProperty() methods + +--- + +## LootManager Adaptation Summary + +When copying LootManager.cs, these are the specific changes: + +Old (Decal) -> New (NexCore) +CoreManager _core + PluginHost _host -> NexCoreHost _host + WorldObjectCache _cache +_core.Actions.BusyState -> _busyCount > 0 (tracked via events) +_core.Actions.OpenedContainer -> _openedContainerId (tracked via events) +_core.Actions.SelectItem(id) -> _host.SelectItem((uint)id) +_core.Actions.UseItem(id, 0) -> _host.UseObject((uint)id) +_core.Actions.RequestId(id) -> _host.RequestId((uint)id) +_core.Actions.MoveItem(id, dest, slot, true) -> _host.MoveItemInternal((uint)id, (uint)dest, slot, 0) for stacking +_host.Actions.AddChatText(text, color) -> _host.WriteToChat(text, color) +_host.Actions.SalvagePanelAdd(id) -> _host.SalvagePanelAdd((uint)id) (new SDK method) +_host.Actions.SalvagePanelSalvage() -> _host.SalvagePanelSalvage() (new SDK method) +_core.WorldFilter[id] -> _cache[id] +_core.WorldFilter.GetByContainer(id) -> _host.GetContainerContents(id, ...) (new SDK method) +_core.WorldFilter.GetInventory() -> _cache.GetInventory() +_core.WorldFilter.GetLandscape() -> _cache.GetLandscape() +_core.WorldFilter.Distance(a, b) -> _cache.Distance(a, b) +_core.CharacterFilter.Id -> (int)_host.GetPlayerId() +_core.CharacterFilter.Name -> _host.TryGetObjectName(_host.GetPlayerId(), out name) +VTClassic.LootCore (Path 1) -> REMOVED — VTankLootParser handles all UTL evaluation +uTank2.PluginCore.PC.* (Path 3) -> REMOVED — single evaluation path +FLootPluginQueryNeedsID(id) -> Always true — always RequestId +WorldObject.Values((StringValueKey)k, "") -> wo.Values((StringValueKey)k, "") (new method on WorldObject) +WorldObject.Values((DoubleValueKey)k, 0.0) -> wo.Values((DoubleValueKey)k, 0.0) (new method on WorldObject) + +--- + +## Implementation Order + +### Phase 1: Engine — Property APIs +1. Find VAs for CBaseQualities::InqString and CBaseQualities::InqFloat +2. Add to ClientObjectHooks.cs: delegates, TryGetObjectStringProperty(), TryGetObjectFloatProperty() +3. Add to NexCoreApiNative.cs: GetObjectStringPropertyFn, GetObjectFloatPropertyFn +4. Add to NexCoreHost.cs: wrapper methods +5. Wire function pointers in EntryPoint.cs + +### Phase 2: Engine — Container Contents API +1. Add GetContainerContents() wrapper around existing GetExhaustiveContainedItemsList +2. Wire through SDK + +### Phase 3: Engine — Salvage Panel APIs +1. Find VAs for salvage panel functions in acclient.exe vtable +2. Implement + wire through SDK + +### Phase 4: Plugin — Expand Type System +1. AcStubs.cs: Add StringValueKey, DoubleValueKey enums +2. AcStubs.cs: Expand AcObjectClass (Corpse, Container, Salvage, Foci) +3. WorldObject: Add Values(StringValueKey), Values(DoubleValueKey) methods +4. WorldObjectCache: Add GetStringProperty(), GetFloatProperty(), expand classification + +### Phase 5: Plugin — Copy & Adapt Loot Files +1. Copy VTankLootParser.cs -> update namespace, replace Decal types with local types +2. Copy LootManager.cs -> apply all substitutions from table above +3. Simplify to single loot evaluation path (VTankLootParser only) +4. Always-RequestId for NeedsID + +### Phase 6: Plugin — Integration +1. Wire LootManager into NexAiPlugin.cs +2. Add settings to LegacyUiSettings.cs +3. Add chat commands for profile loading + +--- + +## Key Files to Modify + +### Engine (C:\Projects\nexcore\src\NexCore.Engine\) +- Compatibility/ClientObjectHooks.cs — InqString, InqFloat +- Compatibility/UpdateObjectInventoryHooks.cs — GetContainerContents export +- Compatibility/SalvagePanelHooks.cs — NEW: salvage APIs +- EntryPoint.cs — Wire new API function pointers + +### SDK (C:\Projects\nexcore\src\NexCore.PluginSdk\) +- NexCoreApiNative.cs — New function pointer fields +- NexCoreHost.cs — New wrapper methods + +### Plugin (C:\Projects\NexSuite\Plugins\NexCore.Plugin.NexAi\) +- Combat/AcStubs.cs — StringValueKey, DoubleValueKey, expanded ObjectClass +- Combat/WorldObjectCache.cs — Classification expansion, container tracking, new property methods +- Loot/VTankLootParser.cs — NEW (copy + adapt) +- Loot/LootManager.cs — NEW (copy + adapt) +- NexAiPlugin.cs — Wire LootManager +- LegacyUi/LegacyUiSettings.cs — Loot settings + +--- + +## Verification +1. cd src\NexCore.Engine && dotnet publish -c Release — engine builds +2. cd Plugins\NexCore.Plugin.NexAi && dotnet publish -c Release — plugin builds +3. Deploy to C:\Games\NexCore\ + inject into AC client +4. Load a VTank UTL profile via /na lootprofile <path> +5. Verify: corpse detection -> item scanning -> RequestId -> loot evaluation -> pickup +6. Verify: salvage queue processes items correctly +7. Check %USERPROFILE%\Desktop\NexCore.log for errors diff --git a/native/Loader/Loader.c b/native/Loader/Loader.c index 396d25c..fcf3344 100644 --- a/native/Loader/Loader.c +++ b/native/Loader/Loader.c @@ -13,9 +13,10 @@ // reload, so a reload gives its memory back. // // Either way the loader owns the reload event, the file watcher, the address-space -// guard, the reload cap (MaxHotReloads per client) and a MinHook facade (Hooks.c): -// every hook is installed once, through a permanent stub, and a reload only re-points -// the stub. For the managed engine it also sets up CoreCLR's crash dumps (Logs\dumps). +// guard, the reload cap (MaxHotReloads per client), the in-world MayHotReload hold +// (2.2+), and a MinHook facade (Hooks.c): every hook is installed once, through a +// permanent stub, and a reload only re-points the stub. For the managed engine it +// also sets up CoreCLR's crash dumps (Logs\dumps). // ============================================================================ #include "Loader.h" @@ -30,6 +31,9 @@ #define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused" #define ENGINE_MAXRELOADS_EXPORT "RynthCoreMaxHotReloads" #define ENGINE_CAPPED_EXPORT "RynthCoreReloadCapped" +// 1 = reload now, 0 = wait (in-world). Missing export = old engine, proceed. +#define ENGINE_MAYRELOAD_EXPORT "RynthCoreMayHotReload" +#define MAY_RELOAD_POLL_MS 2000 #ifndef LOG_DIR // the offline tests (tools\Loader*Tests) log into their own folder #define LOG_DIR "C:\\Games\\RynthCore\\Logs" #define LOG_PARENT "C:\\Games\\RynthCore" @@ -64,6 +68,7 @@ typedef unsigned int (__stdcall *engine_u32_fn)(void* param); typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb); typedef int (__stdcall *engine_max_reloads_fn)(void); typedef unsigned int (__stdcall *engine_capped_fn)(int reloads, int cap); +typedef int (__stdcall *engine_may_reload_fn)(void); static volatile LONG g_initialized; static char g_loaderDir[MAX_PATH]; @@ -534,13 +539,58 @@ static DWORD WINAPI ReloadWatcher(LPVOID unused) LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced."); continue; } + + // Hold before Shutdown while the engine says the player is still in the world + // (RynthCoreMayHotReload). The game keeps running on this generation; FileWatcher + // signals coalesce on the auto-reset event until we finish. Missing export = go now + // (old engines); their Shutdown path also waits in-world since 2026-10-16. + { + engine_may_reload_fn may = (engine_may_reload_fn)EngineExport(ENGINE_MAYRELOAD_EXPORT); + int loggedHold = 0; + while (may && may() == 0) { + if (!loggedHold) { + LoaderLog("INF", "ReloadWatcher: holding reload - engine says not safe yet (in-world); " + "will retry every %d ms until logout / character select.", MAY_RELOAD_POLL_MS); + loggedHold = 1; + } + Sleep(MAY_RELOAD_POLL_MS); + // Cap / address space can change while we wait; refuse rather than tear down late. + reloadsDone = g_initCount - 1; + cap = CurrentReloadCap(); + if (ReloadCapReached(reloadsDone, cap)) { + LoaderLog("WRN", "ReloadWatcher: reload REFUSED while holding for the world - hot reload " + "cap reached (%d of %d). Staying on gen %d.", reloadsDone, cap, g_initCount); + engine_capped_fn capped = (engine_capped_fn)EngineExport(ENGINE_CAPPED_EXPORT); + if (capped) capped(reloadsDone, cap); + InterlockedExchange(&g_reloadInFlight, 0); + goto next_signal; + } + freeMb = LoaderFreeAddressSpaceMb(&largestMb); + shortOf = ReloadSpaceShort(g_engineIsManaged, freeMb, largestMb); + if (shortOf) { + LoaderLog("WRN", "ReloadWatcher: reload REFUSED while holding for the world - address space " + "short (free %ld MB, largest %ld MB).", freeMb, largestMb); + engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT); + if (refused) refused((int)(shortOf == 1 ? freeMb : largestMb)); + InterlockedExchange(&g_reloadInFlight, 0); + goto next_signal; + } + } + if (loggedHold) + LoaderLog("INF", "ReloadWatcher: engine says reload is safe now; proceeding."); + } + Reload(); g_lastReloadDone = GetTickCount64(); InterlockedExchange(&g_reloadInFlight, 0); - int drained = 0; - while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++; - if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained); + { + int drained = 0; + while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++; + if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained); + } + next_signal: + ; } } diff --git a/native/Loader/Loader.h b/native/Loader/Loader.h index 18e1622..7e62493 100644 --- a/native/Loader/Loader.h +++ b/native/Loader/Loader.h @@ -2,7 +2,7 @@ #define WIN32_LEAN_AND_MEAN #include <windows.h> -#define LOADER_VERSION "2.1" +#define LOADER_VERSION "2.2" // Loader.c void LoaderLog(const char* level, const char* fmt, ...); diff --git a/scripts/Fetch-Dxvk.ps1 b/scripts/Fetch-Dxvk.ps1 new file mode 100644 index 0000000..867fc11 --- /dev/null +++ b/scripts/Fetch-Dxvk.ps1 @@ -0,0 +1,67 @@ +# Fetch-Dxvk.ps1 +# Downloads the latest official DXVK release and stages x32/d3d9.dll into a cache folder +# (default: C:\Games\RynthCore\Runtime\dxvk). Used by the launcher's "Fetch / update DXVK" +# (C# twin: DxvkPackageService) and by Build-Installer.ps1 to seed the installer payload. +# +# .\scripts\Fetch-Dxvk.ps1 +# .\scripts\Fetch-Dxvk.ps1 -Target "D:\asherons call-int code\RynthCore\installer\staging\core\Runtime\dxvk" +# .\scripts\Fetch-Dxvk.ps1 -Version 3.1.1 # pin a tag (without leading v) + +param( + [string]$Target = "C:\Games\RynthCore\Runtime\dxvk", + [string]$Version = "" # empty = latest from GitHub +) + +$ErrorActionPreference = "Stop" + +function Get-LatestDxvkTag { + $headers = @{ "User-Agent" = "RynthCore-Fetch-Dxvk/1.0"; "Accept" = "application/vnd.github+json" } + $rel = Invoke-RestMethod -Uri "https://api.github.com/repos/doitsujin/dxvk/releases/latest" -Headers $headers + return ($rel.tag_name -replace '^v', '') +} + +function Get-DxvkTarballUrl([string]$tag) { + $headers = @{ "User-Agent" = "RynthCore-Fetch-Dxvk/1.0"; "Accept" = "application/vnd.github+json" } + $rel = Invoke-RestMethod -Uri "https://api.github.com/repos/doitsujin/dxvk/releases/tags/v$tag" -Headers $headers + $asset = $rel.assets | Where-Object { + $_.name -like "dxvk-*.tar.gz" -and $_.name -notlike "*native*" + } | Select-Object -First 1 + if (-not $asset) { throw "No dxvk-*.tar.gz asset on release v$tag" } + return @{ Url = $asset.browser_download_url; Name = $asset.name } +} + +if ([string]::IsNullOrWhiteSpace($Version)) { + $Version = Get-LatestDxvkTag + Write-Host "Latest DXVK tag: $Version" +} + +$asset = Get-DxvkTarballUrl $Version +$stage = Join-Path $env:TEMP ("rynthcore-dxvk-" + [guid]::NewGuid().ToString("N")) +New-Item -ItemType Directory -Force -Path $stage | Out-Null +$tarball = Join-Path $stage $asset.Name +Write-Host "Downloading $($asset.Url) ..." +Invoke-WebRequest -Uri $asset.Url -OutFile $tarball -UseBasicParsing + +$extract = Join-Path $stage "extract" +New-Item -ItemType Directory -Force -Path $extract | Out-Null +tar -xzf $tarball -C $extract + +$src = Get-ChildItem $extract -Recurse -Filter "d3d9.dll" | + Where-Object { $_.Directory.Name -eq "x32" } | + Select-Object -First 1 +if (-not $src) { throw "x32/d3d9.dll not found in archive" } + +New-Item -ItemType Directory -Force -Path $Target | Out-Null +Copy-Item $src.FullName (Join-Path $Target "d3d9.dll") -Force +$utf8 = New-Object System.Text.UTF8Encoding $false +[IO.File]::WriteAllText((Join-Path $Target "version.txt"), $Version, $utf8) +$conf = @" +# Managed by RynthCore (launcher Enable DXVK). Safe to delete with the toggle off. +dxgi.deferSurfaceCreation = True +d3d9.maxFrameLatency = 1 +d3d9.presentInterval = 1 +"@ +[IO.File]::WriteAllText((Join-Path $Target "dxvk.conf"), $conf.TrimStart() + "`n", $utf8) + +Write-Host "DXVK $Version staged at $Target" +Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue diff --git a/scripts/Run-AllTests.ps1 b/scripts/Run-AllTests.ps1 index a1314e6..53da5b3 100644 --- a/scripts/Run-AllTests.ps1 +++ b/scripts/Run-AllTests.ps1 @@ -14,6 +14,9 @@ (2026-10-22: tests only ran when someone remembered to; a release went out with Missile Crafting broken while the tests that existed passed). + Each test program is also checked for test groups that exist but never run (a class with a static + Register(...) that is never registered, a static RunXxx() that is never called): those fail the run. + Every folder whose name contains "Test" is run unless $Skip below names it with a reason; skipped ones are listed in the summary, never dropped silently. Each program's output goes to <LogDir>\<repo>.<name>.log, and the summary (also <LogDir>\summary.txt) shows each failure's last lines. @@ -75,6 +78,48 @@ foreach ($r in $repos) { } if ($Only.Count -gt 0 -and $tests.Count -eq 0 -and $skipped.Count -eq 0) { throw "-Only matched no test folder: $($Only -join ', ')" } +# Tests that exist but never run (2026-10-30: RynthAiHostTests' RingEscapeTests and RingEvadeTests +# had stopped being registered in a merge, and PetDamageTintTests never was; their checks silently +# didn't run). In each test program: every class with a static Register(...) must be registered +# (Name.Register( somewhere in the program), and every parameterless "static void RunXxx()" group +# must be called. A miss fails the run as "<repo>.<folder> (registration)". +function Find-UnrunTests([string]$dir) { + $files = @(Get-ChildItem $dir -Recurse -Filter *.cs | Where-Object { $_.FullName -notmatch '[\\/](bin|obj)[\\/]' }) + if ($files.Count -eq 0) { return @() } + $src = @{} + foreach ($f in $files) { $src[$f.FullName] = Get-Content $f.FullName -Raw } + $all = ($src.Values -join "`n") + $miss = [System.Collections.Generic.List[string]]::new() + foreach ($kv in $src.GetEnumerator()) { + $text = $kv.Value + if ($text -notmatch 'static\s+void\s+Register\s*\(\s*Runner\b') { } + else { + foreach ($m in [regex]::Matches($text, '(?:internal|public)\s+(?:static\s+)?(?:sealed\s+)?(?:partial\s+)?class\s+(\w+)')) { + $cls = $m.Groups[1].Value + # the class's own Register: the first "static void Register(" after its declaration, before the next class + $rest = $text.Substring($m.Index + $m.Length) + $next = [regex]::Match($rest, '(?:internal|public)\s+(?:static\s+)?(?:sealed\s+)?(?:partial\s+)?class\s+\w+') + $body = if ($next.Success) { $rest.Substring(0, $next.Index) } else { $rest } + if ($body -match 'static\s+void\s+Register\s*\(\s*Runner\b' -and $all -notmatch "\b$cls\.Register\s*\(") { + $miss.Add("$cls.Register(...) is never called ($([IO.Path]::GetRelativePath($dir, $kv.Key)))") + } + } + } + foreach ($m in [regex]::Matches($text, 'static\s+void\s+(Run[A-Z]\w*)\s*\(\s*\)')) { + $name = $m.Groups[1].Value + if ($all -notmatch "\b$name\s*\(\s*\)\s*;") { $miss.Add("$name() is never called ($([IO.Path]::GetRelativePath($dir, $kv.Key)))") } + } + } + return $miss +} + +$registration = [System.Collections.Generic.List[object]]::new() +foreach ($t in $tests) { + if ($t.Kind -ne "dotnet") { continue } + $miss = @(Find-UnrunTests $t.Dir) + if ($miss.Count -gt 0) { $registration.Add([pscustomobject]@{ Id = "$($t.Id) (registration)"; Lines = $miss }) } +} + # Runs one program with its output captured; returns @{ Code; TimedOut; Output }. function Invoke-Captured([string]$file, [string[]]$argList, [string]$cwd) { $psi = [System.Diagnostics.ProcessStartInfo]::new($file) @@ -138,6 +183,13 @@ foreach ($t in $tests) { $results.Add([pscustomobject]@{ Id = $t.Id; Status = $status; Seconds = [math]::Round($sw.Elapsed.TotalSeconds); Log = $log }) } +foreach ($g in $registration) { + $log = Join-Path $LogDir "$($g.Id -replace '[^\w.\-]', '_').log" + Set-Content $log (@("Tests that exist but never run:") + $g.Lines) + Write-Host ("{0}: {1} test group(s) never run" -f $g.Id, $g.Lines.Count) -ForegroundColor Red + $results.Add([pscustomobject]@{ Id = $g.Id; Status = "NOT RUN"; Seconds = 0; Log = $log }) +} + $failed = @($results | Where-Object Status -ne "PASS") $summary = [System.Collections.Generic.List[string]]::new() $summary.Add("RynthCore $(git -C $RynthCoreRoot rev-parse --short HEAD) ($RynthCoreRoot), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD) ($RynthSuiteRoot), RynthServers $(git -C $RynthServersRoot rev-parse --short HEAD) ($RynthServersRoot)") diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 47ca5e1..5d62049 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -23,14 +23,19 @@ internal partial class AccountProfileDialog : Window private bool _loginAsChanged; private bool _loadingLoginAs; + // acclient.exe's path: Snapshot copies the UserPreferences.ini this install uses (the game folder's). + private readonly string? _acClientPath; + /// <param name="knownCharactersFor">(account name, server name) -> the characters known for it.</param> + /// <param name="acClientPath">acclient.exe, to find the live UserPreferences.ini.</param> public AccountProfileDialog(LaunchAccountProfile profile, List<LaunchServerProfile> servers, - Func<string, string, List<string>> knownCharactersFor) + Func<string, string, List<string>> knownCharactersFor, string? acClientPath = null) { _profile = profile; _servers = servers; _knownCharactersFor = knownCharactersFor; _passwordReveal = SavedPasswordReveal.For(profile); + _acClientPath = acClientPath; InitializeComponent(); ServerComboBox.ItemsSource = _servers.Select(s => s.DisplayName).ToList(); @@ -152,10 +157,7 @@ internal partial class AccountProfileDialog : Window stashPath = Path.Combine(appdata, "RynthCore", "prefs", $"{safeName}.ini"); } - string livePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "Asheron's Call", - "UserPreferences.ini"); + string livePath = AcClientLaunchSettingsService.LivePrefsPath(_acClientPath); if (!File.Exists(livePath)) { diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index c275320..34ae616 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -227,6 +227,7 @@ <ListBox Grid.Row="2" x:Name="AccountProfilesList" MinHeight="200" + MaxHeight="280" Background="#0F161D" BorderBrush="#243742" Foreground="#EAF0F4" @@ -432,6 +433,18 @@ <CheckBox x:Name="AllowMultipleClientsCheckBox" Content="Allow multiple clients" /> <CheckBox x:Name="SkipIntroVideosCheckBox" Content="Skip intro videos" /> <CheckBox x:Name="SkipLoginLogosCheckBox" Content="Skip login logos" /> + <CheckBox x:Name="EnableDxvkCheckBox" + Content="Enable DXVK (Vulkan D3D9) for AC clients" + ToolTip.Tip="Copies DXVK's 32-bit d3d9.dll next to acclient.exe so AC renders through Vulkan. Rynth forces the software overlay path under DXVK. Off by default. Requires a restart of AC after toggle. Package: <RynthCore>\Runtime\dxvk\ (installer or Fetch)." /> + <StackPanel Orientation="Horizontal" Spacing="8"> + <Button x:Name="FetchDxvkButton" + Content="Fetch / update DXVK" + ToolTip.Tip="Downloads the latest official DXVK release (x32 d3d9.dll) into Runtime\dxvk. Then enable the checkbox (or re-launch) to install it beside AC." /> + <TextBlock x:Name="DxvkCacheStatusText" + VerticalAlignment="Center" + Foreground="#9AA8B3" + Text="DXVK: not cached" /> + </StackPanel> <CheckBox x:Name="AutoInjectAfterLaunchCheckBox" Content="Auto inject after launch" /> <CheckBox x:Name="WatchForAcStartCheckBox" Content="Auto-inject into externally-launched AC" diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 1fa1b0b..abe6724 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -411,6 +411,10 @@ internal partial class MainWindow : Window AllowMultipleClientsCheckBox.IsChecked = _settings.AllowMultipleClients; SkipIntroVideosCheckBox.IsChecked = _settings.SkipIntroVideos; SkipLoginLogosCheckBox.IsChecked = _settings.SkipLoginLogos; + EnableDxvkCheckBox.IsChecked = _settings.EnableDxvk; + RefreshDxvkCacheStatus(); + EnableDxvkCheckBox.IsCheckedChanged += OnEnableDxvkChanged; + FetchDxvkButton.Click += async (_, _) => await FetchDxvkAsync(); AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch; AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch; WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart; @@ -448,6 +452,73 @@ internal partial class MainWindow : Window } } + private void RefreshDxvkCacheStatus() + { + if (DxvkCacheStatusText == null) + return; + if (DxvkPackageService.IsCached) + { + string ver = DxvkPackageService.CachedVersion ?? "?"; + DxvkCacheStatusText.Text = $"DXVK cache: {ver}"; + } + else + { + DxvkCacheStatusText.Text = "DXVK: not cached"; + } + } + + private async void OnEnableDxvkChanged(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e) + { + bool enable = EnableDxvkCheckBox.IsChecked == true; + _settings.EnableDxvk = enable; + SaveSettings(); + + string acPath = AcClientPathTextBox.Text?.Trim() ?? _settings.AcClientPath; + if (enable && !DxvkPackageService.IsCached) + { + AppendActivity("DXVK enabled — cache empty, fetching latest…"); + string? ver = await DxvkPackageService.EnsureCachedOrFetchAsync(AppendActivity); + RefreshDxvkCacheStatus(); + if (ver == null) + { + AppendActivity("DXVK: could not fetch a package; leave the checkbox on and use Fetch later, or reinstall."); + return; + } + } + + DxvkPackageService.ApplyToClient(acPath, enable, AppendActivity); + RefreshDxvkCacheStatus(); + AppendActivity(enable + ? "DXVK on — relaunch AC clients to load the drop-in d3d9.dll." + : "DXVK off — relaunch AC clients to return to System32 d3d9."); + } + + private async Task FetchDxvkAsync() + { + try + { + FetchDxvkButton.IsEnabled = false; + AppendActivity("Fetching latest DXVK (x32) from GitHub…"); + string version = await DxvkPackageService.EnsureLatestAsync(new Progress<string>(AppendActivity)); + RefreshDxvkCacheStatus(); + AppendActivity($"DXVK {version} ready in {DxvkPackageService.CacheDirectory}."); + if (EnableDxvkCheckBox.IsChecked == true) + { + string acPath = AcClientPathTextBox.Text?.Trim() ?? _settings.AcClientPath; + DxvkPackageService.ApplyToClient(acPath, enable: true, AppendActivity); + AppendActivity("DXVK cache applied to the current AC client path (relaunch clients)."); + } + } + catch (Exception ex) + { + AppendActivity($"DXVK fetch failed: {ex.Message}"); + } + finally + { + FetchDxvkButton.IsEnabled = true; + } + } + private void BuildPluginLoadout() { PluginLoadoutPanel.Children.Clear(); @@ -878,7 +949,7 @@ internal partial class MainWindow : Window // Defaults to the server selected in the list (a new server's first account), not the // first profile, which RefreshLaunchTargets would otherwise assign. var draft = new RynthCore.App.LaunchAccountProfile { ServerId = GetSelectedServer()?.Id ?? string.Empty }; - var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters); + var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters, _settings.AcClientPath); bool? accepted = await dialog.ShowDialog<bool?>(this); if (accepted != true) return; @@ -899,7 +970,7 @@ internal partial class MainWindow : Window return; LaunchAccountProfile draft = selected.Clone(); - var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters); + var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters, _settings.AcClientPath); bool? accepted = await dialog.ShowDialog<bool?>(this); if (accepted != true) return; @@ -1664,6 +1735,7 @@ internal partial class MainWindow : Window _settings.AllowMultipleClients = AllowMultipleClientsCheckBox.IsChecked == true; _settings.SkipIntroVideos = SkipIntroVideosCheckBox.IsChecked == true; _settings.SkipLoginLogos = SkipLoginLogosCheckBox.IsChecked == true; + _settings.EnableDxvk = EnableDxvkCheckBox.IsChecked == true; _settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true; _settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true; _settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true; @@ -1684,6 +1756,10 @@ internal partial class MainWindow : Window _settings.EnabledPluginIds.Add("rynthcore-engine"); SaveSettings(); SyncPluginPathsToEngineSettings(); + // Keep the AC folder in sync with the DXVK toggle even when not launching yet. + string acPath = AcClientPathTextBox.Text?.Trim() ?? _settings.AcClientPath; + DxvkPackageService.ApplyToClient(acPath, _settings.EnableDxvk, appendActivity ? AppendActivity : null); + RefreshDxvkCacheStatus(); if (appendActivity) { AppendActivity($"Logging level saved: {_settings.LoggingLevel}."); @@ -1904,9 +1980,9 @@ internal partial class MainWindow : Window try { SetOperationState(true); - // acclient's own settings (multiple clients, intro videos); nothing a Headless launch reads. + // acclient's own settings (multiple clients, intro videos, DXVK); nothing a Headless launch reads. if (accountsToLaunch.Any(a => a.InjectionMode != InjectionMode.Headless)) - _launchSettings.Apply(acPath, _settings.AllowMultipleClients, _settings.SkipIntroVideos, AppendActivity); + _launchSettings.Apply(acPath, _settings.AllowMultipleClients, _settings.SkipIntroVideos, _settings.EnableDxvk, AppendActivity); AppendActivity($"Preparing {launchLabel}."); HashSet<string> activeAccountKeys = GetActiveAccountKeys(); @@ -2048,12 +2124,14 @@ internal partial class MainWindow : Window { string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); + // Per-account graphics profiles write different values into the one INI: serialize like a swap. + bool needsLock = needsPrefsSwap || GraphicsNeedsLaunchLock(); string entryAccountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); int crashHistCount = _crashHistoryByAccount.TryGetValue(entryAccountKey, out List<DateTime>? hist0) ? hist0.Count : 0; LauncherDiag.Info($"LaunchOneInjected ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count} crashHist={crashHistCount}"); - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneInjected acquiring _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); await _userPrefsSwapLock.WaitAsync(); @@ -2062,7 +2140,9 @@ internal partial class MainWindow : Window try { - PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath, acPath) : null; + // This account's RynthAi graphics profile over whatever the INI holds now (AC rewrites it on exit). + ApplyGraphicsForLaunch(acPath, launchContext); InjectionResult result = await Task.Run(() => _injector.LaunchSuspendedAndInject( @@ -2100,12 +2180,12 @@ internal partial class MainWindow : Window AppendActivity($"Launch failed for {launchSummary}: {result.Summary}"); } - if (needsPrefsSwap) + if (needsLock) await Task.Delay(UserPrefsSettleDelay); } finally { - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneInjected releasing _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); _userPrefsSwapLock.Release(); @@ -2126,12 +2206,14 @@ internal partial class MainWindow : Window { string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); + // Per-account graphics profiles write different values into the one INI: serialize like a swap. + bool needsLock = needsPrefsSwap || GraphicsNeedsLaunchLock(); string entryAccountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName); int crashHistCount = _crashHistoryByAccount.TryGetValue(entryAccountKey, out List<DateTime>? hist0) ? hist0.Count : 0; LauncherDiag.Info($"LaunchOneDecal ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count} crashHist={crashHistCount}"); - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneDecal acquiring _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); await _userPrefsSwapLock.WaitAsync(); @@ -2140,7 +2222,9 @@ internal partial class MainWindow : Window try { - PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath, acPath) : null; + // This account's RynthAi graphics profile over whatever the INI holds now (AC rewrites it on exit). + ApplyGraphicsForLaunch(acPath, launchContext); // enginePath != null: "Decal + RynthCore" - Decal is injected first, then the // RynthCore loader, before the client resumes. @@ -2181,12 +2265,12 @@ internal partial class MainWindow : Window AppendActivity($"Decal launch failed for {launchSummary}: {result.Summary}"); } - if (needsPrefsSwap) + if (needsLock) await Task.Delay(UserPrefsSettleDelay); } finally { - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneDecal releasing _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); _userPrefsSwapLock.Release(); @@ -2205,10 +2289,12 @@ internal partial class MainWindow : Window { string resolvedPrefsPath = ResolveUserPrefsPath(account, launchContext.ServerName); bool needsPrefsSwap = !string.IsNullOrEmpty(resolvedPrefsPath) && File.Exists(resolvedPrefsPath); + // Per-account graphics profiles write different values into the one INI: serialize like a swap. + bool needsLock = needsPrefsSwap || GraphicsNeedsLaunchLock(); LauncherDiag.Info($"LaunchOneNoInject ENTRY account='{launchContext.AccountName}' needsPrefsSwap={needsPrefsSwap} semCount={_userPrefsSwapLock.CurrentCount} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count}"); - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneNoInject acquiring _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); await _userPrefsSwapLock.WaitAsync(); @@ -2217,7 +2303,9 @@ internal partial class MainWindow : Window try { - PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath, acPath) : null; + // This account's RynthAi graphics profile over whatever the INI holds now (AC rewrites it on exit). + ApplyGraphicsForLaunch(acPath, launchContext); Process? proc = null; Exception? launchEx = null; @@ -2261,12 +2349,12 @@ internal partial class MainWindow : Window } AppendActivity($"Launched AC (no injection) using {launchSummary}."); - if (needsPrefsSwap) + if (needsLock) await Task.Delay(UserPrefsSettleDelay); } finally { - if (needsPrefsSwap) + if (needsLock) { LauncherDiag.Info($"LaunchOneNoInject releasing _userPrefsSwapLock (semCount={_userPrefsSwapLock.CurrentCount})"); _userPrefsSwapLock.Release(); @@ -5293,9 +5381,10 @@ internal partial class MainWindow : Window /// Copies the account's saved UserPreferences.ini over the live one (caller holds /// _userPrefsSwapLock) and returns what was swapped, or null when nothing was. /// </summary> - private PrefsSwapLaunch? ApplyPrefsSwap(LaunchAccountProfile account, string? serverName, string resolvedPrefsPath) + private PrefsSwapLaunch? ApplyPrefsSwap(LaunchAccountProfile account, string? serverName, string resolvedPrefsPath, string acPath) { - UserPrefsSwap? swap = _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); + // Into the INI this install's clients actually read (the game folder's when it has one). + UserPrefsSwap? swap = _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity, acPath); if (swap == null) return null; @@ -5305,6 +5394,50 @@ internal partial class MainWindow : Window return new PrefsSwapLaunch(swap, generation, isOverride, ResolveLegacyUserPrefsPath(account)); } + /// <summary> + /// True when any account has a RynthAi graphics profile (graphics.json): accounts started + /// together would write different values into the one UserPreferences.ini, so the launch takes + /// _userPrefsSwapLock and waits for AC to read it before the next account writes. + /// </summary> + private static bool GraphicsNeedsLaunchLock() + { + try + { + return RynthCore.Graphics.AcGraphicsProfiles.Load(RynthCore.Graphics.AcGraphicsPrefs.ConfigPath).Accounts.Count > 0; + } + catch { return false; } + } + + /// <summary> + /// Writes the launching account's RynthAi graphics profile (Settings > Graphics, graphics.json) into + /// the UserPreferences.ini files AC reads, just before the client starts (after any per-account prefs + /// swap, so RynthAi's values win). Keys left on "AC's choice" are not touched; an account with no + /// profile changes nothing. Never throws. + /// </summary> + private void ApplyGraphicsForLaunch(string acPath, LaunchContextRecord launchContext) + { + try + { + var all = RynthCore.Graphics.AcGraphicsProfiles.Load(RynthCore.Graphics.AcGraphicsPrefs.ConfigPath); + string accountKey = RynthCore.Graphics.AcGraphicsPrefs.AccountKey(launchContext.ServerName, launchContext.AccountName); + RynthCore.Graphics.AcGraphicsConfig cfg = all.For(accountKey); + if (!cfg.HasAny) + return; + Dictionary<string, string> values = cfg.IniValues(); + foreach (string ini in RynthCore.Graphics.AcGraphicsPrefs.IniPaths(Path.GetDirectoryName(acPath))) + { + List<string> changed = RynthCore.Graphics.AcPrefsIni.Apply(ini, values); + if (changed.Count > 0) + AppendActivity($"Graphics profile applied for account {launchContext.AccountName}: {string.Join(", ", changed)} ({Path.GetFileName(Path.GetDirectoryName(ini))})."); + LauncherDiag.Info($"Graphics: {ini} account='{accountKey}' changed=[{string.Join(", ", changed)}]"); + } + } + catch (Exception ex) + { + AppendActivity($"Graphics settings not applied: {ex.Message}"); + } + } + /// <summary>Remembers which swap a launched client started with (no-op without a swap).</summary> private void TrackPrefsSwap(int pid, PrefsSwapLaunch? prefsSwap) { @@ -5378,10 +5511,8 @@ internal partial class MainWindow : Window if (string.IsNullOrEmpty(stashPath)) return; - string livePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "Asheron's Call", - "UserPreferences.ini"); + // The INI the session actually wrote (the game folder's when it has one). + string livePath = AcClientLaunchSettingsService.LivePrefsPath(_settings.AcClientPath); if (!File.Exists(livePath)) return; diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 00e1545..3fd6431 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -1,12 +1,12 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.5. + <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.8. No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the product version derived from it is what the launcher/About show (BuildVersion.Format). --> - <Version>0.1.6</Version> - <AssemblyVersion>0.1.6.0</AssemblyVersion> - <FileVersion>0.1.6.0</FileVersion> + <Version>0.1.9</Version> + <AssemblyVersion>0.1.9.0</AssemblyVersion> + <FileVersion>0.1.9.0</FileVersion> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows7.0</TargetFramework> <PlatformTarget>x86</PlatformTarget> @@ -60,7 +60,10 @@ <Compile Include="..\RynthCore.App\CrashDumpWriterRule.cs" Link="Shared\CrashDumpWriterRule.cs" /> <Compile Include="..\RynthCore.App\AcWindowPlacementRule.cs" Link="Shared\AcWindowPlacementRule.cs" /> <Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" /> + <Compile Include="..\RynthCore.App\DxvkPackageService.cs" Link="Shared\DxvkPackageService.cs" /> <Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" /> + <!-- RynthAi's Settings > Graphics: graphics.json, enforced on UserPreferences.ini before each launch. --> + <Compile Include="..\RynthCore.Engine\Graphics\AcGraphicsPrefs.cs" Link="Shared\AcGraphicsPrefs.cs" /> <Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" /> <Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" /> <Compile Include="..\RynthCore.App\LaunchContextStore.cs" Link="Shared\LaunchContextStore.cs" /> diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.cs b/src/RynthCore.App.Avalonia/RynthUpdater.cs index 50d27a7..50f4506 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.cs @@ -197,10 +197,14 @@ internal sealed partial class RynthUpdater Manifest manifest = ParseManifest(payload); // Replay guard: a signed but older feed (an attacker re-serving last month's) is refused. - int floor = Math.Max(ReadHighestRelease(), InstalledCoreRelease); - if (manifest.Release < floor) - throw new InvalidDataException($"the feed is older ({manifest.Release}) than one already seen ({floor})"); - if (manifest.Release > ReadHighestRelease()) + // Floor is only the highest *feed* we have already accepted — not InstalledCoreRelease. + // A local/test install ahead of the published feed (e.g. 2026.10.16.18 with feed still + // at 2026.10.15.7) must still check: there is no core update, but plugins and the card + // should not hard-error as "Couldn't check for updates". + int seenFloor = ReadHighestRelease(); + if (manifest.Release < seenFloor) + throw new InvalidDataException($"the feed is older ({manifest.Release}) than one already seen ({seenFloor})"); + if (manifest.Release > seenFloor) WriteHighestRelease(manifest.Release); var statuses = new List<PluginStatus>(); diff --git a/src/RynthCore.App/AcClientLaunchSettingsService.cs b/src/RynthCore.App/AcClientLaunchSettingsService.cs index 77720c4..c267f7a 100644 --- a/src/RynthCore.App/AcClientLaunchSettingsService.cs +++ b/src/RynthCore.App/AcClientLaunchSettingsService.cs @@ -13,26 +13,67 @@ internal sealed class AcClientLaunchSettingsService private const string IntroVideoFileName = "turbine_logo_ac.avi"; private const string DisabledIntroVideoSuffix = ".rynthcore-disabled"; - public void Apply(string acClientPath, bool allowMultipleClients, bool skipIntroVideos, Action<string>? log = null) + public void Apply( + string acClientPath, + bool allowMultipleClients, + bool skipIntroVideos, + bool enableDxvk = false, + Action<string>? log = null) { if (string.IsNullOrWhiteSpace(acClientPath) || !File.Exists(acClientPath)) return; string gameDirectory = Path.GetDirectoryName(acClientPath) ?? string.Empty; - UpdateUserPreferences(allowMultipleClients, log); + UpdateUserPreferences(allowMultipleClients, log, acClientPath); UpdateIntroVideoState(gameDirectory, skipIntroVideos, log); + // Drop-in DXVK d3d9.dll beside acclient (or remove a Rynth-managed copy). + DxvkPackageService.ApplyToClient(acClientPath, enableDxvk, log); } /// <summary> - /// Copies a per-account UserPreferences.ini stash over the live file in - /// My Documents\Asheron's Call, then re-applies the ComputeUniquePort flag. + /// The UserPreferences.ini this AC install reads and writes: the one in the game folder + /// (beside acclient.exe) when it exists - an install's clients use it, and the Documents copy + /// goes stale (2026-10-17: the game folder's file changed every session, Documents' hadn't + /// since April) - else My Documents\Asheron's Call\UserPreferences.ini. + /// </summary> + public static string LivePrefsPath(string? acClientPath) + { + string? gameDirectory = string.IsNullOrWhiteSpace(acClientPath) ? null : Path.GetDirectoryName(acClientPath); + if (!string.IsNullOrWhiteSpace(gameDirectory)) + { + string gamePrefs = Path.Combine(gameDirectory, UserPreferencesFileName); + if (File.Exists(gamePrefs)) + return gamePrefs; + } + return DocumentsPrefsPath; + } + + /// <summary>Every UserPreferences.ini AC may read that exists (the live one when neither does).</summary> + public static List<string> AllPrefsPaths(string? acClientPath) + { + var paths = new List<string>(); + string live = LivePrefsPath(acClientPath); + paths.Add(live); + if (!string.Equals(live, DocumentsPrefsPath, StringComparison.OrdinalIgnoreCase) && File.Exists(DocumentsPrefsPath)) + paths.Add(DocumentsPrefsPath); + return paths; + } + + private static string DocumentsPrefsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", UserPreferencesFileName); + + /// <summary> + /// Copies a per-account UserPreferences.ini stash over the live file (<see cref="LivePrefsPath"/>: + /// the game folder's when it has one, else My Documents\Asheron's Call's), then re-applies the + /// ComputeUniquePort flag. /// If <paramref name="stashPath"/> is empty or missing, no swap is performed /// and the live file is left as-is. /// Returns what was swapped (null when nothing was), so a client that quits at /// startup can be traced back to the stash and the swap undone /// (<see cref="UserPrefsSwapRecovery"/>). /// </summary> - public UserPrefsSwap? SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null) + public UserPrefsSwap? SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null, + string? acClientPath = null) { if (string.IsNullOrWhiteSpace(stashPath)) return null; @@ -43,9 +84,8 @@ internal sealed class AcClientLaunchSettingsService return null; } - string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call"); - string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName); + string prefsPath = LivePrefsPath(acClientPath); + string prefsDirectory = Path.GetDirectoryName(prefsPath) ?? string.Empty; byte[] stashBytes; byte[]? previousLiveBytes; @@ -64,29 +104,31 @@ internal sealed class AcClientLaunchSettingsService // Re-apply the ComputeUniquePort flag — the stash may have it set to // the wrong value (e.g. user set it up before enabling multi-client). - UpdateUserPreferences(allowMultipleClients, log: null); - log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)}."); + UpdateUserPreferences(allowMultipleClients, log: null, acClientPath); + log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)} to {prefsPath}."); return new UserPrefsSwap(stashPath, prefsPath, stashBytes, previousLiveBytes); } - private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log) + /// <summary>Sets ComputeUniquePort in every UserPreferences.ini AC may read (<see cref="AllPrefsPaths"/>).</summary> + private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log, string? acClientPath) { - string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call"); - string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName); + foreach (string prefsPath in AllPrefsPaths(acClientPath)) + { + string? prefsDirectory = Path.GetDirectoryName(prefsPath); + if (!string.IsNullOrEmpty(prefsDirectory)) + Directory.CreateDirectory(prefsDirectory); - Directory.CreateDirectory(prefsDirectory); + List<string> lines = File.Exists(prefsPath) + ? File.ReadAllLines(prefsPath).ToList() + : []; - List<string> lines = File.Exists(prefsPath) - ? File.ReadAllLines(prefsPath).ToList() - : []; + bool changed = SetIniValue(lines, NetSectionName, ComputeUniquePortKey, allowMultipleClients ? "True" : "False"); + if (!changed) + continue; - bool changed = SetIniValue(lines, NetSectionName, ComputeUniquePortKey, allowMultipleClients ? "True" : "False"); - if (!changed) - return; - - File.WriteAllLines(prefsPath, lines); - log?.Invoke($"Launch setting applied: ComputeUniquePort={(allowMultipleClients ? "True" : "False")} in UserPreferences.ini."); + File.WriteAllLines(prefsPath, lines); + log?.Invoke($"Launch setting applied: ComputeUniquePort={(allowMultipleClients ? "True" : "False")} in {prefsPath}."); + } } private static void UpdateIntroVideoState(string gameDirectory, bool skipIntroVideos, Action<string>? log) diff --git a/src/RynthCore.App/AppSettings.cs b/src/RynthCore.App/AppSettings.cs index 5256cd8..5321f6b 100644 --- a/src/RynthCore.App/AppSettings.cs +++ b/src/RynthCore.App/AppSettings.cs @@ -18,6 +18,13 @@ internal sealed class AppSettings public bool AllowMultipleClients { get; set; } = true; public bool SkipIntroVideos { get; set; } = true; public bool SkipLoginLogos { get; set; } = true; + + /// <summary> + /// When true, each launch (and Save Launch Behavior) installs DXVK's x86 + /// <c>d3d9.dll</c> next to <see cref="AcClientPath"/>. Off by default — opt-in. + /// Package lives under <RynthCore>\Runtime\dxvk\ (installer seed or GitHub fetch). + /// </summary> + public bool EnableDxvk { get; set; } public bool AutoLaunch { get; set; } public bool AutoInjectAfterLaunch { get; set; } = true; public bool WatchForAcStart { get; set; } diff --git a/src/RynthCore.App/DxvkPackageService.cs b/src/RynthCore.App/DxvkPackageService.cs new file mode 100644 index 0000000..d5f6741 --- /dev/null +++ b/src/RynthCore.App/DxvkPackageService.cs @@ -0,0 +1,305 @@ +// RynthCore.App — DxvkPackageService.cs +// Caches an x86 DXVK d3d9.dll under <RynthCore>\Runtime\dxvk\ and copies it +// into (or removes it from) the AC client folder when the launcher toggle flips. +// Fetch uses the official GitHub releases API (doitsujin/dxvk); the installer +// can pre-seed the same cache folder so first enable works offline. +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Install; + +namespace RynthCore.App; + +internal static class DxvkPackageService +{ + public const string DllFileName = "d3d9.dll"; + public const string ConfFileName = "dxvk.conf"; + public const string MarkerFileName = "d3d9.dll.rynthcore-dxvk"; + public const string PreexistingSuffix = ".rynthcore-preexisting"; + public const string VersionFileName = "version.txt"; + public const string DefaultDxvkConf = """ + # Managed by RynthCore (launcher Enable DXVK). Safe to delete with the toggle off. + dxgi.deferSurfaceCreation = True + d3d9.maxFrameLatency = 1 + d3d9.presentInterval = 1 + """; + + private static readonly HttpClient Http = CreateHttp(); + + private static HttpClient CreateHttp() + { + var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; + client.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher-DxvkFetch/1.0"); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return client; + } + + /// <summary>Cache folder: <CoreDir>\Runtime\dxvk (d3d9.dll + version.txt).</summary> + public static string CacheDirectory => Path.Combine(RynthInstallPaths.CoreDir, "Runtime", "dxvk"); + + public static string CachedDllPath => Path.Combine(CacheDirectory, DllFileName); + + public static string? CachedVersion + { + get + { + string path = Path.Combine(CacheDirectory, VersionFileName); + if (!File.Exists(path)) + return null; + try { return File.ReadAllText(path).Trim(); } + catch { return null; } + } + } + + public static bool IsCached => File.Exists(CachedDllPath); + + /// <summary> + /// Copy DXVK into the AC game folder, or remove a Rynth-managed copy. + /// Never deletes a non-DXVK d3d9 that we did not install (parks as preexisting first). + /// </summary> + public static void ApplyToClient(string acClientPath, bool enable, Action<string>? log = null) + { + if (string.IsNullOrWhiteSpace(acClientPath) || !File.Exists(acClientPath)) + { + log?.Invoke("DXVK: skipped — AC client path missing."); + return; + } + + string gameDir = Path.GetDirectoryName(acClientPath) ?? ""; + if (string.IsNullOrWhiteSpace(gameDir) || !Directory.Exists(gameDir)) + return; + + string dllPath = Path.Combine(gameDir, DllFileName); + string confPath = Path.Combine(gameDir, ConfFileName); + string markerPath = Path.Combine(gameDir, MarkerFileName); + string preexistingPath = dllPath + PreexistingSuffix; + + if (!enable) + { + RemoveManaged(gameDir, dllPath, confPath, markerPath, preexistingPath, log); + return; + } + + if (!IsCached) + { + log?.Invoke("DXVK: cache empty — use \"Fetch DXVK\" (or reinstall) before enabling, or wait for auto-fetch."); + return; + } + + try + { + // Park a non-Rynth d3d9 so disable can restore it. + if (File.Exists(dllPath) && !File.Exists(markerPath) && !LooksLikeDxvk(dllPath)) + { + if (File.Exists(preexistingPath)) + File.Delete(preexistingPath); + File.Move(dllPath, preexistingPath); + log?.Invoke($"DXVK: parked existing {DllFileName} as {Path.GetFileName(preexistingPath)}."); + } + + File.Copy(CachedDllPath, dllPath, overwrite: true); + File.WriteAllText(markerPath, CachedVersion ?? "unknown"); + if (!File.Exists(confPath)) + File.WriteAllText(confPath, DefaultDxvkConf); + + log?.Invoke($"DXVK: installed {CachedVersion ?? "cached"} into {gameDir}."); + } + catch (Exception ex) + { + log?.Invoke($"DXVK: failed to install into client folder: {ex.Message}"); + } + } + + private static void RemoveManaged( + string gameDir, + string dllPath, + string confPath, + string markerPath, + string preexistingPath, + Action<string>? log) + { + bool managed = File.Exists(markerPath) || (File.Exists(dllPath) && LooksLikeDxvk(dllPath)); + if (!managed && !File.Exists(preexistingPath)) + { + log?.Invoke("DXVK: already off for this client folder."); + return; + } + + try + { + if (managed && File.Exists(dllPath)) + File.Delete(dllPath); + if (File.Exists(markerPath)) + File.Delete(markerPath); + // Only remove conf if we wrote the marker (ours). + if (managed && File.Exists(confPath)) + { + string text = File.ReadAllText(confPath); + if (text.Contains("Managed by RynthCore", StringComparison.Ordinal)) + File.Delete(confPath); + } + + if (File.Exists(preexistingPath)) + { + File.Move(preexistingPath, dllPath); + log?.Invoke($"DXVK: removed; restored preexisting {DllFileName} in {gameDir}."); + } + else + { + log?.Invoke($"DXVK: removed from {gameDir} (stock System32 d3d9 will load)."); + } + } + catch (Exception ex) + { + log?.Invoke($"DXVK: failed to remove from client folder: {ex.Message}"); + } + } + + public static bool LooksLikeDxvk(string dllPath) + { + try + { + FileVersionInfo vi = FileVersionInfo.GetVersionInfo(dllPath); + string blob = $"{vi.ProductName}|{vi.CompanyName}|{vi.FileDescription}|{vi.FileVersion}"; + return blob.Contains("dxvk", StringComparison.OrdinalIgnoreCase); + } + catch + { + return false; + } + } + + /// <summary> + /// Download the latest DXVK release (x32 d3d9.dll) into the cache. + /// Returns the version tag (e.g. "3.1.1") or throws. + /// </summary> + public static async Task<string> EnsureLatestAsync( + IProgress<string>? progress = null, + CancellationToken cancellationToken = default) + { + progress?.Report("Querying GitHub for the latest DXVK release…"); + using HttpResponseMessage metaResponse = await Http.GetAsync( + "https://api.github.com/repos/doitsujin/dxvk/releases/latest", + cancellationToken).ConfigureAwait(false); + metaResponse.EnsureSuccessStatusCode(); + await using Stream metaStream = await metaResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + using JsonDocument doc = await JsonDocument.ParseAsync(metaStream, cancellationToken: cancellationToken).ConfigureAwait(false); + + string tag = doc.RootElement.GetProperty("tag_name").GetString() ?? ""; + string version = tag.TrimStart('v'); + if (string.IsNullOrWhiteSpace(version)) + throw new InvalidOperationException("DXVK release JSON had no tag_name."); + + string? tarballUrl = null; + string? assetName = null; + foreach (JsonElement asset in doc.RootElement.GetProperty("assets").EnumerateArray()) + { + string name = asset.GetProperty("name").GetString() ?? ""; + // Official package is dxvk-X.Y.Z.tar.gz (not dxvk-native-*). + if (name.StartsWith("dxvk-", StringComparison.OrdinalIgnoreCase) && + name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase) && + !name.Contains("native", StringComparison.OrdinalIgnoreCase)) + { + tarballUrl = asset.GetProperty("browser_download_url").GetString(); + assetName = name; + break; + } + } + + if (string.IsNullOrWhiteSpace(tarballUrl) || string.IsNullOrWhiteSpace(assetName)) + throw new InvalidOperationException("DXVK release had no dxvk-*.tar.gz asset."); + + if (string.Equals(CachedVersion, version, StringComparison.OrdinalIgnoreCase) && IsCached) + { + progress?.Report($"DXVK {version} already cached."); + return version; + } + + progress?.Report($"Downloading {assetName}…"); + string stageRoot = Path.Combine(Path.GetTempPath(), "rynthcore-dxvk-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(stageRoot); + string tarballPath = Path.Combine(stageRoot, assetName); + try + { + using (HttpResponseMessage dl = await Http.GetAsync(tarballUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false)) + { + dl.EnsureSuccessStatusCode(); + await using FileStream fs = File.Create(tarballPath); + await dl.Content.CopyToAsync(fs, cancellationToken).ConfigureAwait(false); + } + + progress?.Report("Extracting x32/d3d9.dll…"); + string extractDir = Path.Combine(stageRoot, "extract"); + Directory.CreateDirectory(extractDir); + await ExtractTarGzAsync(tarballPath, extractDir, cancellationToken).ConfigureAwait(false); + + string? found = FindX32D3d9(extractDir); + if (found == null) + throw new InvalidOperationException("Archive did not contain x32/d3d9.dll."); + + Directory.CreateDirectory(CacheDirectory); + string dest = CachedDllPath; + string tempDest = dest + ".partial"; + File.Copy(found, tempDest, overwrite: true); + if (File.Exists(dest)) + File.Delete(dest); + File.Move(tempDest, dest); + File.WriteAllText(Path.Combine(CacheDirectory, VersionFileName), version); + File.WriteAllText(Path.Combine(CacheDirectory, ConfFileName), DefaultDxvkConf); + + progress?.Report($"DXVK {version} cached at {CacheDirectory}."); + return version; + } + finally + { + try { Directory.Delete(stageRoot, recursive: true); } catch { /* best effort */ } + } + } + + /// <summary>Ensure cache exists: use existing, else fetch latest. Returns version or null on failure.</summary> + public static async Task<string?> EnsureCachedOrFetchAsync( + Action<string>? log = null, + CancellationToken cancellationToken = default) + { + if (IsCached) + return CachedVersion ?? "cached"; + + try + { + return await EnsureLatestAsync( + new Progress<string>(m => log?.Invoke(m)), + cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + log?.Invoke($"DXVK: fetch failed: {ex.Message}"); + return null; + } + } + + private static string? FindX32D3d9(string extractRoot) + { + foreach (string path in Directory.EnumerateFiles(extractRoot, DllFileName, SearchOption.AllDirectories)) + { + string? parent = Path.GetFileName(Path.GetDirectoryName(path)); + if (string.Equals(parent, "x32", StringComparison.OrdinalIgnoreCase)) + return path; + } + return null; + } + + private static async Task ExtractTarGzAsync(string tarballPath, string destinationDir, CancellationToken cancellationToken) + { + await using FileStream compressed = File.OpenRead(tarballPath); + await using var gzip = new GZipStream(compressed, CompressionMode.Decompress); + // System.Formats.Tar (net5+): extract the whole tree; we only need x32/d3d9.dll. + await System.Formats.Tar.TarFile.ExtractToDirectoryAsync(gzip, destinationDir, overwriteFiles: true, cancellationToken) + .ConfigureAwait(false); + } +} diff --git a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs index ea95d83..6c9a278 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs @@ -112,6 +112,118 @@ internal static class CharacterCaptureHooks // or relaunch. private static int _autoLoginEverFired; + // ── Character switch on request (/rc switchchar <name>) ───────────────────── + // 2026-10-25: RynthInventory's trade logs a mule account onto the character that holds + // the items. In the world: CPlayerSystem::LogOffCharacter(false) (as the Log Out button), + // then at char-select the same native LogOnCharacter the launch auto-login drives. The + // launch auto-login stands down for good once a switch has been asked for, so its + // bounce watch never logs the launch character back on over the switch. + private const int SwitchLogoffWaitMs = 30_000; + private const int SwitchLogOnTimeoutMs = 90_000; + private const int SwitchReissueMs = 5_000; + private static string? _switchTarget; + + /// <summary>A /rc switchchar is running (logging off, or logging the new character on).</summary> + internal static bool SwitchInProgress => Volatile.Read(ref _switchTarget) != null; + + /// <summary> + /// Logs this client onto <paramref name="name"/> (one of this account's characters): logs + /// the current character off first when in the world. AC's main thread (the chat + /// command). Returns the line for the player. + /// </summary> + internal static string RequestSwitch(string name) + { + name = name.Trim(); + if (name.Length == 0) + return "Usage: /rc switchchar <character name>"; + string? running = Interlocked.CompareExchange(ref _switchTarget, name, null); + if (running != null) + return $"Already switching to {running}."; + + Interlocked.Exchange(ref _autoLoginEverFired, 1); + CharacterManagementHooks.TryGetCurrentMode(out int mode); + bool inWorld = mode == GamePlayUIMode; + if (inWorld) + { + if (!LogoffOriginProbe.TryRequestLogOff(out string why)) + { + Volatile.Write(ref _switchTarget, null); + return "Can't log off to switch: " + why; + } + } + else if (mode != CharacterManagementUIMode) + { + Volatile.Write(ref _switchTarget, null); + return "Not in the world or at character select yet."; + } + + RynthLog.Info($"CharacterCapture: switch to '{name}' requested ({(inWorld ? "logging off first" : "at char-select")})."); + EngineThreads.Start("RynthCore.SwitchCharacter", () => SwitchLoop(name)); + return inWorld ? $"Logging off to switch to {name}." : $"Logging on {name}."; + } + + private static void SwitchLoop(string target) + { + try + { + // Wait for char-select (the logoff takes ~6 s). + long start = Environment.TickCount64; + while (true) + { + if (!EngineThreads.Sleep(250)) return; + if (CharacterManagementHooks.TryGetCurrentMode(out int m) && m == CharacterManagementUIMode) + break; + if (Environment.TickCount64 - start > SwitchLogoffWaitMs) + { + RynthLog.Warn($"CharacterCapture: switch to '{target}' gave up: not at char-select {SwitchLogoffWaitMs / 1000}s after the logoff."); + return; + } + } + + // Same settle time the launch auto-login gives char-select before logging on. + if (!EngineThreads.Sleep(AutoLoginDelayMs)) return; + TryCaptureNativeCharacterList(); + + long logOnStart = Environment.TickCount64; + long lastIssue = 0; + string status = string.Empty; + while (true) + { + CharacterManagementHooks.TryGetCurrentMode(out int mode); + if (mode == GamePlayUIMode) + { + RynthLog.Info($"CharacterCapture: switched to '{target}'."); + return; + } + long now = Environment.TickCount64; + if (mode == CharacterManagementUIMode && (lastIssue == 0 || now - lastIssue >= SwitchReissueMs)) + { + if (CharacterManagementHooks.TryLogOnCharacter(target, out string matched, out uint avatarId, out status)) + { + lastIssue = now; + RynthLog.Info($"CharacterCapture: switch issued LogOnCharacter for '{matched}' (avatar 0x{avatarId:X8})."); + } + else + RynthLog.Verbose($"CharacterCapture: switch to '{target}' - {status}"); + } + if (now - logOnStart > SwitchLogOnTimeoutMs) + { + RynthLog.Warn($"CharacterCapture: switch to '{target}' gave up after {SwitchLogOnTimeoutMs / 1000}s at char-select. Last status: {status}"); + return; + } + if (!EngineThreads.Sleep(AutoLoginPollIntervalMs)) return; + } + } + catch (Exception ex) + { + RynthLog.Compat($"CharacterCapture: switch loop crashed - {ex.Message}"); + } + finally + { + Volatile.Write(ref _switchTarget, null); + } + } + /// <summary> /// Starts the character-list capture poll (always) and the poll-driven /// auto-login worker. Call once from InitWorker. Auto-login no-ops if no @@ -556,7 +668,8 @@ internal static class CharacterCaptureHooks return (characters, slotCount); } - private static (string accountName, string serverName, string targetCharacter) ReadLaunchContext() + // Also read by Graphics/AcGraphics.cs (which account's graphics profile applies before login). + internal static (string accountName, string serverName, string targetCharacter) ReadLaunchContext() { try { diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index accbc9e..a5a6b5b 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -338,8 +338,19 @@ internal static class ChatCallbackHooks // Fall through and print. (If the line was handed over, it isn't handed over twice.) } - // 3. Call original - int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo); + // 3. Call original (/rc chatlinkprobe: with coordinates as AC links, when AC strings can be built) + int result; + string? linked = _replayReady && stringInfo == IntPtr.Zero && MainThreadGuard.IsOnMainThread() ? ChatLinkProbe.LinkCoords(raw) : null; + if (linked != null) + { + fixed (char* chars = linked) + { + var wide = OutgoingWidePString.Create((ushort*)chars); + try { result = pOriginal(thisPtr, (IntPtr)(&wide), chatType, unknown, stringInfo); } + finally { wide.Dispose(); } + } + } + else result = pOriginal(thisPtr, text, chatType, unknown, stringInfo); // 4. Queue AFTER original returns — game state is consistent if (line != null && !handedOver) @@ -425,7 +436,9 @@ internal static class ChatCallbackHooks _replayDepth++; try { - fixed (char* chars = h.Raw) // .NET strings end in a NUL, as the PStringBase ctor needs + // /rc chatlinkprobe: coordinates printed as AC links (plugins already heard the original). + string shown = ChatLinkProbe.LinkCoords(h.Raw) ?? h.Raw; + fixed (char* chars = shown) // .NET strings end in a NUL, as the PStringBase ctor needs { var wide = OutgoingWidePString.Create((ushort*)chars); try @@ -561,6 +574,16 @@ internal static class ChatCallbackHooks _lastOutgoingSource = commandSource; } + // Typed in AC's own chat bar (not a line Dispatch is sending: a plugin's, or RynthChat's + // box, which marks it itself): a /command's reply also shows in RynthChat's open tab, + // as when it is typed in RynthChat's box (ChatReplyTab). 2026-10-26: /fship typed in + // AC's bar printed in AC's chat but sat only under RynthChat's All and System. + if (!ChatCommandDispatcher.InDispatch && line != null) + { + try { UI.Data.ChatModel.ReplyTabs.NoteSent(line, UI.Data.ChatModel.CurrentTab(), Environment.TickCount64); } + catch { } + } + // RynthCore engine commands (/rc ...) — consume before plugins or // AC see the line so the user never broadcasts "/rc resetbar" and // a hidden overlay bar stays recoverable. Typed by the player: every diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs index 8dba6f6..116f2af 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs @@ -76,6 +76,14 @@ internal static unsafe class ChatCommandDispatcher [ThreadStatic] private static bool _inPluginPreDispatch; + /// <summary> + /// True on AC's main thread while Dispatch sends a line (a plugin's InvokeChatParser, RynthChat's + /// box, a login command): AC's outgoing-chat hook then knows the line wasn't typed in AC's own + /// chat bar (ChatCallbackHooks.OutgoingChatDetour, ChatReplyTab). 2026-10-26. + /// </summary> + [ThreadStatic] + internal static bool InDispatch; + /// <summary> /// AC1Legacy::PStringBase<char> for Event_* functions. /// </summary> @@ -137,6 +145,8 @@ internal static unsafe class ChatCommandDispatcher if (!MainThreadGuard.IsOnMainThread()) return AcMainThreadQueue.EnqueueChatCommand(text, origin); + bool outerDispatch = InDispatch; + InDispatch = true; try { string trimmed = text.Trim(); @@ -245,6 +255,7 @@ internal static unsafe class ChatCommandDispatcher RynthLog.Compat($"ChatDispatch: error - {ex.GetType().Name}: {ex.Message}"); return false; } + finally { InDispatch = outerDispatch; } } /// <summary> @@ -384,9 +395,29 @@ internal static unsafe class ChatCommandDispatcher return DecalBridgeHost.TryInvokeChatParser(command); if (ChatCallbackHooks.TryDispatchDirect(command)) return true; + // No chat target captured yet this login (nothing has gone through AC's chat bar since): + // the keystroke fallback types into AC's window, and on a client in the background, or + // with RynthChat's window popped out, those keystrokes were lost while the dispatch said + // ok (2026-10-30: /fship list from RynthChat never left two of five clients). A server + // command goes to the server as "@command" instead (ACE runs "@x" exactly as a forwarded + // "/x"). Only commands AC handles itself still need the keystrokes. + if (ServerCommandFallback.TryAsServerCommand(command, out string? atCommand)) + { + LogoffOriginProbe.RecordChat("ServerCommand fallback", atCommand!); + if (DispatchSay(atCommand!)) + { + if (Interlocked.Increment(ref _fallbackSentLogged) <= 5) + RynthLog.Compat($"ChatDispatch: no chat target captured yet; '{command.Trim()}' sent to the server as '{atCommand}'."); + return true; + } + } + if (Interlocked.Increment(ref _fallbackKeysLogged) <= 5) + RynthLog.Compat($"ChatDispatch: no chat target captured yet; '{command.Trim()}' typed into AC's window with simulated keys (lost if AC doesn't take them)."); return SimulateChatInput(command); } + private static int _fallbackSentLogged, _fallbackKeysLogged; + /// <summary> /// Simulates keyboard input to type and submit a chat command. /// Used as fallback for commands without a direct Event_* function. diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index 0d28ae2..483effa 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -193,6 +193,12 @@ internal static class ChatCommandReplies V("sense", RynthCore.Engine.UI.Data.SenseLayout.Usage, RynthCore.Engine.UI.Data.SenseLayout.IsValidArgs), V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"), V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"), + // The test branch's verbs (listed 2026-11-01: they were answered as unknown before their handlers ran). + V("chatlinkprobe", "Usage: /rc chatlinkprobe [seconds|off]", null), + V("switchchar", "Usage: /rc switchchar <character name>", null), + V("window", "Usage: /rc window reset | save | fill on|off (reset: borderless off, a normal resizable window, centred)", null), + V("borderless", "Usage: /rc borderless on|off (stuck? /rc window reset)", Words("on", "off")), + V("radar", "Usage: /rc radar (opens or closes the Radar panel)", NoArgs), V("itemtool", "Usage: /rc itemtool (opens or closes the Item Tool panel: chest looter and Quick give)", NoArgs), V("resetbar", "Usage: /rc resetbar (moves the RynthCore bar back to the top-left corner)", NoArgs, "barreset"), V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"), diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs index c55347e..69b83d3 100644 --- a/src/RynthCore.Engine/Compatibility/ChatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -135,6 +135,8 @@ internal static class ChatHooks } if (++_listenFires <= 3) RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}"); + // /rc chatlinkprobe: log what the chat UI is told (finding AC's chat link click). + ChatLinkProbe.OnChatUiMessage(thisPtr, msgInfo); try { _originalListen!(thisPtr, msgInfo); } catch (Exception ex) { try { RynthLog.Compat($"ChatHooks: Listen original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; } } diff --git a/src/RynthCore.Engine/Compatibility/ChatLinkProbe.cs b/src/RynthCore.Engine/Compatibility/ChatLinkProbe.cs new file mode 100644 index 0000000..7110d66 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ChatLinkProbe.cs @@ -0,0 +1,177 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ChatLinkProbe.cs +// +// A temporary probe to learn how AC reports a click on a link in its own chat window, +// so map coordinates there can become RynthNav links natively (RynthChat already has +// them; AC's window has had none without Decal). +// +// /rc chatlinkprobe [seconds] (default 60, at most 600; "off" ends it) +// - coordinates in AC's chat are printed as AC's clickable-name markup, +// <Tell:IIDString:110011:42.1N, 33.6E>42.1N, 33.6E<\Tell> (ChatCallbackHooks prints +// the linked text; plugins and RynthChat still get the line as the server sent it); +// - every message gmMainChatUI::ListenToElementMessage receives is logged (ChatHooks): +// its first dwords and any text those point at, so a click on one of those links +// (and on a player's name, to compare) shows which message carries it. +// Nothing changes while it is off. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class ChatLinkProbe +{ + /// <summary>The link id coordinates carry (GoArrow's and UtilityBelt's).</summary> + public const int CoordLinkId = 110011; + + private const int DefaultSeconds = 60; + private const int MaxSeconds = 600; + /// <summary>Messages logged per probe run (mouse moves can arrive every frame).</summary> + private const int MaxLogged = 400; + private const int DwordsLogged = 12; + private const int MaxTextChars = 80; + + private static long _untilMs; + private static int _logged; + private static int _linked; + + /// <summary>The probe is running (coordinates linked, chat UI messages logged). Any thread.</summary> + public static bool Active => Environment.TickCount64 < Volatile.Read(ref _untilMs); + + /// <summary>/rc chatlinkprobe [seconds|off]: what to tell the player.</summary> + public static string Command(string arg) + { + arg = (arg ?? "").Trim(); + if (arg.Equals("off", StringComparison.OrdinalIgnoreCase)) + { + Volatile.Write(ref _untilMs, 0); + RynthLog.Compat("ChatLinkProbe: stopped."); + return "Chat link probe off."; + } + int seconds = int.TryParse(arg, out int s) ? Math.Clamp(s, 5, MaxSeconds) : DefaultSeconds; + _logged = 0; + _linked = 0; + Volatile.Write(ref _untilMs, Environment.TickCount64 + seconds * 1000L); + RynthLog.Compat($"ChatLinkProbe: on for {seconds} s - coordinates in AC's chat are links; gmMainChatUI messages are logged."); + return $"Chat link probe on for {seconds} s: new coordinates in AC's chat window are links. Click one, then click a player's name, then wait for it to end."; + } + + /// <summary> + /// <paramref name="raw"/> with each coordinate pair outside markup wrapped as an AC chat link + /// (CoordLinkId), or null when there is nothing to wrap or the probe is off. + /// </summary> + public static string? LinkCoords(string? raw) + { + if (!Active || string.IsNullOrEmpty(raw) || raw.Contains("IIDString:" + CoordLinkId + ":", StringComparison.Ordinal)) + return null; + List<ChatCoord> coords = ChatCoords.Find(raw); + if (coords.Count == 0) return null; + var sb = new StringBuilder(raw.Length + coords.Count * 40); + int at = 0; + foreach (ChatCoord c in coords) + { + if (InsideMarkup(raw, c.Start)) continue; + string shown = raw.Substring(c.Start, c.Length); + sb.Append(raw, at, c.Start - at); + sb.Append("<Tell:IIDString:").Append(CoordLinkId).Append(':').Append(c.Text).Append('>').Append(shown).Append("<\\Tell>"); + at = c.Start + c.Length; + } + if (at == 0) return null; + sb.Append(raw, at, raw.Length - at); + string linked = sb.ToString(); + if (Interlocked.Increment(ref _linked) <= 10) + RynthLog.Compat($"ChatLinkProbe: linked '{Cut(linked, 160)}'"); + return linked; + } + + /// <summary>Inside a tag, or inside a link's shown text: AC's own markup is never rewritten.</summary> + private static bool InsideMarkup(string text, int at) + { + int open = text.LastIndexOf('<', at); + if (open >= 0 && text.IndexOf('>', open) >= at) return true; + int tellOpen = text.LastIndexOf("<Tell:", at, StringComparison.Ordinal); + if (tellOpen < 0) return false; + int tellClose = text.IndexOf("<\\Tell>", tellOpen, StringComparison.Ordinal); + return tellClose < 0 || tellClose >= at; + } + + /// <summary> + /// One message to gmMainChatUI::ListenToElementMessage (AC's main thread, before the original): + /// logged while the probe runs. Reads only memory that probes as accessible; never throws. + /// </summary> + public static void OnChatUiMessage(IntPtr thisPtr, IntPtr msgInfo) + { + if (!Active || msgInfo == IntPtr.Zero) return; + if (Interlocked.Increment(ref _logged) > MaxLogged) return; + try + { + var sb = new StringBuilder(256); + sb.Append($"ChatLinkProbe: msg this=0x{thisPtr.ToInt32():X8} info=0x{msgInfo.ToInt32():X8}"); + var texts = new StringBuilder(); + for (int i = 0; i < DwordsLogged; i++) + { + IntPtr at = msgInfo + i * 4; + if (!ClientObjectHooks.IsReadablePointer(at)) break; + int v = Marshal.ReadInt32(at); + sb.Append($" [{i * 4:X2}]={v:X8}"); + string? t = TextAt(new IntPtr(v)); + if (t != null) texts.Append($" [{i * 4:X2}]->\"{t}\""); + } + RynthLog.Compat(sb.ToString() + (texts.Length > 0 ? " |" + texts : "")); + } + catch { } + } + + /// <summary>Printable text at <paramref name="p"/> (wide, a PStringBase's buffer, or ASCII), or null.</summary> + private static string? TextAt(IntPtr p) + { + if (p.ToInt64() < 0x10000 || !ClientObjectHooks.IsReadablePointer(p)) return null; + string? wide = Wide(p); + if (wide != null) return "w:" + wide; + IntPtr inner = Marshal.ReadIntPtr(p); + if (inner.ToInt64() >= 0x10000 && ClientObjectHooks.IsReadablePointer(inner)) + { + string? viaPtr = Wide(inner); + if (viaPtr != null) return "*w:" + viaPtr; + } + string? ascii = Ascii(p); + return ascii != null ? "a:" + ascii : null; + } + + private static string? Wide(IntPtr p) + { + var sb = new StringBuilder(); + for (int i = 0; i < MaxTextChars; i++) + { + IntPtr c = p + i * 2; + if (!ClientObjectHooks.IsReadablePointer(c)) break; + char ch = (char)Marshal.ReadInt16(c); + if (ch == '\0') break; + if (ch < 0x20 || ch > 0x7E) return null; + sb.Append(ch); + } + return sb.Length >= 3 ? sb.ToString() : null; + } + + private static string? Ascii(IntPtr p) + { + var sb = new StringBuilder(); + for (int i = 0; i < MaxTextChars; i++) + { + IntPtr c = p + i; + if (!ClientObjectHooks.IsReadablePointer(c)) break; + byte b = Marshal.ReadByte(c); + if (b == 0) break; + if (b < 0x20 || b > 0x7E) return null; + sb.Append((char)b); + } + return sb.Length >= 3 ? sb.ToString() : null; + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, max) + "..."; +} diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index b5733f7..74690e4 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -374,7 +374,7 @@ internal static class ClientHelperHooks // Skills panel raises (CM_Train senders). try { PlayerTraining.Probe(text); } catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); } - // v85 confirmation answers (CM_Character::Event_ConfirmationResponse). + // v81 confirmation answers (CM_Character::Event_ConfirmationResponse). try { ConfirmationResponder.Probe(text); } catch (Exception ex) { RynthLog.Compat($"Compat: confirmation response binding failed - {ex.Message}"); } _initialized = true; diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index f83d305..491138b 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -169,7 +169,8 @@ internal static class ClientObjectHooks // 1 TotalExperience, 2 AvailableExperience, 6 AvailableLuminance, 7 MaximumLuminance, then // Aelrynth's Bank session totals (custom ids, absent on other servers): 9101 Radiance earned, // 9102 Luminance auto-banked, 9103 Luminance drawn from the bank. RynthTracker reads them. - private static readonly uint[] PlayerQuadStypes = { 1u, 2u, 6u, 7u, 9101u, 9102u, 9103u }; + // 9005 is ACECustom's banked luminance (the session rates count its rises as income). + private static readonly uint[] PlayerQuadStypes = { 1u, 2u, 6u, 7u, 9005u, 9101u, 9102u, 9103u }; private static readonly Dictionary<uint, long> _cachedPlayerQuad = new(); // Secondary attributes (vitals) by stype 1..6 from InqAttribute2ndBaseLevel: the buffed // maximums RynthAi's getcharvital_buffedmax and RynthLua read. diff --git a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs index 4e64f3d..bf26f58 100644 --- a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs +++ b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs @@ -1,7 +1,7 @@ // ============================================================================ // RynthCore.Engine - Compatibility/ConfirmationResponder.cs // -// Plugin API v85: answer the server's yes/no prompts (craft chance, augmentation, +// Plugin API v81: answer the server's yes/no prompts (craft chance, augmentation, // ...) for a plugin, the way UtilityBelt's helper clicks "Yes" on the tinkering // dialog, without the client ever opening that dialog. // diff --git a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs index fa78df3..0126653 100644 --- a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; @@ -7,12 +8,6 @@ using RynthCore.Engine.Hooking; namespace RynthCore.Engine.Compatibility; -// 2026-10-15: back on the kernel32 exports. SilentKelpie's 2026-10-14 change hooked only the -// acclient.exe and MSVCR70 CreateFile import slots, but AC opens its data files with -// CreateFileW by another route: no .dat open reached the hook, the first client on that -// engine held a data file without sharing it, and every client started after it stopped -// with "Can't open the data files" (2026.10.15.2 / .3). Only .dat paths are changed; every -// other CreateFile (Direct3D, drivers) passes through untouched with its last-error kept. /// <summary> /// IAT-hooks acclient.exe's <c>kernel32!CreateFileW</c> and <c>CreateFileA</c> /// imports to force maximally-permissive share semantics on AC's data files. @@ -33,12 +28,24 @@ namespace RynthCore.Engine.Compatibility; /// Other paths pass through untouched. /// /// Why IAT-hook instead of MinHook on the kernel32 export: -/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile -/// (that's how Decal-injected Thwargle clients can multibox without a -/// second AC install). IAT-hooking acclient.exe's import slot intercepts only -/// acclient.exe's own calls; our detour's call into the saved IAT pointer -/// still routes through any Decal MinHook trampoline on the kernel32 export. -/// No collision; both hooks fire in order. +/// Only the modules that open AC's data files are hooked: acclient.exe +/// (imports CreateFileA), its CRT MSVCR70.dll (CreateFileA/W, behind +/// fopen/_wfopen), and acclient.exe's private CreateFileW slot, which the +/// 2025 client fills on first use and opens every DAT through (it is in no +/// import table; <see cref="LazyImportSlotScanner"/>). Missing that slot let +/// the first client open the DATs read/write, deny-write, and every later +/// client failed with "Can't open the data files" (2026-10-15). +/// A kernel32 export hook also caught every other module, +/// including d3d9.dll and the GPU driver while AC created its device: their +/// CreateFile calls went through managed code, could wait on the runtime +/// while plugins loaded, and on some PCs AC then failed with "Could not +/// initialize Direct3D" (2026-10-14). The detour preserves the Win32 last +/// error, because callers read it after a successful CreateFile too +/// (ERROR_ALREADY_EXISTS). +/// Decal coexistence: our detour calls the pointer the IAT slot held, so any +/// Decal detour on the kernel32 export still runs. Both hooks fire in order. +/// The slots are restored at engine shutdown (<see cref="Uninstall"/>): the +/// detours live in this engine generation, which hot reload unloads. /// </summary> internal static class DatFileShareHooks { @@ -83,23 +90,16 @@ internal static class DatFileShareHooks [DllImport("kernel32.dll", SetLastError = true)] private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); - // Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a - // weak handle, so the delegate must be reachable for the process lifetime. - private static CreateFileWDelegate? _wDetour; - private static CreateFileADelegate? _aDetour; + /// <summary> + /// One patched import slot. <see cref="Slot"/> is the address inside the IAT array (not a + /// function address); <see cref="Original"/> is what it held (the real kernel32!CreateFile, + /// or another hooker's detour), written back by <see cref="Uninstall"/>. <see cref="Detour"/> + /// keeps the delegate reachable: the function pointer handed to native code is only valid + /// while it is. + /// </summary> + private sealed record IatHook(string Module, string Function, IntPtr Slot, IntPtr Original, Delegate Detour); - // The IAT slot pointer (the address inside the IAT array, NOT the original - // function address) — needed for the unhook path. - private static IntPtr _wIatSlot; - private static IntPtr _aIatSlot; - - // What was in the IAT slot when we patched it. Could be the real - // kernel32!CreateFile, or another hooker's detour if they got there first. - private static IntPtr _wOriginalPtr; - private static IntPtr _aOriginalPtr; - - private static CreateFileWDelegate? _wOriginal; - private static CreateFileADelegate? _aOriginal; + private static readonly List<IatHook> _iatHooks = []; private static string _statusMessage = "Not probed yet."; @@ -143,80 +143,32 @@ internal static class DatFileShareHooks return; } - // Hook the kernel32 exports directly with MinHook so we catch ALL - // callers in the process — acclient.exe itself, the CRT layer - // (msvcrt.dll, which is how AC's fopen-style DAT loads route), and - // any plugin or runtime DLL. IAT-hooking acclient.exe alone misses - // CRT-mediated calls because they go through msvcrt's own IAT slot. - IntPtr hKernel32 = GetModuleHandleW("kernel32.dll"); - if (hKernel32 == IntPtr.Zero) + // acclient.exe opens DATs with its own CreateFileA import, or (the 2025 client) + // through a private CreateFileW slot its Layer-for-Unicode stub fills; its CRT + // (MSVCR70.dll, statically imported, so loaded by now) does fopen/_wfopen + // opens through its CreateFileA/W imports. Nothing else is hooked. + HookModuleImports("acclient.exe", moduleBase); + HookModuleImports("MSVCR70.dll", GetModuleHandleW("MSVCR70.dll")); + try { - _statusMessage = "kernel32.dll module handle not found."; - RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}"); - return; + HookLazySlots(moduleBase); + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: DAT share - private slot scan failed: {ex.Message}"); } - // Two-phase install. Phase 1: create both hooks (inactive), - // assign typed trampolines into _aOriginal/_wOriginal. Phase 2: - // memory barrier then Enable. Critical ordering: the detour can - // fire from ANY caller in the process the moment Enable returns, - // and the detour calls _aOriginal/_wOriginal — those fields MUST - // be set first or the first invocation null-derefs and kills the - // engine init thread. - IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA"); - IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW"); - - int patched = 0; - if (aTarget != IntPtr.Zero) + if (_iatHooks.Count == 0) { - _aDetour = CreateFileADetour; - IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour); - _aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr); - _aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr); - patched++; - } - - if (wTarget != IntPtr.Zero) - { - _wDetour = CreateFileWDetour; - IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour); - _wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr); - _wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr); - patched++; - } - - // Publish trampolines to other cores before enabling. - Thread.MemoryBarrier(); - - if (aTarget != IntPtr.Zero) - { - MinHook.Enable(aTarget); - RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8})."); - } - else - { - RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found."); - } - - if (wTarget != IntPtr.Zero) - { - MinHook.Enable(wTarget); - RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8})."); - } - else - { - RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found."); - } - - if (patched == 0) - { - _statusMessage = "MinHook on kernel32 CreateFile exports failed."; + _statusMessage = "no CreateFile import slots found in acclient.exe or MSVCR70.dll."; RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}"); return; } IsInstalled = true; - _statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured)."; + _statusMessage = $"DAT share hook installed ({_iatHooks.Count} import slot(s): " + + string.Join(", ", _iatHooks.Select(h => $"{h.Module}!{h.Function}")) + + "); Direct3D and drivers call CreateFile unhooked."; RynthLog.Info($"Compat: {_statusMessage}"); } catch (Exception ex) @@ -226,9 +178,133 @@ internal static class DatFileShareHooks } } + /// <summary> + /// Points <paramref name="moduleName"/>'s kernel32 CreateFileA/W import slots at detours that + /// call whatever each slot held. A module that isn't loaded, or doesn't import one of them, + /// is skipped (logged). + /// </summary> + private static void HookModuleImports(string moduleName, IntPtr moduleBase) + { + if (moduleBase == IntPtr.Zero) + { + RynthLog.Compat($"Compat: DAT share - {moduleName} is not loaded; its CreateFile imports are not hooked."); + return; + } + + foreach (string function in new[] { "CreateFileW", "CreateFileA" }) + { + if (TryPatchIatSlot(moduleBase, function, out IntPtr slot, out IntPtr current)) + HookSlot(moduleName, function, "import", slot, current, current); + } + } + + /// <summary> + /// Points acclient.exe's private CreateFileA/W slots (filled on first use by a Layer-for-Unicode + /// style stub, see <see cref="LazyImportSlotScanner"/>) at the detours. The 2025 client opens + /// its DAT files through the CreateFileW one; it is not in any import table. + /// </summary> + private static unsafe void HookLazySlots(IntPtr moduleBase) + { + byte* basePtr = (byte*)moduleBase; + int peOffset = *(int*)(basePtr + 0x3C); + uint sizeOfImage = *(uint*)(basePtr + peOffset + 24 + 56); + var image = new ReadOnlySpan<byte>(basePtr, (int)sizeOfImage); + uint imageBase = (uint)moduleBase.ToInt32(); + var sections = LazyImportSlotScanner.ReadSections(image); + + foreach (string function in new[] { "CreateFileW", "CreateFileA" }) + { + foreach (LazyImportSlot lazy in LazyImportSlotScanner.FindSlots(image, imageBase, sections, "kernel32.dll", function)) + { + var slot = (IntPtr)(int)lazy.SlotVa; + IntPtr current = Marshal.ReadIntPtr(slot); + // Not resolved yet: the slot still points at its stub inside acclient.exe. Calling + // the stub would overwrite the slot with the real function (dropping the detour), + // so the detour calls the kernel32 export the stub would have resolved. + IntPtr target = current; + if ((uint)current.ToInt32() - imageBase < sizeOfImage) + target = GetProcAddress(GetModuleHandleW("kernel32.dll"), function); + if (target == IntPtr.Zero) + { + RynthLog.Compat($"Compat: DAT share - kernel32!{function} not found; private slot 0x{lazy.SlotVa:X8} left alone."); + continue; + } + HookSlot("acclient.exe", function, $"private slot (stub 0x{lazy.StubVa:X8})", slot, current, target); + } + } + } + + /// <summary> + /// Builds the detour for <paramref name="function"/> calling <paramref name="callTarget"/>, + /// and points <paramref name="slot"/> at it. <paramref name="restoreValue"/> is what + /// <see cref="Uninstall"/> writes back. + /// </summary> + private static void HookSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr restoreValue, IntPtr callTarget) + { + if (function == "CreateFileW") + { + CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(callTarget); + CreateFileWDelegate detour = (name, access, share, security, disposition, flags, template) => + CreateFileWDetour(original, name, access, share, security, disposition, flags, template); + InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour)); + } + else + { + CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(callTarget); + CreateFileADelegate detour = (name, access, share, security, disposition, flags, template) => + CreateFileADetour(original, name, access, share, security, disposition, flags, template); + InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour)); + } + } + + /// <summary> + /// Records the hook (so the delegate stays reachable) before the slot is written: the + /// detour can run on any thread the moment the pointer lands. + /// </summary> + private static void InstallSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr) + { + var hook = new IatHook(moduleName, function, slot, original, detour); + _iatHooks.Add(hook); + Thread.MemoryBarrier(); + + if (WriteIatPointer(slot, detourPtr)) + { + RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} {kind} (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8})."); + return; + } + + _iatHooks.Remove(hook); + } + + /// <summary> + /// Writes every patched slot back to what it held, at engine shutdown. The detours are in + /// this engine generation, which hot reload unloads; a slot left pointing at them would + /// crash the next CreateFile. + /// </summary> + public static void Uninstall() + { + if (_iatHooks.Count == 0) + return; + + int restored = 0; + foreach (IatHook hook in _iatHooks) + { + if (WriteIatPointer(hook.Slot, hook.Original)) + restored++; + } + + RynthLog.Info($"Compat: DAT share - restored {restored}/{_iatHooks.Count} CreateFile import slot(s)."); + _iatHooks.Clear(); + IsInstalled = false; + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr GetModuleHandleW(string? lpModuleName); + // Plain import (no SetLastError marshalling): it must leave the value it sets. + [DllImport("kernel32.dll", EntryPoint = "SetLastError")] + private static extern void SetWin32LastError(uint dwErrCode); + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); @@ -408,12 +484,8 @@ internal static class DatFileShareHooks && path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase); } - // Puts back the Win32 last-error the real CreateFile set, so the caller reads its own answer - // (the detour's managed work in between may change it; SilentKelpie's 2026-10-14 fix). - [DllImport("kernel32.dll", EntryPoint = "SetLastError")] - private static extern void SetWin32LastError(uint dwErrCode); - private static IntPtr CreateFileWDetour( + CreateFileWDelegate original, IntPtr lpFileName, uint dwDesiredAccess, uint dwShareMode, @@ -443,14 +515,14 @@ internal static class DatFileShareHooks { } - IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); // Captured by the SetLastError=true delegate; the caller may read it even on success. int lastError = Marshal.GetLastPInvokeError(); if (isAnyDatExt) { - uint err = result == new IntPtr(-1) ? (uint)lastError : 0; + int err = result == new IntPtr(-1) ? lastError : 0; string fname = Path.GetFileName(path!); string note = isDat ? "filtered" : "passthrough"; RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}"); @@ -461,6 +533,7 @@ internal static class DatFileShareHooks } private static IntPtr CreateFileADetour( + CreateFileADelegate original, IntPtr lpFileName, uint dwDesiredAccess, uint dwShareMode, @@ -490,14 +563,13 @@ internal static class DatFileShareHooks { } - IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); - // Captured by the SetLastError=true delegate; the caller may read it even on success. int lastError = Marshal.GetLastPInvokeError(); if (isAnyDatExt) { - uint err = result == new IntPtr(-1) ? (uint)lastError : 0; + int err = result == new IntPtr(-1) ? lastError : 0; string fname = Path.GetFileName(path!); string note = isDat ? "filtered" : "passthrough"; RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}"); diff --git a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs index 49fe936..516f2ae 100644 --- a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs +++ b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs @@ -42,13 +42,55 @@ internal static class EngineStatusMetrics _mReconciles = reconciles; _mForceClears = forceClears; } - // Per-process session baselines for the per-hour rates. Each client is its own - // process, so these naturally reset per launch; we also reset on an XP drop - // (relog / char swap). - private static long _xpBaseline = -1; - private static long _lumBaseline = -1; + // The session's XP / luminance totals and rates: RynthSuite's shared formula (SessionRates), + // a new session per character. Locked: the status JSON and the Mini Remote's Session Stats + // section read it from different threads, and chat lines arrive on a third. + private static readonly object _ratesLock = new(); + private static readonly SessionRates _rates = new(); private static int _deathsBaseline = -1; - private static DateTime _statsSessionStartUtc = DateTime.UtcNow; + private static uint _deathsCharacter; + private const uint Int64BankedLuminance = 9005; // ACECustom bank + private const uint Int64AelLuminanceBanked = 9102; // Aelrynth bank: luminance auto-banked + private const uint Int64AelLuminanceDrawn = 9103; // Aelrynth bank: luminance drawn + + /// <summary>A chat line (PluginManager.QueueChatWindowText): luminance moved into the bank isn't income.</summary> + internal static void OnChatLine(string? text) + { + if (string.IsNullOrEmpty(text) || !SessionRates.TryMovedIntoBank(text, out _)) return; + lock (_ratesLock) _rates.OnChat(text, DateTime.UtcNow); + } + + /// <summary> + /// Samples the player now and returns the session's totals and rates (the Mini Remote's + /// Session Stats section). Any thread; reads only the main-thread-cached player stats. + /// </summary> + internal static SessionRatesView SessionView() + { + try + { + ClientObjectHooks.TryGetPlayerStats(out long xp, out long lum, out _, out _, out _, out _, out _, out _, out _, out _); + return SampleRates(xp, lum); + } + catch + { + return new SessionRatesView(DateTime.UtcNow, 0, 0, 0, 0, 0); + } + } + + /// <summary>Feeds one read to the shared-formula session (bank properties read from the property cache).</summary> + private static SessionRatesView SampleRates(long xp, long lum) + { + uint player = ClientHelperHooks.GetPlayerId(); + long? Quad(uint stype) => player != 0 && ClientObjectHooks.TryGetObjectQuadProperty(player, stype, out long v) ? v : null; + var sample = new SessionRatesSample(xp > 0 ? xp : null, lum > 0 ? lum : null, + Quad(Int64BankedLuminance), Quad(Int64AelLuminanceBanked), Quad(Int64AelLuminanceDrawn)); + DateTime now = DateTime.UtcNow; + lock (_ratesLock) + { + _rates.Sample(player, sample, now); + return _rates.View(now); + } + } /// <summary> /// Compose the engine-side status fields as a JSON object string, from the @@ -120,17 +162,15 @@ internal static class EngineStatusMetrics out int encVal, out int encCap, out uint landcell, out float px, out float py, out float pz); double vitaePct = Math.Clamp((1.0 - vitae) * 100.0, 0.0, 100.0); - // Lazy baselines; reset on an XP drop (relog / char change). - if (xp > 0 && (_xpBaseline < 0 || xp < _xpBaseline)) - { - _xpBaseline = xp; _deathsBaseline = deaths; _statsSessionStartUtc = DateTime.UtcNow; - } - if (_deathsBaseline < 0 && xp > 0) _deathsBaseline = deaths; - if (lum > 0 && (_lumBaseline < 0 || lum < _lumBaseline)) _lumBaseline = lum; - double hours = (DateTime.UtcNow - _statsSessionStartUtc).TotalHours; - double xpPerHour = (hours > 1.0 / 3600.0 && _xpBaseline >= 0 && xp >= _xpBaseline) ? (xp - _xpBaseline) / hours : 0; - double lumPerHour = (hours > 1.0 / 3600.0 && _lumBaseline >= 0 && lum >= _lumBaseline) ? (lum - _lumBaseline) / hours : 0; - long xpSession = (_xpBaseline >= 0 && xp >= _xpBaseline) ? xp - _xpBaseline : 0; + // XP and luminance: the shared formula (sum of rises, ACECustom / Aelrynth bank aware), + // one session per character, the same numbers RynthAi and RynthTracker show. + SessionRatesView rates = SampleRates(xp, lum); + double xpPerHour = rates.XpPerHour; + double lumPerHour = rates.LumPerHour; + long xpSession = rates.Xp; + // Deaths this session: from the first read for this character. + uint who = ClientHelperHooks.GetPlayerId(); + if (who != 0 && who != _deathsCharacter) { _deathsCharacter = who; _deathsBaseline = deaths; } int deathsSession = (_deathsBaseline >= 0 && deaths >= _deathsBaseline) ? deaths - _deathsBaseline : 0; double burdenPct = encCap > 0 ? Math.Round((double)encVal / encCap * 100.0) : 0; w.WriteNumber("deaths", deaths); @@ -139,6 +179,7 @@ internal static class EngineStatusMetrics w.WriteNumber("xpPerHour", Math.Round(xpPerHour)); w.WriteNumber("luminancePerHour", Math.Round(lumPerHour)); w.WriteNumber("xpSession", xpSession); + w.WriteNumber("luminanceSession", rates.Lum); // additive (2026.10.5.54): the luminance total behind luminancePerHour w.WriteNumber("burdenPct", burdenPct); w.WriteString("area", landcell != 0 ? (landcell >> 16).ToString("X4") : ""); // [status-export] live map-dot position. wx/wy are ABSOLUTE world coords (cell-local origin + the diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 6a1c1c3..38fa726 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -175,6 +175,8 @@ internal static class HeartbeatLogger if (free >= 0) vaField = $" vafree={free}MB"; long largest = AddressSpace.FreeAndLargestMb().LargestFreeMb; if (largest >= 0) vaField += $" valargest={largest}MB"; + // Nearly out soon after start: Adaptive degrade back on for the next launch. + Graphics.AcGraphics.CheckLowMemory(free, largest); } catch { } // Crash logger module cache (native): rebuilt every 10 s here, so a fault diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index 22b23e9..4078e67 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -1233,6 +1233,8 @@ internal static partial class InventoryModel lines.Add(sb.ToString()); } } + if (appraised && item != null && (item.Type & WeaponTypeMask) != 0) + AddWeaponSpecials(id, lines); if (item != null && item.SpellId != 0 && (lines.Count == 0 || !appraised)) { if (!PortalSpellTable.Ready) PortalSpellTable.EnsureLoadQueued(); @@ -1243,6 +1245,94 @@ internal static partial class InventoryModel return new InventoryTooltip { Id = id, Lines = lines.ToArray(), Identifying = identifying }; } + // ── Weapon imbues and slayer (tooltip, 2026-10-25) ────────────────── + // ItemType melee weapon | missile weapon | caster. + private const uint WeaponTypeMask = 0x1 | 0x100 | 0x8000; + // ACE: ImbuedEffect 179 (+ ImbuedEffect2..5 = 303..306), SlayerCreatureType 166, + // SlayerDamageBonus 138 (rarely sent), LongDesc 16 (ACECustom "Property Details:" strengths). + private const uint StypeImbuedEffect = 179, StypeSlayerCreature = 166, StypeSlayerBonus = 138, StypeLongDesc = 16; + private static readonly uint[] ImbueStypes = { StypeImbuedEffect, 303, 304, 305, 306 }; + + // ACE ImbuedEffectType bits, in the order the appraisal lists them. + private static readonly (int Bit, string Name, string Detail)[] ImbueNames = + { + (0x0001, "Critical Strike", "Critical Strike"), (0x0002, "Crippling Blow", "Crippling Blow"), + (0x0004, "Armor Rending", "Armor Rending"), (0x0008, "Slash Rending", "Slash"), + (0x0010, "Pierce Rending", "Pierc"), (0x0020, "Bludgeon Rending", "Bludg"), + (0x0040, "Acid Rending", "Acid"), (0x0080, "Cold Rending", "Cold|Frost"), + (0x0100, "Lightning Rending", "Electric|Lightning"), (0x0200, "Fire Rending", "Fire"), + (0x4000, "Nether Rending", "Nether"), (0x0400, "Melee Defense imbue", ""), + (0x0800, "Missile Defense imbue", ""), (0x1000, "Magic Defense imbue", ""), + (0x2000, "Spellbook (Hematited)", ""), + }; + + // ACE CreatureType, index = value (same list as RynthAi's MagItemInfoTables / LootRuleText). + private static readonly string[] CreatureTypeNames = + { + "Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker", + "Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo", + "Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus", + "Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman", + "Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny", + "Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion", + "Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun", + "Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental", + "Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken", + "Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", + "Target", "Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", + "Remoran", "Swarm", "Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", + "Paradox Olthoi", "Harvest", "Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", + "Gear Knight", "Gurog", "Anekshay", + }; + + // "- Fire Rending: +176% Dmg", "- Armor Rending: 12.5% Ignored", "- Crippling Blow: 2.5x Crit Dmg". + private static readonly System.Text.RegularExpressions.Regex ImbueDetailLine = new( + @"^\s*-\s*(?<name>[A-Za-z' ]+?)\s*:\s*(?<value>[+-]?[\d.,]+\s?[%x])", + System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + /// <summary>"Imbues: Armor Rending 16%, Slash Rending +161%" and "Slayer: Undead" for an identified weapon.</summary> + private static void AddWeaponSpecials(uint id, List<string> lines) + { + int mask = 0; + foreach (uint stype in ImbueStypes) + if (ClientObjectHooks.TryGetObjectIntProperty(id, stype, out int v)) mask |= v; + if (mask != 0) + { + string desc = ClientObjectHooks.TryGetObjectStringProperty(id, StypeLongDesc, out string d) ? d ?? string.Empty : string.Empty; + var parts = new List<string>(2); + foreach (var (bit, name, detail) in ImbueNames) + { + if ((mask & bit) == 0) continue; + string strength = detail.Length > 0 ? ImbueStrength(desc, detail) : string.Empty; + parts.Add(strength.Length > 0 ? name + " " + strength : name); + } + if (parts.Count > 0) lines.Add("Imbues: " + string.Join(", ", parts)); + } + + if (ClientObjectHooks.TryGetObjectIntProperty(id, StypeSlayerCreature, out int slay) && slay > 0) + { + string creature = slay < CreatureTypeNames.Length ? CreatureTypeNames[slay] : "creature type " + slay.ToString(CultureInfo.InvariantCulture); + string bonus = ClientObjectHooks.TryGetObjectDoubleProperty(id, StypeSlayerBonus, out double b) && b > 1 + ? $" ({b.ToString("0.##", CultureInfo.InvariantCulture)}x damage)" : string.Empty; + lines.Add($"Slayer: {creature}{bonus}"); + } + } + + /// <summary>The strength of one imbue from the "Property Details:" text, or empty.</summary> + private static string ImbueStrength(string desc, string detail) + { + if (desc.Length == 0) return string.Empty; + bool rending = detail is not ("Critical Strike" or "Crippling Blow" or "Armor Rending"); + foreach (System.Text.RegularExpressions.Match m in ImbueDetailLine.Matches(desc)) + { + string name = m.Groups["name"].Value; + if (!Array.Exists(detail.Split('|'), k => name.Contains(k, StringComparison.OrdinalIgnoreCase))) continue; + if (rending && !name.Contains("Rending", StringComparison.OrdinalIgnoreCase)) continue; + return m.Groups["value"].Value.Replace(" ", ""); + } + return string.Empty; + } + private static string SpellName(uint spellId) { // Spell ids in an appraisal can carry the layer in the high word. diff --git a/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs b/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs new file mode 100644 index 0000000..d1a5c87 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One section of a PE image as it is mapped in memory (RVA layout, not file layout).</summary> +internal readonly record struct ImageSection(string Name, uint Rva, uint Size, bool Executable); + +/// <summary>A private function-pointer slot filled by a lazy-resolve stub, and the stub that fills it.</summary> +internal readonly record struct LazyImportSlot(uint SlotVa, uint StubVa); + +/// <summary> +/// Finds the private pointer slots that Layer-for-Unicode style stubs fill on first use. +/// +/// The 2025 ACClient.exe (0.0.11.6096) does not import kernel32!CreateFileW. It resolves it the +/// first time it is called, with a stub of this exact shape, and every call goes through the slot: +/// <code> +/// 68 xx xx xx xx push fallback +/// FF 35 xx xx xx xx push [module handle cache] +/// 68 SS SS SS SS push slot (the pointer the stub fills) +/// 68 NN NN NN NN push "CreateFileW" +/// 68 DD DD DD DD push "kernel32.dll" +/// E8 xx xx xx xx call resolver +/// FF 25 SS SS SS SS jmp [slot] +/// </code> +/// AC opens its DAT files through that slot, so a hook on the import table alone never sees them. +/// The pattern is matched in full (both slot operands must agree, and the DLL operand must name +/// <c>dll</c>), so a stray push of the name string is never taken for a stub. +/// </summary> +internal static class LazyImportSlotScanner +{ + private const byte PushImm32 = 0x68; + private const byte CallRel32 = 0xE8; + private const int IMAGE_SCN_CNT_CODE = 0x00000020; + private const int IMAGE_SCN_MEM_EXECUTE = 0x20000000; + + // Offsets inside the stub, from the "push name" instruction. + private const int SlotPushBack = 5; // push slot sits right before push name + private const int DllPushAhead = 5; // push dll sits right after it + private const int CallAhead = 10; + private const int JmpAhead = 15; // FF 25 <slot>, after the 5-byte call + private const int StubHeadBytes = 11; // push fallback (5) + push [handle cache] (6), before push slot + + /// <summary> + /// Reads the section table of a PE32 image mapped at RVA layout (a module's memory, or a test + /// buffer laid out the same way). Returns an empty list when the headers don't parse. + /// </summary> + public static List<ImageSection> ReadSections(ReadOnlySpan<byte> image) + { + var sections = new List<ImageSection>(); + if (image.Length < 0x40) + return sections; + + int pe = BitConverter.ToInt32(image.Slice(0x3C, 4)); + if (pe <= 0 || pe + 24 > image.Length || BitConverter.ToUInt32(image.Slice(pe, 4)) != 0x00004550) // "PE\0\0" + return sections; + + int count = BitConverter.ToUInt16(image.Slice(pe + 6, 2)); + int optionalSize = BitConverter.ToUInt16(image.Slice(pe + 20, 2)); + int table = pe + 24 + optionalSize; + for (int i = 0; i < count; i++) + { + int h = table + 40 * i; + if (h + 40 > image.Length) + break; + string name = Encoding.ASCII.GetString(image.Slice(h, 8)).TrimEnd('\0'); + uint virtualSize = BitConverter.ToUInt32(image.Slice(h + 8, 4)); + uint rva = BitConverter.ToUInt32(image.Slice(h + 12, 4)); + uint rawSize = BitConverter.ToUInt32(image.Slice(h + 16, 4)); + int flags = BitConverter.ToInt32(image.Slice(h + 36, 4)); + uint size = virtualSize != 0 ? virtualSize : rawSize; + // Clamp to the buffer: a section can't be scanned past the mapped image. + if (rva >= image.Length) + continue; + size = (uint)Math.Min(size, image.Length - rva); + bool executable = (flags & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE)) != 0; + sections.Add(new ImageSection(name, rva, size, executable)); + } + return sections; + } + + /// <summary> + /// Every slot a stub fills with <paramref name="dll"/>!<paramref name="function"/>, as absolute + /// addresses (the stubs push absolute addresses, already relocated to <paramref name="imageBase"/>). + /// </summary> + public static List<LazyImportSlot> FindSlots(ReadOnlySpan<byte> image, uint imageBase, + IReadOnlyList<ImageSection> sections, string dll, string function) + { + var found = new List<LazyImportSlot>(); + Span<byte> needle = stackalloc byte[5]; + foreach (uint nameVa in FindNameStrings(image, imageBase, sections, function)) + { + needle[0] = PushImm32; + BitConverter.TryWriteBytes(needle.Slice(1), nameVa); + + foreach (ImageSection code in sections) + { + if (!code.Executable) + continue; + ReadOnlySpan<byte> text = image.Slice((int)code.Rva, (int)code.Size); + int from = 0; + while (true) + { + int hit = text.Slice(from).IndexOf(needle); + if (hit < 0) + break; + int at = from + hit; + from = at + 1; + if (TryReadStub(text, at, image, imageBase, dll, out uint slotVa)) + found.Add(new LazyImportSlot(slotVa, imageBase + code.Rva + (uint)Math.Max(0, at - SlotPushBack - StubHeadBytes))); + } + } + } + return found; + } + + // The NUL-terminated name, not as the tail of a longer identifier (e.g. "MyCreateFileW"). + private static IEnumerable<uint> FindNameStrings(ReadOnlySpan<byte> image, uint imageBase, + IReadOnlyList<ImageSection> sections, string function) + { + byte[] name = Encoding.ASCII.GetBytes(function + "\0"); + var hits = new List<uint>(); + foreach (ImageSection s in sections) + { + if (s.Executable) + continue; + ReadOnlySpan<byte> data = image.Slice((int)s.Rva, (int)s.Size); + int from = 0; + while (true) + { + int hit = data.Slice(from).IndexOf(name); + if (hit < 0) + break; + int at = from + hit; + from = at + 1; + if (at > 0 && IsIdentifierByte(data[at - 1])) + continue; + hits.Add(imageBase + s.Rva + (uint)at); + } + } + return hits; + } + + private static bool TryReadStub(ReadOnlySpan<byte> text, int namePush, ReadOnlySpan<byte> image, + uint imageBase, string dll, out uint slotVa) + { + slotVa = 0; + int slotPush = namePush - SlotPushBack; + if (slotPush < 0 || namePush + JmpAhead + 6 > text.Length) + return false; + if (text[slotPush] != PushImm32 + || text[namePush + DllPushAhead] != PushImm32 + || text[namePush + CallAhead] != CallRel32 + || text[namePush + JmpAhead] != 0xFF || text[namePush + JmpAhead + 1] != 0x25) + return false; + + uint slot = BitConverter.ToUInt32(text.Slice(slotPush + 1, 4)); + uint jmpSlot = BitConverter.ToUInt32(text.Slice(namePush + JmpAhead + 2, 4)); + if (slot != jmpSlot || !InImage(slot, 4, imageBase, image.Length)) + return false; + + uint dllVa = BitConverter.ToUInt32(text.Slice(namePush + DllPushAhead + 1, 4)); + if (!string.Equals(ReadAsciiz(image, imageBase, dllVa), dll, StringComparison.OrdinalIgnoreCase)) + return false; + + slotVa = slot; + return true; + } + + private static bool InImage(uint va, int size, uint imageBase, int imageLength) => + va >= imageBase && (long)va - imageBase + size <= imageLength; + + private static string? ReadAsciiz(ReadOnlySpan<byte> image, uint imageBase, uint va) + { + if (!InImage(va, 1, imageBase, image.Length)) + return null; + ReadOnlySpan<byte> rest = image.Slice((int)(va - imageBase)); + int end = rest.IndexOf((byte)0); + if (end < 0 || end > 260) + return null; + return Encoding.ASCII.GetString(rest.Slice(0, end)); + } + + private static bool IsIdentifierByte(byte b) => + b is >= (byte)'A' and <= (byte)'Z' or >= (byte)'a' and <= (byte)'z' or >= (byte)'0' and <= (byte)'9' or (byte)'_'; +} diff --git a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs index 0fce0bf..dd587b3 100644 --- a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs +++ b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs @@ -122,6 +122,7 @@ internal static unsafe class LogoffOriginProbe HookResolver.ResolveResult r; r = HookResolver.Resolve(text, "LogoffProbe.LogOffCharacter", LogOffCharacterPattern, ProbeLogOffCharacterVa); + if (r.Success) _logOffCharacterEntry = r.Address; delegate* unmanaged[Thiscall]<IntPtr, byte, void> dLogOffCharacter = &LogOffCharacterDetour; if (TryHook(r, "CPlayerSystem::LogOffCharacter", (IntPtr)dLogOffCharacter, out _origLogOffCharacter)) hooked++; @@ -144,6 +145,26 @@ internal static unsafe class LogoffOriginProbe RynthLog.Compat($"LogoffProbe: {hooked}/5 logoff-origin hooks installed (labels {(_labelsValid ? "on" : "off - not the reference client")})."); } + // CPlayerSystem::LogOffCharacter's entry (hooked or not): TryRequestLogOff calls it. + private static IntPtr _logOffCharacterEntry; + + /// <summary> + /// Logs the character off the way the Log Out button does: CPlayerSystem::LogOffCharacter(false) + /// (through the hook above when it is in, so the logoff is recorded like any other). AC's main + /// thread only. False with a reason when it can't be called. + /// </summary> + public static bool TryRequestLogOff(out string status) + { + if (!MainThreadGuard.IsOnMainThread()) { status = "off AC's main thread."; return false; } + IntPtr fn = _logOffCharacterEntry; + if (fn == IntPtr.Zero) { status = "CPlayerSystem::LogOffCharacter isn't resolved."; return false; } + IntPtr playerSystem = CharacterManagementHooks.PlayerSystemOnMainThread(); + if (playerSystem == IntPtr.Zero) { status = "the player system isn't available."; return false; } + ((delegate* unmanaged[Thiscall]<IntPtr, byte, void>)fn)(playerSystem, 0); + status = "logging off."; + return true; + } + private static bool TryHook(HookResolver.ResolveResult r, string name, IntPtr detour, out IntPtr original) { original = IntPtr.Zero; diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index e0eed66..6ceb600 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -46,6 +46,9 @@ namespace RynthCore.Engine.Compatibility; /// — read / trade with the open vendor through the engine's vendor /// primitives (<see cref="VendorTrade"/>); a manual test hook for the /// plugin API. Replies go to chat from the main-thread drain and to the log.</item> +/// <item><c>/rc chatlinkprobe [seconds|off]</c> — a temporary probe (<see cref="ChatLinkProbe"/>): +/// coordinates in AC's chat window become AC links and every chat UI message is logged, +/// to find how AC reports a click on a link (native coordinate links, no Decal).</item> /// <item><c>/rc chathold [on|off|status]</c> — incoming chat waits for the plugins' /// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat /// window too (<see cref="ChatCallbackHooks"/>). On at every start; not saved.</item> @@ -90,6 +93,9 @@ namespace RynthCore.Engine.Compatibility; /// Logs\flight-<pid>-<time>.txt; <c>/rc flightdump auto <reason></c> is the rate-limited /// automatic form. <c>/rc flight [status|mark <text>|on|off|auto on|off]</c>.</item> /// <item><c>/rc quit</c> / <c>/rc exit</c> - closes the client cleanly, as its close button does.</item> +/// <item><c>/rc switchchar <name></c> - logs this client onto another character of the same +/// account: logs off when in the world, then logs the character on at char-select +/// (<see cref="CharacterCaptureHooks.RequestSwitch"/>; RynthInventory's trade uses it).</item> /// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it /// opens the panel; with text it sends that report now, with the recent log attached /// (the panel is where the log can be left out). One report a minute.</item> @@ -252,6 +258,14 @@ internal static class RynthCoreChatCommands return; } + // /rc chatlinkprobe [seconds|off]: coordinates in AC's chat as links + chat UI messages logged + if (IsVerb(sub, "chatlinkprobe", out string probeArgs)) + { + try { Reply(ChatLinkProbe.Command(probeArgs)); } + catch (Exception ex) { Failed("chatlinkprobe", ex); } + return; + } + // /rc chathold [on|off|status]: lines a plugin eats stay out of AC's chat window too if (IsVerb(sub, "chathold", out string holdArgs)) { @@ -348,6 +362,13 @@ internal static class RynthCoreChatCommands return; } + // /rc switchchar <name> : log this client onto another character of the account (2026-10-25) + if (IsVerb(sub, "switchchar", out string switchArgs)) + { + Reply(CharacterCaptureHooks.RequestSwitch(switchArgs)); + return; + } + // /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log) if (IsVerb(sub, "report", out string reportArgs)) { @@ -420,13 +441,15 @@ internal static class RynthCoreChatCommands return; } - // /rc miniremote [show|hide|toggle|tab <tab>|section <id>] : the ImGui Mini Remote panel, like - // its bar button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of - // its tabs (RynthAi's pets, crafting; RynthILT's gear, games; none = the remote). Quests are - // RynthOracle's window (/ro) since 2026-10-13. Since 2026.10.5.54 the old "character" tab - // (the generic overview) opens RynthOracle's Character tab (/ro character). Infinite - // Leaftide's own tabs ("charms", "banking", "gear", "games") stay RynthILT's, in this window. - // "section" opens it on one of its sections (char = Session Stats, map, skills, ...; "remote" = the remote). + // /rc miniremote [show|hide|toggle|tab <tab>|section <id>|undock|dock] : the ImGui Mini Remote + // panel, like its bar button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens + // it on one of its tabs (RynthAi's pets, crafting; RynthILT's gear, games; none = the remote). + // Quests are RynthOracle's window (/ro) since 2026-10-13. Since 2026.10.5.54 the old + // "character" and "charms" tabs open RynthOracle's Character tab (/ro character) and + // "banking" opens RynthInventory's Global Inventory on its Banking tab (/ginv bank). + // "section" opens it on one of its sections (char = Session Stats, map, skills, ...; + // "remote" = the remote). "undock" / "popout" / "float" opens (or keeps) it in its own + // window so Options has room; "dock" / "redock" puts it back in the client. if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs)) { MiniRemoteCommand(remoteArgs); @@ -685,6 +708,49 @@ internal static class RynthCoreChatCommands return; } + // /rc window reset|save|fill on|off (UI/AcWindowChrome.cs): + // reset - a stuck AC window (borderless too small, off-screen) back to a normal framed, + // resizable one, centred; borderless is turned off and the saved spot replaced; + // save - save where the window is now (framed or borderless) for the next launch; + // fill - Settings > Game Client "Borderless Fills Monitor". + if (IsVerb(sub, "window", out string windowArgs)) + { + string wa = windowArgs.ToLowerInvariant(); + if (wa == "reset") + Reply(UI.AcWindowChrome.ResetWindow()); + else if (wa == "save") + Reply(UI.AcWindowChrome.SaveWindowNow()); + else if (wa is "fill on" or "fill off") + { + Plugins.EngineSettings.BorderlessFillMonitor = wa == "fill on"; + Graphics.AcGraphics.DisplayTogglesChanged(); + UI.AcWindowChrome.ApplyFillMonitorChanged(UI.AcWindowChrome.ResolveGameHwndForSettings()); + Reply(Plugins.EngineSettings.BorderlessFillMonitor + ? "Borderless fills the monitor." + : "Borderless keeps the framed window's size and spot (set it framed, then turn borderless on)."); + } + else + Fail("Usage: /rc window reset | save | fill on|off (reset: borderless off, a normal resizable window, centred)"); + return; + } + // /rc borderless on|off : the Settings > Game Client toggle (on fills the monitor). + if (IsVerb(sub, "borderless", out string borderlessArgs)) + { + if (borderlessArgs.Equals("on", StringComparison.OrdinalIgnoreCase) + || borderlessArgs.Equals("off", StringComparison.OrdinalIgnoreCase)) + { + Plugins.EngineSettings.BorderlessWindowed = borderlessArgs.Equals("on", StringComparison.OrdinalIgnoreCase); + Graphics.AcGraphics.DisplayTogglesChanged(); + UI.AcWindowChrome.ApplyBorderlessDesired(UI.AcWindowChrome.ResolveGameHwndForSettings()); + Reply("Borderless windowed " + (Plugins.EngineSettings.BorderlessWindowed + ? (Plugins.EngineSettings.BorderlessFillMonitor ? "on (fills the monitor)." : "on (kept size).") + : "off.")); + } + else + Fail("Usage: /rc borderless on|off (stuck? /rc window reset)"); + return; + } + switch (sub.ToLowerInvariant()) { case "rl": @@ -725,6 +791,14 @@ internal static class RynthCoreChatCommands "The Item Count panel isn't available (the ImGui layer is off?)."); return; + case "radar": + // Radar left the top bar (under RynthNav); same PanelRouter path as before. + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.RadarFace.Title)) + Reply("The Radar panel isn't available (the ImGui layer is off?)."); + else + UI.PanelRouter.Toggle(ImGuiBackend.Panels.RadarFace.Title); + return; + case "itemtool": // The ImGui Item Tool panel (chest looter + Quick give), like its bar button. TogglePanel(ImGuiBackend.Panels.ItemToolFace.Title, "Item Tool panel", @@ -1217,6 +1291,20 @@ internal static class RynthCoreChatCommands /// </summary> private static bool TryPanelMode(string args, out bool? show) => ChatCommandReplies.TryPanelMode(args, out show); + /// <summary> + /// Mini Remote dock verbs: undock / popout / float → true; dock / redock → false. + /// </summary> + private static bool IsMiniRemoteDockVerb(string args, out bool undock) + { + undock = false; + switch (args.Trim().ToLowerInvariant()) + { + case "undock": case "popout": case "float": undock = true; return true; + case "dock": case "redock": return true; + default: return false; + } + } + /// <summary>Opens (true), closes (false) or toggles (null) an ImGui panel, like its bar button.</summary> private static void SetPanelOpen(string title, bool? show) { @@ -1437,13 +1525,14 @@ internal static class RynthCoreChatCommands } /// <summary> - /// The command for a Mini Remote tab that moved out (2026.10.5.54): "character" (the generic - /// overview) is RynthOracle's Character tab. Null for a tab still in the Mini Remote, which - /// includes RynthILT's Leaftide tabs (Charms, Banking, Gear, Games): those stay RynthILT's. + /// The command for a Mini Remote tab that moved out (2026.10.5.54): "character" and "charms" + /// are RynthOracle's Character tab, "banking" is RynthInventory's Global Inventory Banking tab. + /// Null for a tab still in the Mini Remote. /// </summary> internal static string? MovedTabCommand(string tab) => tab.Trim().ToLowerInvariant() switch { - "character" or "char" => "/ro character", + "character" or "char" or "charms" => "/ro character", + "banking" or "bank" => "/ginv bank", _ => null, }; diff --git a/src/RynthCore.Engine/Compatibility/ServerCommandFallback.cs b/src/RynthCore.Engine/Compatibility/ServerCommandFallback.cs new file mode 100644 index 0000000..cac27a5 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ServerCommandFallback.cs @@ -0,0 +1,53 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ServerCommandFallback.cs +// A slash command with no captured chat target goes to the server as "@command". +// +// ChatCommandDispatcher.DispatchRaw sends a "/command" through AC's own outgoing-chat +// function, using the chat manager AC passed the last time a line went through the chat +// bar (ChatCallbackHooks.TryDispatchDirect). Until that happens in a login it typed the +// line into AC's window with simulated keys. Silentkelpie (2026-10-30): /fship list typed in +// RynthChat showed nowhere on two of five clients. Their flight recorders show no Talk sent +// at all, while the dispatch reported ok; the other three sent it and got the reply. +// A server command (anything AC doesn't handle itself) now goes out as "@command" through +// Event_Talk, which needs no captured target: ACE runs "@x" the same as "/x". +// Pure: tools/ChatFilterTests compiles this file. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class ServerCommandFallback +{ + /// <summary>Commands the AC client runs itself (never sent to the server): these still need the keystrokes.</summary> + private static readonly string[] ClientCommands = + { + "/framerate", "/render", "/quit", "/exit", "/logout", "/logoff", "/clear", "/cls", "/filter", "/config", + "/fillcomps", "/hide", "/chatlog", "/screenshot", "/ss", "/camera", "/loc", "/help", "/h", + "/die", "/lifestone", "/marketplace", "/house", "/emotes", "/soundtrack", "/music", + "/f", "/a", "/p", "/v", "/c", "/m", "/fellowship", "/allegiance", "/patron", "/vassals", + "/covassals", "/monarch", "/say", "/s", "/tell", "/t", "/reply", "/r", "/retell", "/rt", + "/emote", "/e", "/me", "/em", "/general", "/trade", "/lfg", "/roleplay", "/society", "/olthoi", + "/cg", "/ct", "/clfg", "/crp", "/cs", "/co", + }; + + /// <summary> + /// "/fship list" → "@fship list". False for a client command, a line that isn't a slash + /// command, or one with characters ACE's Talk can't carry. + /// </summary> + public static bool TryAsServerCommand(string? command, out string? atCommand) + { + atCommand = null; + string t = (command ?? "").Trim(); + if (t.Length < 2 || t[0] != '/' || t.Length > 200) return false; + foreach (char c in t) + if (c < 0x20 || c > 0x7E) return false; + int sp = t.IndexOf(' '); + string verb = sp < 0 ? t : t[..sp]; + if (verb.Length < 2 || !char.IsLetter(verb[1])) return false; + foreach (string client in ClientCommands) + if (verb.Equals(client, StringComparison.OrdinalIgnoreCase)) return false; + atCommand = "@" + t.Substring(1); + return true; + } +} diff --git a/src/RynthCore.Engine/Compatibility/SessionRates.cs b/src/RynthCore.Engine/Compatibility/SessionRates.cs new file mode 100644 index 0000000..66a3b99 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/SessionRates.cs @@ -0,0 +1,160 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/SessionRates.cs +// The engine's XP / luminance session totals and per-hour rates: the status feed +// (EngineStatusMetrics, GetEngineStatusJson) and the Mini Remote's Session Stats +// section. Same formula as RynthSuite's Plugins/Shared/SessionStats.cs, which +// RynthAi, RynthTracker, RynthOracle and RynthILT show (2026-10-13), so every +// XP/hour and lum/hour on screen agrees: +// - a total is the sum of every rise of the property since the session began; +// a drop (spending luminance, a server resetting a session total) only moves +// the baseline, never takes earnings back; +// - ACECustom's bank (Int64 9005) counts its rises as income, and once it has +// been read the character's AvailableLuminance rises are withdrawals, not income; +// a deposit or incoming transfer seen in chat ("Deposited N luminance") is moved +// money, so that much of the next bank rise isn't counted; +// - Aelrynth's bank: luminance auto-banked (9102) was earned before it left the +// character, luminance drawn (9103) landed on the character without being earned; +// - rate = total / session hours, the session at least one second long. +// A different character (or the first read) starts a new session. +// +// Pure: no AC, no engine state (tools/SectionsTests compiles it). Not thread-safe: +// one caller at a time (EngineStatusMetrics locks around it). +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One read of the player's properties (null = not readable on this server or yet).</summary> +internal readonly record struct SessionRatesSample( + long? TotalXp, long? AvailableLum, long? BankLum, long? AelBanked, long? AelDrawn); + +/// <summary>The totals and rates as of the last sample.</summary> +internal readonly record struct SessionRatesView( + DateTime StartUtc, double Seconds, long Xp, double XpPerHour, long Lum, double LumPerHour); + +internal sealed class SessionRates +{ + private uint _character; + private DateTime _startUtc; + private long _xp, _lum; + private Rise _xpRise, _lumRise, _bankRise, _aelBankedRise, _aelDrawnRise; + private bool _bankTracked; + // Luminance deposited (or transferred in) waiting for its bank rise, which isn't income. + private long _movedIntoBank; + private DateTime _movedIntoBankUntil; + private static readonly TimeSpan MovedIntoBankLife = TimeSpan.FromSeconds(60); + + /// <summary>The character the session belongs to (0 = none yet).</summary> + public uint Character => _character; + + /// <summary>Starts a fresh session for <paramref name="character"/> at <paramref name="nowUtc"/>.</summary> + public void Reset(uint character, DateTime nowUtc) + { + _character = character; + _startUtc = nowUtc; + _xp = _lum = 0; + _xpRise = default; _lumRise = default; _bankRise = default; _aelBankedRise = default; _aelDrawnRise = default; + _bankTracked = false; + _movedIntoBank = 0; + _movedIntoBankUntil = DateTime.MinValue; + } + + /// <summary> + /// A chat line: "Deposited N luminance" (character to bank) or "Received N luminance from X" + /// (a transfer) means the next N of bank rise is moved money, not income. + /// </summary> + public void OnChat(string? text, DateTime nowUtc) + { + if (!TryMovedIntoBank(text, out long moved)) return; + _movedIntoBank += moved; + _movedIntoBankUntil = nowUtc + MovedIntoBankLife; + } + + /// <summary>The deposit / incoming-transfer lines (the shared SessionLumChat.TryMovedIntoBank).</summary> + internal static bool TryMovedIntoBank(string? text, out long amount) + => TryAmount(text, "Deposited ", " luminance", out amount) + || TryAmount(text, "Received ", " luminance from ", out amount); + + // The line starts with the prefix (a player quoting it in a tell doesn't), then "1,234,567", then the suffix. + private static bool TryAmount(string? text, string prefix, string suffix, out long amount) + { + amount = 0; + if (string.IsNullOrEmpty(text)) return false; + int i = 0; + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (string.Compare(text, i, prefix, 0, prefix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; + i += prefix.Length; + int digits = 0; + long value = 0; + for (; i < text.Length; i++) + { + char c = text[i]; + if (c == ',') continue; + if (c < '0' || c > '9') break; + if (value > (long.MaxValue - 9) / 10) return false; + value = value * 10 + (c - '0'); + digits++; + } + if (digits == 0) return false; + if (string.Compare(text, i, suffix, 0, suffix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; + amount = value; + return true; + } + + /// <summary>Takes one read; a new character starts a new session first.</summary> + public void Sample(uint character, in SessionRatesSample s, DateTime nowUtc) + { + if (character == 0) return; + if (character != _character) Reset(character, nowUtc); + + if (s.TotalXp is long xp && xp > 0) _xp += _xpRise.Take(xp); + + if (nowUtc > _movedIntoBankUntil) _movedIntoBank = 0; + + long lumUp = 0; + // ACECustom's bank first, so the character rise below already knows it is tracked. + if (s.BankLum is long bank && bank >= 0) + { + _bankTracked = true; + long up = _bankRise.Take(bank); + long moved = Math.Min(up, _movedIntoBank); + _movedIntoBank -= moved; + lumUp += up - moved; + } + long charUp = 0; + if (s.AvailableLum is long lum && lum >= 0) + { + long up = _lumRise.Take(lum); + if (!_bankTracked) charUp += up; + } + if (s.AelDrawn is long drawn) charUp -= _aelDrawnRise.Take(drawn); + if (s.AelBanked is long banked) charUp += _aelBankedRise.Take(banked); + if (charUp > 0) lumUp += charUp; + _lum += lumUp; + } + + /// <summary>The totals and per-hour rates at <paramref name="nowUtc"/> (zeros before the first sample).</summary> + public SessionRatesView View(DateTime nowUtc) + { + if (_character == 0) return new SessionRatesView(nowUtc, 0, 0, 0, 0, 0); + double seconds = Math.Max(1.0, (nowUtc - _startUtc).TotalSeconds); + double hours = seconds / 3600.0; + return new SessionRatesView(_startUtc, seconds, _xp, _xp / hours, _lum, _lum / hours); + } + + /// <summary>How much a value went up since the last read; the first read is the baseline.</summary> + private struct Rise + { + private long _last; + private bool _seen; + + public long Take(long value) + { + long up = _seen && value > _last ? value - _last : 0; + _last = value; + _seen = true; + return up; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index 25314d5..d166830 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -200,7 +200,7 @@ internal static class SmartBoxHooks ParseGameEvent(eventType, data, (uint)len); if ((eventType >= 0x02C2 && eventType <= 0x02C8) || eventType == 0x0312) enchantment = CaptureEnchantmentEvent(eventType, data, (uint)len); - // v85: a prompt a plugin armed an answer for is answered here instead of + // v81: a prompt a plugin armed an answer for is answered here instead of // opening AC's dialog. if (eventType == ConfirmationResponder.EventConfirmationRequest) answered = ConfirmationResponder.OnRequest(data, (uint)len); diff --git a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs index d7a6bf9..8e30c9d 100644 --- a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs +++ b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs @@ -67,6 +67,8 @@ internal static class D3D9Bootstrapper while (GetModuleHandleA("d3d9.dll") == IntPtr.Zero) if (!EngineThreads.Sleep(PollIntervalMs)) return; + DxvkDetection.EnsureProbed(); + DxvkDetection.ApplyOverlayPolicy(); RynthLog.D3D9("D3D9Bootstrapper: Decal in the process - discovering EndScene without creating a device."); EndSceneHook.InstallWithoutDevice("decal-live-device"); return; @@ -79,6 +81,9 @@ internal static class D3D9Bootstrapper IntPtr earlyModule = GetModuleHandleA("d3d9.dll"); if (earlyModule != IntPtr.Zero) { + // Log DXVK / non-system d3d9 early so smoke greps see it before EndScene. + DxvkDetection.EnsureProbed(); + DxvkDetection.ApplyOverlayPolicy(); RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device."); Compatibility.MemoryUse.Mark("D3D9 bootstrap: NULLREF device for the vtable"); EndSceneHook.Install("post-login-vtable"); diff --git a/src/RynthCore.Engine/D3D9/DxvkDetection.cs b/src/RynthCore.Engine/D3D9/DxvkDetection.cs new file mode 100644 index 0000000..62aa832 --- /dev/null +++ b/src/RynthCore.Engine/D3D9/DxvkDetection.cs @@ -0,0 +1,156 @@ +// RynthCore.Engine — D3D9/DxvkDetection.cs +// Detects a drop-in DXVK (or other non-system) d3d9.dll so overlay / texture +// paths that need D3D9Ex shared HANDLEs can stay on CreateTexture+LockRect. +// AC is 32-bit: only an x86 DXVK d3d9.dll next to acclient.exe is relevant. +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.D3D9; + +/// <summary> +/// One-shot probe of the loaded <c>d3d9.dll</c>. Safe to call before or after +/// EndScene install; logs a Milestone line the smoke checklist greps for. +/// </summary> +internal static class DxvkDetection +{ + private static int _probed; + private static bool _isDxvk; + private static bool _isNonSystemD3d9; + private static string _modulePath = ""; + private static string _productHint = ""; + + /// <summary>True when the in-process d3d9 looks like DXVK (version resource / product name).</summary> + public static bool IsDxvk + { + get { EnsureProbed(); return _isDxvk; } + } + + /// <summary>True when d3d9.dll is not the Windows System32/SysWOW64 copy (DXVK, dgVoodoo, etc.).</summary> + public static bool IsNonSystemD3d9 + { + get { EnsureProbed(); return _isNonSystemD3d9; } + } + + public static string ModulePath + { + get { EnsureProbed(); return _modulePath; } + } + + public static string ProductHint + { + get { EnsureProbed(); return _productHint; } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] + private static extern IntPtr GetModuleHandleA(string? lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetModuleFileNameW(IntPtr hModule, char[] lpFilename, uint nSize); + + /// <summary> + /// Probe once and, when DXVK (or any non-system d3d9) is present, force the + /// software Avalonia overlay path so shared-HANDLE uploads are never attempted. + /// </summary> + public static void ApplyOverlayPolicy() + { + EnsureProbed(); + if (!_isDxvk && !_isNonSystemD3d9) + return; + + // Shared D3D9Ex HANDLEs are not reliable under translation layers; LockRect is. + OverlaySurfaceBridge.UseSoftwareFallback(); + OverlaySurfaceBridge.NotifySharedTextureUnavailable(); + RynthLog.Milestone( + _isDxvk + ? $"DxvkDetection: DXVK d3d9 active ({_productHint}) — forcing software overlay textures (path={_modulePath})." + : $"DxvkDetection: non-system d3d9 active ({_productHint}) — forcing software overlay textures (path={_modulePath})."); + } + + /// <summary>Idempotent probe; returns whether DXVK was identified.</summary> + public static bool EnsureProbed() + { + if (Interlocked.CompareExchange(ref _probed, 1, 0) != 0) + return _isDxvk; + + try + { + IntPtr hMod = GetModuleHandleA("d3d9.dll"); + if (hMod == IntPtr.Zero) + { + RynthLog.D3D9("DxvkDetection: d3d9.dll not loaded yet — probe deferred."); + Interlocked.Exchange(ref _probed, 0); + return false; + } + + char[] buf = new char[520]; + uint n = GetModuleFileNameW(hMod, buf, (uint)buf.Length); + _modulePath = n > 0 ? new string(buf, 0, (int)n) : ""; + + string dir = Path.GetDirectoryName(_modulePath) ?? ""; + string dirLower = dir.ToLowerInvariant(); + bool inSystem = + dirLower.Contains("\\windows\\system32") || + dirLower.Contains("\\windows\\syswow64") || + dirLower.EndsWith("\\system32") || + dirLower.EndsWith("\\syswow64"); + _isNonSystemD3d9 = !inSystem && !string.IsNullOrEmpty(_modulePath); + + string product = ""; + string company = ""; + string fileDesc = ""; + string fileVer = ""; + try + { + if (!string.IsNullOrEmpty(_modulePath) && File.Exists(_modulePath)) + { + FileVersionInfo vi = FileVersionInfo.GetVersionInfo(_modulePath); + product = vi.ProductName ?? ""; + company = vi.CompanyName ?? ""; + fileDesc = vi.FileDescription ?? ""; + fileVer = vi.FileVersion ?? vi.ProductVersion ?? ""; + } + } + catch (Exception ex) + { + RynthLog.D3D9($"DxvkDetection: FileVersionInfo failed: {ex.GetType().Name}: {ex.Message}"); + } + + string blob = $"{product}|{company}|{fileDesc}|{fileVer}|{_modulePath}"; + _isDxvk = + blob.Contains("dxvk", StringComparison.OrdinalIgnoreCase) || + File.Exists(Path.Combine(dir, "dxvk.conf")) || + File.Exists(Path.Combine(dir, "d3d9.dll.conf")); + + _productHint = string.IsNullOrWhiteSpace(product) + ? (string.IsNullOrWhiteSpace(fileDesc) ? (fileVer.Length > 0 ? fileVer : "unknown") : fileDesc) + : product; + if (!string.IsNullOrWhiteSpace(fileVer) && !_productHint.Contains(fileVer, StringComparison.Ordinal)) + _productHint = $"{_productHint} {fileVer}".Trim(); + + if (_isDxvk) + { + RynthLog.Milestone($"DxvkDetection: DXVK detected — {_productHint} @ {_modulePath}"); + } + else if (_isNonSystemD3d9) + { + RynthLog.Milestone($"DxvkDetection: non-system d3d9.dll (not DXVK by name) — {_productHint} @ {_modulePath}"); + } + else + { + RynthLog.D3D9($"DxvkDetection: stock system d3d9.dll — {_productHint} @ {_modulePath}"); + } + + return _isDxvk; + } + catch (Exception ex) + { + RynthLog.D3D9($"DxvkDetection: probe threw {ex.GetType().Name}: {ex.Message}"); + Interlocked.Exchange(ref _probed, 0); + return false; + } + } +} diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index c408256..e1b1c7b 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -444,6 +444,10 @@ internal static class EndSceneHook EngineFrameController.OnEndScene(pDevice); _uiFrameCount++; + // AC's real drawing size, about once a second: the window code sizes the window for it. + if (_uiFrameCount % 60 == 1) + Graphics.AcGraphics.SampleBackBuffer(pDevice); + if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend) RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable."); if (_renderCount == WarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend) diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 1f58e84..018d5ad 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -136,12 +136,32 @@ public static class EntryPoint return 0; } + /// <summary> + /// Loader asks before tearing the engine down (loader 2.2+): 1 = reload now, 0 = wait + /// (still in the world; poll again). Missing export = old engines, loader proceeds. + /// Only with engine.json HoldReloadInWorld on (opt-in, default off): then the loader waits while + /// the player is in the world, a manual ERl included, since a mid-session CoreCLR re-init can + /// still AV (2026-10-16.5). Off: 1. Loader thread; never throws. + /// </summary> + [UnmanagedCallersOnly(EntryPoint = "RynthCoreMayHotReload")] + public static int MayHotReload() + { + try + { + if (!EngineSettings.HoldReloadInWorld) return 1; + return IsInWorldForAutoReloadDeferral() ? 0 : 1; + } + catch { return 1; } // fail open so a gate bug cannot wedge the loader forever + } + [UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")] public static uint Shutdown(IntPtr lpParam) { // Only the loader's hot reload calls this export (process exit and the engine's own // teardowns call EngineLifecycle.Shutdown directly), on its reload thread: wait here, // with the game running on this engine, while a plugin says a reload now would hurt. + // Also holds automatic reloads while in-world (ReloadInWorldGate) so old loaders that + // never call MayHotReload still avoid mid-session CoreCLR re-init crashes. try { DeferReloadWhilePluginsObject(); } catch { } try { @@ -261,6 +281,7 @@ public static class EntryPoint RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins."); return; } + var deferral = new ReloadDeferral { Query = PluginManager.QueryReloadBlockers, @@ -273,6 +294,28 @@ public static class EntryPoint RynthLog.Info($"engine reload: deferral {outcome} after {waited.TotalSeconds:0.0} s."); } + /// <summary> + /// Player asked for an engine reload (ERl / /rc rl / hotkey). While in-world the loader + /// keeps holding; we still signal so it applies on logout, and say so in chat once. + /// </summary> + internal static void RequestManualReload(string source) + { + NoteManualReload(); + if (EngineSettings.HoldReloadInWorld && IsInWorldForAutoReloadDeferral()) + { + RynthLog.Info($"{source}: in-world — signaling reload; loader holds until logout / character select."); + try + { + Compatibility.AcMainThreadQueue.EnqueueWriteToChat( + "[RynthCore] Engine reload will apply when you leave the world (logout / character select). Mid-session hot reload crashes the client.", 1); + } + catch { /* chat must not block the signal */ } + } + else + RynthLog.Info($"{source}: signaling reload."); + EngineLifecycle.SignalReload(); + } + private static uint InitializeCore(IntPtr lpParam) { if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) @@ -682,11 +725,10 @@ public static class EntryPoint { // RynthILT's ILT tabs in RynthAi's Mini Remote (shown once the server reports each on). // A RynthAi that doesn't publish sections gets these stand-ins; one that does lists them itself. - // Character (the generic overview) is RynthOracle's Character tab since 2026.10.5.54; - // the Leaftide tabs (Charms, Banking, Gear, Games) stay RynthILT's. + // Character and Charms are RynthOracle's Character tab and Banking is RynthInventory's + // Global Inventory since 2026.10.5.54, so only Gear and Games are left here. foreach ((string label, string tab, string section) in new[] { - ("Charms", "charms", "inventory"), ("Banking", "banking", "inventory"), ("Gear", "gear", "inventory"), ("Games", "games", "fellowship"), }) { diff --git a/src/RynthCore.Engine/Graphics/AcGraphics.cs b/src/RynthCore.Engine/Graphics/AcGraphics.cs new file mode 100644 index 0000000..79cf427 --- /dev/null +++ b/src/RynthCore.Engine/Graphics/AcGraphics.cs @@ -0,0 +1,464 @@ +// ============================================================================ +// RynthCore.Engine - Graphics/AcGraphics.cs +// The engine side of RynthAi's Settings > Graphics (AcGraphicsPrefs.cs has the +// shared model): this account's graphics profile, the edits from the panel, +// and the size AC really draws at (for the window code). +// +// Per account (2026.10.18.3): graphics.json holds a profile per "server|account". +// A client edits only its own account's profile, re-reading the file first so it +// never overwrites another client's. The launcher writes the launching account's +// profile into UserPreferences.ini just before that client starts. +// +// Never fights AC live (2026.10.18.3): the window is sized for the resolution AC +// is actually drawing (its back buffer, sampled from EndScene; else what it +// launched with), never for a Graphics value AC isn't using yet. A Resolution +// set here applies at the next launch. Clients don't write the shared INI on an +// edit either (each would put its own account's values over the others'); only +// the launcher, and "Write to AC's settings now", do. +// +// Window mode is the exception that applies now: it is RynthCore's own window +// chrome (AcWindowChrome), not an AC setting (except exclusive full screen, which +// starts at the next launch). +// +// Threads: reads are cheap snapshots from any thread; edits come from the +// Settings panel (AC's main thread) and queue their file writes on +// UiBackgroundWriter. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; +using RynthCore.Graphics; + +namespace RynthCore.Engine.Graphics; + +internal static class AcGraphics +{ + private static readonly object Sync = new(); + private static AcGraphicsProfiles _profiles = new(); // under Sync + private static bool _loaded; + private static DateTime _configStamp; + private static long _nextReloadCheck; + // UserPreferences.ini as AC launched with it (read once, at the first use). + private static Dictionary<string, string>? _launchIni; + private static string _launchContextKey = ""; + private static string _launchAccountName = ""; + // AC's back buffer, sampled from EndScene (0 = not seen yet). + private static int _backBufferW, _backBufferH; + + // ── Reads ──────────────────────────────────────────────────────────────── + + /// <summary>"server|account" of this client: the logged-in one, else the launch context's.</summary> + public static string AccountKey + { + get + { + string key = AcGraphicsPrefs.AccountKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastAccountName); + if (key.Length > 0) return key; + EnsureLoaded(); + return _launchContextKey; + } + } + + /// <summary>This client's account name for the panel, empty before one is known.</summary> + public static string AccountName + { + get + { + string name = SessionStateRegistry.LastAccountName; + if (name.Length > 0) return name; + EnsureLoaded(); + return _launchAccountName; + } + } + + /// <summary>A copy of this account's profile (empty when it has none).</summary> + private static AcGraphicsConfig Profile() + { + string key = AccountKey; + lock (Sync) { EnsureLoadedLocked(); return _profiles.For(key).Clone(); } + } + + /// <summary>The size AC is drawing at: its back buffer once seen, else the resolution it launched + /// with. The window is sized for this, so it never fights AC's own resolution.</summary> + public static bool TryGetDrawSize(out int width, out int height) + { + width = Volatile.Read(ref _backBufferW); + height = Volatile.Read(ref _backBufferH); + if (width >= 640 && height >= 480) return true; + return AcGraphicsPrefs.TryParseResolution(LaunchValue(AcGraphicsPrefs.ResolutionId), out width, out height); + } + + /// <summary>EndScene, about once a second: remembers AC's back-buffer size.</summary> + public static void SampleBackBuffer(IntPtr device) + { + if (!ImGuiBackend.DX9Backend.TryGetBackBufferSize(device, out int w, out int h)) return; + int oldW = Volatile.Read(ref _backBufferW), oldH = Volatile.Read(ref _backBufferH); + if (w == oldW && h == oldH) return; + Volatile.Write(ref _backBufferW, w); + Volatile.Write(ref _backBufferH, h); + RynthLog.UI($"AcGraphics: AC draws at {w}x{h}" + (oldW > 0 ? $" (was {oldW}x{oldH})." : ".")); + } + + /// <summary>The window mode in effect (one of AcGraphicsPrefs.WindowModeIds): this account's, else + /// the Display toggles'.</summary> + public static string WindowMode => Profile().WindowMode ?? LegacyWindowMode(); + + /// <summary>The account's own window mode, or null (the Display toggles decide).</summary> + public static string? ProfileWindowMode => Profile().WindowMode; + + /// <summary>RynthCore should strip the window frame (either borderless mode).</summary> + public static bool WantBorderless => WindowMode is AcGraphicsPrefs.ModeBorderlessFill or AcGraphicsPrefs.ModeBorderlessSized; + + /// <summary>Borderless fills the monitor (else it is AC's drawing size).</summary> + public static bool FillMonitor => WindowMode != AcGraphicsPrefs.ModeBorderlessSized; + + /// <summary>The value this account enforces for <paramref name="id"/> ("Section.Key"), or null (AC's choice).</summary> + public static string? Get(string id) => Profile().Values.TryGetValue(id, out string? v) ? v : null; + + /// <summary>What AC launched with for <paramref name="id"/>, or null.</summary> + public static string? LaunchValue(string id) + { + EnsureLoaded(); + Dictionary<string, string>? ini = Volatile.Read(ref _launchIni); + return ini != null && ini.TryGetValue(id, out string? v) ? v : null; + } + + // ── Edits (Settings > Graphics), this account's profile only ───────────── + + /// <summary>Sets (or with null clears: AC's choice) a value in this account's profile.</summary> + public static void Set(string id, string? value) => + Edit(cfg => { if (value == null) cfg.Values.Remove(id); else cfg.Values[id] = value; }, windowChanged: false); + + /// <summary>Sets this account's window mode (null clears it: the Display toggles decide).</summary> + public static void SetWindowMode(string? mode) => Edit(cfg => cfg.WindowMode = mode, windowChanged: true); + + /// <summary>"Reset Window Borders": this account's window mode becomes Windowed if it was set. Saves only.</summary> + public static void ResetWindowModeToWindowed() + { + if (Profile().WindowMode is null or AcGraphicsPrefs.ModeWindowed) return; + Edit(cfg => cfg.WindowMode = AcGraphicsPrefs.ModeWindowed, windowChanged: false); + } + + /// <summary>The Display toggles were used: this account's window mode is cleared so they decide again. Saves only.</summary> + public static void DisplayTogglesChanged() + { + if (Profile().WindowMode == null) return; + Edit(cfg => cfg.WindowMode = null, windowChanged: false); + } + + /// <summary>Clears this account's whole profile (AC's own settings stay as they are).</summary> + public static void ResetAll() => Edit(cfg => { cfg.Values.Clear(); cfg.WindowMode = null; }, windowChanged: true); + + /// <summary>"Write to AC's settings now": this account's profile into UserPreferences.ini.</summary> + public static void WriteIniNow() + { + Dictionary<string, string> values = Profile().IniValues(); + UI.UiBackgroundWriter.Enqueue("graphics settings (write now)", () => + { + try + { + if (values.Count == 0) { RynthLog.UI("AcGraphics: nothing to write (every setting is AC's choice)."); return; } + foreach (string ini in AcGraphicsPrefs.IniPaths(Environment.CurrentDirectory)) + { + List<string> changed = AcPrefsIni.Apply(ini, values); + RynthLog.UI(changed.Count > 0 + ? $"AcGraphics: wrote {string.Join(", ", changed)} to {ini}." + : $"AcGraphics: {ini} already matches this account's profile."); + } + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: writing UserPreferences.ini failed - {ex.Message}"); } + }); + } + + /// <summary>Called by the window code every couple of seconds: picks up another client's edits.</summary> + public static void PollReload() + { + long now = Environment.TickCount64; + if (now < _nextReloadCheck) return; + _nextReloadCheck = now + 3000; + try + { + DateTime stamp = File.Exists(AcGraphicsPrefs.ConfigPath) ? File.GetLastWriteTimeUtc(AcGraphicsPrefs.ConfigPath) : default; + lock (Sync) + { + if (!_loaded || stamp == _configStamp) return; + } + AcGraphicsProfiles all = AcGraphicsProfiles.Load(AcGraphicsPrefs.ConfigPath); + lock (Sync) { _profiles = all; _configStamp = stamp; } + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: re-read failed - {ex.Message}"); } + } + + /// <summary>One line for the top of Settings > Graphics.</summary> + public static string StatusLine() + { + string launched = LaunchValue(AcGraphicsPrefs.ResolutionId) ?? "?"; + bool launchedFull = string.Equals(LaunchValue(AcGraphicsPrefs.FullScreenId), "True", StringComparison.OrdinalIgnoreCase); + string draws = TryGetDrawSize(out int w, out int h) ? w + "x" + h : "?"; + int modeIdx = Array.IndexOf(AcGraphicsPrefs.WindowModeIds, WindowMode); + string mode = modeIdx >= 0 ? AcGraphicsPrefs.WindowModeLabels[modeIdx] : WindowMode; + string who = AccountName.Length > 0 ? $"Profile for account '{AccountName}'. " : "No account known yet. "; + return $"{who}AC started at {launched}{(launchedFull ? " full screen" : "")} and draws at {draws}; window: {mode}."; + } + + // ── Display modes for the panel ────────────────────────────────────────── + + /// <summary>The primary monitor's resolutions (24/32-bit), largest first, plus the launched one.</summary> + public static string[] AvailableResolutions() + { + var set = new SortedSet<(int W, int H)>(Comparer<(int W, int H)>.Create((a, b) => b.W != a.W ? b.W.CompareTo(a.W) : b.H.CompareTo(a.H))); + foreach (DEVMODE dm in DisplayModes()) + if (dm.dmBitsPerPel >= 24 && dm.dmPelsWidth >= 800 && dm.dmPelsHeight >= 600) + set.Add((dm.dmPelsWidth, dm.dmPelsHeight)); + if (AcGraphicsPrefs.TryParseResolution(LaunchValue(AcGraphicsPrefs.ResolutionId), out int lw, out int lh)) set.Add((lw, lh)); + var list = new List<string>(); + foreach ((int w, int h) in set) list.Add(w + "x" + h); + return list.ToArray(); + } + + /// <summary>The primary monitor's refresh rates (Hz), highest first.</summary> + public static string[] AvailableRefreshRates() + { + var set = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a))); + foreach (DEVMODE dm in DisplayModes()) + if (dm.dmDisplayFrequency > 1) set.Add(dm.dmDisplayFrequency); + var list = new List<string>(); + foreach (int hz in set) list.Add(hz.ToString(System.Globalization.CultureInfo.InvariantCulture)); + return list.ToArray(); + } + + // ── Memory safeguard (2026.10.18.11) ───────────────────────────────────── + + // A client this short of address space this soon after it started is being filled by AC's own + // loading (seen: 450 MB -> 3.1 GB in 13 s after login with Adaptive degrade off), not a slow leak. + private const long LowFreeMb = 200, LowLargestFreeMb = 128; + private const double LowMemoryWindowMinutes = 10; + private static int _lowMemoryHandled; + private static string _lowMemoryNote = string.Empty; + private static readonly DateTime ProcessStartLocal = ReadProcessStart(); + + private static DateTime ReadProcessStart() + { + try { return System.Diagnostics.Process.GetCurrentProcess().StartTime; } + catch { return DateTime.Now; } + } + + /// <summary>What AC uses for <paramref name="id"/>: this account's value, else what it launched with.</summary> + private static string? Effective(string id) => Get(id) ?? LaunchValue(id); + + /// <summary>The Graphics panel's warning: Adaptive degrade off with a far draw distance (empty when fine), + /// plus what the low-memory fallback did this session.</summary> + public static string MemoryWarning() + { + string risk = AcGraphicsPrefs.MemoryRisk(Effective(AcGraphicsPrefs.AutomaticDegradesId), + Effective(AcGraphicsPrefs.SceneryDrawDistanceId), Effective(AcGraphicsPrefs.LandscapeDrawDistanceId)); + string note = Volatile.Read(ref _lowMemoryNote); + return note.Length == 0 ? risk : risk.Length == 0 ? note : note + "\n" + risk; + } + + /// <summary> + /// Heartbeat (once a second, its own thread): when the address space is nearly gone within + /// <see cref="LowMemoryWindowMinutes"/> of the client starting and AC runs with Adaptive degrade + /// off, this account's profile turns it back on, saved at once (the client may be about to + /// die), so the launcher writes it into UserPreferences.ini at the next launch. Once a session. + /// </summary> + public static void CheckLowMemory(long freeMb, long largestFreeMb) + { + bool low = (freeMb >= 0 && freeMb < LowFreeMb) || (largestFreeMb >= 0 && largestFreeMb < LowLargestFreeMb); + if (!low || Volatile.Read(ref _lowMemoryHandled) != 0) return; + if ((DateTime.Now - ProcessStartLocal).TotalMinutes > LowMemoryWindowMinutes) return; + if (Interlocked.Exchange(ref _lowMemoryHandled, 1) != 0) return; + + string? degrade = Effective(AcGraphicsPrefs.AutomaticDegradesId); + string where = $"free address space {freeMb} MB, largest block {largestFreeMb} MB, " + + $"{(DateTime.Now - ProcessStartLocal).TotalSeconds:0} s after the client started"; + if (!string.Equals(degrade, "False", StringComparison.OrdinalIgnoreCase)) + { + RynthLog.UI($"AcGraphics: low memory ({where}); Adaptive degrade is already {(degrade ?? "AC's default")}, nothing changed."); + return; + } + string key = AccountKey; + if (key.Length == 0) + { + RynthLog.UI($"AcGraphics: low memory ({where}) with Adaptive degrade off, but no account is known; nothing changed."); + return; + } + try + { + AcGraphicsConfig mine; + lock (Sync) + { + EnsureLoadedLocked(); + mine = _profiles.For(key).Clone(); + mine.Values[AcGraphicsPrefs.AutomaticDegradesId] = "True"; + _profiles.Put(key, mine); + } + SaveAccountProfile(key, mine); + string scenery = Effective(AcGraphicsPrefs.SceneryDrawDistanceId) ?? "AC's default"; + Volatile.Write(ref _lowMemoryNote, + $"This client ran low on memory {(DateTime.Now - ProcessStartLocal).TotalSeconds:0} s after it started, with Adaptive degrade off " + + $"(scenery distance {scenery}): Adaptive degrade is now on for this account from the next launch."); + RynthLog.UI($"AcGraphics: LOW MEMORY ({where}) with Adaptive degrade off: turned it on in {key}'s profile; " + + $"the launcher writes it into UserPreferences.ini at the next launch (scenery distance {scenery})."); + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: low-memory fallback failed - {ex.Message}"); } + } + + // ── Internals ──────────────────────────────────────────────────────────── + + /// <summary>Re-reads graphics.json and replaces only <paramref name="key"/>'s entry. Any thread.</summary> + private static void SaveAccountProfile(string key, AcGraphicsConfig mine) + { + string path = AcGraphicsPrefs.ConfigPath; + AcGraphicsProfiles onDisk = AcGraphicsProfiles.Load(path); + onDisk.Put(key, mine); + onDisk.Save(path); + lock (Sync) + { + _profiles = onDisk; + _configStamp = File.GetLastWriteTimeUtc(path); + } + } + + private static string LegacyWindowMode() => + !EngineSettings.BorderlessWindowed ? AcGraphicsPrefs.ModeWindowed + : EngineSettings.BorderlessFillMonitor ? AcGraphicsPrefs.ModeBorderlessFill + : AcGraphicsPrefs.ModeBorderlessSized; + + /// <summary>Changes this account's profile in memory and queues the save (re-read, replace this + /// account's entry, write), so another client's account is never overwritten.</summary> + private static void Edit(Action<AcGraphicsConfig> change, bool windowChanged) + { + string key = AccountKey; + if (key.Length == 0) + { + RynthLog.UI("AcGraphics: no account known yet; graphics change not saved."); + return; + } + AcGraphicsConfig mine; + lock (Sync) + { + EnsureLoadedLocked(); + mine = _profiles.For(key).Clone(); + change(mine); + _profiles.Put(key, mine); + } + QueueSave(); + if (!windowChanged) return; + try { UI.AcWindowChrome.ApplyGraphicsChanged(UI.AcWindowChrome.ResolveGameHwndForSettings()); } + catch (Exception ex) { RynthLog.UI($"AcGraphics: window apply failed - {ex.Message}"); } + } + + // One queued save at a time: a slider drag edits every frame, and the job saves whatever is + // current when it runs (an edit after it starts queues the next one). + private static int _saveQueued; + + private static void QueueSave() + { + if (Interlocked.Exchange(ref _saveQueued, 1) == 1) return; + UI.UiBackgroundWriter.Enqueue("graphics settings", () => + { + Volatile.Write(ref _saveQueued, 0); + string key = AccountKey; + AcGraphicsConfig mine; + lock (Sync) { mine = _profiles.For(key).Clone(); } + // Only this account's entry changes: the others come from the file as it is now. + try { SaveAccountProfile(key, mine); } + catch (Exception ex) { RynthLog.UI($"AcGraphics: saving graphics.json failed - {ex.Message}"); } + }); + } + + private static void EnsureLoaded() + { + lock (Sync) EnsureLoadedLocked(); + } + + private static void EnsureLoadedLocked() + { + if (_loaded) return; + _loaded = true; + try + { + string path = AcGraphicsPrefs.ConfigPath; + _profiles = AcGraphicsProfiles.Load(path); + _configStamp = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : default; + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: reading graphics.json failed - {ex.Message}"); } + try + { + // The game folder's INI first (this install's clients read and write it). + foreach (string ini in AcGraphicsPrefs.IniPaths(Environment.CurrentDirectory)) + { + _launchIni = AcPrefsIni.Read(ini); + if (_launchIni.Count > 0) break; + } + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: reading UserPreferences.ini failed - {ex.Message}"); } + try + { + (string account, string server, _) = CharacterCaptureHooks.ReadLaunchContext(); + _launchContextKey = AcGraphicsPrefs.AccountKey(server, account); + _launchAccountName = account ?? ""; + } + catch { /* no launch context: a client the launcher didn't start */ } + } + + private static IEnumerable<DEVMODE> DisplayModes() + { + var list = new List<DEVMODE>(); + try + { + var dm = new DEVMODE { dmSize = (short)Marshal.SizeOf<DEVMODE>() }; + for (int i = 0; EnumDisplaySettings(null, i, ref dm) && i < 2000; i++) + { + list.Add(dm); + dm = new DEVMODE { dmSize = (short)Marshal.SizeOf<DEVMODE>() }; + } + } + catch (Exception ex) { RynthLog.UI($"AcGraphics: listing display modes failed - {ex.Message}"); } + return list; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct DEVMODE + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName; + public short dmSpecVersion; + public short dmDriverVersion; + public short dmSize; + public short dmDriverExtra; + public int dmFields; + public int dmPositionX; + public int dmPositionY; + public int dmDisplayOrientation; + public int dmDisplayFixedOutput; + public short dmColor; + public short dmDuplex; + public short dmYResolution; + public short dmTTOption; + public short dmCollate; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName; + public short dmLogPixels; + public int dmBitsPerPel; + public int dmPelsWidth; + public int dmPelsHeight; + public int dmDisplayFlags; + public int dmDisplayFrequency; + public int dmICMMethod; + public int dmICMIntent; + public int dmMediaType; + public int dmDitherType; + public int dmReserved1; + public int dmReserved2; + public int dmPanningWidth; + public int dmPanningHeight; + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern bool EnumDisplaySettings(string? deviceName, int modeNum, ref DEVMODE devMode); +} diff --git a/src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs b/src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs new file mode 100644 index 0000000..1c12b0d --- /dev/null +++ b/src/RynthCore.Engine/Graphics/AcGraphicsPrefs.cs @@ -0,0 +1,384 @@ +// ============================================================================ +// RynthCore.Engine - Graphics/AcGraphicsPrefs.cs +// AC's graphics settings (the retail Options > Graphics and Rendering pages), +// kept by RynthAi in %APPDATA%\RynthCore\graphics.json and enforced on AC's +// UserPreferences.ini every launch, so a value set in RynthAi wins over +// whatever AC (or its own options page) last wrote there. +// +// Shared source: compiled into the engine AND the launcher +// (RynthCore.App.Avalonia links this file), so it depends on nothing else. +// +// Model: one profile per account ("server|account", lower case; 2026.10.18.3 - +// a single shared set made every client fight over one resolution). A profile: +// - Values: "Section.Key" -> the value as AC writes it ("Medium", "True", +// "0.89", "1760x990"). A key not in Values is "AC's choice": never touched. +// - WindowMode: Windowed / BorderlessFill / BorderlessSized / FullScreen +// (null = not set). FullScreen writes Display.FullScreen=True, every other +// mode False; the borderless modes are RynthCore's window chrome. +// The launcher writes the launching account's profile into UserPreferences.ini +// just before that client starts. The 2026.10.18.1 single global set is ignored. +// +// The value lists come from acclient.exe's own strings (Render.* keys and the +// ID_Graphics_Value_* / TextureFiltering_* labels): VeryLow..Extreme, Bilinear / +// Trilinear / Sharp / Anisotropic, Normal / Wide, RefreshRate Auto or Hz. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Graphics; + +/// <summary>How a graphics setting is edited.</summary> +public enum AcGraphicsKind { Choice, Bool, Float } + +/// <summary>One AC graphics setting: its UserPreferences.ini place, its label, and its values.</summary> +public sealed record AcGraphicsSetting( + string Section, + string Key, + string Label, + AcGraphicsKind Kind, + string[]? Choices = null, + double Min = 0, + double Max = 1, + double Step = 0.01, + string Help = "") +{ + /// <summary>"Section.Key", the id used in graphics.json.</summary> + public string Id => Section + "." + Key; +} + +/// <summary>The settings, window modes and the INI file AC reads.</summary> +public static class AcGraphicsPrefs +{ + public const string ResolutionId = "Display.Resolution"; + public const string FullScreenId = "Display.FullScreen"; + public const string RefreshRateId = "Display.RefreshRate"; + public const string SyncToRefreshId = "Display.SyncToRefresh"; + public const string AutomaticDegradesId = "Render.AutomaticDegrades"; + public const string SceneryDrawDistanceId = "Render.SceneryDrawDistance"; + public const string LandscapeDrawDistanceId = "Render.LandscapeDrawDistance"; + + /// <summary> + /// The 32-bit client's memory risk (2026-10-18: a tester's client filled its 4 GB in 13 s after + /// login and died, every launch, once Adaptive degrade was off with a far scenery distance): + /// with degrades off AC loads every object in range at full detail. The warning text, or empty. + /// The values are what AC uses (this account's, else the INI's); null reads as AC's default. + /// </summary> + public static string MemoryRisk(string? automaticDegrades, string? sceneryDistance, string? landscapeDistance) + { + if (!string.Equals(automaticDegrades?.Trim(), "False", StringComparison.OrdinalIgnoreCase)) return string.Empty; + static bool Far(string? d) => Array.IndexOf(DistanceLevels, d?.Trim() ?? "") >= Array.IndexOf(DistanceLevels, "High"); + if (!Far(sceneryDistance) && !Far(landscapeDistance)) return string.Empty; + return "Warning: Adaptive degrade is off with a far draw distance. AC then loads everything in range at full detail\n" + + "and can run out of memory (a 32-bit client has 4 GB) in a busy town, freezing and closing right after login.\n" + + "Turn Adaptive degrade on, or lower the scenery / landscape draw distance to Medium."; + } + + // Window modes: ids stored in graphics.json, labels shown in the panel (same order). + public const string ModeWindowed = "Windowed"; + public const string ModeBorderlessFill = "BorderlessFill"; + public const string ModeBorderlessSized = "BorderlessSized"; + public const string ModeFullScreen = "FullScreen"; + public static readonly string[] WindowModeIds = { ModeWindowed, ModeBorderlessFill, ModeBorderlessSized, ModeFullScreen }; + public static readonly string[] WindowModeLabels = + { "Windowed", "Borderless (fill the monitor)", "Borderless (resolution size)", "Full screen (exclusive)" }; + + private static readonly string[] DetailLevels = { "VeryLow", "Low", "Medium", "High", "VeryHigh" }; + private static readonly string[] DistanceLevels = { "VeryLow", "Low", "Medium", "High", "VeryHigh", "Extreme" }; + + /// <summary>The Render settings (retail Graphics page), in the retail page's order.</summary> + public static readonly AcGraphicsSetting[] RenderSettings = + { + new("Render", "LandscapeDrawDistance", "Landscape draw distance", AcGraphicsKind.Choice, DistanceLevels, + Help: "How far away the land is drawn."), + new("Render", "SceneryDrawDistance", "Scenery draw distance", AcGraphicsKind.Choice, DistanceLevels, + Help: "How far away trees, rocks and other scenery are drawn."), + new("Render", "LandscapeTextureDetail", "Landscape texture detail", AcGraphicsKind.Choice, DetailLevels, + Help: "Detail of the ground textures."), + new("Render", "EnvironmentTextureDetail", "Environment texture detail", AcGraphicsKind.Choice, DetailLevels, + Help: "Detail of building, dungeon and object textures."), + new("Render", "TextureFiltering", "Texture filtering", AcGraphicsKind.Choice, + new[] { "Bilinear", "Trilinear", "Sharp", "Anisotropic" }, + Help: "How textures are smoothed: Bilinear is the cheapest, Anisotropic the sharpest at an angle."), + new("Render", "LandscapeDetailTextures", "Landscape detail textures", AcGraphicsKind.Bool, + Help: "Extra close-up detail on the ground."), + new("Render", "BuildingDetailTextures", "Building detail textures", AcGraphicsKind.Bool, + Help: "Extra close-up detail on buildings."), + new("Render", "MultiPassAlpha", "Multi-pass alpha", AcGraphicsKind.Bool, + Help: "Better see-through surfaces (foliage, water) at some cost."), + new("Render", "FieldOfView", "Field of view", AcGraphicsKind.Float, Min: 60, Max: 160, Step: 1, + Help: "The camera's field of view."), + new("Render", "ScreenBrightness", "Screen brightness", AcGraphicsKind.Float, Min: -1, Max: 1, Step: 0.05, + Help: "Gamma: 0 is AC's default."), + new("Render", "AspectRatio", "Aspect ratio", AcGraphicsKind.Choice, new[] { "Normal", "Wide" }, + Help: "Wide for a widescreen resolution, so the picture isn't stretched."), + new("Render", "AutomaticDegrades", "Adaptive degrade", AcGraphicsKind.Bool, + Help: "Let AC lower detail on its own to keep the frame rate up."), + new("Render", "GraphicsPerformance", "Adaptive degrade bias", AcGraphicsKind.Float, Min: -1, Max: 1, Step: 0.05, + Help: "With adaptive degrade on: lower favours speed, higher favours looks."), + new("Render", "DegradeDistance", "Degrade distance", AcGraphicsKind.Float, Min: 0, Max: 1, Step: 0.01, + Help: "How far away objects start being drawn with less detail (higher = further)."), + }; + + /// <summary>Display.SyncToRefresh (retail "Sync to display refresh").</summary> + public static readonly AcGraphicsSetting SyncToRefresh = + new("Display", "SyncToRefresh", "Sync to display refresh", AcGraphicsKind.Bool, + Help: "VSync: no tearing, the frame rate capped at the monitor's refresh."); + + /// <summary>Where the config is kept (all clients on this PC).</summary> + public static string ConfigPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "graphics.json"); + + /// <summary>The UserPreferences.ini files AC may read: the game folder's (this install's clients + /// write it) and My Documents\Asheron's Call's. Only existing ones; the game folder's when neither is.</summary> + public static List<string> IniPaths(string? gameDirectory) + { + var list = new List<string>(); + string? gameIni = string.IsNullOrWhiteSpace(gameDirectory) ? null : Path.Combine(gameDirectory, "UserPreferences.ini"); + string docsIni = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", "UserPreferences.ini"); + if (gameIni != null && File.Exists(gameIni)) list.Add(gameIni); + if (File.Exists(docsIni)) list.Add(docsIni); + if (list.Count == 0 && gameIni != null) list.Add(gameIni); + return list; + } + + /// <summary>"server|account", trimmed and lower case; empty when either is missing.</summary> + public static string AccountKey(string? server, string? account) + { + string s = (server ?? "").Trim(), a = (account ?? "").Trim(); + if (s.Length == 0 || a.Length == 0) return ""; + return (s + "|" + a).ToLowerInvariant(); + } + + /// <summary>"1760x990" -> (1760, 990); false for anything else.</summary> + public static bool TryParseResolution(string? text, out int width, out int height) + { + width = height = 0; + if (string.IsNullOrWhiteSpace(text)) return false; + string[] parts = text.Trim().ToLowerInvariant().Split('x'); + return parts.Length == 2 + && int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out width) + && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out height) + && width >= 640 && height >= 480 && width <= 16384 && height <= 16384; + } + + /// <summary>A float as AC writes it ("0.89").</summary> + public static string FormatFloat(double v) => v.ToString("0.00", CultureInfo.InvariantCulture); +} + +/// <summary>One account's graphics profile: what RynthAi enforces on AC's graphics settings.</summary> +public sealed class AcGraphicsConfig +{ + public Dictionary<string, string> Values { get; } = new(StringComparer.OrdinalIgnoreCase); + public string? WindowMode { get; set; } + + /// <summary>True when there is anything to enforce.</summary> + public bool HasAny => Values.Count > 0 || WindowMode != null; + + /// <summary>Every "Section.Key" -> value to write (FullScreen from the window mode).</summary> + public Dictionary<string, string> IniValues() + { + var map = new Dictionary<string, string>(Values, StringComparer.OrdinalIgnoreCase); + if (WindowMode != null) map[AcGraphicsPrefs.FullScreenId] = WindowMode == AcGraphicsPrefs.ModeFullScreen ? "True" : "False"; + return map; + } + + public AcGraphicsConfig Clone() + { + var copy = new AcGraphicsConfig { WindowMode = WindowMode }; + foreach (KeyValuePair<string, string> kv in Values) copy.Values[kv.Key] = kv.Value; + return copy; + } + + internal static AcGraphicsConfig Parse(JsonElement el) + { + var cfg = new AcGraphicsConfig(); + if (el.TryGetProperty("values", out JsonElement vals) && vals.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in vals.EnumerateObject()) + if (p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() is { Length: > 0 } v) + cfg.Values[p.Name] = v; + if (el.TryGetProperty("windowMode", out JsonElement wm) && wm.ValueKind == JsonValueKind.String + && Array.IndexOf(AcGraphicsPrefs.WindowModeIds, wm.GetString()) >= 0) + cfg.WindowMode = wm.GetString(); + return cfg; + } + + internal void Write(Utf8JsonWriter w) + { + w.WriteStartObject("values"); + foreach (KeyValuePair<string, string> kv in Values) w.WriteString(kv.Key, kv.Value); + w.WriteEndObject(); + if (WindowMode != null) w.WriteString("windowMode", WindowMode); + } +} + +/// <summary>graphics.json: a graphics profile per account ("server|account").</summary> +public sealed class AcGraphicsProfiles +{ + public Dictionary<string, AcGraphicsConfig> Accounts { get; } = new(StringComparer.OrdinalIgnoreCase); + + /// <summary>The account's profile, or an empty one (not added) when it has none.</summary> + public AcGraphicsConfig For(string accountKey) => + accountKey.Length > 0 && Accounts.TryGetValue(accountKey, out AcGraphicsConfig? c) ? c : new AcGraphicsConfig(); + + /// <summary>Sets (or with an empty profile removes) one account's profile.</summary> + public void Put(string accountKey, AcGraphicsConfig cfg) + { + if (accountKey.Length == 0) return; + if (cfg.HasAny) Accounts[accountKey] = cfg; + else Accounts.Remove(accountKey); + } + + public static AcGraphicsProfiles Load(string path) + { + var all = new AcGraphicsProfiles(); + if (!File.Exists(path)) return all; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path)); + // Only "accounts": the 2026.10.18.1 file's top-level "values" / "characters" were one set for + // every client (each fought the others over one resolution) and are left unused. + if (doc.RootElement.TryGetProperty("accounts", out JsonElement accounts) && accounts.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in accounts.EnumerateObject()) + { + if (p.Value.ValueKind != JsonValueKind.Object) continue; + AcGraphicsConfig cfg = AcGraphicsConfig.Parse(p.Value); + if (cfg.HasAny) all.Accounts[p.Name] = cfg; + } + return all; + } + + public string ToJson() + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteString("comment", "AC graphics profiles per account (server|account) that RynthAi enforces on UserPreferences.ini when the launcher starts that account (Settings > Graphics)."); + w.WriteStartObject("accounts"); + foreach (KeyValuePair<string, AcGraphicsConfig> kv in Accounts) + { + if (!kv.Value.HasAny) continue; + w.WriteStartObject(kv.Key); + kv.Value.Write(w); + w.WriteEndObject(); + } + w.WriteEndObject(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + /// <summary>Writes graphics.json atomically (temp file, then swap).</summary> + public void Save(string path) + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + AcPrefsIni.WriteAtomic(path, ToJson()); + } +} + +/// <summary>Reads and edits UserPreferences.ini, keeping every line it doesn't change.</summary> +public static class AcPrefsIni +{ + /// <summary>"Section.Key" -> value for every key in the file.</summary> + public static Dictionary<string, string> Read(string path) + { + var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + if (!File.Exists(path)) return map; + string section = ""; + foreach (string raw in ReadLinesShared(path)) + { + string line = raw.Trim(); + if (line.StartsWith('[') && line.EndsWith(']')) { section = line[1..^1].Trim(); continue; } + int eq = line.IndexOf('='); + if (eq <= 0) continue; + map[section + "." + line[..eq].Trim()] = line[(eq + 1)..].Trim(); + } + return map; + } + + /// <summary>Puts <paramref name="values"/> ("Section.Key" -> value) in the file's lines: an existing key is + /// replaced in place, a missing one added at the end of its section (the section added if needed). + /// Returns the ids that changed.</summary> + public static List<string> ApplyToLines(List<string> lines, IReadOnlyDictionary<string, string> values) + { + var changed = new List<string>(); + foreach (KeyValuePair<string, string> kv in values) + { + int dot = kv.Key.IndexOf('.'); + if (dot <= 0) continue; + if (SetValue(lines, kv.Key[..dot], kv.Key[(dot + 1)..], kv.Value)) changed.Add(kv.Key); + } + return changed; + } + + /// <summary>Applies <paramref name="values"/> to the file (written only when something changed).</summary> + public static List<string> Apply(string path, IReadOnlyDictionary<string, string> values) + { + var lines = File.Exists(path) ? new List<string>(ReadLinesShared(path)) : new List<string>(); + List<string> changed = ApplyToLines(lines, values); + if (changed.Count > 0) + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + WriteAtomic(path, string.Join("\r\n", lines) + "\r\n"); + } + return changed; + } + + /// <summary>Writes a temp file beside <paramref name="path"/> and swaps it in (retried on a sharing clash).</summary> + public static void WriteAtomic(string path, string text) + { + string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp"; + File.WriteAllText(tmp, text, new UTF8Encoding(false)); + for (int attempt = 0; ; attempt++) + { + try { File.Move(tmp, path, overwrite: true); return; } + catch (IOException) when (attempt < 5) { System.Threading.Thread.Sleep(20); } + catch (UnauthorizedAccessException) when (attempt < 5) { System.Threading.Thread.Sleep(20); } + catch { try { File.Delete(tmp); } catch { } throw; } + } + } + + private static string[] ReadLinesShared(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var sr = new StreamReader(fs); + return sr.ReadToEnd().Replace("\r\n", "\n").TrimEnd('\n').Split('\n'); + } + + private static bool SetValue(List<string> lines, string section, string key, string value) + { + string header = "[" + section + "]"; + int start = lines.FindIndex(l => string.Equals(l.Trim(), header, StringComparison.OrdinalIgnoreCase)); + string wanted = key + "=" + value; + if (start < 0) + { + lines.Add(header); + lines.Add(wanted); + return true; + } + int end = start + 1; + while (end < lines.Count && !IsHeader(lines[end])) end++; + for (int i = start + 1; i < end; i++) + { + string t = lines[i].Trim(); + int eq = t.IndexOf('='); + if (eq <= 0 || !string.Equals(t[..eq].Trim(), key, StringComparison.OrdinalIgnoreCase)) continue; + if (string.Equals(t[(eq + 1)..].Trim(), value, StringComparison.Ordinal)) return false; + lines[i] = wanted; + return true; + } + lines.Insert(end, wanted); + return true; + } + + private static bool IsHeader(string line) + { + string t = line.Trim(); + return t.StartsWith('[') && t.EndsWith(']'); + } +} diff --git a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs index 3ba7e63..45de744 100644 --- a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs +++ b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs @@ -414,10 +414,9 @@ internal static class HotkeyService case "patrol": UI.Data.RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}", refreshPatrol: true); break; case "autosort": UI.Data.RynthSortCommands.ToggleAuto(); break; case "reload": - // As /rc rl and the bar's RL: signalled from a pool thread (the reload shuts this engine down). + // As /rc rl and the bar's RL: in-world holds until logout (mid-session CoreCLR re-init AVs). RynthLog.Compat("Hotkeys: engine reload requested."); - EntryPoint.NoteManualReload(); - ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null); + ThreadPool.UnsafeQueueUserWorkItem(static _ => EntryPoint.RequestManualReload("hotkey reload"), null); break; default: Reply($"Hotkey {b.Combo}: '{a.Name}' isn't wired up in this engine."); diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 77f4a66..aa659c1 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -486,6 +486,55 @@ internal static unsafe class DX9Backend return creationParameters.hFocusWindow; } + // IDirect3DSurface9::GetDesc (IUnknown 3 + IDirect3DResource9 8 + GetContainer = slot 12). + private const int SurfaceGetDescSlot = 12; + + [StructLayout(LayoutKind.Sequential)] + private struct D3DSURFACE_DESC + { + public int Format, Type; + public uint Usage; + public int Pool, MultiSampleType; + public uint MultiSampleQuality, Width, Height; + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int SurfaceGetDescD(IntPtr surface, D3DSURFACE_DESC* desc); + + /// <summary>The size AC's back buffer is (what it really draws at), or false. AC's main thread + /// (EndScene). Used by the window code so the window follows AC's own resolution.</summary> + public static bool TryGetBackBufferSize(IntPtr pDevice, out int width, out int height) + { + width = height = 0; + if (pDevice == IntPtr.Zero) return false; + IntPtr backBuffer = IntPtr.Zero; + try + { + if (_getBackBuffer == null) + { + IntPtr vtable = Marshal.ReadIntPtr(pDevice); + _getBackBuffer = Get<GetBackBufferD>(vtable, DeviceVTableIndex.GetBackBuffer); + } + if (_getBackBuffer(pDevice, 0, 0, D3DBACKBUFFER_TYPE_MONO, out backBuffer) < 0 || backBuffer == IntPtr.Zero) + return false; + var getDesc = Get<SurfaceGetDescD>(Marshal.ReadIntPtr(backBuffer), SurfaceGetDescSlot); + D3DSURFACE_DESC desc = default; + if (getDesc(backBuffer, &desc) < 0) return false; + width = (int)desc.Width; + height = (int)desc.Height; + return width > 0 && height > 0; + } + catch (Exception ex) + { + LogOnce(nameof(TryGetBackBufferSize), ex); + return false; + } + finally + { + ReleaseComObject(backBuffer); + } + } + public static bool IsRenderingToBackBuffer(IntPtr pDevice) { if (pDevice == IntPtr.Zero) return true; diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index d0a0682..d062626 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -67,8 +67,11 @@ internal static class ImGuiBar // Opened from the RynthAi launcher, not the bar (AvaloniaOverlay.BuildRoot). Lua has // its own bar button since it became the RynthLua plugin. "Monsters" (retired 2026-10-01, // still registered by EntryPoint) must never get a button: PanelRouter sends it to Damage. + // Radar + Sense: under RynthNav (header toggles + /rc radar|sense). Vision + Tracker: + // under Oracle (companion strip). Keep OverlayHost / face registration so PanelRouter, + // restore and Avalonia chrome still work. private static readonly HashSet<string> LauncherOnly = new(StringComparer.OrdinalIgnoreCase) - { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items" }; + { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items", "Radar", "Vision", "Tracker" }; // Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton); // the button toggles it through ScriptWindowRegistry, like the Scripts menu does. @@ -90,24 +93,18 @@ internal static class ImGuiBar private static readonly Func<string, bool> IsOpenCheck = ImGuiPanelHost.IsOpen; // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. - // Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu. - // Skills moves under RynthOracle (Skills / Attributes / Progress tabs): its icon shows only while Oracle's - // tabs can't be reached (SkillsRouting.ShowSkillsBarIcon), so nobody loses the way in. Mini Remote stays. + // Skills moved under RynthOracle (Skills / Attributes / Progress tabs; /ro skills): its icon shows only + // while Oracle's tabs can't be reached (SkillsRouting.ShowSkillsBarIcon), so nobody loses the way in. + // Item Count / Mini Remote: under Inventory since 2026-10-16 (no bar icons of their own). + // Sense: under RynthNav since 2026-10-16 (header toggle + /rc sense). private static readonly string[] ImGuiOnlyBarPanels = - { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.MiniRemoteFace.Title, - Panels.ItemToolFace.Title }; + { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.ItemToolFace.Title }; // Characters: RynthNet's window since 2026-10-21 /// <summary>An ImGui-only panel's bar button is wanted: it has a face, and Skills only while Oracle can't host it.</summary> private static bool ImGuiOnlyWanted(string title) => ImGuiPanelHost.HasFace(title) && (title != Panels.SkillsFace.Title || Panels.SkillsRouting.ShowSkillsBarIcon); - // The ILT section: ImGui-only Infinite Leaftide panels (Bounties and Guardian, both RynthILT's). - // They never get buttons of their own; one ILT button stands for them, shown only on Infinite - // Leaftide (IltInfo.IsIlt) with RynthILT loaded (IltInfo.PluginLoaded), and only for the ones - // registered (EntryPoint registers them when RynthILT is installed). - private static readonly string[] IltPanels = { Panels.BountiesFace.Title, Panels.GuardianFace.Title }; - // Known panels' icons (DrakBot's where the same window exists); others show their first letter. private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase) { @@ -506,9 +503,9 @@ internal static class ImGuiBar // Rows (header): perRow icons a row, each row from iconsX (under the first icon); // RL and pop out go at the end of the first row (NextSlot, or after the icons when // they all fit on it). - int iltCount = IltPanelCount(); + // ILT leaf moved under Oracle (2026-10-16); no longer occupies a bar slot. ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems; - int icons = _buttons!.Length + (iltCount > 0 ? 1 : 0) + (scripts.Length > 0 ? 1 : 0); + int icons = _buttons!.Length + (scripts.Length > 0 ? 1 : 0); RowSettings rows = RowLayout; int perRow = BarLayout.PerRow(icons, rows.Rows, rows.MaxPerRow); Volatile.Write(ref _shownPerRow, perRow); @@ -538,21 +535,6 @@ internal static class ImGuiBar if (_menuHover.OpenFor != b.Id) SafeImGui.SetItemTooltip(b.Tooltip); // the dropdown sits where it would show } - // The ILT section: one button, only on Infinite Leaftide with ILT panels registered - // (Bounties, Guardian). With one panel it toggles that panel; with more it opens a menu. - if (iltCount > 0) - { - NextSlot(ref slot, perRow, iconsX, s, iconFont, popped); - string? only = iltCount == 1 ? FirstIltPanel() : null; - bool open = BarOpenState.AnyOpen(IltPanels, IsOpenCheck); - if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText, open)) - { - if (only != null) PanelRouter.Toggle(only); - else ImGuiNET.ImGui.OpenPopup("##ilt_menu"); - } - SafeImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide"); - } - // Script windows (decision 2): one button with a menu, only while a ShowInBar // script window exists. A window that also sets BarButton (plugin windows such as // RynthSort's) has a button of its own instead (EnsureButtons) and isn't listed here. @@ -571,7 +553,6 @@ internal static class ImGuiBar // Drawn after the bar buttons' style is popped, so the menu has the normal look. ScriptsMenu(scripts); - IltMenu(); _menuHover.Update(menuHovered, _overMenu, menuNow); DrawBarMenu(s, square, iconFont, letterFont); } @@ -704,11 +685,10 @@ internal static class ImGuiBar ImGuiNET.ImGui.SameLine(0, 6 * s); if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel)) { - // By hand: not held while a plugin objects (combat, looting); the player chose the moment. - EntryPoint.NoteManualReload(); - ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null); + // In-world: loader holds until logout; skips combat deferral once out of world. + ThreadPool.UnsafeQueueUserWorkItem(static _ => EntryPoint.RequestManualReload("RL"), null); } - ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init."); + ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL). While in-world it waits until logout / character select."); // The bar draws only as the ImGui face (ResolveFace), so it pops out as itself. ImGuiNET.ImGui.SameLine(); @@ -717,43 +697,6 @@ internal static class ImGuiBar SafeImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); } - /// <summary>The ILT panels the bar offers now: 0 off Infinite Leaftide or without RynthILT. AC thread.</summary> - private static int IltPanelCount() - { - int n = 0; - foreach (string title in IltPanels) - if (ImGuiPanelHost.HasFace(title)) n++; - return n > 0 && IltInfo.IsIlt && IltInfo.PluginLoaded ? n : 0; - } - - private static string? FirstIltPanel() - { - foreach (string title in IltPanels) - if (ImGuiPanelHost.HasFace(title)) return title; - return null; - } - - /// <summary>The ILT button's menu (two or more ILT panels): a checkbox item each for open.</summary> - private static void IltMenu() - { - if (!ImGuiNET.ImGui.BeginPopup("##ilt_menu")) return; - try - { - ImGuiNET.ImGui.TextDisabled("Infinite Leaftide"); - foreach (string title in IltPanels) - { - if (!ImGuiPanelHost.HasFace(title)) continue; - bool open = ImGuiPanelHost.IsOpen(title); - if (ImGuiNET.ImGui.MenuItem(title, "", open)) - PanelRouter.Toggle(title); - } - } - finally - { - ImGuiNET.ImGui.EndPopup(); - } - } - /// <summary> /// The Scripts button's popup: the ShowInBar script windows grouped by script, a /// checkbox item each for open. Toggling tells the owner (Visibility, reason 2). diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 29c2120..a96440c 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -959,8 +959,12 @@ internal static class ImGuiPanelHost Vector2 size = entry.Size; Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen(); int left = (int)(origin.X + entry.Pos.X), top = (int)(origin.Y + entry.Pos.Y); + // Prefer the last floating screen spot whenever we have one — including after a + // redock (Persist keeps FloatingLeft/Top while Floating goes false). The old gate + // required (fromSaved || Floating), so Float → move → Dock → Float reopened over the + // docked client spot and PersistPopped overwrote the saved floating coords. if (PanelStateStore.TryGetPanel(entry.Title, out PanelStateStore.PanelEntry saved) - && (saved.FloatingLeft != 0 || saved.FloatingTop != 0) && (fromSaved || saved.Floating)) + && (fromSaved || saved.Floating || saved.FloatingLeft != 0 || saved.FloatingTop != 0)) { left = (int)Math.Round(saved.FloatingLeft); top = (int)Math.Round(saved.FloatingTop); @@ -1881,16 +1885,47 @@ internal static class ImGuiPanelHost string title = entry.Title; Vector2 docked = DockedHome(entry) / placeScale; Vector2 size = new Vector2(width, height) / placeScale; + string caller = _popSpotLogged < 60 ? PopOutCaller() : ""; UiBackgroundWriter.Enqueue($"persist {title}", () => { PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior); double w = keepSize && prior.Width > 0 ? prior.Width : size.X; double h = keepSize && prior.Height > 0 ? prior.Height : size.Y; + // Every change of a pop-out's saved spot, with the call that made it (2026-11-01: pop-outs + // came up elsewhere at login and nothing said what had saved that spot). + if ((int)Math.Round(prior.FloatingLeft) != left || (int)Math.Round(prior.FloatingTop) != top) + NotePopOutSpot(title, (int)Math.Round(prior.FloatingLeft), (int)Math.Round(prior.FloatingTop), left, top, width, height, open, caller); PanelStateStore.SetPanel(title, new PanelStateStore.PanelEntry( open, docked.X, docked.Y, w, h, true, left, top)); }); } + private static int _popSpotLogged; + + /// <summary>The calls that led to a pop-out's spot being saved (for the log). AC thread.</summary> + private static string PopOutCaller() + { + try + { + var st = new System.Diagnostics.StackTrace(1, false); + var names = new List<string>(); + for (int i = 0; i < st.FrameCount && names.Count < 4; i++) + { + var m = st.GetFrame(i)?.GetMethod(); + if (m == null || m.Name.StartsWith("<", StringComparison.Ordinal) || m.Name is "Invoke" or "PersistPopped") continue; + names.Add((m.DeclaringType?.Name ?? "") + "." + m.Name); + } + return string.Join(" < ", names); + } + catch { return ""; } + } + + private static void NotePopOutSpot(string title, int fromX, int fromY, int x, int y, int width, int height, bool open, string caller) + { + if (System.Threading.Interlocked.Increment(ref _popSpotLogged) > 60) return; + RynthLog.UI($"ImGuiPanelHost: {title} pop-out spot saved ({fromX},{fromY}) -> ({x},{y}) {width}x{height}{(open ? "" : " (closing)")}{(caller.Length > 0 ? " via " + caller : "")}."); + } + /// <summary> /// The docked spot to save (client px): the panel's home (HomePlace), not where it draws: a pull onto /// a smaller screen or for a taller moment is never written over the saved spot. diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 01188e0..f47d3fd 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -209,8 +209,11 @@ internal static unsafe class ImGuiPopOuts try { // A saved spot off the screen (a monitor since unplugged, a bad save) comes back on it. - if (LayeredWindow.ClampToWorkArea(ref pop.Left, ref pop.Top, pop.Width, pop.Height)) - RynthLog.UI($"ImGuiPopOuts: {pop.Title}: saved spot was off the screen; moved to ({pop.Left},{pop.Top})."); + // One mostly on it stays where the player left it (2026-11-01). + int savedLeft = pop.Left, savedTop = pop.Top; + if (!LayeredWindow.MostlyOnScreen(pop.Left, pop.Top, pop.Width, pop.Height) + && LayeredWindow.ClampToWorkArea(ref pop.Left, ref pop.Top, pop.Width, pop.Height)) + RynthLog.UI($"ImGuiPopOuts: {pop.Title}: saved spot ({savedLeft},{savedTop}) {pop.Width}x{pop.Height} was off the screen; moved to ({pop.Left},{pop.Top})."); var window = new LayeredWindow(pop.Width, pop.Height, pop.Left, pop.Top, Win32Backend.GameHwnd) { CaptionHeight = pop.CaptionHeight, @@ -559,7 +562,10 @@ internal static unsafe class ImGuiPopOuts // Shown, or its picture changed size (the bar grows to its content): // none of it may hang off the screen. if ((!pop.Visible || w != pop.ShownWidth || h != pop.ShownHeight) && window.EnsureOnScreen()) + { + RynthLog.UI($"ImGuiPopOuts: {pop.Title}: {w}x{h} was mostly off the screen; pulled onto it at ({window.ScreenLeft},{window.ScreenTop})."); NotifyMoved(pop, window, window.ScreenLeft, window.ScreenTop); + } pop.ShownWidth = w; pop.ShownHeight = h; if (!pop.Visible) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index f0529b5..b5829bb 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -390,7 +390,7 @@ internal sealed class ChatFace : IImGuiPanel ChatModel.SetHistoryLines(_historyEdit); _historyEdit = 0; } - ImGuiNET.ImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" + + SafeImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" + "About 2 MB of memory per 1000 lines. Lowering it drops the oldest lines."); ImGuiNET.ImGui.PopItemWidth(); @@ -430,7 +430,7 @@ internal sealed class ChatFace : IImGuiPanel ChatModel.LogEnabled = log; ChatModel.SaveSettings(); } - ImGuiNET.ImGui.SetItemTooltip("%%AppData%%\\RynthCore\\ChatLogs\\<character>.log"); // a format string: %% is a literal % + SafeImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log"); // SafeImGui doubles the % itself bool through = ChatModel.CtrlGatedClickThrough; if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through)) ChatModel.SetCtrlGatedClickThrough(through); diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 115de74..3c79649 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -214,6 +214,14 @@ internal sealed class ChatFiltersFace : IImGuiPanel SafeImGui.SetItemTooltip("On: a line a rule or standard filter hides doesn't print in AC's own chat window either.\n" + "Off: hiding only applies to RynthChat; the retail chat shows everything.\n" + "Moved / copied lines still show in the retail chat either way."); + bool automated = ChatModel.AutomatedToSystem; + if (ImGuiNET.ImGui.Checkbox("Automated system text shows in System only##autosys", ref automated)) + ChatModel.SetAutomatedToSystem(automated); + SafeImGui.SetItemTooltip("On (the default): replies to the commands plugins send by themselves (/myquests, /qb list,\n" + + "login probes), the server's login messages, and any line a plugin hides from the retail chat\n" + + "show in the System tab, not under All.\n" + + "Off: they show under All and their channel tab like any other line.\n" + + "A rule or standard filter that moves or hides such a line still decides first."); foreach (string group in UI.Panels.RynthChatPresets.Groups) { int on = 0, total = 0; @@ -425,7 +433,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel { if (r.Pattern.Trim().Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute)); if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red); - if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber); + if (r.Slow) return ("Too slow: matching it took too long twice running (see the RynthCore log), so the rule is skipped for a while. It is tried again on its own; editing the pattern tries it at once.", Amber); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0) return ("Pick a tab: until then it only colours.", Amber); if (!r.Enabled) return ("Off.", Faded(Mute)); @@ -622,6 +630,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel _testResult.Add((step.Rule switch { ChatRouter.StandardFilterStep => "Standard", + ChatRouter.AutomatedStep => "Automated", < 0 => "Your name", _ => $"Rule {step.Rule + 1}", } + ": " + step.What, Text)); diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatView.cs b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs index 21d0704..ede9e1f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatView.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs @@ -107,6 +107,13 @@ internal sealed class ChatView private readonly byte[] _search = new byte[128], _newTab = new byte[64]; private bool _stick = true; private float _lastScrollY; + // The left button went down on the list's scrollbar: a scrollbar drag until it comes up. + private bool _scrollbarDrag; + // Scrolled up when the list was rebuilt for a route change (another client's settings + // reload, a rule edit): the line that was at the top of the view (Id, -1 = none) and how + // far into it the view was, so DrawLines puts the view back there instead of jumping. + private long _anchorId = -1; + private float _anchorOffset; // Height of lines dropped off the top (the buffer is full) while not following the // tail: the view is moved up by as much, so the lines being read stay put instead of // sliding away. @@ -372,6 +379,21 @@ internal sealed class ChatView if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch) { + // Only the routes changed (rules, or another client's settings) while reading back: + // remember the top line, so the rebuild keeps the place. A new tab or search starts + // at the newest line, as before. + bool keepPlace = tab == _seenTab && search == _seenSearch && !Following && _vis.Count > 0; + _anchorId = -1; + if (keepPlace) + { + UpdateTops(); + int top = FirstAtOrBelow(Math.Max(0f, _lastScrollY), _vis.Count); + if (top < _vis.Count) + { + _anchorId = _vis[top].Id; + _anchorOffset = _lastScrollY - _tops[top]; + } + } _seenRoutes = routes; _seenTab = tab; _seenSearch = search; @@ -385,7 +407,8 @@ internal sealed class ChatView _heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first _topsDirty = true; ClearSelection(); - _stick = true; // a rebuild re-pins to the newest line + // A rebuild re-pins to the newest line, unless it keeps the place being read. + _stick = _anchorId < 0; _droppedAbove = 0f; return; } @@ -393,21 +416,7 @@ internal sealed class ChatView _seenLinesVersion = snap.Version; // Drop lines the source no longer keeps, then add the new ones. - long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue; - int drop = 0; - while (drop < _vis.Count && _vis[drop].Id < oldest) drop++; - if (drop > 0 && !_selDragging) - { - if (!Following) - for (int i = 0; i < drop; i++) _droppedAbove += _h[i]; - _vis.RemoveRange(0, drop); - _h.RemoveRange(0, drop); - _lay.RemoveRange(0, drop); - _heightsFrom = Math.Max(0, _heightsFrom - drop); - _measuredFrom = Math.Max(0, _measuredFrom - drop); - if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); } - _topsDirty = true; - } + if (!_selDragging) DropGone(lines); foreach (ChatLine line in lines) { if (line.Id <= _lastId) continue; @@ -421,9 +430,85 @@ internal sealed class ChatView } } + /// <summary> + /// Removes the shown lines the source no longer keeps: the oldest when the history is full, + /// and older automated text from anywhere in it (that has its own budget, ChatHistory.Keep, + /// 2026-10-24). Both lists are in Id order. Off-screen lines above the view move it up by + /// their height (not following), so what is being read stays put. + /// </summary> + private void DropGone(ChatLine[] lines) + { + int n = _vis.Count; + if (n == 0) return; + UpdateTops(); + float viewTop = _lastScrollY + _scrollCarry - _droppedAbove; + bool following = Following; + int j = 0, w = 0, goneHeights = 0, goneMeasured = 0; + int anchor = -1, end = -1; + float above = 0f; + for (int i = 0; i < n; i++) + { + long id = _vis[i].Id; + while (j < lines.Length && lines[j].Id < id) j++; + bool kept = j < lines.Length && lines[j].Id == id; + if (!kept) + { + if (i < _heightsFrom) goneHeights++; + if (i < _measuredFrom) goneMeasured++; + if (!following && _tops[i] < viewTop) above += Math.Min(_h[i], viewTop - _tops[i]); + continue; + } + if (i == _selAnchor) anchor = w; + if (i == _selEnd) end = w; + if (w != i) + { + _vis[w] = _vis[i]; + _h[w] = _h[i]; + _lay[w] = _lay[i]; + } + w++; + } + if (w == n) return; + _vis.RemoveRange(w, n - w); + _h.RemoveRange(w, n - w); + _lay.RemoveRange(w, n - w); + _heightsFrom = Math.Max(0, _heightsFrom - goneHeights); + _measuredFrom = Math.Max(0, _measuredFrom - goneMeasured); + if (_selAnchor >= 0) + { + if (anchor < 0 || end < 0) ClearSelection(); + else { _selAnchor = anchor; _selEnd = end; } + } + if (!following) _droppedAbove += above; + _topsDirty = true; + } + /// <summary>The view follows the newest line (auto-scroll on and not scrolled away).</summary> private bool Following => ChatModel.AutoScroll && _stick; + /// <summary> + /// After a rebuild that kept the place (SyncLines): moves the view to the line that was at its + /// top (or the next one still shown), through the same path as lines dropping off the top, so + /// MeasureLines then keeps it there while the lines above it get their real heights. + /// </summary> + private void RestoreAnchor() + { + if (_anchorId < 0) return; + long id = _anchorId; + _anchorId = -1; + UpdateTops(); + int lo = 0, hi = _vis.Count; // first line with Id >= id (Ids increase) + while (lo < hi) + { + int mid = (lo + hi) >> 1; + if (_vis[mid].Id < id) lo = mid + 1; else hi = mid; + } + if (lo >= _vis.Count) { _stick = true; return; } // nothing left below it: back to the newest + float target = _tops[lo] + (_vis[lo].Id == id ? _anchorOffset : 0f); + _scrollCarry = 0f; + _droppedAbove = _lastScrollY - target; // DrawLines: scroll = last - dropped = target + } + public void DrawLines(Vector2 size) { float fontSize = ChatModel.FontSize; @@ -437,6 +522,7 @@ internal sealed class ChatView // _wrapFix corrects that guess if the child ever reports otherwise. float wrapW = Math.Max(20, MathF.Floor(size.X) - ListScrollbarW - 6 + _wrapFix); float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0; + RestoreAnchor(); MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y)); float total = _tops[_vis.Count]; @@ -456,27 +542,38 @@ internal sealed class ChatView // A frame with wheel input over the list leaves the scroll to the wheel (this would // override it); a drag-select scrolls the list itself. Vector2 listPos = ImGuiNET.ImGui.GetCursorScreenPos(); - bool wheelHere = ImGuiNET.ImGui.GetIO().MouseWheel != 0f - && ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false); + Vector2 mousePos = ImGuiNET.ImGui.GetMousePos(); + bool overList = ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false); + float wheel = ImGuiNET.ImGui.GetIO().MouseWheel; + bool wheelHere = wheel != 0f && overList; + // A press on the scrollbar strip starts a scrollbar drag (ImGui moves the scroll in this + // frame's Begin); it lasts while the button is held. + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) _scrollbarDrag = false; + else if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) && overList && mousePos.X >= listPos.X + size.X - ListScrollbarW - 2) + _scrollbarDrag = true; + // The player moves the list only with the wheel, the scrollbar or a drag-select past its + // edges. (2026-10-24, the chat "jumping to the top": any other change of the scroll was + // read as the player's - a hover, a focus change, a re-measure, a clamp - so following + // stopped by itself and the view then crept up as old lines left the top.) + bool playerScroll = wheelHere || _scrollbarDrag || _selDragging; ImGuiNET.ImGui.SetNextWindowContentSize(new Vector2(0f, total)); - bool compensated = false; if (Following) { _droppedAbove = 0f; _scrollCarry = 0f; - // Not counted as "our move": a scrollbar drag in this Begin overrides it, and the - // check below must see that to stop following. - if (!wheelHere && !_selDragging) + if (!playerScroll) ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, total)); } - else if (_droppedAbove != 0f && !wheelHere) + else if (!playerScroll) { + // Not following: the view stays where the player left it, moved only by however much + // the lines above it changed (dropped off a full buffer, re-measured), every frame, + // so nothing else can move it. float target = _lastScrollY + _scrollCarry - _droppedAbove; float applied = MathF.Round(Math.Max(0f, target)); // ImGui rounds scroll to whole pixels _scrollCarry = target > 0f ? target - applied : 0f; ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, applied)); _droppedAbove = 0f; - compensated = true; } ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u); @@ -501,16 +598,16 @@ internal sealed class ChatView float textW = Math.Max(20, wrapW - tsW); int n = _vis.Count; - // Following the tail until the user scrolls away from it. + // Following the tail until the player scrolls away from it; back at the bottom, it follows again. float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY(); - if (compensated) _lastScrollY = scrollY; // our move, not the user's - else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) _scrollCarry = 0f; // the user's: start afresh - // Wheel up over the chat stops following at once; reaching the bottom again resumes it. - // Not while it has nothing to scroll: no scroll change would ever turn following back on. - if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f) - _stick = false; - else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) - _stick = scrollY >= maxY - StickThreshold; + if (playerScroll) + { + _scrollCarry = 0f; // the player's move: start afresh from where it ends + _droppedAbove = 0f; + if (maxY <= 0f) _stick = true; // nothing to scroll + else if (wheelHere && wheel > 0f) _stick = false; // wheel up stops following at once + else _stick = scrollY >= maxY - StickThreshold; + } Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); float viewH = ImGuiNET.ImGui.GetWindowHeight(); diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs index d9be3b1..4469b5b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs @@ -36,6 +36,8 @@ internal sealed class ClassicLootTab : IClassicTab private float _grab; private LootEditStateDto? _filesFor; private string[] _files = Array.Empty<string>(); + // Add: the Loot Editor's new-rule checklist (2026-11-07), the same as Filter inventory. + private readonly LootAddDialog _lootAdd = new("##cl_lootadd") { EmptyRule = () => LootEditCommands.Simple("add", -1) }; public void Shown() { @@ -43,7 +45,11 @@ internal sealed class ClassicLootTab : IClassicTab UiSources.LootEdit.RequestRefresh(); } - public void Hidden() => UiSources.LootEdit.Unsubscribe(); + public void Hidden() + { + _lootAdd.Cancel(); + UiSources.LootEdit.Unsubscribe(); + } public float Draw(ClassicContext ctx, Vector2 o, float w) { @@ -170,8 +176,11 @@ internal sealed class ClassicLootTab : IClassicTab SafeImGui.SetItemTooltip("Delete the selected rule"); x += Px(50); if (Plate("##cl_add", "Add", new Vector2(x, y)) && editable) - LootEditCommands.Simple("add", -1); - SafeImGui.SetItemTooltip("Add a new rule at the end (write it in the Loot Editor)"); + { + if (s!.Dirty) LootEditCommands.Simple("add", -1); // the checklist saves: unsaved edits get the empty rule + else _lootAdd.Open(0, string.Empty, toOpenProfile: true, LootAddMode.AddRule, blank: true); + } + SafeImGui.SetItemTooltip("A new rule at the end from the attribute checklist (the same as Filter inventory)"); x += Px(50); // The selected item, not the selected rule: RynthAi's "Why this loot rule?" window. if (x + Px(46) <= o.X + w && Plate("##cl_why", "Why?", new Vector2(x, y))) @@ -194,6 +203,7 @@ internal sealed class ClassicLootTab : IClassicTab TextClip(dl, o.X + 2 * bw + Px(18), y, Px(32), o.X + w, s.Message, s.MessageOk ? Green : Down, 10); y += Px(32); } + _lootAdd.Draw(); return y - o.Y; } diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 148ce8d..92cf250 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -577,7 +577,7 @@ internal sealed class DamageFace : IImGuiPanel if (all == null || count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), all == null + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), all == null ? " Monster rules not loaded yet." : " No name rules yet: add one below."); } else @@ -764,7 +764,7 @@ internal sealed class DamageFace : IImGuiPanel bool filtering = _filterWid != 0 || _searchText.Length > 0; bool anyData = _view.Rows.Exists(r => !r.IsDefault); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), anyData && filtering + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), anyData && filtering ? " No monsters match the current filter." : " No monsters yet: fight some and they show up here."); } @@ -1106,7 +1106,7 @@ internal sealed class DamageFace : IImGuiPanel Rule? view = RuleFor(name, out bool custom); bool isDefault = name.Equals("Default", StringComparison.OrdinalIgnoreCase); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), "Debuffs · " + name); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), "Debuffs · " + name); ImGuiNET.ImGui.PopFont(); if (view == null) { @@ -1115,7 +1115,7 @@ internal sealed class DamageFace : IImGuiPanel return; } ImGuiNET.ImGui.PushTextWrapPos(0); - SafeImGui.TextColored((custom || isDefault ? RynthTheme.Vec(0xFFFFD16A) : RynthTheme.VecOf(RynthTheme.MuteAlt)), + SafeImGui.TextColored(RynthTheme.Vec(custom || isDefault ? 0xFFFFD16A : 0xFFC8D4E0), isDefault ? "Every monster set to Default uses these." : custom ? "This monster's own debuffs." : "Following Default: a change here gives it its own."); ImGuiNET.ImGui.PopTextWrapPos(); @@ -1432,7 +1432,7 @@ internal sealed class DamageFace : IImGuiPanel if (ropen) { ImGuiNET.ImGui.PushTextWrapPos(0); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Remove " + _removeName + "?"); + SafeImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Remove " + _removeName + "?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Its learned numbers and your settings for it (weapon, offhand, pet, HP) are deleted. It comes back if you meet it again."); diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs b/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs new file mode 100644 index 0000000..617e10c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs @@ -0,0 +1,35 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DamageTypeColors.cs +// Text colour per damage type, from UB-ILT's LeaftideDamageTypeVtColors (the +// Virindi Tank / Leaftide label palette its Items, Spell and Pets tabs share). +// RynthAi's Pets roster uses the same values (IltHub\IltDamageTypeTint.cs); +// keep the two tables in step. Colours are the panels' ABGR (RynthTheme.Argb). +// ============================================================================ + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class DamageTypeColors +{ + private static uint C(uint argb) => RynthTheme.Argb(argb); + + public static readonly uint Slash = C(0xFFFFB478), Pierce = C(0xFFF0C88C), Bludgeon = C(0xFFDCBE8C), + Cold = C(0xFFA0D2FF), Fire = C(0xFFFF8246), Acid = C(0xFFA0FF8C), Lightning = C(0xFFFFF078), + Nether = C(0xFFC8A0FF), + // Prismatic (universal damage, missile weapons and ammo): a light rose that reads apart from the eight elements. + Prismatic = C(0xFFFFA0DC); + + /// <summary>Colour for an element name as the panels write it; <paramref name="fallback"/> for anything else (Shield, Auto, None).</summary> + public static uint For(string? element, uint fallback) => element switch + { + "Slash" or "Slashing" => Slash, + "Pierce" or "Piercing" => Pierce, + "Bludgeon" or "Bludgeoning" => Bludgeon, + "Cold" or "Frost" => Cold, + "Fire" => Fire, + "Acid" => Acid, + "Lightning" or "Electric" or "Storm" => Lightning, + "Nether" => Nether, + "Prismatic" => Prismatic, + _ => fallback, + }; +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 78e6242..4a69ea1 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -439,7 +439,7 @@ internal sealed class DashboardDrawers bool rightClicked = d.CanMove && ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right); // Like SetItemTooltip (same delay), but the closed tooltip is only built while it shows. if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) - SafeImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right) + (d.CanMove ? MoveHint : "")); + SafeImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right)); if (clicked) Toggle(d); if (rightClicked) ImGuiNET.ImGui.OpenPopup(d.SideMenuId); diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs index 4c212ef..d4a97c7 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -325,10 +325,14 @@ internal sealed class DungeonMapFace : IImGuiPanel } } - // Visited cells, the player's floor only: 4 floats per strip. - if (curVisible && view.VisitedByLayer[cur] is float[] visited) + // Visited cells (the walked trail), 4 floats per strip: each floor shown draws its own, the player's floor in + // full and the other shown floors dimmed like their walls. RynthAi paints a floor only while you stand on it + // (2026-11-11), so a floor above or below shows nothing of where you walked unless you walked it and it's on. + for (int k = 0; k < n; k++) { - uint fill = RynthTheme.Argb(FillVisited); + int layer = _drawOrder[k]; + if (view.VisitedByLayer[layer] is not float[] visited) continue; + uint fill = layer == cur ? RynthTheme.Argb(FillVisited) : MulAlpha(FillVisited, DimOtherFloors); for (int i = 0; i + 3 < visited.Length; i += 4) FillRect(dl, proj, visited[i], visited[i + 1], visited[i + 2], visited[i + 3], fill, clipMin, clipMax); } diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs index b2a46d8..7e0578a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs @@ -55,6 +55,9 @@ internal sealed partial class InventoryFace if (_attrLoaded) return; _attrLoaded = true; _attr = InventoryAttributeFilter.Parse(InventorySettingsStore.AttrFilter); + // The tools-row button opens the checklist filter now (InventoryFace.LikeFilter.cs, 2026-10-24): + // the old rule list stays saved but no longer hides items. + _attr.Enabled = false; } /// <summary>An appraisal rule is on and a second has passed: rebuild to pick up new identifies.</summary> @@ -111,22 +114,13 @@ internal sealed partial class InventoryFace private void AttrFilterButton(Vector2 pos) { - bool on = AttrOn; + bool on = LikeOn; if (IconButton("##inv_attr", PhosphorIcons.ListChecks, pos, new Vector2(22, 22), on ? Teal : Mute, on ? Selected : BtnFill, border: on ? Teal : 0u, font: UiFont.Ui11)) - _openAttr = true; - if (!ImGuiNET.ImGui.IsItemHovered()) return; - if (_attrSummaryVersion != _attr.Version) - { - _attrSummaryVersion = _attr.Version; - _attrSummary = _attr.Rules.Count == 0 ? string.Empty : _attr.Summary(); - } - string tip = on ? "Attribute filter on: " + _attrSummary - : _attr.Rules.Count > 0 ? "Attribute filter off (" + _attrSummary + ")" - : "Filter by item attributes (armor level, ratings, spells, slot...)"; - if (on && _unidentified.Count > 0) - tip += "\n" + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " hidden until identified."; - SafeImGui.SetTooltip(tip); + OpenBlankFilter(); + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip(on ? "Filter on: " + _likeLabel + " (click to make a new one; the X on its bar clears it)" + : "Filter by item attributes: the same checklist as Add to loot profile, with spell and cantrip lists"); } // ── The editor popup ──────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 229a097..9edf997 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -43,6 +43,7 @@ using ImGuiNET; using RynthCore.Engine.Compatibility; using RynthCore.Engine.Net; using RynthCore.Engine.UI; +using RynthCore.Engine.UI.ScriptWindows; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; @@ -179,6 +180,7 @@ internal sealed partial class InventoryFace ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(o.X + 6, toolsBottom + 4)); Tools(w - 12); Chips(w - 12); + LikeBar(w - 12); toolsBottom = ImGuiNET.ImGui.GetCursorScreenPos().Y; } float ry = toolsBottom - TitleH * s; // where retail y = 0 lands @@ -215,6 +217,21 @@ internal sealed partial class InventoryFace dl.AddImage(tex, o + new Vector2(0, band), o + new Vector2(w, h), new Vector2(0, TitleH / ArtH), Vector2.One); } + /// <summary>The Classic title bar's "more" menu: open or close the panels related to the inventory.</summary> + private static void RelatedPanelsMenu(bool remoteOpen, bool sortOpen, bool countOpen, bool ginvOpen) + { + if (!ImGuiNET.ImGui.BeginPopup("##inv_related_menu")) return; + if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", remoteOpen)) ToggleMiniRemote(); + if (ImGuiNET.ImGui.MenuItem("RynthSort", "/rsort", sortOpen)) ToggleRynthSort(); + if (!ScriptWindowRegistry.Has(RynthSortKey)) ImGuiNET.ImGui.SetItemTooltip("Needs the RynthSort plugin"); + if (ImGuiNET.ImGui.MenuItem("Item Count", "/rc itemcount", countOpen)) ToggleItemCount(); + if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv", ginvOpen)) ToggleGlobalInventory(); + if (!ScriptWindowRegistry.Has(GlobalInventoryKey)) ImGuiNET.ImGui.SetItemTooltip("Needs the RynthInventory plugin"); + if (ImGuiNET.ImGui.MenuItem("Trade Shop", "/ra tradeshop ui")) ToggleTradeShop(); + SafeImGui.SetItemTooltip(TradeShopTip); + ImGuiNET.ImGui.EndPopup(); + } + private void TitleBar(InventoryView view, ImDrawListPtr dl, Vector2 o, float w, float s) { float h = TitleH * s, closeW = 24 * s; @@ -289,6 +306,14 @@ internal sealed partial class InventoryFace _vaultOpen = false; } + // Trade Shop Storefront — always present (catalog prices + conversion rates). + if (lay.Shop.Present) + { + if (TitleToggle("##inv_tradeshop", PhosphorIcons.Storefront, At(lay.Shop), btn, false)) + ToggleTradeShop(); + SafeImGui.SetItemTooltip(TradeShopTip); + } + // Related panels: Mini Remote, RynthSort, Item Count, Global Inventory. switch (lay.Mode) { @@ -324,7 +349,7 @@ internal sealed partial class InventoryFace if (TitleToggle("##inv_more", PhosphorIcons.DotsThree, At(lay.More), btn, MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen)) _openMore = true; - ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory"); + ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory, Trade Shop"); break; } RelatedMenu(); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.LikeFilter.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.LikeFilter.cs new file mode 100644 index 0000000..fbe8f72 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.LikeFilter.cs @@ -0,0 +1,228 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/InventoryFace.LikeFilter.cs +// "Filter inventory like this" (right-click an item, 2026-10-24): the +// "Add to loot profile" popup in a filter mode (LootAddDialog) builds a rule +// from the item with the same match and attribute checklist, and RynthAi +// judges the panel's items with its looter's evaluator. The list then shows +// only the matches, under a bar that names the filter, counts what it can't +// judge yet (not identified: "Identify N") and clears it. +// +// The matches are RynthAi's answer for a list of ids, so the panel asks again +// (find_refresh, every two seconds while it shows) to pick up new loot and +// identifies; RynthAi answers only when something changed. The filter lasts +// until it is cleared or the panel is hidden; Clear filters (closing the +// Classic tools row) clears it too, and in Classic it shows in the tools row, +// which opens when the filter is applied. +// +// "Find like this in Global Inventory" uses the same popup; RynthInventory +// does the filtering there (/ginv like), so nothing of it lives here. +// Threads: the panel's (render) thread only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class InventoryFace +{ + private static readonly long LikeRefreshTicks = Stopwatch.Frequency * 2; + + private bool _likeActive, _likeSubscribed; + private string _likeLabel = string.Empty, _likeTip = string.Empty, _likeError = string.Empty; + private readonly HashSet<uint> _likeIds = new(); + private readonly List<uint> _likeUnknown = new(); + // Bumped whenever the matches change, so the list rebuilds. + private int _likeVersion; + private int _builtLikeKey = int.MinValue; + private bool _likePass; + private long _likeRefreshAt; + // The answers this panel waits for: the Filter that started it, then its refreshes. + private int _likeAppliedSeq; + private readonly HashSet<int> _likeAsked = new(); + private long _likeSeenVersion = -1; + + /// <summary>The like filter hides items now (in Classic, only while the tools row is open).</summary> + private bool LikeOn => _likeActive && (!InventorySettingsStore.Classic || InventorySettingsStore.ShowTools); + + /// <summary>Opens the filter popup for <paramref name="it"/> (Global: Global Inventory instead of this panel).</summary> + private void OpenLikeFilter(InventoryItem it, bool global) + { + _lootAdd.Candidates = LikeCandidates; + _lootAdd.Found = ApplyLike; + _lootAdd.Open(it.Id, it.Name, toOpenProfile: false, global ? LootAddMode.FilterGlobal : LootAddMode.FilterInventory); + } + + /// <summary>The tools row's filter button: the same popup with every attribute and no item.</summary> + private void OpenBlankFilter() + { + _lootAdd.Candidates = LikeCandidates; + _lootAdd.Found = ApplyLike; + _lootAdd.Open(0, string.Empty, toOpenProfile: false, LootAddMode.FilterInventory, blank: true); + } + + /// <summary>Every item the panel knows: the packs' (pack-slot items included) and the worn ones.</summary> + private static List<uint> LikeCandidates() + { + InventoryView view = InventoryModel.Current; + var ids = new List<uint>(view.ItemCount + view.Worn.Length + 8); + var seen = new HashSet<uint>(); + foreach (InventoryPack p in view.Packs) + foreach (InventoryItem it in p.Items) + if (seen.Add(it.Id)) ids.Add(it.Id); + foreach (InventoryItem it in view.Worn) + if (seen.Add(it.Id)) ids.Add(it.Id); + return ids; + } + + /// <summary>RynthAi's answer to Filter: show its matches from now on.</summary> + private void ApplyLike(LootEditItemFindDto f) + { + if (!_likeSubscribed) + { + UiSources.LootEdit.Subscribe(); + _likeSubscribed = true; + } + _likeActive = true; + _likeLabel = f.Label.Length > 0 ? f.Label : "like " + f.ItemName; + _likeTip = "Filter " + _likeLabel + "\n" + string.Join("\n", f.Lines); + _likeError = string.Empty; + _likeAppliedSeq = f.Seq; + _likeAsked.Clear(); + _likeSeenVersion = UiSources.LootEdit.Current?.Version ?? -1; + SetLikeResult(f); + _likeRefreshAt = Stopwatch.GetTimestamp() + LikeRefreshTicks; + // Classic shows the filter bar in its tools row. + if (InventorySettingsStore.Classic && !InventorySettingsStore.ShowTools) InventorySettingsStore.SetShowTools(true); + } + + private void SetLikeResult(LootEditItemFindDto f) + { + _likeIds.Clear(); + foreach (uint id in f.Ids) _likeIds.Add(id); + _likeUnknown.Clear(); + _likeUnknown.AddRange(f.Unknown); + _likeVersion++; + } + + /// <summary>Clears the like filter (and tells RynthAi to drop its rule).</summary> + private void ClearLike() + { + if (!_likeActive && !_likeSubscribed) return; + if (_likeActive) LootEditCommands.Simple("find_close"); + _likeActive = false; + _likeIds.Clear(); + _likeUnknown.Clear(); + _likeAsked.Clear(); + _likeError = string.Empty; + _likeVersion++; + if (_likeSubscribed) + { + UiSources.LootEdit.Unsubscribe(); + _likeSubscribed = false; + } + } + + /// <summary>Once per frame before the list rebuild: takes refresh answers and asks again when due.</summary> + private void LikeTick() + { + if (!_likeActive) return; + var snap = UiSources.LootEdit.Current; + if (snap != null && snap.Version != _likeSeenVersion) + { + _likeSeenVersion = snap.Version; + LootEditItemFindDto? f = snap.Value.State?.ItemFind; + if (f != null && f.Scope == LootFindScopes.Inventory && f.Seq > _likeAppliedSeq && _likeAsked.Contains(f.Seq)) + { + _likeAppliedSeq = f.Seq; + _likeAsked.RemoveWhere(s => s <= f.Seq); + if (f.Ok) + { + _likeError = string.Empty; + SetLikeResult(f); + } + else + _likeError = f.Error; // keep the last matches; the bar says what went wrong + } + } + long now = Stopwatch.GetTimestamp(); + if (now < _likeRefreshAt) return; + _likeRefreshAt = now + LikeRefreshTicks; + int seq = LootAddDialog.NextSeq(); + if (_likeAsked.Count > 8) _likeAsked.Clear(); // answers that never came (RynthAi unloaded) + _likeAsked.Add(seq); + LootEditCommands.Send(new LootEditCmd + { + Op = "find_refresh", + Item = new LootEditItemRequestDto { Seq = seq, Find = true, Scope = LootFindScopes.Inventory, Candidates = LikeCandidates() }, + }); + } + + /// <summary>Start of a list rebuild.</summary> + private void BeginLikePass(bool likeOn) => _likePass = likeOn; + + /// <summary>Does the like filter keep <paramref name="item"/>?</summary> + private bool LikeKeeps(InventoryItem item) => _likeIds.Contains(item.Id); + + /// <summary>The bar under the tools row while the like filter is on: what it is, what it can't judge, clear.</summary> + private void LikeBar(float w) + { + if (!LikeOn) return; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, h), Selected, 4); + dl.AddRect(p, p + new Vector2(w, h), Teal, 4); + ImFontPtr icons = ImGuiFonts.Get(UiFont.Ui11); + PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Funnel, p, new Vector2(20, h), Teal); + + // Right side: Identify N (when some can't be judged yet), then the clear button. + float right = p.X + w - 2; + if (IconButton("##inv_like_x", PhosphorIcons.X, new Vector2(right - 20, p.Y + 1), new Vector2(20, 20), Amber, BtnFill, font: UiFont.Ui11)) + { + ClearLike(); + NextLine(p, h + 4); + return; + } + SafeImGui.SetItemTooltip("Clear the filter"); + right -= 24; + if (_likeUnknown.Count > 0) + { + string label = "Identify " + _likeUnknown.Count.ToString(CultureInfo.InvariantCulture); + float bw = ImGuiNET.ImGui.CalcTextSize(label).X + 14; + if (Button("##inv_like_id", label, new Vector2(right - bw, p.Y + 1), new Vector2(bw, 20), Amber, BtnFill)) + InventoryModel.QueueIdentify(_likeUnknown); + SafeImGui.SetItemTooltip(_likeUnknown.Count.ToString(CultureInfo.InvariantCulture) + + " item(s) hidden: the filter needs what an identify tells about them. Identify asks the server (a few a second)."); + right -= bw + 4; + } + + string text = _likeError.Length > 0 ? _likeLabel + " - " + _likeError : _likeLabel; + float tx = p.X + 22, maxW = Math.Max(10, right - tx - 4); + string shown = Fit(text, maxW); + dl.AddText(new Vector2(tx, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), _likeError.Length > 0 ? Amber : Teal, shown); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(tx, p.Y)); + ImGuiNET.ImGui.InvisibleButton("##inv_like_lbl", new Vector2(maxW, h)); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(_likeTip); + NextLine(p, h + 4); + } + + /// <summary><paramref name="text"/>, cut with "..." to fit <paramref name="width"/>.</summary> + private static string Fit(string text, float width) + { + if (ImGuiNET.ImGui.CalcTextSize(text).X <= width) return text; + for (int n = text.Length - 1; n > 0; n--) + { + string s = text.Substring(0, n) + "..."; + if (ImGuiNET.ImGui.CalcTextSize(s).X <= width) return s; + } + return "..."; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs index 1e275cd..b7c83c9 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs @@ -21,6 +21,7 @@ using System.Globalization; using System.Numerics; using ImGuiNET; using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; @@ -302,6 +303,7 @@ internal sealed partial class InventoryFace } ImGuiNET.ImGui.Separator(); SelectionMenuItems(clicked); + TradeShopMenuItems(); if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); } @@ -319,6 +321,29 @@ internal sealed partial class InventoryFace } } + /// <summary>Add the picked item(s) to RynthAi's Trade Shop catalog (/ra tradeshop addids).</summary> + private void TradeShopMenuItems() + { + int n = _multi.Count > 0 ? _multi.Count : (_selected != 0 ? 1 : 0); + if (n <= 0) return; + string label = n == 1 ? "Add to Trade Shop" : "Add " + n.ToString(CultureInfo.InvariantCulture) + " to Trade Shop"; + if (!ImGuiNET.ImGui.MenuItem(label)) return; + var ids = new List<uint>(); + if (_multi.Count > 0) + { + foreach (uint id in _multi.Ids) + if (id != 0) ids.Add(id); + } + else if (_selected != 0) + ids.Add(_selected); + if (ids.Count == 0) return; + // Decimal object ids; Trade Shop opens the window and lists them at 1p for editing. + string cmd = "/ra tradeshop addids " + string.Join(",", ids); + ServerMenus.Run(cmd); + ServerMenus.Run("/ra tradeshop ui on"); + SafeImGui.SetItemTooltip("Lists the selection in the Trade Shop catalog (edit prices there)."); + } + // ── Status and pieces ─────────────────────────────────────────────── /// <summary> diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index feb1f9c..4e2f9b9 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -122,6 +122,16 @@ internal sealed partial class InventoryFace : IImGuiPanel private InventoryItem? _splitItem; private int _splitAmount = 1; private uint _splitTarget; + // AC ItemType bits (melee weapon, missile weapon, caster) and the shield slot (ValidLocations). + private const uint TypeMeleeWeapon = 0x1, TypeMissileWeapon = 0x100, TypeCaster = 0x8000, ShieldSlot = 0x200000; + + /// <summary> + /// A weapon, wand or shield: what the right-click can add to RynthAi's weapons (the Damage + /// panel's list). RynthAi checks again when it adds it. + /// </summary> + private static bool IsCombatGear(InventoryItem it) => + !it.IsPack && ((it.Type & (TypeMeleeWeapon | TypeMissileWeapon | TypeCaster)) != 0 || (it.ValidLocations & ShieldSlot) != 0); + // "Add to loot profile..." (right-click): RynthAi builds the rule, the popup previews it. private readonly LootAddDialog _lootAdd = new("##inv_lootadd"); @@ -147,6 +157,7 @@ internal sealed partial class InventoryFace : IImGuiPanel ItemDragBridge.EndPopOutDrag(); UiDropTargets.EngineDragObject = 0; _lootAdd.Cancel(); + ClearLike(); } // ===================================================================== @@ -169,6 +180,7 @@ internal sealed partial class InventoryFace : IImGuiPanel } _hoverLabel = _hoverLabel2 = null; + LikeTick(); // Text follows the panel's size setting (the - / + in the Classic title bar). ImGuiNET.ImGui.SetWindowFontScale(InventorySettingsStore.SizeFactor); if (InventorySettingsStore.Classic) ClassicBody(view, origin, size); @@ -199,6 +211,7 @@ internal sealed partial class InventoryFace : IImGuiPanel Header(view, w); Tools(w); Chips(w); + LikeBar(w); RebuildIfNeeded(view, _pack); // Body: pack column | grid, then zones and the status row at the bottom. @@ -228,6 +241,7 @@ internal sealed partial class InventoryFace : IImGuiPanel private const string MiniRemoteTip = "Mini Remote (/rc miniremote): remote, sections and HUDs"; private const string ItemCountTip = "Item Count (/rc itemcount): how many of each named item you carry"; + private const string TradeShopTip = "Trade Shop (/ra tradeshop ui): priced catalog, conversion rates, Mode 1/2"; private static string RynthSortTip() => ScriptWindowRegistry.Has(RynthSortKey) ? "RynthSort (/rsort): pack sort rules and auto-sort" : "RynthSort (/rsort) - needs the RynthSort plugin"; @@ -269,10 +283,13 @@ internal sealed partial class InventoryFace : IImGuiPanel /// <summary>Opens or closes RynthSort (same as /rsort).</summary> private static void ToggleRynthSort() => ToggleScriptWindow(RynthSortKey, "/rsort"); + /// <summary>Opens or closes RynthAi's Trade Shop editor (same as /ra tradeshop ui).</summary> + private static void ToggleTradeShop() => ServerMenus.Run("/ra tradeshop ui"); + // The "more" menu both looks use when their bar is too short for the four buttons. private bool _openMore; - /// <summary>The "more" popup: the four related panels as menu lines (checked while open). Draw where its button was.</summary> + /// <summary>The "more" popup: related panels as menu lines (checked while open). Draw where its button was.</summary> private void RelatedMenu() { if (_openMore) @@ -295,6 +312,9 @@ internal sealed partial class InventoryFace : IImGuiPanel if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv", GlobalInventoryOpen)) ToggleGlobalInventory(); SafeImGui.SetItemTooltip(GlobalInventoryTip()); + if (ImGuiNET.ImGui.MenuItem("Trade Shop", "/ra tradeshop ui")) + ToggleTradeShop(); + SafeImGui.SetItemTooltip(TradeShopTip); ImGuiNET.ImGui.EndPopup(); } PopMenuStyle(); @@ -333,9 +353,8 @@ internal sealed partial class InventoryFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)"); // Related panels (Mini Remote, RynthSort, Item Count, Global Inventory): four icons when the room - // left of the Classic / Close buttons holds them, else one "more" menu, else none (the Character - // menu has them all). The item count text gives way last. On Aelrynth the Vault button sits next - // to the Classic button and takes its room first: it is never dropped + // left of Classic / Close / Vault / Trade Shop holds them, else one "more" menu, else none (the + // Character menu has them all). Trade Shop and Vault are never dropped. // (UI/InventoryTitleLayout.InventoryHeaderLayout, tested in tools/BarDeclutterTests). float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X; float leftEnd = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6; @@ -366,10 +385,19 @@ internal sealed partial class InventoryFace : IImGuiPanel if (IconButton("##inv_more", PhosphorIcons.DotsThree, At(hl.More), btn22, MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) _openMore = true; - ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory"); + ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory, Trade Shop"); } RelatedMenu(); + // Trade Shop (always): priced catalog + conversion rates (/ra tradeshop ui). + if (hl.Shop.Present) + { + if (IconButton("##inv_tradeshop", PhosphorIcons.Storefront, At(hl.Shop), btn22, + Amber, BtnFill, font: UiFont.Ui11)) + ToggleTradeShop(); + SafeImGui.SetItemTooltip(TradeShopTip); + } + // Vault (Aelrynth only): the grid shows the account vault instead of the packs. if (hl.Plan.Vault) { @@ -474,14 +502,20 @@ internal sealed partial class InventoryFace : IImGuiPanel bool classic = InventorySettingsStore.Classic; bool attrOn = AttrOn; int attrKey = attrOn ? _attr.Version : -1; + bool likeOn = LikeOn; + int likeKey = likeOn ? _likeVersion : -1; if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort && _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic - && _builtOrderVersion == Net.InventoryOrder.Version && _builtAttrKey == attrKey && !AttrRefreshDue(attrOn)) + && _builtOrderVersion == Net.InventoryOrder.Version && _builtAttrKey == attrKey && _builtLikeKey == likeKey + && !AttrRefreshDue(attrOn)) return; - if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category || _builtAttrKey != attrKey) + if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category || _builtAttrKey != attrKey + || _builtLikeKey != likeKey) _gridFirstRow = 0; // another pack or filter: back to the top (Classic grid) _builtAttrKey = attrKey; + _builtLikeKey = likeKey; BeginAttrPass(attrOn); + BeginLikePass(likeOn); if (!ReferenceEquals(view, _builtFor)) PruneSelection(view); _builtFor = view; _builtPack = pack; @@ -555,7 +589,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _orderKnown && _sort == 0 && !FiltersOn && !item.RequiresPackSlot && !item.IsPack; /// <summary>Some filter hides items: a category, search text or the attribute filter.</summary> - private bool FiltersOn => _category != 0 || _searchText.Length > 0 || AttrOn; + private bool FiltersOn => _category != 0 || _searchText.Length > 0 || AttrOn || LikeOn; /// <summary>The slot an item holds now among its pack's ordinary items, or -1 when unknown.</summary> private static int SlotOf(InventoryItem item) @@ -579,6 +613,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (_category != 0 && it.Category != cat) continue; if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue; if (_attrPass && !AttrKeeps(it)) continue; + if (_likePass && !LikeKeeps(it)) continue; _shown.Add(it); } } @@ -903,7 +938,7 @@ internal sealed partial class InventoryFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(pos); bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); - SafeImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); // the Give zone's tip carries the target's name bool dropHot = enabled && _dragItem != null && hot; var dl = ImGuiNET.ImGui.GetWindowDrawList(); uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill; @@ -1080,6 +1115,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _searchText = string.Empty; _category = 0; SetAttrEnabled(false); + ClearLike(); } private void Refuse(string why) @@ -1304,6 +1340,22 @@ internal sealed partial class InventoryFace : IImGuiPanel _lootAdd.Open(it.Id, it.Name, toOpenProfile: false); if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)"); + if (ImGuiNET.ImGui.MenuItem("Filter inventory like this...")) + OpenLikeFilter(it, global: false); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Show only your items like this one: the same match and attribute choices as Add to loot profile"); + bool ginv = ScriptWindowRegistry.Has(GlobalInventoryKey); + if (ImGuiNET.ImGui.MenuItem("Find like this in Global Inventory...", "", false, ginv)) + OpenLikeFilter(it, global: true); + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGuiNET.ImGui.SetTooltip(ginv + ? "Find items like this one on every character (Global Inventory), with the same attribute choices" + : "Needs the RynthInventory plugin (Global Inventory)"); + if (IsCombatGear(it) && ImGuiNET.ImGui.MenuItem("Add to Damage panel weapons")) + UI.Data.ItemsCommands.AddWeapon(it.Id); + if (IsCombatGear(it) && ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Let RynthAi use this in combat: it joins the weapons the Damage panel offers per monster" + + " (a shield goes in as an off-hand item). RynthAi says in chat when it is added or already listed."); if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD")) UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name); if (ImGuiNET.ImGui.IsItemHovered()) @@ -1311,6 +1363,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (!it.IsPack) MiniRemoteMenu(it); ImGuiNET.ImGui.Separator(); SelectionMenuItems(it); + TradeShopMenuItems(); if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); } diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs index 53f27a5..4b7bda3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs @@ -14,6 +14,9 @@ // or NPC in the world (Use selected as target), press Give: every // such item in your packs is handed over, one give at a time. // The target's name is shown (PLAYER for a player). +// Amount: how many a round gives (0 = all). Every (s): a round +// again that many seconds after the last ends, until Stop +// (0 = one round). "/ra itemtool giveamount N | giveevery N". // // Data: ItemToolSource (RynthPluginGetItemToolJson, 250 ms while open). Buttons // post words to RynthPluginItemToolCommand (ItemToolCommands.Send), the same @@ -130,7 +133,9 @@ internal sealed class ItemToolFace : IImGuiPanel private static void DrawGive(GiveToolState g, float w) { Label("Quick give", Teal); - Wrapped("Hands every matching item in your packs to one player or NPC, one give at a time, until none is left or you press Stop. Never worn gear.", Mute, w); + Wrapped(g.AmountMax <= 0 + ? "Hands every matching item in your packs to one player or NPC, one give at a time, until none is left or you press Stop. Never worn gear." + : "Hands the picked item to one player or NPC, one give at a time: Amount of them (0 = all), and again Every so many seconds until you press Stop (0 = once). Never worn gear.", Mute, w); Pick("Item:", g.Item, "(none: select the item in your pack)", w); Pick("Target:", g.Target, "(none: select the player or NPC in the world)", w); @@ -140,6 +145,8 @@ internal sealed class ItemToolFace : IImGuiPanel if (hit == 0) ItemToolCommands.Send("giveitem"); else if (hit == 1) ItemToolCommands.Send("givetarget"); + DrawGiveNumbers(g, w); + hit = StartStop("##give_run", "Give", "Stop", ready && !g.Running, g.Running, w); if (hit == 0) ItemToolCommands.Send("give"); else if (hit == 1) ItemToolCommands.Send("givestop"); @@ -147,6 +154,47 @@ internal sealed class ItemToolFace : IImGuiPanel Wrapped(g.Status, g.Running ? Amber : Text, w); } + // A value just sent, shown until RynthAi reports it back (the snapshot is 250 ms behind). + private static int _amountEdit, _everyEdit; + private static long _amountSentAt, _everySentAt; + private const long GivePendingMs = 2000; + + /// <summary> + /// "Amount" and "Every (s)" side by side (2026-11-15). A value goes to RynthAi on Enter or a +/- click + /// ("giveamount N", "giveevery N"); a running give takes the amount from its next give and the interval + /// from its next round. Hidden for a RynthAi that predates them. + /// </summary> + private static void DrawGiveNumbers(GiveToolState g, float w) + { + if (g.AmountMax <= 0) return; + float half = Math.Max(70, (w - 10) / 2); + float x0 = ImGuiNET.ImGui.GetCursorPosX(); + Label("Amount (0 = all)", Mute); + ImGuiNET.ImGui.SameLine(x0 + half + 10); + Label("Every (s, 0 = once)", Mute); + + NumberField("##give_amount", "giveamount", g.Amount, g.AmountMax, ref _amountEdit, ref _amountSentAt, half, + "How many a round gives; a stack bigger than what is left is split.\n0 = every one in your packs.\nEnter (or +/-) to set it."); + ImGuiNET.ImGui.SameLine(0, 10); + NumberField("##give_every", "giveevery", g.EverySec, g.EveryMax, ref _everyEdit, ref _everySentAt, half, + "Seconds from the end of one round to the start of the next; it goes on until you press Stop.\nBetween rounds, the target away, a fight or none in your packs only delays the next round.\n0 = one round. Enter (or +/-) to set it."); + } + + private static void NumberField(string id, string verb, int current, int max, ref int edit, ref long sentAt, float width, string tip) + { + long now = Environment.TickCount64; + int v = now - sentAt < GivePendingMs && current != edit ? edit : current; + ImGuiNET.ImGui.SetNextItemWidth(width); + if (ImGuiNET.ImGui.InputInt(id, ref v, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue)) + { + v = Math.Clamp(v, 0, Math.Max(0, max)); + edit = v; + sentAt = now; + ItemToolCommands.Send(verb + " " + v.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + SafeImGui.SetItemTooltip(tip); + } + // ── Pieces ────────────────────────────────────────────────────────── /// <summary>"Label value" (amber while nothing is picked, the hint then).</summary> diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 5c15930..e4a9e4f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -94,8 +94,9 @@ internal sealed class ItemsFace : IImGuiPanel int i = idx[k]; ItemsPanel.WeaponEntry wpn = _data.Weapons[i]; ImGuiNET.ImGui.PushID("w" + i); - int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), k > 0, k < idx.Count - 1, - wpn.ShowsNoBuff ? wpn.NoBuff : null); + int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), + DamageTypeColors.For(wpn.Element, Text), k > 0, k < idx.Count - 1, + wpn.ShowsNoBuff ? wpn.NoBuff : null); ImGuiNET.ImGui.PopID(); if (r == 5) { @@ -116,9 +117,11 @@ internal sealed class ItemsFace : IImGuiPanel if (r == 1) { Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; - _picker.Open(at, ItemsCommands.Elements, Array.IndexOf(ItemsCommands.Elements, wpn.Element), e => + // Missile weapons and ammo can also be Prismatic: universal damage, the target's weakest element. + string[] choices = ItemsCommands.ElementsFor(wpn.Kind); + _picker.Open(at, choices, Array.IndexOf(choices, wpn.Element), e => { - wpn.Element = ItemsCommands.Elements[e]; + wpn.Element = choices[e]; Save(); }, 160); } @@ -146,7 +149,7 @@ internal sealed class ItemsFace : IImGuiPanel { ItemsPanel.ConsumableEntry c = _data.Consumables[i]; ImGuiNET.ImGui.PushID("c" + i); - int r = Row(c.Name, c.Type, i, bw, missing: false, canUp: i > 0, canDown: i < _data.Consumables.Count - 1); + int r = Row(c.Name, c.Type, i, bw, missing: false, tint: Text, canUp: i > 0, canDown: i < _data.Consumables.Count - 1); ImGuiNET.ImGui.PopID(); if (r == 3 || r == 4) { @@ -309,8 +312,11 @@ internal sealed class ItemsFace : IImGuiPanel /// warning icon, "(missing)" and a tooltip saying what to do). <paramref name="noBuff"/> /// non-null (a shield row, RynthAi sending noBuff): the value column is the "No buff" toggle /// instead of the picker (a shield has no element; its column only said "Shield"). + /// Otherwise the name and value are drawn in <paramref name="tint"/> (a weapon's damage-type + /// colour, as UB-ILT's Items tab). /// </summary> - private static int Row(string name, string value, int index, float w, bool missing, bool canUp = false, bool canDown = false, + /// <param name="tint">The value button's text colour (a weapon's damage type colour, else Text).</param> + private static int Row(string name, string value, int index, float w, bool missing, uint tint, bool canUp = false, bool canDown = false, bool? noBuff = null) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); @@ -330,11 +336,11 @@ internal sealed class ItemsFace : IImGuiPanel } else { - dl.AddText(new Vector2(p.X + 6, ty), Text, name); + dl.AddText(new Vector2(p.X + 6, ty), tint, name); } dl.PopClipRect(); if (missing && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(nameW, 24))) - ImGuiNET.ImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n" + SafeImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n" + "Add Selected Weapon again, or remove this entry."); int result = 0; float bx = p.X + nameW + 2; @@ -350,7 +356,7 @@ internal sealed class ItemsFace : IImGuiPanel nb ? OnText : Mute, nb ? OnBg : BtnFill)) result = 5; ImGuiNET.ImGui.SetItemTooltip(NoBuffTip); } - else if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; + else if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), tint, BtnFill)) result = 1; if (IconButton("##del", PhosphorIcons.Trash, new Vector2(bx + 100, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2; ImGuiNET.ImGui.SetItemTooltip("Remove"); NextLine(p, 24); diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index 96fc069..3bd10d4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -25,17 +25,37 @@ // save; this face only posts item_preview / item_add / item_close through // LootEditCommands and shows LootEditStateDto.ItemDraft. A face owns one of // these and calls Draw once per frame outside any child window. +// +// Filter modes (2026-10-24): the Inventory panel's "Filter inventory like +// this" and "Find like this in Global Inventory" open the same popup with the +// same match and attribute checklist, but no profile, action or name: the +// rule becomes a filter. item_find asks RynthAi to judge the panel's items +// (FilterInventory: the result goes to Found) or to encode the rule for +// RynthInventory (FilterGlobal: "/ginv like <spec>" runs, which opens Global +// Inventory filtered). A filter defaults to "Items like this". // ============================================================================ using System; using System.Globalization; using System.Numerics; using ImGuiNET; +using RynthCore.Engine.UI; using RynthCore.Engine.UI.Data; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; +/// <summary>What the popup makes of the item: a loot rule, or a filter (2026-10-24).</summary> +internal enum LootAddMode : byte +{ + /// <summary>Add to loot profile.</summary> + AddRule, + /// <summary>Filter the Inventory panel to items like this.</summary> + FilterInventory, + /// <summary>Open Global Inventory filtered to items like this, on every character.</summary> + FilterGlobal, +} + internal sealed class LootAddDialog { private static readonly string[] MatchLabels = { "Name + class", "Name only", "Items like this" }; @@ -47,10 +67,16 @@ internal sealed class LootAddDialog }; private static readonly int[] ActionIds = { LootEditVocabulary.Keep, LootEditVocabulary.KeepUpTo, LootEditVocabulary.Salvage, LootEditVocabulary.Sell, LootEditVocabulary.Read }; - private static readonly string[] ActionLabels = { "Keep", "Keep #", "Salvage", "Sell", "Read" }; + // "Keep #" + "##a1" would read "###a1" (an id-only label) and lose its "#". + private static readonly string[] ActionLabels = { "Keep", "Keep up to", "Salvage", "Sell", "Read" }; private readonly string _id; private bool _open, _openRequested, _subscribed; + private LootAddMode _mode; + // A filter's item_find in flight (its answer is LootEditStateDto.ItemFind with this Seq). + private bool _finding, _closeRequested; + private DateTime _findSentAt; + private string _findError = string.Empty; private uint _itemId; private string _itemName = string.Empty; private bool _toOpenProfile; @@ -58,6 +84,17 @@ internal sealed class LootAddDialog // What the popup asks for (0 / -1 = RynthAi's default). private int _match, _action, _keep = -1; private bool _includeT11; + // No item (the panel's own filter: every attribute, 2026-10-24). + private bool _blank; + // The open group of a long (blank) checklist; the others show only their ticked rows. + private string _openGroup = string.Empty; + // Blank: the rule being edited (-1: a new one) and its name as the editor showed it (2026-11-07). + private int _editIndex = -1; + private string _editName = string.Empty; + // Spells and cantrips added from the standard lists, by their row id (LootItemAttributes.ExtraId). + private readonly System.Collections.Generic.Dictionary<string, LootEditItemExtraDto> _extras = new(); + // The spell pickers' current picks. + private int _pickSchool, _pickFamily, _pickLevel = 6, _pickTier = 3, _pickCantrip; private readonly byte[] _name = new byte[128]; private int _keepEdit = 1; @@ -92,22 +129,60 @@ internal sealed class LootAddDialog public bool IsOpen => _open; + /// <summary> + /// A blank rule's "Start empty": the Loot Editor adds an empty rule to edit by hand (its old Add + /// rule), the popup closes. Null: no such button. + /// </summary> + public Action? EmptyRule { get; set; } + + /// <summary>Editing a rule: "Raw editor" closes the popup and opens the rule's raw conditions (index). Null: no button.</summary> + public Action<int>? RawEditor { get; set; } + + /// <summary>FilterInventory: the items to judge (the panel's), asked when the player presses Filter.</summary> + public Func<System.Collections.Generic.List<uint>>? Candidates { get; set; } + + /// <summary>FilterInventory: RynthAi's answer to Filter (Ok), handed over as the popup closes.</summary> + public Action<LootEditItemFindDto>? Found { get; set; } + + /// <summary>A fresh request Seq, unique across popups and the panel's own find_refresh asks.</summary> + public static int NextSeq() => System.Threading.Interlocked.Increment(ref s_seq); + /// <summary> /// Opens the popup for <paramref name="itemId"/> (0: the item selected in the /// game, resolved once). <paramref name="toOpenProfile"/>: the rule goes to the /// profile open in the Loot Editor, else to the one RynthAi loots with. /// </summary> - public void Open(uint itemId, string itemName, bool toOpenProfile) + /// <summary> + /// Edits rule <paramref name="index"/> (named <paramref name="name"/>) of the profile open in the Loot + /// Editor with the same checklist (2026-11-07): it starts from the rule's conditions; Save replaces it. + /// </summary> + public void OpenEdit(int index, string name) { - _itemId = itemId; + Open(0, string.Empty, toOpenProfile: true, LootAddMode.AddRule, blank: true, editIndex: index, editName: name); + } + + public void Open(uint itemId, string itemName, bool toOpenProfile, LootAddMode mode = LootAddMode.AddRule, bool blank = false, + int editIndex = -1, string editName = "") + { + _editIndex = blank && mode == LootAddMode.AddRule ? editIndex : -1; + _editName = editName ?? string.Empty; + // Blank: no item, every attribute (the Inventory panel's own filter, and since 2026-11-07 the + // Loot Editor's Add rule: the same checklist makes the new rule). + _blank = blank; + _extras.Clear(); + _itemId = _blank ? 0 : itemId; _itemName = itemName ?? string.Empty; _toOpenProfile = toOpenProfile; - _match = 0; + _mode = mode; + _finding = _closeRequested = false; + _findError = string.Empty; + _match = mode == LootAddMode.AddRule && !blank ? 0 : 2; // a filter looks for look-alikes _action = 0; _keep = -1; _includeT11 = false; Array.Clear(_name); _choices.Clear(); + _openGroup = string.Empty; _valueBufs.Clear(); _editingId = string.Empty; _draft = null; @@ -125,9 +200,11 @@ internal sealed class LootAddDialog private void Send(string op) { - _seq = System.Threading.Interlocked.Increment(ref s_seq); + _seq = NextSeq(); _mine.Add(_seq); _sentAt = DateTime.UtcNow; + bool filter = _mode != LootAddMode.AddRule; + bool global = _mode == LootAddMode.FilterGlobal; LootEditCommands.Send(new LootEditCmd { Op = op, @@ -137,6 +214,13 @@ internal sealed class LootAddDialog RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, IncludeT11 = _includeT11, Seq = _seq, // Null until the player changes a row: RynthAi's defaults (and its notes about them). Choices = _choices.Count == 0 ? null : new System.Collections.Generic.List<LootEditItemChoiceDto>(_choices.Values), + Find = filter, + Blank = _blank, + EditIndex = _editIndex, + EditName = _editName, + Extras = _extras.Count == 0 ? null : new System.Collections.Generic.List<LootEditItemExtraDto>(_extras.Values), + Scope = !filter ? string.Empty : global ? LootFindScopes.Global : LootFindScopes.Inventory, + Candidates = op == "item_find" && filter && !global ? Candidates?.Invoke() : null, }, }); } @@ -171,6 +255,7 @@ internal sealed class LootAddDialog } if (!_open) return; TakeDraft(); + TakeFind(); PushStyle(); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); @@ -184,7 +269,13 @@ internal sealed class LootAddDialog } try { - if (Body()) ImGuiNET.ImGui.CloseCurrentPopup(); + if (_closeRequested) + { + _closeRequested = false; + Close(); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (_mode == LootAddMode.AddRule ? Body() : FilterBody()) ImGuiNET.ImGui.CloseCurrentPopup(); } finally { @@ -226,15 +317,169 @@ internal sealed class LootAddDialog } } + /// <summary> + /// A filter's answer from RynthAi: an error stays in the popup; Global Inventory gets its + /// "/ginv like"; the Inventory panel gets the matches (Found); then the popup closes. + /// </summary> + private void TakeFind() + { + if (!_finding) return; + LootEditItemFindDto? f = UiSources.LootEdit.Current?.Value.State?.ItemFind; + if (f == null || f.Seq != _seq) + { + if ((DateTime.UtcNow - _findSentAt).TotalSeconds > 5) + { + _finding = false; + _findError = "No answer from RynthAi. A RynthAi older than this feature can't filter; update RynthSuite."; + } + return; + } + _finding = false; + if (!f.Ok) + { + _findError = f.Error.Length > 0 ? f.Error : "RynthAi couldn't build the filter."; + return; + } + if (_mode == LootAddMode.FilterGlobal) + { + if (f.Spec.Length == 0) + { + _findError = "RynthAi sent no filter for Global Inventory."; + return; + } + ServerMenus.Run("/ginv like " + f.Spec); + } + else + Found?.Invoke(f); + _closeRequested = true; + } + + /// <summary>The filter modes' contents: match, checklist, the conditions, Filter / Cancel. True when it should close.</summary> + private bool FilterBody() + { + bool global = _mode == LootAddMode.FilterGlobal; + LootEditItemDraftDto? d = _draft; + float w = d?.AttributesSupported == true ? 500 : 380; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(_blank + ? PhosphorIcons.Funnel + " Filter inventory" + : global + ? PhosphorIcons.GlobeHemisphereWest + " Find like this in Global Inventory" + : PhosphorIcons.Funnel + " Filter inventory like this"); + ImGuiNET.ImGui.PopStyleColor(); + if (_blank) ImGuiNET.ImGui.TextDisabled("Tick what the items must have; add spells and cantrips from the lists."); + else ImGuiNET.ImGui.TextUnformatted(_itemName.Length > 0 ? _itemName : "the selected item"); + ImGuiNET.ImGui.Separator(); + + bool current = d != null && d.Seq == _seq; + if (d == null) + { + bool slow = (DateTime.UtcNow - _sentAt).TotalSeconds > 3; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, slow ? Amber : Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(slow + ? "No answer from RynthAi. Is it loaded? (A RynthAi older than this feature can't filter.)" + : "Reading the item..."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return CloseRow(w); + } + if (!d.Find) + { + // A RynthAi from before filters answers with a loot rule draft (and asks for a profile). + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted("This RynthAi is older than inventory filters. Update RynthSuite to filter like this."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return CloseRow(w); + } + + bool changed = false; + if (!_blank) + { + ImGuiNET.ImGui.TextDisabled("Match:"); + for (int i = 0; i < MatchLabels.Length; i++) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(MatchLabels[i] + "##fm" + i.ToString(CultureInfo.InvariantCulture), d.Match == i) && d.Match != i) + { + _match = i; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]); + } + } + if (d.AttributesSupported) changed |= DrawAttributes(d, w); + + // The filter in words. + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, current ? Teal : Faded(Teal)); + foreach (string line in d.Preview) ImGuiNET.ImGui.TextUnformatted(line); + ImGuiNET.ImGui.PopStyleColor(); + if (global) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.TextUnformatted("Looks through every character's saved packs and storage. Attributes that need an identify are only known for items that were identified when their character last saved."); + ImGuiNET.ImGui.PopStyleColor(); + } + if (d.Notes.Count > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + foreach (string n in d.Notes) ImGuiNET.ImGui.TextUnformatted(n); + ImGuiNET.ImGui.PopStyleColor(); + } + string error = !d.Ok && d.Error.Length > 0 ? d.Error : _findError; + if (error.Length > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + ImGuiNET.ImGui.TextUnformatted(error); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.PopTextWrapPos(); + + if (changed) + { + Send("item_preview"); // Filter waits for the answer (the conditions show faded until then) + _findError = string.Empty; + current = false; + } + + // Filter / Cancel. + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + bool canGo = current && d.Ok && !_finding; + string goLabel = _finding ? "Filtering..." : global ? PhosphorIcons.GlobeHemisphereWest + " Search" : PhosphorIcons.Funnel + " Filter"; + if (Button("##la_find", goLabel, bp, new Vector2(110, 24), canGo ? Green : Mute, canGo ? StartBg : BtnFill, canGo)) + { + _finding = true; + _findError = string.Empty; + _findSentAt = DateTime.UtcNow; + Send("item_find"); + } + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip(global + ? "Open Global Inventory showing every character's items that match" + : "Show only the items in your packs that match (the funnel bar over the list clears it)"); + if (Button("##la_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) + return CloseNow(); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + return false; + } + /// <summary>The popup's contents; true when it should close.</summary> private bool Body() { // Wider with the checklist (label, comparison, value on one line). - float w = _draft?.AttributesSupported == true ? 440 : 380; + float w = _draft?.AttributesSupported == true ? 500 : 380; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); - ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Plus + " Add to loot profile"); + ImGuiNET.ImGui.TextUnformatted(_editIndex >= 0 + ? PhosphorIcons.PencilSimple + " Edit loot rule " + (_editIndex + 1).ToString(CultureInfo.InvariantCulture) + (_editName.Length > 0 ? ": " + _editName : string.Empty) + : PhosphorIcons.Plus + (_blank ? " New loot rule" : " Add to loot profile")); ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.TextUnformatted(_itemName.Length > 0 ? _itemName : "the selected item"); + if (_blank) ImGuiNET.ImGui.TextDisabled("Tick what the items must have; add spells and cantrips from the lists."); + else ImGuiNET.ImGui.TextUnformatted(_itemName.Length > 0 ? _itemName : "the selected item"); ImGuiNET.ImGui.Separator(); LootEditItemDraftDto? d = _draft; @@ -251,6 +496,26 @@ internal sealed class LootAddDialog ImGuiNET.ImGui.PopStyleColor(); return CloseRow(w); } + if (_blank && (!d.Blank || d.EditIndex != _editIndex)) + { + // A RynthAi from before 2026-11-07 answers a blank rule with the selected item's draft. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted("This RynthAi is older than the attribute checklist for new rules. Update RynthSuite, or start an empty rule and edit it by hand."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + if (EmptyRule != null) + { + Vector2 ep = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##la_empty_old", PhosphorIcons.Plus + " Start empty", ep, new Vector2(110, 24), Text, BtnFill)) + { + EmptyRule(); + return CloseNow(); + } + ImGuiNET.ImGui.SetCursorScreenPos(ep + new Vector2(0, 28)); + } + return CloseRow(w); + } if (d.Added && _addedAt != default) { @@ -273,17 +538,20 @@ internal sealed class LootAddDialog } bool changed = false; - // Match. - ImGuiNET.ImGui.TextDisabled("Match:"); - for (int i = 0; i < MatchLabels.Length; i++) + // Match (an item's rule only: a blank rule is what is ticked). + if (!_blank) { - ImGuiNET.ImGui.SameLine(); - if (ImGuiNET.ImGui.RadioButton(MatchLabels[i] + "##m" + i.ToString(CultureInfo.InvariantCulture), d.Match == i) && d.Match != i) + ImGuiNET.ImGui.TextDisabled("Match:"); + for (int i = 0; i < MatchLabels.Length; i++) { - _match = i; - changed = true; + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(MatchLabels[i] + "##m" + i.ToString(CultureInfo.InvariantCulture), d.Match == i) && d.Match != i) + { + _match = i; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]); } - if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]); } if (d.AttributesSupported) @@ -339,7 +607,7 @@ internal sealed class LootAddDialog changed = true; } ImGuiNET.ImGui.SameLine(); - SafeImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); + SafeImGui.TextDisabled(d.Stackable || _blank ? "(counts stack sizes)" : "(items)"); } // Name. @@ -386,18 +654,42 @@ internal sealed class LootAddDialog // Add / Cancel. Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); bool canAdd = current && d.Ok && !_adding; - string addLabel = _adding ? "Adding..." : PhosphorIcons.Plus + " Add rule"; + string addLabel = _adding ? (_editIndex >= 0 ? "Saving..." : "Adding...") + : _editIndex >= 0 ? PhosphorIcons.Check + " Save rule" : PhosphorIcons.Plus + " Add rule"; if (Button("##la_add", addLabel, bp, new Vector2(110, 24), canAdd ? Green : Mute, canAdd ? StartBg : BtnFill, canAdd)) { _adding = true; Send("item_add"); } if (ImGuiNET.ImGui.IsItemHovered()) - SafeImGui.SetTooltip(d.InsertAt >= 0 + SafeImGui.SetTooltip(_editIndex >= 0 + ? $"Replace rule {_editIndex + 1}, save {d.TargetFile} (old file kept as .bak) and reload it" + : d.InsertAt >= 0 ? $"Insert at {d.InsertAt + 1} of {d.RuleCount + 1}, save {d.TargetFile} (old file kept as .bak) and reload it" : "Add the rule"); if (Button("##la_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) return CloseNow(); + if (_editIndex >= 0 && RawEditor != null) + { + int at = _editIndex; + if (Button("##la_raw", PhosphorIcons.Code + " Raw editor", bp + new Vector2(202, 0), new Vector2(110, 24), Mute, BtnFill)) + { + Action<int> open = RawEditor; + bool closed = CloseNow(); + open(at); + return closed; + } + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip("Edit this rule's conditions one by one, as written in the file"); + } + if (_blank && EmptyRule != null && _editIndex < 0) + { + if (Button("##la_empty", PhosphorIcons.Plus + " Start empty", bp + new Vector2(202, 0), new Vector2(110, 24), Mute, BtnFill)) + { + EmptyRule(); + return CloseNow(); + } + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip("Add an empty rule at the end and write its conditions by hand"); + } ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); return false; @@ -421,15 +713,22 @@ internal sealed class LootAddDialog int ticked = rows.FindAll(r => r.On).Count; SafeImGui.TextDisabled($"{ticked} of {rows.Count} required (tick what the rule needs)"); - int groups = 0; + // One group open at a time, the ticked rows of the others always shown (2026-11-07: the same as + // RynthInventory's Global Inventory checklist). A short list (an item's) shows every group. + bool fold = rows.Count > 24; + if (fold && (_openGroup.Length == 0 || !rows.Exists(r => r.Group == _openGroup))) _openGroup = rows[0].Group; + int groups = 0, shownRows = 0; string? last = null; foreach (LootEditItemAttributeDto r in rows) + { if (r.Group != last) { groups++; last = r.Group; } + if (!fold || r.On || r.Group == _openGroup) shownRows++; + } float lineH = ImGuiNET.ImGui.GetFrameHeightWithSpacing(); - float h = Math.Min(rows.Count * lineH + groups * lineH + 8, 300); + float h = Math.Min(shownRows * lineH + groups * lineH + 8, 300); bool changed = false; - const float opX = 230, valueX = 330; + const float opX = 250, valueX = 350; ImGuiNET.ImGui.BeginChild("##la_attrs", new Vector2(w, h), ImGuiChildFlags.Borders); string? group = null; foreach (LootEditItemAttributeDto r in rows) @@ -437,8 +736,18 @@ internal sealed class LootAddDialog if (r.Group != group) { group = r.Group; + string g = group; + int inGroup = rows.FindAll(x => x.Group == g && x.On).Count; + bool open = !fold || _openGroup == g; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); - ImGuiNET.ImGui.TextUnformatted(group); + string head = (fold ? (open ? "- " : "+ ") : string.Empty) + g + + (inGroup > 0 ? " (" + inGroup.ToString(CultureInfo.InvariantCulture) + ")" : string.Empty); + if (fold) + { + if (ImGuiNET.ImGui.Selectable(head + "##la_grp_" + g, open, ImGuiSelectableFlags.None, new Vector2(opX - 12, 0))) + _openGroup = open ? string.Empty : g; + } + else ImGuiNET.ImGui.TextUnformatted(head); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.SameLine(opX); if (ImGuiNET.ImGui.SmallButton("all##la_all_" + group)) changed |= TickGroup(rows, group, true); @@ -446,10 +755,13 @@ internal sealed class LootAddDialog if (ImGuiNET.ImGui.SmallButton("none##la_none_" + group)) changed |= TickGroup(rows, group, false); } + if (fold && !r.On && r.Group != _openGroup) continue; // a folded group shows its ticked rows only bool on = r.On; if (ImGuiNET.ImGui.Checkbox(r.Label + "##la_on_" + r.Id, ref on)) { - SetChoice(r, on: on); + // Unticking a spell added from the lists removes it. + if (!on && _extras.Remove(r.Id)) _choices.Remove(r.Id); + else SetChoice(r, on: on); changed = true; } if (ImGuiNET.ImGui.IsItemHovered() && r.Tip.Length > 0) SafeImGui.SetTooltip(r.Tip); @@ -475,7 +787,29 @@ internal sealed class LootAddDialog // The value: a box for numbers, the item's value (by name) for the rest. ImGuiNET.ImGui.SameLine(valueX); - if (r.Editable) + if (r.Op == LootAttrOps.Any) + SafeImGui.TextDisabled("any value"); + else if (r.Flags && LootAttrOps.PicksSeveral(r.Op) && r.Choices != null && r.Choices.Count > 0) + changed |= FlagsPicker(r, w - valueX - 16); + else if (r.Choices != null && r.Choices.Count > 0) + { + // A named value: pick another from its list (material, skill, class...). + int cur = int.TryParse(r.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int cv) ? cv : int.MinValue; + string curName = r.ItemValue; + foreach (LootEditNameDto c in r.Choices) if (c.Id == cur) { curName = c.Name; break; } + ImGuiNET.ImGui.SetNextItemWidth(w - valueX - 16); + if (ImGuiNET.ImGui.BeginCombo("##la_ch_" + r.Id, curName, ImGuiComboFlags.HeightLarge)) + { + foreach (LootEditNameDto c in r.Choices) + if (ImGuiNET.ImGui.Selectable(c.Name + "##la_chv_" + r.Id + c.Id.ToString(CultureInfo.InvariantCulture), c.Id == cur) && c.Id != cur) + { + SetChoice(r, value: c.Id.ToString(CultureInfo.InvariantCulture), on: true); // picking a value means "require it" + changed = true; + } + ImGuiNET.ImGui.EndCombo(); + } + } + else if (r.Editable) { if (!_valueBufs.TryGetValue(r.Id, out byte[]? buf)) { @@ -500,9 +834,145 @@ internal sealed class LootAddDialog SafeImGui.TextDisabled(r.ItemValue); } ImGuiNET.ImGui.EndChild(); + changed |= SpellPickers(w); return changed; } + /// <summary> + /// A flags row with "has any" / "has all" (2026-11-07, multi imbues): tick several in the list; + /// a pick of several ("Any elemental rend") ticks or clears all of its flags. The value sent is + /// their sum. True when it changed. + /// </summary> + private bool FlagsPicker(LootEditItemAttributeDto r, float width) + { + int cur = int.TryParse(r.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int cv) ? cv : 0; + var names = new System.Collections.Generic.List<string>(); + foreach (LootEditNameDto c in r.Choices!) + if (IsSingleFlag(c.Id) && (cur & c.Id) != 0) names.Add(c.Name); + string preview = names.Count == 0 ? "(pick)" : string.Join(", ", names); + bool changed = false; + ImGuiNET.ImGui.SetNextItemWidth(width); + if (ImGuiNET.ImGui.BeginCombo("##la_fl_" + r.Id, preview, ImGuiComboFlags.HeightLarge)) + { + int next = cur; + foreach (LootEditNameDto c in r.Choices) + { + bool single = IsSingleFlag(c.Id); + bool all = (cur & c.Id) == c.Id; + string mark = single ? (all ? "[x] " : "[ ] ") : (all ? "[x] " : (cur & c.Id) != 0 ? "[-] " : "[ ] "); + if (ImGuiNET.ImGui.Selectable(mark + c.Name + "##la_flv_" + r.Id + c.Id.ToString(CultureInfo.InvariantCulture), false, ImGuiSelectableFlags.NoAutoClosePopups)) + next = all ? next & ~c.Id : next | c.Id; + } + ImGuiNET.ImGui.EndCombo(); + if (next != cur && next != 0) + { + SetChoice(r, value: next.ToString(CultureInfo.InvariantCulture), on: true); + r.Value = next.ToString(CultureInfo.InvariantCulture); // shows at once; RynthAi's answer follows + changed = true; + } + } + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip(r.Op == LootAttrOps.HasAll ? "The item must have every ticked one." : "The item must have at least one of the ticked ones."); + return changed; + } + + private static bool IsSingleFlag(int v) => v != 0 && (v & (v - 1)) == 0; + + /// <summary> + /// "Add spell" and "Add cantrip": a spell family from the standard creature / life / item + /// lists at a level (I-VIII), or a cantrip at a tier (Minor ... Paragon), from RynthAi's + /// spell table (the vocabulary). Adding one ticks a new row ("or better" by default). + /// </summary> + private bool SpellPickers(float w) + { + LootEditVocabDto? vocab = UiSources.LootEdit.Current?.Value.Vocab; + if (vocab == null || vocab.SpellFamilies.Count == 0) + { + SafeImGui.TextDisabled("Spell lists: waiting for RynthAi's spell table (an older RynthAi has none)."); + return false; + } + bool changed = false; + string[] schools = { "Creature", "Life", "Item" }; + _pickSchool = Math.Clamp(_pickSchool, 0, schools.Length - 1); + var fams = vocab.SpellFamilies.FindAll(f => f.School == schools[_pickSchool]); + + ImGuiNET.ImGui.TextDisabled("Add spell:"); + ImGuiNET.ImGui.SameLine(80); + ImGuiNET.ImGui.SetNextItemWidth(80); + if (ImGuiNET.ImGui.BeginCombo("##la_psch", schools[_pickSchool])) + { + for (int i = 0; i < schools.Length; i++) + if (ImGuiNET.ImGui.Selectable(schools[i], i == _pickSchool)) { _pickSchool = i; _pickFamily = 0; } + ImGuiNET.ImGui.EndCombo(); + } + _pickFamily = fams.Count == 0 ? 0 : Math.Clamp(_pickFamily, 0, fams.Count - 1); + LootEditSpellFamilyDto? fam = fams.Count > 0 ? fams[_pickFamily] : null; + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(w - 80 - 80 - 70 - 60 - 24); + if (ImGuiNET.ImGui.BeginCombo("##la_pfam", fam?.Name ?? "(none)", ImGuiComboFlags.HeightLarge)) + { + for (int i = 0; i < fams.Count; i++) + if (ImGuiNET.ImGui.Selectable(fams[i].Name + "##la_pf" + i.ToString(CultureInfo.InvariantCulture), i == _pickFamily)) _pickFamily = i; + ImGuiNET.ImGui.EndCombo(); + } + if (fam != null) _pickLevel = Math.Clamp(_pickLevel, Math.Max(1, fam.MinLevel), Math.Min(8, fam.MaxLevel)); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(70); + if (ImGuiNET.ImGui.BeginCombo("##la_plvl", "Level " + Roman(_pickLevel))) + { + int lo = fam != null ? Math.Max(1, fam.MinLevel) : 1, hi = fam != null ? Math.Min(8, fam.MaxLevel) : 8; + for (int l = lo; l <= hi; l++) + if (ImGuiNET.ImGui.Selectable(Roman(l) + "##la_pl" + l.ToString(CultureInfo.InvariantCulture), l == _pickLevel)) _pickLevel = l; + ImGuiNET.ImGui.EndCombo(); + } + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Add##la_padd", new Vector2(56, 0)) && fam != null) + changed |= AddExtra(new LootEditItemExtraDto { Kind = LootEditItemExtraDto.Spell, Name = fam.Name, Level = _pickLevel }); + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Require this spell (Self or Other) at this level or better; change it to exact or any level in its row."); + + var tiers = vocab.CantripTiers.Count > 0 ? vocab.CantripTiers : new System.Collections.Generic.List<string> { "Minor", "Major", "Epic", "Legendary", "Paragon" }; + _pickTier = Math.Clamp(_pickTier, 0, tiers.Count - 1); + _pickCantrip = vocab.Cantrips.Count == 0 ? 0 : Math.Clamp(_pickCantrip, 0, vocab.Cantrips.Count - 1); + ImGuiNET.ImGui.TextDisabled("Add cantrip:"); + ImGuiNET.ImGui.SameLine(80); + ImGuiNET.ImGui.SetNextItemWidth(80); + if (ImGuiNET.ImGui.BeginCombo("##la_ptier", tiers[_pickTier])) + { + for (int i = 0; i < tiers.Count; i++) + if (ImGuiNET.ImGui.Selectable(tiers[i], i == _pickTier)) _pickTier = i; + ImGuiNET.ImGui.EndCombo(); + } + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(w - 80 - 80 - 60 - 16); + string cname = vocab.Cantrips.Count > 0 ? vocab.Cantrips[_pickCantrip] : "(none)"; + if (ImGuiNET.ImGui.BeginCombo("##la_pcan", cname, ImGuiComboFlags.HeightLarge)) + { + for (int i = 0; i < vocab.Cantrips.Count; i++) + if (ImGuiNET.ImGui.Selectable(vocab.Cantrips[i] + "##la_pc" + i.ToString(CultureInfo.InvariantCulture), i == _pickCantrip)) _pickCantrip = i; + ImGuiNET.ImGui.EndCombo(); + } + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Add##la_cadd", new Vector2(56, 0)) && vocab.Cantrips.Count > 0) + changed |= AddExtra(new LootEditItemExtraDto { Kind = LootEditItemExtraDto.Cantrip, Name = cname, Level = _pickTier }); + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Require this cantrip at this tier or better (Minor < Major < Epic < Legendary < Paragon)."); + return changed; + } + + private bool AddExtra(LootEditItemExtraDto x) + { + string id = x.Kind == LootEditItemExtraDto.Cantrip + ? "x:cantrip:" + x.Level.ToString(CultureInfo.InvariantCulture) + ":" + x.Name.Trim() + : "x:spell:" + x.Name.Trim() + ":" + x.Level.ToString(CultureInfo.InvariantCulture); + if (_extras.ContainsKey(id)) return false; + _extras[id] = x; + return true; + } + + private static readonly string[] RomanNumerals = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII" }; + private static string Roman(int level) => RomanNumerals[Math.Clamp(level, 1, 8) - 1]; + /// <summary>Ticks or clears every row of <paramref name="group"/>; true when one changed.</summary> private bool TickGroup(System.Collections.Generic.List<LootEditItemAttributeDto> rows, string group, bool on) { diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index f9e6834..04483f3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -367,7 +367,7 @@ internal sealed class LootEditorFace : IImGuiPanel { var n = new string[list.Count]; var id = new int[list.Count]; - for (int i = 0; i < list.Count; i++) { n[i] = list[i].Name + " (" + list[i].Id.ToString(CultureInfo.InvariantCulture) + ")"; id[i] = list[i].Id; } + for (int i = 0; i < list.Count; i++) { n[i] = list[i].Name; id[i] = list[i].Id; /* names only (2026-11-07) */ } return (n, id); } } @@ -709,7 +709,17 @@ internal sealed class LootEditorFace : IImGuiPanel // Name | conditions; click to edit. float textW = Math.Max(1, right - 4 - x); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); - if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, RowH))) OpenRule(index); + // Click: the same checklist as Add rule (2026-11-07); the popup's "Raw editor" is the rule view. + if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, RowH))) + { + if (_state != null && !_state.ReadOnly && !_state.Dirty && !string.Equals(_state.Format, "json", StringComparison.OrdinalIgnoreCase)) + { + _lootAdd.EmptyRule = null; + _lootAdd.RawEditor = OpenRule; + _lootAdd.OpenEdit(index, r.Name); + } + else OpenRule(index); + } bool hot = ImGuiNET.ImGui.IsItemHovered(); if (hot) { @@ -734,6 +744,13 @@ internal sealed class LootEditorFace : IImGuiPanel return changed; } + /// <summary>An empty rule at the end, opened to edit by hand (Add rule before the checklist).</summary> + private void AddEmptyRule() + { + LootEditCommands.Simple("add", -1); + Expect(Await.OpenFocus); + } + private void Expect(Await kind) { _await = kind; @@ -748,12 +765,21 @@ internal sealed class LootEditorFace : IImGuiPanel string addLabel = PhosphorIcons.Plus + " Add rule"; float addW = ButtonWidth(addLabel) + 6; bool canAdd = !s.ReadOnly && s.Path.Length > 0; + // The same attribute checklist as the Inventory panel's filter (2026-11-07): tick what the items + // must have, pick the action; "Start empty" in the popup is the old empty rule to edit by hand. + bool canChecklist = canAdd && !s.Dirty; if (Button("##add", addLabel, p, new Vector2(addW, h), canAdd ? Green : Mute, canAdd ? StartBg : BtnFill, canAdd)) { - LootEditCommands.Simple("add", -1); - Expect(Await.OpenFocus); + if (canChecklist) + { + _lootAdd.EmptyRule = AddEmptyRule; + _lootAdd.Open(0, string.Empty, toOpenProfile: true, LootAddMode.AddRule, blank: true); + } + else AddEmptyRule(); // unsaved edits: the checklist saves, so add the empty rule as before } - ImGuiNET.ImGui.SetItemTooltip("Add a rule at the end and edit it"); + ImGuiNET.ImGui.SetItemTooltip(canChecklist + ? "A new rule from the attribute checklist (the same as Filter inventory): tick what the items must have, pick the action" + : "Add an empty rule at the end and edit it (save your edits first to use the checklist)"); string itemLabel = PhosphorIcons.Plus + " Add selected item"; float itemW = ButtonWidth(itemLabel) + 6; bool canItem = s.Path.Length > 0 && !s.Dirty && (!s.ReadOnly || s.Format == "json"); @@ -827,6 +853,26 @@ internal sealed class LootEditorFace : IImGuiPanel _keepField.Shown = null; } + /// <summary>The checklist edits saved rules of a .utl profile: nothing unapplied here, nothing unsaved.</summary> + private bool CanChecklist(LootEditStateDto s, bool dirty) => + !s.ReadOnly && !dirty && !s.Dirty && _editIndex >= 0 && !string.Equals(s.Format, "json", StringComparison.OrdinalIgnoreCase); + + private string ChecklistWhyNot(LootEditStateDto s, bool dirty) => + s.ReadOnly ? "This profile is read-only here" + : string.Equals(s.Format, "json", StringComparison.OrdinalIgnoreCase) ? "Native-format rules are edited here, by hand" + : dirty ? "Apply or Revert this rule's changes first (the checklist saves the file)" + : s.Dirty ? "Save the profile first (the checklist saves the file)" + : "Pick a rule"; + + private void OpenChecklist() + { + if (_state == null || _editIndex < 0) return; + string name = _expect ?? _edit?.Name ?? string.Empty; + _lootAdd.EmptyRule = null; + _lootAdd.RawEditor = null; // already in the rule view + _lootAdd.OpenEdit(_editIndex, name); + } + private void Apply() { if (_edit == null || _state == null || _state.ReadOnly) return; @@ -872,6 +918,16 @@ internal sealed class LootEditorFace : IImGuiPanel if (Button("##apply", applyL, new Vector2(rx, p.Y), new Vector2(applyW, h), dirty ? Green : Mute, dirty ? StartBg : BtnFill, dirty && !ro)) Apply(); ImGuiNET.ImGui.SetItemTooltip("Put these changes in the profile (then Save writes the file)"); + // The same checklist as Add rule and Filter inventory (2026-11-07). + string checkL = PhosphorIcons.ListChecks + " Edit with checklist"; + float checkW = ButtonWidth(checkL) + 6; + rx -= checkW + 8; + bool canCheck = CanChecklist(s, dirty); + if (Button("##checklist", checkL, new Vector2(rx, p.Y), new Vector2(checkW, h), canCheck ? Teal : Mute, BtnFill, canCheck)) + OpenChecklist(); + ImGuiNET.ImGui.SetItemTooltip(canCheck + ? "Edit this rule's conditions with the attribute checklist (as Add rule and Filter inventory); what it can't show is kept as written" + : ChecklistWhyNot(s, dirty)); NextLine(p, h + 4); Separator(w); @@ -972,9 +1028,17 @@ internal sealed class LootEditorFace : IImGuiPanel ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); p = ImGuiNET.ImGui.GetCursorScreenPos(); + // Add condition: the checklist (2026-11-07), as Add rule; "Raw condition" picks a node type by hand. string addL = PhosphorIcons.Plus + " Add condition"; - if (Button("##add_cond", addL, p, new Vector2(ButtonWidth(addL) + 6, h), ro ? Mute : Teal, BtnFill, !ro && _nodeItems.Length > 0)) - _picker.Open(new Vector2(p.X, p.Y + h), _nodeItems, -1, i => + bool canCheck = CanChecklist(_state!, EditDirty); + float addW = ButtonWidth(addL) + 6; + if (Button("##add_cond", addL, p, new Vector2(addW, h), canCheck ? Teal : Mute, BtnFill, canCheck)) + OpenChecklist(); + ImGuiNET.ImGui.SetItemTooltip(canCheck ? "Tick more of the checklist's attributes for this rule" : ChecklistWhyNot(_state!, EditDirty)); + string rawL = PhosphorIcons.PencilSimple + " Raw condition"; + Vector2 rp = new(p.X + addW + 6, p.Y); + if (Button("##add_raw", rawL, rp, new Vector2(ButtonWidth(rawL) + 6, h), ro ? Mute : Text, BtnFill, !ro && _nodeItems.Length > 0)) + _picker.Open(new Vector2(rp.X, rp.Y + h), _nodeItems, -1, i => { if (_edit == null) return; // Before any DisabledRule node, so the rule's file layout stays VTank's. @@ -1192,7 +1256,7 @@ internal sealed class LootEditorFace : IImGuiPanel if (c.Lines.Count == 0) return; string raw = c.Lines[0].Trim(); int sel = TryWhole(raw, out int value) ? Array.IndexOf(table.Ids, value) : -1; - string shown = sel >= 0 ? table.Items[sel] : "value " + raw; + string shown = sel >= 0 ? table.Items[sel] : raw; if (PickerButton("##valpick", shown, p, w, h, ro)) { LootEditConditionDto target = c; diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs index fc3262f..2896f2b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -580,7 +580,7 @@ internal sealed class LuaFace : IImGuiPanel ImGuiNET.ImGui.PushTextWrapPos(0); string text = _data?.Console ?? string.Empty; if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text); - if (_note.Length > 0) SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), "[panel] " + _note); + if (_note.Length > 0) SafeImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index 143b3f6..559d523 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -524,7 +524,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.SetCursorScreenPos(p); DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), width, height); if (c.Condition == MetaRuleEdit.NoKillsWithinMinutes) - SafeImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData)); + SafeImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData)); // typed text may hold %: SafeImGui escapes it } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height)); ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); @@ -875,7 +875,7 @@ internal sealed partial class MetaFace private static void Note(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs index 4f2024b..ce0f500 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -468,7 +468,7 @@ internal sealed partial class MetaFace dl.AddRect(a, b, Teal, 8); dl.AddText(small, small.FontSize, new Vector2(a.X + 5, a.Y + 2), Teal, tag); if (_stateClock.Known && ImGuiNET.ImGui.IsMouseHoveringRect(a, b)) - ImGuiNET.ImGui.SetTooltip("The meta's current state, and how long it has been in it (what \"In state >= N s\" rules count)."); + SafeImGui.SetTooltip("The meta's current state, and how long it has been in it (what \"In state >= N s\" rules count)."); rx = a.X - 6; // The Watchdog, while one is set: it sends the meta to its state when the time runs out diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index a84d256..21365cb 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -183,9 +183,9 @@ internal sealed partial class MetaFace : sc.LastPollMs == 0 ? "Waiting for the first /myquests." : $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago."; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - SafeImGui.TextColored(RynthTheme.VecOf(sc.ServerDisabled ? RynthTheme.Highlight : RynthTheme.MuteAlt), Fit(poll, w)); + SafeImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w)); if (sc.LastSwitch.Length > 0) - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w)); ImGuiNET.ImGui.PopFont(); } @@ -367,7 +367,7 @@ internal sealed partial class MetaFace ScheduleRuleDto r = _schedRule; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); ImGuiNET.ImGui.PopFont(); FieldLabel("When:"); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index f6fcc43..87fcb31 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -1039,7 +1039,7 @@ internal sealed partial class MetaFace : IImGuiPanel private static void FieldLabel(string text) { ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); - SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); } private static void Separator(float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs index b005d06..b88213f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs @@ -64,7 +64,7 @@ internal sealed partial class MiniRemoteFace private static bool RailShown => PanelColumnStore.Get(RailKey, 1f) >= 0.5f; - // ── Requests (commands; render thread) ────────────────────────────── + // ── Requests (commands; render thread) ────────────────────────────── /// <summary>Shows section <paramref name="sectionId"/> ("remote" = the remote) on the next draw.</summary> public static void RequestSection(string sectionId) @@ -153,7 +153,7 @@ internal sealed partial class MiniRemoteFace if (PanelColumnStore.Get(SectionKey, -1f) != index) PanelColumnStore.Set(SectionKey, index); } - // ── Rail ──────────────────────────────────────────────────────────── + // ── Rail ──────────────────────────────────────────────────────────── /// <summary>Draws the rail at the body's left; returns the width it takes (with its gap).</summary> private float DrawRail(SectionRegistry.Snapshot snap, Vector2 origin, Vector2 size) @@ -237,7 +237,7 @@ internal sealed partial class MiniRemoteFace _ => "nothing installed adds to it on this world.", }; - // ── Section body ──────────────────────────────────────────────────── + // ── Section body ──────────────────────────────────────────────────── private void DrawSection(SectionRegistry.Snapshot snap, float w, Vector2 origin, Vector2 size) { @@ -460,7 +460,7 @@ internal sealed partial class MiniRemoteFace return result == PluginManager.EmbedDrawn ? want : Vector2.Zero; } - // ── Session Stats overview ────────────────────────────────────────── + // ── Session Stats overview ────────────────────────────────────────── /// <summary> /// The Session Stats section's stand-in, shown only while no plugin fills the section (RynthAi @@ -494,7 +494,7 @@ internal sealed partial class MiniRemoteFace } } - // ── Menu ──────────────────────────────────────────────────────────── + // ── Menu ──────────────────────────────────────────────────────────── /// <summary>The menu's section half: every section, the active servers' items, the rail switch.</summary> private void DrawSectionsMenuItems() @@ -506,6 +506,20 @@ internal sealed partial class MiniRemoteFace SelectSection(v.Id); ServerMenus.DrawImGuiMenu(separatorFirst: true); ImGuiNET.ImGui.Separator(); + // Dock / undock: same as the host title ↗/↙, and as /rc miniremote undock|dock. + if (PanelRouter.CanPopOut) + { + bool popped = ImGuiPanelHost.IsPopped(Title) || ImGuiPopOuts.InPopOutFrame; + if (ImGuiNET.ImGui.MenuItem(popped ? "Dock Mini Remote" : "Undock Mini Remote", + popped ? "/rc miniremote dock" : "/rc miniremote undock", false)) + { + if (popped) DockOrOpen(); + else OpenUndocked(); + } + SafeImGui.SetItemTooltip(popped + ? "Dock back into the game window." + : "Pop out into a floating window so Options / sections have more room."); + } bool rail = RailShown; if (ImGuiNET.ImGui.MenuItem("Show the sections rail", "", rail)) { diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs index d9a2679..81da08a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -46,6 +46,7 @@ using System.Numerics; using ImGuiNET; using RynthCore.Engine.Compatibility; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI; using RynthCore.Engine.UI.Data; using RynthCore.Engine.UI.ScriptWindows; using RynthCore.Engine.UI.Sections; @@ -65,6 +66,35 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel ItemHudStore.EnsureLoadQueued(); } + /// <summary> + /// Opens on Remote and pops out into its own window (room for Options / sections). + /// Safe if already open or already undocked. AC / chat thread. + /// </summary> + public static void OpenUndocked() + { + RequestSection(SectionCatalog.RemoteId); + if (!ImGuiPanelHost.IsOpen(Title)) + ImGuiPanelHost.Open(Title); + // Open queues into _open immediately, so PopOut is allowed in the same turn. + if (PanelRouter.CanPopOut && !ImGuiPanelHost.IsPopped(Title)) + ImGuiPanelHost.PopOut(Title); + } + + /// <summary> + /// Docks a popped-out Mini Remote back into the client, or opens it docked when closed. + /// AC / chat thread. + /// </summary> + public static void DockOrOpen() + { + if (ImGuiPanelHost.IsPopped(Title)) + ImGuiPanelHost.Redock(Title); + else if (!ImGuiPanelHost.IsOpen(Title)) + { + RequestSection(SectionCatalog.RemoteId); + ImGuiPanelHost.Open(Title); + } + } + /// <summary> /// The RynthAi surface for this window (NUL-terminated for the export): "miniremote-remote" /// (the remote alone: its tabs are sections here) from a RynthAi that publishes sections @@ -186,7 +216,7 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel FitGrid(data, w, haveH); } - // ── RynthAi's Mini Remote ─────────────────────────────────────────── + // ── RynthAi's Mini Remote ─────────────────────────────────────────── /// <summary> /// Lets RynthAi draw its Mini Remote here. True when it did (or is mid-layout after @@ -242,10 +272,10 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel if (result == PluginManager.EmbedFailed) _embedOff = true; } - // ── Window fit ────────────────────────────────────────────────────── + // ── Window fit ────────────────────────────────────────────────────── /// <summary> - /// Sizes the window so the body area (<paramref name="haveW"/> × <paramref name="haveH"/> + /// Sizes the window so the body area (<paramref name="haveW"/> × <paramref name="haveH"/> /// now) becomes <paramref name="wantPx"/>; never taller than the screen. Docked only: /// popped out the OS window keeps its size, as other faces do (RynthNavArrowFace). /// </summary> @@ -282,7 +312,7 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel FitWindow(body, w, haveH); } - // ── Engine grid ───────────────────────────────────────────────────── + // ── Engine grid ───────────────────────────────────────────────────── private void Resolve(ItemHudCharacter data, HudItem[] items) { @@ -418,7 +448,7 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel if (!ItemHudStore.Update(d => d.WithSlot(i, new RemoteSlot(itemId, name)), out string why)) ShowMessage(why, Amber); } - // ── Status ────────────────────────────────────────────────────────── + // ── Status ────────────────────────────────────────────────────────── private void ShowMessage(string text, uint color) { @@ -450,7 +480,7 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel private static float BodyGripRoom() => ImGuiPanelHost.BodyGripReserve; - // ── Right-click menu ──────────────────────────────────────────────── + // ── Right-click menu ──────────────────────────────────────────────── /// <summary> /// The right-click menu: a slot's options (the engine grid), then the sections, the active diff --git a/src/RynthCore.Engine/ImGui/Panels/OracleCompanionStrip.cs b/src/RynthCore.Engine/ImGui/Panels/OracleCompanionStrip.cs new file mode 100644 index 0000000..ed253ef --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/OracleCompanionStrip.cs @@ -0,0 +1,109 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/OracleCompanionStrip.cs +// Header-style toggles drawn at the top of RynthOracle's main window (same +// idea as RynthNav's Radar / Sense / Map buttons). Vision, Tracker and the +// Infinite Leaftide (server plugin) leaf left the top bar 2026-10-16; they +// still open through PanelRouter / OverlayHost / /rc ui — only the bar icon +// moved here. ScriptWindowFace calls Draw() before replaying Oracle's tabs. +// ============================================================================ + +using System; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// <summary>Companion toggles for panels that used to live on the top bar, now under Oracle.</summary> +internal static class OracleCompanionStrip +{ + /// <summary>ILT ImGui faces (RynthILT): one leaf stands for them, like the old bar button.</summary> + private static readonly string[] IltPanels = { BountiesFace.Title, GuardianFace.Title }; + + /// <summary> + /// Draws Vision / Tracker / ILT toggles in the Oracle body (above the script tab strip). + /// No-op when none of those faces are registered. AC thread. + /// </summary> + public static void Draw() + { + bool any = false; + if (ImGuiPanelHost.HasFace(VisionFace.Title)) + { + Toggle(VisionFace.Title, PhosphorIcons.Eye + " Vision", + "Vision: terrain overlays, nameplates and combat text (RynthVision)"); + any = true; + } + if (ImGuiPanelHost.HasFace("Tracker")) + { + if (any) ImGui.SameLine(); + Toggle("Tracker", PhosphorIcons.ChartLineUp + " Tracker", + "Tracker: session stats HUD (RynthTracker)"); + any = true; + } + + int ilt = IltPanelCount(); + if (ilt > 0) + { + if (any) ImGui.SameLine(); + string? only = ilt == 1 ? FirstIltPanel() : null; + bool open = only != null && ImGuiPanelHost.IsOpen(only); + if (ImGui.Button((open ? PhosphorIcons.Leaf + " ILT*" : PhosphorIcons.Leaf + " ILT") + "##oracle_ilt")) + { + if (only != null) PanelRouter.Toggle(only); + else ImGui.OpenPopup("##oracle_ilt_menu"); + } + ImGui.SetItemTooltip(only != null + ? "Infinite Leaftide: " + only + : "Infinite Leaftide (Bounties, Guardian) — server plugin panels"); + any = true; + IltMenu(); + } + + if (any) ImGui.Separator(); + } + + private static void Toggle(string title, string label, string tip) + { + bool open = ImGuiPanelHost.IsOpen(title); + if (open) ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.Argb(0xFF1A2E38)); + if (ImGui.Button(label + "##oracle_" + title)) + PanelRouter.Toggle(title); + if (open) ImGui.PopStyleColor(); + ImGui.SetItemTooltip(tip); + } + + private static int IltPanelCount() + { + int n = 0; + foreach (string title in IltPanels) + if (ImGuiPanelHost.HasFace(title)) n++; + return n > 0 && IltInfo.IsIlt && IltInfo.PluginLoaded ? n : 0; + } + + private static string? FirstIltPanel() + { + foreach (string title in IltPanels) + if (ImGuiPanelHost.HasFace(title)) return title; + return null; + } + + private static void IltMenu() + { + if (!ImGui.BeginPopup("##oracle_ilt_menu")) return; + try + { + ImGui.TextDisabled("Infinite Leaftide"); + foreach (string title in IltPanels) + { + if (!ImGuiPanelHost.HasFace(title)) continue; + bool open = ImGuiPanelHost.IsOpen(title); + if (ImGui.MenuItem(title, "", open)) + PanelRouter.Toggle(title); + } + } + finally + { + ImGui.EndPopup(); + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index d116623..9e28420 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -34,7 +34,8 @@ internal static class P1Faces // Registered here so engine init needs no new line in EntryPoint; ImGuiBar gives // it a bar button (ImGuiOnlyPanels). SkillsFace.Register(); - // Sense (watch list of names, anywhere the client knows): ImGui only, like Skills. + // Sense (watch list of names, anywhere the client knows): ImGui only; bar icon + // lives under RynthNav (header toggle + /rc sense) since 2026-10-16. SenseFace.Register(); // Item Count and Mini Remote (items by name with their carried count; a grid of // items to use): ImGui only, saved per character in item_huds.txt. diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index 7b3e19a..39616ba 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -207,7 +207,7 @@ internal sealed partial class RynthAiFace } /// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (its drawer tab).</summary> - private sealed class RemoteDrawer : RynthAiDrawer + private sealed class RemoteDrawer : DashboardDrawer { /// <summary>The plugin surface name, NUL-terminated for the export.</summary> private static ReadOnlySpan<byte> Surface => "miniremote\0"u8; @@ -227,7 +227,7 @@ internal sealed partial class RynthAiFace public override string TabTooltip(bool right) => "Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" + "Its Options button picks the sections. RynthILT's ILT tabs are in the Mini Remote window (Char, or the bar button).\n" + - "Click to slide it out."; + (right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out."); public override float Width(float k) => Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k; diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 5b350ac..890c5b2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -1043,6 +1043,13 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiCommands.ApplyRemoteCommand("hub", section.Length > 0 ? "tab " + section : "tab"); } + /// <summary>Opens Mini Remote undocked (floating) on the remote so Options has room.</summary> + private static void ShowMiniRemoteUndocked() + { + MiniRemoteFace.OpenUndocked(); + RynthAiCommands.ApplyRemoteCommand("hub", "tab"); + } + /// <summary> /// RynthOracle's Character tab ("/ro character"), or the Mini Remote's Session Stats section /// when RynthOracle isn't loaded. Every generic "Character" link goes here (Leaftide's Charms @@ -1118,8 +1125,15 @@ internal sealed partial class RynthAiFace : IImGuiPanel SafeImGui.SetItemTooltip(hasOracle ? "RynthOracle's Character tab: level, XP and session rates. Infinite Leaftide's charms and banking are the Mini Remote's ILT tabs (Server, below)." : "RynthOracle's Character tab (RynthOracle isn't loaded)."); - if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title))) + if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title) && !ImGuiPanelHost.IsPopped(MiniRemoteFace.Title))) ShowMiniRemoteTab(""); + if (PanelRouter.CanPopOut) + { + if (ImGuiNET.ImGui.MenuItem("Mini Remote (undocked)", "/rc miniremote undock", + ImGuiPanelHost.IsOpen(MiniRemoteFace.Title) && ImGuiPanelHost.IsPopped(MiniRemoteFace.Title))) + ShowMiniRemoteUndocked(); + SafeImGui.SetItemTooltip("Open Mini Remote in its own floating window (room for Options / sections). Dock back from the title ↙, Float/Dock, or Options."); + } if (ImGuiNET.ImGui.MenuItem("Spells", "/rc spells")) RynthAiCommands.ApplyRemoteCommand("spells", "toggle"); ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: the spell catalog and buff profiles."); @@ -1157,6 +1171,19 @@ internal sealed partial class RynthAiFace : IImGuiPanel ? "Every character's saved packs and storage (RynthInventory)." : "Global Inventory (RynthInventory isn't loaded)."); PanelMenuItem("Characters", "/rc characters"); // RynthNet's window (a plugin window since 2026-10-21) + // Radar / Sense live under RynthNav (header toggles); keep Char menu linkage. + PanelMenuItem(RadarFace.Title, "/rc radar"); + PanelMenuItem(SenseFace.Title, "/rc sense"); + PanelMenuItem(RynthNavFace.Title, "/rc ui open RynthNav"); + // Vision / Tracker / ILT live under Oracle (companion strip); keep Char menu linkage. + if (ImGuiPanelHost.HasFace(VisionFace.Title)) + PanelMenuItem(VisionFace.Title, "/rc ui open Vision"); + if (ImGuiPanelHost.HasFace("Tracker")) + PanelMenuItem("Tracker", "/rc ui open Tracker"); + if (ImGuiPanelHost.HasFace(BountiesFace.Title)) + PanelMenuItem(BountiesFace.Title, "/rc ui open " + BountiesFace.Title); + if (ImGuiPanelHost.HasFace(GuardianFace.Title)) + PanelMenuItem(GuardianFace.Title, "/rc ui open " + GuardianFace.Title); UI.ServerMenus.DrawImGuiMenu(separatorFirst: true); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs index 46bf3ed..b9713ee 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -66,12 +66,46 @@ internal sealed class RynthNavArrowFace : IImGuiPanel private int _scrolledTo = -1; private float _requestedH = -1; + // Auto-close: once the arrow had a target and it went away (you arrived, or it was + // cleared elsewhere), the overlay says so for AutoCloseMs and then hides itself. Opened + // empty (to type coordinates), it stays until closed. + private const long AutoCloseMs = 4000; + private bool _hadTarget; + private long _targetGoneMs; + private string _lastTarget = ""; + public void OnShown() { UiSources.RynthNav.Subscribe(); UiSources.RynthNav.RequestRefresh(); _showRoute = false; _requestedH = -1; + _hadTarget = false; + _targetGoneMs = 0; + } + + /// <summary>Clears RynthNav's arrow (and stops a walk to it), then hides the overlay.</summary> + private static void ClearTarget(RynthNavStatus? st) + { + if (st?.Goto == true) RynthNavCommands.Move(5); // stop walking there too + RynthNavCommands.Command("arrow clear"); + ImGuiPanelHost.Close(Title); + } + + /// <summary>Tracks the target going away; true when the overlay should hide now.</summary> + private bool AutoCloseDue() + { + if (_read.HasTarget) + { + _hadTarget = true; + _targetGoneMs = 0; + _lastTarget = _read.Line1; + return false; + } + if (!_hadTarget) return false; + long now = Environment.TickCount64; + if (_targetGoneMs == 0) _targetGoneMs = now; + return now - _targetGoneMs >= AutoCloseMs; } public void OnHidden() => UiSources.RynthNav.Unsubscribe(); @@ -84,6 +118,13 @@ internal sealed class RynthNavArrowFace : IImGuiPanel if (size.X < 40 || size.Y < 30) return; RynthNavStatus? st = UiSources.RynthNav.Current?.Value; _read.Update(st); + if (AutoCloseDue()) + { + _hadTarget = false; + ImGuiPanelHost.Close(Title); + return; + } + bool justDone = !_read.HasTarget && _hadTarget; // arrived or cleared: closing shortly ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); const float pad = 5, gap = 3; @@ -111,21 +152,30 @@ internal sealed class RynthNavArrowFace : IImGuiPanel // Name, then distance and compass point (the route step on the right of it). float tx = origin.X + pad + d + 8, right = origin.X + size.X - pad; const float sb = 14; // the corner buttons: small, for a small panel - dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 2 * sb - 4, origin.Y + size.Y), true); - dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + pad + 2), Teal, _read.Line1); + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 3 * sb - 6, origin.Y + size.Y), true); + dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + pad + 2), justDone ? Green : Teal, + justDone ? "Done: " + _lastTarget : _read.Line1); dl.PopClipRect(); string step = _read.HasTarget && st?.Arrow is { Steps: > 1 } sa ? $"{sa.Step}/{sa.Steps}" : ""; float stepW = step.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, step).X + 4 : 0; float line2Y = origin.Y + pad + 2 + bold.FontSize + 4; dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - stepW, origin.Y + size.Y), true); if (_read.HasTarget) dl.AddText(f10, f10.FontSize, new Vector2(tx, line2Y), Text, _read.Line2); + else if (justDone) dl.AddText(f9, f9.FontSize, new Vector2(tx, line2Y + 1), Mute, "arrived or cleared - closing"); else dl.AddText(f9, f9.FontSize, new Vector2(tx, line2Y + 1), Mute, _read.Line3.Length > 0 ? "Type coordinates or a place below" : ""); dl.PopClipRect(); if (step.Length > 0) dl.AddText(f9, f9.FontSize, new Vector2(right - stepW + 4, line2Y + 1), Mute, step); - // Top-right corner: pop out, hide (small and flat). + // Top-right corner: clear, pop out, hide (small and flat). var closePos = new Vector2(origin.X + size.X - 3 - sb, origin.Y + 3); var popPos = closePos - new Vector2(sb + 2, 0); + var clearPos = popPos - new Vector2(sb + 2, 0); + if (IconButton("##rna_clear", PhosphorIcons.Eraser, clearPos, new Vector2(sb, sb), _read.HasTarget ? Amber : Done, Glass, + enabled: _read.HasTarget, font: UiFont.Ui9) && _read.HasTarget) + ClearTarget(st); + SafeImGui.SetItemTooltip(st?.Goto == true + ? "Clear the arrow and stop walking there (/rnav arrow clear)" + : "Clear the arrow (/rnav arrow clear) and hide this"); if (PanelRouter.CanPopOut) { if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index 356ef0d..8556f02 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -23,6 +23,9 @@ // arrow overlay (RynthNavArrowFace), Go / Stop / Clear / favorite, // set it to a place or coordinates, the arrival radius. // +// Header also toggles the World Map, Mini Map, Radar and Sense (Radar/Sense +// left the top bar 2026-10-16; same PanelRouter path as /rc radar|/rc sense). +// // Our take on GoArrow's arrow, atlas and routes (Digero 2006, Virindi 2011, // MIT). RynthNav (the plugin) owns the arrow, favorites, recent, routing and // recalls; this face shows its status and sends it /rnav commands @@ -87,7 +90,7 @@ internal sealed class RynthNavFace : IImGuiPanel // Go tab: the picked destination (a row of the list), what the commands get for it, its line. private AtlasRow? _pick; private string _pickArg = "", _pickCoord = "", _pickLine = "", _typedLine = "", _typedCoord = ""; - private bool _recallsOpen, _infoOpen; + private bool _recallsOpen, _infoOpen, _learnOpen; public void OnShown() { @@ -127,16 +130,45 @@ internal sealed class RynthNavFace : IImGuiPanel ImFontPtr big = ImGuiFonts.Get(UiFont.UiBold14); dl.AddText(big, big.FontSize, p + new Vector2(16, 1), Teal, "RynthNav"); float tw = ImGuiNET.ImGui.CalcTextSize("RynthNav").X * big.FontSize / ImGuiNET.ImGui.GetFontSize(); - dl.AddText(p + new Vector2(24 + tw, 6), Mute, "go · atlas · arrow"); + dl.AddText(p + new Vector2(24 + tw, 6), Mute, "go · atlas · arrow · radar · sense"); + // Right-side toggles: Sense, Radar (left of Mini), Mini, Map — same open path as the old bar. + float hx = p.X + w; if (ImGuiPanelHost.HasFace(WorldMapFace.Title)) { - bool mapOpen = ImGuiPanelHost.IsOpen(WorldMapFace.Title), miniOpen = ImGuiPanelHost.IsOpen(MiniMapFace.Title); - if (Button("##rnav_worldmap", PhosphorIcons.GlobeHemisphereWest + " Map", new Vector2(p.X + w - 62, p.Y - 1), new Vector2(62, 22), + bool mapOpen = ImGuiPanelHost.IsOpen(WorldMapFace.Title); + hx -= 62; + if (Button("##rnav_worldmap", PhosphorIcons.GlobeHemisphereWest + " Map", new Vector2(hx, p.Y - 1), new Vector2(62, 22), mapOpen ? Teal : Text, mapOpen ? Selected : BtnFill, border: mapOpen ? Teal : 0)) UI.PanelRouter.Toggle(WorldMapFace.Title); - if (Button("##rnav_minimap", "Mini", new Vector2(p.X + w - 62 - 4 - 40, p.Y - 1), new Vector2(40, 22), + hx -= 4; + } + if (ImGuiPanelHost.HasFace(MiniMapFace.Title)) + { + bool miniOpen = ImGuiPanelHost.IsOpen(MiniMapFace.Title); + hx -= 40; + if (Button("##rnav_minimap", "Mini", new Vector2(hx, p.Y - 1), new Vector2(40, 22), miniOpen ? Teal : Text, miniOpen ? Selected : BtnFill, border: miniOpen ? Teal : 0)) UI.PanelRouter.Toggle(MiniMapFace.Title); + hx -= 4; + } + if (ImGuiPanelHost.HasFace(RadarFace.Title)) + { + bool radarOpen = ImGuiPanelHost.IsOpen(RadarFace.Title); + hx -= 58; + if (Button("##rnav_radar", PhosphorIcons.Compass + " Radar", new Vector2(hx, p.Y - 1), new Vector2(58, 22), + radarOpen ? Teal : Text, radarOpen ? Selected : BtnFill, border: radarOpen ? Teal : 0)) + UI.PanelRouter.Toggle(RadarFace.Title); + ImGuiNET.ImGui.SetItemTooltip("Radar (/rc radar): nearby objects, walls and floor overlay"); + hx -= 4; + } + if (ImGuiPanelHost.HasFace(SenseFace.Title)) + { + bool senseOpen = ImGuiPanelHost.IsOpen(SenseFace.Title); + hx -= 58; + if (Button("##rnav_sense", PhosphorIcons.Binoculars + " Sense", new Vector2(hx, p.Y - 1), new Vector2(58, 22), + senseOpen ? Teal : Text, senseOpen ? Selected : BtnFill, border: senseOpen ? Teal : 0)) + UI.PanelRouter.Toggle(SenseFace.Title); + ImGuiNET.ImGui.SetItemTooltip("Sense (/rc sense): watch list of names anywhere the client knows"); } NextLine(p, 22); DrawTabs(w); @@ -354,6 +386,7 @@ internal sealed class RynthNavFace : IImGuiPanel DrawRouteView(st, cw); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); if (Fold("##go_fold_recalls", _recallsOpen ? RecallsOpenLabel : RecallsShutLabel, ref _recallsOpen, cw)) DrawRecalls(st, cw); + if (st?.HasLearn == true && Fold("##go_fold_learn", _learnOpen || st.LearnOn ? LearnOpenLabel : LearnShutLabel, ref _learnOpen, cw)) DrawLearn(st, cw); if (Fold("##go_fold_info", _infoOpen ? InfoOpenLabel : InfoShutLabel, ref _infoOpen, cw)) DrawInfo(st, cw); } ImGuiNET.ImGui.EndChild(); @@ -464,6 +497,8 @@ internal sealed class RynthNavFace : IImGuiPanel private const string GoLabel = PhosphorIcons.Play + " Go"; private const string RecallsOpenLabel = PhosphorIcons.CaretDown + " RECALLS AND PORTAL TIES", RecallsShutLabel = PhosphorIcons.CaretRight + " RECALLS AND PORTAL TIES", + LearnOpenLabel = PhosphorIcons.CaretDown + " CUSTOM PORTALS (THIS SERVER)", + LearnShutLabel = PhosphorIcons.CaretRight + " CUSTOM PORTALS (THIS SERVER)", InfoOpenLabel = PhosphorIcons.CaretDown + " INFO, LOAD / TEST, MOVEMENT", InfoShutLabel = PhosphorIcons.CaretRight + " INFO, LOAD / TEST, MOVEMENT"; @@ -585,6 +620,70 @@ internal sealed class RynthNavFace : IImGuiPanel ImGuiNET.ImGui.Unindent(4); } + // ── Custom portals section (RynthNav "learn") ───────────────────────── + + /// <summary> + /// This server's own portals: the counts, Scan (write down the portals around you), Learn (go + /// and try every portal within the range, learn each landing, come back, repeat; Stop ends it) + /// and the range with - / +. + /// </summary> + private static void DrawLearn(RynthNavStatus st, float cw) + { + ImGuiNET.ImGui.Indent(4); + float iw = cw - 4; + Wrapped(st.LearnCounts, Text, iw); + + // Range: - [ 200 yd ] + + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + double r = st.LearnRange, step = r >= 500 ? 100 : r >= 100 ? 25 : 10; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + DrawSmallLabel(p + new Vector2(0, 5), Mute, "SEARCH RANGE"); + ImGuiNET.ImGui.PopFont(); + float x = p.X + 92; + if (Button("##learn_minus", "-", new Vector2(x, p.Y), new Vector2(24, 22), Text, BtnFill, enabled: r > st.LearnMin)) + RynthNavCommands.Command("portals learn range " + Math.Max(st.LearnMin, r - step).ToString("0", System.Globalization.CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("A smaller range: fewer portals, closer to where learning starts"); + string rt = r.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + " yd"; + float tw = ImGuiNET.ImGui.CalcTextSize(rt).X; + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(x + 28 + (64 - tw) * 0.5f, p.Y + 3), Teal, rt); + if (Button("##learn_plus", "+", new Vector2(x + 96, p.Y), new Vector2(24, 22), Text, BtnFill, enabled: r < st.LearnMax)) + RynthNavCommands.Command("portals learn range " + Math.Min(st.LearnMax, r + step).ToString("0", System.Globalization.CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip($"A bigger range (up to {st.LearnMax:0} yd): more portals, longer runs"); + NextLine(p, 26); + + // Learn / Stop, Scan + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = (iw - 4) * 0.5f; + if (!st.LearnOn) + { + if (Button("##learn_go", PhosphorIcons.Play + " Learn portals", p, new Vector2(bw, 24), RunGreen, BtnFill, border: RunGreen)) + RynthNavCommands.Command("portals learn"); + ImGuiNET.ImGui.SetItemTooltip("From where you stand: walk into every portal within the range it hasn't mapped,\n" + + "learn where each one lands, come back here by a route (portals and recalls), and go on\n" + + "until all have been tried. Stop (or any movement key) ends it."); + } + else + { + if (Button("##learn_stop", PhosphorIcons.Stop + " Stop learning", p, new Vector2(bw, 24), Amber, BtnFill, border: Amber)) + RynthNavCommands.Command("portals learn stop"); + ImGuiNET.ImGui.SetItemTooltip("Stop learning portals (the walk stops too)"); + } + if (Button("##learn_scan", PhosphorIcons.MagnifyingGlass + " Scan here", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 24), Text, BtnFill, + enabled: !st.LearnOn)) + RynthNavCommands.Command("portals scan " + r.ToString("0", System.Globalization.CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("Write down the portals around you within the range (their landing is learned when one is taken)"); + NextLine(p, 28); + + if (st.LearnLine.Length > 0) Wrapped(st.LearnLine, st.LearnOn ? Amber : Mute, iw); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Wrapped("Routes use these with \"Use portals and recalls\" on. A portal that lands in a dungeon is kept, not routed. /rnav portals list shows them.", Mute, iw); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.Unindent(4); + } + + private static void DrawSmallLabel(Vector2 at, uint color, string text) => ImGuiNET.ImGui.GetWindowDrawList().AddText(at, color, text); + // ── Info section ───────────────────────────────────────────────────── private void DrawInfo(RynthNavStatus? st, float cw) diff --git a/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs index c51f808..7b3444a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs @@ -66,6 +66,9 @@ internal sealed unsafe class ScriptWindowFace : IImGuiPanel { ScriptWindowMetrics.Refresh(); ReportGeometry(); + // Oracle: Vision / Tracker / ILT toggles above the script tabs (left the top bar). + if (OracleSkillsEmbed.IsOraclePanel(_window.PanelKey)) + OracleCompanionStrip.Draw(); ScriptWindowReplay.Draw(_window); // Oracle Skills / Attributes / Progress: after the script tab strip, draw the // engine SkillsFace body (raise/train/progression) into the remaining space. diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs index 0b074c2..5ef1020 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -1,12 +1,10 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs // The Skills panel's Progression tab, shown on ILT-like worlds only: -// - XP planner: exact XP for the next N raises of every attribute and vital, -// from the client's XP tables (raising stays on the Attributes & Vitals tab). -// - Attribute raiser: infinite attributes past the retail cap. RynthILT reads the -// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from -// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP -// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost. +// - Attributes: one section - client XP-table planner for retail ranks, plus (when the +// server supports infinite attributes) the ILT raiser to auto-raise past the retail +// cap with "/xp all" + "/attr" (UB Leaftide XP tab layout). RynthILT reads the +// server's costs and raises, by hand or on a timer from unassigned XP. // - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc / // Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game. // - Augmentations / Enlightenment: the ILT Hub's planners (RynthILT's since @@ -17,8 +15,10 @@ // ============================================================================ using System; +using RynthCore.Engine.Compatibility; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Engine.UI; @@ -100,15 +100,23 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); try { - DrawXpPlanner(w); + // Off Infinite Leaftide (2026-11-11, Silentkelpie: "progress should still show for all, but the progress top + // section should be hidden unless on leaftide"): the retail XP planner only - no infinite attributes, no + // augmentation / enlightenment planners and no word about them. + bool ilt = (info != null && info.Available) || IltInfo.IsIlt; + if (!ilt) + { + DrawRetailOnly(w); + return; + } + // One Attributes section: retail XP planner + (when supported) infinite-attr raiser. + DrawAttributes(info?.Attr, w); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); if (info == null || !info.Available) { Message("Augmentations and Enlightenment need RynthILT's ILT features on an ILT world.", w); return; } - DrawAttrRaiser(info.Attr, w); - ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); DrawAugPlanner(info.Aug, w); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); DrawEnlPlanner(info.Enl, w); @@ -120,15 +128,64 @@ internal sealed partial class SkillsFace } } - private void DrawXpPlanner(float w) + /// <summary>Off Infinite Leaftide: the retail XP planner, under its own heading.</summary> + private void DrawRetailOnly(float w) + { + Section("Attribute raises", w); + ImGuiNET.ImGui.Indent(8); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24); + try { DrawRetailXpPlanner(w); } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Unindent(8); + } + } + + /// <summary> + /// Single Attributes section: client XP-table costs up to the retail cap, and - when the + /// server supports infinite attributes - the controls to auto-raise past that cap. + /// </summary> + private void DrawAttributes(AttrRaiser? a, float w) + { + Section("Attributes", w); + ImGuiNET.ImGui.Indent(8); + float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; + ImGuiNET.ImGui.PushTextWrapPos(wrap); + try + { + DrawRetailXpPlanner(w); + + // Infinite-attributes segment: only when RynthILT reports the server can raise past retail. + bool infiniteOk = a != null && !a.Off; + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.Separator(); + Label(infiniteOk + ? "Infinite attributes (past retail max)" + : "Infinite attributes", + infiniteOk ? Amber : Mute); + if (a == null) + Label("Update RynthILT to raise attributes past the retail cap on this server.", Mute); + else if (a.Off) + Label(a.Reason.Length > 0 ? a.Reason : "This server does not support infinite attributes (/xp /attr).", Mute); + else + DrawInfiniteAttrControls(a, w); + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Unindent(8); + } + } + + /// <summary>Client XP tables for the next N retail raises (Attributes & Vitals tab still spends them).</summary> + private void DrawRetailXpPlanner(float w) { - Section("XP planner", w); if (_snap == null || _dat == null || _attributes.Count == 0) { Message("Waiting for your character's data...", w); return; } - ImGuiNET.ImGui.Indent(8); long have = _snap.UnassignedXp; Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute); ImGuiNET.ImGui.SetNextItemWidth(160); @@ -146,9 +203,7 @@ internal sealed partial class SkillsFace foreach (Row r in _vitals) PlannerRow(r, have); ImGuiNET.ImGui.EndTable(); } - Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab" - + (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim); - ImGuiNET.ImGui.Unindent(8); + Label("Exact costs from the client's XP tables (up to the retail cap). Raise those on the Attributes & Vitals tab.", Dim); } private void PlannerRow(Row r, long have) @@ -180,89 +235,76 @@ internal sealed partial class SkillsFace private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value) private int? _attrEveryEdit; // interval box being typed in - private void DrawAttrRaiser(AttrRaiser? a, float w) + /// <summary>Infinite-attribute raiser controls (only drawn when the server supports /xp + /attr past retail).</summary> + private void DrawInfiniteAttrControls(AttrRaiser a, float w) { - Section("Attribute raiser (infinite attributes)", w); - ImGuiNET.ImGui.Indent(8); - float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; - ImGuiNET.ImGui.PushTextWrapPos(wrap); - try + Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal); + if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (a.Running) { - if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; } - if (a.Off) { Label(a.Reason, Mute); return; } - - Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal); - if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - if (a.Running) - { - if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop"); - } - else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal)) - SendProg("attrrun"); - if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running)) - SendProg("attrcosts"); - ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all."); - if (a.Updated.Length > 0) - { - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4)); - Label("Last updated: " + a.Updated, Dim); - } - NextLine(p, 28); - if (a.Status.Length > 0) SafeImGui.TextWrapped(a.Status); - if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); - - ImGuiNET.ImGui.Separator(); - bool auto = a.Auto; - if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto)) - SendProg("attrauto " + (auto ? "on" : "off")); - ImGuiNET.ImGui.SameLine(); - // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send - // restarts the auto-raise timer). - int every = _attrEveryEdit ?? a.Every; - ImGuiNET.ImGui.SetNextItemWidth(90); - bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue); - bool everyActive = ImGuiNET.ImGui.IsItemActive(); - if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) - { - _attrEveryEdit = null; - if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture)); - } - else _attrEveryEdit = everyActive ? every : null; - if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim); - - int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1); - ImGuiNET.ImGui.SetNextItemWidth(260); - if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length)) - SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture)); - - // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an - // Enter on an untouched box can't round the reserve. - string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep; - string keep = _attrKeepEdit ?? shownKeep; - ImGuiNET.ImGui.SetNextItemWidth(140); - bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u, - ImGuiInputTextFlags.EnterReturnsTrue); - bool keepActive = ImGuiNET.ImGui.IsItemActive(); - if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) - { - _attrKeepEdit = null; - if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal)) - SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal)); - } - else _attrKeepEdit = keepActive ? keep : null; - ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes."); - - DrawAttrTable(a, w); - Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. " - + "+1 / +10 raise by hand (red = not enough unassigned XP). " - + "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim); + if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop"); } - finally + else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal)) + SendProg("attrrun"); + if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running)) + SendProg("attrcosts"); + ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all."); + if (a.Updated.Length > 0) { - ImGuiNET.ImGui.PopTextWrapPos(); - ImGuiNET.ImGui.Unindent(8); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4)); + Label("Last updated: " + a.Updated, Dim); } + NextLine(p, 28); + if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status); + if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); + + ImGuiNET.ImGui.Separator(); + bool auto = a.Auto; + if (ImGuiNET.ImGui.Checkbox("Auto-raise past retail max##attr_auto", ref auto)) + SendProg("attrauto " + (auto ? "on" : "off")); + ImGuiNET.ImGui.SetItemTooltip("Spends unassigned XP with /attr past the retail attribute cap (server costs from /xp all)."); + ImGuiNET.ImGui.SameLine(); + // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send + // restarts the auto-raise timer). + int every = _attrEveryEdit ?? a.Every; + ImGuiNET.ImGui.SetNextItemWidth(90); + bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue); + bool everyActive = ImGuiNET.ImGui.IsItemActive(); + if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrEveryEdit = null; + if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture)); + } + else _attrEveryEdit = everyActive ? every : null; + if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim); + + int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1); + ImGuiNET.ImGui.SetNextItemWidth(260); + if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length)) + SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture)); + + // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an + // Enter on an untouched box can't round the reserve. + string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep; + string keep = _attrKeepEdit ?? shownKeep; + ImGuiNET.ImGui.SetNextItemWidth(140); + bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool keepActive = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrKeepEdit = null; + if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal)) + SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal)); + } + else _attrKeepEdit = keepActive ? keep : null; + ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes."); + + DrawAttrTable(a, w); + Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. " + + "+1 / +10 raise by hand (red = not enough unassigned XP). " + + "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim); } /// <summary> @@ -411,6 +453,19 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber); ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber); } + // What is still to find: the plan's luminance less banked + character, and the coins short. + if (a.StillLum.Length > 0 && a.StillLum != "-") + { + bool done = a.StillLum == "0" && a.StillCoins == 0; + uint c = done ? Green : Amber; + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); Label("STILL NEEDED", c); + ImGuiNET.ImGui.TableNextColumn(); + ImGuiNET.ImGui.TableNextColumn(); Label("after banked lum", Dim); + ImGuiNET.ImGui.TableNextColumn(); + ImGuiNET.ImGui.TableNextColumn(); Label(a.StillLum, c); + ImGuiNET.ImGui.TableNextColumn(); Label(a.StillCoins > 0 ? a.StillCoins.ToString("N0", CultureInfo.InvariantCulture) : "0", c); + } ImGuiNET.ImGui.EndTable(); } @@ -441,6 +496,7 @@ internal sealed partial class SkillsFace if (a.Short.Length > 0) Label(a.Short, Text); } Label(a.Banked, Dim); + if (a.StillLine.Length > 0) Label(a.StillLine, Amber); if (a.Config != null) DrawAugCostSettings(a.Config, w); } finally @@ -589,11 +645,20 @@ internal sealed partial class SkillsFace Label(e.Header, Text); Label(e.Next, Teal); + // Plan-to-target: calculator uses character AvailableLuminance + pack mats. int target = e.Target; ImGuiNET.ImGui.SetNextItemWidth(100); - if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target)) + if (ImGuiNET.ImGui.InputInt("Plan to enl##prog_enlt", ref target)) SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture)); - foreach (string line in e.Plan) SafeImGui.BulletText(line); + ImGuiNET.ImGui.SetItemTooltip("Target enlightenment level. The calculator below shows each step and what you still need."); + + if (e.Plan.Length > 0) + { + Label("Totals to plan:", Dim); + foreach (string line in e.Plan) SafeImGui.BulletText(line); + } + + DrawEnlCalculator(e, w); DrawEnlCalculator(e, w); @@ -685,6 +750,30 @@ internal sealed partial class SkillsFace DrawEnlLevels(e.Levels, tw, k); DrawEnlMaterials(e.Materials, tw, k); DrawEnlChain(e, tw, k); + if (e.Chain.Length > 0 && e.ExtractsPerAscension >= 0) DrawChainTrades(e); + } + + /// <summary> + /// The sigil chain's vendor rates (RynthILT 0.2.23+): Necrolytic Extracts per Ascension Coin, + /// and the extracts-for-Trophies trade. 0 hides a trade. + /// </summary> + private void DrawChainTrades(EnlPlanner e) + { + int perAsc = e.ExtractsPerAscension; + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("Extracts per Ascension Coin (vendor)##prog_epa", ref perAsc)) + SendProg("extractsperasc " + Math.Max(0, perAsc).ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("Necrolytic Extracts a vendor takes for one Ascension Coin. 0 = no such vendor."); + int trEx = e.TrophyExtracts, trCount = e.TrophyCount; + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("extracts##prog_tre", ref trEx)) + SendProg("trophyextracts " + Math.Max(0, trEx).ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("Necrolytic Extracts the vendor takes for one Trophy trade. 0 = don't show the trade."); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(100); + if (ImGuiNET.ImGui.InputInt("Trophies (vendor trade)##prog_trc", ref trCount)) + SendProg("trophycount " + Math.Max(0, trCount).ToString(CultureInfo.InvariantCulture)); + ImGuiNET.ImGui.SetItemTooltip("Trophies that trade gives you."); } private void DrawEnlLevels(EnlLevelRow[] rows, float tw, float k) @@ -756,12 +845,15 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.PushTextWrapPos(0f); try { - if (ImGuiNET.ImGui.BeginTable("##enl_mats", 3, + // RynthILT 0.2.23+ says how to get a material (recipe or vendor trade): a fourth column. + bool how = rows.Any(m => m.How.Length > 0); + if (ImGuiNET.ImGui.BeginTable("##enl_mats", how ? 4 : 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0))) { ImGuiNET.ImGui.TableSetupColumn("Material"); ImGuiNET.ImGui.TableSetupColumn("Still need", ImGuiTableColumnFlags.WidthFixed, 72 * k); ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k); + if (how) ImGuiNET.ImGui.TableSetupColumn("How to get"); ImGuiNET.ImGui.TableHeadersRow(); int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows); for (int i = 0; i < n; i++) @@ -772,6 +864,7 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.TableNextColumn(); Label(m.Label, c); ImGuiNET.ImGui.TableNextColumn(); Label(m.Need, c); ImGuiNET.ImGui.TableNextColumn(); Label(m.Have, c); + if (how) { ImGuiNET.ImGui.TableNextColumn(); Label(m.How, Dim); } } ImGuiNET.ImGui.EndTable(); } @@ -792,12 +885,15 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.PushTextWrapPos(0f); try { - if (ImGuiNET.ImGui.BeginTable("##enl_chain", 3, + // RynthILT 0.2.23+ says how to get each item (its recipe or a vendor trade): a fourth column. + bool how = rows.Any(r => r.How.Length > 0); + if (ImGuiNET.ImGui.BeginTable("##enl_chain", how ? 4 : 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0))) { ImGuiNET.ImGui.TableSetupColumn("Item"); ImGuiNET.ImGui.TableSetupColumn("Need", ImGuiTableColumnFlags.WidthFixed, 72 * k); ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k); + if (how) ImGuiNET.ImGui.TableSetupColumn("How to get"); ImGuiNET.ImGui.TableHeadersRow(); int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows); for (int i = 0; i < n; i++) @@ -808,6 +904,7 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.TableNextColumn(); Label(r.DisplayLabel, c); ImGuiNET.ImGui.TableNextColumn(); Label(r.NeedText, c); ImGuiNET.ImGui.TableNextColumn(); Label(r.HaveText, c); + if (how) { ImGuiNET.ImGui.TableNextColumn(); Label(r.How, Dim); } } ImGuiNET.ImGui.EndTable(); } diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index f9d185d..5482528 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -369,14 +369,12 @@ internal static class RynthCoreShell new System.Threading.Thread(() => { System.Threading.Thread.Sleep(120); - // Asked for by hand: the reload deferral (EntryPoint.Shutdown) doesn't hold it. - EntryPoint.NoteManualReload(); - bool ok = EngineLifecycle.SignalReload(); - RynthLog.Info($"ERl: SignalReload returned {ok}."); + // In-world: loader holds until logout (mid-session CoreCLR re-init AVs). + EntryPoint.RequestManualReload("ERl"); }) { IsBackground = true, Name = "RynthCore.ERl" }.Start(); } - ShowTooltip("Engine reload: shut down, FreeLibrary, reload from disk, re-init. Picks up new engine builds without restarting AC."); + ShowTooltip("Engine reload: picks up a new build. While in-world it waits until logout / character select (mid-session hot reload crashes)."); ImGui.End(); ImGui.PopStyleVar(3); diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index de7206f..20b55ed 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -43,6 +43,8 @@ internal static class EngineSettings private static bool _insertReleasesUi; // Settings > Game Client: strip AC window chrome while windowed (default off). private static bool _borderlessWindowed; + // Settings > Game Client: borderless fills the monitor (default on) or keeps the framed game area. + private static bool _borderlessFillMonitor = true; // Settings > Interface: reopen Rynth panels where they were (default on: panels have always been remembered). private static bool _rememberWindowLayout = true; // Settings > Interface: each character keeps its own panel layout (default on; off = the one shared layout). @@ -455,6 +457,26 @@ internal static class EngineSettings } } + /// <summary>"BorderlessFillMonitor" in engine.json (default true, 2026-10-17): borderless + /// windowed fills the monitor the window is on. Off: it keeps the game area where the framed + /// window had it (a custom borderless size/spot). Set in game in Settings > Game Client.</summary> + public static bool BorderlessFillMonitor + { + get + { + EnsureLoaded(); + return _borderlessFillMonitor; + } + set + { + EnsureLoaded(); + if (_borderlessFillMonitor == value) return; + _borderlessFillMonitor = value; + Save("BorderlessFillMonitor"); + // AcWindowChrome.ApplyFillMonitorChanged (Settings > Game Client) re-places the window. + } + } + /// <summary>"RememberWindowLayout" in engine.json (default true: Rynth panels have always been /// remembered). Off: panel_state.txt is not overwritten and open panels are not reopened from /// the last session. Does not touch the AC window itself (RememberAcWindowPosition). @@ -893,6 +915,10 @@ internal static class EngineSettings (blwEl.ValueKind == JsonValueKind.True || blwEl.ValueKind == JsonValueKind.False)) _borderlessWindowed = blwEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("BorderlessFillMonitor", out var bfmEl) && + (bfmEl.ValueKind == JsonValueKind.True || bfmEl.ValueKind == JsonValueKind.False)) + _borderlessFillMonitor = bfmEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("RememberWindowLayout", out var rwlEl) && (rwlEl.ValueKind == JsonValueKind.True || rwlEl.ValueKind == JsonValueKind.False)) _rememberWindowLayout = rwlEl.GetBoolean(); @@ -1013,7 +1039,7 @@ internal static class EngineSettings "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", - "FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout", + "FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "BorderlessFillMonitor", "RememberWindowLayout", "RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", "LoadAllServerPlugins", "TransitionGate", "WebPanel", @@ -1087,6 +1113,8 @@ internal static class EngineSettings w.WriteBoolean("InsertReleasesUi", true); if (_borderlessWindowed) // default false: leave the file as it was w.WriteBoolean("BorderlessWindowed", true); + if (!_borderlessFillMonitor) // default true: leave the file as it was + w.WriteBoolean("BorderlessFillMonitor", false); if (!_rememberWindowLayout) // default true: leave the file as it was w.WriteBoolean("RememberWindowLayout", false); if (!_panelLayoutPerCharacter) // default true: leave the file as it was diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 41c2253..2905a12 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -953,8 +953,8 @@ internal struct RynthCoreAPI /// for every plugin: each server the engine knows (built in, or declared by a loaded plugin) /// with its verdict, this character's override, why, and the plugin that owns its settings; /// plus the active server and the Diagnostics pick (UI/Sections/ServerStateJson.cs has the - /// schema). Returns the UTF-8 byte length; when it is >= capacity nothing was written (call - /// again with a bigger buffer). -1 on failure. Any thread. Requires API v86+.</summary> + /// schema). Copies NUL-terminated UTF-8 JSON when it fits and returns its byte length either + /// way (length >= capacity: call again with a bigger buffer). Any thread. Requires API v86+.</summary> public IntPtr GetServerStateJsonFn; /// <summary>v87: <c>int GetWieldedItems(uint* ids, uint* locations, int max)</c>: what the player /// wields and where (EquipMask), from the server's WieldObject / InventoryPutObjInContainer / @@ -1091,6 +1091,16 @@ internal struct RynthCoreAPI /// <summary>v94: <c>int WebPanelGetState(int handle, WebPanelStateNative* state)</c>: the WebPanelStatusCode /// (a handle that is not the live one reads 6 Superseded), -1 bad args.</summary> public IntPtr WebPanelGetStateFn; + + // ── v98: per-character window placements (WindowPlacementApi.cs) ── + /// <summary>v98: <c>int GetWindowPlacement(const char* key, float* xywh)</c>: where the player left the + /// plugin's own floating window <c>key</c> on this character (x, y, width, height; ImGui screen pixels, + /// width/height 0 = sized itself). 1 found, 0 none saved, -1 bad key or no character. Any thread.</summary> + public IntPtr GetWindowPlacementFn; + /// <summary>v98: <c>int SetWindowPlacement(const char* key, float x, float y, float w, float h)</c>: saves it, + /// per character (window_state.<server>.<character>.txt, not the imgui.ini every client shares). + /// 1 saved, 0 no character yet, -1 bad key (empty, over 96 chars, '=' or a line break). Any thread.</summary> + public IntPtr SetWindowPlacementFn; } /// <summary>v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary> @@ -2003,6 +2013,10 @@ internal unsafe delegate int GetAmbientLightCallbackDelegate(uint* client, uint* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetMonsterHealthCallbackDelegate(uint id, float* ratio, uint* ageMs); +internal unsafe delegate int GetWindowPlacementCallbackDelegate(byte* key, float* xywh); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int SetWindowPlacementCallbackDelegate(byte* key, float x, float y, float w, float h); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int WebPanelOpenCallbackDelegate(WebPanelOpenNative* open); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index bbe7930..b2a53e6 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -71,5 +71,13 @@ internal static class PluginContractVersion /// <summary>The API version whose ArmConfirmation takes the leave-below (sticky) flag.</summary> public const uint ConfirmationLeaveBelow = 97; - public const uint Current = 97; + // v98: GetWindowPlacement and SetWindowPlacement: a plugin's own floating windows keep their spot + // per character (window_state.<server>.<character>.txt) instead of in the imgui.ini every + // running client shares and rewrites (2026-10-26). Appended after v94's web panel slots. + // (Was v91 on the test branch; renumbered after upstream's v91 and v92, 2026-10-29, to v94 after + // upstream's v93 GetMonsterHealth, 2026-11-10, and to v98 after upstream's v94-v97, 2026-11-14.) + /// <summary>The API version that added Get/SetWindowPlacement.</summary> + public const uint WindowPlacements = 98; + + public const uint Current = 98; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs index b28e194..e5b2160 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs @@ -95,7 +95,7 @@ internal static partial class PluginManager return; } - RynthLog.Plugin($"PluginManager: {s.ServerName} ({s.ServerId}) is this server (its world name, or forced On) - loading {file} (va before: {Compatibility.AddressSpace.Describe()})"); + RynthLog.Plugin($"PluginManager: {s.ServerName} ({s.ServerId}) forced On - loading {file} (va before: {Compatibility.AddressSpace.Describe()})"); LoadedPlugin? plugin = PluginLoader.LoadSingle(s.Path, _shadowRootDir, _loadGeneration); RynthLog.Plugin($"PluginManager: loaded {file}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); if (plugin == null) @@ -113,7 +113,7 @@ internal static partial class PluginManager UI.Sections.SectionRegistry.RefreshManifests(); if (plugin.Initialized && !plugin.Failed) - AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Loaded {s.PluginName} for {s.ServerName} (its world name, or picked in Options > Diagnostics).", 1); + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Loaded {s.PluginName} for {s.ServerName} (forced On in Options > Diagnostics).", 1); } /// <summary> diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index c3b92e3..cf7bbab 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -40,10 +40,11 @@ internal static partial class PluginManager private readonly record struct PendingEnchantmentAdded(uint SpellId, double DurationSeconds); private readonly record struct PendingEnchantmentRemoved(uint EnchantmentId); - // A /myquests reply is one line per quest flag (hundreds on a played character) and arrives - // in one burst; a slow pump tick (a busy plugin window) must not drop its head. Lines are short - // strings, so a deep queue costs little. Drops are counted and logged (DispatchQueuedChatWindowText). - private const int MaxPendingIncomingChats = 4096; + // A /myquests or /qb list reply is one line per quest flag (15,000-25,000+ on an ACECustom + // character) and arrives in one burst; a slow pump tick (a busy plugin window) must not drop + // its head. Lines are short strings (~100 bytes), so even a full queue is a few MB. Drops are + // counted and logged (DispatchQueuedChatWindowText). + private const int MaxPendingIncomingChats = 65_536; private static long _droppedIncomingChats; // lines dropped unheard since the last log private static long _droppedIncomingChatsLoggedMs; // when that was last logged private const int MaxPendingBusyCountEvents = 128; @@ -310,6 +311,8 @@ internal static partial class PluginManager private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v94 private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v94 #endif + private static GetWindowPlacementCallbackDelegate? _getWindowPlacementCallback; // v98 + private static SetWindowPlacementCallbackDelegate? _setWindowPlacementCallback; // v98 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -662,7 +665,9 @@ internal static partial class PluginManager try { + int before = eat; plugin.OnChatBarEnter(textPtr, eatPtr); + if (before == 0 && eat != 0) NoteChatBarEaten(plugin.DisplayName, text); } catch (Exception ex) { @@ -683,6 +688,26 @@ internal static partial class PluginManager } } + // Which plugin took a typed / dispatched chat line (2026-10-30: a /fship list that never + // left the client could have been any of fifteen plugins; the log said nothing). Three + // lines per plugin and command word, so a plugin's own /ra or /ilt commands don't flood it. + private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, int> _chatBarEatLogged = new(StringComparer.OrdinalIgnoreCase); + + private static void NoteChatBarEaten(string plugin, string? text) + { + try + { + string t = (text ?? "").Trim(); + int sp = t.IndexOf(' '); + string verb = sp < 0 ? t : t[..sp]; + if (verb.Length > 24) verb = verb[..24]; + int n = _chatBarEatLogged.AddOrUpdate(plugin + "|" + verb, 1, (_, v) => v + 1); + if (n <= 3) + RynthLog.Plugin($"PluginManager: {plugin} took the chat line '{(t.Length > 80 ? t[..80] + "..." : t)}' (it isn't sent to AC or the server){(n == 3 ? "; no more lines logged for " + verb : "")}."); + } + catch { } + } + public static void QueueChatWindowText(string? text, uint chatType) => QueueChatWindowText(text, chatType, null); /// <summary> @@ -1820,6 +1845,11 @@ internal static partial class PluginManager unsafe { + // RynthChat's RynthChatNoteEaten (0.3.4+), looked up once per batch on first need: + // no plugin loads or unloads in the middle of this loop (same thread). + delegate* unmanaged[Cdecl]<IntPtr, int> noteEaten = null; + bool noteEatenResolved = false; + foreach (PendingIncomingChat evt in pending) { IntPtr textPtr = IntPtr.Zero; @@ -1862,6 +1892,21 @@ internal static partial class PluginManager } eaten = HeldChatQueue.PluginsAteIt(eat, threw); + // A plugin ate it: a reply to that plugin's own command (/myquests, /qb list, + // a login probe). RynthChat marks it automated so it shows in System only. + if (eaten && textPtr != IntPtr.Zero) + { + if (!noteEatenResolved) + { + noteEatenResolved = true; + noteEaten = (delegate* unmanaged[Cdecl]<IntPtr, int>)UI.Data.PluginExportBinder.Resolve("RynthChat", "RynthChatNoteEaten"); + } + if (noteEaten != null) + { + try { noteEaten(textPtr); } + catch (Exception ex) { RynthLog.Plugin($"PluginManager: RynthChat eaten-line note failed ({ex.GetType().Name}: {ex.Message})."); } + } + } // RynthChat's Hide rules / standard filters live in the engine, not in a plugin, so // without this a hidden line still printed in AC's own chat window. Only a held line // can still be kept out (one already printed has gone); a failure lets it show. @@ -3267,6 +3312,8 @@ internal static partial class PluginManager _webPanelCloseCallback ??= WebPanel.WebPanelApi.Close; unsafe { _webPanelGetStateCallback ??= WebPanel.WebPanelApi.GetState; } #endif + unsafe { _getWindowPlacementCallback ??= WindowPlacementApi.Get; } + unsafe { _setWindowPlacementCallback ??= WindowPlacementApi.Set; } _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3446,6 +3493,8 @@ internal static partial class PluginManager _api.WebPanelCloseFn = Marshal.GetFunctionPointerForDelegate(_webPanelCloseCallback!); _api.WebPanelGetStateFn = Marshal.GetFunctionPointerForDelegate(_webPanelGetStateCallback!); #endif + _api.GetWindowPlacementFn = Marshal.GetFunctionPointerForDelegate(_getWindowPlacementCallback); + _api.SetWindowPlacementFn = Marshal.GetFunctionPointerForDelegate(_setWindowPlacementCallback); RouteApiThroughLoader(); } diff --git a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs index 5f936d2..66d272f 100644 --- a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs +++ b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs @@ -104,13 +104,10 @@ internal static class PluginManifestGate } /// <summary> - /// The server plugins to leave out (their paths). With <paramref name="connectHost"/> known, - /// only the plugins that list it load; when none does, none load (every server plugin is a - /// runtime in a 32-bit client, and a dozen of them for a server nobody claims only cost address - /// space). A skipped plugin still loads late when its server announces a world name it lists, - /// or when the character forces its server On (SectionRegistry), so a server that moved to a - /// new host still gets its plugin. With no host (an externally launched client) all load. - /// Nothing is left out when <paramref name="loadAll"/> is set. + /// The server plugins to leave out (their paths). Fail-open: a server plugin is left out only + /// when <paramref name="connectHost"/> is known and another installed server plugin claims it, + /// so a server that moved to a new host still gets its plugin (all of them load, each shows + /// only on its own server). Nothing is left out when <paramref name="loadAll"/> is set. /// </summary> internal static HashSet<string> SelectServerPlugins(IReadOnlyList<PluginCandidate> candidates, string? connectHost, bool loadAll, List<string> log) @@ -137,14 +134,16 @@ internal static class PluginManifestGate if (c.Manifest!.Server!.MatchesHost(host, out string hit)) claimants.Add($"{c.Manifest.Name} ({c.Manifest.Server.Id}, \"{hit}\")"); if (claimants.Count == 0) - log.Add($"{servers.Count} server plugin(s): none lists host {host}, so none load now (one loads once its world name is announced, or when its server is picked)."); + { + log.Add($"{servers.Count} server plugin(s): none lists host {host}, so all load (each shows only on its own server)."); + return skip; + } foreach (PluginCandidate c in servers) { if (c.Manifest!.Server!.MatchesHost(host, out _)) continue; skip.Add(c.Key); - if (claimants.Count > 0) - log.Add($"{Path.GetFileName(c.Key)}: not loaded - it is for {c.Manifest.Server.Name}, and host {host} is {string.Join(", ", claimants)}."); + log.Add($"{Path.GetFileName(c.Key)}: not loaded - it is for {c.Manifest.Server.Name}, and host {host} is {string.Join(", ", claimants)}."); } return skip; } diff --git a/src/RynthCore.Engine/Plugins/WindowPlacementApi.cs b/src/RynthCore.Engine/Plugins/WindowPlacementApi.cs new file mode 100644 index 0000000..444e708 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/WindowPlacementApi.cs @@ -0,0 +1,45 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/WindowPlacementApi.cs +// Plugin API v98 GetWindowPlacement / SetWindowPlacement: a plugin's own floating +// ImGui windows keep their spot per character (UI/WindowPlacementStore). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.Plugins; + +internal static unsafe class WindowPlacementApi +{ + /// <summary>1 found (xywh filled), 0 none saved, -1 bad key or no character yet.</summary> + public static int Get(byte* key, float* xywh) + { + try + { + if (key == null || xywh == null) return -1; + string? k = Marshal.PtrToStringUTF8((IntPtr)key); + if (!WindowPlacementStore.ValidKey(k)) return -1; + if (WindowPlacementStore.FileNameFor(Compatibility.SessionStateRegistry.LastServerName, + Compatibility.SessionStateRegistry.LastCharacterName) == null) return -1; + if (!WindowPlacementStore.TryGet(k!, out float x, out float y, out float w, out float h)) return 0; + xywh[0] = x; xywh[1] = y; xywh[2] = w; xywh[3] = h; + return 1; + } + catch { return -1; } + } + + /// <summary>1 saved, 0 no character yet, -1 bad key or numbers.</summary> + public static int Set(byte* key, float x, float y, float w, float h) + { + try + { + if (key == null) return -1; + string? k = Marshal.PtrToStringUTF8((IntPtr)key); + if (!WindowPlacementStore.ValidKey(k) || !float.IsFinite(x) || !float.IsFinite(y) + || !float.IsFinite(w) || !float.IsFinite(h)) return -1; + return WindowPlacementStore.Set(k!, x, y, w, h) ? 1 : 0; + } + catch { return -1; } + } +} diff --git a/src/RynthCore.Engine/UI/AcWindowChrome.cs b/src/RynthCore.Engine/UI/AcWindowChrome.cs index 8a21415..bcbe068 100644 --- a/src/RynthCore.Engine/UI/AcWindowChrome.cs +++ b/src/RynthCore.Engine/UI/AcWindowChrome.cs @@ -2,41 +2,46 @@ // RynthCore.Engine - UI/AcWindowChrome.cs // Settings > Game Client helpers for the Asheron's Call game HWND: // - Borderless windowed: strip caption / thick frame while leaving the client -// windowed (not exclusive fullscreen). Chrome is only given back to a window -// WE stripped: that is recorded as an HWND property (SetProp) holding the -// window's style from before, which outlives an in-process engine hot reload -// and dies with the process. No marker and the setting off = hands off. -// - Remember placement (opt-in): persist the outer window rect per client -// (ac_window.<server-character>.txt) and put its POSITION back once after login. -// Since 2026-11-15 (report R-20261115-160655-1201) never its size, and a rect is -// saved only in the world once it held for 30 s: see AcWindowChromePolicy. -// While this is on, the launcher leaves the window's position to the engine. -// Original: SilentKelpie (RynthCore PR 6). Decisions live in AcWindowChromePolicy. -// -// Threading. Tick runs inside EndScene (the render callback) and only READS there -// (styles, rect, the marker); anything that changes the window - the style, a -// SetWindowPos that moves or resizes it - is posted to the game window's own WndProc -// (Win32Backend.PostToGameThread, the way pop-out windows are created), so it never -// runs inside the render call. Rect files are written by UiBackgroundWriter, never -// on the render thread. With no WndProc subclass (ImGui backend off) the feature -// stays inactive instead of touching the window from the render thread. +// windowed (not exclusive fullscreen). Two sizes (Borderless Fills Monitor): +// on (default) - fill the monitor the window is on (borderless fullscreen); +// off - keep the game area exactly where the framed window had it, +// so a custom borderless size/spot is set by placing the framed +// window first, then turning borderless on. +// Stripping the frame alone left the window at AC's resolution with no border +// to drag and no maximize box: stuck small (worst under DXVK, where AC re-sized +// the window to its resolution after a device reset). The borderless rect is +// kept (bounded re-applies), the framed rect comes back when it's turned off, +// and "Reset Window Borders" / "/rc window reset" always gets a normal, +// resizable window back. +// - Remember placement: persist and restore the window across launches when +// "Remember open windows and HUD positions" is on — the framed rect and the +// borderless rect separately (ac_window.txt: left/top/width/height and +// bl_left/bl_top/bl_width/bl_height). +// Styles use SetWindowLong (x86); SWP_FRAMECHANGED so the non-client area +// rebuilds after GWL_STYLE changes. // ============================================================================ using System; -using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Runtime.InteropServices; -using System.Threading; -using RynthCore.App; -using RynthCore.Engine.Compatibility; using RynthCore.Engine.Plugins; -using static RynthCore.Engine.UI.AcWindowChromePolicy; namespace RynthCore.Engine.UI; internal static class AcWindowChrome { private const int GwlStyle = -16; + private const int GwlExStyle = -20; + private const int WsCaption = 0x00C00000; + private const int WsThickFrame = 0x00040000; + private const int WsSysMenu = 0x00080000; + private const int WsMinimizeBox = 0x00020000; + private const int WsMaximizeBox = 0x00010000; + private const int WsBorder = 0x00800000; + // Caption + frame + sysmenu/minmax: the chrome "Borderless windowed" removes. + private const int BorderChromeMask = + WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox | WsBorder; private const uint SwpNosize = 0x0001; private const uint SwpNomove = 0x0002; @@ -44,70 +49,62 @@ internal static class AcWindowChrome private const uint SwpNoactivate = 0x0010; private const uint SwpFramechanged = 0x0020; - // HWND properties: they live on the window, so they survive an engine hot reload. - private const string StyleProp = "RynthCore.AcWindowChrome.StyleBeforeBorderless"; - private const string PlacementDoneProp = "RynthCore.AcWindowChrome.PlacementRestored"; - - private const long TickIntervalMs = 2000; - private const long NoKeyFallbackMs = 90000; // no character this long: use the shared file - private const long PostStuckMs = 10000; // a posted job that never ran may be posted again - private const long StyleRetryMs = 10000; // a style change that does not stick is not retried every tick - private static readonly object Sync = new(); - private static readonly Action PostedWork = RunOnGameThread; - private static long _nextTickMs, _firstTickMs, _workPostedAtMs, _nextStyleActionMs; - private static int _workPosted; - private static bool _loggedNoExecutor; + private static int? _savedStyle; + private static IntPtr _styleHwnd; + private static bool _borderlessApplied; + private static long _nextApplyTick; + private static long _nextPlacementSaveTick; + private static bool _placementRestored; + // The first borderless apply this process may take the saved borderless rect (launch restore); + // later ones (the Settings toggle) use where the window is now. + private static bool _borderlessRestoreTried; + // The windowed (framed) rect from before borderless, put back when it's turned off. + private static RECT? _savedRect; + // Where the borderless window should be (the monitor, or the kept game area). + private static RECT? _borderlessTarget; + // Re-applies after AC re-sized the borderless window to its resolution: counted so the two + // never fight forever (MaxRefills in RefillWindowMs, then left alone with a log line). + private const int MaxRefills = 4; + private const long RefillWindowMs = 60_000; + private static int _refills; + private static long _refillWindowStart; + private static bool _refillGaveUp; - // Placement (under Sync). The saved rect, read once per key; the restore's clocks; what a new - // rect is compared with (the saved rect, else the first one seen in the world) and the rect - // waiting out AcWindowPlacementRule.StableFor. A hot reload resets them, which is fine: the - // PlacementDoneProp on the HWND keeps the restore from running twice. - private static string? _savedKey; - private static bool _savedLoaded; - private static Rect? _saved; - private static long _restoreWatchStartMs, _sizeSinceMs; - private static int _sizeW, _sizeH; - private static Rect? _reference; - private static bool _referenceSet; - private static AcWindowPlacementRule.Pending? _pending; + private static string PlacementPath + { + get + { + string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(root, "RynthCore", "ac_window.txt"); + } + } - // ── Frame loop (EndScene): reads + posts only ──────────────────────── - - /// <summary>Call from the frame loop; throttled. Never changes the window itself.</summary> + /// <summary>Re-apply borderless / restore placement when the HWND is known. + /// Cheap when nothing changed; call from the frame loop at a low rate.</summary> public static void Tick(IntPtr hwnd) { if (hwnd == IntPtr.Zero) return; long now = Environment.TickCount64; - if (now < _nextTickMs) return; - _nextTickMs = now + TickIntervalMs; - if (_firstTickMs == 0) _firstTickMs = now; + if (now < _nextApplyTick) return; + _nextApplyTick = now + 2000; try { - if (!ImGuiBackend.Win32Backend.CanRunOnGameThread) + // Another client may have changed Settings > Graphics (graphics.json). + Graphics.AcGraphics.PollReload(); + + if (EngineSettings.RememberAcWindowPosition && !_placementRestored) + TryRestorePlacement(hwnd); + + ApplyBorderlessDesired(hwnd); + + // Keep AC placement fresh while the user drags/resizes (throttled). + if (EngineSettings.RememberAcWindowPosition && now >= _nextPlacementSaveTick) { - // No WndProc subclass to run window changes from: stay out of the window. - if (!_loggedNoExecutor && (EngineSettings.BorderlessWindowed || EngineSettings.RememberAcWindowPosition)) - { - _loggedNoExecutor = true; - RynthLog.UI("AcWindowChrome: no game-thread executor (ImGui backend off); display chrome inactive."); - } - return; + _nextPlacementSaveTick = now + 10000; + SavePlacement(hwnd); } - - int style = GetWindowLong(hwnd, GwlStyle); - bool work = now >= Interlocked.Read(ref _nextStyleActionMs) - && DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style, - LooksExclusiveFullscreen(hwnd, style)).Action != ChromeAction.None; - - // Posted every tick until the restore is decided: it waits for AC's size to settle. - if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd) && InWorld() && KeyReady(now, out _)) - work = true; - - if (work) PostWork(now); - - MaybeSavePlacement(hwnd, now, style); } catch (Exception ex) { @@ -115,232 +112,386 @@ internal static class AcWindowChrome } } - /// <summary>A Settings > Game Client toggle changed: apply it on the game thread soon (not inline).</summary> - public static void RequestApply() + /// <summary>Immediate borderless apply (Settings toggle).</summary> + public static void ApplyBorderlessDesired(IntPtr hwnd) { - try - { - if (ImGuiBackend.Win32Backend.CanRunOnGameThread) - PostWork(Environment.TickCount64); - // else: Tick applies it once a game-thread executor exists. - } - catch (Exception ex) - { - try { RynthLog.UI($"AcWindowChrome: apply request failed - {ex.Message}"); } catch { } - } - } - - private static void PostWork(long now) - { - // One job in flight; a job that never ran (window gone, reload) may be re-posted after a while. - if (Interlocked.CompareExchange(ref _workPosted, 1, 0) != 0 && now - _workPostedAtMs < PostStuckMs) - return; - _workPostedAtMs = now; - Volatile.Write(ref _workPosted, 1); - if (!ImGuiBackend.Win32Backend.PostToGameThread(PostedWork)) - Volatile.Write(ref _workPosted, 0); - } - - // ── Game thread (the game WndProc) ─────────────────────────────────── - - private static void RunOnGameThread() - { - Volatile.Write(ref _workPosted, 0); - try - { - IntPtr hwnd = ResolveGameHwnd(); - if (hwnd == IntPtr.Zero) return; - lock (Sync) - { - if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd)) - TryRestorePlacement(hwnd); - ApplyBorderless(hwnd); - } - } - catch (Exception ex) - { - try { RynthLog.UI($"AcWindowChrome: apply failed - {ex.Message}"); } catch { } - } - } - - private static void ApplyBorderless(IntPtr hwnd) - { - int style = GetWindowLong(hwnd, GwlStyle); - ChromeDecision d = DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style, - LooksExclusiveFullscreen(hwnd, style)); - if (d.Action != ChromeAction.None) - Interlocked.Exchange(ref _nextStyleActionMs, Environment.TickCount64 + StyleRetryMs); - switch (d.Action) - { - case ChromeAction.Strip: - SetWindowLong(hwnd, GwlStyle, d.NewStyle); - SetProp(hwnd, StyleProp, new IntPtr(d.NewMarker)); - Refresh(hwnd); - RynthLog.UI("AcWindowChrome: borderless windowed on."); - break; - case ChromeAction.Restore: - SetWindowLong(hwnd, GwlStyle, d.NewStyle); - RemoveProp(hwnd, StyleProp); - Refresh(hwnd); - RynthLog.UI("AcWindowChrome: window borders restored."); - break; - case ChromeAction.ClearMarker: - RemoveProp(hwnd, StyleProp); - RynthLog.UI("AcWindowChrome: borderless marker cleared (" + d.Reason + ")."); - break; - } - } - - // Style change only: same outer rect, non-client area rebuilt. - private static void Refresh(IntPtr hwnd) - => SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, - SwpNomove | SwpNosize | SwpNozorder | SwpNoactivate | SwpFramechanged); - - private static void TryRestorePlacement(IntPtr hwnd) - { - long now = Environment.TickCount64; - if (!InWorld() || !KeyReady(now, out string? key)) return; // login screen / character select - if (_restoreWatchStartMs == 0) _restoreWatchStartMs = now; - if (!GetWindowRect(hwnd, out RECT wr)) return; - var cur = new Rect(wr.Left, wr.Top, wr.Right, wr.Bottom); - if (cur.Width != _sizeW || cur.Height != _sizeH) - { - _sizeW = cur.Width; - _sizeH = cur.Height; - _sizeSinceMs = now; - } - - Rect? saved = LoadSaved(key); - var d = DecideRestore(saved, IsIconic(hwnd) || IsZoomed(hwnd), - LooksExclusiveFullscreen(hwnd, GetWindowLong(hwnd, GwlStyle)), cur, - TimeSpan.FromMilliseconds(now - _sizeSinceMs), TimeSpan.FromMilliseconds(now - _restoreWatchStartMs), - WorkAreas()); - if (d.Action == AcWindowPlacementRule.RestoreAction.Wait) return; // asked again next tick - - // One decision per window, even a skipped one; the HWND carries it across a hot reload. - SetProp(hwnd, PlacementDoneProp, new IntPtr(1)); - SetReference(saved); - if (d.Action == AcWindowPlacementRule.RestoreAction.Move && saved is Rect from) - { - // SWP_NOSIZE: AC sizes its own window from its resolution; a smaller window crops the - // picture and leaves the HUD out of reach (R-20261115-160655-1201). - SetWindowPos(hwnd, IntPtr.Zero, d.X, d.Y, 0, 0, SwpNosize | SwpNozorder | SwpNoactivate); - RynthLog.UI(d.Clamped - ? FormattableString.Invariant($"AcWindowChrome: restored AC window position to ({d.X},{d.Y}), pulled onto the screen from ({from.Left},{from.Top}); size left to AC ({cur.Width}x{cur.Height}).") - : FormattableString.Invariant($"AcWindowChrome: restored AC window position to ({d.X},{d.Y}); size left to AC ({cur.Width}x{cur.Height}).")); - } - else if (saved is Rect sv) - { - RynthLog.UI(FormattableString.Invariant( - $"AcWindowChrome: saved position ({sv.Left},{sv.Top}) not restored ({d.Why}); leaving AC where it is.")); - } - } - - /// <summary>The saved rect for this client, read once per key (null: none, or unreadable).</summary> - private static Rect? LoadSaved(string? key) - { - if (_savedLoaded && string.Equals(_savedKey, key, StringComparison.Ordinal)) return _saved; - _savedLoaded = true; - _savedKey = key; - _saved = null; - string path = PlacementPath(key); - try - { - if (File.Exists(path) && TryParsePlacement(File.ReadAllLines(path), out Rect r)) - _saved = r; - } - catch (Exception ex) - { - try { RynthLog.UI($"AcWindowChrome: read placement failed - {ex.Message}"); } catch { } - } - return _saved; - } - - private static void SetReference(Rect? r) - { - _reference = r; - _referenceSet = true; - _pending = null; - } - - // ── Saving the rect (read on the render thread, written in the background) ── - - private static void MaybeSavePlacement(IntPtr hwnd, long now, int style) - { - if (!EngineSettings.RememberAcWindowPosition) return; - // Not before the restore is decided: it would overwrite the saved rect with the launch position. - if (!PlacementDone(hwnd)) return; - TrySavePlacement(hwnd, style, now, force: false); - } - - private static void TrySavePlacement(IntPtr hwnd, int style, long now, bool force) - { - if (!KeyReady(now, out string? key)) return; - if (!GetWindowRect(hwnd, out RECT wr)) return; - var cur = new Rect(wr.Left, wr.Top, wr.Right, wr.Bottom); - bool saveable = !IsIconic(hwnd) && !IsZoomed(hwnd) && !LooksExclusiveFullscreen(hwnd, style); - bool inWorld = InWorld(); - bool baselineOk = inWorld && saveable && AcWindowPlacementRule.IsCapturable(ToPlacement(cur)); - + if (hwnd == IntPtr.Zero) return; + // Settings > Graphics window mode (this account's profile), else the Display toggles. + bool want = Graphics.AcGraphics.WantBorderless; lock (Sync) { - // After a hot reload the restore was decided by the old engine: start from the saved rect. - if (!_referenceSet) SetReference(LoadSaved(key)); - if (_reference is null && !force) + if (hwnd != _styleHwnd) { - // Nothing saved: the first rect in the world is AC's own placement, never saved - // until the player moves the window away from it (as in the launcher). - if (baselineOk) _reference = cur; - return; + _styleHwnd = hwnd; + _savedStyle = null; + _borderlessApplied = false; } - var d = DecideSave(inWorld, saveable, force, cur, _reference, ref _pending, DateTime.UtcNow); - if (d.Action == AcWindowPlacementRule.SaveAction.LoginShrink) - { - if (d.FirstSeen && _reference is Rect rf) - RynthLog.UI(FormattableString.Invariant( - $"AcWindowChrome: not saving {cur.Width}x{cur.Height}, under half the in-game {rf.Width}x{rf.Height} (the login / character-select window).")); - return; - } - if (d.Action != AcWindowPlacementRule.SaveAction.Save) return; + int style = GetWindowLong(hwnd, GwlStyle); + bool missingChrome = (style & WsCaption) == 0; - // Off-screen (a monitor that is gone) or absurd: not worth saving. - if (EvaluatePlacement(true, false, cur, Monitors()) != PlacementVerdict.Ok) return; - _reference = cur; + if (want) + { + // Leave true exclusive fullscreen alone — but a maximized borderless + // window we made ourselves still needs to be able to restore later. + if (!_borderlessApplied && IsLikelyExclusiveFullscreen(hwnd, style)) + { + RynthLog.UI("AcWindowChrome: skip borderless — looks like exclusive fullscreen."); + return; + } + + if (_borderlessApplied && missingChrome) + { + // Already borderless: keep it where it should be. AC sizes its window to + // its own resolution after a device reset (seen with DXVK), which left a + // frame-less window too small to fix by hand. + KeepAtTarget(hwnd); + return; + } + + // Remember a style that still has chrome. After a hot reload the window + // can already be borderless while our statics were cleared — OR the mask + // back on so turning the setting off can still restore a real frame. + if (_savedStyle is null) + _savedStyle = missingChrome ? (style | BorderChromeMask) : style; + + Placement file = EngineSettings.RememberAcWindowPosition ? ReadPlacementFile() : default; + bool launch = !_borderlessRestoreTried; + _borderlessRestoreTried = true; + + // The framed rect to go back to: the saved one at launch (TryRestorePlacement + // skips while borderless), else where the framed window is now. + if (_savedRect is null) + { + if (launch && file.Framed is RECT ff && IsRectOnAnyMonitor(ff) && !SavedClientIsLoginSize(hwnd, ff)) + _savedRect = FitToWorkArea(ff); + else if (!missingChrome && GetWindowRect(hwnd, out RECT framed)) + _savedRect = framed; + } + + RECT target = ChooseBorderlessTarget(hwnd, missingChrome, launch ? file.Borderless : null); + + SetWindowLong(hwnd, GwlStyle, style & ~BorderChromeMask); + MoveTo(hwnd, target); + _borderlessTarget = target; + _borderlessApplied = true; + _refills = 0; + _refillGaveUp = false; + string how = Graphics.AcGraphics.FillMonitor ? "filling the monitor" : "resolution size"; + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: borderless windowed on at ({target.Left},{target.Top}) {Width(target)}x{Height(target)} ({how}).")); + if (EngineSettings.RememberAcWindowPosition) SavePlacement(hwnd); + } + else + { + // Restore even when the window fills the monitor (maximized borderless + // looks like exclusive fullscreen and used to early-return forever). + // Also heal a stuck chrome-less window after engine reload with the + // setting already off (_borderlessApplied false, _savedStyle null). + if (!_borderlessApplied && _savedStyle is null && !missingChrome) return; + + int restore; + if (_savedStyle is int saved && (saved & WsCaption) != 0) + restore = saved; + else + restore = style | BorderChromeMask; + + if (style != restore) + SetWindowLong(hwnd, GwlStyle, restore); + // Back to a framed window where it was before borderless (else the saved framed + // placement, else centred), sized for AC's resolution. + RECT at = _savedRect + ?? (ReadPlacementFile().Framed is RECT ff && IsRectOnAnyMonitor(ff) ? ff : DefaultWindowedRect(hwnd)); + RECT target = FramedAtResolution(hwnd, at, restore); + MoveTo(hwnd, target); + _borderlessApplied = false; + _borderlessTarget = null; + _savedStyle = null; + _savedRect = null; + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: window borders restored ({Width(target)}x{Height(target)}).")); + } } - - string path = PlacementPath(key); - UiBackgroundWriter.Enqueue("ac window placement", () => WritePlacement(path, cur)); } - private static void WritePlacement(string path, Rect r) + /// <summary>Settings > Game Client "Borderless Fills Monitor" changed: re-place a borderless window + /// (fill: its monitor; kept size: where the framed window was) and save it.</summary> + public static void ApplyFillMonitorChanged(IntPtr hwnd) { - try + if (hwnd == IntPtr.Zero) return; + lock (Sync) { - string? dir = Path.GetDirectoryName(path); - if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - File.WriteAllText(path, FormatPlacement(r)); - } - catch (Exception ex) - { - try { RynthLog.UI($"AcWindowChrome: save placement failed - {ex.Message}"); } catch { } + if (!_borderlessApplied || (GetWindowLong(hwnd, GwlStyle) & WsCaption) != 0) return; + RECT target; + if (Graphics.AcGraphics.FillMonitor) + { + if (!TryMonitorRect(hwnd, out target, out _)) return; + } + else + { + // Resolution size, where the framed window was (else centred on the monitor). + RECT at = _savedRect is RECT fr && IsRectOnAnyMonitor(fr) ? fr : DefaultWindowedRect(hwnd); + target = BorderlessAtResolution(hwnd, at.Left, at.Top); + } + MoveTo(hwnd, target); + _borderlessTarget = target; + _refills = 0; + _refillGaveUp = false; + string how = Graphics.AcGraphics.FillMonitor ? "filling the monitor" : "resolution size"; + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: borderless now {Width(target)}x{Height(target)} ({how}).")); + if (EngineSettings.RememberAcWindowPosition) SavePlacement(hwnd); } } - /// <summary>Settings > Interface "Save Layout Now". Runs on the render thread (a button in a - /// frame): everything that touches a file is queued to the background writer.</summary> + /// <summary> + /// Settings > Game Client "Reset Window Borders" and "/rc window reset": borderless off (saved), + /// the frame back, and a normal window of a sensible size, centred; the saved placement is + /// replaced by it (the borderless rect is forgotten) so the next launch isn't stuck either. + /// For a window stuck too small or off-screen. AC's main thread. + /// </summary> + public static string ResetWindow() + { + IntPtr hwnd = ResolveGameHwnd(); + if (hwnd == IntPtr.Zero) return "The game window isn't known yet."; + if (EngineSettings.BorderlessWindowed) EngineSettings.BorderlessWindowed = false; + // This account's Settings > Graphics window mode too, or it would win. + Graphics.AcGraphics.ResetWindowModeToWindowed(); + lock (Sync) + { + int style = GetWindowLong(hwnd, GwlStyle); + SetWindowLong(hwnd, GwlStyle, style | BorderChromeMask); + // Centred, sized for the resolution AC is really drawing at. + RECT target = DefaultWindowedRect(hwnd); + MoveTo(hwnd, target); + _styleHwnd = hwnd; + _borderlessApplied = false; + _borderlessTarget = null; + _savedStyle = null; + _savedRect = null; + WritePlacementFile(new Placement { Framed = target, Borderless = null }); + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: window reset to a framed {Width(target)}x{Height(target)}.")); + return FormattableString.Invariant( + $"Window reset: borderless off, normal resizable window ({Width(target)}x{Height(target)})."); + } + } + + /// <summary>"/rc window save": write the window's placement now (framed or borderless).</summary> + public static string SaveWindowNow() + { + IntPtr hwnd = ResolveGameHwnd(); + if (hwnd == IntPtr.Zero) return "The game window isn't known yet."; + if (!SavePlacement(hwnd, force: true)) return "Nothing saved (not in the world, exclusive fullscreen, or the window is too small)."; + bool borderless = (GetWindowLong(hwnd, GwlStyle) & WsCaption) == 0; + return borderless ? "Borderless window position saved." : "Window position saved."; + } + + /// <summary>Where a borderless window goes: fill (the saved rect's monitor at launch, else the + /// window's) or resolution size (at the saved spot at launch, else where the framed window's game + /// area is, so the picture doesn't move).</summary> + private static RECT ChooseBorderlessTarget(IntPtr hwnd, bool missingChrome, RECT? savedBorderless) + { + bool useSaved = savedBorderless is RECT sb && IsRectOnAnyMonitor(sb) && !IsLoginScreenSize(Width(sb), Height(sb)); + if (Graphics.AcGraphics.FillMonitor) + { + if (useSaved && TryMonitorRectAt(savedBorderless!.Value, out RECT savedMon)) return savedMon; + if (TryMonitorRect(hwnd, out RECT mon, out _)) return mon; + } + else + { + if (useSaved) return BorderlessAtResolution(hwnd, savedBorderless!.Value.Left, savedBorderless.Value.Top); + if (!missingChrome && TryClientRectOnScreen(hwnd, out RECT client)) return BorderlessAtResolution(hwnd, client.Left, client.Top); + if (GetWindowRect(hwnd, out RECT wr)) return BorderlessAtResolution(hwnd, wr.Left, wr.Top); + } + return DefaultWindowedRect(hwnd); + } + + /// <summary> + /// Settings > Graphics changed the window mode: apply it to the window now (a Resolution change + /// waits for the next launch: the window always follows what AC really draws at). + /// Borderless modes go through <see cref="ApplyBorderlessDesired"/> (and re-place a window that + /// is already borderless); windowed and full screen get a frame sized for the resolution, where + /// the window is. Full screen itself (AC's exclusive mode) starts at the next launch. AC's main thread. + /// </summary> + public static void ApplyGraphicsChanged(IntPtr hwnd) + { + if (hwnd == IntPtr.Zero) return; + lock (Sync) + { + bool framed = (GetWindowLong(hwnd, GwlStyle) & WsCaption) != 0; + if (Graphics.AcGraphics.WantBorderless) + { + if (_borderlessApplied && !framed) ApplyFillMonitorChanged(hwnd); + else ApplyBorderlessDesired(hwnd); + return; + } + if (_borderlessApplied || !framed) + { + ApplyBorderlessDesired(hwnd); // frame back, sized for the resolution + return; + } + if (!GetWindowRect(hwnd, out RECT wr)) return; + RECT target = FramedAtResolution(hwnd, wr, GetWindowLong(hwnd, GwlStyle)); + if (!SameRect(target, wr)) MoveTo(hwnd, target); + string later = Graphics.AcGraphics.WindowMode == AcGraphicsModes.FullScreen ? " (full screen starts at the next launch)" : ""; + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: window set to {Width(target)}x{Height(target)} for {Graphics.AcGraphics.WindowMode}{later}.")); + if (EngineSettings.RememberAcWindowPosition) SavePlacement(hwnd); + } + } + + /// <summary>Short names for the window mode ids (RynthCore.Graphics.AcGraphicsPrefs).</summary> + private static class AcGraphicsModes + { + public const string FullScreen = global::RynthCore.Graphics.AcGraphicsPrefs.ModeFullScreen; + } + + /// <summary>The outer size of a window with <paramref name="style"/> whose game area is the size AC + /// is really drawing at (its back buffer, else the resolution it launched with). False when unknown.</summary> + private static bool TryFramedSizeForResolution(IntPtr hwnd, int style, out int width, out int height) + { + width = height = 0; + if (!Graphics.AcGraphics.TryGetDrawSize(out int rw, out int rh)) return false; + var r = new RECT { Left = 0, Top = 0, Right = rw, Bottom = rh }; + // The frame the window really has (AC's is fixed: no sizing border). A frame-less window + // gets the frame it will be given back (its style plus the chrome mask). + int framedStyle = (style & WsCaption) != 0 ? style : style | BorderChromeMask; + if (!AdjustWindowRectEx(ref r, framedStyle, false, GetWindowLong(hwnd, GwlExStyle))) return false; + width = Width(r); + height = Height(r); + return true; + } + + /// <summary>A framed rect at <paramref name="at"/>'s top-left, sized for AC's resolution (else + /// <paramref name="at"/>'s size), kept inside the screen.</summary> + private static RECT FramedAtResolution(IntPtr hwnd, RECT at, int style) + { + if (!TryFramedSizeForResolution(hwnd, style, out int w, out int h)) return FitToWorkArea(at); + return FitToWorkArea(new RECT { Left = at.Left, Top = at.Top, Right = at.Left + w, Bottom = at.Top + h }); + } + + /// <summary>A frame-less rect of AC's resolution at (<paramref name="left"/>, <paramref name="top"/>), + /// kept inside the screen; the monitor when the resolution isn't known.</summary> + private static RECT BorderlessAtResolution(IntPtr hwnd, int left, int top) + { + if (!Graphics.AcGraphics.TryGetDrawSize(out int rw, out int rh)) + return TryMonitorRect(hwnd, out RECT mon, out _) ? mon : DefaultWindowedRect(hwnd); + return FitToWorkArea(new RECT { Left = left, Top = top, Right = left + rw, Bottom = top + rh }); + } + + /// <summary>Borderless but no longer where it should be (AC re-sized it): put it back, a few times at most.</summary> + private static void KeepAtTarget(IntPtr hwnd) + { + if (_refillGaveUp || _borderlessTarget is not RECT target) return; + if (!GetWindowRect(hwnd, out RECT wr)) return; + if (SameRect(wr, target)) return; + long now = Environment.TickCount64; + if (now - _refillWindowStart > RefillWindowMs) { _refillWindowStart = now; _refills = 0; } + if (++_refills > MaxRefills) + { + _refillGaveUp = true; + RynthLog.UI("AcWindowChrome: AC keeps re-sizing the borderless window; leaving it (Settings > Game Client > Reset Window Borders, or \"/rc window reset\", for a normal window)."); + return; + } + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: borderless window was {Width(wr)}x{Height(wr)}; putting it back to {Width(target)}x{Height(target)}.")); + MoveTo(hwnd, target); + } + + private static void MoveTo(IntPtr hwnd, RECT r) => + SetWindowPos(hwnd, IntPtr.Zero, r.Left, r.Top, Width(r), Height(r), + SwpNozorder | SwpNoactivate | SwpFramechanged); + + private static int Width(RECT r) => r.Right - r.Left; + private static int Height(RECT r) => r.Bottom - r.Top; + + private static bool SameRect(RECT a, RECT b) => + Math.Abs(a.Left - b.Left) <= 2 && Math.Abs(a.Top - b.Top) <= 2 + && Math.Abs(a.Right - b.Right) <= 2 && Math.Abs(a.Bottom - b.Bottom) <= 2; + + /// <summary>A framed window centred on the monitor's work area: sized for AC's resolution, else + /// three quarters of the work area. Never bigger than the work area.</summary> + private static RECT DefaultWindowedRect(IntPtr hwnd) + { + if (!TryMonitorRect(hwnd, out _, out RECT work)) + return new RECT { Left = 50, Top = 50, Right = 50 + 1296, Bottom = 50 + 759 }; + int ww = Width(work), wh = Height(work); + int w = ww * 3 / 4, h = wh * 3 / 4; + if (TryFramedSizeForResolution(hwnd, GetWindowLong(hwnd, GwlStyle), out int rw, out int rh)) + { + w = Math.Min(rw, ww); + h = Math.Min(rh, wh); + } + int left = work.Left + (ww - w) / 2, top = work.Top + (wh - h) / 2; + return new RECT { Left = left, Top = top, Right = left + w, Bottom = top + h }; + } + + /// <summary>The whole rect and the work area of the monitor nearest the window.</summary> + private static bool TryMonitorRect(IntPtr hwnd, out RECT monitor, out RECT work) => + TryMonitorInfo(MonitorFromWindow(hwnd, 2 /* MONITOR_DEFAULTTONEAREST */), out monitor, out work); + + /// <summary>The whole rect of the monitor holding the centre of <paramref name="r"/>.</summary> + private static bool TryMonitorRectAt(RECT r, out RECT monitor) + { + var pt = new POINT { X = r.Left + Width(r) / 2, Y = r.Top + Height(r) / 2 }; + return TryMonitorInfo(MonitorFromPoint(pt, 2 /* MONITOR_DEFAULTTONEAREST */), out monitor, out _); + } + + private static bool TryMonitorInfo(IntPtr mon, out RECT monitor, out RECT work) + { + monitor = default; work = default; + if (mon == IntPtr.Zero) return false; + var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; + if (!GetMonitorInfo(mon, ref mi)) return false; + monitor = mi.rcMonitor; + work = mi.rcWork; + return true; + } + + /// <summary>The client area in screen coordinates (the game picture, without the frame).</summary> + private static bool TryClientRectOnScreen(IntPtr hwnd, out RECT r) + { + r = default; + if (!GetClientRect(hwnd, out RECT c)) return false; + var tl = new POINT { X = c.Left, Y = c.Top }; + if (!ClientToScreen(hwnd, ref tl)) return false; + r = new RECT { Left = tl.X, Top = tl.Y, Right = tl.X + Width(c), Bottom = tl.Y + Height(c) }; + return Width(r) >= 160 && Height(r) >= 120; + } + + /// <summary>Write the AC window rect when layout remembering is on (or always when + /// <paramref name="force"/> for "Save layout now"): the framed rect while it has a frame, the + /// borderless rect while it's borderless (ours, not exclusive fullscreen). The other is kept. + /// True when something was written.</summary> + public static bool SavePlacement(IntPtr hwnd, bool force = false) + { + if (hwnd == IntPtr.Zero) return false; + if (!force && !EngineSettings.RememberAcWindowPosition) return false; + // Only the world's window is the player's placement: at the login and character-select + // screens AC shrinks its window to 800x600, and saving that made every client start small. + if (Compatibility.UiFlowHooks.CurrentMode != Compatibility.UiFlowHooks.ModeGamePlay) return false; + int style = GetWindowLong(hwnd, GwlStyle); + bool framed = (style & WsCaption) != 0; + // Frame-less and not made by us: exclusive fullscreen (or not ours to remember). + if (!framed && !_borderlessApplied) return false; + if (!GetWindowRect(hwnd, out RECT rc)) return false; + if (Width(rc) < 160 || Height(rc) < 120) return false; + if (GetClientRect(hwnd, out RECT client) && IsLoginScreenSize(Width(client), Height(client))) return false; + + Placement p = ReadPlacementFile(); + if (framed) p.Framed = rc; + else p.Borderless = rc; + return WritePlacementFile(p); + } + + /// <summary>Force-save panels (already on disk via PanelStateStore), AC window, + /// Vision self-plate, and ImGui.ini. Used by Settings > Interface "Save Layout Now".</summary> public static void SaveLayoutNow() { - try - { - IntPtr hwnd = ResolveGameHwnd(); - if (hwnd != IntPtr.Zero && EngineSettings.RememberAcWindowPosition) - TrySavePlacement(hwnd, GetWindowLong(hwnd, GwlStyle), Environment.TickCount64, force: true); - } - catch (Exception ex) - { - try { RynthLog.UI($"AcWindowChrome: save window failed - {ex.Message}"); } catch { } - } + IntPtr hwnd = ResolveGameHwnd(); + if (hwnd != IntPtr.Zero) + SavePlacement(hwnd, force: true); try { ImGuiBackend.Hud.MonsterHudSettings.Save(); } catch { /* best-effort */ } @@ -356,45 +507,211 @@ internal static class AcWindowChrome } // Rewrites the layout's panel_state.txt from the in-memory state (even with Remember Open Windows off). - UiBackgroundWriter.Enqueue("panel state (save now)", PanelStateStore.Flush); + try { PanelStateStore.Flush(); } catch { /* best-effort */ } try { // The PC-wide default with Panel Layout Per Character on is only read (2026-11-05): say so. string? problem = PanelLayout.SavePlacesProblem(); if (problem == null) - AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1); + Compatibility.AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1); else - AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved HUD positions. Open windows and their places weren't saved: " + problem + ".", 0x1A); + Compatibility.AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved HUD positions. Open windows and their places weren't saved: " + problem + ".", 0x1A); } catch { /* chat may not be ready */ } } - // ── Helpers ────────────────────────────────────────────────────────── - - /// <summary> - /// In the world after a login: not the login screen, not character select (where AC's window - /// is its small 800x600 one), not AC closing. A mode not seen yet counts as the world, as - /// elsewhere in the engine; the 30 s rule and the login-shrink guard cover that gap. - /// </summary> - private static bool InWorld() - => LoginLifecycleHooks.HasObservedLoginComplete - && UiFlowHooks.InWorldOrUnknown - && !UiFlowHooks.ClientCleanupStarted; - - private static bool KeyReady(long now, out string? key) - => TryResolveKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName, - _firstTickMs == 0 ? 0 : now - _firstTickMs, NoKeyFallbackMs, out key); - - private static string PlacementPath(string? key) + private static void TryRestorePlacement(IntPtr hwnd) { - string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - return Path.Combine(root, "RynthCore", PlacementFileName(key)); + _placementRestored = true; + if (!EngineSettings.RememberAcWindowPosition) return; + // Borderless restores its own rect (ApplyBorderlessDesired); the framed one would only + // move the window first. + if (Graphics.AcGraphics.WantBorderless) return; + int style = GetWindowLong(hwnd, GwlStyle); + if (IsLikelyExclusiveFullscreen(hwnd, style)) return; + + if (ReadPlacementFile().Framed is not RECT saved) return; + // Only the saved position is the player's: the size always comes from the resolution AC is + // really drawing at (its back buffer, else what it launched with), so a size saved at another resolution + // or at the login screen can't shrink the window. + bool sized = TryFramedSizeForResolution(hwnd, style, out int rw, out int rh); + RECT r = sized + ? new RECT { Left = saved.Left, Top = saved.Top, Right = saved.Left + rw, Bottom = saved.Top + rh } + : saved; + // Without a known resolution, a rect saved at the character-select screen (800x600 game + // area, before 2026.10.17.8) isn't the player's window: restoring it shrank the world window. + if (!sized && SavedClientIsLoginSize(hwnd, r)) + { + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: ignoring saved placement {Width(r)}x{Height(r)} (AC's 800x600 login-screen size); leaving AC's own size.")); + return; + } + // Keep the restored rect on a visible monitor so a missing display does not + // park the client off-screen. + if (!IsRectOnAnyMonitor(r)) + { + RynthLog.UI("AcWindowChrome: saved placement is off-screen; leaving AC where it is."); + return; + } + + // AC anchors its toolbar to the window's bottom-right: a saved rect bigger than this + // monitor (another PC, a lower resolution, a torn read) parked it off-screen. + RECT fitted = FitToWorkArea(r); + MoveTo(hwnd, fitted); + string note = SameRect(fitted, r) ? "" + : FormattableString.Invariant($" (saved {Width(r)}x{Height(r)} at ({r.Left},{r.Top}) didn't fit the screen)"); + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: restored AC window to ({fitted.Left},{fitted.Top}) {Width(fitted)}x{Height(fitted)}{note}.")); } - private static int ReadMarker(IntPtr hwnd) => unchecked((int)GetProp(hwnd, StyleProp).ToInt64()); + /// <summary>AC's login / character-select window: an 800x600 game area.</summary> + private static bool IsLoginScreenSize(int clientW, int clientH) => clientW == 800 && clientH == 600; - private static bool PlacementDone(IntPtr hwnd) => GetProp(hwnd, PlacementDoneProp) != IntPtr.Zero; + /// <summary>True when the saved framed rect <paramref name="saved"/> holds an 800x600 game area + /// with this window's frame (the frame size is taken from the window as it is now).</summary> + private static bool SavedClientIsLoginSize(IntPtr hwnd, RECT saved) + { + if (!GetWindowRect(hwnd, out RECT wr) || !GetClientRect(hwnd, out RECT cr)) return false; + if ((GetWindowLong(hwnd, GwlStyle) & WsCaption) == 0) return false; + int frameW = Width(wr) - Width(cr), frameH = Height(wr) - Height(cr); + return IsLoginScreenSize(Width(saved) - frameW, Height(saved) - frameH); + } + + /// <summary><paramref name="r"/> moved, and shrunk if needed, to lie inside the work area of the + /// monitor holding its centre, so no edge of the window (or AC's toolbar) is off-screen.</summary> + private static RECT FitToWorkArea(RECT r) + { + var pt = new POINT { X = r.Left + Width(r) / 2, Y = r.Top + Height(r) / 2 }; + if (!TryMonitorInfo(MonitorFromPoint(pt, 2 /* MONITOR_DEFAULTTONEAREST */), out _, out RECT work)) return r; + int w = Math.Min(Width(r), Width(work)); + int h = Math.Min(Height(r), Height(work)); + int left = Math.Clamp(r.Left, work.Left, work.Right - w); + int top = Math.Clamp(r.Top, work.Top, work.Bottom - h); + return new RECT { Left = left, Top = top, Right = left + w, Bottom = top + h }; + } + + /// <summary>ac_window.txt: the framed rect (left/top/width/height, as before) and the + /// borderless rect (bl_ keys). Either may be missing.</summary> + private struct Placement + { + public RECT? Framed; + public RECT? Borderless; + } + + private static Placement ReadPlacementFile() + { + var p = new Placement(); + string path = PlacementPath; + if (!File.Exists(path)) return p; + + int left = 0, top = 0, width = 0, height = 0; + int bl = 0, bt = 0, bw = 0, bh = 0; + try + { + // Every client on the PC shares this file: read with sharing on, so a read never + // fails because another client has it open. + string text; + using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (var sr = new StreamReader(fs)) + text = sr.ReadToEnd(); + foreach (string raw in text.Split('\n')) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim().ToLowerInvariant(); + string val = line[(eq + 1)..].Trim(); + if (!int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) continue; + switch (key) + { + case "left": left = n; break; + case "top": top = n; break; + case "width": width = n; break; + case "height": height = n; break; + case "bl_left": bl = n; break; + case "bl_top": bt = n; break; + case "bl_width": bw = n; break; + case "bl_height": bh = n; break; + } + } + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: read placement failed - {ex.Message}"); } catch { } + return p; + } + + if (width >= 160 && height >= 120) + p.Framed = new RECT { Left = left, Top = top, Right = left + width, Bottom = top + height }; + if (bw >= 160 && bh >= 120) + p.Borderless = new RECT { Left = bl, Top = bt, Right = bl + bw, Bottom = bt + bh }; + return p; + } + + private static bool WritePlacementFile(Placement p) + { + try + { + string path = PlacementPath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + var sb = new System.Text.StringBuilder("# RynthCore AC window placement — auto-generated.\n"); + if (p.Framed is RECT f) + sb.Append(FormattableString.Invariant( + $"left={f.Left}\ntop={f.Top}\nwidth={Width(f)}\nheight={Height(f)}\n")); + if (p.Borderless is RECT b) + sb.Append(FormattableString.Invariant( + $"bl_left={b.Left}\nbl_top={b.Top}\nbl_width={Width(b)}\nbl_height={Height(b)}\n")); + string text = sb.ToString(); + + // Every client saves every 10 s: skip a write that changes nothing, so clients + // rarely touch the shared file at all. + if (ReadPlacementText(path) == text) return true; + + // Write a temp file and swap it in, so another client never reads a half-written + // file (a torn read restored a wrong rect). A sharing clash is retried, then left + // for the next save. + string tmp = FormattableString.Invariant($"{path}.{Environment.ProcessId}.tmp"); + File.WriteAllText(tmp, text); + for (int attempt = 0; ; attempt++) + { + try + { + File.Move(tmp, path, overwrite: true); + return true; + } + catch (IOException) when (attempt < 3) + { + System.Threading.Thread.Sleep(15); + } + catch (UnauthorizedAccessException) when (attempt < 3) + { + System.Threading.Thread.Sleep(15); + } + } + } + catch (Exception ex) + { + try { File.Delete(FormattableString.Invariant($"{PlacementPath}.{Environment.ProcessId}.tmp")); } catch { } + try { RynthLog.UI($"AcWindowChrome: save placement failed - {ex.Message}"); } catch { } + return false; + } + } + + /// <summary>The placement file's text (shared read), or null when missing or unreadable.</summary> + private static string? ReadPlacementText(string path) + { + try + { + if (!File.Exists(path)) return null; + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var sr = new StreamReader(fs); + return sr.ReadToEnd(); + } + catch { return null; } + } /// <summary>Game HWND for Settings toggles (EntryPoint, else Win32Backend).</summary> internal static IntPtr ResolveGameHwndForSettings() => ResolveGameHwnd(); @@ -406,49 +723,31 @@ internal static class AcWindowChrome try { return ImGuiBackend.Win32Backend.GameHwnd; } catch { return IntPtr.Zero; } } - /// <summary>True when the outer rect fills a monitor and has no caption: exclusive fullscreen or - /// an already borderless fullscreen; do not fight it.</summary> - private static bool LooksExclusiveFullscreen(IntPtr hwnd, int style) + /// <summary>True when the outer rect fills a monitor and has no caption — exclusive + /// fullscreen or already-borderless fullscreen; do not fight it.</summary> + private static bool IsLikelyExclusiveFullscreen(IntPtr hwnd, int style) { if ((style & WsCaption) != 0) return false; if (!GetWindowRect(hwnd, out RECT wr)) return false; - IntPtr mon = MonitorFromWindow(hwnd, 2 /* MONITOR_DEFAULTTONEAREST */); - if (mon == IntPtr.Zero) return false; - var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; - if (!GetMonitorInfo(mon, ref mi)) return false; - int mw = mi.rcMonitor.Right - mi.rcMonitor.Left; - int mh = mi.rcMonitor.Bottom - mi.rcMonitor.Top; - int ww = wr.Right - wr.Left; - int wh = wr.Bottom - wr.Top; - return Math.Abs(ww - mw) <= 4 && Math.Abs(wh - mh) <= 4 - && Math.Abs(wr.Left - mi.rcMonitor.Left) <= 4 - && Math.Abs(wr.Top - mi.rcMonitor.Top) <= 4; + if (!TryMonitorRect(hwnd, out RECT mon, out _)) return false; + return Math.Abs(Width(wr) - Width(mon)) <= 4 && Math.Abs(Height(wr) - Height(mon)) <= 4 + && Math.Abs(wr.Left - mon.Left) <= 4 + && Math.Abs(wr.Top - mon.Top) <= 4; } - private static List<Rect> Monitors() => EnumMonitors(work: false); - - /// <summary>Each monitor's work area (the screen minus the taskbar): where a restored window is pulled onto.</summary> - private static List<Rect> WorkAreas() => EnumMonitors(work: true); - - private static List<Rect> EnumMonitors(bool work) + private static bool IsRectOnAnyMonitor(RECT r) { - var list = new List<Rect>(4); - EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (IntPtr mon, IntPtr dc, ref RECT rc, IntPtr data) => - { - var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; - if (GetMonitorInfo(mon, ref mi)) - { - RECT m = work ? mi.rcWork : mi.rcMonitor; - list.Add(new Rect(m.Left, m.Top, m.Right, m.Bottom)); - } - return true; - }, IntPtr.Zero); - return list; + // Probe the center of the saved rect; if no monitor claims it, skip restore. + var pt = new POINT { X = r.Left + Width(r) / 2, Y = r.Top + Height(r) / 2 }; + return MonitorFromPoint(pt, 0 /* MONITOR_DEFAULTTONULL */) != IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] + private struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] private struct MONITORINFO { @@ -458,8 +757,6 @@ internal static class AcWindowChrome public uint dwFlags; } - private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData); - [DllImport("user32.dll")] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); @@ -474,26 +771,20 @@ internal static class AcWindowChrome private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] - private static extern bool IsIconic(IntPtr hWnd); + private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] - private static extern bool IsZoomed(IntPtr hWnd); + private static extern bool AdjustWindowRectEx(ref RECT lpRect, int dwStyle, bool bMenu, int dwExStyle); + + [DllImport("user32.dll")] + private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint); [DllImport("user32.dll")] private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); + [DllImport("user32.dll")] + private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags); + [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi); - - [DllImport("user32.dll")] - private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern bool SetProp(IntPtr hWnd, string lpString, IntPtr hData); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr GetProp(IntPtr hWnd, string lpString); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr RemoveProp(IntPtr hWnd, string lpString); } diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index a2da693..32a9553 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -753,7 +753,15 @@ internal static class AvaloniaOverlay StringComparison.Ordinal); UseCustomSkiaBridge = customBridgeRequested || (UseAnglePreferredBridge && !customBridgeDisabled); - if (UseAnglePreferredBridge) + // DXVK / drop-in d3d9: shared D3D9Ex HANDLEs are unreliable — stay on LockRect. + D3D9.DxvkDetection.EnsureProbed(); + if (D3D9.DxvkDetection.IsDxvk || D3D9.DxvkDetection.IsNonSystemD3d9) + { + UseAnglePreferredBridge = false; + UseCustomSkiaBridge = false; + D3D9.DxvkDetection.ApplyOverlayPolicy(); + } + else if (UseAnglePreferredBridge) OverlaySurfaceBridge.UseAngleStub(); else OverlaySurfaceBridge.UseSoftwareFallback(); @@ -1439,8 +1447,8 @@ internal class RynthOverlayWindow : Window Foreground = Brushes.Khaki, Margin = new Thickness(8, 0, 0, 0), }); - ToolTip.SetTip(reloadBtn, "Engine reload — shut down, FreeLibrary, reload from disk, re-init."); - reloadBtn.Click += (_, _) => EngineLifecycle.SignalReload(); + ToolTip.SetTip(reloadBtn, "Engine reload. While in-world it waits until logout / character select."); + reloadBtn.Click += (_, _) => EntryPoint.RequestManualReload("Avalonia RL"); stack.Children.Add(reloadBtn); // Register under a special key so RefreshHitTestSnapshot publishes // its rect to Win32Backend — without this, clicks over RL fall diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 69b7adf..d527f5a 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -25,7 +25,10 @@ // add up; the first matching Move or Hide decides and stops the routing. The // first matching line colour wins, and so does the first matching highlight // (on its own: a line can have both); matched-text colours add up, a higher -// rule winning where two overlap. +// rule winning where two overlap. After the rules and the standard filters, +// automated system text (2026-10-19: RynthChat's "auto" - /myquests and /qb +// list replies, the login burst, lines a plugin ate) that nothing placed +// shows in the System tab only (AutomatedToSystem). // // Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line // once, and every kept line again when the rules change (in 8 ms slices, newest @@ -94,8 +97,7 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]> protected internal override void Poll() { - // Another client saved the shared settings: pick up its rules / filters (every 2 s at most). - ChatModel.PollSettingsFile(); + // The shared settings file is checked by UiDataHub every step (ChatModel.PollSettingsFile). try { PollLines(); } finally { @@ -172,6 +174,8 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]> dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text) { Seq = dto.Seq, + Automated = dto.Auto, + ReplyTab = ChatModel.ReplyTabs.TabFor(dto.Chan ?? "Other", dto.Auto, Environment.TickCount64), OwnArgb = ownArgb, OwnSpans = ChatOwnColors.ArrivedSpans(ownSpans, dto.Text, text), }; @@ -186,7 +190,7 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]> } ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>(); - Publish(ChatHistory.Merge(old, added, maxLines)); + Publish(ChatHistory.Merge(old, added, maxLines, IsAutomated)); ChatModel.PumpLog(added); RelayRead(added); } @@ -232,11 +236,14 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]> return lo - 1; } + /// <summary>Automated system text (/myquests replies, lines a plugin ate) is kept on its own budget.</summary> + private static bool IsAutomated(ChatLine line) => line.Automated; + /// <summary>The setting was lowered: drop the oldest kept lines now, not only when new ones arrive.</summary> private void TrimToLength(int maxLines) { ChatLine[]? kept = Current?.Value; - if (kept != null && ChatHistory.Trim(kept, maxLines) is { } trimmed) Publish(trimmed); + if (kept != null && ChatHistory.Keep(kept, maxLines, IsAutomated) is { } trimmed) Publish(trimmed); } /// <summary>Tells RynthChat (0.3.0+) the history length once it's bound and whenever the setting moves.</summary> @@ -429,6 +436,20 @@ internal static class ChatModel /// just RynthChat's (ShouldHideInRetail, from PluginManager's held-line verdict). /// </summary> public static volatile bool HideInRetailChat = true; + /// <summary> + /// Automated system text (the /myquests and /qb list replies, the login burst, lines a + /// plugin ate; ChatLine.Automated) shows in the System tab only, not under All. On by + /// default; a rule or standard filter that routes such a line still decides first. + /// </summary> + public static volatile bool AutomatedToSystem = true; + + /// <summary>Turns <see cref="AutomatedToSystem"/> on or off: the kept lines are routed again, and it saves.</summary> + public static void SetAutomatedToSystem(bool on) + { + if (on == AutomatedToSystem) return; + AutomatedToSystem = on; + FiltersChanged(); + } /// <summary>A short system beep on a new mention (at most every 3 s).</summary> public static volatile bool MentionSound; /// <summary>Extra words to highlight, comma-separated.</summary> @@ -633,11 +654,14 @@ internal static class ChatModel return AllTabs().Contains(active, StringComparer.OrdinalIgnoreCase) ? active : "All"; } + /// <summary> + /// Switches this client's tab. Not saved on its own: the file is every client's, so a tab + /// click rewrote everyone's rules. The tab is written with this client's next real change. + /// </summary> public static void SelectTab(string tab) { if (string.Equals(ActiveChannel, tab, StringComparison.Ordinal)) return; ActiveChannel = tab; - SaveSettings(); } /// <summary>Creates a tab (or finds the existing one) and switches to it.</summary> @@ -714,7 +738,12 @@ internal static class ChatModel } /// <summary>Is the line shown under <paramref name="tab"/> (rules applied, no search)?</summary> - public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel); + public static bool LineInTab(ChatLine line, string tab) + => line.Route.ShowsIn(tab, line.Channel) + || (line.ReplyTab != null && !line.Route.Hidden && string.Equals(line.ReplyTab, tab, StringComparison.OrdinalIgnoreCase)); + + /// <summary>Where the reply to a command typed in the box also shows (ChatReplyTab).</summary> + internal static readonly ChatReplyTab ReplyTabs = new(); public static bool LineVisible(ChatLine line, string tab, string search) => LineInTab(line, tab) @@ -746,7 +775,7 @@ internal static class ChatModel long version = FiltersVersion; var cached = _pumpRouter; if (cached is { } c && c.Version == version && c.Name == name) return c.Router; - var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true); + var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true, AutomatedToSystem); _pumpRouter = (version, name, router); return router; } @@ -784,7 +813,7 @@ internal static class ChatModel { string name = SessionStateRegistry.LastCharacterName; if (string.IsNullOrWhiteSpace(name)) name = _pumpName ?? ""; - return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false); + return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false, AutomatedToSystem); } private static Regex? BuildMentionRegex(string name) @@ -1149,6 +1178,8 @@ internal static class ChatModel SetInput("", 0, null); IntPtr send = SendLinePtr; if (text.Length == 0 || send == IntPtr.Zero) return; + // A /command's reply (System or Rynth text) also shows in the tab it was typed in. + ReplyTabs.NoteSent(text, CurrentTab(), Environment.TickCount64); IntPtr ptr = Marshal.StringToHGlobalAnsi(text); // RynthChat sends the line through Host.InvokeChatParser, on this thread: an engine /rc // command in it is the player's, so it answers in chat (RynthCoreChatCommands.PlayerLine). @@ -1367,13 +1398,30 @@ internal static class ChatModel // last write, so its own saves don't count as a change. private static readonly SharedFileWatch SettingsWatch = new(pollMs: 2000); + // The settings text this client's settings in memory come from (its last load, or its own + // last write): the base a save merges against when another client changed the file in + // between (ChatSettingsMerge). + private static string? _baseJson; + // A save that took in another client's settings: applied here on the pump thread at the next poll, + // unless this client asked for a newer save since (that save merges again and carries its change). + private sealed record PendingReload(string Json, long SaveSeq); + private static PendingReload? _pendingReload; + private static long _saveSeq; + /// <summary> - /// Pump thread (ChatSource.Poll): reloads the settings when another client saved the file. - /// Rules, standard filters, tabs and display options follow; this client's selected tab stays. + /// Pump thread (UiDataHub, every step, chat window open or not): reloads the settings when + /// another client saved the file. Rules, standard filters, tabs and display options follow; + /// this client's selected tab stays. /// </summary> internal static void PollSettingsFile() { if (Volatile.Read(ref _settingsLoaded) == 0) return; + PendingReload? merged = Interlocked.Exchange(ref _pendingReload, null); + if (merged != null && merged.SaveSeq == Interlocked.Read(ref _saveSeq)) + { + RynthLog.UI("ChatModel: a save took in another client's chat settings; applying them here too."); + LoadSettings(merged.Json, reload: true); + } try { string? json = SettingsWatch.Changed(Environment.TickCount64, SettingsPath); // null: nobody else saved @@ -1431,6 +1479,7 @@ internal static class ChatModel ShowTimestamps = dto.ShowTimestamps; MentionHighlight = dto.MentionHighlight; HideInRetailChat = dto.HideInRetail ?? true; // absent before 2026-10-16: on + AutomatedToSystem = dto.AutomatedToSystem ?? true; // absent before 2026-10-19: on MentionSound = dto.MentionSound; MentionWords = dto.MentionWords ?? ""; HistoryLines = ChatHistory.Clamp(dto.HistoryLines ?? 0); // absent before 2026-10-11: the default @@ -1478,6 +1527,7 @@ internal static class ChatModel ActiveChannel = dto.ActiveChannel; else if (reload && !AllTabs().Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = "All"; // the tab this client was on was removed elsewhere + Volatile.Write(ref _baseJson, json); } catch (Exception ex) when (reload) { @@ -1520,6 +1570,7 @@ internal static class ChatModel ShowTimestamps = ShowTimestamps, MentionHighlight = MentionHighlight, HideInRetail = HideInRetailChat, + AutomatedToSystem = AutomatedToSystem, MentionSound = MentionSound, MentionWords = MentionWords, // Left out at the default, so a file follows the default if it ever changes. @@ -1535,6 +1586,10 @@ internal static class ChatModel .Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab.Length > 0 ? p.Tab : null }) .ToArray(), }; + // The base is taken with the settings, not at write time: a reload of another client's file + // between this call and the write must not make these (older) settings look current. + string? baseJson = Volatile.Read(ref _baseJson); + long seq = Interlocked.Increment(ref _saveSeq); UiBackgroundWriter.Enqueue("persist chat settings", () => { lock (SaveLock) @@ -1547,11 +1602,19 @@ internal static class ChatModel string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file try { - string json = JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto); + string mine = JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto); + string json = MergeWithFile(path, mine, baseJson); // Before the swap: PollSettingsFile must see this text as ours, not another client's. SettingsWatch.Saved(json); File.WriteAllText(tmp, json); File.Move(tmp, path, overwrite: true); + // The base is what this client's settings in memory come from. Its own settings + // written as they are: those. A merge: memory doesn't have the other client's part + // until PollSettingsFile applies it (LoadSettings then moves the base). + if (string.Equals(json, mine, StringComparison.Ordinal)) + Volatile.Write(ref _baseJson, json); + else + Volatile.Write(ref _pendingReload, new PendingReload(json, seq)); } catch { @@ -1561,4 +1624,31 @@ internal static class ChatModel } }); } + + /// <summary> + /// Writer thread, under SaveLock: <paramref name="mine"/>, or a merge with the file when another + /// client saved it after <paramref name="baseJson"/> (this client's last load or write when the + /// save was asked for; ChatSettingsMerge). A file that can't be read, or a merge that doesn't + /// load back as settings, leaves <paramref name="mine"/>. + /// </summary> + private static string MergeWithFile(string path, string mine, string? baseJson) + { + if (baseJson == null || !File.Exists(path)) return mine; + string theirs; + try { theirs = File.ReadAllText(path); } + catch (Exception ex) + { + RynthLog.UI($"ChatModel: couldn't read the settings before saving ({ex.GetType().Name}); saving this client's."); + return mine; + } + string merged = ChatSettingsMerge.Merge(baseJson, mine, theirs); + if (string.Equals(merged, mine, StringComparison.Ordinal)) return mine; + try + { + if (JsonSerializer.Deserialize(merged, RynthChatJsonContext.Default.RynthChatSettingsDto) == null) return mine; + } + catch (JsonException) { return mine; } + RynthLog.UI("ChatModel: another client changed the chat settings since this one read them; saved this client's change on top of theirs."); + return merged; + } } diff --git a/src/RynthCore.Engine/UI/Data/ChatHistory.cs b/src/RynthCore.Engine/UI/Data/ChatHistory.cs index 59e8910..986579f 100644 --- a/src/RynthCore.Engine/UI/Data/ChatHistory.cs +++ b/src/RynthCore.Engine/UI/Data/ChatHistory.cs @@ -67,4 +67,45 @@ internal static class ChatHistory Array.Copy(lines, lines.Length - max, kept, 0, max); return kept; } + + /// <summary> + /// The newest <paramref name="max"/> ordinary lines and, on their own budget, the newest + /// <paramref name="max"/> <paramref name="extra"/> ones (automated system text: a /myquests + /// reply is 2,000+ lines on a well-played character, and on the shared budget each of the + /// Meta Manager's polls pushed every line people read out of the history, 2026-10-24), + /// in their order. Null when nothing is dropped. + /// </summary> + public static T[]? Keep<T>(IReadOnlyList<T> lines, int max, Func<T, bool> extra) + { + max = Math.Max(1, max); + if (lines.Count <= max) return null; + int normal = 0, auto = 0, from = lines.Count; + var keep = new bool[lines.Count]; + int kept = 0; + for (int i = lines.Count - 1; i >= 0; i--) + { + bool x = extra(lines[i]); + if (x ? auto >= max : normal >= max) continue; + if (x) auto++; else normal++; + keep[i] = true; + kept++; + from = i; + if (normal >= max && auto >= max) break; + } + if (kept == lines.Count) return null; + var result = new T[kept]; + int w = 0; + for (int i = from; i < lines.Count; i++) + if (keep[i]) result[w++] = lines[i]; + return result; + } + + /// <summary><see cref="Merge{T}"/> with automated lines on their own budget (<see cref="Keep{T}"/>).</summary> + public static T[] Merge<T>(T[] old, IReadOnlyList<T> added, int max, Func<T, bool> extra) + { + var all = new T[old.Length + added.Count]; + Array.Copy(old, all, old.Length); + for (int i = 0; i < added.Count; i++) all[old.Length + i] = added[i]; + return Keep(all, max, extra) ?? all; + } } diff --git a/src/RynthCore.Engine/UI/Data/ChatReplyTab.cs b/src/RynthCore.Engine/UI/Data/ChatReplyTab.cs new file mode 100644 index 0000000..8058c6e --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatReplyTab.cs @@ -0,0 +1,73 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatReplyTab.cs +// Shows the reply to a command typed in RynthChat's box in the tab it was typed in. +// +// The server's reply to a /command is system text (ACE's ChatMessageType.Broadcast) +// and a plugin's reply is "[Rynth...]" output, so RynthChat files them under System +// and Rynth: they showed only in All and those tabs. Silentkelpie (2026-10-24) typed +// /fship on another tab and saw nothing: the seven "[FSHIP]: use /fship ..." lines +// were under All. A slash command sent from the box now marks this client's tab for +// WindowMs; System and Rynth lines arriving in that time also show in it. +// +// Not for chat (/say, /tell, /f, /a, emotes: those land in Chat as typed), from All +// (it shows everything), or for automated lines (a plugin's own polls, the login burst). +// Pure: tools/ChatFilterTests compiles this file. NoteSent runs on AC's main thread, +// TabFor on the pump thread: the window is one immutable record swapped in whole. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class ChatReplyTab +{ + /// <summary>How long after a command its replies also go to the tab it was typed in.</summary> + public const long WindowMs = 5000; + + /// <summary>Channels a command's reply arrives in (RynthChat's ChatClassifier): the server's, a plugin's.</summary> + public const string SystemChannel = "System", RynthChannel = "Rynth"; + + // Commands that are chat: AC files what they say under Chat (or a channel) already. + private static readonly string[] ChatVerbs = + { + "/say", "/s", "/tell", "/t", "/reply", "/r", "/retell", "/rt", "/f", "/a", + "/emote", "/e", "/me", "/em", "/general", "/trade", "/lfg", "/roleplay", "/society", + }; + + private sealed record Window(string Tab, long UntilMs); + private Window? _window; + + /// <summary>A slash command that isn't chat: "/fship", "/bank d", "/ra hub", "@help".</summary> + public static bool IsCommand(string? text) + { + string t = (text ?? "").Trim(); + if (t.Length < 2 || (t[0] != '/' && t[0] != '@')) return false; + int sp = t.IndexOf(' '); + string verb = "/" + (sp < 0 ? t[1..] : t[1..sp]); + foreach (string chat in ChatVerbs) + if (verb.Equals(chat, StringComparison.OrdinalIgnoreCase)) return false; + return true; + } + + /// <summary>The player sent <paramref name="text"/> from <paramref name="tab"/>. AC's main thread.</summary> + public void NoteSent(string? text, string tab, long nowMs) + { + if (!IsCommand(text) || string.IsNullOrEmpty(tab) || tab.Equals("All", StringComparison.OrdinalIgnoreCase)) + return; + Volatile.Write(ref _window, new Window(tab, nowMs + WindowMs)); + } + + /// <summary> + /// The tab a line arriving now also shows in, or null. Only System and Rynth lines, never an + /// automated one, and not when the command was typed in the line's own channel tab. + /// </summary> + public string? TabFor(string channel, bool automated, long nowMs) + { + Window? w = Volatile.Read(ref _window); + if (w == null || automated || nowMs > w.UntilMs) return null; + if (!channel.Equals(SystemChannel, StringComparison.OrdinalIgnoreCase) + && !channel.Equals(RynthChannel, StringComparison.OrdinalIgnoreCase)) return null; + return channel.Equals(w.Tab, StringComparison.OrdinalIgnoreCase) ? null : w.Tab; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 8decf42..2db507d 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -41,6 +41,18 @@ internal sealed class ChatLine /// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not /// from RynthChat. The Discord relay tells news from scrollback by it.</summary> public ulong Seq { get; init; } + + /// <summary> + /// Automated system text (RynthChat's "auto", 0.3.4+): a reply to a plugin's own command, + /// the login burst, or a line a plugin ate. Unless a rule or standard filter routes it, it + /// shows in the System tab only (ChatModel.AutomatedToSystem). + /// </summary> + public bool Automated { get; init; } + /// <summary> + /// The tab a /command was typed in when this line (its reply) arrived: it shows there too, + /// unless a rule hides it (ChatReplyTab, ChatModel.LineInTab). Null for most lines. + /// </summary> + public string? ReplyTab { get; init; } public string Timestamp { get; } /// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary> public string Channel { get; } @@ -307,22 +319,28 @@ internal sealed class ChatRouter /// <summary>ChatMessageType Emote (0x0C).</summary> private const int EmoteType = 0x0C; + /// <summary>The tab automated system text goes to (and the only one it shows in).</summary> + public const string AutomatedTab = "System"; + private readonly ChatFilterRule[] _rules; private readonly Regex? _mention; private readonly string _self; private readonly bool _countHits; + private readonly bool _automatedToSystem; private readonly long[] _passTicks; private long _passBudgetTicks = PassBudgetTicks; private bool _inPass; /// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param> /// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param> - public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) + /// <param name="automatedToSystem">Automated system text no rule routed shows in <see cref="AutomatedTab"/> only.</param> + public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits, bool automatedToSystem = false) { _rules = rules; _mention = mention; _self = self.Trim(); _countHits = countHits; + _automatedToSystem = automatedToSystem; _passTicks = new long[rules.Length]; } @@ -367,10 +385,14 @@ internal sealed class ChatRouter /// <summary><see cref="Step.Rule"/> of a standard-filter (RynthChatPresets) step.</summary> public const int StandardFilterStep = -2; - public ChatRoute Evaluate(ChatLine line, List<Step>? trace) => - Evaluate(line.Text, line.Channel, line.ChatType, trace); + /// <summary><see cref="Step.Rule"/> of the automated-system-text step (shown in System only).</summary> + public const int AutomatedStep = -3; - public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace) + public ChatRoute Evaluate(ChatLine line, List<Step>? trace) => + Evaluate(line.Text, line.Channel, line.ChatType, trace, line.Automated); + + /// <param name="automated">The line is automated system text (ChatLine.Automated).</param> + public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace, bool automated = false) { bool hidden = false, inHome = true, routed = false; List<string>? tabs = null; @@ -487,6 +509,16 @@ internal sealed class ChatRouter } } + // Automated system text (/myquests, /qb list, the login burst, lines a plugin ate) + // that neither the rules nor a standard filter placed: the System tab only, not All. + if (!routed && automated && _automatedToSystem) + { + routed = true; + inHome = false; + AddTab(ref tabs, AutomatedTab); + trace?.Add(new Step(AutomatedStep, $"automated system text: shown in {AutomatedTab} only")); + } + bool mention = false; if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType)) { diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs index d3dfbf9..4e8fc8b 100644 --- a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -21,6 +21,8 @@ internal sealed class RynthChatLineDto [JsonPropertyName("type")] public int Type { get; set; } = -1; [JsonPropertyName("sender")] public string? Sender { get; set; } [JsonPropertyName("text")] public string Text { get; set; } = ""; + /// <summary>Automated system text (RynthChat 0.3.4+): shown in the System tab only. Absent = false.</summary> + [JsonPropertyName("auto")] public bool Auto { get; set; } } // Property names match the legacy hand-written JSON so existing settings load. @@ -59,6 +61,8 @@ internal sealed class RynthChatSettingsDto [JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true; /// <summary>Hidden lines are also kept out of AC's chat window; null (older files) = on.</summary> [JsonPropertyName("hideInRetail")] public bool? HideInRetail { get; set; } + /// <summary>Automated system text shows in the System tab only, not under All; null (older files) = on.</summary> + [JsonPropertyName("automatedToSystem")] public bool? AutomatedToSystem { get; set; } [JsonPropertyName("mentionSound")] public bool MentionSound { get; set; } [JsonPropertyName("mentionWords")] public string? MentionWords { get; set; } // 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... }; diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsMerge.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsMerge.cs new file mode 100644 index 0000000..66cc552 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsMerge.cs @@ -0,0 +1,75 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatSettingsMerge.cs +// Three-way merge of rynthchat_settings.json for a save that finds another +// client changed the file since this client last read it. +// +// Every client shares the file and saves its whole state. Before this merge, a +// client that hadn't picked up another client's change yet (its chat window was +// closed, so it never polled; or the change was under 2 s old) wrote its stale +// rules and standard filters back over it, and every other client then reloaded +// that stale copy: filters "came back", or switched off, on all clients. +// +// Per top-level setting (filters, presets, tabs, font size, colours, ...): the +// one this client changed since its base wins; one it left alone takes the file's. +// "filters" and "presets" are each one setting, so two clients editing rules at +// the same moment still end with the later save's list, but a client that only +// changed something else no longer undoes another client's rules. +// +// Pure (BCL only, no engine state): tools/ChatFilterTests compiles this file. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace RynthCore.Engine.UI.Data; + +internal static class ChatSettingsMerge +{ + /// <summary> + /// The settings to write. <paramref name="baseJson"/> is what this client last loaded or wrote, + /// <paramref name="mine"/> what it would save now, <paramref name="theirs"/> the file on disk. + /// Returns <paramref name="mine"/> unchanged when there is nothing to merge or any input + /// isn't a JSON object (a broken file is never merged into a save). + /// </summary> + public static string Merge(string? baseJson, string mine, string? theirs) + { + if (string.IsNullOrEmpty(baseJson) || string.IsNullOrEmpty(theirs)) return mine; + if (string.Equals(theirs, baseJson, StringComparison.Ordinal)) return mine; // nobody else saved + if (string.Equals(theirs, mine, StringComparison.Ordinal)) return mine; + + JsonObject? b = ParseObject(baseJson); + JsonObject? m = ParseObject(mine); + JsonObject? t = ParseObject(theirs); + if (b == null || m == null || t == null) return mine; + + // Keys in the order this client writes them, then any only the other client has. + var keys = new List<string>(); + foreach (var kv in m) keys.Add(kv.Key); + foreach (var kv in t) if (!m.ContainsKey(kv.Key)) keys.Add(kv.Key); + foreach (var kv in b) if (!m.ContainsKey(kv.Key) && !t.ContainsKey(kv.Key)) keys.Add(kv.Key); + + var merged = new JsonObject(); + foreach (string key in keys) + { + string? mineText = TextOf(m, key); + bool changedHere = !string.Equals(mineText, TextOf(b, key), StringComparison.Ordinal); + // Changed here: this client's value (absent = removed here). Else the file's. + JsonObject from = changedHere ? m : t; + if (from.TryGetPropertyValue(key, out JsonNode? node)) + merged[key] = node?.DeepClone(); + } + return merged.ToJsonString(); + } + + private static JsonObject? ParseObject(string json) + { + try { return JsonNode.Parse(json) as JsonObject; } + catch (JsonException) { return null; } + } + + /// <summary>The setting's JSON text (null when absent): two equal values compare equal.</summary> + private static string? TextOf(JsonObject obj, string key) + => obj.TryGetPropertyValue(key, out JsonNode? node) ? (node?.ToJsonString() ?? "null") : null; +} diff --git a/src/RynthCore.Engine/UI/Data/ItemToolData.cs b/src/RynthCore.Engine/UI/Data/ItemToolData.cs index 010b479..81ee0e5 100644 --- a/src/RynthCore.Engine/UI/Data/ItemToolData.cs +++ b/src/RynthCore.Engine/UI/Data/ItemToolData.cs @@ -48,6 +48,15 @@ internal sealed class GiveToolState [JsonPropertyName("status")] public string Status { get; set; } = string.Empty; [JsonPropertyName("running")] public bool Running { get; set; } [JsonPropertyName("given")] public int Given { get; set; } + // Amount (units a round, 0 = all) and Every (seconds between rounds, 0 = one round), 2026-11-15. + // AmountMax 0 = a RynthAi that predates them: the panel hides the two fields. + [JsonPropertyName("amount")] public int Amount { get; set; } + [JsonPropertyName("everySec")] public int EverySec { get; set; } + [JsonPropertyName("amountMax")] public int AmountMax { get; set; } + [JsonPropertyName("everyMax")] public int EveryMax { get; set; } + [JsonPropertyName("rounds")] public int Rounds { get; set; } + [JsonPropertyName("units")] public int Units { get; set; } + [JsonPropertyName("nextInSec")] public long NextInSec { get; set; } } [JsonSerializable(typeof(ItemToolSnapshot))] @@ -96,7 +105,7 @@ internal static unsafe class ItemToolCommands /// <summary> /// Posts one Item Tool command ("chest set", "chest key", "chest start", "chest stop", "relock N", - /// "giveitem", "givetarget", "give", "givestop"). Runs on the pump; RynthAi older than this build has no such + /// "giveitem", "givetarget", "give", "givestop", "giveamount N", "giveevery N"). Runs on the pump; RynthAi older than this build has no such /// export: the click is logged and dropped. /// </summary> public static void Send(string words) => UiDataHub.Post("Item Tool " + words, () => diff --git a/src/RynthCore.Engine/UI/Data/ItemsData.cs b/src/RynthCore.Engine/UI/Data/ItemsData.cs index ca47cc4..3929055 100644 --- a/src/RynthCore.Engine/UI/Data/ItemsData.cs +++ b/src/RynthCore.Engine/UI/Data/ItemsData.cs @@ -64,16 +64,31 @@ internal static unsafe class ItemsCommands { private static delegate* unmanaged[Cdecl]<IntPtr, void> _set; private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addShield, _addConsumable, _clean; + private static delegate* unmanaged[Cdecl]<uint, void> _addWeaponById; /// <summary>ItemRule.Action value the plugin uses for off-hand shields.</summary> public const string ShieldAction = "Shield"; static ItemsCommands() { - PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; _clean = null; }; + PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; _clean = null; _addWeaponById = null; }; } public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + + /// <summary> + /// Universal damage (2026-10-19): prismatic ammo deals every damage type, so RynthAi treats a + /// missile weapon or ammo set to it as whatever the target is weakest to (MissileAmmo.Universal). + /// </summary> + public const string Prismatic = "Prismatic"; + + /// <summary>The elements plus <see cref="Prismatic"/>: what a missile weapon or ammo can be set to.</summary> + public static readonly string[] MissileElements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether", Prismatic }; + + /// <summary>The element choices for a weapon of <paramref name="kind"/> (RynthAi's WeaponEntry.Kind): Prismatic only for missile weapons and ammo.</summary> + public static string[] ElementsFor(string? kind) => + string.Equals(kind, "Missile", StringComparison.OrdinalIgnoreCase) || string.Equals(kind, "Ammo", StringComparison.OrdinalIgnoreCase) + ? MissileElements : Elements; public static readonly string[] ConsumableTypes = { "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" }; private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name); @@ -97,6 +112,20 @@ internal static unsafe class ItemsCommands UiSources.Items.RequestRefresh(); }); + /// <summary> + /// Adds item <paramref name="id"/> (a weapon, wand or shield) to RynthAi's weapons: the ones the + /// Damage panel offers and combat may use. The Inventory panel's right-click (2026-10-25). + /// RynthAi says in chat what it did; one without the export (before 2026-10-25) is logged. + /// </summary> + public static void AddWeapon(uint id) => UiDataHub.Post("Items add weapon by id", () => + { + if (_addWeaponById == null) _addWeaponById = (delegate* unmanaged[Cdecl]<uint, void>)Export("RynthPluginAddWeaponById"); + if (_addWeaponById != null) _addWeaponById(id); + else RynthLog.UI("ItemsCommands: Add to Damage panel weapons unavailable - this RynthAi has no RynthPluginAddWeaponById."); + UiSources.Items.RequestRefresh(); + UiSources.Damage.RequestRefresh(); + }); + /// <summary> /// Adds the item selected in the inventory as an off-hand shield. RynthAi older than /// 0.6.20 has no such export: the click is logged and dropped. diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs index ee7361f..e95acd7 100644 --- a/src/RynthCore.Engine/UI/Data/LootEditData.cs +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -27,6 +27,8 @@ namespace RynthCore.Engine.UI.Data; internal sealed class LootEditStateDto { public long Revision { get; set; } + /// <summary>On Infinite Leaftide (added 2026-11-07): the vocabulary must say the same, else it is asked again.</summary> + public bool Ilt { get; set; } = true; public string Path { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty; public string Format { get; set; } = string.Empty; @@ -45,6 +47,8 @@ internal sealed class LootEditStateDto public List<LootEditRowDto> Rules { get; set; } = new(); /// <summary>"Add to loot profile" popup's rule (added 2026-10); null from an older RynthAi.</summary> public LootEditItemDraftDto? ItemDraft { get; set; } + /// <summary>The Inventory panel's "Filter like this" result (added 2026-10-24); null from an older RynthAi.</summary> + public LootEditItemFindDto? ItemFind { get; set; } } internal sealed class LootEditFileDto @@ -144,6 +148,61 @@ internal sealed class LootEditItemRequestDto /// <summary>The attribute checklist's choices (added 2026-10-18); null: every row at its default.</summary> public List<LootEditItemChoiceDto>? Choices { get; set; } public int Seq { get; set; } + /// <summary>A filter, not a rule to add (added 2026-10-24): item_preview without a loot profile; item_find filters.</summary> + public bool Find { get; set; } + /// <summary>item_find: <see cref="LootFindScopes"/>.</summary> + public string Scope { get; set; } = string.Empty; + /// <summary>item_find / find_refresh, scope inventory: the panel's items to judge.</summary> + public List<uint>? Candidates { get; set; } + /// <summary>No item (added 2026-10-24): the checklist lists every attribute (the panel's own filter).</summary> + public bool Blank { get; set; } + /// <summary>Blank: edit this rule of the open profile instead of adding one (added 2026-11-07); -1 adds.</summary> + public int EditIndex { get; set; } = -1; + public string EditName { get; set; } = string.Empty; + /// <summary>Spells and cantrips added from the standard lists (added 2026-10-24).</summary> + public List<LootEditItemExtraDto>? Extras { get; set; } +} + +/// <summary>A spell picked from the standard lists (LootEditWire's LootEditItemExtra).</summary> +internal sealed class LootEditItemExtraDto +{ + public const string Spell = "spell", Cantrip = "cantrip"; + public string Kind { get; set; } = Spell; + /// <summary>The family ("Strength") or the cantrip without its tier ("Coordination").</summary> + public string Name { get; set; } = string.Empty; + /// <summary>Spell: level 1-8. Cantrip: tier index (0 Minor ... 4 Paragon).</summary> + public int Level { get; set; } + public int Op { get; set; } = -1; +} + +/// <summary>Where "Filter like this" looks (LootEditWire's LootFindScopes).</summary> +internal static class LootFindScopes +{ + public const string Inventory = "inventory"; + public const string Global = "global"; +} + +/// <summary>"Filter like this": the rule and, for the panel's items, which match (LootEditWire's LootEditItemFind).</summary> +internal sealed class LootEditItemFindDto +{ + public int Seq { get; set; } + public bool Ok { get; set; } + public string Error { get; set; } = string.Empty; + public string Scope { get; set; } = string.Empty; + public uint ItemId { get; set; } + public string ItemName { get; set; } = string.Empty; + /// <summary>"like Gold Ring".</summary> + public string Label { get; set; } = string.Empty; + /// <summary>The conditions in words.</summary> + public List<string> Lines { get; set; } = new(); + /// <summary>Scope inventory: the candidates the rule takes.</summary> + public List<uint> Ids { get; set; } = new(); + /// <summary>Scope inventory: candidates it can't judge until they are identified.</summary> + public List<uint> Unknown { get; set; } = new(); + public int Checked { get; set; } + /// <summary>Scope global: the "/ginv like" argument.</summary> + public string Spec { get; set; } = string.Empty; + public bool NeedsIdentify { get; set; } } /// <summary>One checklist row as the player set it (LootEditWire's LootEditItemChoice).</summary> @@ -170,19 +229,29 @@ internal sealed class LootEditItemAttributeDto public bool Editable { get; set; } public bool On { get; set; } public string Tip { get; set; } = string.Empty; + /// <summary>The values a named row can take (added 2026-10-24): a list, the picked Id sent as the Value.</summary> + public List<LootEditNameDto>? Choices { get; set; } + /// <summary>The Choices are flags: "has any" / "has all" pick several (added 2026-11-07).</summary> + public bool Flags { get; set; } } /// <summary>The checklist's comparison codes (LootSdk LootItemAttributeOp) and how the popup labels them.</summary> internal static class LootAttrOps { - public const int AtLeast = 0, Exactly = 1, AtMost = 2, Not = 3, SpellExact = 10, SpellOrBetter = 11, SpellAnyTier = 12; + public const int AtLeast = 0, Exactly = 1, AtMost = 2, Not = 3, HasAny = 4, Any = 5, HasAll = 6, SpellExact = 10, SpellOrBetter = 11, SpellAnyTier = 12; + + /// <summary>The ops that pick several flags at once (the value is their sum).</summary> + public static bool PicksSeveral(int op) => op is HasAny or HasAll; public static string Label(int op) => op switch { - AtLeast => ">=", - Exactly => "=", - AtMost => "<=", - Not => "not", + AtLeast => "at least", + Exactly => "is", + AtMost => "at most", + Not => "is not", + HasAny => "has any", + Any => "any", + HasAll => "has all", SpellExact => "exact", SpellOrBetter => "or better", SpellAnyTier => "any tier", @@ -224,10 +293,18 @@ internal sealed class LootEditItemDraftDto public List<LootEditItemAttributeDto> Attributes { get; set; } = new(); public bool Added { get; set; } public string Message { get; set; } = string.Empty; + /// <summary>A filter's draft (added 2026-10-24).</summary> + public bool Find { get; set; } + /// <summary>A new rule from the blank checklist (added 2026-11-07; false from an older RynthAi).</summary> + public bool Blank { get; set; } + /// <summary>The rule this draft edits, -1 when it adds one (added 2026-11-07).</summary> + public int EditIndex { get; set; } = -1; } internal sealed class LootEditVocabDto { + /// <summary>Built for Infinite Leaftide: the ACECustom keys are offered (added 2026-11-07; true from an older RynthAi).</summary> + public bool Ilt { get; set; } = true; public List<LootEditNameDto> Actions { get; set; } = new(); public List<LootEditNodeTypeDto> NodeTypes { get; set; } = new(); public List<LootEditNameDto> ObjectClasses { get; set; } = new(); @@ -237,6 +314,18 @@ internal sealed class LootEditVocabDto public List<LootEditNameDto> Skills { get; set; } = new(); /// <summary>Names for long keys' values (added 2026-10); empty from an older RynthAi (the value stays a text box).</summary> public List<LootEditValueTableDto> LongValueTables { get; set; } = new(); + /// <summary>The standard spell lists (added 2026-10-24); empty from an older RynthAi.</summary> + public List<LootEditSpellFamilyDto> SpellFamilies { get; set; } = new(); + public List<string> Cantrips { get; set; } = new(); + public List<string> CantripTiers { get; set; } = new(); +} + +internal sealed class LootEditSpellFamilyDto +{ + public string Name { get; set; } = string.Empty; + public string School { get; set; } = string.Empty; + public int MinLevel { get; set; } = 1; + public int MaxLevel { get; set; } = 8; } internal sealed class LootEditNameDto @@ -297,6 +386,7 @@ internal sealed unsafe class LootEditSource : UiSource<LootEditView> private LootEditRuleDto? _rule; private int _ruleIndex = -1, _ruleRevision; private int _wantRule = -1; + private long _vocabRetryAt; public LootEditSource() : base("LootEdit", periodMs: 1000) { } @@ -323,10 +413,16 @@ internal sealed unsafe class LootEditSource : UiSource<LootEditView> } bool changed = false; - if (_vocab == null) + // The spell lists arrive once RynthAi has read its spell table: ask again until they do. + if (_vocab == null || (_vocab.SpellFamilies.Count == 0 && Environment.TickCount64 >= _vocabRetryAt)) { - _vocab = Parse(_getVocab(), LootEditJsonContext.Default.LootEditVocabDto); - changed |= _vocab != null; + _vocabRetryAt = Environment.TickCount64 + 10_000; + LootEditVocabDto? v = Parse(_getVocab(), LootEditJsonContext.Default.LootEditVocabDto); + if (v != null && (_vocab == null || v.SpellFamilies.Count > 0)) + { + _vocab = v; + changed = true; + } } int revision = _revision(); @@ -340,6 +436,12 @@ internal sealed unsafe class LootEditSource : UiSource<LootEditView> // The list call may have opened the profile (first look): the state's own revision is current. _lastRevision = unchecked((int)state.Revision); changed = true; + // Moved to or from Leaftide: the pickers' keys change with it. + if (_vocab != null && _vocab.Ilt != state.Ilt) + { + LootEditVocabDto? v = Parse(_getVocab(), LootEditJsonContext.Default.LootEditVocabDto); + if (v != null) _vocab = v; + } } } diff --git a/src/RynthCore.Engine/UI/Data/ProgressionData.cs b/src/RynthCore.Engine/UI/Data/ProgressionData.cs index 62af741..5e17750 100644 --- a/src/RynthCore.Engine/UI/Data/ProgressionData.cs +++ b/src/RynthCore.Engine/UI/Data/ProgressionData.cs @@ -104,6 +104,11 @@ internal sealed class AugPlanner [JsonPropertyName("totCoins")] public long TotalCoins { get; set; } [JsonPropertyName("coinsLine")] public string CoinsLine { get; set; } = ""; [JsonPropertyName("lumToBuy")] public string LumToBuy { get; set; } = ""; + // STILL NEEDED row (RynthILT 0.2.23+; empty from older): the plan's luminance less banked and + // character luminance, the e-coins still short, and the line that spells it out. + [JsonPropertyName("stillLum")] public string StillLum { get; set; } = ""; + [JsonPropertyName("stillCoins")] public long StillCoins { get; set; } + [JsonPropertyName("stillLine")] public string StillLine { get; set; } = ""; /// <summary>Ready-made clipboard texts (UB's Copy Discord / Copy In-Game).</summary> [JsonPropertyName("copyDiscord")] public string CopyDiscord { get; set; } = ""; [JsonPropertyName("copyIngame")] public string CopyIngame { get; set; } = ""; @@ -162,6 +167,10 @@ internal sealed class EnlPlanner [JsonPropertyName("target")] public int Target { get; set; } [JsonPropertyName("plan")] public string[] Plan { get; set; } = Array.Empty<string>(); [JsonPropertyName("coinsPerToken")] public int CoinsPerToken { get; set; } + // Sigil chain vendor trades (RynthILT 0.2.23+; -1 = an older RynthILT, no editors shown). + [JsonPropertyName("extractsPerAsc")] public int ExtractsPerAscension { get; set; } = -1; + [JsonPropertyName("trophyExtracts")] public int TrophyExtracts { get; set; } = -1; + [JsonPropertyName("trophyCount")] public int TrophyCount { get; set; } = -1; [JsonPropertyName("tokensShort")] public string TokensShort { get; set; } = ""; /// <summary>Client-side requirements not yet met; empty = the client checks pass.</summary> [JsonPropertyName("blockers")] public string[] Blockers { get; set; } = Array.Empty<string>(); @@ -221,6 +230,8 @@ internal sealed class EnlMaterialRow [JsonPropertyName("need")] public string Need { get; set; } = "0"; [JsonPropertyName("have")] public string Have { get; set; } = "0"; [JsonPropertyName("ok")] public bool Ok { get; set; } + /// <summary>How to get it: a recipe or a vendor trade ("" = nothing to say; older RynthILT).</summary> + [JsonPropertyName("how")] public string How { get; set; } = ""; } /// <summary>One row of the 301-325 sigil craft chain. Craft rows count crafts left, raw rows what to get.</summary> @@ -234,6 +245,8 @@ internal sealed class EnlChainRow [JsonPropertyName("ok")] public bool Ok { get; set; } /// <summary>An in-between item the player crafts (Ascension Coins, Lifeblood Elixirs, Lifebloom Resins).</summary> [JsonPropertyName("craft")] public bool Craft { get; set; } + /// <summary>The recipe of a crafted item, or a vendor trade ("" = nothing to say; older RynthILT).</summary> + [JsonPropertyName("how")] public string How { get; set; } = ""; /// <summary>The label with "(craft)" for an in-between item the player crafts.</summary> [JsonIgnore] public string DisplayLabel => _displayLabel ??= Craft ? Label + " (craft)" : Label; diff --git a/src/RynthCore.Engine/UI/Data/RynthNavData.cs b/src/RynthCore.Engine/UI/Data/RynthNavData.cs index 60acb9e..810ef6f 100644 --- a/src/RynthCore.Engine/UI/Data/RynthNavData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthNavData.cs @@ -116,6 +116,11 @@ internal sealed class RynthNavStatus public int MeshRadius = 40, MeshTriangles = 3000, MeshDrawn; public bool HasSave, CanSave, SaveBusy; public string SaveFor = "", SaveName = "", SaveConflict = "", SaveLast = ""; + // Custom-server portals and learning them (RynthNav "learn", 2026-10-29; HasLearn false on older plugins). + public bool HasLearn, LearnOn; + public double LearnRange = 200, LearnMin = 20, LearnMax = 2000; + public int LearnSaved, LearnRoutable, LearnTried, LearnLearned; + public string LearnServer = "", LearnLine = "", LearnCounts = ""; public bool HasTies; public int Tie1Known = -1, Tie2Known = -1; public string TiePending = ""; @@ -284,6 +289,22 @@ internal sealed class RynthNavStatus s.TownNetLoaded = Int(info, "townNet") != 0; s.TownNetStatus = Str(info, "townNetStatus"); } + if (r.TryGetProperty("learn", out var ln) && ln.ValueKind == JsonValueKind.Object) + { + s.HasLearn = true; + s.LearnOn = Int(ln, "on") != 0; + s.LearnRange = Num(ln, "range"); + s.LearnMin = Num(ln, "min"); + s.LearnMax = Num(ln, "max"); + s.LearnServer = Str(ln, "server"); + s.LearnSaved = Int(ln, "saved"); + s.LearnRoutable = Int(ln, "routable"); + s.LearnTried = Int(ln, "tried"); + s.LearnLearned = Int(ln, "learned"); + s.LearnLine = Str(ln, "line"); + s.LearnCounts = s.LearnServer.Length == 0 ? "Not logged in yet." + : $"{s.LearnServer}: {s.LearnSaved} custom portal(s) saved, {s.LearnRoutable} with a known landing (used by routes)."; + } if (r.TryGetProperty("markers", out var mk) && mk.ValueKind == JsonValueKind.Object) { s.HasMarkers = true; diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 5c926c9..6a516dd 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -314,14 +314,16 @@ internal sealed class RynthAiSettings // Salvage with the 0x027D request sent straight to the server, no salvage panel on screen // (default on; used when the engine has API v81; an older RynthAi doesn't send it). public bool SalvageWithoutPanel { get; set; } = true; + // Inter-Item Delay and Closing Delay: RynthAi's corpse looting never reads them (not shown in + // the panel since 2026.10.5.59), carried so a save doesn't send them missing. public int LootInterItemDelayMs { get; set; } = 50; - public int LootContentSettleMs { get; set; } = 100; - public int LootEmptyCorpseMs { get; set; } = 300; + public int LootContentSettleMs { get; set; } = LootTimerDefaults.ContentSettleMs; + public int LootEmptyCorpseMs { get; set; } = LootTimerDefaults.EmptyCorpseMs; public int LootClosingDelayMs { get; set; } = 200; - public int LootAssessWindowMs { get; set; } = 200; - public int LootRetryTimeoutMs { get; set; } = 500; - public int LootOpenRetryMs { get; set; } = 1500; - public int LootCorpseTimeoutMs { get; set; } = 12000; + public int LootAssessWindowMs { get; set; } = LootTimerDefaults.AssessWindowMs; + public int LootRetryTimeoutMs { get; set; } = LootTimerDefaults.RetryTimeoutMs; + public int LootOpenRetryMs { get; set; } = LootTimerDefaults.OpenRetryMs; + public int LootCorpseTimeoutMs { get; set; } = LootTimerDefaults.CorpseTimeoutMs; public int SalvageOpenDelayFirstMs { get; set; } = 400; public int SalvageOpenDelayFastMs { get; set; } = 50; public int SalvageAddDelayFirstMs { get; set; } = 600; @@ -910,6 +912,129 @@ internal static class SettingsSchema return list.ToArray(); } + // ── Settings > Graphics (Graphics/AcGraphics.cs, Graphics/AcGraphicsPrefs.cs) ───────────── + // AC's own graphics options as a profile per account, written to UserPreferences.ini by the + // launcher when it starts that account. "AC's choice" = not enforced (AC keeps whatever it has). + // Declared before Tabs: static field initializers run in order. + private const string AcChoice = "AC's choice"; + private const string DisplayToggles = "Game Client tab's toggles"; + private static readonly string[] GfxResolutions = Graphics.AcGraphics.AvailableResolutions(); + private static readonly string[] GfxResolutionItems = Prepend(AcChoice, GfxResolutions); + private static readonly string[] GfxModeItems = Prepend(DisplayToggles, global::RynthCore.Graphics.AcGraphicsPrefs.WindowModeLabels); + private static readonly string[] GfxRefreshValues = Prepend("Auto", Graphics.AcGraphics.AvailableRefreshRates()); + private static readonly string[] GfxRefreshItems = Prepend(AcChoice, Array.ConvertAll(GfxRefreshValues, v => v == "Auto" ? "Auto" : v + " Hz")); + private static readonly string[] GfxTriState = { AcChoice, "On", "Off" }; + + private static string[] Prepend(string first, string[] rest) + { + var all = new string[rest.Length + 1]; + all[0] = first; + Array.Copy(rest, 0, all, 1, rest.Length); + return all; + } + + /// <summary>The window-mode combo's index: 0 = the Game Client tab's toggles decide, else this account's mode.</summary> + private static int GfxModeIndex() => + Graphics.AcGraphics.ProfileWindowMode is string m + ? Array.IndexOf(global::RynthCore.Graphics.AcGraphicsPrefs.WindowModeIds, m) + 1 + : 0; + + /// <summary>A combo index for an enforced value in <paramref name="values"/> (0 = AC's choice / not listed).</summary> + private static int GfxIndex(string id, string[] values) + { + string? v = Graphics.AcGraphics.Get(id); + if (v == null) return 0; + int i = Array.FindIndex(values, x => string.Equals(x, v, StringComparison.OrdinalIgnoreCase)); + return i < 0 ? 0 : i + 1; + } + + /// <summary>The rows for one Render setting: a combo (choices, or AC's choice / On / Off), or for a + /// number a "Set" checkbox that shows its slider.</summary> + private static SettingRow[] GfxRows(global::RynthCore.Graphics.AcGraphicsSetting g) + { + string id = g.Id; + string tip = g.Help + "\nAC's choice: RynthAi leaves AC's own setting as it is. This account only; applies at the next launch."; + switch (g.Kind) + { + case global::RynthCore.Graphics.AcGraphicsKind.Choice: + string[] choices = g.Choices!; + return new[] + { + Combo(g.Label, Prepend(AcChoice, choices), _ => GfxIndex(id, choices), + (_, v) => Graphics.AcGraphics.Set(id, v <= 0 ? null : choices[v - 1]), tip), + }; + case global::RynthCore.Graphics.AcGraphicsKind.Bool: + return new[] + { + Combo(g.Label, GfxTriState, _ => GfxIndex(id, new[] { "True", "False" }), + (_, v) => Graphics.AcGraphics.Set(id, v == 1 ? "True" : v == 2 ? "False" : null), tip), + }; + default: + double mid = (g.Min + g.Max) / 2; + return new[] + { + Bool("Set " + char.ToLowerInvariant(g.Label[0]) + g.Label[1..], _ => Graphics.AcGraphics.Get(id) != null, + (_, on) => + { + if (!on) { Graphics.AcGraphics.Set(id, null); return; } + // Start from what AC has now, inside the slider's range. + double start = double.TryParse(Graphics.AcGraphics.LaunchValue(id), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out double cur) ? cur : mid; + Graphics.AcGraphics.Set(id, global::RynthCore.Graphics.AcGraphicsPrefs.FormatFloat(Math.Clamp(start, g.Min, g.Max))); + }, tip, gates: true), + Float(" " + g.Label, _ => float.TryParse(Graphics.AcGraphics.Get(id), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out float f) ? f : (float)mid, + (_, v) => Graphics.AcGraphics.Set(id, global::RynthCore.Graphics.AcGraphicsPrefs.FormatFloat(v)), + (float)g.Min, (float)g.Max, (float)g.Step, tip, when: _ => Graphics.AcGraphics.Get(id) != null), + }; + } + } + + private static SettingRow[] GraphicsRows() + { + var rows = new System.Collections.Generic.List<SettingRow> + { + Status(_ => Graphics.AcGraphics.StatusLine()), + Note("A profile per account: these apply to this account's clients only. AC reads them at startup, so\n" + + "they apply at the next launch: the launcher writes this account's profile into AC's\n" + + "UserPreferences.ini just before it starts the account. Only the window mode changes the window now;\n" + + "the window always follows the resolution AC is really drawing at."), + Section("Window"), + Combo("Window mode", GfxModeItems, _ => GfxModeIndex(), + (_, v) => Graphics.AcGraphics.SetWindowMode(v <= 0 ? null + : global::RynthCore.Graphics.AcGraphicsPrefs.WindowModeIds[Math.Clamp(v - 1, 0, 3)]), + "Game Client tab's toggles: Borderless Windowed / Fills Monitor decide (all clients).\n" + + "Windowed: a normal framed window, sized for AC's resolution.\n" + + "Borderless (fill the monitor): no frame, covering the whole monitor the game is on.\n" + + "Borderless (resolution size): no frame, AC's resolution in size, where the window was.\n" + + "Full screen (exclusive): AC's own full screen; starts at the next launch.\n" + + "This account only. The window's position is remembered; its size follows AC's resolution."), + Combo("Resolution", GfxResolutionItems, _ => GfxIndex(global::RynthCore.Graphics.AcGraphicsPrefs.ResolutionId, GfxResolutions), + (_, v) => Graphics.AcGraphics.Set(global::RynthCore.Graphics.AcGraphicsPrefs.ResolutionId, v <= 0 ? null : GfxResolutions[v - 1]), + "AC's display resolution for this account, from the next launch (the window isn't changed now: it\n" + + "follows what AC draws at). AC's choice: whatever AC's own options have."), + Combo("Refresh rate", GfxRefreshItems, _ => GfxIndex(global::RynthCore.Graphics.AcGraphicsPrefs.RefreshRateId, GfxRefreshValues), + (_, v) => Graphics.AcGraphics.Set(global::RynthCore.Graphics.AcGraphicsPrefs.RefreshRateId, v <= 0 ? null : GfxRefreshValues[v - 1]), + "The monitor refresh rate AC asks for in full screen. Auto: the monitor's own. Applies at the next launch."), + }; + rows.AddRange(GfxRows(global::RynthCore.Graphics.AcGraphicsPrefs.SyncToRefresh)); + + rows.Add(Spacer()); + rows.Add(Section("Graphics")); + // Adaptive degrade off with a far draw distance can run the client out of memory (shown only then). + rows.Add(Status(_ => Graphics.AcGraphics.MemoryWarning())); + foreach (global::RynthCore.Graphics.AcGraphicsSetting g in global::RynthCore.Graphics.AcGraphicsPrefs.RenderSettings) + rows.AddRange(GfxRows(g)); + + rows.Add(Spacer()); + rows.Add(Button("Write to AC's settings now", "Write", () => Graphics.AcGraphics.WriteIniNow(), + "Write this account's profile into AC's UserPreferences.ini now, for the next start of a client the\n" + + "launcher doesn't start (the launcher does it before every start of this account).")); + rows.Add(Button("Reset all to AC's choice", "Reset", () => Graphics.AcGraphics.ResetAll(), + "Stop enforcing every graphics setting for this account. AC's own settings stay as they are now.")); + return rows.ToArray(); + } + public static readonly SettingsTab[] Tabs = { // ── RynthCore · this PC: how Rynth looks and the game client (stored by the engine, mostly) ── @@ -1050,7 +1175,7 @@ internal static class SettingsSchema Section("Window Layout"), Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout, (_, v) => Plugins.EngineSettings.RememberWindowLayout = v, - "On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."), + "On (default): reopen Rynth panels where you left them and keep the Vision self-plate / ImGui layout.\nOff: do not overwrite the saved layout or reopen panels from the last session. Applies to all your clients.\nThe game window itself: Remember Game Window Position."), // Stored in engine.json for every client (EngineSettings); the layouts themselves by UI/PanelLayout. Bool("Panel Layout Per Character", _ => Plugins.EngineSettings.PanelLayoutPerCharacter, (_, v) => Plugins.EngineSettings.PanelLayoutPerCharacter = v, @@ -1074,16 +1199,40 @@ internal static class SettingsSchema (_, v) => { Plugins.EngineSettings.BorderlessWindowed = v; - AcWindowChrome.RequestApply(); // applied from the game thread, not inside this frame + // This toggle decides again over this account's Settings > Graphics window mode. + Graphics.AcGraphics.DisplayTogglesChanged(); + try + { + // ResolveGameHwnd covers EntryPoint + Win32Backend; Tick retries if zero. + AcWindowChrome.ApplyBorderlessDesired(AcWindowChrome.ResolveGameHwndForSettings()); + } + catch { /* HWND may not be ready; Tick applies later */ } }, - "On: hide the Asheron's Call window title bar and borders while staying windowed (exclusive fullscreen is left alone).\nOff (default): normal window chrome. Turning it off only gives back the chrome this setting removed.\nApplies to all your clients; others pick it up when they start."), - Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, + "On: hide the Asheron's Call window title bar and borders while staying windowed (no exclusive fullscreen).\nOff (default): normal window chrome. Applies to all your clients; others pick it up when they start.\nStuck at a size you can't change? Reset Window Borders below, or /rc window reset in chat."), + Bool("Borderless Fills Monitor", _ => Plugins.EngineSettings.BorderlessFillMonitor, (_, v) => { - Plugins.EngineSettings.RememberAcWindowPosition = v; - AcWindowChrome.RequestApply(); + Plugins.EngineSettings.BorderlessFillMonitor = v; + Graphics.AcGraphics.DisplayTogglesChanged(); + try { AcWindowChrome.ApplyFillMonitorChanged(AcWindowChrome.ResolveGameHwndForSettings()); } + catch { /* HWND may not be ready; the next borderless apply uses the setting */ } }, - "On: save where the Asheron's Call window sits for each character and move it back there after you log in. The game sets the window's size from its resolution; this never changes it. While this is on, the launcher's own memory of the window's spot (per account) stands aside.\nOff (default): the engine never moves the game window. A spot off every screen (a monitor that is gone) is pulled back onto one."), + "On (default): borderless fills the whole monitor the game is on.\nOff: borderless is AC's resolution in size, where the framed window had the game. To move it: turn\nBorderless Windowed off, move the window, then turn it back on.\nThe borderless position is remembered across launches (with Remember Game Window Position on).\nSettings > Graphics can set a window mode per account instead."), + Button("Reset Window Borders", "Reset", () => + { + try { Compatibility.AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + AcWindowChrome.ResetWindow(), 1); } + catch { /* chat may not be ready */ } + }, + "Turn borderless off and put the frame back: a normal window sized for the resolution AC is really drawing\nat, centred. Also replaces the saved window position, so the next launch isn't stuck\neither. Same as /rc window reset."), + Button("Save Window Position", "Save", () => + { + try { Compatibility.AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + AcWindowChrome.SaveWindowNow(), 1); } + catch { /* chat may not be ready */ } + }, + "Save where the game window is now, framed or borderless (kept separately), for the next launch.\nIt is also saved every 10 seconds while Remember Game Window Position is on. Same as /rc window save."), + Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, + (_, v) => Plugins.EngineSettings.RememberAcWindowPosition = v, + "On: save the Asheron's Call window's position and size (framed and borderless kept separately) and put it\nback at the next launch.\nOff (default): the game window is never moved."), Spacer(), Section("Performance"), Bool("Enable FPS Limit", s => s.EnableFPSLimit, (s, v) => s.EnableFPSLimit = v, gates: true), @@ -1133,6 +1282,16 @@ internal static class SettingsSchema "How long a held reload waits for you to leave the world before it reloads anyway (default 10).", when: _ => Plugins.EngineSettings.HoldReloadInWorld), Spacer(), + Section("VirindiTank"), + // Every server (was Mini Remote / ILT Hub Gear only). Copies files into RynthAi folders and merges MyMonsters. + Button("Import VirindiTank profiles", "Import...", + () => RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra vtimport"), + "Opens the VirindiTank Import window: pick Monsters, Loot, Nav, Meta and Settings profiles folders, then Import.\n" + + "Copies into RynthAi (LootProfiles / NavProfiles / MetaFiles); .usd profiles → SettingsProfiles;\n" + + "optional MyMonsters merge into this character.\n" + + "Also: /ra vtimport (window) or /ra vtimport go [files] (default folders, no window)."), + Note("Was under Mini Remote / ILT Hub Gear. Choose up to five source folders (Browse…), or fill from the VirindiTank default."), + Spacer(), Section("Server"), new SettingRow(SettingKind.ServerPick, "Server", "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" @@ -1141,6 +1300,8 @@ internal static class SettingsSchema Note("The list is every server the engine knows: the built-in ones and those declared by the loaded server plugins. \"Settings from\" is the plugin the others ask for that server's settings."), }), + new("Graphics", GraphicsRows()), + // The user hotkeys: stored by the engine for the PC (Hotkeys/HotkeyService.cs, hotkeys.txt), // not in the RynthAi profile; the ImGui face draws the whole editor for this one row. new("Hotkeys", new[] diff --git a/src/RynthCore.Engine/UI/Data/UiDataHub.cs b/src/RynthCore.Engine/UI/Data/UiDataHub.cs index 8f38040..660ec0f 100644 --- a/src/RynthCore.Engine/UI/Data/UiDataHub.cs +++ b/src/RynthCore.Engine/UI/Data/UiDataHub.cs @@ -124,6 +124,12 @@ internal static class UiDataHub if (Stopwatch.GetTimestamp() > commandDeadline) break; } + // Another client saved the shared chat settings: pick them up whether or not this client's + // chat window is open (a client with it closed kept stale rules and wrote them back over + // everyone's at its next save). Throttled inside (a timestamp check every 2 s). + try { ChatModel.PollSettingsFile(); } + catch (Exception ex) { RynthLog.UI($"UiDataHub: chat settings poll threw {ex.GetType().Name}: {ex.Message}"); } + string? slowest = null; long slowestTicks = 0; foreach (UiSource source in sources) diff --git a/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs b/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs index 48e241e..778a05e 100644 --- a/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs +++ b/src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs @@ -1,6 +1,6 @@ // DComp overlay — bar + free-floating panel windows. // -// Bar: ⠿ RC | AI | Status | Log | Radar | RL +// Bar: ⠿ RC | AI | Status | Log | RL (Radar moved under RynthNav, 2026-10-16) // Each panel is an independent DcompFloatingPanel (movable + resizable). // RynthAi footer buttons (Settings, Items, Monsters, Nav, Meta) call // AvaloniaOverlay.ActivateBarButton() which is redirected here via @@ -129,14 +129,14 @@ internal sealed class DcompOverlayWindow : Window private Control BuildBar() { + // Radar moved under RynthNav (2026-10-16); still openable via PanelDefs + ActivateBarButton. var aiBtn = RegisterBarButton("AI"); var statusBtn = RegisterBarButton("Status"); var logBtn = RegisterBarButton("Log"); - var radarBtn = RegisterBarButton("Radar"); var reloadBtn = MakeButton("RL"); reloadBtn.Foreground = Brushes.Khaki; - reloadBtn.Click += (_, _) => EngineLifecycle.SignalReload(); + reloadBtn.Click += (_, _) => EntryPoint.RequestManualReload("Dcomp RL"); var barStack = new StackPanel { @@ -166,7 +166,6 @@ internal sealed class DcompOverlayWindow : Window aiBtn, statusBtn, logBtn, - radarBtn, reloadBtn, }, }; diff --git a/src/RynthCore.Engine/UI/InventoryTitleLayout.cs b/src/RynthCore.Engine/UI/InventoryTitleLayout.cs index 00758f5..790d492 100644 --- a/src/RynthCore.Engine/UI/InventoryTitleLayout.cs +++ b/src/RynthCore.Engine/UI/InventoryTitleLayout.cs @@ -35,7 +35,7 @@ internal readonly record struct InventoryTitleLayout( TitleExtrasMode Mode, float Btn, TitleSlot Smaller, TitleSlot Bigger, TitleSlot Tools, TitleSlot Modern, - TitleSlot Vault, + TitleSlot Vault, TitleSlot Shop, TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv, TitleSlot More, float TitleLeft, float TitleRight) @@ -48,13 +48,14 @@ internal readonly record struct InventoryTitleLayout( /// <summary>The title's room (TitleRight - TitleLeft), never negative.</summary> public float TitleWidth => Math.Max(0f, TitleRight - TitleLeft); - /// <summary>The left edge of everything drawn left of the title (Vault and the related buttons): the drag surface ends here.</summary> + /// <summary>The left edge of everything drawn left of the title (Vault / Shop / related): the drag surface ends here.</summary> public float LeftmostX { get { float x = Math.Min(Modern.X, Smaller.X); if (Vault.Present) x = Math.Min(x, Vault.X); + if (Shop.Present) x = Math.Min(x, Shop.X); if (Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons) x = Math.Min(x, Remote.X); if (Mode == TitleExtrasMode.Menu) x = Math.Min(x, More.X); return x; @@ -98,6 +99,16 @@ internal readonly record struct InventoryTitleLayout( edge = vx; } + // Trade Shop Storefront — always present on real panels (opens /ra tradeshop ui). + // Dropped only when the bar is too narrow to sit left of Vault without going off-panel. + TitleSlot shopSlot = default; + float shopX = edge - btn - VaultGap * s; + if (shopX >= 0f) + { + shopSlot = new TitleSlot(shopX, btn); + edge = shopX; + } + // The room left of `edge` is shared by the title and the related buttons. The title is owed // TitleMinUnits (less if its whole text is shorter); take the richest button style that leaves it. float titleMin = Math.Min(titleWantW, TitleMinUnits * s); @@ -148,12 +159,14 @@ internal readonly record struct InventoryTitleLayout( } float titleRight = Math.Max(pad, groupLeft - TitleGap * s); - return new InventoryTitleLayout(mode, btn, smaller, bigger, tools, modern, vaultSlot, + return new InventoryTitleLayout(mode, btn, smaller, bigger, tools, modern, vaultSlot, shopSlot, remote, sort, count, ginv, more, pad, titleRight); } /// <summary>Header (Modern look) buttons: four 22 px icons at a 24 px pitch, or one "more" button.</summary> public const float HeaderIconsW = 96, HeaderMenuW = 24, HeaderCountGap = 10; + /// <summary>Trade Shop Storefront icon (always placed, like Vault) — 22 px at a 24 px pitch.</summary> + public const float HeaderShopW = 24; /// <summary> /// The Modern header's related-panel buttons for <paramref name="freeW"/> pixels between the pyreals @@ -177,15 +190,14 @@ internal readonly record struct InventoryTitleLayout( public const float HeaderVaultW = 24; /// <summary> - /// <see cref="ChooseHeaderExtras"/> with the Vault button in the picture: when <paramref name="vault"/> - /// the Vault takes its 24 px first and is never dropped (it is the only way into the vault in the Modern - /// look); the four related buttons, the "more" menu and the count text share what is left, as before. - /// Without a vault the result is exactly ChooseHeaderExtras'. + /// <see cref="ChooseHeaderExtras"/> with Vault and Trade Shop reserved: both take 24 px each and are + /// never dropped; the four related buttons / "more" menu and the count text share what is left. /// </summary> internal static HeaderPlan ChooseHeader(float freeW, float countW, bool vault) { if (!float.IsFinite(freeW)) freeW = 0f; - TitleExtrasMode extras = ChooseHeaderExtras(vault ? freeW - HeaderVaultW : freeW, countW, out bool showCount); + float reserved = HeaderShopW + (vault ? HeaderVaultW : 0f); + TitleExtrasMode extras = ChooseHeaderExtras(freeW - reserved, countW, out bool showCount); return new HeaderPlan(vault, extras, showCount); } @@ -215,16 +227,15 @@ internal readonly record struct HeaderPlan(bool Vault, TitleExtrasMode Extras, b /// <summary>The Modern header's button positions, header-relative pixels (add the header's left edge).</summary> internal readonly record struct InventoryHeaderLayout( HeaderPlan Plan, - TitleSlot Close, TitleSlot Classic, TitleSlot Vault, + TitleSlot Close, TitleSlot Classic, TitleSlot Vault, TitleSlot Shop, TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv, TitleSlot More, float RightEdge, float CountX) { public const float Btn = 22, Pitch = 24; /// <summary> - /// Right to left: Close, Classic, the Vault (when there is one), then four related icons or the - /// "more" button, then the count text. <paramref name="w"/> is the header's width, <paramref name="leftEnd"/> - /// where the pyreals text ends (header-relative), <paramref name="countW"/> the count text's width. + /// Right to left: Close, Classic, Vault (when present), Trade Shop (always), then four related + /// icons or the "more" button, then the count text. /// </summary> public static InventoryHeaderLayout Compute(float w, float leftEnd, float countW, bool vault) { @@ -245,6 +256,10 @@ internal readonly record struct InventoryHeaderLayout( anchor = vaultSlot.X; } + // Trade Shop Storefront — always present (opens /ra tradeshop ui). + var shop = new TitleSlot(anchor - Pitch, Btn); + anchor = shop.X; + TitleSlot remote = default, sort = default, count = default, ginv = default, more = default; float rightEdge = anchor - 2; if (plan.Extras == TitleExtrasMode.Icons) @@ -260,7 +275,7 @@ internal readonly record struct InventoryHeaderLayout( more = new TitleSlot(anchor - Pitch, Btn); rightEdge = more.X - 2; } - return new InventoryHeaderLayout(plan, close, classic, vaultSlot, remote, sort, count, ginv, more, + return new InventoryHeaderLayout(plan, close, classic, vaultSlot, shop, remote, sort, count, ginv, more, rightEdge, rightEdge - countW - 4); } } diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 17e527c..82422a2 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -1180,6 +1180,26 @@ internal sealed unsafe class LayeredWindow : IDisposable return true; } + /// <summary> + /// True when a window at this spot is usable where it is: at least half of it on the nearest + /// monitor's work area and its top strip (where it is dragged from) reachable there. A window + /// that hangs a little past an edge or over the taskbar is left where the player put it + /// (2026-11-01: pop-outs moved at every login over a few pixels). Any thread. + /// </summary> + public static bool MostlyOnScreen(int left, int top, int width, int height) + { + width = Math.Max(1, width); height = Math.Max(1, height); + if (!TryGetWorkArea(left, top, width, height, out int wl, out int wt, out int wr, out int wb)) return true; + long ix = Math.Max(0, Math.Min(left + width, wr) - Math.Max(left, wl)); + long iy = Math.Max(0, Math.Min(top + height, wb) - Math.Max(top, wt)); + bool half = ix * iy * 2 >= (long)width * height; + int strip = Math.Min(height, 24); + long sx = ix; // the top strip spans the same columns + long sy = Math.Max(0, Math.Min(top + strip, wb) - Math.Max(top, wt)); + bool grabbable = sx >= Math.Min(60, width) && sy >= Math.Min(8, strip); + return half && grabbable; + } + /// <summary>The work area of the monitor nearest a rectangle (screen px). Any thread.</summary> public static bool TryGetWorkArea(int left, int top, int width, int height, out int workLeft, out int workTop, out int workRight, out int workBottom) { @@ -1196,14 +1216,15 @@ internal sealed unsafe class LayeredWindow : IDisposable } /// <summary> - /// Moves the window back inside the nearest monitor's work area when any of - /// it is off the screen. No OnMoved (the caller persists). True when it moved. + /// Moves the window back inside the nearest monitor's work area when too much of + /// it is off the screen (MostlyOnScreen). No OnMoved (the caller persists). True when it moved. /// The window's thread. /// </summary> public bool EnsureOnScreen() { if (_disposed || Hwnd == IntPtr.Zero || _dragMode != DragNone) return false; // a drag ends with its own check int x = ScreenLeft, y = ScreenTop; + if (MostlyOnScreen(x, y, Width, Height)) return false; if (!ClampToWorkArea(ref x, ref y, Width, Height)) return false; Move(x, y); return true; diff --git a/src/RynthCore.Engine/UI/PanelStatePath.cs b/src/RynthCore.Engine/UI/PanelStatePath.cs new file mode 100644 index 0000000..a0619ab --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelStatePath.cs @@ -0,0 +1,80 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelStatePath.cs +// Which panel_state file a client keeps its window layout in (PanelStateStore). +// +// Until 2026-10-24 every client on the machine shared one panel_state.txt and +// rewrote all of it whenever any window moved, opened or closed, so each client's +// windows came back (after a restart or an engine reload) wherever the client that +// saved last had its own: Silentkelpie's chat window kept "resetting". Each +// character now keeps its own layout: +// +// panel_state.<server>.<character>.txt the character the launcher started +// panel_state.txt no launch context (started outside the +// launcher): the shared file, as before; also +// the starting layout of a character's first run +// +// The character is the launch context's TargetCharacter for this process +// (%AppData%\RynthCore\launch_contexts\launch_context_<pid>.json), known before any +// window is placed. Pure (no engine state): tools/PanelStateTests compiles this file. +// ============================================================================ + +using System; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Engine.UI; + +internal static class PanelStatePath +{ + /// <summary>The layout every client shared before 2026-10-24; a character's first-run start.</summary> + public const string SharedFileName = "panel_state.txt"; + + /// <summary>A name part in a file name is cut to this many characters.</summary> + public const int MaxPartLength = 48; + + /// <summary> + /// "panel_state.<server>.<character>.txt" (lower case, unsafe characters as "_"), or the + /// shared file name when the character isn't known. A blank server is left out. + /// </summary> + public static string FileNameFor(string? server, string? character) + { + string c = Part(character); + if (c.Length == 0) return SharedFileName; + string s = Part(server); + return s.Length == 0 ? $"panel_state.{c}.txt" : $"panel_state.{s}.{c}.txt"; + } + + /// <summary>The launch context's ServerName and TargetCharacter ("" when absent or unreadable).</summary> + public static (string Server, string Character) ParseLaunchContext(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return ("", ""); + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return ("", ""); + return (Str(root, "ServerName"), Str(root, "TargetCharacter")); + } + catch (JsonException) + { + return ("", ""); + } + } + + private static string Str(JsonElement root, string name) + => root.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? "").Trim() : ""; + + /// <summary>Letters and digits kept (lower case), anything else one "_", trimmed of "_".</summary> + private static string Part(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return ""; + var sb = new StringBuilder(text.Length); + foreach (char ch in text.Trim()) + { + if (ch < 128 && char.IsLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch)); + else if (sb.Length > 0 && sb[^1] != '_') sb.Append('_'); + } + string part = sb.ToString().Trim('_'); + return part.Length > MaxPartLength ? part[..MaxPartLength].TrimEnd('_') : part; + } +} diff --git a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs index 73b5fa8..68f1603 100644 --- a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs @@ -48,9 +48,6 @@ internal static class ItemsPanel private static readonly IBrush ColBtnBord = new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59)); private static readonly IBrush ColHdrBg = new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42)); - private static readonly string[] Elements = - { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; - private static readonly string[] ConsumableTypes = { "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" }; @@ -535,8 +532,9 @@ internal static class ItemsPanel Grid.SetColumn(nameTb, 0); grid.Children.Add(nameTb); - // Element picker button - int elemIdx = Array.IndexOf(Elements, w.Element); + // Element picker button (missile weapons and ammo can also be Prismatic: universal damage). + string[] choices = UI.Data.ItemsCommands.ElementsFor(w.Kind); + int elemIdx = Array.IndexOf(choices, w.Element); if (elemIdx < 0) elemIdx = 0; var elemBtn = new Button { @@ -552,9 +550,9 @@ internal static class ItemsPanel }; elemBtn.Click += (_, _) => { - showPicker(elemBtn, Elements, Array.IndexOf(Elements, w.Element), picked => + showPicker(elemBtn, choices, Array.IndexOf(choices, w.Element), picked => { - w.Element = Elements[picked]; + w.Element = choices[picked]; elemBtn.Content = w.Element; onChanged(); }); diff --git a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs index eb0ea9d..310943c 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs @@ -598,19 +598,13 @@ internal static partial class RynthAiPanel ClosePicker(); RynthAiCommands.ApplyRemoteCommand("hub", "show"); }); - ToolTip.SetTip(charBtn, "Open the Mini Remote (/ra hub show)."); - - // Hub: the Mini Remote and the Inventory HUDs setup are ImGui windows inside RynthAi. - var hudBtn = AddLauncher(launcherGrid, 2, 1, "Hub", "▣", - onClick: () => - { - ClosePicker(); - RynthAiCommands.ApplyRemoteCommand("remote", "toggle"); - }); - ToolTip.SetTip(hudBtn, "Left-click: show/hide the Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds)."); - hudBtn.PointerPressed += (_, e) => + ToolTip.SetTip(charBtn, "Left-click: open the Mini Remote (/ra hub show). Right-click: Inventory HUDs setup (/ra huds)."); + // The separate Hub launcher (the same Mini Remote again) was removed 2026-10-13, as on the + // ImGui dashboard; its right-click, the Inventory HUDs setup (an ImGui window inside + // RynthAi), moved to Char. + charBtn.PointerPressed += (_, e) => { - if (e.GetCurrentPoint(hudBtn).Properties.IsRightButtonPressed) + if (e.GetCurrentPoint(charBtn).Properties.IsRightButtonPressed) { e.Handled = true; ClosePicker(); diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs index da5fb47..b4f3bae 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs @@ -1,14 +1,19 @@ // ============================================================================ // RynthCore.Engine — UI/Panels/RynthChatPresets.cs // Canned ("standard") RynthChat filters, modelled on UtilityBelt-IT's -// ChatFilter / Mag ChatFilter categories. Each preset is a tick-box in the -// ChatFilters panel that hides its lines or moves them to a tab. +// ChatFilterTool (Mag ChatFilter parity) plus the classic ChatFilter / +// ChatHandler categories. Each preset is a tick-box in the ChatFilters +// panel that hides its lines or moves them to a tab. // // Presets match the raw line text (no timestamp / sender prefix). Most are // limited to non-chat channels so a player typing the same words in Local or // a channel is never eaten. ChatRouter evaluates them on the plugin pump // (after the custom rules); editors change Enabled / Tab from any thread and // then call ChatModel.FiltersChanged so every kept line is routed again. +// +// Not ported as text presets (need Decal WorldFilter / StatusTextIntercept): +// VendorTells, MonsterTell, NpcChatter, StatusTextAll. Use custom rules if +// you want a blunt "tells you" / "says," filter. // ============================================================================ using System; @@ -87,7 +92,7 @@ internal static class RynthChatPresets @"|Your killing blow nearly turns .+ inside-out!|The thunder of crushing .+ is followed by the deafening silence of death!" + @"|Your attack stops .+ cold!)"; - // Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ". + // Optional combat prefixes ("Critical hit! ", "Sneak Attack! " ...): the older presets' broad form. private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*"; // The new damage presets (melee_dealt ... magic_taken) name their prefixes: "Critical hit! ", @@ -109,7 +114,7 @@ internal static class RynthChatPresets private static readonly Preset[] _all = { - // ── Combat ──────────────────────────────────────────────────────── + // ── Combat (specific before umbrella: FirstMatch order) ─────────── new("combat.attack_evades", "Combat", "Your attacks evaded", "A monster evades your melee or missile attack.", "Drudge Slinker evaded your attack.", Scope.NotPlayerChat, @" evaded your attack\.\s*$"), @@ -311,7 +316,7 @@ internal static class RynthChatPresets new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)", "All Master Arbitrator speech and the fellowship-lock notice.", "Master Arbitrator tells you, \"You shall be known…\"", Scope.Any, - @"^Master Arbitrator (?:says|tells you)|^Your fellowship is now locked\..*you have 15 minutes to be recruited"), + @"^Master Arbitrator (?:says|tells you)|^\[Fellowship\] Master Arbitrator |^Your fellowship is now locked\..*you have 15 minutes to be recruited"), // ── Pets (ACE custom combat pets) ───────────────────────────────── new("pet.hit", "Pets", "Pet hits", diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index 3252e08..24e18a8 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -350,6 +350,20 @@ internal static class SettingsPanel }, row.Tooltip); case SettingKind.TraceCategories: return TraceCategoriesRow(state, row); + case SettingKind.ServerPick: + { + // The picker itself is the ImGui face's; here, what is picked and how to change it. + var snap = UI.Sections.SectionRegistry.Current; + string pick = UI.Sections.ServerSelection.CurrentPick(snap.Servers) ?? "mixed"; + var active = UI.Sections.ServerSelection.ActiveServer(snap.Servers); + return new TextBlock + { + Text = $"Server: {(active == null ? "none active" : active.Name + " (" + active.Id + ")")}, pick {pick}. " + + "Change it with /rc server pick <id>|auto (the ImGui panel has a picker).", + Foreground = ColTeal, FontSize = 11, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2), + }; + } case SettingKind.Text: return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v => { diff --git a/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs index 412700f..a42f706 100644 --- a/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs +++ b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs @@ -15,7 +15,7 @@ using System.Collections.Generic; namespace RynthCore.Engine.UI.Sections; /// <summary>An installed server plugin that is not loaded: its server and the plugin's name.</summary> -internal readonly record struct NotLoadedServer(string Id, string Name, string Plugin, string[]? WorldNames = null); +internal readonly record struct NotLoadedServer(string Id, string Name, string Plugin); internal static class NotLoadedServers { @@ -39,25 +39,10 @@ internal static class NotLoadedServers /// <summary>The not-loaded servers this character forces On: their plugins should load now.</summary> public static List<string> ForcedOn(IReadOnlyList<NotLoadedServer> notLoaded, Func<string, ServerForce> force) - => ToLoad(notLoaded, force, world: null); - - /// <summary> - /// The not-loaded servers whose plugins should load now: forced On by this character, or (not - /// forced Off) named by the world name the server announced (<paramref name="world"/>; null or - /// empty before login). The host left them out, but the world says this is their server. - /// </summary> - public static List<string> ToLoad(IReadOnlyList<NotLoadedServer> notLoaded, Func<string, ServerForce> force, string? world) { var ids = new List<string>(); foreach (NotLoadedServer s in notLoaded) - { - if (s.Id.Length == 0) continue; - ServerForce f = force(s.Id); - if (f == ServerForce.On - || (f != ServerForce.Off && !string.IsNullOrWhiteSpace(world) && s.WorldNames is { Length: > 0 } - && Compatibility.IltDetect.WorldNameMatches(world, s.WorldNames, out _))) - ids.Add(s.Id); - } + if (s.Id.Length > 0 && force(s.Id) == ServerForce.On) ids.Add(s.Id); return ids; } } diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs index a677357..bb3ecbb 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -201,7 +201,7 @@ internal static class SectionRegistry // loaded as soon as this character forces their server On (picker, chat or saved override). List<NotLoadedServer> notLoaded = NotLoadedServerPlugins(); NotLoadedServers.Append(servers, notLoaded, ServerForceStore.Get); - foreach (string id in NotLoadedServers.ToLoad(notLoaded, ServerForceStore.Get, AccountHooks.AnnouncedWorldName)) + foreach (string id in NotLoadedServers.ForcedOn(notLoaded, ServerForceStore.Get)) Plugins.PluginManager.RequestServerPluginLoad(id); List<SectionView> sections = SectionCatalog.Build(manifests, ImGuiBackend.ImGuiPanelHost.CanEmbed, servers); @@ -256,7 +256,7 @@ internal static class SectionRegistry IReadOnlyList<Plugins.SkippedServerPlugin> skipped = Plugins.PluginManager.SkippedServerPlugins; var list = new List<NotLoadedServer>(skipped.Count); foreach (Plugins.SkippedServerPlugin s in skipped) - list.Add(new NotLoadedServer(SectionManifestParser.Id(s.ServerId), s.ServerName, s.PluginName, s.Manifest.Server!.WorldNames.ToArray())); + list.Add(new NotLoadedServer(SectionManifestParser.Id(s.ServerId), s.ServerName, s.PluginName)); return list; } diff --git a/src/RynthCore.Engine/UI/ServerMenus.cs b/src/RynthCore.Engine/UI/ServerMenus.cs index 7e0ec64..d63794e 100644 --- a/src/RynthCore.Engine/UI/ServerMenus.cs +++ b/src/RynthCore.Engine/UI/ServerMenus.cs @@ -133,7 +133,7 @@ internal static class ServerMenus /// </summary> public static void Tick() { - SectionRegistry.Tick(); // the server verdicts (GetServerStateJson) and late server-plugin loads + SectionRegistry.Tick(); SectionRegistry.Snapshot snap = SectionRegistry.Current; List<string> serverPlugins = ServerPluginTargets(snap); if (!PushToRynthAi && !PushToRynthIlt && serverPlugins.Count == 0) return; diff --git a/src/RynthCore.Engine/UI/WindowPlacementStore.cs b/src/RynthCore.Engine/UI/WindowPlacementStore.cs new file mode 100644 index 0000000..cd5cb43 --- /dev/null +++ b/src/RynthCore.Engine/UI/WindowPlacementStore.cs @@ -0,0 +1,140 @@ +// ============================================================================ +// RynthCore.Engine - UI/WindowPlacementStore.cs +// Where the player left each plugin's own floating ImGui window (an Item HUD, a +// settings window), per character (plugin API v98, Get/SetWindowPlacement). +// +// Plugin windows saved their spot in imgui.ini, one file every running client +// shares: each client loads it at start and later rewrites all of it, so a window +// moved in one client came back where another client's next save had it +// (2026-10-26). Engine panels never had the problem (PanelStateStore, one file per +// character); this gives plugin windows the same, with the plugin's own look. +// +// File: %LocalAppData%\RynthCore\window_state.<server>.<character>.txt, one line +// per window, "<key>=<x>,<y>,<width>,<height>" (ImGui screen pixels; width and +// height 0 for a window that sizes itself). The character is the one logged in, +// so a client that switches characters reads the new one's file. Only that +// character's client writes it: written to a temp file and swapped in. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace RynthCore.Engine.UI; + +internal static class WindowPlacementStore +{ + /// <summary>A key longer than this, or with '=' or a line break, is refused.</summary> + public const int MaxKeyLength = 96; + + private static readonly object Sync = new(); + private static readonly Dictionary<string, float[]> Windows = new(StringComparer.OrdinalIgnoreCase); + private static string? _file; // the file Windows was read from (null: nothing read yet) + + private static string Folder => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore"); + + /// <summary>The logged-in character's file name, or null when no character is known yet.</summary> + internal static string? FileNameFor(string? server, string? character) + { + string name = PanelStatePath.FileNameFor(server, character); + if (name == PanelStatePath.SharedFileName) return null; // no character: nothing is saved + return "window_state" + name.Substring("panel_state".Length); + } + + public static bool ValidKey(string? key) => + !string.IsNullOrWhiteSpace(key) && key.Length <= MaxKeyLength + && key.IndexOf('=') < 0 && key.IndexOf('\n') < 0 && key.IndexOf('\r') < 0; + + /// <summary>The placement saved for <paramref name="key"/> on this character. Any thread.</summary> + public static bool TryGet(string key, out float x, out float y, out float width, out float height) + { + x = y = width = height = 0; + if (!ValidKey(key)) return false; + lock (Sync) + { + if (!Select()) return false; + if (!Windows.TryGetValue(key.Trim(), out float[]? v)) return false; + (x, y, width, height) = (v[0], v[1], v[2], v[3]); + return true; + } + } + + /// <summary>Saves <paramref name="key"/>'s placement for this character. False with no character or a bad key. Any thread.</summary> + public static bool Set(string key, float x, float y, float width, float height) + { + if (!ValidKey(key) || !float.IsFinite(x) || !float.IsFinite(y) || !float.IsFinite(width) || !float.IsFinite(height)) + return false; + lock (Sync) + { + if (!Select() || _file == null) return false; + float[] v = { x, y, Math.Max(0, width), Math.Max(0, height) }; + string k = key.Trim(); + if (Windows.TryGetValue(k, out float[]? old) && old.AsSpan().SequenceEqual(v)) return true; + Windows[k] = v; + Save(_file); + return true; + } + } + + /// <summary>Reads the logged-in character's file when the character changed. Under Sync.</summary> + private static bool Select() + { + string? name = FileNameFor(Compatibility.SessionStateRegistry.LastServerName, Compatibility.SessionStateRegistry.LastCharacterName); + if (name == null) return false; + string path = Path.Combine(Folder, name); + if (string.Equals(path, _file, StringComparison.OrdinalIgnoreCase)) return true; + _file = path; + Windows.Clear(); + try + { + if (!File.Exists(path)) return true; + foreach (string line in File.ReadAllLines(path)) + { + if (line.Length == 0 || line[0] == '#') continue; + int eq = line.LastIndexOf('='); + if (eq <= 0) continue; + string[] parts = line.Substring(eq + 1).Split(','); + if (parts.Length != 4) continue; + var v = new float[4]; + bool ok = true; + for (int i = 0; i < 4 && ok; i++) + ok = float.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out v[i]) && float.IsFinite(v[i]); + if (ok) Windows[line.Substring(0, eq).Trim()] = v; + } + } + catch (Exception ex) + { + try { RynthLog.UI($"WindowPlacementStore: {name} unreadable ({ex.GetType().Name}); windows start where they open."); } catch { } + } + return true; + } + + private static void Save(string path) + { + try + { + var sb = new StringBuilder("# RynthCore plugin window spots for this character - auto-generated, hand-edits OK.\n"); + foreach (var (key, v) in Windows) + { + sb.Append(key).Append('='); + for (int i = 0; i < 4; i++) + { + if (i > 0) sb.Append(','); + sb.Append(v[i].ToString("0.#", CultureInfo.InvariantCulture)); + } + sb.Append('\n'); + } + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp"; + File.WriteAllText(tmp, sb.ToString()); + File.Move(tmp, path, overwrite: true); + } + catch (Exception ex) + { + try { RynthLog.UI($"WindowPlacementStore: saving {Path.GetFileName(path)} failed ({ex.GetType().Name}: {ex.Message})."); } catch { } + } + } +} diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index b86b37a..d133b96 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -209,6 +209,9 @@ public struct RynthCoreApiNative public IntPtr WebPanelNavigateFn; // int WebPanelNavigate(int handle, byte* url) -> 1 queued; -2 off-list; -6 stale public IntPtr WebPanelCloseFn; // int WebPanelClose(int handle) -> 1 queued, 0 already closed, -6 stale public IntPtr WebPanelGetStateFn; // int WebPanelGetState(int handle, WebPanelStateNative*) -> Status (non-live handle -> 6 Superseded), -1 bad args + // v98: per-character window placements (APPEND-AT-END (ABI)) + public IntPtr GetWindowPlacementFn; // v98 int GetWindowPlacement(const char* key, float* xywh) -> 1 found, 0 none, -1 bad key / no character + public IntPtr SetWindowPlacementFn; // v98 int SetWindowPlacement(const char* key, float x, y, w, h) -> 1 saved, 0 no character, -1 bad key } /// <summary> diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 20298bb..786eb2d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -675,11 +675,11 @@ public readonly unsafe struct RynthCoreHost } /// <summary> - /// v85: answer the next server prompt of <paramref name="type"/> (a + /// v81: answer the next server prompt of <paramref name="type"/> (a /// <see cref="ConfirmationKind"/>) that arrives within <paramref name="timeoutMs"/>, /// without the client opening its dialog: Yes when the server's "N percent chance" is at /// least <paramref name="minPercent"/> (or it is 0), else No. One-shot; timeoutMs <= 0 - /// disarms. 1 armed, 0 unavailable (engine before v85, sender or hook missing), -3 bad + /// disarms. 1 armed, 0 unavailable (engine before v81, sender or hook missing), -3 bad /// arguments. /// </summary> public int ArmConfirmation(uint type, int minPercent, int timeoutMs) @@ -1826,6 +1826,44 @@ public readonly unsafe struct RynthCoreHost return item; } + /// <summary>v98: the engine keeps a plugin window's spot per character (<see cref="TryGetWindowPlacement"/>).</summary> + public bool HasWindowPlacements => _api.Version >= 98 && _api.GetWindowPlacementFn != IntPtr.Zero && _api.SetWindowPlacementFn != IntPtr.Zero; + + /// <summary> + /// v94: where the player left the plugin's own floating window <paramref name="key"/> on this character + /// (ImGui screen pixels; a zero size = the window sized itself). False when nothing is saved, no + /// character is logged in yet, or the engine is older. Keys: up to 96 characters, no '=' or line break; + /// prefix them with the plugin's name. Any thread. Plugins/Shared SavedWindow wraps this. + /// </summary> + public bool TryGetWindowPlacement(string key, out System.Numerics.Vector2 pos, out System.Numerics.Vector2 size) + { + pos = size = default; + if (!HasWindowPlacements || string.IsNullOrEmpty(key) || key.Length > 96) return false; + Span<byte> utf8 = stackalloc byte[392]; + int n = System.Text.Encoding.UTF8.GetBytes(key, utf8[..^1]); + utf8[n] = 0; + float* v = stackalloc float[4]; + int r; + fixed (byte* p = utf8) + r = ((delegate* unmanaged[Cdecl]<byte*, float*, int>)_api.GetWindowPlacementFn)(p, v); + if (r != 1) return false; + pos = new System.Numerics.Vector2(v[0], v[1]); + size = new System.Numerics.Vector2(v[2], v[3]); + return true; + } + + /// <summary>v98: saves window <paramref name="key"/>'s spot for this character (see <see cref="TryGetWindowPlacement"/>). False when not saved.</summary> + public bool SetWindowPlacement(string key, System.Numerics.Vector2 pos, System.Numerics.Vector2 size) + { + if (!HasWindowPlacements || string.IsNullOrEmpty(key) || key.Length > 96) return false; + Span<byte> utf8 = stackalloc byte[392]; + int n = System.Text.Encoding.UTF8.GetBytes(key, utf8[..^1]); + utf8[n] = 0; + fixed (byte* p = utf8) + return ((delegate* unmanaged[Cdecl]<byte*, float, float, float, float, int>)_api.SetWindowPlacementFn)( + p, pos.X, pos.Y, size.X, size.Y) == 1; + } + /// <summary>v90: AC's own panels (<see cref="IsAcPanelOpen"/>, <see cref="AcPanel"/>).</summary> public bool HasAcPanels => _api.Version >= 90 && _api.AcPanelFn != IntPtr.Zero; diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 7eec6b7..6f034f9 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ <PropertyGroup> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> - <RynthCoreSdkApiVersion>97</RynthCoreSdkApiVersion> + <RynthCoreSdkApiVersion>98</RynthCoreSdkApiVersion> <!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). --> <RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi> <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn> diff --git a/tools/AcGraphicsPrefsTests/AcGraphicsPrefsTests.csproj b/tools/AcGraphicsPrefsTests/AcGraphicsPrefsTests.csproj new file mode 100644 index 0000000..e33949d --- /dev/null +++ b/tools/AcGraphicsPrefsTests/AcGraphicsPrefsTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for RynthAi's Settings > Graphics model (2026-10-17): + src\RynthCore.Engine\Graphics\AcGraphicsPrefs.cs, compiled in (it is shared with the launcher). + graphics.json round-trips as a profile per account; one account's save leaves the others alone; + the 2026.10.18.1 shared set is ignored; the window mode drives Display.FullScreen; applying to a + UserPreferences.ini replaces keys in + place, adds missing keys and sections, leaves every other line alone, and writes nothing when + nothing changed. Works on temp files only. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>AcGraphicsPrefsTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Graphics\AcGraphicsPrefs.cs" Link="Engine\AcGraphicsPrefs.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/AcGraphicsPrefsTests/Program.cs b/tools/AcGraphicsPrefsTests/Program.cs new file mode 100644 index 0000000..89f43ed --- /dev/null +++ b/tools/AcGraphicsPrefsTests/Program.cs @@ -0,0 +1,140 @@ +// Offline checks for Graphics/AcGraphicsPrefs.cs (RynthAi Settings > Graphics). See the .csproj. +using RynthCore.Graphics; + +int failures = 0, checks = 0; +void Check(bool ok, string what) +{ + checks++; + if (ok) return; + failures++; + Console.WriteLine("FAIL " + what); +} + +string dir = Path.Combine(Path.GetTempPath(), "AcGraphicsPrefsTests-" + Environment.ProcessId); +Directory.CreateDirectory(dir); +try +{ + // ── Per-account profiles: each account's own; FullScreen follows the mode ── + string kelpie = AcGraphicsPrefs.AccountKey("InfiniteLeaftide", "silentkelpie"); + string storm = AcGraphicsPrefs.AccountKey("InfiniteLeaftide", "SilentStorm"); + Check(kelpie == "infiniteleaftide|silentkelpie" && storm == "infiniteleaftide|silentstorm", "account key is server|account, lower case"); + Check(AcGraphicsPrefs.AccountKey("", "X") == "" && AcGraphicsPrefs.AccountKey("S", " ") == "", "no key without server and account"); + + var kcfg = new AcGraphicsConfig { WindowMode = AcGraphicsPrefs.ModeFullScreen }; + kcfg.Values[AcGraphicsPrefs.ResolutionId] = "1280x720"; + var scfg = new AcGraphicsConfig { WindowMode = AcGraphicsPrefs.ModeBorderlessFill }; + scfg.Values["Render.TextureFiltering"] = "Anisotropic"; + var all = new AcGraphicsProfiles(); + all.Put(kelpie, kcfg); + all.Put(storm, scfg); + all.Put("x|y", new AcGraphicsConfig()); + Check(all.Accounts.Count == 2, "an empty profile isn't kept"); + + Dictionary<string, string> forKelpie = all.For(kelpie).IniValues(); + Check(forKelpie[AcGraphicsPrefs.FullScreenId] == "True" && forKelpie[AcGraphicsPrefs.ResolutionId] == "1280x720", + "Kelpie's profile: full screen at 1280x720"); + Dictionary<string, string> forStorm = all.For(storm).IniValues(); + Check(forStorm[AcGraphicsPrefs.FullScreenId] == "False" && !forStorm.ContainsKey(AcGraphicsPrefs.ResolutionId), + "Storm's profile: borderless, no resolution of Kelpie's"); + Check(forStorm["Render.TextureFiltering"] == "Anisotropic", "render values pass through"); + Check(all.For("infiniteleaftide|nobody").IniValues().Count == 0, "an account without a profile writes nothing"); + + // ── graphics.json round-trip; another account's entry survives a save ── + string json = Path.Combine(dir, "graphics.json"); + all.Save(json); + AcGraphicsProfiles back = AcGraphicsProfiles.Load(json); + Check(back.For(kelpie).WindowMode == AcGraphicsPrefs.ModeFullScreen && back.For(kelpie).Values[AcGraphicsPrefs.ResolutionId] == "1280x720", + "Kelpie's profile round-trips"); + Check(back.For(storm).Values["render.texturefiltering"] == "Anisotropic", "Storm's profile round-trips (ids case-insensitive)"); + Check(!File.Exists(json + "." + Environment.ProcessId + ".tmp"), "no temp file left"); + + // A client edits only its own account: load, put, save (as AcGraphics.QueueSave does). + AcGraphicsProfiles onDisk = AcGraphicsProfiles.Load(json); + AcGraphicsConfig k2 = onDisk.For(kelpie).Clone(); + k2.Values.Remove(AcGraphicsPrefs.ResolutionId); + onDisk.Put(kelpie, k2); + onDisk.Save(json); + AcGraphicsProfiles after = AcGraphicsProfiles.Load(json); + Check(!after.For(kelpie).Values.ContainsKey(AcGraphicsPrefs.ResolutionId), "Kelpie's change saved"); + Check(after.For(storm).WindowMode == AcGraphicsPrefs.ModeBorderlessFill, "Storm's profile untouched by Kelpie's save"); + + // The 2026.10.18.1 single shared set is ignored (it made every client fight over one resolution). + File.WriteAllText(json, "{\"values\":{\"Display.Resolution\":\"1760x990\"},\"windowMode\":\"Windowed\",\"characters\":{}}"); + Check(AcGraphicsProfiles.Load(json).Accounts.Count == 0, "old global graphics.json is not applied to anyone"); + File.WriteAllText(json, "{\"accounts\":{\"a|b\":{\"windowMode\":\"Bogus\",\"values\":{}}}}"); + Check(AcGraphicsProfiles.Load(json).Accounts.Count == 0, "unknown mode dropped; empty profile not kept"); + + // ── Resolution parsing ── + Check(AcGraphicsPrefs.TryParseResolution("1760x990", out int w, out int h) && w == 1760 && h == 990, "parses 1760x990"); + Check(!AcGraphicsPrefs.TryParseResolution("800", out _, out _) && !AcGraphicsPrefs.TryParseResolution("100x50", out _, out _), + "rejects junk and tiny sizes"); + Check(AcGraphicsPrefs.FormatFloat(0.891) == "0.89", "floats as AC writes them"); + + // ── Applying to UserPreferences.ini ── + string ini = Path.Combine(dir, "UserPreferences.ini"); + File.WriteAllText(ini, + "[Render]\r\nFieldOfView=160.00\r\nTextureFiltering=Bilinear\r\n[Net]\r\nComputeUniquePort=True\r\n[Display]\r\nResolution=1760x990\r\nFullScreen=False\r\n"); + var values = new Dictionary<string, string> + { + ["Render.TextureFiltering"] = "Anisotropic", + ["Display.Resolution"] = "1920x1080", + ["Display.FullScreen"] = "False", + ["Render.MultiPassAlpha"] = "False", + ["Camera.Stiffness"] = "0.50", + }; + List<string> changed = AcPrefsIni.Apply(ini, values); + Dictionary<string, string> now = AcPrefsIni.Read(ini); + Check(changed.Count == 4 && !changed.Contains("Display.FullScreen"), "only changed keys are reported"); + Check(now["Render.TextureFiltering"] == "Anisotropic" && now["Display.Resolution"] == "1920x1080", "keys replaced in place"); + Check(now["Render.MultiPassAlpha"] == "False", "missing key added to its section"); + Check(now["Camera.Stiffness"] == "0.50", "missing section added"); + Check(now["Render.FieldOfView"] == "160.00" && now["Net.ComputeUniquePort"] == "True", "other keys untouched"); + string[] lines = File.ReadAllLines(ini); + int renderAt = Array.IndexOf(lines, "[Render]"), netAt = Array.IndexOf(lines, "[Net]"); + int mpaAt = Array.IndexOf(lines, "MultiPassAlpha=False"); + Check(mpaAt > renderAt && mpaAt < netAt, "added key sits inside [Render]"); + + DateTime stamp = File.GetLastWriteTimeUtc(ini); + Thread.Sleep(30); + Check(AcPrefsIni.Apply(ini, values).Count == 0 && File.GetLastWriteTimeUtc(ini) == stamp, "no write when nothing changed"); + + string fresh = Path.Combine(dir, "sub", "UserPreferences.ini"); + AcPrefsIni.Apply(fresh, new Dictionary<string, string> { ["Display.Resolution"] = "1280x720" }); + Check(AcPrefsIni.Read(fresh)["Display.Resolution"] == "1280x720", "creates a missing file"); + + // ── Which INI files: the game folder's first (the one this install's clients use) ── + string gameDir = Path.Combine(dir, "game"); + Directory.CreateDirectory(gameDir); + string gameIni = Path.Combine(gameDir, "UserPreferences.ini"); + Check(AcGraphicsPrefs.IniPaths(gameDir)[0] != gameIni || File.Exists(gameIni), "no game-folder INI: listed only as the fallback"); + File.WriteAllText(gameIni, "[Display]\r\nResolution=1760x990\r\n"); + List<string> paths = AcGraphicsPrefs.IniPaths(gameDir); + Check(paths.Count >= 1 && paths[0] == gameIni, "game folder's INI comes first when it exists"); + Check(paths.TrueForAll(File.Exists), "only existing files listed when the game folder has one"); + + // ── Every Render setting has sane metadata ── + foreach (AcGraphicsSetting s in AcGraphicsPrefs.RenderSettings) + { + Check(s.Section == "Render" && s.Key.Length > 0 && s.Label.Length > 0, $"{s.Id}: section, key, label"); + if (s.Kind == AcGraphicsKind.Choice) Check(s.Choices is { Length: > 1 }, $"{s.Id}: has choices"); + if (s.Kind == AcGraphicsKind.Float) Check(s.Max > s.Min && s.Step > 0, $"{s.Id}: slider range"); + } + Check(AcGraphicsPrefs.WindowModeIds.Length == AcGraphicsPrefs.WindowModeLabels.Length, "a label per window mode"); + + // ── Memory risk: Adaptive degrade off with a far draw distance (2026-10-18) ── + Check(AcGraphicsPrefs.MemoryRisk("False", "Extreme", null).StartsWith("Warning"), "risk: degrade off, Extreme scenery"); + Check(AcGraphicsPrefs.MemoryRisk("false", null, "High").Length > 0, "risk: degrade off, High landscape (any case)"); + Check(AcGraphicsPrefs.MemoryRisk("False", "Medium", "Medium").Length == 0, "no risk: degrade off, Medium distances"); + Check(AcGraphicsPrefs.MemoryRisk("True", "Extreme", "Extreme").Length == 0, "no risk: degrade on"); + Check(AcGraphicsPrefs.MemoryRisk(null, "Extreme", "Extreme").Length == 0, "no risk: degrade at AC's default"); + Check(AcGraphicsPrefs.MemoryRisk("False", null, null).Length == 0, "no risk: distances at AC's default"); + foreach (string id in new[] { AcGraphicsPrefs.AutomaticDegradesId, AcGraphicsPrefs.SceneryDrawDistanceId, AcGraphicsPrefs.LandscapeDrawDistanceId }) + Check(Array.Exists(AcGraphicsPrefs.RenderSettings, s => s.Id == id), $"{id} is a Render setting"); +} +finally +{ + try { Directory.Delete(dir, recursive: true); } catch { } +} + +Console.WriteLine(failures == 0 ? $"PASS ({checks} checks)" : $"{failures} FAILURE(S) of {checks} checks"); +return failures == 0 ? 0 : 1; diff --git a/tools/BarDeclutterTests/Program.cs b/tools/BarDeclutterTests/Program.cs index 06bf208..cb570fa 100644 --- a/tools/BarDeclutterTests/Program.cs +++ b/tools/BarDeclutterTests/Program.cs @@ -259,6 +259,7 @@ internal static class Program yield return ("Tools", l.Tools); yield return ("Modern", l.Modern); yield return ("Vault", l.Vault); + yield return ("Shop", l.Shop); yield return ("Remote", l.Remote); yield return ("Sort", l.Sort); yield return ("Count", l.Count); @@ -278,6 +279,7 @@ internal static class Program Check(present[i - 1].Slot.Right <= present[i].Slot.X + 0.001f, $"{tag}: {present[i - 1].Name} does not overlap {present[i].Name} ({present[i - 1].Slot.Right} vs {present[i].Slot.X})"); Eq(l.Vault.Present, vault, $"{tag}: Vault present iff the server has it"); + Check(l.Shop.Present, $"{tag}: Trade Shop Storefront is on the bar"); bool extrasShown = l.Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons; Eq(l.Remote.Present && l.Sort.Present && l.Count.Present && l.GInv.Present, extrasShown, $"{tag}: all four related buttons or none"); Eq(l.More.Present, l.Mode == TitleExtrasMode.Menu, $"{tag}: the more button iff Menu mode"); @@ -325,9 +327,11 @@ internal static class Program Eq(InventoryTitleLayout.Compute(276f * 1.5f, 1.5f, true, 130f * 1.5f).Mode, TitleExtrasMode.Menu, "retail at 1.5x + Vault: more menu"); // The case from the review: 190 px of text buttons used to push Vault to x=-44 at 300 / scale 1. + // Trade Shop sits left of Vault; title room is a bit tighter than the pre-Shop layout (~100 px). var r = InventoryTitleLayout.Compute(276f, 1f, true, 130f); Check(r.Vault.X > 100f && r.Vault.Right <= r.Smaller.X, $"Vault sits just left of the toggles at retail width (x={r.Vault.X})"); - Check(r.TitleWidth >= 100f, $"and the title keeps {r.TitleWidth} px at retail width"); + Check(r.Shop.Present && r.Shop.Right <= r.Vault.X, $"Shop sits left of Vault (x={r.Shop.X})"); + Check(r.TitleWidth >= 80f, $"and the title keeps {r.TitleWidth} px at retail width"); // Everything is relative to the bar: scaling the bar scales the positions (whole-pixel rounding aside). var a = InventoryTitleLayout.Compute(276f, 1f, true, 130f); @@ -350,8 +354,10 @@ internal static class Program Check(l.TitleWidth >= 0f, $"w={barW}: title width never negative"); } // Far too narrow for the toggles: Vault is clamped at the left edge, never negative; no related buttons. + // Trade Shop is dropped so it does not pile on top of the pinned Vault. var tiny = InventoryTitleLayout.Compute(60f, 1f, true, 130f); Check(tiny.Vault.Present && tiny.Vault.X == 0f, "a 60 px bar: Vault pinned at x=0, not negative"); + Check(!tiny.Shop.Present, "a 60 px bar: Trade Shop dropped (no room left of Vault)"); Eq(tiny.Mode, TitleExtrasMode.None, "a 60 px bar: no related buttons"); Check(tiny.TitleWidth >= 0f, "a 60 px bar: title width not negative"); var noVault = InventoryTitleLayout.Compute(60f, 1f, false, 130f); @@ -408,6 +414,7 @@ internal static class Program yield return ("Close", h.Close); yield return ("Classic", h.Classic); yield return ("Vault", h.Vault); + yield return ("Shop", h.Shop); yield return ("Remote", h.Remote); yield return ("Sort", h.Sort); yield return ("Count", h.Count); @@ -417,32 +424,32 @@ internal static class Program private static void HeaderVault() { - Console.WriteLine("Modern header: the Vault button"); + Console.WriteLine("Modern header: Vault + Trade Shop Storefront"); - // Without a vault the plan is exactly the old one, so the header is unchanged off Aelrynth. + // Without a vault, ChooseHeader still reserves Trade Shop (24 px) before the related buttons. foreach (float free in new[] { -30f, 0f, 10f, 24f, 40f, 90f, 100f, 130f, 300f }) foreach (float cw in new[] { 0f, 30f, 50f, 80f }) { var plan = InventoryTitleLayout.ChooseHeader(free, cw, vault: false); - TitleExtrasMode old = InventoryTitleLayout.ChooseHeaderExtras(free, cw, out bool oldCount); - Check(!plan.Vault && plan.Extras == old && plan.ShowCount == oldCount, $"no vault: same as ChooseHeaderExtras (free {free}, count {cw})"); + TitleExtrasMode old = InventoryTitleLayout.ChooseHeaderExtras(free - InventoryTitleLayout.HeaderShopW, cw, out bool oldCount); + Check(!plan.Vault && plan.Extras == old && plan.ShowCount == oldCount, $"no vault: Shop reserved then ChooseHeaderExtras (free {free}, count {cw})"); } - // With a vault the Vault takes its 24 px first; the rest shares what is left. + // With a vault: Vault + Shop take 48 px first; the rest shares what is left. + const float reservedVaultShop = 24f + 24f; // HeaderVaultW + HeaderShopW Eq(InventoryTitleLayout.ChooseHeader(300f, 50f, true).Extras, TitleExtrasMode.Icons, "lots of room + vault: four icons"); - Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f - 1f, 50f, true).Extras, TitleExtrasMode.Menu, "one px short of icons + vault: the menu"); - Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f, 50f, true).Extras, TitleExtrasMode.Icons, "icons + count + vault just fit"); - Eq(InventoryTitleLayout.ChooseHeader(24f + 24f + 60f, 50f, true).Extras, TitleExtrasMode.Menu, "vault + menu + count"); - var tight = InventoryTitleLayout.ChooseHeader(24f + 24f, 50f, true); - Check(tight.Vault && tight.Extras == TitleExtrasMode.Menu && !tight.ShowCount, "vault + menu, the count text dropped"); - var tiny = InventoryTitleLayout.ChooseHeader(24f, 50f, true); - Check(tiny.Vault && tiny.Extras == TitleExtrasMode.None && !tiny.ShowCount, "room for the vault only: no menu, no count"); + Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + reservedVaultShop - 1f, 50f, true).Extras, TitleExtrasMode.Menu, "one px short of icons + vault + shop: the menu"); + Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + reservedVaultShop, 50f, true).Extras, TitleExtrasMode.Icons, "icons + count + vault + shop just fit"); + Eq(InventoryTitleLayout.ChooseHeader(reservedVaultShop + 24f + 60f, 50f, true).Extras, TitleExtrasMode.Menu, "vault + shop + menu + count"); + var tight = InventoryTitleLayout.ChooseHeader(reservedVaultShop + 24f, 50f, true); + Check(tight.Vault && tight.Extras == TitleExtrasMode.Menu && !tight.ShowCount, "vault + shop + menu, the count text dropped"); + var tiny = InventoryTitleLayout.ChooseHeader(reservedVaultShop, 50f, true); + Check(tiny.Vault && tiny.Extras == TitleExtrasMode.None && !tiny.ShowCount, "room for vault + shop only: no menu, no count"); foreach (float free in new[] { 20f, 0f, -40f, float.NaN, float.NegativeInfinity }) Check(InventoryTitleLayout.ChooseHeader(free, 50f, true).Vault, $"the Vault is kept whatever the room ({free})"); // Every supported width (the panel's minimum is 140 px) and a range of left-hand text widths: - // the Vault is present, inside the header, clear of the other buttons, and nothing drawn right of the - // pyreals overlaps anything else. Without a vault the geometry is the one the header always had. + // Vault (when asked) and Shop are present, inside the header, clear of the other buttons. int checkedLayouts = 0; for (float w = 140f; w <= 800f; w += 1f) foreach (float leftEnd in new[] { 80f, 120f, 150f, 200f }) @@ -467,6 +474,8 @@ internal static class Program Check(ok, $"{tag}: buttons inside the header and not overlapping"); Check(h.Plan.Vault == vault && h.Vault.Present == vault, $"{tag}: the Vault button exists exactly when asked for"); + Check(h.Shop.Present && h.Shop.W >= 22f, $"{tag}: Trade Shop Storefront is always present"); + Check(h.Shop.Right <= (vault ? h.Vault.X : h.Classic.X) + 0.001f, $"{tag}: Shop sits left of Vault/Classic"); if (vault) { Check(h.Vault.Right <= h.Classic.X + 0.001f && h.Vault.X >= 0f, $"{tag}: Vault sits left of the Classic button, inside the header"); @@ -478,30 +487,31 @@ internal static class Program else { Check(h.Classic.X == w - 46 && h.Close.X == w - 22, $"{tag}: Close / Classic where they always were"); - if (h.Plan.Extras == TitleExtrasMode.Icons) Check(h.GInv.X == w - 46 - 24 && h.Remote.X == w - 46 - 96, $"{tag}: the four icons where they always were"); - if (h.Plan.Extras == TitleExtrasMode.Menu) Check(h.More.X == w - 46 - 24, $"{tag}: the menu button where it always was"); + Check(h.Shop.X == w - 46 - 24, $"{tag}: Shop right beside Classic when there is no Vault"); + if (h.Plan.Extras == TitleExtrasMode.Icons) Check(h.GInv.X == h.Shop.X - 24 && h.Remote.X == h.Shop.X - 96, $"{tag}: the four icons start left of Shop"); + if (h.Plan.Extras == TitleExtrasMode.Menu) Check(h.More.X == h.Shop.X - 24, $"{tag}: the menu button sits left of Shop"); } // Related buttons / count never reach back over the pyreals when there was room for them. TitleSlot? leftmost = h.Plan.Extras == TitleExtrasMode.Icons ? h.Remote : h.Plan.Extras == TitleExtrasMode.Menu ? h.More : null; if (leftmost is { } lm) Check(lm.X >= leftEnd + 4f - 0.001f, $"{tag}: related buttons start clear of the pyreals text"); if (h.Plan.ShowCount) - Check(h.CountX + cw <= (leftmost?.X ?? (vault ? h.Vault.X : h.Classic.X)) + 0.001f, $"{tag}: the count text sits left of the buttons"); + Check(h.CountX + cw <= (leftmost?.X ?? h.Shop.X) + 0.001f, $"{tag}: the count text sits left of the buttons"); } Check(checkedLayouts > 10000, $"swept the layouts ({checkedLayouts})"); - // At the retail width (302 px) and the usual left-hand text the Vault is a button, and so are the - // rest that fit: a worked example. + // At the retail width (302 px) and the usual left-hand text: Vault, Shop, and the menu that fits. var r = InventoryHeaderLayout.Compute(302f, 150f, 50f, vault: true); Check(r.Vault.Present && r.Vault.X == 302f - 46 - 24, "302 px: Vault right beside the Classic button"); + Check(r.Shop.Present && r.Shop.X == r.Vault.X - 24, "302 px: Shop left of Vault"); Eq(r.Plan.Extras, TitleExtrasMode.Menu, "302 px with a vault: related panels fold into the menu"); - Check(r.More.Present && r.More.Right <= r.Vault.X, "...left of the Vault"); + Check(r.More.Present && r.More.Right <= r.Shop.X, "...left of Shop"); var wide = InventoryHeaderLayout.Compute(600f, 150f, 50f, vault: true); Eq(wide.Plan.Extras, TitleExtrasMode.Icons, "600 px with a vault: four icons"); - Check(wide.Vault.X == 600f - 46 - 24 && wide.GInv.X == wide.Vault.X - 24, "...the icons start just left of the Vault"); + Check(wide.Vault.X == 600f - 46 - 24 && wide.Shop.X == wide.Vault.X - 24 && wide.GInv.X == wide.Shop.X - 24, "...icons start just left of Shop"); - // Garbage in, no crash and the Vault still present. + // Garbage in, no crash and the Vault / Shop still present. var bad = InventoryHeaderLayout.Compute(float.NaN, float.NaN, float.NaN, vault: true); - Check(bad.Vault.Present, "NaN sizes: the Vault slot exists (the caller never draws a header this small)"); + Check(bad.Vault.Present && bad.Shop.Present, "NaN sizes: Vault and Shop slots exist (the caller never draws a header this small)"); } } diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index b0f2d29..81a8a8d 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -112,6 +112,9 @@ internal static class Program ("actionstate", "actions", "actionstate now"), ("unlockactions", "unlock", "unlockactions now"), ("vitals", "hud", "vitals now"), + // 2026-11-01: the test branch's verbs, now in the list. + ("borderless", "borderless on", "borderless frob"), + ("radar", "radar", "radar now"), ("layout", "layout", "layout frob"), ("layout", "layout reset confirm", "layout reset now"), ("layout", "layout default", "layout default now"), @@ -154,6 +157,9 @@ internal static class Program private static readonly (string Verb, string Valid, string Invalid, string Who)[] Handled = { ("vendor", "vendor list", "vendor frob", "VendorTrade: '[RC] /rc vendor list | info | ...'"), + ("chatlinkprobe", "chatlinkprobe 30", "chatlinkprobe frob", "ChatLinkProbe.Command: its usage"), + ("switchchar", "switchchar Kelpie", "switchchar", "CharacterCaptureHooks.RequestSwitch: says a name is needed"), + ("window", "window reset", "window frob", "the window usage (a failure)"), ("ui", "ui list", "ui frob", "HandleUiCommand: its usage"), ("discord", "discord status", "discord frob", "ChatDiscord.HandleCommand: its usage"), ("plates", "plates status", "plates frob", "HandlePlatesCommand: the plates usage"), @@ -211,8 +217,9 @@ internal static class Program Check(unknown.Problem!.Contains(v.Name, StringComparison.Ordinal), $"the list names {v.Name}"); ChatVerbCheck bare = ChatCommandReplies.Check(""); Check(bare.Verb == null && bare.Problem != null && bare.Problem.StartsWith("Usage: /rc <command>.", StringComparison.Ordinal), "'/rc' alone: the usage and the list"); - Check(ChatCommandReplies.Check("window save").Problem!.StartsWith("Unknown command '/rc window'", StringComparison.Ordinal), - "'/rc window save' (sent by /ub window save) is not an engine verb, and now says so"); + // The test branch's /rc window (reset | save | fill) is an engine verb: '/rc window save' (also what + // /ub window save sends) runs it. Before 2026-11-01 the list lacked it and answered "Unknown command". + Check(ChatCommandReplies.Check("window save") is { Problem: null, Verb.Name: "window" }, "'/rc window save' runs the engine's window verb"); Check(ChatCommandReplies.Check(" SKILLS Show ").Problem == null, "case and spaces as IsVerb takes them"); } diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj index e870212..6cd5c0c 100644 --- a/tools/ChatFilterTests/ChatFilterTests.csproj +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -34,6 +34,9 @@ <Compile Include="..\..\src\RynthCore.Engine\UI\Panels\RynthChatPresets.cs" Link="Engine\RynthChatPresets.cs" /> <!-- 2026-10-19: re-reading the shared rynthchat_settings.json when another client saved it. --> <Compile Include="..\..\src\RynthCore.Engine\UI\Data\SharedFileWatch.cs" Link="Engine\SharedFileWatch.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatSettingsMerge.cs" Link="Engine\ChatSettingsMerge.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatReplyTab.cs" Link="Engine\ChatReplyTab.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\ServerCommandFallback.cs" Link="Engine\ServerCommandFallback.cs" /> <!-- 2026-11-05: a plugin's own colour for a line it writes (RynthAi's Info text colour). --> <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatOwnColors.cs" Link="Engine\ChatOwnColors.cs" /> </ItemGroup> diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 20cb2dd..5f8cdcd 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -60,6 +60,10 @@ internal static class Program LineColorRetail(); LineColorPrecedence(); LineColorJson(); + SettingsMergeOnSave(); + CommandReplyInTypedTab(); + FshipListNotFiltered(); + ServerCommandsWithoutChatTarget(); HighlightRouting(); HighlightPrecedence(); HighlightBand(); @@ -80,12 +84,144 @@ internal static class Program return _failed == 0 ? 0 : 1; } + /// <summary> + /// Silentkelpie 2026-10-23, two days into a session: rule after rule was "too slow ... skipped + /// until edited", even "^\[RynthNet] Silentstorm connected\.$" - a pause of the thread during an + /// easy match. A timed-out match now runs once more before a rule is judged slow, and a slow rule + /// is tried again after 10 minutes (doubling per strike, at most 4 hours); an edit still resets it. + /// </summary> + /// <summary> + /// Silentkelpie 2026-10-24: filters kept "losing". Every client saves the whole shared + /// rynthchat_settings.json; one that hadn't picked up another client's change (chat window + /// closed, so it never polled) wrote its stale rules back over it. A save now merges with the + /// file per setting: what this client changed since its base wins, the rest is the file's. + /// </summary> + private static void SettingsMergeOnSave() + { + Case("settings merge: a save never undoes another client's rules"); + const string baseJson = "{\"version\":2,\"fontSize\":10,\"activeChannel\":\"All\",\"filters\":[{\"pattern\":\"old\"}],\"presets\":[{\"id\":\"a\",\"enabled\":true}]}"; + // Another client added a rule and turned a standard filter off. + const string theirs = "{\"version\":2,\"fontSize\":10,\"activeChannel\":\"Loot\",\"filters\":[{\"pattern\":\"old\"},{\"pattern\":\"new\"}],\"presets\":[]}"; + // This client (stale) only changed its font size and tab. + const string mine = "{\"version\":2,\"fontSize\":12,\"activeChannel\":\"Combat\",\"filters\":[{\"pattern\":\"old\"}],\"presets\":[{\"id\":\"a\",\"enabled\":true}]}"; + + string merged = ChatSettingsMerge.Merge(baseJson, mine, theirs); + using (var doc = JsonDocument.Parse(merged)) + { + JsonElement root = doc.RootElement; + Check(root.GetProperty("filters").GetArrayLength() == 2, "the other client's new rule survives"); + Check(root.GetProperty("presets").GetArrayLength() == 0, "the other client's preset change survives"); + Check(root.GetProperty("fontSize").GetInt32() == 12, "this client's own change is saved"); + Check(root.GetProperty("activeChannel").GetString() == "Combat", "this client's tab is its own"); + } + + // This client edited the rules too: its list wins (one setting), the other client's font stays. + const string theirsFont = "{\"version\":2,\"fontSize\":14,\"activeChannel\":\"All\",\"filters\":[{\"pattern\":\"old\"}],\"presets\":[{\"id\":\"a\",\"enabled\":true}]}"; + const string mineRules = "{\"version\":2,\"fontSize\":10,\"activeChannel\":\"All\",\"filters\":[{\"pattern\":\"mine\"}],\"presets\":[{\"id\":\"a\",\"enabled\":true}]}"; + using (var doc = JsonDocument.Parse(ChatSettingsMerge.Merge(baseJson, mineRules, theirsFont))) + { + Check(doc.RootElement.GetProperty("filters")[0].GetProperty("pattern").GetString() == "mine", "this client's rule edit is saved"); + Check(doc.RootElement.GetProperty("fontSize").GetInt32() == 14, "the other client's font size stays"); + } + + // A setting only the other client has (newer build), and one this client removed. + const string theirsExtra = "{\"version\":2,\"fontSize\":10,\"filters\":[{\"pattern\":\"old\"}],\"presets\":[{\"id\":\"a\",\"enabled\":true}],\"activeChannel\":\"All\",\"lineColors\":{\"x\":1}}"; + const string mineNoPresets = "{\"version\":2,\"fontSize\":10,\"activeChannel\":\"All\",\"filters\":[{\"pattern\":\"old\"}]}"; + using (var doc = JsonDocument.Parse(ChatSettingsMerge.Merge(baseJson, mineNoPresets, theirsExtra))) + { + Check(doc.RootElement.TryGetProperty("lineColors", out _), "a setting only the other client wrote is kept"); + Check(!doc.RootElement.TryGetProperty("presets", out _), "a setting this client removed stays removed"); + } + + Check(ChatSettingsMerge.Merge(baseJson, mine, baseJson) == mine, "nobody else saved: this client's text as is"); + Check(ChatSettingsMerge.Merge(null, mine, theirs) == mine, "no base (first save): this client's text"); + Check(ChatSettingsMerge.Merge(baseJson, mine, "{ cut-off") == mine, "a broken file is never merged in"); + Check(ChatSettingsMerge.Merge(baseJson, mine, null) == mine, "no file: this client's text"); + } + + /// <summary> + /// Silentkelpie 2026-10-24: /fship typed on another tab "didn't show": its replies are System + /// lines, shown only under All and System. A command sent from the box now puts the System and + /// Rynth lines of the next few seconds in the tab it was typed in too. + /// </summary> + private static void CommandReplyInTypedTab() + { + Case("command replies: shown in the tab the command was typed in"); + Check(ChatReplyTab.IsCommand("/fship"), "/fship is a command"); + Check(ChatReplyTab.IsCommand("/bank d p 10k"), "a command with arguments"); + Check(ChatReplyTab.IsCommand("@help"), "an @ command"); + Check(!ChatReplyTab.IsCommand("/tell Bob, hi"), "/tell is chat"); + Check(!ChatReplyTab.IsCommand("/f hello fellows"), "/f is chat"); + Check(!ChatReplyTab.IsCommand("/a hello"), "/a is chat"); + Check(!ChatReplyTab.IsCommand("hello"), "plain text is chat"); + Check(!ChatReplyTab.IsCommand("/"), "a lone slash"); + + var reply = new ChatReplyTab(); + reply.NoteSent("/fship", "Chat", nowMs: 1000); + Check(reply.TabFor("System", automated: false, nowMs: 1200) == "Chat", "the server's reply also shows in Chat"); + Check(reply.TabFor("Rynth", automated: false, nowMs: 1200) == "Chat", "a plugin's reply too"); + Check(reply.TabFor("Combat", automated: false, nowMs: 1200) == null, "combat lines stay where they are"); + Check(reply.TabFor("System", automated: true, nowMs: 1200) == null, "a plugin's own poll reply isn't copied"); + Check(reply.TabFor("System", automated: false, nowMs: 1000 + ChatReplyTab.WindowMs + 1) == null, "only for a few seconds"); + + var fromAll = new ChatReplyTab(); + fromAll.NoteSent("/fship", "All", nowMs: 1000); + Check(fromAll.TabFor("System", false, 1200) == null, "typed in All: it already shows there"); + + var fromSystem = new ChatReplyTab(); + fromSystem.NoteSent("/fship", "System", nowMs: 1000); + Check(fromSystem.TabFor("System", false, 1200) == null, "typed in System: already there"); + Check(fromSystem.TabFor("Rynth", false, 1200) == "System", "a plugin reply still follows to System"); + + var chat = new ChatReplyTab(); + chat.NoteSent("/tell Bob, hi", "Combat", nowMs: 1000); + Check(chat.TabFor("System", false, 1200) == null, "a /tell marks nothing"); + } + private static void Case(string name) { _case = name; Console.WriteLine("- " + name); } + /// <summary> + /// Silentkelpie 2026-10-30: /fship list showed nowhere in RynthChat. ILT's reply (flight + /// recorder, chat type 0): a dashed rule, "[FSHIP]: Fellowships in your area:", one line per + /// fellowship, a dashed rule. No standard filter (every one on) may hide it. + /// </summary> + private static void FshipListNotFiltered() + { + string[] reply = + { + "---------------------------", + "[FSHIP]: Fellowships in your area:", + " 'But the lum is so good' led by Io (Leader not in area)", + "No fellowships found in your area.", + }; + foreach (var p in RynthCore.Engine.UI.Panels.RynthChatPresets.All) + foreach (string line in reply) + Check(!p.Matches(line, "System"), $"fship list: standard filter '{p.Id}' leaves \"{line.Trim()}\" alone"); + } + + /// <summary> + /// 2026-10-30: with no chat target captured yet, a server command goes out as "@command" + /// (ACE runs it as the "/command"); AC's own commands and chat still need the chat bar. + /// </summary> + private static void ServerCommandsWithoutChatTarget() + { + static string? At(string c) => RynthCore.Engine.Compatibility.ServerCommandFallback.TryAsServerCommand(c, out string? a) ? a : null; + Check(At("/fship list") == "@fship list", "/fship list -> @fship list"); + Check(At(" /bank ") == "@bank", "/bank -> @bank (trimmed)"); + Check(At("/myquests") == "@myquests", "/myquests -> @myquests"); + Check(At("/f hello all") == null, "/f is fellowship chat: the chat bar"); + Check(At("/tell Bob, hi") == null, "/tell: the chat bar"); + Check(At("/framerate") == null, "/framerate is AC's own"); + Check(At("/LOC") == null, "/loc is AC's own (any case)"); + Check(At("hello") == null, "plain text isn't a command"); + Check(At("/") == null && At("/1") == null, "no command word"); + Check(At("/fship add Bjørn") == null, "non-ASCII stays on the chat bar"); + } + private static void Check(bool ok, string what) { _checks++; diff --git a/tools/ChatHistoryBench/Program.cs b/tools/ChatHistoryBench/Program.cs index 4fc2bd7..6cbdade 100644 --- a/tools/ChatHistoryBench/Program.cs +++ b/tools/ChatHistoryBench/Program.cs @@ -26,6 +26,7 @@ internal static unsafe class Program InitImGui(); ScrollChecks(); HistoryChecks(); + AutomatedChecks(); Memory(); Cpu(); Console.WriteLine(); @@ -466,6 +467,54 @@ internal static unsafe class Program Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}: {detail}"); } + /// <summary> + /// Automated system text (2026-10-19): RynthChat marks it ("auto"), and the router shows it in + /// the System tab only, unless a rule placed it or the setting is off. + /// </summary> + private static void AutomatedChecks() + { + Console.WriteLine(); + Console.WriteLine("Automated system text checks:"); + const int Broadcast = 0x00, Say = 0x02, AdminTell = 0x1F, Notice = 0x1A; + var router = new ChatRouter(Array.Empty<ChatFilterRule>(), null, "Drakkon", countHits: false, automatedToSystem: true); + var line = new ChatLine(1, "08:00:00", "System", Broadcast, null, "Dynamic_1_ANND! - 1 solves (1719432000)\"Dynamic\" 1 0") { Automated = true }; + ChatRoute route = router.Evaluate(line, null); + Check("an automated line shows in System only", route.ShowsIn("System", "System") && !route.ShowsIn("All", "System"), ""); + var other = new ChatLine(2, "08:00:00", "Other", Notice, null, "flagone") { Automated = true }; + ChatRoute r2 = router.Evaluate(other, null); + Check("an automated line from another channel goes to System, not All or Other", + r2.ShowsIn("System", "Other") && !r2.ShowsIn("All", "Other") && !r2.ShowsIn("Other", "Other"), ""); + var plain = new ChatLine(3, "08:00:00", "System", Broadcast, null, "You feel a chill."); + Check("a line not marked automated still shows under All", router.Evaluate(plain, null).ShowsIn("All", "System"), ""); + var off = new ChatRouter(Array.Empty<ChatFilterRule>(), null, "Drakkon", countHits: false, automatedToSystem: false); + Check("setting off: automated lines show under All", off.Evaluate(line, null).ShowsIn("All", "System"), ""); + var move = new ChatFilterRule { Pattern = "solves", Tab = "Quests", Action = ChatRuleAction.Move }; + move.Recompile(); + var ruled = new ChatRouter(new[] { move }, null, "Drakkon", countHits: false, automatedToSystem: true); + ChatRoute r3 = ruled.Evaluate(line, null); + Check("a rule that moves it still decides first", r3.ShowsIn("Quests", "System") && !r3.ShowsIn("System", "System"), ""); +#if HAVE_RYNTHCHAT + Check("classifier: /myquests and /qb lines are automated (system types only)", + RynthCore.Plugin.RynthChat.ChatClassifier.IsAutomatedText("bigflag00001 - 3 solves (1719432000)\"Q\" -1 0", Broadcast) + && RynthCore.Plugin.RynthChat.ChatClassifier.IsAutomatedText("Your current quest bonus count: 15,234", Broadcast) + && RynthCore.Plugin.RynthChat.ChatClassifier.IsAutomatedText("Welcome to Asheron's Call\n powered by ACEmulator", Broadcast) + && !RynthCore.Plugin.RynthChat.ChatClassifier.IsAutomatedText("bigflag00001 - 3 solves (1719432000)\"Q\" -1 0", Say) + && !RynthCore.Plugin.RynthChat.ChatClassifier.IsAutomatedText("Your current quest bonus count: 1", AdminTell), ""); + var b = new RynthCore.Plugin.RynthChat.ChatBuffer(100); + b.Add("Welcome back, the server restarts at noon.", Broadcast, loginBurst: true); + b.Add("Bob says, \"hi\"", Say, loginBurst: true); + b.Add("An admin tells you, \"hello\"", AdminTell, loginBurst: true); + b.Add("You feel a chill.", Broadcast, loginBurst: false); + b.Add("qbflagthree", Notice); + bool markedWrong = b.NoteEaten("not the newest line"); + bool marked = b.NoteEaten("qbflagthree"); + bool[] autos = JsonSerializer.Deserialize(b.BuildJson(0), RynthChatJsonContext.Default.RynthChatLineDtoArray)!.Select(d => d.Auto).ToArray(); + Check("buffer: login-burst system text is automated; speech, an admin's tell and later text aren't", + autos.Length == 5 && autos[0] && !autos[1] && !autos[2] && !autos[3], string.Join(",", autos)); + Check("buffer: an eaten line is marked when it is the newest; other text isn't", marked && !markedWrong && autos[4], ""); +#endif + } + /// <summary>ChatHistory's arithmetic and RynthChat's resizable ring (newest kept, seq untouched).</summary> private static void HistoryChecks() { diff --git a/tools/ChatHistoryBench/Stubs.cs b/tools/ChatHistoryBench/Stubs.cs index 52391ec..642b779 100644 --- a/tools/ChatHistoryBench/Stubs.cs +++ b/tools/ChatHistoryBench/Stubs.cs @@ -12,6 +12,21 @@ namespace RynthCore.Engine.Compatibility } } +namespace RynthCore.Engine.UI.Panels +{ + /// <summary>The standard filters ChatRouter checks after the rules: none enabled here.</summary> + internal static class RynthChatPresets + { + internal sealed class Preset + { + internal string Tab { get; } = ""; + internal string Label { get; } = ""; + } + + internal static Preset? FirstMatch(string text, string channel) => null; + } +} + namespace RynthCore.Engine.UI.Data { internal static class ChatModel diff --git a/tools/DatShareSlotTests/DatShareSlotTests.csproj b/tools/DatShareSlotTests/DatShareSlotTests.csproj new file mode 100644 index 0000000..d9c2d7b --- /dev/null +++ b/tools/DatShareSlotTests/DatShareSlotTests.csproj @@ -0,0 +1,24 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs (2026-10-15): + the 2025 ACClient.exe resolves kernel32!CreateFileW into a private slot on first use and opens + its DAT files through it, so the DAT share hook has to find that slot as well as the import + slots. Synthetic images cover the stub shape and the near misses that must not match; when the + 2025 client is on this PC (or RYNTH_ACCLIENT points at one) its real slot is checked too. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>DatShareSlotTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs" Link="Engine\LazyImportSlotScanner.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/DatShareSlotTests/Program.cs b/tools/DatShareSlotTests/Program.cs new file mode 100644 index 0000000..431c8b8 --- /dev/null +++ b/tools/DatShareSlotTests/Program.cs @@ -0,0 +1,241 @@ +using System.Text; +using RynthCore.Engine.Compatibility; + +namespace DatShareSlotTests; + +/// <summary> +/// LazyImportSlotScanner: finds the private CreateFileW slot the 2025 ACClient.exe fills on first +/// use. Without it the DAT share hook missed every DAT open and a second client failed with +/// "Can't open the data files" (2026-10-15). +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + // Synthetic image layout: headers, .text at 0x1000 (code), .rdata at 0x2000 (strings + slots). + private const uint ImageBase = 0x00400000; + private const uint TextRva = 0x1000; + private const uint DataRva = 0x2000; + private const int ImageSize = 0x3000; + private const uint DllRva = DataRva + 0x10; + private const uint NameRva = DataRva + 0x40; + private const uint SlotRva = DataRva + 0x100; + + private static int Main() + { + ReadsSections(); + FindsTheStub(); + UnresolvedOrResolvedSlotIsFoundTheSame(); + RejectsJmpThroughAnotherSlot(); + RejectsAnotherDll(); + RejectsNameAsTailOfLongerName(); + RejectsBrokenStubShape(); + OtherFunctionHasNoSlot(); + Real2025Client(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + // ── synthetic image ────────────────────────────────────────────────────── + + /// <summary>A minimal PE32 header with .text and .rdata, plus "kernel32.dll" and the name.</summary> + private static byte[] NewImage(string functionName = "CreateFileW", string dllName = "kernel32.dll") + { + var img = new byte[ImageSize]; + const int pe = 0x80; + BitConverter.TryWriteBytes(img.AsSpan(0x3C), pe); + Encoding.ASCII.GetBytes("PE\0\0").CopyTo(img, pe); + BitConverter.TryWriteBytes(img.AsSpan(pe + 6), (ushort)2); // NumberOfSections + BitConverter.TryWriteBytes(img.AsSpan(pe + 20), (ushort)0xE0); // SizeOfOptionalHeader + BitConverter.TryWriteBytes(img.AsSpan(pe + 24), (ushort)0x10B); // PE32 + int table = pe + 24 + 0xE0; + WriteSection(img, table, ".text", TextRva, 0x1000, 0x60000020); + WriteSection(img, table + 40, ".rdata", DataRva, 0x1000, 0x40000040); + Encoding.ASCII.GetBytes(dllName + "\0").CopyTo(img, DllRva); + Encoding.ASCII.GetBytes(functionName + "\0").CopyTo(img, NameRva); + return img; + } + + private static void WriteSection(byte[] img, int at, string name, uint rva, uint size, uint flags) + { + Encoding.ASCII.GetBytes(name.PadRight(8, '\0')).CopyTo(img, at); + BitConverter.TryWriteBytes(img.AsSpan(at + 8), size); + BitConverter.TryWriteBytes(img.AsSpan(at + 12), rva); + BitConverter.TryWriteBytes(img.AsSpan(at + 16), size); + BitConverter.TryWriteBytes(img.AsSpan(at + 20), rva); + BitConverter.TryWriteBytes(img.AsSpan(at + 36), flags); + } + + /// <summary>Writes the stub at <paramref name="stubRva"/>, the same bytes the 2025 client has.</summary> + private static void WriteStub(byte[] img, uint stubRva, uint slotVa, uint nameVa, uint dllVa, uint jmpSlotVa) + { + var code = new List<byte>(); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(0x00405BB3u)); // push fallback + code.Add(0xFF); code.Add(0x35); code.AddRange(BitConverter.GetBytes(0x00906788u)); // push [handle cache] + code.Add(0x68); code.AddRange(BitConverter.GetBytes(slotVa)); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(nameVa)); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(dllVa)); + code.Add(0xE8); code.AddRange(BitConverter.GetBytes(0xFFD4CD41u)); // call resolver + code.Add(0xFF); code.Add(0x25); code.AddRange(BitConverter.GetBytes(jmpSlotVa)); // jmp [slot] + code.CopyTo(img, (int)stubRva); + } + + private static List<LazyImportSlot> Scan(byte[] img, string function = "CreateFileW") => + LazyImportSlotScanner.FindSlots(img, ImageBase, LazyImportSlotScanner.ReadSections(img), "kernel32.dll", function); + + // ── cases ──────────────────────────────────────────────────────────────── + + private static void ReadsSections() + { + _case = "sections"; + var s = LazyImportSlotScanner.ReadSections(NewImage()); + Check(s.Count == 2, $"two sections, got {s.Count}"); + Check(s.Count == 2 && s[0].Name == ".text" && s[0].Executable && s[0].Rva == TextRva, ".text is code at 0x1000"); + Check(s.Count == 2 && s[1].Name == ".rdata" && !s[1].Executable && s[1].Rva == DataRva, ".rdata is data at 0x2000"); + Check(LazyImportSlotScanner.ReadSections(new byte[0x100]).Count == 0, "no PE signature: nothing"); + } + + private static void FindsTheStub() + { + _case = "stub"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + var found = Scan(img); + Check(found.Count == 1, $"one slot, got {found.Count}"); + Check(found.Count == 1 && found[0].SlotVa == ImageBase + SlotRva, $"slot 0x{ImageBase + SlotRva:X8}"); + Check(found.Count == 1 && found[0].StubVa == ImageBase + TextRva + 0x20, $"stub at 0x{ImageBase + TextRva + 0x20:X8}, got 0x{(found.Count == 1 ? found[0].StubVa : 0):X8}"); + } + + private static void UnresolvedOrResolvedSlotIsFoundTheSame() + { + _case = "slot contents"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), ImageBase + TextRva + 0x20); // still points at its stub + Check(Scan(img).Count == 1, "unresolved (slot points at the stub)"); + BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), 0x76ACEA10u); // resolved to kernel32 + Check(Scan(img).Count == 1, "resolved (slot points into kernel32)"); + } + + private static void RejectsJmpThroughAnotherSlot() + { + _case = "jmp slot"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva + 8); + Check(Scan(img).Count == 0, "the jmp must go through the slot the stub fills"); + } + + private static void RejectsAnotherDll() + { + _case = "dll"; + var img = NewImage(dllName: "user32.dll"); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img).Count == 0, "a stub resolving from user32.dll is not kernel32's CreateFileW"); + var upper = NewImage(dllName: "KERNEL32.DLL"); + WriteStub(upper, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(upper).Count == 1, "the DLL name matches in any case"); + } + + private static void RejectsNameAsTailOfLongerName() + { + _case = "longer name"; + var img = NewImage(functionName: "MyCreateFileW"); + // Points at the "CreateFileW" tail of "MyCreateFileW". + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva + 2, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img).Count == 0, "\"MyCreateFileW\" is not CreateFileW"); + } + + private static void RejectsBrokenStubShape() + { + _case = "shape"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + img[TextRva + 0x20 + 26] = 0x90; // the call becomes a nop + Check(Scan(img).Count == 0, "no call to the resolver: not a stub"); + + var outside = NewImage(); + WriteStub(outside, TextRva + 0x20, 0x12345678, ImageBase + NameRva, ImageBase + DllRva, 0x12345678); + Check(Scan(outside).Count == 0, "a slot outside the image is never written"); + + var atStart = NewImage(); + WriteStub(atStart, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + // A lone push of the name at the very start of .text has no stub around it. + atStart[TextRva] = 0x68; + BitConverter.TryWriteBytes(atStart.AsSpan((int)TextRva + 1), ImageBase + NameRva); + Check(Scan(atStart).Count == 1, "a lone push of the name is skipped, the real stub still found"); + } + + private static void OtherFunctionHasNoSlot() + { + _case = "other function"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img, "CreateFileA").Count == 0, "only the named function's slot is returned"); + } + + // ── the real client ────────────────────────────────────────────────────── + + private static void Real2025Client() + { + _case = "ACClient.exe 0.0.11.6096"; + string? path = Environment.GetEnvironmentVariable("RYNTH_ACCLIENT"); + if (string.IsNullOrEmpty(path)) + path = @"C:\Turbine\Asheron's Call-ryn\ACClient.exe"; + if (!File.Exists(path)) + { + Console.WriteLine($" skip: {path} not found (set RYNTH_ACCLIENT to check a client)"); + return; + } + + byte[] mapped = MapImage(File.ReadAllBytes(path), out uint imageBase); + var sections = LazyImportSlotScanner.ReadSections(mapped); + var w = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileW"); + var a = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileA"); + Console.WriteLine($" {path}: CreateFileW slots {string.Join(", ", w.Select(s => $"0x{s.SlotVa:X8} (stub 0x{s.StubVa:X8})"))}; CreateFileA slots {a.Count}"); + + // Read from the running client on 2026-10-15: slot 0x00837374 held kernel32!CreateFileW. + if (imageBase == 0x00400000 && FileVersion(path) == "00.00.11.6096") + { + Check(w.Count == 1 && w[0].SlotVa == 0x00837374, "the CreateFileW slot is 0x00837374"); + Check(w.Count == 1 && w[0].StubVa == 0x006B8D00, "filled by the stub at 0x006B8D00"); + Check(a.Count == 0, "CreateFileA is a normal import, no private slot"); + } + } + + private static string FileVersion(string path) => + System.Diagnostics.FileVersionInfo.GetVersionInfo(path).FileVersion ?? ""; + + /// <summary>Lays a PE file out the way the loader maps it (headers, then each section at its RVA).</summary> + private static byte[] MapImage(byte[] file, out uint imageBase) + { + int pe = BitConverter.ToInt32(file, 0x3C); + int opt = pe + 24; + imageBase = BitConverter.ToUInt32(file, opt + 28); + uint sizeOfImage = BitConverter.ToUInt32(file, opt + 56); + uint sizeOfHeaders = BitConverter.ToUInt32(file, opt + 60); + var img = new byte[sizeOfImage]; + Array.Copy(file, img, Math.Min(sizeOfHeaders, (uint)file.Length)); + int count = BitConverter.ToUInt16(file, pe + 6); + int table = opt + BitConverter.ToUInt16(file, pe + 20); + for (int i = 0; i < count; i++) + { + int h = table + 40 * i; + uint rva = BitConverter.ToUInt32(file, h + 12); + uint rawSize = BitConverter.ToUInt32(file, h + 16); + uint raw = BitConverter.ToUInt32(file, h + 20); + uint n = Math.Min(rawSize, Math.Min(sizeOfImage - rva, (uint)file.Length - raw)); + Array.Copy(file, raw, img, rva, n); + } + return img; + } +} diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index d03bf1e..8246330 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -255,7 +255,8 @@ namespace EngineSettingsTests Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept"); Eq(after.GetProperty("DecalBridge").GetString(), "On", "DecalBridge On kept"); foreach (JsonProperty p in before.EnumerateObject()) - Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"unchanged key {p.Name} keeps the file's value"); + if (p.Name != "DisabledUiHooks") + Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"unchanged key {p.Name} keeps the file's value"); foreach (string key in new[] { "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableHangMinidump", "PreventIdleLogoff" }) Check(after.TryGetProperty(key, out _) == before.TryGetProperty(key, out _), $"owned key {key} not added or dropped by an unrelated save"); @@ -271,6 +272,17 @@ namespace EngineSettingsTests Eq(after.GetProperty("EnableImGuiBackend").GetBoolean(), false, "EnableImGuiBackend saved"); Check(after.TryGetProperty("EnableDcompOverlay", out _) && after.TryGetProperty("LauncherWindow", out _), "launcher keys survive a second save"); Eq(after.GetProperty("DisabledUiHooks").GetArrayLength(), 1, "first save's DisabledUiHooks kept"); + + // Two clients: one saved EnableImGuiBackend=false above; "another client" now turns the + // shell back on in the file. A later save of a different key here must not put the + // stale EnableImGuiShell back (the last-writer-wins reset of 2026-10-16). + var doc = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(path))!.AsObject(); + doc["EnableImGuiShell"] = true; + File.WriteAllText(path, doc.ToJsonString()); + (exit, output) = RunChild(path, "hook-off", "AnotherHook"); + Eq(exit, 0, "third child exit code (" + output.Trim() + ")"); + after = ReadJson(path); + Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), true, "another client's EnableImGuiShell survives this client's save"); } private static void SaveRoundTripsOwnedKeys() @@ -937,14 +949,23 @@ namespace EngineSettingsTests Eq(DecideSave(true, true, true, LogoutRect, InGame, ref pending, t0).Action, AcWindowPlacementRule.SaveAction.LoginShrink, "Save Layout Now on the login-size window: refused"); } - // Source guard: every SetWindowPos on the AC window keeps AC's size (R-20261115-160655-1201). + // Source guard: AC's window is never given a size of its own (R-20261115-160655-1201: a restored smaller + // window crops the picture and leaves the HUD out of reach). Upstream keeps the size with SWP_NOSIZE. The + // test branch's AcWindowChrome (2026-11-17 merge) sizes the window on purpose (Borderless Fills Monitor, a + // framed window sized for the resolution), so the guard there is: one SetWindowPos (MoveTo), a restore that + // takes only the saved position with the size from AC's resolution, and borderless sized from the + // resolution or the monitor. private static void AcWindowChromeNeverResizes() { string source = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "UI", "AcWindowChrome.cs"))); var calls = Regex.Matches(source, @"^\s*(?:=>\s*)?SetWindowPos\(hwnd,[^;]*;", RegexOptions.Multiline | RegexOptions.Singleline); - Check(calls.Count >= 2, $"found the SetWindowPos calls ({calls.Count})"); - foreach (Match m in calls) - Check(m.Value.Contains("SwpNosize"), "SetWindowPos keeps AC's size: " + Regex.Replace(m.Value.Trim(), @"\s+", " ")); + Check(calls.Count >= 1, $"found the SetWindowPos calls ({calls.Count})"); + Check(Regex.IsMatch(source, @"private static void MoveTo\(IntPtr hwnd, RECT r\) =>\s*SetWindowPos\(hwnd,"), "the only window move is MoveTo"); + Check(calls.Count == 1, $"no SetWindowPos outside MoveTo ({calls.Count})"); + Match restore = Regex.Match(source, @"private static void TryRestorePlacement\(IntPtr hwnd\)\s*\{(?<body>.*?)\n \}", RegexOptions.Singleline); + Check(restore.Success, "found TryRestorePlacement"); + Check(restore.Groups["body"].Value.Contains("TryFramedSizeForResolution("), "the restore's size comes from AC's resolution, not the saved rect"); + Check(source.Contains("BorderlessAtResolution(") && source.Contains("IsLoginScreenSize("), "borderless sized from the resolution; the login-screen size never restored"); } private static void PlacementFilesArePerClient() diff --git a/tools/LootAddWireTests/Program.cs b/tools/LootAddWireTests/Program.cs index c5b9c98..037731c 100644 --- a/tools/LootAddWireTests/Program.cs +++ b/tools/LootAddWireTests/Program.cs @@ -56,7 +56,8 @@ namespace LootAddWireTests // The op codes the popup labels are the SDK's LootItemAttributeOp. MethodInfo label = opsType.GetMethod("Label", All)!; string L(int op) => (string)label.Invoke(null, new object[] { op })!; - Check(L(0) == ">=" && L(1) == "=" && L(2) == "<=" && L(3) == "not", "numeric / named ops label as >= = <= not"); + Check(L(0) == "at least" && L(1) == "is" && L(2) == "at most" && L(3) == "is not", "numeric / named ops label as words (2026-11-07)"); + Check(L(4) == "has any" && L(5) == "any" && L(6) == "has all", "flag ops: has any, any, has all"); Check(L(10) == "exact" && L(11) == "or better" && L(12) == "any tier", "spell ops label as exact / or better / any tier"); // ── An older RynthAi: no checklist -> the popup keeps its T11 box ─────────── diff --git a/tools/PanelStateTests/PanelStateTests.csproj b/tools/PanelStateTests/PanelStateTests.csproj new file mode 100644 index 0000000..dda6e12 --- /dev/null +++ b/tools/PanelStateTests/PanelStateTests.csproj @@ -0,0 +1,22 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for which window-layout file a client uses (src\RynthCore.Engine\UI\PanelStatePath.cs, + compiled in): panel_state.<server>.<character>.txt from the launch context's ServerName and + TargetCharacter, unsafe characters as "_", and the shared panel_state.txt when the character + isn't known. No files, no ImGui. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>PanelStateTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\UI\PanelStatePath.cs" Link="Engine\PanelStatePath.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/PanelStateTests/Program.cs b/tools/PanelStateTests/Program.cs new file mode 100644 index 0000000..2b47173 --- /dev/null +++ b/tools/PanelStateTests/Program.cs @@ -0,0 +1,54 @@ +using RynthCore.Engine.UI; + +namespace PanelStateTests; + +// Offline tests for the per-character window-layout file name. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq<T>(T actual, T expected, string msg) => + Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static int Main() + { + FileNames(); + LaunchContext(); + Console.WriteLine(); + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)"); + return _fails == 0 ? 0 : 1; + } + + /// <summary>Silentkelpie 2026-10-24: each character keeps its own layout, so another client's moves don't reset it.</summary> + private static void FileNames() + { + Console.WriteLine("FileNames"); + Eq(PanelStatePath.FileNameFor("Infinite Leaftide", "Silentkelpie"), "panel_state.infinite_leaftide.silentkelpie.txt", "server and character"); + Eq(PanelStatePath.FileNameFor("ILT", "Sir O'Brien-Smith"), "panel_state.ilt.sir_o_brien_smith.txt", "spaces, apostrophe and dash become one _"); + Eq(PanelStatePath.FileNameFor("", "Silentkelpie"), "panel_state.silentkelpie.txt", "no server: character only"); + Eq(PanelStatePath.FileNameFor("ILT", ""), PanelStatePath.SharedFileName, "no character: the shared file"); + Eq(PanelStatePath.FileNameFor(null, null), PanelStatePath.SharedFileName, "nothing known: the shared file"); + Eq(PanelStatePath.FileNameFor("ILT", " *** "), PanelStatePath.SharedFileName, "a name of only symbols: the shared file"); + Eq(PanelStatePath.FileNameFor("ILT", "Sílentkelpie"), "panel_state.ilt.s_lentkelpie.txt", "non-ASCII letters become _"); + string longName = new string('a', 80); + Eq(PanelStatePath.FileNameFor("x", longName), $"panel_state.x.{new string('a', PanelStatePath.MaxPartLength)}.txt", "a long name is cut"); + Eq(PanelStatePath.FileNameFor("ILT", "Silentkelpie"), PanelStatePath.FileNameFor("ilt", "SILENTKELPIE"), "case doesn't make a second file"); + } + + private static void LaunchContext() + { + Console.WriteLine("LaunchContext"); + var parsed = PanelStatePath.ParseLaunchContext("{\"ProcessId\":5392,\"AccountName\":\"acct\",\"ServerName\":\" ILT \",\"TargetCharacter\":\"Silentkelpie\"}"); + Eq(parsed.Server, "ILT", "server, trimmed"); + Eq(parsed.Character, "Silentkelpie", "character"); + Eq(PanelStatePath.ParseLaunchContext("{\"ServerName\":\"ILT\"}").Character, "", "no character"); + Eq(PanelStatePath.ParseLaunchContext("{\"TargetCharacter\":42}").Character, "", "a non-string character"); + Eq(PanelStatePath.ParseLaunchContext("{ cut-off").Character, "", "a broken file"); + Eq(PanelStatePath.ParseLaunchContext("[1,2]").Character, "", "not an object"); + Eq(PanelStatePath.ParseLaunchContext(null).Character, "", "no file"); + } +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 35ec458..5ee1031 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -54,7 +54,7 @@ internal static class Program Run(nameof(ServerBlockRejectsBadIds), ServerBlockRejectsBadIds); Run(nameof(ServerHostMatching), ServerHostMatching); Run(nameof(ServerGateKeepsOnlyTheHostsPlugin), ServerGateKeepsOnlyTheHostsPlugin); - Run(nameof(ServerGateUnclaimedHost), ServerGateUnclaimedHost); + Run(nameof(ServerGateFailsOpen), ServerGateFailsOpen); Run(nameof(ServerGatePlanFromFiles), ServerGatePlanFromFiles); Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); @@ -525,7 +525,7 @@ internal static class Program Eq(PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", true, log).Count, 0, "LoadAllServerPlugins keeps every one"); } - private static void ServerGateUnclaimedHost() + private static void ServerGateFailsOpen() { var list = new List<PluginCandidate> { @@ -534,7 +534,7 @@ internal static class Program }; var log = new List<string>(); Eq(PluginManifestGate.SelectServerPlugins(list, "", false, log).Count, 0, "no connect host: all load"); - Eq(PluginManifestGate.SelectServerPlugins(list, "10.0.0.5", false, log).Count, 2, "a host nobody lists: none load now (late load by world name or a pick)"); + Eq(PluginManifestGate.SelectServerPlugins(list, "10.0.0.5", false, log).Count, 0, "a host nobody lists: all load"); Check(log.Any(l => l.Contains("none lists host 10.0.0.5")), "said why"); } @@ -608,8 +608,8 @@ internal static class Program (int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>(prev) + IntPtr.Size, "SDK " + slot + " right after " + prev); prev = slot; } - Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four"); - Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four"); + Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(2 + 4).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four (v98's two placement slots follow them)"); + Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(2 + 4).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four (v98's two placement slots follow them)"); } private static void StructMirror(Type engine, Type sdk, int size) @@ -758,27 +758,36 @@ internal static class Program Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow: - // eleven slots to v89, then v90's thirteen, v91's two, v93's one and v94's four). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray(); + // eleven slots to v89, then v90's thirteen, v91's two, v93's one, v94's four and v98's two). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(33).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(33).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } // v80: GetContainerOrder and PutItemInContainer come right before v81's slot, engine and SDK alike; - // v81: GetMergeStackResult, then v82: SalvageDirect, v83's two and v84's GetObjectProperties last. The whole table has the same field names in the same - // order on both sides, and the same size. + // v81: GetMergeStackResult, v82: SalvageDirect, v83: the ghost-creature pair, v84: GetObjectProperties, + // v85: the confirmation pair, v86: GetServerStateJson last. + // The whole table has the same field names in the same order on both sides, and the same size. private static void ContainerOrderSlots() { var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); - // v94: the web panel's four slots end the table; the checks after these are on the table before them. + // v98: the per-character window placements end the table (2026-10-26; v91 on the test branch, v94 after + // upstream's v93, v98 after upstream's v94-v97, 2026-11-14); upstream's v94 web panel slots right before them. + string[] v98 = { "GetWindowPlacementFn", "SetWindowPlacementFn" }; + Check(all.TakeLast(v98.Length).SequenceEqual(v98), "v98 slots last: " + string.Join(",", all.TakeLast(v98.Length))); + Check(sdkAll.TakeLast(v98.Length).SequenceEqual(v98), "SDK v98 slots last: " + string.Join(",", sdkAll.TakeLast(v98.Length))); + foreach (string slot in v98) + Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>(slot), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>(slot), slot + " offset"); + // v94: the web panel's four slots come right before them. string[] v94 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; - Check(all.TakeLast(v94.Length).SequenceEqual(v94), "v94 slots last: " + string.Join(",", all.TakeLast(v94.Length))); - Check(sdkAll.TakeLast(v94.Length).SequenceEqual(v94), "SDK v94 slots last: " + string.Join(",", sdkAll.TakeLast(v94.Length))); - all = all.SkipLast(v94.Length).ToArray(); - sdkAll = sdkAll.SkipLast(v94.Length).ToArray(); + Check(all.SkipLast(v98.Length).TakeLast(v94.Length).SequenceEqual(v94), "v94 slots before v98: " + string.Join(",", all.SkipLast(v98.Length).TakeLast(v94.Length))); + Check(sdkAll.SkipLast(v98.Length).TakeLast(v94.Length).SequenceEqual(v94), "SDK v94 slots before v98: " + string.Join(",", sdkAll.SkipLast(v98.Length).TakeLast(v94.Length))); + all = all.SkipLast(v98.Length + v94.Length).ToArray(); + sdkAll = sdkAll.SkipLast(v98.Length + v94.Length).ToArray(); // v93: the monster plates' health readings end the table (2026-11-07), right after v91's two. Check(all.Last() == "GetMonsterHealthFn", "v93 slot last: " + all.Last()); Check(sdkAll.Last() == "GetMonsterHealthFn", "SDK v93 slot last: " + sdkAll.Last()); diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index bfdeb98..8cff5de 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -37,6 +37,9 @@ internal static class Program BarMenuHoverTiming(); BarMenuReload(); StackCheckAfterPluginDraw(); + RatesRises(); + RatesBank(); + RatesChat(); Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); @@ -334,19 +337,6 @@ internal static class Program Check(load.Count == 1 && load[0] == "coldeve", "only the server forced On asks for its plugin"); forces["coldeve"] = ServerForce.Off; Check(NotLoadedServers.ForcedOn(notLoaded, Force).Count == 0, "Off loads nothing"); - - // The connect host is nobody's (none load at start); the world name the server announces - // loads its plugin late, unless that server is forced Off. - var byWorld = new[] - { - new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE", new[] { "Frosthaven*" }), - new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve", new[] { "Coldeve" }), - }; - Check(NotLoadedServers.ToLoad(byWorld, Force, null).Count == 0, "before login: nothing loads by world name"); - var hit = NotLoadedServers.ToLoad(byWorld, Force, "Frosthaven PvE"); - Check(hit.Count == 1 && hit[0] == "frost", "the announced world name loads its server's plugin"); - Check(NotLoadedServers.ToLoad(byWorld, Force, "Coldeve").Count == 0, "a server forced Off isn't loaded by its world name"); - Check(NotLoadedServers.ToLoad(byWorld, Force, "Somewhere Else").Count == 0, "a world nobody lists loads nothing"); } private static void SelectionCurrentPick() @@ -805,6 +795,79 @@ internal static class Program Check(!ImGuiStackState.WroteExpectedSize(Enumerable.Repeat((byte)0xCC, 64).ToArray(), 0xCC), "nothing written: off"); } + // ── Session rates (status feed / Session Stats) ──────────────────── + + private static readonly DateTime T0 = new(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc); + + /// <summary>XP and character luminance: only rises count, the first read is the baseline.</summary> + private static void RatesRises() + { + Case("rates rises"); + var r = new SessionRates(); + Check(r.View(T0).Xp == 0 && r.View(T0).Seconds == 0, "zeros before the first sample"); + r.Sample(0, new SessionRatesSample(100, 5, null, null, null), T0); + Check(r.Character == 0, "character 0 is ignored"); + + r.Sample(7, new SessionRatesSample(1_000, 50, null, null, null), T0); + Check(r.View(T0).Xp == 0 && r.View(T0).Lum == 0, "first read is the baseline"); + r.Sample(7, new SessionRatesSample(4_000, 80, null, null, null), T0.AddMinutes(30)); + r.Sample(7, new SessionRatesSample(4_000, 10, null, null, null), T0.AddMinutes(45)); // spent 70 lum + r.Sample(7, new SessionRatesSample(5_000, 30, null, null, null), T0.AddHours(1)); + SessionRatesView v = r.View(T0.AddHours(1)); + Check(v.Xp == 4_000, "xp is the sum of rises: " + v.Xp); + Check(v.Lum == 50, "a spend moves the baseline, it doesn't take earnings back: " + v.Lum); + Check(Math.Abs(v.XpPerHour - 4_000) < 0.001 && Math.Abs(v.LumPerHour - 50) < 0.001, "per hour over one hour"); + Check(r.View(T0).Seconds == 1, "a session is at least one second long"); + + r.Sample(8, new SessionRatesSample(9_000, 1, null, null, null), T0.AddHours(2)); + v = r.View(T0.AddHours(2)); + Check(r.Character == 8 && v.Xp == 0 && v.Lum == 0 && v.StartUtc == T0.AddHours(2), "a new character starts a new session"); + } + + /// <summary>ACECustom's bank (9005) and Aelrynth's banked (9102) / drawn (9103) totals.</summary> + private static void RatesBank() + { + Case("rates bank"); + var r = new SessionRates(); + r.Sample(1, new SessionRatesSample(null, 100, 1_000, null, null), T0); + r.Sample(1, new SessionRatesSample(null, 100, 1_500, null, null), T0.AddMinutes(1)); + Check(r.View(T0.AddMinutes(1)).Lum == 500, "a bank rise is income"); + r.Sample(1, new SessionRatesSample(null, 400, 1_200, null, null), T0.AddMinutes(2)); + Check(r.View(T0.AddMinutes(2)).Lum == 500, "a withdrawal (bank down, character up) isn't income once the bank is tracked"); + + var a = new SessionRates(); + a.Sample(2, new SessionRatesSample(null, 10, null, 0, 0), T0); + a.Sample(2, new SessionRatesSample(null, 10, null, 300, 0), T0.AddMinutes(1)); + Check(a.View(T0.AddMinutes(1)).Lum == 300, "auto-banked luminance was earned"); + a.Sample(2, new SessionRatesSample(null, 210, null, 300, 200), T0.AddMinutes(2)); + Check(a.View(T0.AddMinutes(2)).Lum == 300, "drawn luminance landing on the character isn't earned"); + a.Sample(2, new SessionRatesSample(null, 260, null, 300, 200), T0.AddMinutes(3)); + Check(a.View(T0.AddMinutes(3)).Lum == 350, "a real character rise after a draw still counts"); + } + + /// <summary>Deposits and incoming transfers seen in chat aren't income; the marker expires.</summary> + private static void RatesChat() + { + Case("rates chat"); + Check(SessionRates.TryMovedIntoBank("Deposited 1,234 luminance into your bank.", out long n) && n == 1_234, "a deposit line"); + Check(SessionRates.TryMovedIntoBank(" Received 50 luminance from Kelpie.", out n) && n == 50, "a transfer line, padded"); + Check(!SessionRates.TryMovedIntoBank("Kelpie tells you, \"Deposited 5 luminance\"", out _), "a quoted line isn't a deposit"); + Check(!SessionRates.TryMovedIntoBank("Deposited luminance", out _) && !SessionRates.TryMovedIntoBank(null, out _), "no amount, null"); + Check(!SessionRates.TryMovedIntoBank("Deposited 99999999999999999999 luminance", out _), "overflow is rejected"); + + var r = new SessionRates(); + r.Sample(1, new SessionRatesSample(null, 1_000, 0, null, null), T0); + r.OnChat("Deposited 600 luminance", T0.AddSeconds(5)); + r.Sample(1, new SessionRatesSample(null, 400, 600, null, null), T0.AddSeconds(6)); + Check(r.View(T0.AddSeconds(6)).Lum == 0, "a deposit is moved money"); + r.Sample(1, new SessionRatesSample(null, 400, 700, null, null), T0.AddSeconds(7)); + Check(r.View(T0.AddSeconds(7)).Lum == 100, "the next bank rise after the deposit is income"); + + r.OnChat("Received 50 luminance from Someone", T0.AddSeconds(10)); + r.Sample(1, new SessionRatesSample(null, 400, 800, null, null), T0.AddSeconds(100)); + Check(r.View(T0.AddSeconds(100)).Lum == 200, "the marker expires after 60 seconds"); + } + // ── Harness ──────────────────────────────────────────────────────── private static void Case(string name) diff --git a/tools/SectionsTests/SectionsTests.csproj b/tools/SectionsTests/SectionsTests.csproj index 25730bd..500a2db 100644 --- a/tools/SectionsTests/SectionsTests.csproj +++ b/tools/SectionsTests/SectionsTests.csproj @@ -38,6 +38,7 @@ <!-- Installed server plugins the connect host left out: listed in the picker, loaded when forced On. --> <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\NotLoadedServers.cs" Link="Engine\NotLoadedServers.cs" /> <!-- The status feed's / Session Stats' XP and luminance session formula (pure). --> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\SessionRates.cs" Link="Engine\SessionRates.cs" /> </ItemGroup> </Project> diff --git a/tools/SettingsLayoutTests/Program.cs b/tools/SettingsLayoutTests/Program.cs index 95e2654..60706fb 100644 --- a/tools/SettingsLayoutTests/Program.cs +++ b/tools/SettingsLayoutTests/Program.cs @@ -123,7 +123,7 @@ namespace SettingsLayoutTests { string[] want = { - "Interface", "Game Client", "Hotkeys", + "Interface", "Game Client", "Graphics", "Hotkeys", // Graphics: the test branch's per-account AC graphics profile "General", "Recharge", "Combat", "Spell Combat", "Ranges", "Navigation", "Buffing", "Looting", "Inventory", "Vendoring", "Diagnostics", }; -- 2.43.0