Compare commits

...
82 Commits
Author SHA1 Message Date
辉鸭蛋 98b1376111 0.33.1 2024-08-19 23:14:55 +08:00
辉鸭蛋 b62e4a7425 add script group editor 2024-08-18 21:41:12 +08:00
辉鸭蛋 6aa02b94d9 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-08-18 14:49:00 +08:00
qhy040404 be89383add fix relative path 2024-08-18 09:06:58 +08:00
辉鸭蛋 0097bfa8c3 edit auto crystalfly script 2024-08-17 20:23:29 +08:00
辉鸭蛋 6812f30732 optimize script execution 2024-08-17 18:00:03 +08:00
辉鸭蛋 c6680ced12 add js script page 2024-08-17 16:02:54 +08:00
辉鸭蛋 b47ce6f529 modify menu hierarchy 2024-08-17 12:09:03 +08:00
ema 9b874d3747 small trial with using Toast instead of MessageBox 2024-08-16 00:43:32 +08:00
辉鸭蛋 2b6465be22 edit kmscript name 2024-08-16 00:38:41 +08:00
辉鸭蛋 d2574022fc Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-08-16 00:34:29 +08:00
ema 87ae5e437a update: PresentMonFps version 2024-08-16 00:26:50 +08:00
辉鸭蛋 c486b860d0 0.32.6 2024-08-16 00:11:53 +08:00
辉鸭蛋 4784551e10 expand the orange option recognition range 2024-08-16 00:11:20 +08:00
辉鸭蛋 030caec91f fix: auto skip ClosePopupPagedEnabled not effective 2024-08-16 00:02:20 +08:00
辉鸭蛋 8b0bdef670 edit script group name 2024-08-15 23:55:57 +08:00
辉鸭蛋 6651ec7d9f attempt to correct coordinates 2024-08-15 00:00:12 +08:00
辉鸭蛋 d4fe1f2ab0 add BfMatch instead of FlannMatch 2024-08-14 23:21:03 +08:00
辉鸭蛋 4e1a0673c9 fix GetMiniMapPositionByFeatureMatch = 0 2024-08-14 22:25:15 +08:00
辉鸭蛋 f904fe024b Merge remote-tracking branch 'origin/main' into pr/522 2024-08-14 21:57:11 +08:00
ema bb41bcb25e Merge pull request #525 from babalae/cleanup
code cleanup
2024-08-14 19:43:21 +08:00
qhy040404 c490d29aa1 code cleanup 2024-08-14 18:01:02 +08:00
lwh9346 743debb58b Merge branch 'babalae:main' into main 2024-08-14 16:20:32 +08:00
lwh9346 180fc2d228 Merge branch 'main' of github.com:lwh9346/better-genshin-impact 2024-08-14 16:20:16 +08:00
lwh9346 d148014b7f testing code 2024-08-14 16:11:13 +08:00
qhy040404 78ec9d31e8 check integration #468 2024-08-14 16:03:43 +08:00
lwh9346 9fa721d5e4 Merge branch 'babalae:main' into main 2024-08-14 15:10:41 +08:00
lwh9346 8a5d1d5f64 add path executor 2024-08-14 15:08:37 +08:00
lwh9346 cc245b0e8a change file structure 2024-08-14 14:01:21 +08:00
lwh9346 49bc6befb7 add script support 2024-08-14 14:00:56 +08:00
辉鸭蛋 b62e87f36f Merge pull request #524 from babalae/feat-random-opt
随便改改
2024-08-14 11:34:22 +08:00
DismissedLight 48115be84e 随便改改 2024-08-14 11:13:40 +08:00
lwh9346 f82e35382c add UNTESTED path executor 2024-08-14 10:17:16 +08:00
lwh9346 224fc9917a add walk and swim to "move to" function 2024-08-14 01:39:27 +08:00
lwh9346 eb0b681b9d Merge branch 'main' of github.com:lwh9346/better-genshin-impact 2024-08-14 00:37:46 +08:00
lwh9346 f61a7c32d4 add basic code for auto pathing 2024-08-14 00:36:57 +08:00
辉鸭蛋 bc6ef4fa49 add comment 2024-08-14 00:15:25 +08:00
辉鸭蛋 eef5ff32cb add CameraOrientation.ComputeMiniMap(mat) 2024-08-14 00:14:04 +08:00
辉鸭蛋 c9f3f11c8a make the ScriptControlPage visible 2024-08-13 23:29:51 +08:00
辉鸭蛋 4b4ef25ede 0.32.5 2024-08-13 23:09:14 +08:00
辉鸭蛋 644cdea7ee fix the accuracy issue of feature matching 2024-08-13 23:05:53 +08:00
辉鸭蛋 83911bb13d add new knn match 2024-08-13 21:37:00 +08:00
辉鸭蛋 bc3f356d46 add new knn match 2024-08-13 01:52:48 +08:00
辉鸭蛋 f016f6001c Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-08-13 01:07:59 +08:00
辉鸭蛋 e1097199c4 map feature clear up 2024-08-13 01:07:53 +08:00
辉鸭蛋 36639a0786 auto crystalfly more position 2024-08-12 23:49:35 +08:00
辉鸭蛋 be6c5646da Update README.md 2024-08-12 22:16:43 +08:00
ema 4626863f30 fix #446 2024-08-12 00:23:43 +08:00
辉鸭蛋 b07f2ec839 more crystalfly position 2024-08-11 23:21:55 +08:00
辉鸭蛋 b44ddd5625 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-08-11 20:15:23 +08:00
辉鸭蛋 ed9a47a3a1 fix dispather thread safe 2024-08-11 20:14:32 +08:00
ema 3c27c90828 update: GetParent before SetParent 2024-08-11 19:42:49 +08:00
辉鸭蛋 8fa071722e js : dispatcher.addTimer 2024-08-11 17:58:22 +08:00
辉鸭蛋 2c2e9c0303 supplement the mode of the runner 2024-08-11 10:41:01 +08:00
辉鸭蛋 a7153a47f6 auto crystalfly init 2024-08-11 02:32:00 +08:00
辉鸭蛋 26aa811e97 add script group runner 2024-08-11 00:09:25 +08:00
辉鸭蛋 00f822c49d switch to ground when big map in underground 2024-08-10 23:14:08 +08:00
辉鸭蛋 02b3d80056 record camera orientation config 2024-08-10 22:04:17 +08:00
辉鸭蛋 0edf6c13ef script group ui3 2024-08-10 21:18:48 +08:00
辉鸭蛋 ad288c60cc script group ui 2 2024-08-10 19:16:35 +08:00
辉鸭蛋 308d398036 script group ui 2024-08-10 13:37:29 +08:00
辉鸭蛋 dc09a0ac7b Merge pull request #514 from lwh9346/main
修复了相机视角记录频率不正确的问题
2024-08-10 08:51:57 +08:00
lwh9346 0a4e8e6403 Merge branch 'babalae:main' into main 2024-08-10 00:39:23 +08:00
lwh9346 b881ba313e bug fix 2024-08-10 00:37:52 +08:00
辉鸭蛋 7422454c56 Merge pull request #512 from lwh9346/main
通过在录制脚本时记录相机视角改善回放精度
2024-08-09 19:57:53 +08:00
ema 00ab7042c5 chrome://flags/#enable-force-dark 2024-08-09 17:04:25 +08:00
lwh9346 d69a7c428e capture camera orientation while recording mouse movement to improve replay accuracy 2024-08-09 15:58:40 +08:00
辉鸭蛋 c1072d0574 script: support running macros 2024-08-07 01:07:58 +08:00
辉鸭蛋 bd64181b7c Merge pull request #511 from lwh9346/main
改进键鼠脚本录制与回放精度
2024-08-06 23:57:16 +08:00
lwh9346 6bd9079b3b improve macro player 2024-08-06 23:43:48 +08:00
ema 44921dd3e0 create ISSUE_TEMPLATE\feature.md 2024-08-05 12:02:31 +08:00
辉鸭蛋 d5ac4c523e add crud helper 2024-08-04 23:47:54 +08:00
ema fe418e7bc4 update server b login pos #495 2024-08-04 15:21:51 +08:00
ema a1c5c25623 change server b identity 2024-08-04 15:15:34 +08:00
辉鸭蛋 4610c9e7ca add script engine 2024-08-03 19:41:48 +08:00
辉鸭蛋 abac18bc7e reduce the recognition rate requirements for Qin and costume characters 2024-08-02 22:38:47 +08:00
辉鸭蛋 352b45f07d use FileStorage save KeyPoints 2024-08-01 22:36:06 +08:00
辉鸭蛋 65f2aad4c2 add tp click & fix mask window display 2024-07-31 23:44:25 +08:00
辉鸭蛋 4e5629bc16 fix stop recorder hotkey #501 2024-07-30 00:26:52 +08:00
辉鸭蛋 917df88099 add cancel task hotkey #501 2024-07-30 00:12:18 +08:00
辉鸭蛋 96a56ac4b8 fix stop when recorder starting #501 2024-07-29 23:59:22 +08:00
辉鸭蛋 f9cada6ef9 revert mask window old style #503 2024-07-29 23:38:30 +08:00
247 changed files with 8897 additions and 1821 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
---
name: I have feature requesting / 我有新功能请求
about: Your request may come as a surprise. / 你的请求也许成为惊喜
title: "[feature] "
labels: feature 功能请求
---
- Your feature requesting / 你的新功能请求
+4 -2
View File
@@ -48,9 +48,11 @@ public partial class MainWindow : Window
private void DoMatchTest(object sender, System.Windows.RoutedEventArgs e)
{
// KeyPointMatchTest.Test();
// EntireMapTest.Test();
EntireMapTest.Test();
// EntireMapTest.Storage();
BigMapMatchTest.Test();
// BigMapMatchTest.Test();
// FeatureTransfer.Transfer();
}
private void MapDrawTeleportPoint(object sender, RoutedEventArgs e)
@@ -6,6 +6,7 @@ using OpenCvSharp.Detail;
using System.Diagnostics;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Helpers.Extensions;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -28,14 +29,14 @@ public class BigMapMatchTest
queryMat = ResizeHelper.Resize(queryMat, 1d / 4);
Cv2.ImShow("queryMat", queryMat);
var pArray = surfMatcher.Match(queryMat);
var p = surfMatcher.Match(queryMat);
speedTimer.Record("匹配1");
if (pArray != null)
if (p.IsEmpty())
{
var rect = Cv2.BoundingRect(pArray);
Debug.WriteLine($"Matched rect 1: {rect}");
Cv2.Rectangle(mainMap100BlockMat, rect, Scalar.Red, 2);
Cv2.ImShow(@"b1", mainMap100BlockMat);
// var rect = Cv2.BoundingRect(pArray);
Debug.WriteLine($"Matched rect 1: {p}");
// Cv2.Rectangle(mainMap100BlockMat, rect, Scalar.Red, 2);
// Cv2.ImShow(@"b1", mainMap100BlockMat);
}
else
{
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using OpenCvSharp;
using OpenCvSharp.Detail;
using System.Diagnostics;
@@ -19,22 +20,21 @@ public class EntireMapTest
speedTimer.Record("初始化特征");
var pArray = surfMatcher.Match(queryMat);
var p = surfMatcher.Match(queryMat);
speedTimer.Record("匹配1");
if (pArray != null)
if (!p.IsEmpty())
{
var rect = Cv2.BoundingRect(pArray);
Debug.WriteLine($"Matched rect 1: {rect}");
Cv2.Rectangle(mainMap1024BlockMat, rect, Scalar.Red, 2);
Debug.WriteLine($"Matched rect 1: {p}");
Cv2.Circle(mainMap1024BlockMat, p.ToPoint(), 10, Scalar.Red);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b1.png", mainMap1024BlockMat);
var pArray2 = surfMatcher.Match(queryMat, rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
var p2 = surfMatcher.Match(queryMat, p.X, p.Y);
speedTimer.Record("匹配2");
if (pArray2 != null)
if (!p2.IsEmpty())
{
var rect2 = Cv2.BoundingRect(pArray2);
Debug.WriteLine($"Matched rect 2: {rect2}");
Cv2.Rectangle(mainMap1024BlockMat, rect2, Scalar.Yellow, 1);
// var rect2 = Cv2.BoundingRect(pArray2);
Debug.WriteLine($"Matched rect 2: {p2}");
// Cv2.Rectangle(mainMap1024BlockMat, rect2, Scalar.Yellow, 1);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b2.png", mainMap1024BlockMat);
}
else
@@ -0,0 +1,33 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using System.IO;
namespace BetterGenshinImpact.Test.Simple.AllMap;
public class FeatureTransfer
{
private static string rootPath = Global.Absolute(@"User\Map\");
public static void Transfer()
{
var kp = LoadKeyPointArrayOld();
if (kp != null)
{
string kpPath = Path.Combine(rootPath, $"mainMap2048Block_SIFT.kp");
FileStorage fs = new(kpPath, FileStorage.Modes.Write);
fs.Write("kp", kp);
fs.Release();
}
}
public static KeyPoint[]? LoadKeyPointArrayOld()
{
string kpPath = Path.Combine(rootPath, "mainMap2048Block_SIFT.kp.old");
if (File.Exists(kpPath))
{
return ObjectUtils.Deserialize(File.ReadAllBytes(kpPath)) as KeyPoint[];
}
return null;
}
}
+4 -1
View File
@@ -2,12 +2,14 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bgivc="clr-namespace:BetterGenshinImpact.View.Converters"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<vio:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
@@ -15,6 +17,7 @@
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<bgivc:NotNullConverter x:Key="NotNullConverter" />
</ResourceDictionary>
</Application.Resources>
</Application>
+3 -2
View File
@@ -20,7 +20,6 @@ using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Wpf.Ui;
namespace BetterGenshinImpact;
@@ -33,6 +32,7 @@ public partial class App : Application
// https://docs.microsoft.com/dotnet/core/extensions/configuration
// https://docs.microsoft.com/dotnet/core/extensions/logging
private static readonly IHost _host = Host.CreateDefaultBuilder()
.CheckIntegration()
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureServices(
@@ -87,13 +87,14 @@ public partial class App : Application
services.AddView<HotKeyPage, HotKeyPageViewModel>();
services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
services.AddView<KeyMouseRecordPage, KeyMouseRecordPageViewModel>();
// services.AddView<DispatcherPage, DispatcherPageViewModel>();
services.AddView<JsListPage, JsListViewModel>();
// My Services
services.AddSingleton<TaskTriggerDispatcher>();
services.AddSingleton<NotificationService>();
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
services.AddSingleton<NotifierManager>();
services.AddSingleton<IScriptService, ScriptService>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

+9 -31
View File
@@ -5,7 +5,7 @@
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>True</UseWindowsForms>
<UseWindowsForms>true</UseWindowsForms>
<LangVersion>12.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\logo.ico</ApplicationIcon>
@@ -47,7 +47,7 @@
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="PresentMonFps" Version="2.0.1" />
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
@@ -58,13 +58,14 @@
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="WPF-UI" Version="3.0.4" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.4" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.2" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
</ItemGroup>
<ItemGroup>
@@ -73,27 +74,6 @@
<ProjectReference Include="..\Fischless.WindowsInput\Fischless.WindowsInput.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="GameTask\TaskContext.cs">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Compile>
<Compile Update="View\MaskWindow.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Pages\HotkeyPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Pages\TriggerSettingsPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\PickerWindow.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Windows\MapViewer.xaml.cs">
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="Assets\Map\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@@ -146,11 +126,9 @@
<None Update="User\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="GameTask\Common\Element\Assets\MapPoint\" />
<Folder Include="View\Controls\WpfUi\" />
<None Update="Script\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+3 -1
View File
@@ -1,4 +1,5 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
@@ -13,7 +14,6 @@ using Fischless.GameCapture;
using System;
using System.ComponentModel;
using System.Text.Json.Serialization;
using BetterGenshinImpact.GameTask.AutoCook;
namespace BetterGenshinImpact.Core.Config;
@@ -126,6 +126,8 @@ public partial class AllConfig : ObservableObject
/// </summary>
public MacroConfig MacroConfig { get; set; } = new();
public RecordConfig RecordConfig { get; set; } = new();
/// <summary>
/// 快捷键配置
/// </summary>
+11 -1
View File
@@ -5,7 +5,7 @@ namespace BetterGenshinImpact.Core.Config;
public class Global
{
public static string Version { get; } = "0.32.0";
public static string Version { get; } = "0.33.1";
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
@@ -14,6 +14,16 @@ public class Global
return Path.Combine(StartUpPath, relativePath);
}
public static string ScriptPath()
{
return Absolute("Script");
}
public static string ScriptPath(string folderName)
{
return Path.Combine(Absolute("Script"), folderName);
}
public static string? ReadAllTextIfExist(string relativePath)
{
var path = Absolute(relativePath);
@@ -170,6 +170,27 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _test2HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径记录开始
[ObservableProperty]
private string _pathRecorderHotkey = "";
[ObservableProperty]
private string _pathRecorderHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 添加路径记录点
[ObservableProperty]
private string _addWaypointHotkey = "";
[ObservableProperty]
private string _addWaypointHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径执行
[ObservableProperty]
private string _executePathHotkey = "";
[ObservableProperty]
private string _executePathHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 日志与状态窗口展示
[ObservableProperty]
private string _logBoxDisplayHotkey = "";
@@ -183,4 +204,11 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _keyMouseMacroRecordHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 停止任意独立任务
[ObservableProperty]
private string _cancelTaskHotkey = "";
[ObservableProperty]
private string _cancelTaskHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -84,4 +84,11 @@ public partial class MaskWindowConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _showFps = false;
/// <summary>
/// 作为原神子窗体
/// 有些bug没解决
/// </summary>
[ObservableProperty]
private bool _useSubform = false;
}
@@ -18,4 +18,10 @@ public partial class RecordConfig : ObservableObject
/// </summary>
[ObservableProperty]
private double _angle2DirectInputX = 1.0;
/// <summary>
/// 图像识别记录相机视角朝向
/// </summary>
[ObservableProperty]
private bool _isRecordCameraOrientation = false;
}
@@ -1,7 +1,6 @@
using BetterGenshinImpact.Core.Recorder;
using SharpDX.DirectInput;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
@@ -4,10 +4,8 @@ using Sdcb.PaddleInference;
using Sdcb.PaddleOCR;
using Sdcb.PaddleOCR.Models;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using BetterGenshinImpact.GameTask;
namespace BetterGenshinImpact.Core.Recognition.OCR;
@@ -1,16 +1,12 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
@@ -1,5 +1,5 @@
using System;
using OpenCvSharp;
using OpenCvSharp;
using System;
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
@@ -0,0 +1,31 @@
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
/// <summary>
/// FlannMatch
/// 优点:
/// 1. 速度快:FlannMatch 使用的是近似最近邻搜索算法,适合处理大规模数据集,速度比暴力匹配器快得多。
/// 2. 可扩展性好:适用于高维特征空间,能够处理大量特征点。
/// 缺点:
/// 1. 精度较低:由于是近似搜索,匹配的精度可能不如暴力匹配器高。
/// 2. 复杂性高:需要对参数进行调优,以获得最佳性能。
/// BfMatch
/// 优点:
/// 1. 精度高:BfMatch 进行的是精确匹配,能够找到最优的匹配对。
/// 2. 简单易用:不需要复杂的参数调优,适合初学者和简单应用。
/// 缺点:
/// 1. 速度慢:对于大规模数据集,暴力匹配器的速度较慢,因为它需要计算所有特征点之间的距离。
/// 2. 不适合高维数据:在高维特征空间中,计算量会显著增加,性能下降明显。
/// 选择建议
/// • 大规模数据集:如果你需要处理大量特征点,且对速度要求较高,FlannMatch 是一个更好的选择。
/// • 高精度要求:如果你的应用对匹配精度要求很高,且数据规模较小,BfMatch 会更合适。
/// </summary>
public enum DescriptorMatcherType
{
// 快速近似最近邻搜索库
BruteForce,
// 暴力匹配器
FlannBased
// 更多类型命名见 DescriptorMatcher.Create
}
@@ -1,12 +1,14 @@
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using OpenCvSharp.Features2D;
using OpenCvSharp.XFeatures2D;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BetterGenshinImpact.GameTask.Common.Map;
using OpenCvSharp.Features2D;
using System.IO;
using System.Linq;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
@@ -15,10 +17,15 @@ public class FeatureMatcher
private readonly double _threshold = 100; // SURF 100
private readonly Feature2D _feature2D;
// private readonly Mat _trainMat; // 大图本身
private readonly Dictionary<DescriptorMatcherType, DescriptorMatcher> _matcherFactory = new()
{
{ DescriptorMatcherType.BruteForce, DescriptorMatcher.Create(DescriptorMatcherType.BruteForce.ToString()) },
{ DescriptorMatcherType.FlannBased, DescriptorMatcher.Create(DescriptorMatcherType.FlannBased.ToString()) }
};
private readonly Size _trainMatSize; // 大图大小
private readonly Mat _trainRet = new(); // 大图特征描述子
private readonly Mat _trainDescriptors = new(); // 大图特征描述子
private readonly KeyPoint[] _trainKeyPoints;
private readonly KeyPointFeatureBlock[][] _blocks; // 特征块存储
@@ -33,11 +40,9 @@ public class FeatureMatcher
/// <param name="trainMat"></param>
/// <param name="featureStorage"></param>
/// <param name="type"></param>
/// <param name="threshold"></param>
/// <exception cref="Exception"></exception>
public FeatureMatcher(Mat trainMat, FeatureStorage? featureStorage = null, Feature2DType type = Feature2DType.SIFT, double threshold = 100)
public FeatureMatcher(Mat trainMat, FeatureStorage? featureStorage = null, Feature2DType type = Feature2DType.SIFT)
{
_threshold = threshold;
_trainMatSize = trainMat.Size();
if (Feature2DType.SURF == type)
{
@@ -56,25 +61,25 @@ public class FeatureMatcher
if (kpFromDisk == null)
{
Debug.WriteLine("特征点不存在");
_feature2D.DetectAndCompute(trainMat, null, out _trainKeyPoints, _trainRet);
_feature2D.DetectAndCompute(trainMat, null, out _trainKeyPoints, _trainDescriptors);
featureStorage.SaveKeyPointArray(_trainKeyPoints);
featureStorage.SaveDescMat(_trainRet);
featureStorage.SaveDescMat(_trainDescriptors);
}
else
{
_trainKeyPoints = kpFromDisk;
_trainRet = featureStorage.LoadDescMat() ?? throw new Exception("加载特征描述矩阵失败");
_trainDescriptors = featureStorage.LoadDescMat() ?? throw new Exception("加载特征描述矩阵失败");
}
}
else
{
_feature2D.DetectAndCompute(trainMat, null, out _trainKeyPoints, _trainRet);
_feature2D.DetectAndCompute(trainMat, null, out _trainKeyPoints, _trainDescriptors);
}
Debug.WriteLine("被匹配的图像生成初始化KeyPoint完成");
Stopwatch sw = new();
sw.Start();
_blocks = KeyPointFeatureBlockHelper.SplitFeatures(_trainMatSize, _splitRow, _splitCol, _trainKeyPoints, _trainRet);
_blocks = KeyPointFeatureBlockHelper.SplitFeatures(_trainMatSize, _splitRow, _splitCol, _trainKeyPoints, _trainDescriptors);
sw.Stop();
Debug.WriteLine($"切割特征点耗时: {sw.ElapsedMilliseconds}ms");
}
@@ -85,11 +90,9 @@ public class FeatureMatcher
/// <param name="trainMatSize"></param>
/// <param name="featureStorage"></param>
/// <param name="type"></param>
/// <param name="threshold"></param>
/// <exception cref="Exception"></exception>
public FeatureMatcher(Size trainMatSize, FeatureStorage featureStorage, Feature2DType type = Feature2DType.SIFT, double threshold = 100)
public FeatureMatcher(Size trainMatSize, FeatureStorage featureStorage, Feature2DType type = Feature2DType.SIFT)
{
_threshold = threshold;
_trainMatSize = trainMatSize;
if (Feature2DType.SURF == type)
{
@@ -102,27 +105,33 @@ public class FeatureMatcher
featureStorage.TypeName = type.ToString();
Debug.WriteLine("尝试从磁盘加载特征点");
var kpFromDisk = featureStorage.LoadKeyPointArray();
_trainKeyPoints = kpFromDisk ?? throw new Exception("特征点不存在");
_trainRet = featureStorage.LoadDescMat() ?? throw new Exception("加载特征描述矩阵失败");
_trainKeyPoints = featureStorage.LoadKeyPointArray() ?? throw new Exception("特征点不存在");
_trainDescriptors = featureStorage.LoadDescMat() ?? throw new Exception("加载特征描述矩阵失败");
Debug.WriteLine("被匹配的图像生成初始化KeyPoint完成");
Stopwatch sw = new();
sw.Start();
_blocks = KeyPointFeatureBlockHelper.SplitFeatures(_trainMatSize, _splitRow, _splitCol, _trainKeyPoints, _trainRet);
_blocks = KeyPointFeatureBlockHelper.SplitFeatures(_trainMatSize, _splitRow, _splitCol, _trainKeyPoints, _trainDescriptors);
sw.Stop();
Debug.WriteLine($"切割特征点耗时: {sw.ElapsedMilliseconds}ms");
}
public DescriptorMatcher GetMatcher(DescriptorMatcherType type)
{
return _matcherFactory[type];
}
#region 普通匹配
/// <summary>
/// 普通匹配(全图特征)
/// </summary>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <returns></returns>
public Point2f[]? Match(Mat queryMat, Mat? queryMatMask = null)
public Point2f Match(Mat queryMat, Mat? queryMatMask = null)
{
return Match(_trainKeyPoints, _trainRet, queryMat, queryMatMask);
return Match(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
}
/// <summary>
@@ -133,14 +142,14 @@ public class FeatureMatcher
/// <param name="prevY">上次匹配到的坐标y</param>
/// <param name="queryMatMask">查询Mask</param>
/// <returns></returns>
public Point2f[]? Match(Mat queryMat, int prevX, int prevY, Mat? queryMatMask = null)
public Point2f Match(Mat queryMat, float prevX, float prevY, Mat? queryMatMask = null)
{
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(_trainMatSize, _splitRow, _splitCol, prevX, prevY);
Debug.WriteLine($"当前坐标({prevX},{prevY})在特征块({cellRow},{cellCol})中");
if (_lastMergedBlock == null || _lastMergedBlock.MergedCenterCellRow != cellRow || _lastMergedBlock.MergedCenterCellCol != cellCol)
{
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainRet, cellRow, cellCol);
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainDescriptors, cellRow, cellCol);
}
return Match(_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!, queryMat, queryMatMask);
@@ -150,25 +159,27 @@ public class FeatureMatcher
/// 普通匹配
/// </summary>
/// <param name="trainKeyPoints"></param>
/// <param name="trainRet"></param>
/// <param name="trainDescriptors"></param>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <param name="matcherType"></param>
/// <returns></returns>
public Point2f[]? Match(KeyPoint[] trainKeyPoints, Mat trainRet, Mat queryMat, Mat? queryMatMask = null)
public Point2f Match(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryRet = new Mat();
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryRet);
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
using var flnMatcher = new FlannBasedMatcher();
var matches = flnMatcher.Match(queryRet, trainRet);
var matches = GetMatcher(matcherType).Match(queryDescriptors, trainDescriptors);
//Finding the Minimum and Maximum Distance
double minDistance = 1000; //Backward approximation
double maxDistance = 0;
for (int i = 0; i < queryRet.Rows; i++)
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance > maxDistance)
@@ -189,7 +200,96 @@ public class FeatureMatcher
var pointsTrain = new List<Point2f>();
//Screening better matching points
// var goodMatches = new List<DMatch>();
for (int i = 0; i < queryRet.Rows; i++)
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance < Math.Max(minDistance * 2, 0.02))
{
pointsQuery.Add(queryKeyPoints[matches[i].QueryIdx].Pt);
pointsTrain.Add(trainKeyPoints[matches[i].TrainIdx].Pt);
//Compression of new ones with distances less than ranges DMatch
// goodMatches.Add(matches[i]);
}
}
speedTimer.Record("FlannMatch");
// var outMat = new Mat();
// algorithm RANSAC Filter the matched results
var pQuery = pointsQuery.ToPoint2d();
var pTrain = pointsTrain.ToPoint2d();
var outMask = new Mat();
// If the original matching result is null, Skip the filtering step
if (pQuery.Count > 0 && pTrain.Count > 0)
{
var hMat = Cv2.FindHomography(pQuery, pTrain, HomographyMethods.Ransac, mask: outMask);
speedTimer.Record("FindHomography");
// 1. 计算查询图像的中心点
var queryCenterPoint = new Point2f(queryMat.Cols / 2f, queryMat.Rows / 2f);
// 2. 使用单应矩阵进行透视变换
Point2f[] queryCenterPoints = [queryCenterPoint];
Point2f[] transformedCenterPoints = Cv2.PerspectiveTransform(queryCenterPoints, hMat);
// 3. 获取变换后的中心点
var trainCenterPoint = transformedCenterPoints[0];
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return trainCenterPoint;
}
speedTimer.DebugPrint();
return new Point2f();
}
/// <summary>
/// 普通匹配
/// </summary>
/// <param name="trainKeyPoints"></param>
/// <param name="trainDescriptors"></param>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <param name="matcherType"></param>
/// <returns></returns>
public Point2f[] MatchCorners(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).Match(queryDescriptors, trainDescriptors);
//Finding the Minimum and Maximum Distance
double minDistance = 1000; //Backward approximation
double maxDistance = 0;
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance > maxDistance)
{
maxDistance = distance;
}
if (distance < minDistance)
{
minDistance = distance;
}
}
// Debug.WriteLine($"max distance : {maxDistance}");
// Debug.WriteLine($"min distance : {minDistance}");
var pointsQuery = new List<Point2f>();
var pointsTrain = new List<Point2f>();
//Screening better matching points
// var goodMatches = new List<DMatch>();
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance < Math.Max(minDistance * 2, 0.02))
@@ -228,74 +328,167 @@ public class FeatureMatcher
}
speedTimer.DebugPrint();
return null;
return [];
}
public Rect MatchRect(Mat queryMat, Mat? queryMatMask = null)
{
var corners = MatchCorners(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
if (corners.Length == 0)
{
return Rect.Empty;
}
return Cv2.BoundingRect(corners);
}
#endregion 普通匹配
#region Knn匹配
public Point2f KnnMatch(Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
return KnnMatch(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask, matcherType);
}
public Point2f KnnMatch(Mat queryMat, float prevX, float prevY, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(_trainMatSize, _splitRow, _splitCol, prevX, prevY);
Debug.WriteLine($"当前坐标({prevX},{prevY})在特征块({cellRow},{cellCol})中");
if (_lastMergedBlock == null || _lastMergedBlock.MergedCenterCellRow != cellRow || _lastMergedBlock.MergedCenterCellCol != cellCol)
{
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainDescriptors, cellRow, cellCol);
}
return KnnMatch(_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!, queryMat, queryMatMask, matcherType);
}
/// <summary>
/// knn的方式匹配
/// https://github.com/tignioj/minimap/blob/main/matchmap/sifttest/sifttest5.py
/// Copilot 生成
/// </summary>
/// <param name="matSrc"></param>
/// <returns></returns>
[Obsolete]
public Point2f[]? KnnMatch(Mat matSrc)
private Point2f KnnMatch(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
using var matSrcRet = new Mat();
KeyPoint[] keyPointsSrc;
using (var surf = SURF.Create(_threshold, 4, 3, false, true))
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
foreach (var match in matches)
{
surf.DetectAndCompute(matSrc, null, out keyPointsSrc, matSrcRet);
speedTimer.Record("模板生成KeyPoint");
}
using var flnMatcher = new FlannBasedMatcher();
var knnMatches = flnMatcher.KnnMatch(matSrcRet, _trainRet, 2);
var minRatio = 0.66;
var pointsSrc = new List<Point2f>();
var pointsDst = new List<Point2f>();
//Screening better matching points
// var goodMatches = new List<DMatch>();
for (int i = 0; i < knnMatches.Length; i++)
{
var best = knnMatches[i][0];
var better = knnMatches[i][1];
var r = best.Distance / better.Distance;
if (r > minRatio)
if (match.Length == 2 && match[0].Distance < 0.75 * match[1].Distance)
{
pointsSrc.Add(keyPointsSrc[best.QueryIdx].Pt);
pointsDst.Add(_trainKeyPoints[best.TrainIdx].Pt);
goodMatches.Add(match[0]);
}
}
speedTimer.Record("FlannMatch.KnnMatch");
// var outMat = new Mat();
// algorithm RANSAC Filter the matched results
var pSrc = pointsSrc.ToPoint2d();
var pDst = pointsDst.ToPoint2d();
var outMask = new Mat();
// If the original matching result is null, Skip the filtering step
if (pSrc.Count > 0 && pDst.Count > 0)
if (goodMatches.Count < 7)
{
var hMat = Cv2.FindHomography(pSrc, pDst, HomographyMethods.Ransac, mask: outMask);
speedTimer.Record("FindHomography");
var objCorners = new Point2f[4];
objCorners[0] = new Point2f(0, 0);
objCorners[1] = new Point2f(0, matSrc.Rows);
objCorners[2] = new Point2f(matSrc.Cols, matSrc.Rows);
objCorners[3] = new Point2f(matSrc.Cols, 0);
var sceneCorners = Cv2.PerspectiveTransform(objCorners, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return sceneCorners;
return new Point2f();
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
{
return new Point2f();
}
speedTimer.Record("FindHomography");
// 计算小地图的中心点
var h = queryMat.Rows;
var w = queryMat.Cols;
var centerPoint = new Point2f(w / 2f, h / 2f);
Point2f[] centerPoints = [centerPoint];
Point2f[] transformedCenter = Cv2.PerspectiveTransform(centerPoints, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return null;
// 返回小地图在大地图中的中心坐标
return transformedCenter[0];
}
public Point2f[] KnnMatchCorners(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
foreach (var match in matches)
{
if (match.Length == 2 && match[0].Distance < 0.75 * match[1].Distance)
{
goodMatches.Add(match[0]);
}
}
if (goodMatches.Count < 7)
{
return [];
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
{
return [];
}
speedTimer.Record("FindHomography");
// 返回四个角点
var objCorners = new Point2f[4];
objCorners[0] = new Point2f(0, 0);
objCorners[1] = new Point2f(0, queryMat.Rows);
objCorners[2] = new Point2f(queryMat.Cols, queryMat.Rows);
objCorners[3] = new Point2f(queryMat.Cols, 0);
var sceneCorners = Cv2.PerspectiveTransform(objCorners, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return sceneCorners;
}
public Rect KnnMatchRect(Mat queryMat, Mat? queryMatMask = null)
{
var corners = KnnMatchCorners(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
if (corners.Length == 0)
{
return Rect.Empty;
}
return Cv2.BoundingRect(corners);
}
#endregion Knn匹配
}
@@ -1,10 +1,7 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
@@ -19,13 +16,34 @@ public class FeatureStorage(string name)
public string TypeName { get; set; } = "UNKNOWN";
// public KeyPoint[]? LoadKeyPointArray1()
// {
// CreateFolder();
// string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
// if (File.Exists(kpPath))
// {
// return ObjectUtils.Deserialize(File.ReadAllBytes(kpPath)) as KeyPoint[];
// }
// return null;
// }
//
// public void SaveKeyPointArray1(KeyPoint[] kpArray)
// {
// CreateFolder();
// string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
// File.WriteAllBytes(kpPath, ObjectUtils.Serialize(kpArray));
// }
public KeyPoint[]? LoadKeyPointArray()
{
CreateFolder();
string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
if (File.Exists(kpPath))
{
return ObjectUtils.Deserialize(File.ReadAllBytes(kpPath)) as KeyPoint[];
FileStorage fs = new(kpPath, FileStorage.Modes.Read);
var kpArray = fs["kp"]?.ReadKeyPoints();
fs.Release();
return kpArray;
}
return null;
}
@@ -34,7 +52,9 @@ public class FeatureStorage(string name)
{
CreateFolder();
string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
File.WriteAllBytes(kpPath, ObjectUtils.Serialize(kpArray));
FileStorage fs = new(kpPath, FileStorage.Modes.Write);
fs.Write("kp", kpArray);
fs.Release();
}
private void CreateFolder()
@@ -45,31 +65,31 @@ public class FeatureStorage(string name)
}
}
public Mat? LoadDescMat1()
{
CreateFolder();
// 格式: Surf_336767x128.mat
var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
if (files.Length == 0)
{
return null;
}
else if (files.Length > 1)
{
Debug.WriteLine($"[FeatureSerializer] Found multiple files: {string.Join(", ", files)}");
}
var rowColPair = Path.GetFileNameWithoutExtension(files[0])
.Replace($"{name}_{TypeName}_", "")
.Split('x');
if (rowColPair.Length != 2)
{
Debug.WriteLine($"[FeatureSerializer] Invalid file name: {files[0]}");
return null;
}
GCHandle pinnedArray = GCHandle.Alloc(ObjectUtils.Deserialize(File.ReadAllBytes(files[0])), GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
return new Mat(Convert.ToInt32(rowColPair[0]), Convert.ToInt32(rowColPair[1]), MatType.CV_32FC1, pointer);
}
// public Mat? LoadDescMat1()
// {
// CreateFolder();
// // 格式: Surf_336767x128.mat
// var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
// if (files.Length == 0)
// {
// return null;
// }
// else if (files.Length > 1)
// {
// Debug.WriteLine($"[FeatureSerializer] Found multiple files: {string.Join(", ", files)}");
// }
// var rowColPair = Path.GetFileNameWithoutExtension(files[0])
// .Replace($"{name}_{TypeName}_", "")
// .Split('x');
// if (rowColPair.Length != 2)
// {
// Debug.WriteLine($"[FeatureSerializer] Invalid file name: {files[0]}");
// return null;
// }
// GCHandle pinnedArray = GCHandle.Alloc(ObjectUtils.Deserialize(File.ReadAllBytes(files[0])), GCHandleType.Pinned);
// IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// return new Mat(Convert.ToInt32(rowColPair[0]), Convert.ToInt32(rowColPair[1]), MatType.CV_32FC1, pointer);
// }
public Mat? LoadDescMat()
{
@@ -89,21 +109,21 @@ public class FeatureStorage(string name)
return mat;
}
public void SaveDescMat1(Mat descMat)
{
CreateFolder();
// 删除旧文件
var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
foreach (var file in files)
{
File.Delete(file);
}
var descPath = Path.Combine(rootPath, $"{name}_{TypeName}_{descMat.Rows}x{descMat.Cols}.mat");
var bytes = new byte[descMat.Step(0) * descMat.Rows]; // matSrcRet.Total() * matSrcRet.ElemSize()
Marshal.Copy(descMat.Data, bytes, 0, bytes.Length);
File.WriteAllBytes(descPath, ObjectUtils.Serialize(bytes));
}
// public void SaveDescMat1(Mat descMat)
// {
// CreateFolder();
// // 删除旧文件
// var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
// foreach (var file in files)
// {
// File.Delete(file);
// }
//
// var descPath = Path.Combine(rootPath, $"{name}_{TypeName}_{descMat.Rows}x{descMat.Cols}.mat");
// var bytes = new byte[descMat.Step(0) * descMat.Rows]; // matSrcRet.Total() * matSrcRet.ElemSize()
// Marshal.Copy(descMat.Data, bytes, 0, bytes.Length);
// File.WriteAllBytes(descPath, ObjectUtils.Serialize(bytes));
// }
public void SaveDescMat(Mat descMat)
{
@@ -68,15 +68,15 @@ public class KeyPointFeatureBlockHelper
return splitKeyPoints;
}
public static (int, int) GetCellIndex(Size originalImage, int rows, int cols, int x, int y)
public static (int, int) GetCellIndex(Size originalImage, int rows, int cols, float x, float y)
{
// Calculate grid size
int cellWidth = originalImage.Width / cols;
int cellHeight = originalImage.Height / rows;
// Calculate cell index for the given point
int cellRow = y / cellHeight;
int cellCol = x / cellWidth;
var cellRow = (int)Math.Round(y / cellHeight, 0);
var cellCol = (int)Math.Round(x / cellWidth, 0);
return (cellRow, cellCol);
}
@@ -155,7 +155,7 @@ public class MatchTemplateHelper
/// <returns></returns>
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, List<Mat> imgSubList, double threshold = 0.8)
{
List<Rect> list = new();
List<Rect> list = [];
foreach (var sub in imgSubList)
while (true)
{
@@ -185,7 +185,7 @@ public class MatchTemplateHelper
/// <returns></returns>
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8)
{
List<Rect> list = new();
List<Rect> list = [];
while (true)
{
@@ -217,7 +217,7 @@ public class MatchTemplateHelper
/// <returns></returns>
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat, double threshold, int maxCount = -1)
{
List<Rect> list = new();
List<Rect> list = [];
if (maxCount < 0)
{
@@ -1,5 +1,5 @@
using System.Collections.Generic;
using OpenCvSharp;
using OpenCvSharp;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.Model;
@@ -9,7 +9,7 @@ namespace BetterGenshinImpact.Core.Recognition.OpenCv.Model;
/// </summary>
public class KeyPointFeatureBlock
{
public List<KeyPoint> KeyPointList { get; set; } = new();
public List<KeyPoint> KeyPointList { get; set; } = [];
private KeyPoint[]? keyPointArray;
@@ -25,7 +25,7 @@ public class KeyPointFeatureBlock
/// <summary>
/// 在完整 KeyPoint[] 中的下标
/// </summary>
public List<int> KeyPointIndexList { get; set; } = new();
public List<int> KeyPointIndexList { get; set; } = [];
public Mat? Descriptor;
@@ -123,26 +123,26 @@ public class RecognitionObject
/// <summary>
/// 部分文字识别结果不准确,进行替换。可选。
/// </summary>
public Dictionary<string, string[]> ReplaceDictionary { get; set; } = new();
public Dictionary<string, string[]> ReplaceDictionary { get; set; } = [];
/// <summary>
/// 包含匹配
/// 多个值全匹配的情况下才算成功
/// 复杂情况请用下面的正则匹配
/// </summary>
public List<string> AllContainMatchText { get; set; } = new();
public List<string> AllContainMatchText { get; set; } = [];
/// <summary>
/// 包含匹配
/// 一个值匹配就算成功
/// </summary>
public List<string> OneContainMatchText { get; set; } = new();
public List<string> OneContainMatchText { get; set; } = [];
/// <summary>
/// 正则匹配
/// 多个值全匹配的情况下才算成功
/// </summary>
public List<string> RegexMatchText { get; set; } = new();
public List<string> RegexMatchText { get; set; } = [];
#endregion OCR文字识别
}
@@ -8,9 +8,9 @@ using Microsoft.Extensions.Logging;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
@@ -20,7 +20,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
private KeyMouseRecorder? _recorder;
private readonly Dictionary<Keys, bool> _keyDownState = new();
private readonly Dictionary<Keys, bool> _keyDownState = [];
private DirectInputMonitor? _directInputMonitor;
@@ -28,6 +28,8 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
private bool _isInMainUi = false; // 是否在主界面
public KeyMouseRecorderStatus Status { get; set; } = KeyMouseRecorderStatus.Stop;
public GlobalKeyMouseRecord()
{
_timer.Elapsed += Tick;
@@ -38,33 +40,49 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
{
if (!TaskContext.Instance().IsInitialized)
{
MessageBox.Show("请先在启动页,启动截图器再使用本功能");
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
}
TaskTriggerDispatcher.Instance().StopTimer();
if (Status != KeyMouseRecorderStatus.Stop)
{
Toast.Warning("已经在录制状态,请不要重复启动录制功能");
return;
}
Status = KeyMouseRecorderStatus.Start;
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
SystemControl.ActivateWindow();
for (var i = 3; i >= 1; i--)
{
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
}
TaskTriggerDispatcher.Instance().StopTimer();
_timer.Start();
_recorder = new KeyMouseRecorder();
_directInputMonitor = new DirectInputMonitor();
_directInputMonitor.Start();
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:{Text}", "已启动");
}
public string StopRecord()
{
if (Status != KeyMouseRecorderStatus.Recording)
{
throw new InvalidOperationException("未处于录制中状态,无法停止");
}
var macro = _recorder?.ToJsonMacro() ?? string.Empty;
_recorder = null;
_directInputMonitor?.Stop();
@@ -76,6 +94,9 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_logger.LogInformation("录制:{Text}", "结束录制");
TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
return macro;
}
@@ -127,7 +148,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
return;
}
if (_keyDownState.ContainsKey(e.KeyCode) && _keyDownState[e.KeyCode])
if (_keyDownState.TryGetValue(e.KeyCode, out bool state) && state)
{
// Debug.WriteLine($"KeyUp: {e.KeyCode}");
_keyDownState[e.KeyCode] = false;
@@ -167,3 +188,10 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_recorder?.MouseMoveBy(state);
}
}
public enum KeyMouseRecorderStatus
{
Start,
Recording,
Stop
}
@@ -1,6 +1,10 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -8,30 +12,27 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
public class KeyMouseMacroPlayer
{
public static async Task PlayMacro(string macro, CancellationToken ct)
public static async Task PlayMacro(string macro, CancellationToken ct, bool withDelay = true)
{
if (!TaskContext.Instance().IsInitialized)
{
MessageBox.Show("请先在启动页,启动截图器再使用本功能");
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
}
try
{
TaskTriggerDispatcher.Instance().StopTimer();
var script = JsonSerializer.Deserialize<KeyMouseScript>(macro, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro");
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect);
SystemControl.ActivateWindow();
var script = JsonSerializer.Deserialize<KeyMouseScript>(macro, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro");
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect);
SystemControl.ActivateWindow();
if (withDelay)
{
for (var i = 3; i >= 1; i--)
{
TaskControl.Logger.LogInformation("{Sec}秒后进行重放...", i);
@@ -39,20 +40,26 @@ public class KeyMouseMacroPlayer
}
TaskControl.Logger.LogInformation("开始重放");
await PlayMacro(script.MacroEvents, ct);
}
finally
{
TaskTriggerDispatcher.Instance().StartTimer();
}
await PlayMacro(script.MacroEvents, ct);
}
public static async Task PlayMacro(List<MacroEvent> macroEvents, CancellationToken ct)
{
WorkingArea = PrimaryScreen.WorkingArea;
var startTime = DateTime.UtcNow;
foreach (var e in macroEvents)
{
await Task.Delay((int)Math.Round(e.Time), ct);
var timeToWait = (int)(e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds);
if (timeToWait < 0)
{
TaskControl.Logger.LogWarning("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), -timeToWait);
}
else
{
await Task.Delay(timeToWait, ct);
}
switch (e.Type)
{
case MacroEventType.KeyDown:
@@ -134,6 +141,18 @@ public class KeyMouseMacroPlayer
break;
case MacroEventType.MouseMoveBy:
if (e.CameraOrientation != null)
{
var cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcGreyMat);
var diff = (cao - (int)e.CameraOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
//过滤一下特别大的角度偏差
if (diff != 0 && diff < 8 && diff > -8)
{
TaskControl.Logger.LogWarning("视角重放偏差{diff}°,尝试修正", diff);
e.MouseX -= diff;
}
}
Simulation.SendInput.Mouse.MoveMouseBy(e.MouseX, e.MouseY);
break;
@@ -1,12 +1,14 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using Gma.System.MouseKeyHook;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using SharpDX.DirectInput;
using BetterGenshinImpact.GameTask;
namespace BetterGenshinImpact.Core.Recorder;
@@ -14,7 +16,11 @@ public class KeyMouseRecorder
{
public List<MacroEvent> MacroEvents { get; } = [];
public DateTime CurrentTime { get; set; } = DateTime.Now;
public DateTime StartTime { get; set; } = DateTime.UtcNow;
public DateTime LastOrientationDetection { get; set; } = DateTime.UtcNow;
public double MergedEventTimeMax { get; set; } = 20.0;
public static readonly JsonSerializerOptions JsonOptions = new()
{
@@ -29,9 +35,63 @@ public class KeyMouseRecorder
public string ToJsonMacro()
{
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
// 合并鼠标移动事件
var mergedMacroEvents = new List<MacroEvent>();
MacroEvent? currentMerge = null;
foreach (var macroEvent in MacroEvents)
{
if (currentMerge == null)
{
currentMerge = macroEvent;
continue;
}
if (currentMerge.Type != macroEvent.Type)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
continue;
}
switch (macroEvent.Type)
{
case MacroEventType.MouseMoveTo:
// 控制合并时间片段长度
if (macroEvent.Time - currentMerge.Time > MergedEventTimeMax)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 合并为最后一个事件的位置,避免丢步
currentMerge.MouseX = macroEvent.MouseX;
currentMerge.MouseY = macroEvent.MouseY;
break;
case MacroEventType.MouseMoveBy:
if (macroEvent.Time - currentMerge.Time > MergedEventTimeMax)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 相对位移量相加
currentMerge.MouseX += macroEvent.MouseX;
currentMerge.MouseY += macroEvent.MouseY;
if (macroEvent.CameraOrientation != null)
{
currentMerge.CameraOrientation = macroEvent.CameraOrientation;
}
break;
default:
mergedMacroEvents.Add(currentMerge);
mergedMacroEvents.Add(macroEvent);
currentMerge = null;
break;
}
}
KeyMouseScript keyMouseScript = new()
{
MacroEvents = MacroEvents,
MacroEvents = mergedMacroEvents,
Info = new KeyMouseScriptInfo
{
X = rect.X,
@@ -49,9 +109,8 @@ public class KeyMouseRecorder
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
CurrentTime = DateTime.Now;
}
public void KeyUp(KeyEventArgs e)
@@ -60,9 +119,8 @@ public class KeyMouseRecorder
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
CurrentTime = DateTime.Now;
}
public void MouseDown(MouseEventExtArgs e)
@@ -73,9 +131,8 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
CurrentTime = DateTime.Now;
}
public void MouseUp(MouseEventExtArgs e)
@@ -86,9 +143,8 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
CurrentTime = DateTime.Now;
}
public void MouseMoveTo(MouseEventExtArgs e)
@@ -98,20 +154,29 @@ public class KeyMouseRecorder
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
CurrentTime = DateTime.Now;
}
public void MouseMoveBy(MouseState state)
{
var now = DateTime.UtcNow;
int? cao = null;
if (TaskContext.Instance().Config.RecordConfig.IsRecordCameraOrientation)
{
if ((now - LastOrientationDetection).TotalMilliseconds > 100.0)
{
LastOrientationDetection = now;
cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcGreyMat);
}
}
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = state.X,
MouseY = state.Y,
Time = (DateTime.Now - CurrentTime).TotalMilliseconds
Time = (now - StartTime).TotalMilliseconds,
CameraOrientation = cao,
});
CurrentTime = DateTime.Now;
}
}
@@ -11,6 +11,8 @@ public class MacroEvent
public int MouseY { get; set; }
public string? MouseButton { get; set; }
public double Time { get; set; }
public int? CameraOrientation { get; set; }
}
public enum MacroEventType
@@ -7,18 +7,25 @@ public class CancellationContext : Singleton<CancellationContext>
{
public CancellationTokenSource Cts { get; set; } = new();
private bool disposed;
public void Set()
{
Cts = new CancellationTokenSource();
disposed = false;
}
public void Cancel()
{
Cts.Cancel();
if (!disposed)
{
Cts.Cancel();
}
}
public void Clear()
{
Cts.Dispose();
disposed = true;
}
}
@@ -0,0 +1,26 @@
using System.Threading.Tasks;
using System.Text.Json;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
namespace BetterGenshinImpact.Core.Script.Dependence
{
internal class AutoPathing(string rootPath)
{
public async Task Run(string json)
{
var task = JsonSerializer.Deserialize<PathingTask>(json);
if (task == null)
{
return;
}
await PathExecutor.Pathing(task, CancellationContext.Instance.Cts);
}
public async Task RunFile(string path)
{
var json = await new LimitedFile(rootPath).ReadText(path);
await Run(json);
}
}
}
@@ -0,0 +1,27 @@
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using System;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Dispatcher
{
public void RunTask()
{
}
public void AddTimer(RealtimeTimer timer)
{
var realtimeTimer = timer;
if (realtimeTimer == null)
{
throw new ArgumentNullException(nameof(realtimeTimer), "实时任务对象不能为空");
}
if (string.IsNullOrEmpty(realtimeTimer.Name))
{
throw new ArgumentNullException(nameof(realtimeTimer.Name), "实时任务名称不能为空");
}
TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config);
}
}
@@ -1,5 +1,5 @@
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -0,0 +1,18 @@
using BetterGenshinImpact.Core.Recorder;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class KeyMouseScript(string rootPath)
{
public async Task Run(string json)
{
await KeyMouseMacroPlayer.PlayMacro(json, CancellationContext.Instance.Cts.Token, false);
}
public async Task RunFile(string path)
{
var json = await new LimitedFile(rootPath).ReadText(path);
await Run(json);
}
}
@@ -0,0 +1,62 @@
using BetterGenshinImpact.Core.Script.Utils;
using System;
using System.IO;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class LimitedFile(string rootPath)
{
/// <summary>
/// Normalize and validate a path.
/// </summary>
private string NormalizePath(string path)
{
return ScriptUtils.NormalizePath(rootPath, path);
}
/// <summary>
/// Read all text from a file.
/// </summary>
/// <param name="path">File path.</param>
/// <returns>Text read from file.</returns>
public string ReadTextSync(string path)
{
path = NormalizePath(path);
return File.ReadAllText(path);
}
/// <summary>
/// Read all text from a file.
/// </summary>
/// <param name="path">File path.</param>
/// <returns>Text read from file.</returns>
public async Task<string> ReadText(string path)
{
path = NormalizePath(path);
var ret = await File.ReadAllTextAsync(path);
return ret;
}
/// <summary>
/// Read all text from a file.
/// </summary>
/// <param name="path">File path.</param>
/// <param name="callbackFunc">Callback function.</param>
/// <returns>Text read from file.</returns>
public async Task<string> ReadText(string path, dynamic callbackFunc)
{
try
{
path = NormalizePath(path);
var ret = await File.ReadAllTextAsync(path);
callbackFunc(null, ret);
return ret;
}
catch (Exception ex)
{
callbackFunc(ex.ToString(), null);
return string.Empty;
}
}
}
@@ -0,0 +1,32 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 实时任务计时器
/// </summary>
public class RealtimeTimer
{
/// <summary>
/// 实时任务触发器名称
/// </summary>
public string? Name { get; set; }
/// <summary>
/// 实时任务触发器时间间隔
/// 默认50ms
/// </summary>
public int Interval { get; set; } = 50;
/// <summary>
/// 实时任务配置
/// </summary>
public object? Config;
public RealtimeTimer()
{
}
public RealtimeTimer(string name)
{
Name = name;
}
}
@@ -0,0 +1,13 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
public class AutoPickExternalConfig
{
// 关闭黑白名单
public bool DisabledBlackWhiteList { get; set; } = false;
// 需要F的文本(对话、拾取)
public string[] TextList { get; set; } = [];
// 无视文本和图标遇到F就点击
public bool ForceInteraction { get; set; } = false;
}
@@ -1,25 +1,42 @@
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using BetterGenshinImpact.Core.Script.Dependence;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script;
public class EngineExtend
{
public static void InitHost(IScriptEngine engine)
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null)
{
// engine.AddHostObject("xHost", new ExtendedHostFunctions()); // 有越权的安全风险
// 添加我的自定义实例化对象
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("autoPathing", new AutoPathing(workDir));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
// 添加方法
// 实时任务调度器
engine.AddHostObject("dispatcher", new Dispatcher());
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
// 直接添加方法
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
#pragma warning restore CS8974 // Converting method group to non-delegate type
// 添加C#的类型
engine.AddHostType(typeof(Task));
// 导入 CommonJS 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
if (searchPaths != null)
{
engine.DocumentSettings.SearchPath = string.Join(';', searchPaths);
}
}
}
@@ -0,0 +1,39 @@
using BetterGenshinImpact.Service;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text.Json;
namespace BetterGenshinImpact.Core.Script.Group;
public partial class ScriptGroup : ObservableObject
{
public int Index { get; set; }
[ObservableProperty]
private string _name = string.Empty;
[ObservableProperty]
private ObservableCollection<ScriptGroupProject> _projects = [];
public ScriptGroup()
{
Projects.CollectionChanged += ProjectsCollectionChanged;
}
private void ProjectsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged(nameof(Projects));
}
public string ToJson()
{
return JsonSerializer.Serialize(this, ConfigService.JsonOptions);
}
public static ScriptGroup FromJson(string json)
{
return JsonSerializer.Deserialize<ScriptGroup>(json, ConfigService.JsonOptions) ?? throw new Exception("解析配置组JSON配置失败");
}
}
@@ -0,0 +1,161 @@
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Project;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Group;
public partial class ScriptGroupProject : ObservableObject
{
[ObservableProperty]
private int _index;
public string Name { get; set; } = string.Empty;
public string FolderName { get; set; } = string.Empty;
[ObservableProperty]
private string _type = string.Empty;
[JsonIgnore]
public string TypeDesc => ScriptGroupProjectExtensions.TypeDescriptions[Type];
[ObservableProperty]
private string _status = string.Empty;
[JsonIgnore]
public string StatusDesc => ScriptGroupProjectExtensions.StatusDescriptions[Status];
/// <summary>
/// 执行周期
/// 不在 ScheduleDescriptions 中则会被视为自定义Cron表达式
/// </summary>
[ObservableProperty]
private string _schedule = string.Empty;
[JsonIgnore]
public string ScheduleDesc => ScriptGroupProjectExtensions.ScheduleDescriptions.GetValueOrDefault(Schedule, "自定义周期");
[ObservableProperty]
private int _runNum = 1;
[JsonIgnore]
public ScriptProject? Project { get; set; }
public ScriptGroupProject()
{
}
public ScriptGroupProject(ScriptProject project)
{
Name = project.Manifest.Name;
FolderName = project.FolderName;
Status = "Enabled";
Schedule = "Daily";
Project = project;
Type = "Javascript";
}
public ScriptGroupProject(string kmName)
{
Name = kmName;
FolderName = kmName;
Status = "Enabled";
Schedule = "Daily";
Project = null; // 不是Js脚本
Type = "KeyMouse";
}
/// <summary>
/// 通过 FolderName 查找 ScriptProject
/// </summary>
public void BuildScriptProjectRelation()
{
if (string.IsNullOrEmpty(FolderName))
{
throw new Exception("FolderName 为空");
}
Project = new ScriptProject(FolderName);
}
public async Task Run()
{
if (Type == "Javascript")
{
if (Project == null)
{
throw new Exception("JS脚本未初始化");
}
await Project.ExecuteAsync();
}
if (Type == "KeyMouse")
{
// 加载并执行
var json = await File.ReadAllTextAsync(Global.Absolute(@$"User\KeyMouseScript\{Name}"));
await KeyMouseMacroPlayer.PlayMacro(json, CancellationContext.Instance.Cts.Token, false);
}
else
{
throw new Exception("不支持的脚本类型");
}
}
partial void OnTypeChanged(string value)
{
OnPropertyChanged(nameof(TypeDesc));
}
partial void OnStatusChanged(string value)
{
OnPropertyChanged(nameof(StatusDesc));
}
partial void OnScheduleChanged(string value)
{
OnPropertyChanged(nameof(ScheduleDesc));
}
}
public class ScriptGroupProjectExtensions
{
public static readonly Dictionary<string, string> TypeDescriptions = new()
{
{ "Javascript", "JS脚本" },
{ "KeyMouse", "键鼠脚本" }
};
public static readonly Dictionary<string, string> StatusDescriptions = new()
{
{ "Enabled", "启用" },
{ "Disabled", "禁用" }
};
public Dictionary<string, string> GetStatusDescriptions()
{
return StatusDescriptions;
}
public static readonly Dictionary<string, string> ScheduleDescriptions = new()
{
{ "Daily", "每日" },
{ "EveryTwoDays", "间隔两天" },
{ "Monday", "每周一" },
{ "Tuesday", "每周二" },
{ "Wednesday", "每周三" },
{ "Thursday", "每周四" },
{ "Friday", "每周五" },
{ "Saturday", "每周六" },
{ "Sunday", "每周日" }
};
public Dictionary<string, string> GetScheduleDescriptions()
{
return ScheduleDescriptions;
}
}
@@ -0,0 +1,7 @@
namespace BetterGenshinImpact.Core.Script.Project;
public class Author
{
public string Name { get; set; } = string.Empty;
public string Link { get; set; } = string.Empty;
}
@@ -0,0 +1,49 @@
using BetterGenshinImpact.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace BetterGenshinImpact.Core.Script.Project;
[Serializable]
public class Manifest
{
public int ManifestVersion { get; set; } = 1;
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<Author> Authors { get; set; } = [];
public string Main { get; set; } = string.Empty;
public string[] Scripts { get; set; } = [];
public string[] Library { get; set; } = [];
public static Manifest FromJson(string json)
{
var manifest = JsonSerializer.Deserialize<Manifest>(json, ConfigService.JsonOptions) ?? throw new Exception("Failed to deserialize JSON.");
return manifest;
}
public void Validate(string path)
{
if (string.IsNullOrWhiteSpace(Name))
{
throw new Exception("manifest.json: name is required.");
}
if (string.IsNullOrWhiteSpace(Version))
{
throw new Exception("manifest.json: version is required.");
}
if (string.IsNullOrWhiteSpace(Main))
{
throw new Exception("manifest.json: main script is required.");
}
if (!File.Exists(Path.Combine(path, Main)))
{
throw new FileNotFoundException("main js file not found.");
}
}
}
@@ -0,0 +1,70 @@
using BetterGenshinImpact.Core.Config;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Project;
public class ScriptProject
{
public string ProjectPath { get; set; }
public string ManifestFile { get; set; }
public Manifest Manifest { get; set; }
public string FolderName { get; set; }
public ScriptProject(string folderName)
{
FolderName = folderName;
ProjectPath = Path.Combine(Global.ScriptPath(), folderName);
ManifestFile = Path.GetFullPath(Path.Combine(ProjectPath, "manifest.json"));
if (!File.Exists(ManifestFile))
{
throw new FileNotFoundException("manifest.json file not found.");
}
Manifest = Manifest.FromJson(File.ReadAllText(ManifestFile));
Manifest.Validate(ProjectPath);
}
public IScriptEngine BuildScriptEngine()
{
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library);
return engine;
}
public async Task ExecuteAsync()
{
var code = await LoadCode();
var engine = BuildScriptEngine();
try
{
await (Task)engine.Evaluate(code);
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
finally
{
engine.Dispose();
}
}
public async Task<string> LoadCode()
{
var code = await File.ReadAllTextAsync(Path.Combine(ProjectPath, Manifest.Main));
if (string.IsNullOrEmpty(code))
{
throw new FileNotFoundException("main js is empty.");
}
return code;
}
}
@@ -0,0 +1,26 @@
using System;
using System.IO;
namespace BetterGenshinImpact.Core.Script.Utils;
public class ScriptUtils
{
/// <summary>
/// Normalize and validate a path.
/// </summary>
public static string NormalizePath(string root, string path)
{
// convert to full path relative to root
path = path.Replace('\\', '/');
var fullPath = Path.GetFullPath(Path.Combine(root, path));
// if root is locked, make sure didn't attempt to exit it
if (!fullPath.StartsWith(root))
{
throw new ArgumentException($"Path '{path}' is not allowed, because its outside the caged root folder!");
}
// return full path
return fullPath;
}
}
@@ -125,7 +125,7 @@ public class PostMessageSimulator
//User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -134,7 +134,7 @@ public class PostMessageSimulator
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
Thread.Sleep(ms);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -143,7 +143,7 @@ public class PostMessageSimulator
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
Thread.Sleep(1000);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -155,7 +155,7 @@ public class PostMessageSimulator
public PostMessageSimulator KeyUp(User32.VK vk)
{
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -164,7 +164,7 @@ public class PostMessageSimulator
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -178,7 +178,7 @@ public class PostMessageSimulator
public PostMessageSimulator KeyUpBackground(User32.VK vk)
{
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, (nint)0xc01e0001);
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
return this;
}
@@ -25,7 +25,6 @@ using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.User32;
@@ -306,7 +305,7 @@ public class AutoDomainTask
private Task StartFight(CombatScenes combatScenes, List<CombatCommand> combatCommands)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenSource cts = new();
_taskParam.Cts.Token.Register(cts.Cancel);
combatScenes.BeforeTask(cts);
// 战斗操作
@@ -412,7 +411,7 @@ public class AutoDomainTask
/// </summary>
private Task FindPetrifiedTree()
{
CancellationTokenSource treeCts = new CancellationTokenSource();
CancellationTokenSource treeCts = new();
_taskParam.Cts.Token.Register(treeCts.Cancel);
// 中键回正视角
Simulation.SendInput.Mouse.MiddleButtonClick();
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model;
using OpenCvSharp;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoFight.Assets;
@@ -1,9 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -1,10 +1,5 @@
using BetterGenshinImpact.GameTask.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -44,6 +44,6 @@ public class CombatAvatar
/// <summary>
/// 别名
/// </summary>
public List<string> Alias { get; set; } = new();
public List<string> Alias { get; set; } = [];
}
@@ -27,12 +27,7 @@ public class DefaultAutoFightConfig
public static string AvatarAliasToStandardName(string alias)
{
var avatar = CombatAvatars.Find(x => x.Alias.Contains(alias));
if (avatar == null)
{
throw new Exception($"角色名称校验失败:{alias}");
}
var avatar = CombatAvatars.Find(x => x.Alias.Contains(alias)) ?? throw new Exception($"角色名称校验失败:{alias}");
return avatar.Name;
}
}
@@ -1,19 +1,16 @@
using System;
using System.Diagnostics;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Config;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Linq;
using System.Threading;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Area;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.User32;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -218,7 +215,7 @@ public class Avatar
if (contours.Length > 0)
{
var boxes = contours.Select(Cv2.BoundingRect).Where(w => w.Width >= 20 * assetScale && w.Height >= 18 * assetScale).OrderByDescending(w => w.Width).ToList();
if (boxes.Any())
if (boxes.Count is not 0)
{
IndexRect = boxes.First();
return false;
@@ -1,9 +1,10 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoFight.Config;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using Compunet.YoloV8;
using Microsoft.Extensions.Logging;
@@ -18,8 +19,6 @@ using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Model.Area;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -34,7 +33,7 @@ public class CombatScenes : IDisposable
/// </summary>
public Avatar[] Avatars { get; set; } = new Avatar[1];
public Dictionary<string, Avatar> AvatarMap { get; set; } = new();
public Dictionary<string, Avatar> AvatarMap { get; set; } = [];
public int AvatarCount { get; set; }
@@ -70,9 +69,9 @@ public class CombatScenes : IDisposable
if (!string.IsNullOrEmpty(pair.Item2))
{
var costumeName = pair.Item2;
if (AutoFightAssets.Instance.AvatarCostumeMap.ContainsKey(costumeName))
if (AutoFightAssets.Instance.AvatarCostumeMap.TryGetValue(costumeName, out string? name))
{
costumeName = AutoFightAssets.Instance.AvatarCostumeMap[costumeName];
costumeName = name;
}
displayNames[i] = $"{pair.Item1}({costumeName})";
@@ -83,7 +82,7 @@ public class CombatScenes : IDisposable
}
}
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
Avatars = BuildAvatars(names.ToList());
Avatars = BuildAvatars([.. names]);
AvatarMap = Avatars.ToDictionary(x => x.Name);
}
catch (Exception e)
@@ -121,10 +120,23 @@ public class CombatScenes : IDisposable
speedTimer.Record("角色侧面头像分类识别");
Debug.WriteLine($"角色侧面头像识别结果:{result}");
speedTimer.DebugPrint();
if (result.TopClass.Confidence < 0.8)
if (result.TopClass.Name.Name.StartsWith("Qin") || result.TopClass.Name.Name.Contains("Costume"))
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
// 降低琴和衣装角色的识别率要求
if (result.TopClass.Confidence < 0.6)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
}
}
else
{
if (result.TopClass.Confidence < 0.8)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
}
}
return result.TopClass.Name.Name;
@@ -132,7 +144,7 @@ public class CombatScenes : IDisposable
private void InitializeTeamFromConfig(string teamNames)
{
var names = teamNames.Split(new[] { ",", "," }, StringSplitOptions.TrimEntries);
var names = teamNames.Split([",", ","], StringSplitOptions.TrimEntries);
if (names.Length != 4)
{
throw new Exception($"强制指定队伍角色数量不正确,必须是4个,当前{names.Length}个");
@@ -146,7 +158,7 @@ public class CombatScenes : IDisposable
Logger.LogInformation("强制指定队伍角色:{Text}", string.Join(",", names));
TaskContext.Instance().Config.AutoFightConfig.TeamNames = string.Join(",", names);
Avatars = BuildAvatars(names.ToList());
Avatars = BuildAvatars([.. names]);
AvatarMap = Avatars.ToDictionary(x => x.Name);
}
@@ -219,8 +231,8 @@ public class CombatScenes : IDisposable
[Obsolete]
private void ParseTeamOcrResult(PaddleOcrResult result, ImageRegion rectArea)
{
List<string> names = new();
List<Rect> nameRects = new();
List<string> names = [];
List<Rect> nameRects = [];
foreach (var item in result.Regions)
{
var name = StringUtils.ExtractChinese(item.Text);
@@ -1,18 +1,18 @@
using System;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.Model;
using System.Threading.Tasks;
using System.Threading;
using BetterGenshinImpact.Core.Config;
using System.Threading.Tasks;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Service;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -193,7 +193,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
var avatarMacros = JsonSerializer.Deserialize<List<AvatarMacro>>(json, ConfigService.JsonOptions);
if (avatarMacros == null)
{
return new Dictionary<string, List<CombatCommand>>();
return [];
}
var result = new Dictionary<string, List<CombatCommand>>();
foreach (var avatarMacro in avatarMacros)
@@ -2,7 +2,6 @@
using BetterGenshinImpact.Helpers;
using System;
using System.Collections.Generic;
using System.Windows.Input;
using TimeSpan = System.TimeSpan;
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
@@ -1,7 +1,7 @@
using System;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
@@ -50,7 +50,7 @@ public class CombatScriptParser
public static CombatScript Parse(string path)
{
var script = File.ReadAllText(path);
var lines = script.Split(new[] { "\r\n", "\r", "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);
var lines = script.Split(["\r\n", "\r", "\n", ";"], StringSplitOptions.RemoveEmptyEntries);
var result = new List<string>();
foreach (var line in lines)
{
@@ -58,7 +58,7 @@ public class CombatScriptParser
.Replace("(", "(")
.Replace(")", ")")
.Replace(",", ",");
if (l.StartsWith("//") || l.StartsWith("#") || string.IsNullOrEmpty(l))
if (l.StartsWith("//") || l.StartsWith('#') || string.IsNullOrEmpty(l))
{
continue;
}
@@ -74,8 +74,8 @@ public class CombatScriptParser
public static CombatScript Parse(List<string> lines)
{
List<CombatCommand> combatCommands = new();
HashSet<string> combatAvatarNames = new();
List<CombatCommand> combatCommands = [];
HashSet<string> combatAvatarNames = [];
foreach (var line in lines)
{
var oneLineCombatCommands = ParseLine(line, combatAvatarNames);
@@ -120,7 +120,7 @@ public class CombatScriptParser
continue;
}
if (command.Contains("(") && !command.Contains(")"))
if (command.Contains('(') && !command.Contains(')'))
{
var j = i + 1;
// 括号被逗号分隔,需要合并
@@ -133,7 +133,7 @@ public class CombatScriptParser
throw new Exception("战斗脚本格式错误,指令括号无法配对");
}
if (command.Contains(")"))
if (command.Contains(')'))
{
i = j;
break;
@@ -142,7 +142,7 @@ public class CombatScriptParser
j++;
}
if (!(command.Contains("(") && command.Contains(")")))
if (!(command.Contains('(') && command.Contains(')')))
{
Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号不完整", command);
throw new Exception("战斗脚本格式错误,指令括号不完整");
@@ -1,36 +1,36 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
public class Method
{
public static readonly Method Skill = new(new() { "skill", "e" });
public static readonly Method Burst = new(new() { "burst", "q" });
public static readonly Method Attack = new(new() { "attack", "普攻", "普通攻击" });
public static readonly Method Charge = new(new() { "charge", "重击" });
public static readonly Method Wait = new(new() { "wait", "after", "等待" });
public static readonly Method Skill = new(["skill", "e"]);
public static readonly Method Burst = new(["burst", "q"]);
public static readonly Method Attack = new(["attack", "普攻", "普通攻击"]);
public static readonly Method Charge = new(["charge", "重击"]);
public static readonly Method Wait = new(["wait", "after", "等待"]);
public static readonly Method Walk = new(new() { "walk", "行走" });
public static readonly Method W = new(new() { "w" });
public static readonly Method A = new(new() { "a" });
public static readonly Method S = new(new() { "s" });
public static readonly Method D = new(new() { "d" });
public static readonly Method Walk = new(["walk", "行走"]);
public static readonly Method W = new(["w"]);
public static readonly Method A = new(["a"]);
public static readonly Method S = new(["s"]);
public static readonly Method D = new(["d"]);
public static readonly Method Aim = new(new() { "aim", "r", "瞄准" });
public static readonly Method Dash = new(new() { "dash", "冲刺" });
public static readonly Method Jump = new(new() { "jump", "j", "跳跃" });
public static readonly Method Aim = new(["aim", "r", "瞄准"]);
public static readonly Method Dash = new(["dash", "冲刺"]);
public static readonly Method Jump = new(["jump", "j", "跳跃"]);
// 宏
public static readonly Method MouseDown = new(new() { "mousedown" });
public static readonly Method MouseUp = new(new() { "mouseup" });
public static readonly Method Click = new(new() { "click" });
public static readonly Method MoveBy = new(new() { "moveby" });
public static readonly Method KeyDown = new(new() { "keydown" });
public static readonly Method KeyUp = new(new() { "keyup" });
public static readonly Method KeyPress = new(new() { "keypress" });
public static readonly Method MouseDown = new(["mousedown"]);
public static readonly Method MouseUp = new(["mouseup"]);
public static readonly Method Click = new(["click"]);
public static readonly Method MoveBy = new(["moveby"]);
public static readonly Method KeyDown = new(["keydown"]);
public static readonly Method KeyUp = new(["keyup"]);
public static readonly Method KeyPress = new(["keypress"]);
public static IEnumerable<Method> Values
{
@@ -1,6 +1,5 @@
using OpenCvSharp;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using CommunityToolkit.Mvvm.ComponentModel;
namespace BetterGenshinImpact.GameTask.AutoFishing;
@@ -2,18 +2,16 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFishing.Assets;
using BetterGenshinImpact.GameTask.AutoFishing.Model;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Drawable;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Compunet.YoloV8;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
@@ -23,8 +21,6 @@ using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Model.Area;
using static Vanara.PInvoke.User32;
using Color = System.Drawing.Color;
using Pen = System.Drawing.Pen;
@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
@@ -44,7 +44,7 @@ public class FishType
public static readonly FishType MaintenanceMekPlatinumCollection = new("maintenance mek- platinum collection", "flashing maintenance mek bait", "维护机关·白金典藏型");
public static readonly FishType MaintenanceMekSituationController = new("maintenance mek- situation controller", "flashing maintenance mek bait", "维护机关·态势控制者");
public static readonly FishType MaintenanceMekWaterBodyCleaner = new("maintenance mek- water body cleaner", "flashing maintenance mek bait", "维护机关·水域清理者");
public static readonly FishType MaintenanceMekWaterGoldLeader = new ("maintenance mek- gold leader", "flashing maintenance mek bait", "维护机关·澄金领队型");
public static readonly FishType MaintenanceMekWaterGoldLeader = new("maintenance mek- gold leader", "flashing maintenance mek bait", "维护机关·澄金领队型");
public static IEnumerable<FishType> Values
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using Compunet.YoloV8.Data;
using OpenCvSharp;
using static OpenCvSharp.Cv2;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
@@ -23,7 +22,7 @@ public class Fishpond
/// <summary>
/// 鱼池中的鱼
/// </summary>
public List<OneFish> Fishes { get; set; } = new();
public List<OneFish> Fishes { get; set; } = [];
public Fishpond(DetectionResult result)
{
@@ -45,7 +44,7 @@ public class Fishpond
}
// 可信度最高的鱼放在最前面
Fishes = Fishes.OrderByDescending(fish => fish.Confidence).ToList();
Fishes = [.. Fishes.OrderByDescending(fish => fish.Confidence)];
FishpondRect = CalculateFishpondRect();
}
@@ -98,7 +97,7 @@ public class Fishpond
/// <returns></returns>
public List<OneFish> FilterByBaitName(string baitName)
{
return Fishes.Where(fish => fish.FishType.BaitName == baitName).OrderByDescending(fish => fish.Confidence).ToList();
return [.. Fishes.Where(fish => fish.FishType.BaitName == baitName).OrderByDescending(fish => fish.Confidence)];
}
public OneFish? FilterByBaitNameAndRecently(string baitName, Rect prevTargetFishRect)
@@ -132,10 +131,10 @@ public class Fishpond
/// <returns></returns>
public string MostMatchBait()
{
Dictionary<string, int> dict = new();
Dictionary<string, int> dict = [];
foreach (var fish in Fishes)
{
if (dict.ContainsKey(fish.FishType.BaitName))
if (dict.TryGetValue(fish.FishType.BaitName, out _))
{
dict[fish.FishType.BaitName]++;
}
@@ -1,20 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoFishing;
namespace BetterGenshinImpact.GameTask.AutoFishing;
public record RodInput
{
public double rod_x1;
public double rod_x2;
public double rod_y1;
public double rod_y2;
public double fish_x1;
public double fish_x2;
public double fish_y1;
public double fish_y2;
public int fish_label;
public double rod_x1;
public double rod_x2;
public double rod_y1;
public double rod_y2;
public double fish_x1;
public double fish_x2;
public double fish_y1;
public double fish_y2;
public int fish_label;
}
@@ -1,6 +1,6 @@
using System;
using OpenCvSharp;
using System;
using System.Linq;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.AutoFishing;
@@ -11,10 +11,10 @@ public class RodNet
{
const double alpha = 1734.34 / 2.5;
static readonly double[] dz = { 0.561117562965, 0.637026851288, 0.705579317577,
static readonly double[] dz = [ 0.561117562965, 0.637026851288, 0.705579317577,
1.062734463845, 0.949307580751, 1.015620474332,
1.797904203405, 1.513476738412, 1.013873007495,
1.159949954831, 1.353650974146, 1.302893195071 };
1.159949954831, 1.353650974146, 1.302893195071 ];
static readonly double[,] theta = {
{-0.262674397633, 0.317025388945, -0.457150765450, 0.174522158281,
@@ -31,10 +31,10 @@ public class RodNet
-1.285988918494}
};
static readonly double[] B = { 1.241950004386, 3.051113640564, -3.848898190087 };
static readonly double[] B = [1.241950004386, 3.051113640564, -3.848898190087];
static readonly double[] offset = { 0.4, 0.2, 0.4, 0, 0.3, 0.3,
0.3, 0.15, 0.5, 0.5, 0.5, 0.5 };
static readonly double[] offset = [ 0.4, 0.2, 0.4, 0, 0.3, 0.3,
0.3, 0.15, 0.5, 0.5, 0.5, 0.5 ];
static void F(double[] dst, double[] x, double[] y)
{
@@ -124,9 +124,7 @@ public class RodNet
if (a < b)
{
double temp = a;
a = b;
b = temp;
(b, a) = (a, b);
}
v0 = (288 - (input.rod_y1 + input.rod_y2) / 2) / alpha;
@@ -135,8 +133,8 @@ public class RodNet
v = (288 - (input.fish_y1 + input.fish_y2) / 2) / alpha;
double[] y0z0t = new double[3];
double[] abv0 = { a, b, v0 };
double[] init = { 30, 15, 1 };
double[] abv0 = [a, b, v0];
double[] init = [30, 15, 1];
bool solveSuccess = NewtonRaphson(F, DfInv, y0z0t, abv0, init, 3, 1000, 1e-6);
@@ -166,7 +164,7 @@ public class RodNet
public static int GetRodState(Rect rod, Rect fish, int fishTypeIndex)
{
RodInput input = new RodInput
RodInput input = new()
{
rod_x1 = rod.Left,
rod_x2 = rod.Right,
@@ -1,11 +1,7 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -19,12 +15,12 @@ public partial class AutoGeniusInvokationConfig : ObservableObject
[ObservableProperty] private int _sleepDelay = 0;
public List<Rect> DefaultCharacterCardRects { get; set; } = new()
{
public List<Rect> DefaultCharacterCardRects { get; set; } =
[
new(667, 632, 165, 282),
new(877, 632, 165, 282),
new(1088, 632, 165, 282)
};
];
/// <summary>
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using static Vanara.PInvoke.Gdi32;
using BetterGenshinImpact.Helpers.Extensions;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -16,6 +10,6 @@ public class AutoGeniusInvokationTask
// 读取策略信息
var duel = ScriptParser.Parse(taskParam.StrategyContent);
SystemControl.ActivateWindow();
duel.RunAsync(taskParam);
duel.RunAsync(taskParam).SafeForget();
}
}
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Config;
@@ -47,12 +47,12 @@ public class SkillsItem
/// <summary>
///
/// </summary>
public List<string> SkillTag { get; set; } = new();
public List<string> SkillTag { get; set; } = [];
/// <summary>
///
/// </summary>
public List<CostItem> Cost { get; set; } = new();
public List<CostItem> Cost { get; set; } = [];
}
[Serializable]
@@ -101,7 +101,7 @@ public class CharacterCard
/// <summary>
///
/// </summary>
public List<SkillsItem> Skills { get; set; } = new();
public List<SkillsItem> Skills { get; set; } = [];
public static void CopyCardProperty(Character source, CharacterCard characterCard)
{
@@ -5,6 +5,8 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Assets;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
@@ -12,12 +14,10 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Model.Area;
using Point = OpenCvSharp.Point;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using Point = OpenCvSharp.Point;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -1041,7 +1041,7 @@ public class GeniusInvokationControl
var srcMat = CaptureGameMat();
int halfHeight = srcMat.Height / 2;
Mat bottomMat = new Mat(srcMat, new Rect(0, halfHeight, srcMat.Width, srcMat.Height - halfHeight));
Mat bottomMat = new(srcMat, new Rect(0, halfHeight, srcMat.Width, srcMat.Height - halfHeight));
var lowPurple = new Scalar(239, 239, 239);
var highPurple = new Scalar(255, 255, 255);
@@ -1056,10 +1056,11 @@ public class GeniusInvokationControl
if (contours.Length > 0)
{
// .Where(w => w.Width > 1 && w.Height >= 5)
var rects = contours.Select(Cv2.BoundingRect).ToList();
// 按照Y轴高度排序
rects = rects.OrderBy(r => r.Y).ToList();
var rects = contours
.Select(Cv2.BoundingRect)
// 按照Y轴高度排序
.OrderBy(r => r.Y)
.ToList();
// 第一个和角色卡重叠的矩形
foreach (var rect in rects)
@@ -1142,7 +1143,7 @@ public class GeniusInvokationControl
if (!string.IsNullOrWhiteSpace(text))
{
var hp = -2;
if (Regex.IsMatch(text, @"^[0-9]+$"))
if (RegexHelper.FullNumberRegex().IsMatch(text))
{
hp = int.Parse(text);
}
@@ -1223,7 +1224,7 @@ public class GeniusInvokationControl
#endif
return -10;
}
else if (Regex.IsMatch(text, @"^[0-9]+$"))
else if (RegexHelper.FullNumberRegex().IsMatch(text))
{
_logger.LogInformation("通过OCR识别当前骰子数量: {Text}", text);
return int.Parse(text);
@@ -1,5 +1,5 @@
using System.Threading;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -7,7 +7,7 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// <summary>
/// 角色
/// </summary>
public Character Character { get; set; }
public Character Character { get; set; } = default!;
public ActionEnum Action { get; set; }
@@ -16,7 +16,7 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// </summary>
public int TargetIndex { get; set; }
public override string ToString()
public override string? ToString()
{
if (Action == ActionEnum.UseSkill)
{
@@ -12,34 +12,24 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
public static ActionEnum ChineseToActionEnum(this string type)
{
type = type.ToLower();
switch (type)
return type switch
{
case "出战":
//return ActionEnum.ChooseFirst;
throw new ArgumentOutOfRangeException(nameof(type), type, null);
case "切换":
//return ActionEnum.SwitchLater;
throw new ArgumentOutOfRangeException(nameof(type), type, null);
case "使用":
return ActionEnum.UseSkill;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
"出战" => /* ActionEnum.ChooseFirst, */ throw new ArgumentOutOfRangeException(nameof(type), type, null),
"切换" => /* ActionEnum.SwitchLater, */ throw new ArgumentOutOfRangeException(nameof(type), type, null),
"使用" => ActionEnum.UseSkill,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
public static string ToChinese(this ActionEnum type)
{
switch (type)
return type switch
{
case ActionEnum.ChooseFirst:
return "出战";
case ActionEnum.SwitchLater:
return "切换";
case ActionEnum.UseSkill:
return "使用";
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
ActionEnum.ChooseFirst => "出战",
ActionEnum.SwitchLater => "切换",
ActionEnum.UseSkill => "使用",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
}
}
@@ -1,9 +1,9 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
{
@@ -16,9 +16,9 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// </summary>
public int Index { get; set; }
public string Name { get; set; }
public string Name { get; set; } = default!;
public ElementalType Element { get; set; }
public Skill[] Skills { get; set; }
public Skill[] Skills { get; set; } = default!;
/// <summary>
@@ -46,7 +46,7 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// <summary>
/// 角色身上的负面状态
/// </summary>
public List<CharacterStatusEnum> StatusList { get; set; } = new List<CharacterStatusEnum>();
public List<CharacterStatusEnum> StatusList { get; set; } = [];
/// <summary>
/// 角色区域
@@ -60,7 +60,7 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
public override string ToString()
{
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append($"角色{Index},");
if (Hp != -2)
{
@@ -2,7 +2,7 @@
{
public enum CharacterStatusEnum
{
Frozen,
Frozen,
Dizziness
}
}
@@ -9,7 +9,6 @@ using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -22,13 +21,13 @@ public class Duel
{
private readonly ILogger<Duel> _logger = App.GetLogger<Duel>();
public Character CurrentCharacter { get; set; }
public Character CurrentCharacter { get; set; } = default!;
public Character[] Characters { get; set; } = new Character[4];
/// <summary>
/// 行动指令队列
/// </summary>
public List<ActionCommand> ActionCommandQueue { get; set; } = new List<ActionCommand>();
public List<ActionCommand> ActionCommandQueue { get; set; } = [];
/// <summary>
/// 当前回合数
@@ -38,7 +37,7 @@ public class Duel
/// <summary>
/// 角色牌位置
/// </summary>
public List<Rect> CharacterCardRects { get; set; }
public List<Rect> CharacterCardRects { get; set; } = default!;
/// <summary>
/// 手牌数量
@@ -50,7 +49,7 @@ public class Duel
/// </summary>
public int CurrentDiceCount { get; set; } = 0;
public CancellationTokenSource Cts { get; set; }
public CancellationTokenSource Cts { get; set; } = default!;
private int _keqingECount = 0;
@@ -95,7 +94,7 @@ public class Duel
if (CharacterCardRects is not { Count: 3 })
{
CharacterCardRects = new List<Rect>();
CharacterCardRects = [];
var defaultCharacterCardRects = TaskContext.Instance().Config.AutoGeniusInvokationConfig.DefaultCharacterCardRects;
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
for (var i = 0; i < defaultCharacterCardRects.Count; i++)
@@ -135,7 +134,7 @@ public class Duel
var elementSet = PredictionDiceType();
// 0 投骰子
GeniusInvokationControl.GetInstance().ReRollDice(elementSet.ToArray());
GeniusInvokationControl.GetInstance().ReRollDice([.. elementSet]);
// 等待到我的回合 // 投骰子动画时间是不确定的 // 可能是对方先手
GeniusInvokationControl.GetInstance().WaitForMyTurn(this, 1000);
@@ -429,7 +428,7 @@ public class Duel
/// <returns></returns>
public List<int> GetCharacterSwitchOrder()
{
List<int> orderList = new List<int>();
List<int> orderList = [];
for (var i = 0; i < ActionCommandQueue.Count; i++)
{
if (!orderList.Contains(ActionCommandQueue[i].Character.Index))
@@ -19,83 +19,56 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
public static ElementalType ToElementalType(this string type)
{
type = type.ToLower();
switch (type)
return type switch
{
case "omni":
return ElementalType.Omni;
case "cryo":
return ElementalType.Cryo;
case "hydro":
return ElementalType.Hydro;
case "pyro":
return ElementalType.Pyro;
case "electro":
return ElementalType.Electro;
case "dendro":
return ElementalType.Dendro;
case "anemo":
return ElementalType.Anemo;
case "geo":
return ElementalType.Geo;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
"omni" => ElementalType.Omni,
"cryo" => ElementalType.Cryo,
"hydro" => ElementalType.Hydro,
"pyro" => ElementalType.Pyro,
"electro" => ElementalType.Electro,
"dendro" => ElementalType.Dendro,
"anemo" => ElementalType.Anemo,
"geo" => ElementalType.Geo,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
public static ElementalType ChineseToElementalType(this string type)
{
type = type.ToLower();
switch (type)
return type switch
{
case "全":
return ElementalType.Omni;
case "冰":
return ElementalType.Cryo;
case "水":
return ElementalType.Hydro;
case "火":
return ElementalType.Pyro;
case "雷":
return ElementalType.Electro;
case "草":
return ElementalType.Dendro;
case "风":
return ElementalType.Anemo;
case "岩":
return ElementalType.Geo;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
"全" => ElementalType.Omni,
"冰" => ElementalType.Cryo,
"水" => ElementalType.Hydro,
"火" => ElementalType.Pyro,
"雷" => ElementalType.Electro,
"草" => ElementalType.Dendro,
"风" => ElementalType.Anemo,
"岩" => ElementalType.Geo,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
public static string ToChinese(this ElementalType type)
{
switch (type)
return type switch
{
case ElementalType.Omni:
return "全";
case ElementalType.Cryo:
return "冰";
case ElementalType.Hydro:
return "水";
case ElementalType.Pyro:
return "火";
case ElementalType.Electro:
return "雷";
case ElementalType.Dendro:
return "草";
case ElementalType.Anemo:
return "风";
case ElementalType.Geo:
return "岩";
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
ElementalType.Omni => "全",
ElementalType.Cryo => "冰",
ElementalType.Hydro => "水",
ElementalType.Pyro => "火",
ElementalType.Electro => "雷",
ElementalType.Dendro => "草",
ElementalType.Anemo => "风",
ElementalType.Geo => "岩",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
public static string ToLowerString(this ElementalType type)
{
return type.ToString().ToLower();
}
}
}
}
@@ -13,7 +13,7 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// 元素类型
/// </summary>
public ElementalType Type { get; set; }
/// <summary>
/// 中心点位置
/// </summary>
@@ -6,19 +6,19 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
[Obsolete]
public class RoundStrategy
{
public List<string> RawCommandList { get; set; } = new List<string>();
public List<string> RawCommandList { get; set; } = [];
public List<ActionCommand> ActionCommands { get; set; } = new List<ActionCommand>();
public List<ActionCommand> ActionCommands { get; set; } = [];
public List<ElementalType> MaybeNeedElement(Duel duel)
{
List<ElementalType> result = new List<ElementalType>();
List<ElementalType> result = [];
for (int i = 0; i < ActionCommands.Count; i++)
{
if (ActionCommands[i].Action == ActionEnum.SwitchLater
&& i != ActionCommands.Count-1
&& ActionCommands[i+1].Action == ActionEnum.UseSkill)
if (ActionCommands[i].Action == ActionEnum.SwitchLater
&& i != ActionCommands.Count - 1
&& ActionCommands[i + 1].Action == ActionEnum.UseSkill)
{
result.Add(duel.Characters[ActionCommands[i].TargetIndex].Element);
}
@@ -1,12 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using BetterGenshinImpact.GameTask.AutoFight.Config;
using BetterGenshinImpact.GameTask.AutoFight.Config;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Config;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -16,7 +16,7 @@ public class ScriptParser
public static Duel Parse(string script)
{
var lines = script.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var lines = script.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
var result = new List<string>();
foreach (var line in lines)
{
@@ -29,7 +29,7 @@ public class ScriptParser
public static Duel Parse(List<string> lines)
{
Duel duel = new Duel();
Duel duel = new();
string stage = "";
int i = 0;
@@ -38,7 +38,7 @@ public class ScriptParser
for (i = 0; i < lines.Count; i++)
{
var line = lines[i];
if (line.Contains(":"))
if (line.Contains(':'))
{
stage = line;
continue;
@@ -58,7 +58,7 @@ public class ScriptParser
{
MyAssert(duel.Characters[3] != null, "角色未定义");
string[] actionParts = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string[] actionParts = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
MyAssert(actionParts.Length == 3, "策略中的行动命令解析错误");
MyAssert(actionParts[1] == "使用", "策略中的行动命令解析错误");
@@ -79,7 +79,7 @@ public class ScriptParser
MyAssert(j <= 3, "策略中的行动命令解析错误:角色名称无法从角色定义中匹配到");
int skillNum = int.Parse(Regex.Replace(actionParts[2], @"[^0-9]+", ""));
int skillNum = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(actionParts[2], ""));
MyAssert(skillNum < 5, "策略中的行动命令解析错误:技能编号错误");
actionCommand.TargetIndex = skillNum;
duel.ActionCommandQueue.Add(actionCommand);
@@ -96,7 +96,7 @@ public class ScriptParser
{
MyLogger.LogError($"解析脚本错误,行号:{i + 1},错误信息:{ex}");
MessageBox.Show($"解析脚本错误,行号:{i + 1},错误信息:{ex}", "策略解析失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
return default!;
}
return duel;
@@ -117,14 +117,14 @@ public class ScriptParser
var characterAndSkill = line.Split('{');
var parts = characterAndSkill[0].Split('=');
character.Index = int.Parse(Regex.Replace(parts[0], @"[^0-9]+", ""));
character.Index = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(parts[0], ""));
MyAssert(character.Index >= 1 && character.Index <= 3, "角色序号必须在1-3之间");
if (parts[1].Contains("|"))
if (parts[1].Contains('|'))
{
var nameAndElement = parts[1].Split('|');
character.Name = nameAndElement[0];
character.Element = nameAndElement[1].Substring(0, 1).ChineseToElementalType();
character.Element = nameAndElement[1][..1].ChineseToElementalType();
// 技能
string skillStr = characterAndSkill[1].Replace("}", "");
@@ -136,7 +136,7 @@ public class ScriptParser
skills[skill.Index] = skill;
}
character.Skills = skills.ToArray();
character.Skills = [.. skills];
}
else
{
@@ -172,16 +172,16 @@ public class ScriptParser
{
var skill = new Skill();
var parts = oneSkillStr.Split('=');
skill.Index = short.Parse(Regex.Replace(parts[0], @"[^0-9]+", ""));
skill.Index = short.Parse(RegexHelper.ExcludeNumberRegex().Replace(parts[0], ""));
MyAssert(skill.Index >= 1 && skill.Index <= 5, "技能序号必须在1-5之间");
var costStr = parts[1];
var costParts = costStr.Split('+');
skill.SpecificElementCost = int.Parse(costParts[0].Substring(0, 1));
skill.SpecificElementCost = int.Parse(costParts[0][..1]);
skill.Type = costParts[0].Substring(1, 1).ChineseToElementalType();
// 杂色骰子在+号右边
if (costParts.Length > 1)
{
skill.AnyElementCost = int.Parse(costParts[1].Substring(0, 1));
skill.AnyElementCost = int.Parse(costParts[1][..1]);
}
skill.AllCost = skill.SpecificElementCost + skill.AnyElementCost;
@@ -1,5 +1,5 @@
using System.Threading;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoMusicGame;
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
[Serializable]
public class PathingTask
{
public PathingTaskInfo? Info { get; set; }
public List<Waypoint> Waypoints { get; set; } = [];
}
[Serializable]
public class Waypoint
{
public double X { get; set; }
public double Y { get; set; }
public WaypointType WaypointType { get; set; }
public MoveType MoveType { get; set; }
public ActionType? ActionType { get; set; }
}
public enum WaypointType
{
Transit,
Target,
Teleport,
}
public enum MoveType
{
Walk,
Fly,
Jump,
Swim,
}
public enum ActionType
{
StopFlying,
}
[Serializable]
public class PathingTaskInfo
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
@@ -0,0 +1,52 @@
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Common;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Text;
namespace BetterGenshinImpact.GameTask.AutoPathing;
internal class Navigation
{
internal static Point2f GetPosition()
{
var greyMat = TaskControl.CaptureToRectArea().SrcGreyMat;
greyMat = new Mat(greyMat, new Rect(62, 19, 212, 212));
return EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
}
internal static int GetTargetOrientation(Waypoint waypoint, Point2f position)
{
var target = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
double deltaX = target.x - position.X;
double deltaY = target.y - position.Y;
double vectorLength = Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
if (vectorLength == 0)
{
return 0;
}
// 计算向量与x轴之间的夹角(逆时针方向)
double angle = Math.Acos(deltaX / vectorLength);
// 如果向量在x轴下方,角度需要调整
if (deltaY < 0)
{
angle = 2 * Math.PI - angle;
}
// 将角度转换为顺时针方向
angle = 2 * Math.PI - angle;
return (int)(angle * (180.0 / Math.PI));
}
internal static double GetDistance(Waypoint waypoint, Point2f position)
{
var x1 = waypoint.X;
var y1 = waypoint.Y;
var x2 = position.X;
var y2 = position.Y;
return Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
@@ -0,0 +1,264 @@
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.Common;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask;
using System.Windows.Forms;
using Vanara.PInvoke;
using Microsoft.Extensions.Logging;
using System.Linq;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Core.Simulator;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition.OCR;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.GameTask.AutoPathing;
public class PathExecutor
{
public static async Task Pathing(PathingTask task, CancellationTokenSource cts, bool withDelay = true)
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
}
SystemControl.ActivateWindow();
if (withDelay)
{
for (var i = 3; i >= 1; i--)
{
TaskControl.Logger.LogInformation("{Sec}秒后开始寻路...", i);
await Task.Delay(1000, cts.Token);
}
TaskControl.Logger.LogInformation("开始寻路");
}
if (task.Waypoints.Count == 0)
{
TaskControl.Logger.LogWarning("没有路径点,寻路结束");
return;
}
if (task.Waypoints.First().WaypointType != WaypointType.Teleport)
{
TaskControl.Logger.LogWarning("第一个路径点不是传送点,将不会进行传送");
}
// 这里应该判断一下自动拾取是否处于工作状态,但好像没有什么方便的读取办法
// TODO:大地图传送的时候使用游戏坐标,追踪的时候应该使用2048地图图像坐标,这里临时做转换,后续改进
foreach (var waypoint in task.Waypoints)
{
if (waypoint.WaypointType == WaypointType.Teleport)
{
continue;
}
(waypoint.X, waypoint.Y) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
}
foreach (var waypoint in task.Waypoints)
{
if (waypoint.WaypointType == WaypointType.Teleport)
{
TaskControl.Logger.LogInformation("正在传送到{x},{y}", waypoint.X, waypoint.Y);
await new TpTask(cts).Tp(waypoint.X, waypoint.Y);
continue;
}
// waypoint.WaypointType == WaypointType.Path 或者 WaypointType.Target
// Path不用走得很近,Target需要接近,但都需要先移动到对应位置
await MoveTo(waypoint);
if (waypoint.WaypointType == WaypointType.Target)
{
await MoveCloseTo(waypoint);
}
}
}
internal static async Task MoveTo(Waypoint waypoint)
{
var position = await Task.Run(Navigation.GetPosition);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, Navigation.GetPosition());
TaskControl.Logger.LogInformation("粗略接近路径点,当前位置({x1},{y1}),目标位置({x2},{y2})", position.X, position.Y, waypoint.X, waypoint.Y);
await WaitUntilRotatedTo(targetOrientation, 10);
var startTime = DateTime.UtcNow;
var lastPositionRecord = DateTime.UtcNow;
var fastMode = false;
var prevPositions = new List<Point2f>();
// 按下w,一直走
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
while (true)
{
var now = DateTime.UtcNow;
if ((now - startTime).TotalSeconds > 30)
{
TaskControl.Logger.LogWarning("执行超时,跳过路径点");
break;
}
position = await Task.Run(Navigation.GetPosition);
var distance = Navigation.GetDistance(waypoint, position);
if (distance < 4)
{
TaskControl.Logger.LogInformation("到达路径点附近");
break;
}
if (distance > 500)
{
TaskControl.Logger.LogWarning("距离过远,跳过路径点");
break;
}
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
{
lastPositionRecord = now;
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
var delta = prevPositions[-1] - prevPositions[-8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
{
TaskControl.Logger.LogWarning("疑似卡死,尝试脱离并跳过路径点");
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
await Task.Delay(500);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_S);
await Task.Delay(500);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_A);
await Task.Delay(500);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_D);
await Task.Delay(500);
return;
}
}
}
// 旋转视角
targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
RotateTo(targetOrientation);
// 根据指定方式进行移动
if (waypoint.MoveType == MoveType.Fly)
{
// TODO:一直起跳直到打开风之翼
if (!IsFlying())
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(1000);
}
continue;
}
if (IsFlying())
{
Simulation.SendInput.Mouse.LeftButtonClick();
await Task.Delay(1000);
continue;
}
if (waypoint.MoveType == MoveType.Jump)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(1000);
continue;
}
// 跑步或者游泳
if (distance > 20 != fastMode)// 距离大于20时可以使用疾跑/自由泳
{
if (fastMode)
{
Simulation.SendInput.Mouse.RightButtonUp();
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
await Task.Delay(100);
}
// 抬起w键
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
internal static async Task MoveCloseTo(Waypoint waypoint)
{
var position = await Task.Run(Navigation.GetPosition);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, Navigation.GetPosition());
TaskControl.Logger.LogInformation("精确接近路径点,当前位置({x1},{y1}),目标位置({x2},{y2})", position.X, position.Y, waypoint.X, waypoint.Y);
if (waypoint.MoveType == MoveType.Fly && IsFlying())
{
//下落攻击接近目的地
Simulation.SendInput.Mouse.LeftButtonClick();
await Task.Delay(1000);
}
await WaitUntilRotatedTo(targetOrientation, 2);
var wPressed = false;
var stepsTaken = 0;
while (true)
{
stepsTaken++;
if (stepsTaken > 8)
{
TaskControl.Logger.LogWarning("精确接近超时");
break;
}
position = await Task.Run(Navigation.GetPosition);
if (Navigation.GetDistance(waypoint, position) < 2)
{
TaskControl.Logger.LogInformation("已到达路径点");
break;
}
RotateTo(targetOrientation); //不再改变视角
if (waypoint.MoveType == MoveType.Walk)
{
// 小碎步接近
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_W);
await Task.Delay(500);
continue;
}
if (!wPressed)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
}
await Task.Delay(500);
}
if (wPressed)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
}
internal static int RotateTo(int targetOrientation)
{
var cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcGreyMat);
var diff = (cao - targetOrientation + 180) % 360 - 180;
if (diff == 0)
{
return diff;
}
Simulation.SendInput.Mouse.MoveMouseBy(30 * diff + 10 * diff > 0 ? 1 : -1, 0);
return diff;
}
internal static async Task WaitUntilRotatedTo(int targetOrientation, int maxDiff)
{
int count = 0;
while (Math.Abs(RotateTo(targetOrientation)) > maxDiff && count < 50)
{
await Task.Delay(50);
count++;
}
}
internal static bool IsFlying()
{
var greyMat = TaskControl.CaptureToRectArea().SrcGreyMat;
greyMat = new Mat(greyMat, new Rect(1809, 1025, 61, 28));
var text = OcrFactory.Paddle.OcrWithoutDetector(greyMat);
return text.ToLower() == "space";
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Text;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using BetterGenshinImpact.Core.Config;
using System.IO;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
namespace BetterGenshinImpact.GameTask.AutoPathing;
public class PathRecorder
{
public Model.PathingTask PathingTask { get; set; } = new Model.PathingTask();
public void Start()
{
TaskControl.Logger.LogInformation("开始路径点记录");
var waypoint = new Model.Waypoint();
var position = Navigation.GetPosition();
position = MapCoordinate.Main2048ToGame(position);
waypoint.X = position.X;
waypoint.Y = position.Y;
waypoint.WaypointType = Model.WaypointType.Teleport;
waypoint.MoveType = Model.MoveType.Walk;
PathingTask.Waypoints.Add(waypoint);
TaskControl.Logger.LogInformation("已创建初始路径点({x},{y})", waypoint.X, waypoint.Y);
}
public void AddWaypoint()
{
var waypoint = new Model.Waypoint();
var position = Navigation.GetPosition();
position = MapCoordinate.Main2048ToGame(position);
waypoint.X = position.X;
waypoint.Y = position.Y;
waypoint.WaypointType = Model.WaypointType.Transit;
waypoint.MoveType = Model.MoveType.Walk;
PathingTask.Waypoints.Add(waypoint);
TaskControl.Logger.LogInformation("已添加途径点({x},{y})", waypoint.X, waypoint.Y);
}
public void Save()
{
var json = JsonSerializer.Serialize(PathingTask);
File.WriteAllText(Global.Absolute($@"log\way\{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff}.json"), json);
}
public void Clear() {
PathingTask = new Model.PathingTask();
}
}
@@ -1,7 +1,9 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoPick.Assets;
using BetterGenshinImpact.Helpers;
@@ -14,13 +16,11 @@ using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Recognition;
using Vanara.PInvoke;
using System.Windows.Input;
namespace BetterGenshinImpact.GameTask.AutoPick;
public class AutoPickTrigger : ITaskTrigger
public partial class AutoPickTrigger : ITaskTrigger
{
private readonly ILogger<AutoPickTrigger> _logger = App.GetLogger<AutoPickTrigger>();
private readonly ITextInference _pickTextInference = TextInferenceFactory.Pick;
@@ -35,12 +35,12 @@ public class AutoPickTrigger : ITaskTrigger
/// <summary>
/// 拾取黑名单
/// </summary>
private List<string> _blackList = new();
private List<string> _blackList = [];
/// <summary>
/// 拾取白名单
/// </summary>
private List<string> _whiteList = new();
private List<string> _whiteList = [];
// 自定义拾取按键
private string _pickKeyName = "F";
@@ -48,14 +48,22 @@ public class AutoPickTrigger : ITaskTrigger
private User32.VK _pickVk = User32.VK.VK_F;
private RecognitionObject _pickRo;
// 外部配置
private AutoPickExternalConfig? _externalConfig;
public AutoPickTrigger()
{
_autoPickAssets = AutoPickAssets.Instance;
_pickRo = _autoPickAssets.FRo;
}
public AutoPickTrigger(AutoPickExternalConfig? config) : this()
{
_externalConfig = config;
}
public void Init()
{
_pickRo = _autoPickAssets.FRo;
var keyName = TaskContext.Instance().Config.AutoPickConfig.PickKey;
if (!string.IsNullOrEmpty(keyName))
{
@@ -191,7 +199,7 @@ public class AutoPickTrigger : ITaskTrigger
speedTimer.Record("文字识别");
if (!string.IsNullOrEmpty(text))
{
text = Regex.Replace(text, @"^[\p{P} ]+|[\p{P} ]+$", "");
text = PunctuationAndSpacesRegex().Replace(text, "");
// 唯一一个动态拾取项,特殊处理,不拾取
if (text.Contains("生长时间"))
{
@@ -264,4 +272,7 @@ public class AutoPickTrigger : ITaskTrigger
_lastText = text;
_prevClickFrameIndex = content.FrameIndex;
}
[GeneratedRegex(@"^[\p{P} ]+|[\p{P} ]+$")]
private static partial Regex PunctuationAndSpacesRegex();
}
@@ -1,10 +1,10 @@
using System;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Service;
namespace BetterGenshinImpact.GameTask.AutoSkip.Assets;
@@ -29,7 +29,7 @@ namespace BetterGenshinImpact.GameTask.AutoSkip;
/// <summary>
/// 自动剧情有选项点击
/// </summary>
public class AutoSkipTrigger : ITaskTrigger
public partial class AutoSkipTrigger : ITaskTrigger
{
private readonly ILogger<AutoSkipTrigger> _logger = App.GetLogger<AutoSkipTrigger>();
@@ -47,17 +47,17 @@ public class AutoSkipTrigger : ITaskTrigger
/// <summary>
/// 不自动点击的选项,优先级低于橙色文字点击
/// </summary>
private List<string> _defaultPauseList = new();
private List<string> _defaultPauseList = [];
/// <summary>
/// 不自动点击的选项
/// </summary>
private List<string> _pauseList = new();
private List<string> _pauseList = [];
/// <summary>
/// 优先自动点击的选项
/// </summary>
private List<string> _selectList = new();
private List<string> _selectList = [];
private PostMessageSimulator? _postMessageSimulator;
@@ -78,7 +78,7 @@ public class AutoSkipTrigger : ITaskTrigger
var defaultPauseListJson = Global.ReadAllTextIfExist(@"User\AutoSkip\default_pause_options.json");
if (!string.IsNullOrEmpty(defaultPauseListJson))
{
_defaultPauseList = JsonSerializer.Deserialize<List<string>>(defaultPauseListJson, ConfigService.JsonOptions) ?? new List<string>();
_defaultPauseList = JsonSerializer.Deserialize<List<string>>(defaultPauseListJson, ConfigService.JsonOptions) ?? [];
}
}
catch (Exception e)
@@ -92,7 +92,7 @@ public class AutoSkipTrigger : ITaskTrigger
var pauseListJson = Global.ReadAllTextIfExist(@"User\AutoSkip\pause_options.json");
if (!string.IsNullOrEmpty(pauseListJson))
{
_pauseList = JsonSerializer.Deserialize<List<string>>(pauseListJson, ConfigService.JsonOptions) ?? new List<string>();
_pauseList = JsonSerializer.Deserialize<List<string>>(pauseListJson, ConfigService.JsonOptions) ?? [];
}
}
catch (Exception e)
@@ -106,7 +106,7 @@ public class AutoSkipTrigger : ITaskTrigger
var selectListJson = Global.ReadAllTextIfExist(@"User\AutoSkip\select_options.json");
if (!string.IsNullOrEmpty(selectListJson))
{
_selectList = JsonSerializer.Deserialize<List<string>>(selectListJson, ConfigService.JsonOptions) ?? new List<string>();
_selectList = JsonSerializer.Deserialize<List<string>>(selectListJson, ConfigService.JsonOptions) ?? [];
}
}
catch (Exception e)
@@ -323,38 +323,11 @@ public class AutoSkipTrigger : ITaskTrigger
}
}
/// <summary>
/// 获取橙色选项的文字
/// </summary>
/// <param name="captureMat"></param>
/// <param name="foundIconRectArea"></param>
/// <param name="chatOptionTextWidth"></param>
/// <returns></returns>
[Obsolete]
private string GetOrangeOptionText(Mat captureMat, ImageRegion foundIconRectArea, int chatOptionTextWidth)
{
var textRect = new Rect(foundIconRectArea.X + foundIconRectArea.Width, foundIconRectArea.Y, chatOptionTextWidth, foundIconRectArea.Height);
using var mat = new Mat(captureMat, textRect);
// 只提取橙色
using var bMat = OpenCvCommonHelper.Threshold(mat, new Scalar(247, 198, 50), new Scalar(255, 204, 54));
// Cv2.ImWrite("log/每日委托.png", bMat);
var whiteCount = OpenCvCommonHelper.CountGrayMatColor(bMat, 255);
var rate = whiteCount * 1.0 / (bMat.Width * bMat.Height);
if (rate < 0.06)
{
Debug.WriteLine($"识别到橙色文字区域占比:{rate}");
return string.Empty;
}
var text = OcrFactory.Paddle.Ocr(bMat);
return text;
}
private bool IsOrangeOption(Mat textMat)
{
// 只提取橙色
// Cv2.ImWrite($"log/text{DateTime.Now:yyyyMMddHHmmssffff}.png", textMat);
using var bMat = OpenCvCommonHelper.Threshold(textMat, new Scalar(247, 198, 50), new Scalar(255, 204, 54));
using var bMat = OpenCvCommonHelper.Threshold(textMat, new Scalar(243, 195, 48), new Scalar(255, 205, 55));
var whiteCount = OpenCvCommonHelper.CountGrayMatColor(bMat, 255);
var rate = whiteCount * 1.0 / (bMat.Width * bMat.Height);
Debug.WriteLine($"识别到橙色文字区域占比:{rate}");
@@ -390,7 +363,8 @@ public class AutoSkipTrigger : ITaskTrigger
});
}
private readonly Regex _enOrNumRegex = new(@"^[a-zA-Z0-9]+$");
[GeneratedRegex(@"^[a-zA-Z0-9]+$")]
private static partial Regex EnOrNumRegex();
/// <summary>
/// 新的对话选项选择
@@ -420,7 +394,7 @@ public class AutoSkipTrigger : ITaskTrigger
if (chatOptionResultList.Count > 0)
{
// 第一个元素就是最下面的
chatOptionResultList = chatOptionResultList.OrderByDescending(r => r.Y).ToList();
chatOptionResultList = [.. chatOptionResultList.OrderByDescending(r => r.Y)];
// 通过最下面的气泡框来文字识别
var lowest = chatOptionResultList[0];
@@ -438,11 +412,11 @@ public class AutoSkipTrigger : ITaskTrigger
// 删除为空的结果 和 纯英文的结果
var rs = new List<Region>();
// 按照y坐标排序
ocrResList = ocrResList.OrderBy(r => r.Y).ToList();
ocrResList = [.. ocrResList.OrderBy(r => r.Y)];
for (var i = 0; i < ocrResList.Count; i++)
{
var item = ocrResList[i];
if (string.IsNullOrEmpty(item.Text) || (item.Text.Length < 5 && _enOrNumRegex.IsMatch(item.Text)))
if (string.IsNullOrEmpty(item.Text) || (item.Text.Length < 5 && EnOrNumRegex().IsMatch(item.Text)))
{
continue;
}
@@ -612,6 +586,11 @@ public class AutoSkipTrigger : ITaskTrigger
/// <param name="content"></param>
private void ClosePopupPage(CaptureContent content)
{
if (!_config.ClosePopupPagedEnabled)
{
return;
}
content.CaptureRectArea.Find(_autoSkipAssets.PageCloseRo, pageCloseRoRa =>
{
TaskContext.Instance().PostMessageSimulator.KeyPress(User32.VK.VK_ESCAPE);
@@ -4,25 +4,23 @@ using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.ViewModel.Pages;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using WinRT;
namespace BetterGenshinImpact.GameTask.AutoSkip;
@@ -285,7 +283,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
foreach (var textRa in textRaList)
{
if (textRa.Text.Length < 8 && (textRa.Text.Contains("m") || textRa.Text.Contains("M")))
if (textRa.Text.Length < 8 && textRa.Text.Contains('m', StringComparison.OrdinalIgnoreCase))
{
_missionDistanceRect = textRa.ConvertSelfPositionToGameCaptureRegion();
return StringUtils.TryExtractPositiveInt(textRa.Text);
@@ -4,7 +4,6 @@ using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View.Drawable;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using Sdcb.PaddleOCR;
using System;
using System.Collections.Generic;
@@ -23,7 +22,7 @@ namespace BetterGenshinImpact.GameTask.AutoSkip;
[Obsolete]
public class ExpeditionTask
{
private static readonly List<string> ExpeditionCharacterList = new();
private static readonly List<string> ExpeditionCharacterList = [];
private int _expeditionCount = 0;
@@ -129,12 +128,7 @@ public class ExpeditionTask
var cards = GetCharacterCards(result);
if (cards.Count > 0)
{
var card = cards.FirstOrDefault(c => c.Idle && c.Name != null && ExpeditionCharacterList.Contains(c.Name));
if (card == null)
{
card = cards.First(c => c.Idle);
}
var card = cards.FirstOrDefault(c => c.Idle && c.Name != null && ExpeditionCharacterList.Contains(c.Name)) ?? cards.First(c => c.Idle);
var rect = card.Rects.First();
using var ra = content.CaptureRectArea.Derive(rect);
@@ -158,9 +152,12 @@ public class ExpeditionTask
var captureRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var ocrResultRects = result.Regions.Select(x => x.ToOcrResultRect()).ToList();
ocrResultRects = ocrResultRects.Where(r => r.Rect.X + r.Rect.Width < captureRect.Width / 2)
.OrderBy(r => r.Rect.Y).ThenBy(r => r.Rect.X).ToList();
var ocrResultRects = result.Regions
.Select(x => x.ToOcrResultRect())
.Where(r => r.Rect.X + r.Rect.Width < captureRect.Width / 2)
.OrderBy(r => r.Rect.Y)
.ThenBy(r => r.Rect.X)
.ToList();
var cards = new List<ExpeditionCharacterCard>();
foreach (var ocrResultRect in ocrResultRects)
@@ -1,5 +1,5 @@
using System.Threading;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoSkip.Model;
@@ -12,7 +12,7 @@ public class ExpeditionCharacterCard
public string? Addition { get; set; }
public List<Rect> Rects { get; set; } = new();
public List<Rect> Rects { get; set; } = [];
//public ExpeditionCharacterCard(string name,string addition, bool idle)
//{
@@ -1,5 +1,5 @@
using System.Threading;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -1,16 +1,15 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
@@ -21,15 +20,11 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.Gdi32;
using Point = OpenCvSharp.Point;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -42,11 +37,6 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath;
public class AutoTrackPathTask
{
private readonly AutoTrackPathParam _taskParam;
private readonly Random _rd = new Random();
private readonly List<GiWorldPosition> _tpPositions;
private readonly Dictionary<string, double[]> _countryPositions = MapAssets.Instance.CountryPositions;
private GiPath _way;
@@ -56,7 +46,6 @@ public class AutoTrackPathTask
public AutoTrackPathTask(AutoTrackPathParam taskParam)
{
_taskParam = taskParam;
_tpPositions = MapAssets.Instance.TpPositions;
var wayJson = File.ReadAllText(Global.Absolute(@"log\way\way2.json"));
_way = JsonSerializer.Deserialize<GiPath>(wayJson, ConfigService.JsonOptions) ?? throw new Exception("way json deserialize failed");
@@ -120,18 +109,14 @@ public class AutoTrackPathTask
{
// 1. 传送到最近的传送点
var first = _way.WayPointList[0]; // 解析路线,第一个点为起点
Tp(first.Pt.X, first.Pt.Y);
await new TpTask(_taskParam.Cts).Tp(first.Pt.X, first.Pt.Y);
// 2. 等待传送完成
Sleep(1000);
NewRetry.Do((Action)(() =>
{
var ra = TaskControl.CaptureToRectArea();
var miniMapMat = GetMiniMapMat(ra);
if (miniMapMat == null)
{
throw new RetryException("等待传送完成");
}
var miniMapMat = GetMiniMapMat(ra) ?? throw new RetryException("等待传送完成");
}), TimeSpan.FromSeconds(1), 100);
Logger.LogInformation("传送完成");
Sleep(1000);
@@ -223,23 +208,17 @@ public class AutoTrackPathTask
while (!_taskParam.Cts.IsCancellationRequested)
{
var ra = CaptureToRectArea();
var miniMapMat = GetMiniMapMat(ra);
if (miniMapMat == null)
{
throw new InvalidOperationException("当前不在主界面");
}
var miniMapMat = GetMiniMapMat(ra) ?? throw new InvalidOperationException("当前不在主界面");
// 注意游戏坐标系的角度是顺时针的
var miniMapRect = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(miniMapMat);
if (miniMapRect == Rect.Empty)
var currMapImageAvatarPos = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(miniMapMat);
if (currMapImageAvatarPos.IsEmpty())
{
Debug.WriteLine("识别小地图位置失败");
continue;
}
var currMapImageAvatarPos = miniMapRect.GetCenterPoint();
var (nextMapImagePathPoint, nextPointIndex) = GetNextPoint(currMapImageAvatarPos, pList, currIndex); // 动态计算下个点位
var nextMapImagePathPos = nextMapImagePathPoint.MatchRect.GetCenterPoint();
var nextMapImagePathPos = nextMapImagePathPoint.MatchPt;
Logger.LogInformation("下个点位[{Index}]:{nextMapImagePathPos}", nextPointIndex, nextMapImagePathPos);
var angle = CharacterOrientation.Compute(miniMapMat);
@@ -299,7 +278,7 @@ public class AutoTrackPathTask
/// <param name="pList"></param>
/// <param name="currIndex"></param>
/// <returns></returns>
public (GiPathPoint, int) GetNextPoint(Point currPoint, List<GiPathPoint> pList, int currIndex)
public (GiPathPoint, int) GetNextPoint(Point2f currPoint, List<GiPathPoint> pList, int currIndex)
{
var nextNum = Math.Min(currIndex + 20, pList.Count - 1); // 最多找最近20个点
var minDistance = double.MaxValue;
@@ -311,7 +290,7 @@ public class AutoTrackPathTask
for (var i = currIndex; i < nextNum; i++)
{
var nextPoint = pList[i + 1];
var nextMapImagePos = nextPoint.MatchRect.GetCenterPoint();
var nextMapImagePos = nextPoint.MatchPt;
var distance = MathHelper.Distance(nextMapImagePos, currPoint);
if (distance < minDistance)
{
@@ -363,238 +342,10 @@ public class AutoTrackPathTask
public int GetCharacterOrientationAngle()
{
var ra = CaptureToRectArea();
var miniMapMat = GetMiniMapMat(ra);
if (miniMapMat == null)
{
throw new InvalidOperationException("当前不在主界面");
}
var miniMapMat = GetMiniMapMat(ra) ?? throw new InvalidOperationException("当前不在主界面");
var angle = CharacterOrientation.Compute(miniMapMat);
Logger.LogInformation("当前角度:{Angle}", angle);
// CameraOrientation.DrawDirection(ra, angle);
return angle;
}
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
/// </summary>
/// <param name="tpX"></param>
/// <param name="tpY"></param>
public void Tp(double tpX, double tpY)
{
// 获取最近的传送点位置
var (x, y) = GetRecentlyTpPoint(tpX, tpY);
Logger.LogInformation("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", tpX, tpY, x, y);
// M 打开地图识别当前位置,中心点为当前位置
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
Sleep(1000);
// 计算传送点位置离哪个地图切换后的中心点最近,切换到该地图
SwitchRecentlyCountryMap(x, y);
// 移动地图到指定传送点位置
// Debug.WriteLine("移动地图到指定传送点位置");
// MoveMapTo(x, y);
// 计算坐标后点击
var bigMapInAllMapRect = GetBigMapRect();
while (!bigMapInAllMapRect.Contains((int)x, (int)y))
{
Debug.WriteLine($"({x},{y}) 不在 {bigMapInAllMapRect} 内,继续移动");
Logger.LogInformation("传送点不在当前大地图范围内,继续移动");
MoveMapTo(x, y);
bigMapInAllMapRect = GetBigMapRect();
}
// Debug.WriteLine($"({x},{y}) 在 {bigMapInAllMapRect} 内,计算它在窗体内的位置");
// 注意这个坐标的原点是中心区域某个点,所以要转换一下点击坐标(点击坐标是左上角为原点的坐标系),不能只是缩放
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var clickX = (int)((picX - picRect.X) / picRect.Width * captureRect.Width);
var clickY = (int)((picY - picRect.Y) / picRect.Height * captureRect.Height);
Logger.LogInformation("点击传送点:({X},{Y})", clickX, clickY);
using var ra = CaptureToRectArea();
ra.ClickTo(clickX, clickY);
// 触发一次快速传送功能
}
/// <summary>
/// 移动地图到指定传送点位置
/// 可能会移动不对,所以可以重试此方法
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void MoveMapTo(double x, double y)
{
var bigMapCenterPoint = GetPositionFromBigMap();
// 移动部分内容测试移动偏移
var (xOffset, yOffset) = (x - bigMapCenterPoint.X, y - bigMapCenterPoint.Y);
var diffMouseX = 100; // 每次移动的距离
if (xOffset < 0)
{
diffMouseX = -diffMouseX;
}
var diffMouseY = 100; // 每次移动的距离
if (yOffset < 0)
{
diffMouseY = -diffMouseY;
}
// 先移动到屏幕中心附近随机点位置,避免地图移动无效
MouseMoveMapX(diffMouseX);
MouseMoveMapY(diffMouseY);
var newBigMapCenterPoint = GetPositionFromBigMap();
var diffMapX = Math.Abs(newBigMapCenterPoint.X - bigMapCenterPoint.X);
var diffMapY = Math.Abs(newBigMapCenterPoint.Y - bigMapCenterPoint.Y);
Debug.WriteLine($"每100移动的地图距离:({diffMapX},{diffMapY})");
// 快速移动到目标传送点所在的区域
if (diffMapX > 10 && diffMapY > 10)
{
// // 计算需要移动的次数
var moveCount = (int)Math.Abs(xOffset / diffMapX); // 向下取整 本来还要加1的,但是已经移动了一次了
Debug.WriteLine("X需要移动的次数:" + moveCount);
for (var i = 0; i < moveCount; i++)
{
MouseMoveMapX(diffMouseX);
}
moveCount = (int)Math.Abs(yOffset / diffMapY); // 向下取整 本来还要加1的,但是已经移动了一次了
Debug.WriteLine("Y需要移动的次数:" + moveCount);
for (var i = 0; i < moveCount; i++)
{
MouseMoveMapY(diffMouseY);
}
}
}
public void MouseMoveMapX(int dx)
{
var moveUnit = dx > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(200);
for (var i = 0; i < dx / moveUnit; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy(moveUnit, 0).Sleep(60); // 60 保证没有惯性
}
Simulation.SendInput.Mouse.LeftButtonUp().Sleep(200);
}
public void MouseMoveMapY(int dy)
{
var moveUnit = dy > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(200);
// 原神地图在小范围内移动是无效的,所以先随便移动一下,所以肯定少移动一次
for (var i = 0; i < dy / moveUnit; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy(0, moveUnit).Sleep(60);
}
Simulation.SendInput.Mouse.LeftButtonUp().Sleep(200);
}
public static Point GetPositionFromBigMap()
{
var bigMapRect = GetBigMapRect();
Debug.WriteLine("地图位置转换到游戏坐标:" + bigMapRect);
var bigMapCenterPoint = bigMapRect.GetCenterPoint();
Debug.WriteLine("地图中心坐标:" + bigMapCenterPoint);
return bigMapCenterPoint;
}
public static Rect GetBigMapRect()
{
// 判断是否在地图界面
using var ra = CaptureToRectArea();
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
var rect = BigMap.Instance.GetBigMapPositionByFeatureMatch(ra.SrcGreyMat);
Debug.WriteLine("识别大地图在全地图位置矩形:" + rect);
const int s = 4 * 2; // 相对1024做4倍缩放
return MapCoordinate.Main2048ToGame(new Rect(rect.X * s, rect.Y * s, rect.Width * s, rect.Height * s));
}
else
{
throw new InvalidOperationException("当前不在地图界面");
}
}
/// <summary>
/// 获取最近的传送点位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public (int x, int y) GetRecentlyTpPoint(double x, double y)
{
var recentX = 0;
var recentY = 0;
var minDistance = double.MaxValue;
foreach (var tpPosition in _tpPositions)
{
var distance = Math.Sqrt(Math.Pow(tpPosition.X - x, 2) + Math.Pow(tpPosition.Y - y, 2));
if (distance < minDistance)
{
minDistance = distance;
recentX = (int)Math.Round(tpPosition.X);
recentY = (int)Math.Round(tpPosition.Y);
}
}
return (recentX, recentY);
}
public void SwitchRecentlyCountryMap(double x, double y)
{
var bigMapCenterPoint = GetPositionFromBigMap();
Logger.LogInformation("识别当前位置:{Pos}", bigMapCenterPoint);
var minDistance = Math.Sqrt(Math.Pow(bigMapCenterPoint.X - x, 2) + Math.Pow(bigMapCenterPoint.Y - y, 2));
var minCountry = "当前位置";
foreach (var (country, position) in _countryPositions)
{
var distance = Math.Sqrt(Math.Pow(position[0] - x, 2) + Math.Pow(position[1] - y, 2));
if (distance < minDistance)
{
minDistance = distance;
minCountry = country;
}
}
Logger.LogInformation("离目标传送点最近的区域是:{Country}", minCountry);
if (minCountry != "当前位置")
{
GameCaptureRegion.GameRegionClick((rect, scale) => (rect.Width - 160 * scale, rect.Height - 60 * scale));
Sleep(200, _taskParam.Cts);
var ra = CaptureToRectArea();
var list = ra.FindMulti(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect(ra.Width / 2, 0, ra.Width / 2, ra.Height)
});
list.FirstOrDefault(r => r.Text.Contains(minCountry))?.Click();
Logger.LogInformation("切换到区域:{Country}", minCountry);
Sleep(500, _taskParam.Cts);
}
}
public void Tp(string name)
{
// 通过大地图传送到指定传送点
}
public void TpByF1(string name)
{
// 传送到指定传送点
}
}
@@ -1,28 +1,20 @@
using System;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
[Serializable]
public class GiPath
{
public List<GiPathPoint> WayPointList { get; set; } = new();
public List<GiPathPoint> WayPointList { get; set; } = [];
public void AddPoint(Rect matchRect)
public void AddPoint(Point2f point)
{
// 长宽比例大于 1.5 的矩形不加入
var r = matchRect.Width / (double)matchRect.Height;
if (r is > 1.5 or < 0.66)
{
Debug.WriteLine($"长宽比例不符合要求: {r}");
return;
}
// 离上个点距离小于 10 的矩形不加入
var giPathPoint = GiPathPoint.BuildFrom(matchRect, WayPointList.Count);
var giPathPoint = GiPathPoint.BuildFrom(point, WayPointList.Count);
if (WayPointList.Count > 0)
{
var lastPoint = WayPointList[^1];
@@ -1,7 +1,6 @@
using System;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Common.Map;
using OpenCvSharp;
using System;
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
@@ -12,9 +11,9 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
[Serializable]
public class GiPathPoint
{
public Point Pt { get; set; }
public Point2f Pt { get; set; }
public Rect MatchRect { get; set; }
public Point2f MatchPt { get; set; }
public int Index { get; set; }
@@ -22,13 +21,13 @@ public class GiPathPoint
public string Type { get; set; } = GiPathPointType.Normal.ToString();
public static GiPathPoint BuildFrom(Rect matchRect, int index)
public static GiPathPoint BuildFrom(Point2f point, int index)
{
var pt = MapCoordinate.Main2048ToGame(matchRect.GetCenterPoint());
var pt = MapCoordinate.Main2048ToGame(point);
return new GiPathPoint
{
Pt = pt,
MatchRect = matchRect,
MatchPt = point,
Index = index,
Time = DateTime.Now
};
@@ -1,20 +1,21 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -78,11 +79,11 @@ public class PathPointRecorder : Singleton<PathPointRecorder>
continue;
}
var rect = _bigMap.GetMiniMapPositionByFeatureMatch(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
if (rect != Rect.Empty)
var p2 = _bigMap.GetMiniMapPositionByFeatureMatch(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
if (!p2.IsEmpty())
{
way.AddPoint(rect);
Debug.WriteLine($"AddPoint: {rect}");
way.AddPoint(p2);
Debug.WriteLine($"AddPoint: {p2}");
}
else
{
@@ -1,10 +1,12 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
@@ -12,7 +14,6 @@ using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -23,14 +24,7 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath;
/// </summary>
public class TpTask(CancellationTokenSource cts)
{
private static readonly Random _rd = new Random();
public static async void Test()
{
await new TaskRunner().RunAsync(async () =>
await new TpTask(new CancellationTokenSource())
.Tp(1, 1));
}
private readonly QuickTeleportAssets _assets = QuickTeleportAssets.Instance;
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
@@ -77,6 +71,21 @@ public class TpTask(CancellationTokenSource cts)
ra.ClickTo(clickX, clickY);
// 触发一次快速传送功能
await Delay(500, cts);
await ClickTpPoint(CaptureToRectArea());
// 等待传送完成
for (var i = 0; i < 20; i++)
{
await Delay(1200, cts);
using var ra3 = CaptureToRectArea();
if (Bv.IsInMainUi(ra3))
{
break;
}
}
Logger.LogInformation("传送完成");
}
/// <summary>
@@ -134,7 +143,7 @@ public class TpTask(CancellationTokenSource cts)
public async Task MouseMoveMapX(int dx)
{
var moveUnit = dx > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + Random.Shared.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + Random.Shared.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown();
await Delay(200, cts);
for (var i = 0; i < dx / moveUnit; i++)
@@ -149,7 +158,7 @@ public class TpTask(CancellationTokenSource cts)
public async Task MouseMoveMapY(int dy)
{
var moveUnit = dy > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + Random.Shared.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + Random.Shared.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown();
await Delay(200, cts);
// 原神地图在小范围内移动是无效的,所以先随便移动一下,所以肯定少移动一次
@@ -162,13 +171,9 @@ public class TpTask(CancellationTokenSource cts)
await Delay(200, cts);
}
public Point GetPositionFromBigMap()
public Point2f GetPositionFromBigMap()
{
var bigMapRect = GetBigMapRect();
Debug.WriteLine("地图位置转换到游戏坐标:" + bigMapRect);
var bigMapCenterPoint = bigMapRect.GetCenterPoint();
Debug.WriteLine("地图中心坐标:" + bigMapCenterPoint);
return bigMapCenterPoint;
return GetBigMapCenterPoint();
}
public Rect GetBigMapRect()
@@ -178,13 +183,14 @@ public class TpTask(CancellationTokenSource cts)
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
var rect = BigMap.Instance.GetBigMapPositionByFeatureMatch(ra.SrcGreyMat);
var rect = BigMap.Instance.GetBigMapRectByFeatureMatch(ra.SrcGreyMat);
if (rect == Rect.Empty)
{
throw new InvalidOperationException("识别大地图位置失败");
}
Debug.WriteLine("识别大地图在全地图位置矩形:" + rect);
const int s = 4 * 2; // 相对1024做4倍缩放
const int s = BigMap.ScaleTo2048; // 相对1024做4倍缩放
return MapCoordinate.Main2048ToGame(new Rect(rect.X * s, rect.Y * s, rect.Width * s, rect.Height * s));
}
else
@@ -193,16 +199,38 @@ public class TpTask(CancellationTokenSource cts)
}
}
public Point2f GetBigMapCenterPoint()
{
// 判断是否在地图界面
using var ra = CaptureToRectArea();
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
var p = BigMap.Instance.GetBigMapPositionByFeatureMatch(ra.SrcGreyMat);
if (p.IsEmpty())
{
throw new InvalidOperationException("识别大地图位置失败");
}
Debug.WriteLine("识别大地图在全地图位置:" + p);
return MapCoordinate.Main2048ToGame(new Point2f(BigMap.ScaleTo2048 * p.X, BigMap.ScaleTo2048 * p.Y));
}
else
{
throw new InvalidOperationException("当前不在地图界面");
}
}
/// <summary>
/// 获取最近的传送点位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public (int x, int y) GetRecentlyTpPoint(double x, double y)
public (double x, double y) GetRecentlyTpPoint(double x, double y)
{
var recentX = 0;
var recentY = 0;
double recentX = 0;
double recentY = 0;
var minDistance = double.MaxValue;
foreach (var tpPosition in MapAssets.Instance.TpPositions)
{
@@ -210,16 +238,25 @@ public class TpTask(CancellationTokenSource cts)
if (distance < minDistance)
{
minDistance = distance;
recentX = (int)Math.Round(tpPosition.X);
recentY = (int)Math.Round(tpPosition.Y);
recentX = tpPosition.X;
recentY = tpPosition.Y;
}
}
return (recentX, recentY);
}
public async Task SwitchRecentlyCountryMap(double x, double y)
public async Task<bool> SwitchRecentlyCountryMap(double x, double y)
{
// 可能是地下地图,切换到地上地图
using var ra2 = CaptureToRectArea();
if (Bv.BigMapIsUnderground(ra2))
{
ra2.Find(_assets.MapUndergroundToGroundButtonRo).Click();
await Delay(200, cts);
}
// 识别当前位置
var bigMapCenterPoint = GetPositionFromBigMap();
Logger.LogInformation("识别当前位置:{Pos}", bigMapCenterPoint);
@@ -249,7 +286,10 @@ public class TpTask(CancellationTokenSource cts)
list.FirstOrDefault(r => r.Text.Length == minCountry.Length && !r.Text.Contains("委托") && r.Text.Contains(minCountry))?.Click();
Logger.LogInformation("切换到区域:{Country}", minCountry);
await Delay(500, cts);
return true;
}
return false;
}
public async Task Tp(string name)
@@ -261,4 +301,93 @@ public class TpTask(CancellationTokenSource cts)
{
// 传送到指定传送点
}
public async Task ClickTpPoint(ImageRegion imageRegion)
{
// 1.判断是否在地图界面
if (Bv.IsInBigMapUi(imageRegion))
{
// 2. 判断是否有传送按钮
var hasTeleportButton = CheckTeleportButton(imageRegion);
if (!hasTeleportButton)
{
// 存在地图关闭按钮,说明未选中传送点,直接返回
var mapCloseRa = imageRegion.Find(_assets.MapCloseButtonRo);
if (!mapCloseRa.IsEmpty())
{
return;
}
// 存在地图选择按钮,说明未选中传送点,直接返回
var mapChooseRa = imageRegion.Find(_assets.MapChooseRo);
if (!mapChooseRa.IsEmpty())
{
return;
}
// 3. 循环判断选项列表是否有传送点
var hasMapChooseIcon = CheckMapChooseIcon(imageRegion);
if (hasMapChooseIcon)
{
await Delay(TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay, cts);
CheckTeleportButton(CaptureToRectArea());
}
}
}
}
private bool CheckTeleportButton(ImageRegion imageRegion)
{
var hasTeleportButton = false;
imageRegion.Find(_assets.TeleportButtonRo, ra =>
{
ra.Click();
hasTeleportButton = true;
});
return hasTeleportButton;
}
/// <summary>
/// 全匹配一遍并进行文字识别
/// 60ms ~200ms
/// </summary>
/// <param name="imageRegion"></param>
/// <returns></returns>
private bool CheckMapChooseIcon(ImageRegion imageRegion)
{
var hasMapChooseIcon = false;
// 全匹配一遍
var rResultList = MatchTemplateHelper.MatchMultiPicForOnePic(imageRegion.SrcGreyMat[_assets.MapChooseIconRoi], _assets.MapChooseIconGreyMatList);
// 按高度排序
if (rResultList.Count > 0)
{
rResultList = [.. rResultList.OrderBy(x => x.Y)];
// 点击最高的
foreach (var iconRect in rResultList)
{
// 200宽度的文字区域
using var ra = imageRegion.DeriveCrop(_assets.MapChooseIconRoi.X + iconRect.X + iconRect.Width, _assets.MapChooseIconRoi.Y + iconRect.Y, 200, iconRect.Height);
using var textRegion = ra.Find(new RecognitionObject
{
RecognitionType = RecognitionTypes.ColorRangeAndOcr,
LowerColor = new Scalar(249, 249, 249), // 只取白色文字
UpperColor = new Scalar(255, 255, 255),
});
if (string.IsNullOrEmpty(textRegion.Text) || textRegion.Text.Length == 1)
{
continue;
}
Logger.LogInformation("传送:点击 {Option}", textRegion.Text);
Thread.Sleep(TaskContext.Instance().Config.QuickTeleportConfig.TeleportListClickDelay);
ra.Click();
hasMapChooseIcon = true;
break;
}
}
return hasMapChooseIcon;
}
}
@@ -16,7 +16,7 @@ public class AutoWoodAssets : BaseAssets<AutoWoodAssets>
// 木头数量
public Rect WoodCountUpperRect;
private AutoWoodAssets()
{
@@ -151,8 +151,8 @@ public partial class AutoWoodTask
private bool _firstWoodOcr = true;
private string _firstWoodOcrText = "";
private readonly Dictionary<string, int> _woodMetricsDict = new();
private readonly Dictionary<string, bool> _woodNotPrintDict = new();
private readonly Dictionary<string, int> _woodMetricsDict = [];
private readonly Dictionary<string, bool> _woodNotPrintDict = [];
// from:https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=13
private static readonly List<string> ExistWoods =
@@ -424,8 +424,8 @@ public partial class AutoWoodTask
#if !TEST_WITHOUT_Z_ITEM
throw new NormalEndException("请先装备小道具「王树瑞佑」!");
#else
Thread.Sleep(2000);
Simulation.SendInputEx.Keyboard.KeyPress(_zKey);
System.Threading.Thread.Sleep(2000);
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Debug.WriteLine("[AutoWood] Z");
_first = false;
#endif
@@ -449,7 +449,7 @@ public partial class AutoWoodTask
#if !TEST_WITHOUT_Z_ITEM
throw new RetryException("未找到「王树瑞佑」");
#else
Thread.Sleep(15000);
System.Threading.Thread.Sleep(15000);
#endif
}
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more