Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe2fd5d67c | ||
|
|
08fbd6e2a2 | ||
|
|
e1f3b01eb1 | ||
|
|
0973ca0887 | ||
|
|
be4039a77a | ||
|
|
684fac7d29 | ||
|
|
5c6a96957e | ||
|
|
56477f3490 | ||
|
|
95757a5ed6 | ||
|
|
c4eae50716 | ||
|
|
6da76f4ef7 | ||
|
|
443f79bde3 | ||
|
|
57e24c8e33 | ||
|
|
edff49c9cb | ||
|
|
594b517936 | ||
|
|
5f35d483c2 | ||
|
|
b8e5c179fc | ||
|
|
c5d9930a3d | ||
|
|
a84c94c5ce | ||
|
|
a801bb2c4f | ||
|
|
cb106db75f | ||
|
|
772ab1b7e6 | ||
|
|
92be667328 | ||
|
|
cb75cf8338 | ||
|
|
4bf5001a2c | ||
|
|
6ffe7a670c | ||
|
|
54b669de90 | ||
|
|
65acb852f3 | ||
|
|
c014284b84 | ||
|
|
cf16969ea0 | ||
|
|
89e505f4a5 | ||
|
|
c686c4a4a6 | ||
|
|
3cc313c204 | ||
|
|
9e3d16c819 | ||
|
|
8513c9ed4f | ||
|
|
bb3941d9f5 | ||
|
|
66d1791218 | ||
|
|
27e6de0fbf | ||
|
|
cb9dc4ca2e | ||
|
|
cc16a60896 | ||
|
|
3792a5f0bf | ||
|
|
fec0e8ec39 | ||
|
|
bd4223ddaa | ||
|
|
3a35d537b6 | ||
|
|
87a39c95eb | ||
|
|
fb1eeed107 | ||
|
|
cfe9fc6389 | ||
|
|
9378a134bd | ||
|
|
c27b5176e7 | ||
|
|
85e0c827ca | ||
|
|
790c30183b | ||
|
|
6f67bea46c | ||
|
|
f8ad1bd8e3 | ||
|
|
8fe59842c6 | ||
|
|
ee154da3c3 | ||
|
|
9886e7eeff | ||
|
|
5797c716dc | ||
|
|
dabdfa51f4 | ||
|
|
9ab884512a | ||
|
|
24590d125e | ||
|
|
118307c562 | ||
|
|
7096b9ed9e | ||
|
|
85932c1040 | ||
|
|
d90376461c | ||
|
|
c544c18b07 | ||
|
|
a7fcce36b6 | ||
|
|
e7ef9dcd2f | ||
|
|
80b6e36d9a | ||
|
|
e6c7abb074 | ||
|
|
bcec9cfc6b | ||
|
|
bea434a3bb | ||
|
|
e250498c57 | ||
|
|
0e6e94c1e9 | ||
|
|
87345e6225 | ||
|
|
992d1a2e9e | ||
|
|
87cb044947 | ||
|
|
667043594c | ||
|
|
1f6d4a3346 | ||
|
|
b1e33a6339 | ||
|
|
7953a76b3d | ||
|
|
f1c82f83b0 | ||
|
|
98b744f33f | ||
|
|
9e01dbd88c | ||
|
|
be99fb3605 | ||
|
|
6bf73adce2 | ||
|
|
6b98424603 | ||
|
|
d3f934b1fa | ||
|
|
31db69b20b | ||
|
|
8acf23e9ce | ||
|
|
191786962a | ||
|
|
cf8ab82043 | ||
|
|
a553dc2402 | ||
|
|
8bf6a39177 | ||
|
|
06f77a2d5f | ||
|
|
7dadf9b9f9 | ||
|
|
25ed398524 | ||
|
|
912d86ac33 | ||
|
|
4fa718c6e0 | ||
|
|
c2d3e132e8 | ||
|
|
f0bfdde4b8 | ||
|
|
10d09afb98 | ||
|
|
6761b7d72f | ||
|
|
239ab3384c | ||
|
|
e8a781f040 | ||
|
|
b60784b8df | ||
|
|
18c1e9f978 | ||
|
|
45b5653b13 | ||
|
|
c561da1892 | ||
|
|
4e7da7156e | ||
|
|
e7e238e099 | ||
|
|
59b5656719 | ||
|
|
fe03913020 | ||
|
|
a45b34378c | ||
|
|
c27150d4d3 | ||
|
|
e0ea024631 | ||
|
|
7dda27c59b | ||
|
|
8513d31f13 | ||
|
|
6dc81e181c | ||
|
|
df01527d98 | ||
|
|
fcdf1c4873 | ||
|
|
116a4c8790 | ||
|
|
f64e2f37c9 | ||
|
|
25e640bff1 | ||
|
|
d917720c9e | ||
|
|
7756c3af9c | ||
|
|
643a5b0262 | ||
|
|
4354ca5900 | ||
|
|
27ff3e649b | ||
|
|
e151229eff | ||
|
|
f10694a476 | ||
|
|
a458b86fab | ||
|
|
820cd8949d | ||
|
|
a983ed45ce | ||
|
|
f2908509a4 | ||
|
|
dc389f95b9 | ||
|
|
19c441b8c6 | ||
|
|
a0f94babe8 | ||
|
|
f1ac26155a | ||
|
|
df2926fe95 | ||
|
|
cbca6cfcfe | ||
|
|
aa0fedf808 | ||
|
|
f8f4332abd | ||
|
|
ad606dd29c | ||
|
|
55aa735c3b | ||
|
|
4819849902 | ||
|
|
b8f812c551 | ||
|
|
1060b819ff | ||
|
|
c3ea13715a | ||
|
|
d070f45a0a | ||
|
|
d0405d0800 | ||
|
|
36dcbebdfa | ||
|
|
ed63a68ee5 | ||
|
|
f14d4a4d10 | ||
|
|
edbc860a3d | ||
|
|
d69242f7c2 | ||
|
|
034d695bf8 | ||
|
|
4b41fdcecc | ||
|
|
0453355b8a | ||
|
|
e408750d09 | ||
|
|
8affeff26f | ||
|
|
3b6d5f936f | ||
|
|
9c5bc866f8 | ||
|
|
e744aba880 | ||
|
|
962d00e90d | ||
|
|
94a049e066 | ||
|
|
bdc99e9e06 | ||
|
|
f41cbcdab4 | ||
|
|
7300d32756 | ||
|
|
531ca76cfd | ||
|
|
3df5904d2c | ||
|
|
85b253036c | ||
|
|
2b455ad2fc | ||
|
|
5187001b31 | ||
|
|
314d5b6e9e | ||
|
|
f87500245d | ||
|
|
45f2b9b459 | ||
|
|
09e23cab57 | ||
|
|
24713a47e1 | ||
|
|
a890fa1aca | ||
|
|
32a6507027 | ||
|
|
3f471c68da | ||
|
|
3d4ae6cb06 | ||
|
|
0bfaa0daf2 | ||
|
|
a9ff321daf | ||
|
|
97f2dc4550 | ||
|
|
63bec641af | ||
|
|
04ce508efd | ||
|
|
7e5b7eb1d4 | ||
|
|
4f9424ff3d | ||
|
|
8c025feaba | ||
|
|
083766320d | ||
|
|
a11d31bd62 | ||
|
|
7781ca1271 | ||
|
|
4864d32f8c | ||
|
|
911ee49083 | ||
|
|
4755213ccc | ||
|
|
e62516c9ce | ||
|
|
3973a132b4 | ||
|
|
992e1ac3eb | ||
|
|
94da864852 | ||
|
|
675d3cdb50 | ||
|
|
417dafa456 | ||
|
|
1c97b425f4 | ||
|
|
fdd48f4f62 | ||
|
|
282b7358a0 | ||
|
|
2a7f5265a3 | ||
|
|
43766c6d93 | ||
|
|
087956b161 | ||
|
|
fa9157880f | ||
|
|
c1fce8a3eb | ||
|
|
19e37a35bc | ||
|
|
3385692de3 | ||
|
|
30ec2a55ad | ||
|
|
2448b5b6b0 | ||
|
|
f6e2694204 | ||
|
|
a36c283784 | ||
|
|
741deafd3f | ||
|
|
39e552d9fe | ||
|
|
919d4c5083 | ||
|
|
1d645b1565 | ||
|
|
0d6ad22a22 | ||
|
|
29e679d1fd | ||
|
|
037d4dadff | ||
|
|
62492b3f95 | ||
|
|
11c13c6fdd | ||
|
|
6ba56fe6e2 | ||
|
|
eb0a886784 | ||
|
|
016c94e06c | ||
|
|
8a450d9edd | ||
|
|
bb0ea6622b | ||
|
|
ede7751ebf | ||
|
|
7b721ee13c | ||
|
|
c9851552e4 | ||
|
|
e74422a219 | ||
|
|
77496332bf | ||
|
|
c7df940f13 | ||
|
|
ecaa8c15fb | ||
|
|
3b4c993aab | ||
|
|
b98097e8e6 | ||
|
|
22ea2c2576 | ||
|
|
5b1fe0e2d0 | ||
|
|
ce89e41b60 | ||
|
|
24c4a021cb | ||
|
|
8415daa740 | ||
|
|
ffac1859dc | ||
|
|
ca418ba7b1 | ||
|
|
a1475732af | ||
|
|
006c7a71cc | ||
|
|
5df1eac561 | ||
|
|
8f7cd481f2 | ||
|
|
c664eca7da | ||
|
|
4554769f38 | ||
|
|
3133478fca | ||
|
|
89b85e0bfd | ||
|
|
961e73880b | ||
|
|
920ea6333b | ||
|
|
fb8ee063bc | ||
|
|
60117666a7 | ||
|
|
fd47761f7f | ||
|
|
7d69c2ca7f | ||
|
|
007efdbf1a | ||
|
|
31d7e4c94b | ||
|
|
7590f6a273 | ||
|
|
ccadc11b2b | ||
|
|
c150e6a280 | ||
|
|
4e92f7f2c6 | ||
|
|
c0f34b6c87 | ||
|
|
6b4de6da19 | ||
|
|
b63f95b9c0 | ||
|
|
7fcfdbd3bf | ||
|
|
6f8cfbee4f | ||
|
|
fd79acaee6 | ||
|
|
fecc95230f | ||
|
|
cc181ebd16 | ||
|
|
9c1c283576 | ||
|
|
373b2fe61c | ||
|
|
da353a9472 | ||
|
|
c5f81dd447 | ||
|
|
591007eff6 | ||
|
|
ef8f51d8e1 | ||
|
|
cc37788495 | ||
|
|
9c29156584 | ||
|
|
ca00c3dfd7 | ||
|
|
dd4d8ae2c2 | ||
|
|
f9e9be6d9d | ||
|
|
fbc5a3ced9 | ||
|
|
cb395deef9 | ||
|
|
36aa0270f6 | ||
|
|
e3546e9b80 | ||
|
|
bd366503cf | ||
|
|
9d6d621b75 | ||
|
|
eac6957185 | ||
|
|
0ec20aa86c | ||
|
|
be291d4093 | ||
|
|
0b2541ac3a | ||
|
|
fe9b028bb2 | ||
|
|
aa9f1cb8d9 | ||
|
|
06a46533d0 | ||
|
|
9cc647196c | ||
|
|
b9ea59cc04 | ||
|
|
cb52ddc78b | ||
|
|
aedcb3dde5 | ||
|
|
7660e58452 | ||
|
|
2d6b399a07 | ||
|
|
a2255f8250 | ||
|
|
15a4dbd624 | ||
|
|
3fc3935519 | ||
|
|
1c345eae16 | ||
|
|
c1018bf3fd | ||
|
|
d67e5e5635 | ||
|
|
16a256dbe0 | ||
|
|
ad6d70f75e | ||
|
|
6bb49eb243 | ||
|
|
a9a02c7e9c | ||
|
|
92c30bec11 | ||
|
|
8e700d271e | ||
|
|
a4d4aef130 | ||
|
|
78364c5fa7 | ||
|
|
3628bd1904 | ||
|
|
54ee6e2ad1 | ||
|
|
7ac890e43f | ||
|
|
82ce255617 | ||
|
|
4dc286c8e9 | ||
|
|
9162e5970c | ||
|
|
2f96f7b312 | ||
|
|
0846949823 | ||
|
|
9bab2a0c0c | ||
|
|
afdb8e488d | ||
|
|
387711c413 | ||
|
|
ae4eb6a7f4 | ||
|
|
c714c73975 | ||
|
|
2789b2edb2 | ||
|
|
c32508f0a9 | ||
|
|
215bd3e81f | ||
|
|
149f964350 | ||
|
|
85f87b02aa | ||
|
|
47eb6ae392 | ||
|
|
4f578e293b | ||
|
|
954dc1968d | ||
|
|
1a04986d6e | ||
|
|
288c2856ca | ||
|
|
ee2f9f9368 | ||
|
|
511051eae6 | ||
|
|
61e72330c6 | ||
|
|
b0d2be2808 | ||
|
|
6130852d4b |
No files matched your search
+4
-1
@@ -25,4 +25,7 @@ Tmp/
|
||||
/packages/
|
||||
node_modules/
|
||||
|
||||
*.zip
|
||||
*.zip
|
||||
|
||||
# Rider
|
||||
.idea
|
||||
@@ -3,7 +3,5 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:BetterGenshinImpact.Test"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
<Application.Resources />
|
||||
</Application>
|
||||
@@ -0,0 +1,146 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Dataset;
|
||||
|
||||
public class AvatarClassifyGen
|
||||
{
|
||||
// 基础图像文件夹
|
||||
private const string BaseDir = @"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\分类器\";
|
||||
|
||||
// 背景图像文件夹
|
||||
private static readonly string BackgroundDir = Path.Combine(BaseDir, "background");
|
||||
|
||||
private static readonly Random Rd = new Random();
|
||||
|
||||
public static void GenAll()
|
||||
{
|
||||
// 读取基础图像
|
||||
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// 只用一个图像
|
||||
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Arlecchino.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
|
||||
// 生成训练集
|
||||
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
|
||||
// 生成测试集
|
||||
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\test"), 40);
|
||||
// GenTo(new List<string> { sideImageFiles[1] }, Path.Combine(BaseDir, @"dateset\test"), 1);
|
||||
}
|
||||
|
||||
static void GenTo(List<string> sideImageFiles, string dataFolder, int count)
|
||||
{
|
||||
// 保留区域 从底边中心为固定点
|
||||
var reservedSize = new Size(60, 80);
|
||||
|
||||
Directory.CreateDirectory(dataFolder);
|
||||
// 循环生成每个基础图像对应的数据集
|
||||
foreach (string sideImageFile in sideImageFiles)
|
||||
{
|
||||
// 获取基础图像文件名
|
||||
string sideImageFileName = Path.GetFileNameWithoutExtension(sideImageFile);
|
||||
sideImageFileName = sideImageFileName.Replace("UI_AvatarIcon_Side_", "");
|
||||
// 创建基础图像对应的数据集文件夹
|
||||
string sideDataFolder = Path.Combine(dataFolder, sideImageFileName);
|
||||
Directory.CreateDirectory(sideDataFolder);
|
||||
|
||||
// 读取基础图像
|
||||
Mat sideImageSrc = Cv2.ImRead(sideImageFile, ImreadModes.Unchanged);
|
||||
var channels = sideImageSrc.Split();
|
||||
var alphaChannel = channels[3]; // 透明通道
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Cv2.Multiply(channels[i], alphaChannel, channels[i], 1 / 255.0);
|
||||
}
|
||||
|
||||
var sideImage = new Mat();
|
||||
Cv2.Merge(channels[..3], sideImage);
|
||||
|
||||
// Cv2.ImShow("avatar", sideImage);
|
||||
|
||||
// 循环生成图像
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
// 随机挑选一张背景图像
|
||||
string backgroundImageFile = Path.Combine(BackgroundDir, Directory.GetFiles(BackgroundDir, "*.png")[Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
|
||||
|
||||
// 从背景图像中随机取一块 128x128 的区域
|
||||
Mat backgroundImage = Cv2.ImRead(backgroundImageFile, ImreadModes.Color);
|
||||
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128), new Random().Next(backgroundImage.Height - 128), 128, 128);
|
||||
Mat backgroundImageRegion = backgroundImage[backgroundRect];
|
||||
|
||||
// 随机平移、缩放保留区域
|
||||
float scale = (float)(Rd.NextDouble() * (1.6 - 0.7) + 0.7);
|
||||
int w = (int)(sideImage.Width * scale);
|
||||
int h = (int)(sideImage.Height * scale);
|
||||
|
||||
Debug.WriteLine($"{sideImageFileName} 生成随机缩放{scale}");
|
||||
|
||||
// 把保留区域合成到背景图像上
|
||||
Mat backgroundImageRegionClone = backgroundImageRegion.Clone();
|
||||
var resizedSideImage = new Mat();
|
||||
Cv2.Resize(sideImage, resizedSideImage, new Size(128 * scale, 128 * scale));
|
||||
// Cv2.ImShow("resizedSideImage", resizedSideImage);
|
||||
var resizedMaskImage = new Mat();
|
||||
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
|
||||
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
var resizedAlphaChannel = new Mat();
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
|
||||
// Cv2.ImShow("resizedMaskImage", resizedMaskImage);
|
||||
// generatedImage[transformedRect] = resizedSideImage;
|
||||
Mat result;
|
||||
if (scale > 1)
|
||||
{
|
||||
int xSpace1 = (int)((128 - reservedSize.Width * scale) / 2.0);
|
||||
int ySpace1 = (int)(128 - reservedSize.Height * scale);
|
||||
int xSpace2 = (int)((resizedSideImage.Width - 128) / 2.0);
|
||||
int ySpace2 = resizedSideImage.Height - 128;
|
||||
int xSpace = Math.Min(xSpace1, xSpace2);
|
||||
int ySpace = Math.Min(ySpace1, ySpace2);
|
||||
int offsetX = Rd.Next(-xSpace, xSpace);
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}大于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX, (resizedSideImage.Height - 128) + offsetY, 128, 128);
|
||||
// result = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone, backgroundImageRegionClone, result, resizedMaskImage[roi]);
|
||||
result = Mul(backgroundImageRegionClone, resizedAlphaChannel[roi]);
|
||||
Cv2.Add(result, resizedSideImage[roi], result);
|
||||
}
|
||||
else
|
||||
{
|
||||
int xSpace = (128 - w) / 2;
|
||||
int ySpace = 128 - h;
|
||||
int offsetX = Rd.Next(-xSpace, xSpace);
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}小于等于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX, (128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
|
||||
var res = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone[roi], backgroundImageRegionClone[roi], res, resizedMaskImage);
|
||||
res = Mul(backgroundImageRegionClone[roi], resizedAlphaChannel);
|
||||
Cv2.Add(res, resizedSideImage, res);
|
||||
backgroundImageRegionClone[roi] = res;
|
||||
result = backgroundImageRegionClone.Clone();
|
||||
}
|
||||
|
||||
// Cv2.ImShow("avatarR", result);
|
||||
// 保存生成的图像
|
||||
Cv2.ImWrite(Path.Combine(sideDataFolder, $"{sideImageFileName}_{i}.png"), result);
|
||||
}
|
||||
}
|
||||
|
||||
static Mat Mul(Mat background, Mat alphaChannel)
|
||||
{
|
||||
var channels = background.Split();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
|
||||
}
|
||||
Mat result = new Mat();
|
||||
Cv2.Merge(channels[..3], result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,27 +3,58 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:BetterGenshinImpact.Test"
|
||||
xmlns:oxy="http://oxyplot.org/wpf"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="800" Width="400">
|
||||
<Window.DataContext>
|
||||
<local:MainViewModel/>
|
||||
</Window.DataContext>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition></RowDefinition>
|
||||
<RowDefinition></RowDefinition>
|
||||
<RowDefinition></RowDefinition>
|
||||
</Grid.RowDefinitions>
|
||||
<oxy:PlotView
|
||||
Grid.Row="0"
|
||||
Model="{Binding LeftModel}"/>
|
||||
<oxy:PlotView
|
||||
Grid.Row="1"
|
||||
Model="{Binding RightModel}"/>
|
||||
<oxy:PlotView
|
||||
Grid.Row="2"
|
||||
Model="{Binding AllModel}"/>
|
||||
</Grid>
|
||||
</Window>
|
||||
Title="Test"
|
||||
Width="120"
|
||||
Height="450"
|
||||
mc:Ignorable="d">
|
||||
<Canvas>
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="10"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="ShowCameraRecWindow"
|
||||
Content="视角识别测试" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="40"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="ShowHsvTestWindow"
|
||||
Content="Hsv拉条" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="70"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="DoMapPuzzle"
|
||||
Content="拼接超大地图" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="100"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="DoMatchTest"
|
||||
Content="特征匹配测试" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="130"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="DoMatchTemplateTest"
|
||||
Content="模板匹配测试" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="160"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="MapDrawTeleportPoint"
|
||||
Content="超大地图标点" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="190"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="GenAvatarData"
|
||||
Content="生成侧面头像数据集" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="190"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="AutoCookTestCase"
|
||||
Content="自动烹饪图像测试" />
|
||||
</Canvas>
|
||||
</Window>
|
||||
@@ -1,20 +1,68 @@
|
||||
using System.Windows;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
using BetterGenshinImpact.Test.Dataset;
|
||||
using BetterGenshinImpact.Test.Simple;
|
||||
using BetterGenshinImpact.Test.Simple.AllMap;
|
||||
using BetterGenshinImpact.Test.View;
|
||||
|
||||
namespace BetterGenshinImpact.Test
|
||||
namespace BetterGenshinImpact.Test;
|
||||
|
||||
/// <summary>
|
||||
/// MainWindow.xaml 的交互逻辑
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
public MainWindow()
|
||||
{
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
|
||||
InitializeComponent();
|
||||
|
||||
new HsvTestWindow().Run();
|
||||
|
||||
}
|
||||
InitializeComponent();
|
||||
Global.StartUpPath = @"D:\HuiPrograming\Projects\CSharp\MiHoYo\BetterGenshinImpact\BetterGenshinImpact\bin\x64\Debug\net7.0-windows10.0.22621.0";
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowCameraRecWindow(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
new CameraRecWindow().Show();
|
||||
}
|
||||
|
||||
private void ShowHsvTestWindow(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
new HsvTestWindow().Run();
|
||||
}
|
||||
|
||||
private void DoMapPuzzle(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
MapPuzzle.Put();
|
||||
}
|
||||
|
||||
private void DoOcrTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
OcrTest.TestYap();
|
||||
}
|
||||
|
||||
private void DoMatchTemplateTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
MatchTemplateTest.Test();
|
||||
}
|
||||
|
||||
private void DoMatchTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
// KeyPointMatchTest.Test();
|
||||
// EntireMapTest.Test();
|
||||
EntireMapTest.Storage();
|
||||
}
|
||||
|
||||
private void MapDrawTeleportPoint(object sender, RoutedEventArgs e)
|
||||
{
|
||||
MapTeleportPointDraw.Draw();
|
||||
}
|
||||
|
||||
private void GenAvatarData(object sender, RoutedEventArgs e)
|
||||
{
|
||||
AvatarClassifyGen.GenAll();
|
||||
}
|
||||
|
||||
private void AutoCookTestCase(object sender, RoutedEventArgs e)
|
||||
{
|
||||
AutoCookTest.Test();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Detail;
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class EntireMapTest
|
||||
{
|
||||
public static void Test()
|
||||
{
|
||||
SpeedTimer speedTimer = new();
|
||||
var mainMap1024BlockMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\mainMap1024Block.png", ImreadModes.Grayscale);
|
||||
var surfMatcher = new FeatureMatcher(mainMap1024BlockMat);
|
||||
var queryMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\比较\小地图\Clip_20240323_183119.png", ImreadModes.Grayscale);
|
||||
|
||||
speedTimer.Record("初始化特征");
|
||||
|
||||
var pArray = surfMatcher.Match(queryMat);
|
||||
speedTimer.Record("匹配1");
|
||||
if (pArray != null)
|
||||
{
|
||||
var rect = Cv2.BoundingRect(pArray);
|
||||
Debug.WriteLine($"Matched rect 1: {rect}");
|
||||
Cv2.Rectangle(mainMap1024BlockMat, rect, Scalar.Red, 2);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b1.png", mainMap1024BlockMat);
|
||||
|
||||
var pArray2 = surfMatcher.Match(queryMat, rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
|
||||
speedTimer.Record("匹配2");
|
||||
if (pArray2 != null)
|
||||
{
|
||||
var rect2 = Cv2.BoundingRect(pArray2);
|
||||
Debug.WriteLine($"Matched rect 2: {rect2}");
|
||||
Cv2.Rectangle(mainMap1024BlockMat, rect2, Scalar.Yellow, 1);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b2.png", mainMap1024BlockMat);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine("No match 2");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine("No match 1");
|
||||
}
|
||||
speedTimer.DebugPrint();
|
||||
}
|
||||
|
||||
public static void Storage()
|
||||
{
|
||||
var featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap2048BlockMat.Value, new FeatureStorage("mainMap2048Block"));
|
||||
MessageBox.Show("特征点生成完成");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Xml;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class KeyPointMatchTest
|
||||
{
|
||||
public static void Test()
|
||||
{
|
||||
// var trainMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\比较\叠图\无法匹配2.png", ImreadModes.Color);
|
||||
var trainMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\比较\小地图\Clip_20240323_152015.png", ImreadModes.Grayscale);
|
||||
|
||||
// tar = tar.Resize(new Size(tar.Width * 2, tar.Height * 2), 0, 0, InterpolationFlags.Nearest);
|
||||
|
||||
// var queryMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\combined_image_lim[quick].png", ImreadModes.Color);
|
||||
var queryMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\combined_image_2048_lim[quick].png", ImreadModes.Grayscale);
|
||||
var res = MatchPicBySurf(trainMat, queryMat);
|
||||
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\s1.png", res);
|
||||
}
|
||||
|
||||
/*public static Mat MatchPicBySift(Mat matSrc, Mat matTo)
|
||||
{
|
||||
Stopwatch sw = new Stopwatch();
|
||||
sw.Start();
|
||||
|
||||
Mat matSrcRet = new Mat();
|
||||
using Mat matToRet = new Mat();
|
||||
KeyPoint[] keyPointsSrc, keyPointsTo;
|
||||
using (var sift = SIFT.Create())
|
||||
{
|
||||
var kpPath = @"E:\HuiTask\更好的原神\地图匹配\sift.kp";
|
||||
var kpMatPath = @"E:\HuiTask\更好的原神\地图匹配\sift.mat";
|
||||
if (File.Exists(kpPath) && File.Exists(kpMatPath))
|
||||
{
|
||||
keyPointsSrc = (KeyPoint[])DeserializeObject(File.ReadAllBytes(kpPath));
|
||||
GCHandle pinnedArray = GCHandle.Alloc(DeserializeObject(File.ReadAllBytes(kpMatPath)), GCHandleType.Pinned);
|
||||
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
|
||||
matSrcRet = new Mat(166767, 128, MatType.CV_32FC1, pointer);
|
||||
}
|
||||
else
|
||||
{
|
||||
sift.DetectAndCompute(matSrc, null, out keyPointsSrc, matSrcRet);
|
||||
byte[] arr = new byte[matSrcRet.Step(0) * matSrcRet.Rows]; // matSrcRet.Total() * matSrcRet.ElemSize()
|
||||
Marshal.Copy(matSrcRet.Data, arr, 0, arr.Length);
|
||||
File.WriteAllBytes(kpMatPath, SerializeObject(arr));
|
||||
File.WriteAllBytes(kpPath, SerializeObject(keyPointsSrc));
|
||||
}
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"大地图kp耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
sift.DetectAndCompute(matTo, null, out keyPointsTo, matToRet);
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"模板kp耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
}
|
||||
|
||||
using (var bfMatcher = new OpenCvSharp.BFMatcher())
|
||||
{
|
||||
var matches = bfMatcher.KnnMatch(matSrcRet, matToRet, k: 2);
|
||||
|
||||
var pointsSrc = new List<Point2f>();
|
||||
var pointsDst = new List<Point2f>();
|
||||
var goodMatches = new List<DMatch>();
|
||||
foreach (DMatch[] items in matches.Where(x => x.Length > 1))
|
||||
{
|
||||
if (items[0].Distance < 0.5 * items[1].Distance)
|
||||
{
|
||||
pointsSrc.Add(keyPointsSrc[items[0].QueryIdx].Pt);
|
||||
pointsDst.Add(keyPointsTo[items[0].TrainIdx].Pt);
|
||||
goodMatches.Add(items[0]);
|
||||
Debug.WriteLine($"{keyPointsSrc[items[0].QueryIdx].Pt.X}, {keyPointsSrc[items[0].QueryIdx].Pt.Y}");
|
||||
}
|
||||
}
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"bfMatcher耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
|
||||
var outMat = new Mat();
|
||||
|
||||
// algorithm RANSAC Filter the matched results
|
||||
var pSrc = pointsSrc.ConvertAll(Point2fToPoint2d);
|
||||
var pDst = pointsDst.ConvertAll(Point2fToPoint2d);
|
||||
var outMask = new Mat();
|
||||
// If the original matching result is null, Skip the filtering step
|
||||
if (pSrc.Count > 0 && pDst.Count > 0)
|
||||
Cv2.FindHomography(pSrc, pDst, HomographyMethods.Ransac, mask: outMask);
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"FindHomography耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
// If passed RANSAC After processing, the matching points are more than 10.,Only filters are used. Otherwise, use the original matching point result(When the matching point is too small, it passes through RANSAC After treatment,It is possible to get the result of 0 matching points.).
|
||||
if (outMask.Rows > 10)
|
||||
{
|
||||
byte[] maskBytes = new byte[outMask.Rows * outMask.Cols];
|
||||
outMask.GetArray(out maskBytes);
|
||||
Cv2.DrawMatches(matSrc, keyPointsSrc, matTo, keyPointsTo, goodMatches, outMat, matchesMask: maskBytes, flags: DrawMatchesFlags.NotDrawSinglePoints);
|
||||
}
|
||||
else
|
||||
Cv2.DrawMatches(matSrc, keyPointsSrc, matTo, keyPointsTo, goodMatches, outMat, flags: DrawMatchesFlags.NotDrawSinglePoints);
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"绘图耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
return outMat;
|
||||
}
|
||||
}*/
|
||||
|
||||
//This method may be missed, you may read a lot of blogs, but none of them wrote
|
||||
private static Point2d Point2fToPoint2d(Point2f input)
|
||||
{
|
||||
Point2d p2 = new Point2d(input.X, input.Y);
|
||||
return p2;
|
||||
}
|
||||
|
||||
public static Mat MatchPicBySurf(Mat matSrc, Mat matTo, double threshold = 400)
|
||||
{
|
||||
Stopwatch sw = new Stopwatch();
|
||||
sw.Start();
|
||||
|
||||
using Mat matSrcRet = new Mat();
|
||||
using Mat matToRet = new Mat();
|
||||
KeyPoint[] keyPointsSrc, keyPointsTo;
|
||||
using (var surf = OpenCvSharp.XFeatures2D.SURF.Create(threshold, 4, 3, false, true))
|
||||
{
|
||||
surf.DetectAndCompute(matSrc, null, out keyPointsSrc, matSrcRet);
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"模板kp耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
|
||||
surf.DetectAndCompute(matTo, null, out keyPointsTo, matToRet);
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"大地图kp耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
}
|
||||
|
||||
using (var flnMatcher = new FlannBasedMatcher())
|
||||
{
|
||||
var matches = flnMatcher.Match(matSrcRet, matToRet);
|
||||
//Finding the Minimum and Maximum Distance
|
||||
double minDistance = 1000; //Backward approximation
|
||||
double maxDistance = 0;
|
||||
for (int i = 0; i < matSrcRet.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 pointsSrc = new List<Point2f>();
|
||||
var pointsDst = new List<Point2f>();
|
||||
//Screening better matching points
|
||||
var goodMatches = new List<DMatch>();
|
||||
for (int i = 0; i < matSrcRet.Rows; i++)
|
||||
{
|
||||
double distance = matches[i].Distance;
|
||||
if (distance < Math.Max(minDistance * 2, 0.02))
|
||||
{
|
||||
pointsSrc.Add(keyPointsSrc[matches[i].QueryIdx].Pt);
|
||||
pointsDst.Add(keyPointsTo[matches[i].TrainIdx].Pt);
|
||||
//Compression of new ones with distances less than ranges DMatch
|
||||
goodMatches.Add(matches[i]);
|
||||
}
|
||||
}
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"flnMatcher耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
|
||||
var outMat = new Mat();
|
||||
|
||||
// algorithm RANSAC Filter the matched results
|
||||
var pSrc = pointsSrc.ConvertAll(Point2fToPoint2d);
|
||||
var pDst = pointsDst.ConvertAll(Point2fToPoint2d);
|
||||
var outMask = new Mat();
|
||||
// If the original matching result is null, Skip the filtering step
|
||||
if (pSrc.Count > 0 && pDst.Count > 0)
|
||||
{
|
||||
var hMat = Cv2.FindHomography(pSrc, pDst, HomographyMethods.Ransac, mask: outMask);
|
||||
|
||||
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);
|
||||
|
||||
// for (int i = 0; i < 4; i++)
|
||||
// {
|
||||
// /* 作用和perspectiveTransform一样
|
||||
// double x = obj_corners[i].x;
|
||||
// double y = obj_corners[i].y;
|
||||
// double Z = 1. / (H.At<double>(2, 0) * x + H.At<double>(2, 1) * y + H.At<double>(2, 2));
|
||||
// double X = (H.At<double>(0, 0) * x + H.At<double>(0, 1) * y + H.At<double>(0, 2)) * Z;
|
||||
// double Y = (H.At<double>(1, 0) * x + H.At<double>(1, 1) * y + H.At<double>(1, 2)) * Z;
|
||||
// scene_corners[i] = new Point(cv.Round(X) + img_1.Cols, cv.Round(Y));*/
|
||||
// sceneCorners[i].X += matSrc.Cols;
|
||||
// }
|
||||
|
||||
Cv2.Line(matTo, sceneCorners[0].ToPoint(), sceneCorners[1].ToPoint(), Scalar.Red, 2);
|
||||
Cv2.Line(matTo, sceneCorners[1].ToPoint(), sceneCorners[2].ToPoint(), Scalar.Red, 2);
|
||||
Cv2.Line(matTo, sceneCorners[2].ToPoint(), sceneCorners[3].ToPoint(), Scalar.Red, 2);
|
||||
Cv2.Line(matTo, sceneCorners[3].ToPoint(), sceneCorners[0].ToPoint(), Scalar.Red, 2);
|
||||
}
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"FindHomography耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
sw.Restart();
|
||||
|
||||
// If passed RANSAC After processing, the matching points are more than 10.,Only filters are used. Otherwise, use the original matching point result(When the matching point is too small, it passes through RANSAC After treatment,It's possible to get the result of 0 matching points.).
|
||||
if (outMask.Rows > 10)
|
||||
{
|
||||
Debug.WriteLine($"使用了Ransac的结果");
|
||||
byte[] maskBytes = new byte[outMask.Rows * outMask.Cols];
|
||||
outMask.GetArray(out maskBytes);
|
||||
Cv2.DrawMatches(matSrc, keyPointsSrc, matTo, keyPointsTo, goodMatches, outMat, matchesMask: maskBytes, flags: DrawMatchesFlags.NotDrawSinglePoints);
|
||||
}
|
||||
else
|
||||
Cv2.DrawMatches(matSrc, keyPointsSrc, matTo, keyPointsTo, goodMatches, outMat, flags: DrawMatchesFlags.NotDrawSinglePoints);
|
||||
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"绘图耗时:{sw.ElapsedMilliseconds}ms.");
|
||||
return outMat;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 序列化
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
private static byte[] Serialize(object obj)
|
||||
{
|
||||
using var memoryStream = new MemoryStream();
|
||||
DataContractSerializer ser = new DataContractSerializer(typeof(object));
|
||||
ser.WriteObject(memoryStream, obj);
|
||||
var data = memoryStream.ToArray();
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 反序列化
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
private static T Deserialize<T>(byte[] data)
|
||||
{
|
||||
using var memoryStream = new MemoryStream(data);
|
||||
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());
|
||||
DataContractSerializer ser = new DataContractSerializer(typeof(T));
|
||||
var result = (T)ser.ReadObject(reader, true);
|
||||
return result;
|
||||
}
|
||||
|
||||
static bool WriteRawImage(Mat image, string filename)
|
||||
{
|
||||
using (FileStream file = new FileStream(filename, FileMode.Create))
|
||||
{
|
||||
if (file == null || !file.CanWrite)
|
||||
return false;
|
||||
|
||||
BinaryWriter writer = new BinaryWriter(file);
|
||||
writer.Write(image.Rows);
|
||||
writer.Write(image.Cols);
|
||||
int depth = image.Depth();
|
||||
int type = image.Type();
|
||||
int channels = image.Channels();
|
||||
writer.Write(depth);
|
||||
writer.Write(type);
|
||||
writer.Write(channels);
|
||||
int sizeInBytes = (int)image.Step() * image.Rows;
|
||||
writer.Write(sizeInBytes);
|
||||
byte[] arr = new byte[sizeInBytes];
|
||||
Marshal.Copy(image.Data, arr, 0, arr.Length);
|
||||
writer.Write(arr, 0, sizeInBytes);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool ReadRawImage(out Mat image, string filename)
|
||||
{
|
||||
int rows, cols, data, depth, type, channels;
|
||||
image = null;
|
||||
|
||||
using (FileStream file = new FileStream(filename, FileMode.Open))
|
||||
{
|
||||
if (file == null || !file.CanRead)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
BinaryReader reader = new BinaryReader(file);
|
||||
rows = reader.ReadInt32();
|
||||
cols = reader.ReadInt32();
|
||||
depth = reader.ReadInt32();
|
||||
type = reader.ReadInt32();
|
||||
channels = reader.ReadInt32();
|
||||
data = reader.ReadInt32();
|
||||
image = new Mat(rows, cols, (MatType)type);
|
||||
// reader.Read(image.Data, 0, data);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class MapPuzzle
|
||||
{
|
||||
public static readonly int block = 2048;
|
||||
|
||||
public static List<string> PicWhiteHashList = new List<string>
|
||||
{
|
||||
"25E23B0D18C2CBEA19D28E5E399D42FA",
|
||||
"3B4847FEA7D506EAF3B75D4F4541E867",
|
||||
"CCCAF02768432A46AA0001E51DC5991B",
|
||||
"F80C609208063B289A05B8A1E0351226",
|
||||
"06767779699056515930D0597072AB7D",
|
||||
"04F757BD57FBB5FA74A6C9C0634BB122",
|
||||
"04C1EDFCD89249209D1DD885DD2F2129",
|
||||
"01B8641F5F58BBDE6E10F53D56EA7288",
|
||||
"AF56BDE27BDF534317A9FB34E08165C0",
|
||||
"05F4EAB8C6BFBADD60B8A5CCDD614F83"
|
||||
};
|
||||
|
||||
public static MD5 Md5Service = MD5.Create();
|
||||
|
||||
public static void Put()
|
||||
{
|
||||
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map"; // 图片文件夹路径
|
||||
string pattern = @"UI_MapBack_([-+]?\d+)_([-+]?\d+)(.*)";
|
||||
var images = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly); // 获取所有图片文件路径
|
||||
|
||||
// 解析图片位置信息并存储到字典中
|
||||
var imageLocations = new Dictionary<(int row, int col), ImgInfo>();
|
||||
foreach (var imagePath in images)
|
||||
{
|
||||
// 获取文件大小
|
||||
var fileInfo = new FileInfo(imagePath);
|
||||
|
||||
// 解析图片名称中的行列信息
|
||||
var name = Path.GetFileNameWithoutExtension(imagePath);
|
||||
var match = Regex.Match(name, pattern);
|
||||
int row, col;
|
||||
if (match.Success)
|
||||
{
|
||||
// Debug.WriteLine($"已匹配 ({match.Groups[1].Value}, {match.Groups[2].Value}) {name}");
|
||||
row = int.Parse(match.Groups[1].Value);
|
||||
col = int.Parse(match.Groups[2].Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Debug.WriteLine($"未匹配 {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 排除指定行列的图片
|
||||
if ((row, col) == (4, 6) || (row, col) == (5, 6) || (row, col) == (5, 5) || (row, col) == (5, 2) || (row, col) == (5, 1) || (row, col) == (4, 1))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// 读取图片并计算hash值
|
||||
Mat img = Cv2.ImRead(imagePath);
|
||||
var hashBytes = Md5Service.ComputeHash(File.ReadAllBytes(imagePath));
|
||||
var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToUpperInvariant();
|
||||
|
||||
if (img.Width < 8)
|
||||
{
|
||||
Debug.WriteLine($"太小的不要 ({row}, {col}) {img.Width} {img.Height} {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果只要城市拼接,取消注释这段
|
||||
// if (block == 2048 && img.Width != 2048)
|
||||
// {
|
||||
// Debug.WriteLine($"不是2048的不要 ({row}, {col}) {img.Width} {img.Height} {name}");
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// 如果当前位置已经有图片了,保留尺寸较大的图片
|
||||
if (imageLocations.ContainsKey((row, col)))
|
||||
{
|
||||
// 如果当前位置的图片已经被hash锁定,跳过
|
||||
if (imageLocations[(row, col)].Locked)
|
||||
{
|
||||
Debug.WriteLine($"已锁定 ({row}, {col}) {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (img.Width > imageLocations[(row, col)].Img.Width || fileInfo.Length > imageLocations[(row, col)].FileLength || PicWhiteHashList.Contains(hash))
|
||||
{
|
||||
imageLocations[(row, col)] = new ImgInfo(img, name, fileInfo.Length, PicWhiteHashList.Contains(hash));
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine($"重复 ({row}, {col}) {img.Width} {img.Height} {name}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
imageLocations[(row, col)] = new ImgInfo(img, name, fileInfo.Length, PicWhiteHashList.Contains(hash));
|
||||
}
|
||||
}
|
||||
|
||||
int minRow = imageLocations.Keys.Min(key => key.row);
|
||||
int minCol = imageLocations.Keys.Min(key => key.col);
|
||||
|
||||
// 确定大图的行数和列数
|
||||
int maxRow = imageLocations.Keys.Max(key => key.row);
|
||||
int maxCol = imageLocations.Keys.Max(key => key.col);
|
||||
|
||||
// 计算大图的总宽度和高度
|
||||
var lenCol = maxCol - minCol;
|
||||
var lenRow = maxRow - minRow;
|
||||
int totalWidth = (lenCol + 1) * block;
|
||||
int totalHeight = (lenRow + 1) * block;
|
||||
|
||||
// 创建空白大图
|
||||
Mat largeImage = new Mat(totalHeight, totalWidth, MatType.CV_8UC3, new Scalar(0, 0, 0));
|
||||
|
||||
// 拼接图片
|
||||
int[,] arr = new int[lenRow + 1, lenCol + 1];
|
||||
foreach (var location in imageLocations)
|
||||
{
|
||||
int row = location.Key.row - minRow;
|
||||
int col = location.Key.col - minCol;
|
||||
Mat img = location.Value.Img;
|
||||
|
||||
arr[row, col] = 1;
|
||||
|
||||
// 计算当前图片在大图中的左上角位置
|
||||
int x = (lenCol - col) * block; // 顺序倒过来了,屮
|
||||
int y = (lenRow - row) * block; // 顺序倒过来了,屮
|
||||
|
||||
// 将图片粘贴到大图上
|
||||
if (img.Width != block || img.Height != block)
|
||||
{
|
||||
img = img.Resize(new Size(block, block), 0, 0, InterpolationFlags.Nearest);
|
||||
}
|
||||
|
||||
// 添加位置标识
|
||||
// img.PutText($"{location.Key.row} , {location.Key.col}", new Point(50, 50), HersheyFonts.HersheyComplex, 2, Scalar.Red, 2, LineTypes.Link8);
|
||||
|
||||
img.CopyTo(new Mat(largeImage, new Rect(x, y, img.Width, img.Height)));
|
||||
}
|
||||
|
||||
// 康康二维数组的拼接结果
|
||||
for (int i = 0; i < arr.GetLength(0); i++)
|
||||
{
|
||||
for (int j = 0; j < arr.GetLength(1); j++)
|
||||
{
|
||||
Debug.Write(arr[i, j] + " ");
|
||||
}
|
||||
|
||||
Debug.WriteLine("");
|
||||
}
|
||||
|
||||
// 保存大图
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\map_46_2048.png", largeImage);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_sd4x.png", largeImage.Resize(new Size(largeImage.Width / 4, largeImage.Height / 4), 0, 0, InterpolationFlags.Cubic));
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_small.png", largeImage.Resize(new Size(1400, 1300), 0, 0, InterpolationFlags.Cubic));
|
||||
|
||||
// 释放资源
|
||||
largeImage.Dispose();
|
||||
foreach (var img in imageLocations.Values)
|
||||
{
|
||||
img.Img.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public class ImgInfo
|
||||
{
|
||||
public Mat Img { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 文件大小
|
||||
/// </summary>
|
||||
public long FileLength { get; set; }
|
||||
|
||||
public bool Locked { get; set; }
|
||||
|
||||
public ImgInfo(Mat mat, string name, long fileLength, bool locked = false)
|
||||
{
|
||||
Img = mat;
|
||||
Name = name;
|
||||
FileLength = fileLength;
|
||||
Locked = locked;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using BetterGenshinImpact.Service;
|
||||
using OpenCvSharp;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class MapTeleportPointDraw
|
||||
{
|
||||
public static void Draw()
|
||||
{
|
||||
var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\Json_Integration\锚点&神像\");
|
||||
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\genshin_map_带标记.png");
|
||||
DrawTeleportPoint(map, pList.ToArray());
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\genshin_map_带标记_传送点.png", map);
|
||||
}
|
||||
|
||||
public static void DrawTeleportPoint(Mat map, Point[] points)
|
||||
{
|
||||
foreach (var point in points)
|
||||
{
|
||||
Cv2.Circle(map, new Point(point.X, point.Y), 10, Scalar.Red, 2);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Point> LoadTeleportPoint(string folderPath)
|
||||
{
|
||||
string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
|
||||
List<Point> points = new();
|
||||
foreach (var file in files)
|
||||
{
|
||||
var gamePoint = JsonSerializer.Deserialize<GamePoint>(File.ReadAllText(file), ConfigService.JsonOptions);
|
||||
if (gamePoint == null)
|
||||
{
|
||||
Debug.WriteLine($"{file} json is null");
|
||||
continue;
|
||||
}
|
||||
|
||||
points.Add(Transform(gamePoint.Position));
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 坐标系转换
|
||||
/// </summary>
|
||||
/// <param name="position">[a,b,c]</param>
|
||||
/// <returns></returns>
|
||||
public static Point Transform(decimal[] position)
|
||||
{
|
||||
// 四舍六入五取偶
|
||||
var a = (int)Math.Round(position[0]); // 上
|
||||
var c = (int)Math.Round(position[2]); // 左
|
||||
|
||||
// 转换1024区块坐标,大地图坐标系正轴是往左上方向的
|
||||
// 这里写最左上角的区块坐标(m,n)/(上,左),截止4.5版本,最左上角的区块坐标是(5,7)
|
||||
|
||||
int m = 5, n = 7;
|
||||
return new Point((n + 1) * 1024 - c, (m + 1) * 1024 - a);
|
||||
}
|
||||
|
||||
class GamePoint
|
||||
{
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public decimal[] Position { get; set; } = new decimal[3];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class MatchTemplateTest
|
||||
{
|
||||
public static readonly Size TemplateSize = new(240, 135);
|
||||
|
||||
// 对无用部分进行裁剪(左160,上80,下96)
|
||||
public static readonly Rect TemplateSizeRoi = new Rect(20, 10, TemplateSize.Width - 20, TemplateSize.Height - 22);
|
||||
|
||||
public static void Test()
|
||||
{
|
||||
var tar = new Mat(@"E:\HuiTask\更好的原神\地图匹配\比较\叠图\无法匹配.png", ImreadModes.Grayscale);
|
||||
var sTar = tar.Resize(new Size(240, 135), 0, 0, InterpolationFlags.Cubic);
|
||||
// sTar = new Mat(sTar, TemplateSizeRoi);
|
||||
Cv2.ImShow("sTar", sTar);
|
||||
var src = new Mat(@"E:\HuiTask\更好的原神\地图匹配\combined_image_small.png", ImreadModes.Grayscale);
|
||||
var src2 = src.Clone();
|
||||
var p = MatchTemplateWithGaussianBlur(src, sTar, TemplateMatchModes.CCoeffNormed, null, 0.1);
|
||||
|
||||
Cv2.Rectangle(src2, new Rect(p.X, p.Y, sTar.Width, sTar.Height), new Scalar(0, 0, 255));
|
||||
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\x1.png", src2);
|
||||
}
|
||||
|
||||
public static void TestTrack()
|
||||
{
|
||||
var tar = new Mat(@"E:\HuiTask\更好的原神\自动剧情\任务剧情与地图追踪\blue_task_point_28x.png", ImreadModes.Grayscale);
|
||||
var src = new Mat(@"E:\HuiTask\更好的原神\自动剧情\任务剧情与地图追踪\202404050232291883.png", ImreadModes.Grayscale);
|
||||
var src2 = src.Clone();
|
||||
var p = MatchTemplateHelper.MatchTemplate(src, tar, TemplateMatchModes.CCoeffNormed, null, 0.2);
|
||||
Cv2.Rectangle(src2, new Rect(p.X, p.Y, tar.Width, tar.Height), new Scalar(0, 0, 255), 1);
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\自动剧情\任务剧情与地图追踪\rec_b1.png", src2);
|
||||
}
|
||||
|
||||
public static void TestMenu()
|
||||
{
|
||||
var tar = new Mat(@"D:\HuiPrograming\Projects\CSharp\MiHoYo\BetterGenshinImpact\BetterGenshinImpact\GameTask\Common\Element\Assets\1920x1080\paimon_menu.png", ImreadModes.Color);
|
||||
var src = new Mat(@"E:\HuiTask\更好的原神\地图匹配\比较\菜单\Clip_20240331_155210.png", ImreadModes.Color);
|
||||
var src2 = src.Clone();
|
||||
var p = MatchTemplateHelper.MatchTemplate(src, tar, TemplateMatchModes.CCoeffNormed, null, 0.1);
|
||||
Cv2.Rectangle(src2, new Rect(p.X, p.Y, tar.Width, tar.Height), new Scalar(0, 0, 255), 1);
|
||||
// 画出小地图的位置
|
||||
// 此图38x40 小地图210x210 小地图左上角位置 24,-15
|
||||
Cv2.Rectangle(src2, new Rect(p.X + 24, p.Y - 15, 210, 210), Scalar.Blue, 1);
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\比较\菜单\rec2.png", src2);
|
||||
}
|
||||
|
||||
public static void TestTeamAvatar()
|
||||
{
|
||||
var tar = new Mat(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\识别头像素材\UI_AvatarIcon_Side_Zhongli_2.png", ImreadModes.Unchanged);
|
||||
// tar = tar.Resize(new Size(108, 108), 0, 0, InterpolationFlags.Cubic);
|
||||
var channels = tar.Split();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
channels[i] &= channels[3];
|
||||
}
|
||||
Cv2.Merge(channels[..3], tar);
|
||||
Cv2.ImShow("tar.png", tar);
|
||||
var src = new Mat(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\1.png", ImreadModes.Color);
|
||||
var src2 = src.Clone();
|
||||
var p = MatchTemplateWithGaussianBlur(src, tar, TemplateMatchModes.CCoeffNormed, null, 0.1);
|
||||
Cv2.Rectangle(src2, new Rect(p.X, p.Y, tar.Width, tar.Height), new Scalar(0, 0, 255), 1);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\rec_1.png", src2);
|
||||
Cv2.ImShow("src2", src2);
|
||||
}
|
||||
|
||||
public static Point MatchTemplateWithGaussianBlur(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat = null, double threshold = 0.8)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = new Mat();
|
||||
if (maskMat == null)
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode);
|
||||
}
|
||||
else
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode, maskMat);
|
||||
}
|
||||
|
||||
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.CCoeff or TemplateMatchModes.CCorr)
|
||||
{
|
||||
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax, -1, null);
|
||||
}
|
||||
using var blurResult = new Mat();
|
||||
Cv2.GaussianBlur(result, blurResult, new Size(1, 1), 0);
|
||||
Cv2.ImShow("blurResult", blurResult);
|
||||
Cv2.Subtract(result, blurResult, result);
|
||||
|
||||
Cv2.MinMaxLoc(result, out var minValue, out var maxValue, out var minLoc, out var maxLoc);
|
||||
Cv2.ImShow("result", result);
|
||||
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.SqDiffNormed)
|
||||
{
|
||||
if (minValue <= 1 - threshold)
|
||||
{
|
||||
return minLoc;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (maxValue >= threshold)
|
||||
{
|
||||
return maxLoc;
|
||||
}
|
||||
}
|
||||
|
||||
return new Point();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new Point();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple;
|
||||
|
||||
internal class AutoCookTest
|
||||
{
|
||||
public static void Test()
|
||||
{
|
||||
var img = new Mat(@"E:\HuiTask\更好的原神\自动烹饪\2.png");
|
||||
Cv2.CvtColor(img, img, ColorConversionCodes.BGR2RGB);
|
||||
var img2 = new Mat();
|
||||
// Cv2.InRange(img, new Scalar(255, 192, 64), new Scalar(255, 192, 64), img2);
|
||||
Cv2.InRange(img, new Scalar(255, 255, 192), new Scalar(255, 255, 192), img2);
|
||||
|
||||
Cv2.ImShow("img", img2);
|
||||
}
|
||||
}
|
||||
+18
-12
@@ -1,42 +1,49 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test;
|
||||
namespace BetterGenshinImpact.Test.Simple;
|
||||
|
||||
internal class HsvTestWindow
|
||||
{
|
||||
private const int MaxValueH = 360 / 2;
|
||||
static readonly int MaxValue = 255;
|
||||
private static readonly int MaxValue = 255;
|
||||
|
||||
//private const string WindowCaptureName = "Video Capture";
|
||||
private const string _windowDetectionName = "Object Detection";
|
||||
static int _lowH = 0, _lowS = 0, _lowV = 0;
|
||||
static int _highH = MaxValueH, _highS = MaxValue, _highV = MaxValue;
|
||||
|
||||
static void on_low_H_thresh_trackbar(int pos, IntPtr userdata)
|
||||
private static int _lowH = 0, _lowS = 0, _lowV = 0;
|
||||
private static int _highH = MaxValueH, _highS = MaxValue, _highV = MaxValue;
|
||||
|
||||
static void on_low_H_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_lowH = Math.Min(_highH - 1, _lowH);
|
||||
Cv2.SetTrackbarPos("Low H", _windowDetectionName, _lowH);
|
||||
}
|
||||
static void on_high_H_thresh_trackbar(int pos, IntPtr userdata)
|
||||
|
||||
static void on_high_H_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_highH = Math.Max(_highH, _lowH + 1);
|
||||
Cv2.SetTrackbarPos("High H", _windowDetectionName, _highH);
|
||||
}
|
||||
static void on_low_S_thresh_trackbar(int pos, IntPtr userdata)
|
||||
|
||||
static void on_low_S_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_lowS = Math.Min(_highS - 1, _lowS);
|
||||
Cv2.SetTrackbarPos("Low S", _windowDetectionName, _lowS);
|
||||
}
|
||||
static void on_high_S_thresh_trackbar(int pos, IntPtr userdata)
|
||||
|
||||
static void on_high_S_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_highS = Math.Max(_highS, _lowS + 1);
|
||||
Cv2.SetTrackbarPos("High S", _windowDetectionName, _highS);
|
||||
}
|
||||
static void on_low_V_thresh_trackbar(int pos, IntPtr userdata)
|
||||
|
||||
static void on_low_V_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_lowV = Math.Min(_highV - 1, _lowV);
|
||||
Cv2.SetTrackbarPos("Low V", _windowDetectionName, _lowV);
|
||||
}
|
||||
static void on_high_V_thresh_trackbar(int pos, IntPtr userdata)
|
||||
|
||||
static void on_high_V_thresh_trackbar(int pos, nint userdata)
|
||||
{
|
||||
_highV = Math.Max(_highV, _lowV + 1);
|
||||
Cv2.SetTrackbarPos("High V", _windowDetectionName, _highV);
|
||||
@@ -44,7 +51,6 @@ internal class HsvTestWindow
|
||||
|
||||
public void Run()
|
||||
{
|
||||
|
||||
//Cv2.NamedWindow(WindowCaptureName);
|
||||
Cv2.NamedWindow(_windowDetectionName);
|
||||
Cv2.ResizeWindow(_windowDetectionName, 900, 900);
|
||||
@@ -76,4 +82,4 @@ internal class HsvTestWindow
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -1,7 +1,6 @@
|
||||
using OpenCvSharp;
|
||||
using SharpCompress;
|
||||
|
||||
namespace BetterGenshinImpact.Test;
|
||||
namespace BetterGenshinImpact.Test.Simple.MiniMap;
|
||||
|
||||
public class CameraOrientationTest
|
||||
{
|
||||
@@ -138,8 +137,6 @@ public class CameraOrientationTest
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void Test2()
|
||||
{
|
||||
var mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\视角朝向识别\1.png", ImreadModes.Color);
|
||||
@@ -164,4 +161,4 @@ public class CameraOrientationTest
|
||||
Cv2.Scharr(splitMat[0], andMat, MatType.CV_8UC1, 1, 0);
|
||||
Cv2.ImShow("Scharr", andMat);
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-19
@@ -1,13 +1,8 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using System.Diagnostics;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Test;
|
||||
namespace BetterGenshinImpact.Test.Simple.MiniMap;
|
||||
|
||||
public class CharacterOrientationTest
|
||||
{
|
||||
@@ -20,8 +15,7 @@ public class CharacterOrientationTest
|
||||
Cv2.ImShow("gray", gray);
|
||||
}
|
||||
|
||||
|
||||
static double Distance(OpenCvSharp.Point pt1, OpenCvSharp.Point pt2)
|
||||
static double Distance(Point pt1, Point pt2)
|
||||
{
|
||||
int deltaX = Math.Abs(pt2.X - pt1.X);
|
||||
int deltaY = Math.Abs(pt2.Y - pt1.Y);
|
||||
@@ -69,13 +63,13 @@ public class CharacterOrientationTest
|
||||
double perimeter = Cv2.ArcLength(contours[i], true);
|
||||
|
||||
// 近似多边形拟合
|
||||
OpenCvSharp.Point[] approx = Cv2.ApproxPolyDP(contours[i], 0.04 * perimeter, true);
|
||||
Point[] approx = Cv2.ApproxPolyDP(contours[i], 0.04 * perimeter, true);
|
||||
|
||||
// 如果拟合的多边形有三个顶点,认为是三角形
|
||||
if (approx.Length == 3)
|
||||
{
|
||||
// 在图像上绘制三角形的轮廓
|
||||
Cv2.DrawContours(src, new OpenCvSharp.Point[][] { approx }, -1, Scalar.Green, 1);
|
||||
Cv2.DrawContours(src, new Point[][] { approx }, -1, Scalar.Green, 1);
|
||||
// 计算三条边的长度
|
||||
var sideLengths = new double[3];
|
||||
sideLengths[0] = Distance(approx[1], approx[2]);
|
||||
@@ -90,7 +84,7 @@ public class CharacterOrientationTest
|
||||
// 计算最短线的中点
|
||||
var residue = approx.ToList();
|
||||
residue.RemoveAt(result.Index);
|
||||
var midPoint = new OpenCvSharp.Point((residue[0].X + residue[1].X) / 2, (residue[0].Y + residue[1].Y) / 2);
|
||||
var midPoint = new Point((residue[0].X + residue[1].X) / 2, (residue[0].Y + residue[1].Y) / 2);
|
||||
|
||||
// 在图像上绘制直线
|
||||
Cv2.Line(src, midPoint, approx[result.Index] + (approx[result.Index] - midPoint) * 3, Scalar.Red, 1);
|
||||
@@ -102,7 +96,6 @@ public class CharacterOrientationTest
|
||||
Cv2.ImShow("目标2", src);
|
||||
}
|
||||
|
||||
|
||||
public static void TestArrow2()
|
||||
{
|
||||
var mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\箭头识别\s1.png", ImreadModes.Color);
|
||||
@@ -202,7 +195,6 @@ public class CharacterOrientationTest
|
||||
return angleDegrees;
|
||||
}
|
||||
|
||||
|
||||
public static void FloodFill()
|
||||
{
|
||||
var mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\箭头识别\s1.png", ImreadModes.Color);
|
||||
@@ -260,7 +252,6 @@ public class CharacterOrientationTest
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void Hsv()
|
||||
{
|
||||
var mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\箭头识别\e1.png", ImreadModes.Color);
|
||||
@@ -315,11 +306,10 @@ public class CharacterOrientationTest
|
||||
if (approx.Length == 3)
|
||||
{
|
||||
// 在图像上绘制三角形的轮廓
|
||||
Cv2.DrawContours(mat, new OpenCvSharp.Point[][] { approx }, -1, Scalar.Green, 1);
|
||||
Cv2.DrawContours(mat, new Point[][] { approx }, -1, Scalar.Green, 1);
|
||||
|
||||
// 剪裁出三角形所在区域
|
||||
var newSrcMat = new Mat(mat, maxRect);
|
||||
|
||||
|
||||
// HSV 阈值取出中心飞镖
|
||||
var hsvMat = new Mat();
|
||||
@@ -369,4 +359,4 @@ public class CharacterOrientationTest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Diagnostics;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple;
|
||||
|
||||
public class OcrTest
|
||||
{
|
||||
public static void TestYap()
|
||||
{
|
||||
Mat mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
|
||||
var text = TextInferenceFactory.Pick.Inference(PreProcessForInference(mat));
|
||||
Debug.WriteLine(text);
|
||||
|
||||
Mat mat2 = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
|
||||
var text2 = OcrFactory.Paddle.Ocr(mat2);
|
||||
Debug.WriteLine(text2);
|
||||
}
|
||||
|
||||
private static Mat PreProcessForInference(Mat mat)
|
||||
{
|
||||
// Yap 已经改用灰度图了 https://github.com/Alex-Beng/Yap/commit/c2ad1e7b1442aaf2d80782a032e00876cd1c6c84
|
||||
// 二值化
|
||||
// Cv2.Threshold(mat, mat, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
|
||||
//Cv2.AdaptiveThreshold(mat, mat, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 31, 3); // 效果不错 但是和模型不搭
|
||||
//mat = OpenCvCommonHelper.Threshold(mat, Scalar.FromRgb(235, 235, 235), Scalar.FromRgb(255, 255, 255)); // 识别物品不太行
|
||||
// 不知道为什么要强制拉伸到 221x32
|
||||
mat = ResizeHelper.ResizeTo(mat, 221, 32);
|
||||
// 填充到 384x32
|
||||
var padded = new Mat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
|
||||
padded[new Rect(0, 0, mat.Width, mat.Height)] = mat;
|
||||
//Cv2.ImWrite(Global.Absolute("padded.png"), padded);
|
||||
return padded;
|
||||
}
|
||||
}
|
||||
+7
-9
@@ -1,21 +1,20 @@
|
||||
using OxyPlot;
|
||||
using BetterGenshinImpact.Test.Simple.MiniMap;
|
||||
using OxyPlot;
|
||||
using OxyPlot.Series;
|
||||
using OxyPlot.Wpf;
|
||||
|
||||
namespace BetterGenshinImpact.Test;
|
||||
namespace BetterGenshinImpact.Test.View;
|
||||
|
||||
internal class MainViewModel
|
||||
internal class CameraRecViewModel
|
||||
{
|
||||
|
||||
public PlotModel LeftModel { get; private set; }
|
||||
public PlotModel RightModel { get; private set; }
|
||||
public PlotModel AllModel { get; private set; }
|
||||
|
||||
public MainViewModel()
|
||||
public CameraRecViewModel()
|
||||
{
|
||||
var data = CameraOrientationTest.Test1();
|
||||
|
||||
LeftModel = BuildModel(data.Item1,"左");
|
||||
LeftModel = BuildModel(data.Item1, "左");
|
||||
RightModel = BuildModel(data.Item2, "右(左移90度后)");
|
||||
AllModel = BuildModel(data.Item3, "乘积");
|
||||
}
|
||||
@@ -37,5 +36,4 @@ internal class MainViewModel
|
||||
plotModel.Title = name;
|
||||
return plotModel;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Window x:Class="BetterGenshinImpact.Test.View.CameraRecWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:BetterGenshinImpact.Test"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:oxy="http://oxyplot.org/wpf"
|
||||
xmlns:view="clr-namespace:BetterGenshinImpact.Test.View"
|
||||
Title="MainWindow"
|
||||
Width="400"
|
||||
Height="800"
|
||||
mc:Ignorable="d">
|
||||
<Window.DataContext>
|
||||
<view:CameraRecViewModel />
|
||||
</Window.DataContext>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<oxy:PlotView Grid.Row="0" Model="{Binding LeftModel}" />
|
||||
<oxy:PlotView Grid.Row="1" Model="{Binding RightModel}" />
|
||||
<oxy:PlotView Grid.Row="2" Model="{Binding AllModel}" />
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace BetterGenshinImpact.Test.View;
|
||||
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class CameraRecWindow : System.Windows.Window
|
||||
{
|
||||
public CameraRecWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
<Application x:Class="BetterGenshinImpact.App"
|
||||
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">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ui:ThemesDictionary Theme="Dark" />
|
||||
<ui:ControlsDictionary />
|
||||
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
|
||||
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
|
||||
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
|
||||
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -1,7 +1,10 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using BetterGenshinImpact.Service.Notifier;
|
||||
using BetterGenshinImpact.View;
|
||||
using BetterGenshinImpact.View.Pages;
|
||||
using BetterGenshinImpact.ViewModel;
|
||||
@@ -54,6 +57,7 @@ public partial class App : Application
|
||||
{
|
||||
loggerConfiguration.WriteTo.RichTextBox(maskWindow.LogBox, LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
}
|
||||
|
||||
Log.Logger = loggerConfiguration.CreateLogger();
|
||||
services.AddLogging(c => c.AddSerilog());
|
||||
|
||||
@@ -67,28 +71,24 @@ public partial class App : Application
|
||||
services.AddSingleton<INavigationService, NavigationService>();
|
||||
|
||||
// Main window with navigation
|
||||
services.AddSingleton<INavigationWindow, MainWindow>();
|
||||
services.AddSingleton<MainWindowViewModel>();
|
||||
services.AddView<INavigationWindow, MainWindow, MainWindowViewModel>();
|
||||
services.AddSingleton<NotifyIconViewModel>();
|
||||
|
||||
// Views and ViewModels
|
||||
services.AddSingleton<HomePage>();
|
||||
services.AddSingleton<HomePageViewModel>();
|
||||
services.AddSingleton<ScriptControlPage>();
|
||||
services.AddSingleton<ScriptControlViewModel>();
|
||||
services.AddSingleton<TriggerSettingsPage>();
|
||||
services.AddSingleton<TriggerSettingsPageViewModel>();
|
||||
services.AddSingleton<MacroSettingsPage>();
|
||||
services.AddSingleton<MacroSettingsPageViewModel>();
|
||||
services.AddSingleton<CommonSettingsPage>();
|
||||
services.AddSingleton<CommonSettingsPageViewModel>();
|
||||
services.AddSingleton<TaskSettingsPage>();
|
||||
services.AddSingleton<TaskSettingsPageViewModel>();
|
||||
|
||||
services.AddSingleton<HotKeyPage>();
|
||||
services.AddSingleton<HotKeyPageViewModel>();
|
||||
// Views
|
||||
services.AddView<HomePage, HomePageViewModel>();
|
||||
services.AddView<ScriptControlPage, ScriptControlViewModel>();
|
||||
services.AddView<TriggerSettingsPage, TriggerSettingsPageViewModel>();
|
||||
services.AddView<MacroSettingsPage, MacroSettingsPageViewModel>();
|
||||
services.AddView<CommonSettingsPage, CommonSettingsPageViewModel>();
|
||||
services.AddView<TaskSettingsPage, TaskSettingsPageViewModel>();
|
||||
services.AddView<HotKeyPage, HotKeyPageViewModel>();
|
||||
services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
|
||||
|
||||
// My Services
|
||||
services.AddSingleton<TaskTriggerDispatcher>();
|
||||
services.AddSingleton<NotificationService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
|
||||
services.AddSingleton<NotifierManager>();
|
||||
|
||||
// Configuration
|
||||
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
|
||||
@@ -111,6 +111,16 @@ public partial class App : Application
|
||||
return _host.Services.GetService(typeof(T)) as T;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets registered service.
|
||||
/// </summary>
|
||||
/// <returns>Instance of the service or <see langword="null"/>.</returns>
|
||||
/// <returns></returns>
|
||||
public static object? GetService(Type type)
|
||||
{
|
||||
return _host.Services.GetService(type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when the application is loading.
|
||||
/// </summary>
|
||||
@@ -218,8 +228,14 @@ public partial class App : Application
|
||||
|
||||
private static void HandleException(Exception e)
|
||||
{
|
||||
if (e.InnerException != null)
|
||||
{
|
||||
e = e.InnerException;
|
||||
}
|
||||
|
||||
MessageBox.Show("程序异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
|
||||
|
||||
// log
|
||||
GetLogger<App>().LogDebug(e, "UnHandle Exception");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<SyntaxDefinition name="Json" extensions=".json" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
|
||||
<Color name="Bool" foreground="#569CD6" exampleText="true | false" />
|
||||
<Color name="Number" foreground="#B5CEA8" exampleText="3.14" />
|
||||
<Color name="String" foreground="#CE9178" exampleText="" />
|
||||
<Color name="Null" foreground="#569CD6" exampleText="" />
|
||||
<Color name="FieldName" foreground="#9CDCF0" />
|
||||
<Color name="Punctuation1" foreground="#DA66BE" />
|
||||
<Color name="Punctuation2" foreground="#FFD710" />
|
||||
<Color name="Punctuation3" foreground="#FFFFFF" />
|
||||
|
||||
<RuleSet name="String">
|
||||
<Span begin="\\" end="."/>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Object">
|
||||
<Span color="FieldName" ruleSet="String">
|
||||
<Begin>"</Begin>
|
||||
<End>"</End>
|
||||
</Span>
|
||||
<Span color="FieldName" ruleSet="String">
|
||||
<Begin>'</Begin>
|
||||
<End>'</End>
|
||||
</Span>
|
||||
<Span color="Punctuation3" ruleSet="Expression">
|
||||
<Begin>:</Begin>
|
||||
</Span>
|
||||
<Span color="Punctuation3">
|
||||
<Begin>,</Begin>
|
||||
</Span>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Array">
|
||||
<Import ruleSet="Expression"/>
|
||||
<Span color="Punctuation3">
|
||||
<Begin>,</Begin>
|
||||
</Span>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Expression">
|
||||
<Keywords color="Bool" >
|
||||
<Word>true</Word>
|
||||
<Word>false</Word>
|
||||
</Keywords>
|
||||
<Keywords color="Null" >
|
||||
<Word>null</Word>
|
||||
</Keywords>
|
||||
<Span color="String" ruleSet="String">
|
||||
<Begin>"</Begin>
|
||||
<End>"</End>
|
||||
</Span>
|
||||
<Span color="String" ruleSet="String">
|
||||
<Begin>'</Begin>
|
||||
<End>'</End>
|
||||
</Span>
|
||||
<Span color="Punctuation1" ruleSet="Object" multiline="true">
|
||||
<Begin>\{</Begin>
|
||||
<End>\}</End>
|
||||
</Span>
|
||||
<Span color="Punctuation2" ruleSet="Array" multiline="true">
|
||||
<Begin>\[</Begin>
|
||||
<End>\]</End>
|
||||
</Span>
|
||||
<Rule color="Number">
|
||||
\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?
|
||||
</Rule>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet>
|
||||
<Import ruleSet="Expression"/>
|
||||
</RuleSet>
|
||||
</SyntaxDefinition>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
Binary file not shown.
Binary file not shown.
@@ -1,24 +0,0 @@
|
||||
[
|
||||
"abiding angelfish",
|
||||
"aizen medaka",
|
||||
"akai maou",
|
||||
"betta",
|
||||
"bitter pufferfish",
|
||||
"brown shirakodai",
|
||||
"crystalfish",
|
||||
"dawncatcher",
|
||||
"glaze medaka",
|
||||
"golden koi",
|
||||
"lunged stickleback",
|
||||
"medaka",
|
||||
"moonfin",
|
||||
"pufferfish",
|
||||
"purple shirakodai",
|
||||
"raimei angelfish",
|
||||
"rusty koi",
|
||||
"snowstrider",
|
||||
"sweet-flower medaka",
|
||||
"target",
|
||||
"tea-colored shirakodai",
|
||||
"venomspine fish"
|
||||
]
|
||||
@@ -158,6 +158,8 @@
|
||||
"芙卡洛斯",
|
||||
"夏沃蕾",
|
||||
"娜维娅",
|
||||
"闲云",
|
||||
"嘉明",
|
||||
"希格雯",
|
||||
"克洛琳德",
|
||||
"艾梅莉埃",
|
||||
@@ -1331,6 +1333,9 @@
|
||||
"无光丝线",
|
||||
"无光涡眼",
|
||||
"无光质块",
|
||||
"羽状鳍翅",
|
||||
"月色鳍翅",
|
||||
"渊光鳍翅",
|
||||
"小灯草",
|
||||
"慕风蘑菇",
|
||||
"蒲公英籽",
|
||||
@@ -1347,6 +1352,7 @@
|
||||
"霓裳花",
|
||||
"琉璃百合",
|
||||
"清心",
|
||||
"清水玉",
|
||||
"晶化骨髓",
|
||||
"血斛",
|
||||
"海灵芝",
|
||||
@@ -1568,6 +1574,7 @@
|
||||
"求职招聘互助板",
|
||||
"告示",
|
||||
"告示板",
|
||||
"搬运",
|
||||
"播撒",
|
||||
"钓鱼",
|
||||
"采摘",
|
||||
@@ -1633,6 +1640,7 @@
|
||||
"加入咖啡",
|
||||
"加入水",
|
||||
"加入奶油",
|
||||
"加入奶泡",
|
||||
"加入牛奶",
|
||||
"放置咖啡",
|
||||
"上行",
|
||||
@@ -1737,6 +1745,7 @@
|
||||
"构筑「花庭」",
|
||||
"重置计分",
|
||||
"养鱼",
|
||||
"查看记录",
|
||||
"无名学者的记事·其一",
|
||||
"无名学者的记事·其二",
|
||||
"无名学者的记事·其三",
|
||||
@@ -4077,6 +4086,246 @@
|
||||
"进入仓库",
|
||||
"埃莉莎",
|
||||
"莫里斯",
|
||||
"《古华手记》",
|
||||
"土生",
|
||||
"云云",
|
||||
"古老的摹刻",
|
||||
"歪歪扭扭的摹刻",
|
||||
"碑铭",
|
||||
"仙家笔记·其一",
|
||||
"古老的文本·其一",
|
||||
"《诸武集成校笺·裁雨法》",
|
||||
"《诸武集成校笺·刺明法》",
|
||||
"《百术集全》",
|
||||
"《悬练九剑》",
|
||||
"《遗珑埠不容错过的三种小吃》",
|
||||
"《百术集全》",
|
||||
"《武理歌诀》",
|
||||
"凌霄",
|
||||
"毅钧",
|
||||
"《古华诸贤谱录》",
|
||||
"明礼",
|
||||
"木李",
|
||||
"霸哥",
|
||||
"霸爷",
|
||||
"仁三",
|
||||
"楚伯",
|
||||
"小梁",
|
||||
"贾尔库坦",
|
||||
"琼玖",
|
||||
"前韵",
|
||||
"寒泉",
|
||||
"旋覆",
|
||||
"青夜",
|
||||
"红鱼",
|
||||
"玄机",
|
||||
"香器铭文",
|
||||
"古老的玉玦",
|
||||
"古老的文本·其二",
|
||||
"古老的文本·其三",
|
||||
"谁人的闲笔",
|
||||
"谁人的闲笔",
|
||||
"谁人的闲笔",
|
||||
"大桔",
|
||||
"赛金砖",
|
||||
"青夜",
|
||||
"红鱼",
|
||||
"云云",
|
||||
"椒椒",
|
||||
"模糊的碑铭",
|
||||
"残破的碑铭",
|
||||
"焦黑的笔记",
|
||||
"《草堂拾遗》",
|
||||
"古剑铭文",
|
||||
"调查样品",
|
||||
"石碑铭文",
|
||||
"赤璋舆图",
|
||||
"先民札记·其一",
|
||||
"先民札记·其二",
|
||||
"先民札记·其三",
|
||||
"古老的卷轴",
|
||||
"字迹潦草的日记",
|
||||
"连芳",
|
||||
"阿绿",
|
||||
"方矩",
|
||||
"利兴",
|
||||
"弗里斯兰",
|
||||
"九贯",
|
||||
"捷悟",
|
||||
"却之",
|
||||
"百疏",
|
||||
"小旷",
|
||||
"笃勤",
|
||||
"万斛",
|
||||
"轩瞩",
|
||||
"永赞",
|
||||
"黄三爷",
|
||||
"韩迁",
|
||||
"赫曼逊",
|
||||
"有规",
|
||||
"文华",
|
||||
"仪正",
|
||||
"洪分",
|
||||
"罗叔",
|
||||
"老陆头",
|
||||
"椒椒",
|
||||
"石坤",
|
||||
"莫妍",
|
||||
"沃特蒙泰涅",
|
||||
"大黑",
|
||||
"平善",
|
||||
"望涓",
|
||||
"宜清",
|
||||
"陈八珍",
|
||||
"丰泰",
|
||||
"衡听",
|
||||
"艾葛",
|
||||
"阿林",
|
||||
"老丁",
|
||||
"小丁",
|
||||
"大盗",
|
||||
"泊溯",
|
||||
"孙桡",
|
||||
"舒山",
|
||||
"德音",
|
||||
"若松",
|
||||
"可慎",
|
||||
"文四爷",
|
||||
"礼信",
|
||||
"知贵",
|
||||
"迭跃",
|
||||
"泰锡封",
|
||||
"婉静",
|
||||
"斡流",
|
||||
"嘉明",
|
||||
"闲云",
|
||||
"接笏",
|
||||
"侯章",
|
||||
"陇舟",
|
||||
"知贵",
|
||||
"沙博尼耶",
|
||||
"遐庆",
|
||||
"嘉明阿婶",
|
||||
"叶德",
|
||||
"嘉明阿伯",
|
||||
"嘉明阿叔",
|
||||
"嘉明阿婆",
|
||||
"嘉明阿公",
|
||||
"风涟",
|
||||
"漱玉",
|
||||
"远黛",
|
||||
"远黛",
|
||||
"有些特别的鹤",
|
||||
"远黛",
|
||||
"陷入迷惑的小猫",
|
||||
"开始制作",
|
||||
"等待海灯节开幕",
|
||||
"嘉明阿婶",
|
||||
"嘉明阿伯",
|
||||
"嘉明阿叔",
|
||||
"嘉明阿婆",
|
||||
"嘉明阿公",
|
||||
"问柳",
|
||||
"庆继",
|
||||
"宝泰",
|
||||
"砥心",
|
||||
"漱玉",
|
||||
"桌上的机关",
|
||||
"绍祖",
|
||||
"没有署名的信",
|
||||
"狐狸",
|
||||
"野鹤",
|
||||
"清尘",
|
||||
"清尘",
|
||||
"远黛",
|
||||
"浮锦",
|
||||
"谁人的笔记",
|
||||
"赤井",
|
||||
"马里",
|
||||
"渚春",
|
||||
"铁豆儿",
|
||||
"铁明",
|
||||
"尊尼",
|
||||
"红鱼",
|
||||
"灵渊",
|
||||
"喂食",
|
||||
"「慢悠悠仙像」",
|
||||
"黑帮群演",
|
||||
"铁船儿",
|
||||
"沃克",
|
||||
"青夜",
|
||||
"奇怪的商人",
|
||||
"坐地虎",
|
||||
"明镜",
|
||||
"铁锤儿",
|
||||
"铁瓜儿",
|
||||
"毅钧",
|
||||
"盘枝蛇",
|
||||
"敲敲门",
|
||||
"铁扇儿",
|
||||
"铁门儿",
|
||||
"铁船儿",
|
||||
"遐庆",
|
||||
"文寻",
|
||||
"卷舒",
|
||||
"枕鸢",
|
||||
"接笏",
|
||||
"侯章",
|
||||
"叶德",
|
||||
"桌上散落的信件",
|
||||
"桌上散落的笔记",
|
||||
"厄舍",
|
||||
"莉安",
|
||||
"韦斯",
|
||||
"维格尔",
|
||||
"时装周宣传画报",
|
||||
"进入千织屋",
|
||||
"艾洛迪",
|
||||
"吉莲",
|
||||
"梅里埃",
|
||||
"吉娜",
|
||||
"阿莫瑞",
|
||||
"马洛尼",
|
||||
"贝努瓦",
|
||||
"邦妮",
|
||||
"路边闲聊的人",
|
||||
"路边闲聊的人",
|
||||
"路边闲聊的人",
|
||||
"路边闲聊的人",
|
||||
"莱提西娅",
|
||||
"门外的顾客",
|
||||
"书柜上的纸张",
|
||||
"本子上的备忘录",
|
||||
"桌上的笔记",
|
||||
"科伦汀",
|
||||
"热情的记者",
|
||||
"兴奋的记者",
|
||||
"西里",
|
||||
"雅各",
|
||||
"吉拉尔",
|
||||
"调查笔记",
|
||||
"调查旧作",
|
||||
"调查正式剧本",
|
||||
"调查「原剧本」",
|
||||
"调查手稿",
|
||||
"艾洛迪",
|
||||
"贝努瓦",
|
||||
"观察人群",
|
||||
"观察人群",
|
||||
"观察人群",
|
||||
"观察人群",
|
||||
"留云借风真君…?",
|
||||
"阿泰菲",
|
||||
"弗雷瑞斯",
|
||||
"德佑",
|
||||
"芙里达",
|
||||
"「雪糕」",
|
||||
"「团团灰」",
|
||||
"「阿呆」",
|
||||
"「兔叽」",
|
||||
"「大桔骑士」",
|
||||
"瓦乐瑞娜",
|
||||
"谢妮",
|
||||
"亡国的美奈姬·卷五",
|
||||
"少女薇拉的忧郁·卷一",
|
||||
"少女薇拉的忧郁·卷二",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
@@ -14,40 +14,48 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Assets\*.jpg" />
|
||||
<None Remove="Assets\*.png" />
|
||||
<None Remove="Assets\*.ico" />
|
||||
<None Remove="Assets\Fonts\*.ttf" />
|
||||
<None Remove="Assets\Highlighting\*.xshd" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="Assets\*.jpg" />
|
||||
<Resource Include="Assets\*.png" />
|
||||
<Content Include="Assets\*.ico" />
|
||||
<Resource Include="Assets\*.ico" />
|
||||
<Resource Include="Assets\Fonts\*.ttf" />
|
||||
<Resource Include="Assets\Highlighting\*.xshd" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="H.InputSimulator" Version="1.4.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.16.1" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.16.1" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" Version="1.17.1" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.17.1" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.77" />
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.cuda118_cudnn86_tr85_sm86_89" Version="2.5.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR.Models.Online" Version="2.7.0.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBox.Wpf" Version="1.1.0" />
|
||||
<PackageReference Include="Vanara.PInvoke.NtDll" Version="3.4.17" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="3.4.17" />
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="3.4.17" />
|
||||
<PackageReference Include="WPF-UI" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="YoloV8" Version="2.0.1" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="YoloV8.Gpu" Version="2.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
|
||||
@@ -63,7 +71,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="GameTask\TaskContext.cs">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</Compile>
|
||||
<Compile Update="View\MaskWindow.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
@@ -77,9 +85,36 @@
|
||||
<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\cityMap2048Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\combined_image_2048_lim[quick].png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\combined_image_lim[quick].png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMap100Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMap1024Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMapZoomOut1024.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\map_sd1024.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Common\avatar_side_classify_sim.onnx">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Domain\bgi_tree.onnx">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -89,9 +124,6 @@
|
||||
<None Update="Assets\Model\Fish\bgi_fish.onnx">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Fish\label.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_det\inference.pdiparams">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -164,6 +196,15 @@
|
||||
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\flashing maintenance mek bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\sour bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\sugardew bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\lift_rod.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -290,6 +331,9 @@
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\退出挑战.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\tcg_character_card.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoPick\Assets\1920x1080\F.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -299,6 +343,24 @@
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\collect.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\comfirm_btn1.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\comfirm_btn2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\hangout_selected.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\hangout_unselected.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\primogem.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\re.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -308,7 +370,22 @@
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_explore.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\menu.png">
|
||||
<None Update="GameTask\AutoSkip\Assets\hangout.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\blue_track_point_28x.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_black_cancel.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_online_no.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_online_yes.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\paimon_menu.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_option.png">
|
||||
@@ -320,6 +397,12 @@
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\stop_auto.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\submit_goods.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\submit_icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\character_guide.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -338,6 +421,66 @@
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\TheBoonOfTheElderTree.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_black_confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_white_cancel.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_white_confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\collect.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\comfirm_btn1.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\comfirm_btn2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_daily_reward.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_explore.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_option.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\paimon_menu.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\page_close.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\primogem.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\re.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\stop_auto.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\submit_icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\ui_left_top_cook_icon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\ui_lt_cook_icon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\yellow_track_point_28x.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\GameLoading\Assets\1920x1080\welkin_moon_logo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\Domain.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -359,6 +502,9 @@
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapScaleButton.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapUndergroundSwitchButton.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\PortableWaypoint.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -374,6 +520,9 @@
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\TeleportWaypoint.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickSereniteaPot\Assets\1920x1080\SereniteaPotIcon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\1.四神挂机[推荐].txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -383,6 +532,9 @@
|
||||
<None Update="User\AutoFight\2.宵宫队[请看文件内说明].txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\群友分享\*.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\1.莫娜砂糖琴.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -401,7 +553,7 @@
|
||||
<None Update="User\AutoGeniusInvokation\6.皇女科莱莫娜.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\7.莫娜皇女白术.txt">
|
||||
<None Update="User\AutoGeniusInvokation\7.莫娜白术皇女.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\8.雷神柯莱刻晴[推荐].txt">
|
||||
@@ -419,6 +571,18 @@
|
||||
<None Update="User\AutoGeniusInvokation\a.[惊喜牌组]黄衫.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\default_pause_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\select_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\pause_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\avatar_macro.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\pick_black_lists.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -428,8 +592,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="GameTask\AutoDomain\Model\" />
|
||||
<Folder Include="GameTask\Common\Exception\" />
|
||||
<Folder Include="GameTask\Common\Element\Assets\MapPoint\" />
|
||||
<Folder Include="View\Controls\WpfUi\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,135 +1,173 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
using BetterGenshinImpact.GameTask.AutoPick;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip;
|
||||
using BetterGenshinImpact.GameTask.AutoWood;
|
||||
using BetterGenshinImpact.GameTask.QuickTeleport;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using Fischless.GameCapture;
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
using BetterGenshinImpact.GameTask.AutoWood;
|
||||
using BetterGenshinImpact.GameTask.QuickTeleport;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 更好的原神配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class AllConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 更好的原神配置
|
||||
/// 窗口捕获的方式
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class AllConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private string _captureMode = CaptureModes.BitBlt.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 详细的错误日志
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _detailedErrorLogs;
|
||||
|
||||
/// <summary>
|
||||
/// 不展示新版本提示的最新版本
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _notShowNewVersionNoticeEndVersion = "";
|
||||
|
||||
/// <summary>
|
||||
/// 触发器触发频率(ms)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _triggerInterval = 50;
|
||||
|
||||
/// <summary>
|
||||
/// WGC使用位图缓存
|
||||
/// 高帧率情况下,可能会导致卡顿
|
||||
/// 云原神可能会出现黑屏
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _wgcUseBitmapCache = true;
|
||||
|
||||
/// <summary>
|
||||
/// 推理使用的设备
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _inferenceDevice = "CPU";
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// </summary>
|
||||
public MaskWindowConfig MaskWindowConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 通用配置
|
||||
/// </summary>
|
||||
public CommonConfig CommonConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 原神启动配置
|
||||
/// </summary>
|
||||
public GenshinStartConfig GenshinStartConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动拾取配置
|
||||
/// </summary>
|
||||
public AutoPickConfig AutoPickConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动剧情配置
|
||||
/// </summary>
|
||||
public AutoSkipConfig AutoSkipConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动钓鱼配置
|
||||
/// </summary>
|
||||
public AutoFishingConfig AutoFishingConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 快速传送配置
|
||||
/// </summary>
|
||||
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动烹饪配置
|
||||
/// </summary>
|
||||
public AutoCookConfig AutoCookConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动打牌配置
|
||||
/// </summary>
|
||||
public AutoGeniusInvokationConfig AutoGeniusInvokationConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动伐木配置
|
||||
/// </summary>
|
||||
public AutoWoodConfig AutoWoodConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动战斗配置
|
||||
/// </summary>
|
||||
public AutoFightConfig AutoFightConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动秘境配置
|
||||
/// </summary>
|
||||
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 脚本类配置
|
||||
/// </summary>
|
||||
public MacroConfig MacroConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 快捷键配置
|
||||
/// </summary>
|
||||
public HotKeyConfig HotKeyConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 通知配置
|
||||
/// </summary>
|
||||
public NotificationConfig NotificationConfig { get; set; } = new();
|
||||
|
||||
[JsonIgnore]
|
||||
public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
public void InitEvent()
|
||||
{
|
||||
/// <summary>
|
||||
/// 窗口捕获的方式
|
||||
/// </summary>
|
||||
[ObservableProperty] private string _captureMode = CaptureModes.BitBlt.ToString();
|
||||
PropertyChanged += OnAnyPropertyChanged;
|
||||
MaskWindowConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
CommonConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
|
||||
|
||||
///// <summary>
|
||||
///// 窗口捕获帧数/触发器触发频率
|
||||
///// </summary>
|
||||
//[ObservableProperty] private int _frameRate = 30;
|
||||
|
||||
/// <summary>
|
||||
/// 触发器触发频率(ms)
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _triggerInterval = 50;
|
||||
|
||||
/// <summary>
|
||||
/// 不展示新版本提示的最新版本
|
||||
/// </summary>
|
||||
[ObservableProperty] private string _notShowNewVersionNoticeEndVersion = "";
|
||||
|
||||
/// <summary>
|
||||
/// 详细的错误日志
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _detailedErrorLogs = false;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// </summary>
|
||||
public MaskWindowConfig MaskWindowConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 原神启动配置
|
||||
/// </summary>
|
||||
public GenshinStartConfig GenshinStartConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动拾取配置
|
||||
/// </summary>
|
||||
public AutoPickConfig AutoPickConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动剧情配置
|
||||
/// </summary>
|
||||
public AutoSkipConfig AutoSkipConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动钓鱼配置
|
||||
/// </summary>
|
||||
public AutoFishingConfig AutoFishingConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动钓鱼配置
|
||||
/// </summary>
|
||||
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动打牌配置
|
||||
/// </summary>
|
||||
public AutoGeniusInvokationConfig AutoGeniusInvokationConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动伐木配置
|
||||
/// </summary>
|
||||
public AutoWoodConfig AutoWoodConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动战斗配置
|
||||
/// </summary>
|
||||
public AutoFightConfig AutoFightConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动秘境配置
|
||||
/// </summary>
|
||||
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 脚本类配置
|
||||
/// </summary>
|
||||
public MacroConfig MacroConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 快捷键配置
|
||||
/// </summary>
|
||||
public HotKeyConfig HotKeyConfig { get; set; } = new();
|
||||
|
||||
[JsonIgnore] public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
public void InitEvent()
|
||||
{
|
||||
this.PropertyChanged += OnAnyPropertyChanged;
|
||||
MaskWindowConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
|
||||
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
{
|
||||
GameTaskManager.RefreshTriggerConfigs();
|
||||
OnAnyChangedAction?.Invoke();
|
||||
}
|
||||
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
{
|
||||
GameTaskManager.RefreshTriggerConfigs();
|
||||
OnAnyChangedAction?.Invoke();
|
||||
}
|
||||
|
||||
public void OnNotificationPropertyChanged(object? sender, PropertyChangedEventArgs args)
|
||||
{
|
||||
NotificationService.Instance().RefreshNotifiers();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class CommonConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用遮罩窗口
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _screenshotEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// UID遮盖是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _screenshotUidCoverEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 退出时最小化至托盘
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _exitToTray;
|
||||
}
|
||||
@@ -4,24 +4,38 @@ using System;
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 原神启动配置
|
||||
/// 原神启动配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class GenshinStartConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 自动点击月卡
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoClickBlessingOfTheWelkinMoonEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 联动启动原神本体
|
||||
/// 自动进入游戏(开门)
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _linkedStartEnabled = true;
|
||||
[ObservableProperty]
|
||||
private bool _autoEnterGameEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 原神安装路径
|
||||
/// 原神启动参数
|
||||
/// </summary>
|
||||
[ObservableProperty] private string _installPath = "";
|
||||
[ObservableProperty]
|
||||
private string _genshinStartArgs = "";
|
||||
|
||||
/// <summary>
|
||||
/// 原神启动参数
|
||||
/// 原神安装路径
|
||||
/// </summary>
|
||||
[ObservableProperty] private string _genshinStartArgs = "";
|
||||
}
|
||||
[ObservableProperty]
|
||||
private string _installPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// 联动启动原神本体
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _linkedStartEnabled = true;
|
||||
}
|
||||
@@ -5,11 +5,9 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
public class Global
|
||||
{
|
||||
public static string Version { get; } = "0.21.3";
|
||||
public static string Version { get; } = "0.30.2";
|
||||
|
||||
public static string StartUpPath { get; private set; } = AppContext.BaseDirectory;
|
||||
|
||||
public static string AppPath { get; private set; } = Absolute("BetterGI.exe");
|
||||
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
|
||||
|
||||
public static string Absolute(string relativePath)
|
||||
{
|
||||
@@ -19,15 +17,12 @@ public class Global
|
||||
public static string? ReadAllTextIfExist(string relativePath)
|
||||
{
|
||||
var path = Absolute(relativePath);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return File.ReadAllText(path);
|
||||
}
|
||||
if (File.Exists(path)) return File.ReadAllText(path);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新获取到的版本号与当前版本号比较,判断是否为新版本
|
||||
/// 新获取到的版本号与当前版本号比较,判断是否为新版本
|
||||
/// </summary>
|
||||
/// <param name="currentVersion">新获取到的版本</param>
|
||||
/// <returns></returns>
|
||||
@@ -37,35 +32,34 @@ public class Global
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新获取到的版本号与当前版本号比较,判断是否为新版本
|
||||
/// 新获取到的版本号与当前版本号比较,判断是否为新版本
|
||||
/// </summary>
|
||||
/// <param name="oldVersion">老版本</param>
|
||||
/// <param name="currentVersion">新获取到的版本</param>
|
||||
/// <returns>是否需要更新</returns>
|
||||
public static bool IsNewVersion(string oldVersion, string currentVersion)
|
||||
{
|
||||
var currentVersionArr = oldVersion.Split('.');
|
||||
var newVersionArr = currentVersion.Split('.');
|
||||
if (currentVersionArr.Length != newVersionArr.Length)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Version oldVersionX = new(oldVersion);
|
||||
Version currentVersionX = new(currentVersion);
|
||||
|
||||
for (var i = 0; i < currentVersionArr.Length; i++)
|
||||
{
|
||||
|
||||
if (int.Parse(currentVersionArr[i]) > int.Parse(newVersionArr[i]))
|
||||
{
|
||||
// 不需要更新
|
||||
return false;
|
||||
}
|
||||
|
||||
if (int.Parse(currentVersionArr[i]) < int.Parse(newVersionArr[i]))
|
||||
{
|
||||
if (currentVersionX > oldVersionX)
|
||||
// 需要更新
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
///
|
||||
}
|
||||
|
||||
// 不需要更新
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void WriteAllText(string relativePath, string blackListJson)
|
||||
{
|
||||
var path = Absolute(relativePath);
|
||||
File.WriteAllText(path, blackListJson);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,165 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Model;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 格式必须是 快捷键 与 快捷键Type
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class HotKeyConfig : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string _bgiEnabledHotkey = "F11";
|
||||
[ObservableProperty]
|
||||
private string _autoTrackHotkey = "";
|
||||
|
||||
[ObservableProperty] private string _autoPickEnabledHotkey = "F1";
|
||||
[ObservableProperty]
|
||||
private string _autoTrackHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty] private string _autoSkipEnabledHotkey = "F2";
|
||||
[ObservableProperty]
|
||||
private string _autoDomainHotkey = "";
|
||||
|
||||
[ObservableProperty] private string _autoFishingEnabledHotkey = "";
|
||||
[ObservableProperty]
|
||||
private string _autoDomainHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty] private string _turnAroundHotkey = "F3";
|
||||
[ObservableProperty]
|
||||
private string _autoFightHotkey = "";
|
||||
|
||||
[ObservableProperty] private string _enhanceArtifactHotkey = "F4";
|
||||
[ObservableProperty]
|
||||
private string _autoFightHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty] private string _quickBuyHotkey = "";
|
||||
[ObservableProperty]
|
||||
private string _autoFishingEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty] private string _autoGeniusInvokation = "";
|
||||
[ObservableProperty]
|
||||
private string _autoFishingEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty] private string _autoWoodHotkey = "";
|
||||
[ObservableProperty]
|
||||
private string _autoGeniusInvokationHotkey = "";
|
||||
|
||||
[ObservableProperty] private string _autoFightHotkey = "";
|
||||
[ObservableProperty]
|
||||
private string _autoGeniusInvokationHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty] private string _autoDomainHotkey = "";
|
||||
}
|
||||
[ObservableProperty]
|
||||
private string _autoPickEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoPickEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoSkipEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoSkipEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoSkipHangoutEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoSkipHangoutEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoWoodHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoWoodHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _bgiEnabledHotkey = "F11";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _bgiEnabledHotkeyType = HotKeyTypeEnum.GlobalRegister.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _enhanceArtifactHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _enhanceArtifactHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickBuyHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickBuyHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickSereniteaPotHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickSereniteaPotHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickTeleportEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickTeleportEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 快捷传送触发
|
||||
[ObservableProperty]
|
||||
private string _quickTeleportTickHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 截图
|
||||
[ObservableProperty]
|
||||
private string _takeScreenshotHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _takeScreenshotHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _turnAroundHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _turnAroundHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 点击确认按钮
|
||||
[ObservableProperty]
|
||||
private string _clickGenshinConfirmButtonHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _clickGenshinConfirmButtonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 点击取消按钮
|
||||
[ObservableProperty]
|
||||
private string _clickGenshinCancelButtonHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _clickGenshinCancelButtonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 一键战斗宏
|
||||
[ObservableProperty]
|
||||
private string _oneKeyFightHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _oneKeyFightHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 地图路线录制开始/停止
|
||||
[ObservableProperty]
|
||||
private string _mapPosRecordHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _mapPosRecordHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 活动音游开始/停止
|
||||
[ObservableProperty]
|
||||
private string _autoMusicGameHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoMusicGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 自动寻路
|
||||
[ObservableProperty]
|
||||
private string _autoTrackPathHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoTrackPathHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 测试
|
||||
[ObservableProperty]
|
||||
private string _test1Hotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _test1HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
}
|
||||
@@ -1,39 +1,70 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class MacroConfig : ObservableObject
|
||||
{
|
||||
[Serializable]
|
||||
public partial class MacroConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 长按空格变空格连发
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _spacePressHoldToContinuationEnabled = false;
|
||||
/// <summary>
|
||||
/// 高延迟下强化的额外等待时间
|
||||
/// https://github.com/babalae/better-genshin-impact/issues/9
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _enhanceWaitDelay;
|
||||
|
||||
/// <summary>
|
||||
/// 空格连发时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _spaceFireInterval = 100;
|
||||
/// <summary>
|
||||
/// F连发时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _fFireInterval = 100;
|
||||
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _fPressHoldToContinuationEnabled = false;
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _fPressHoldToContinuationEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// F连发时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _fFireInterval = 100;
|
||||
/// <summary>
|
||||
/// 转圈圈时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _runaroundInterval;
|
||||
|
||||
/// <summary>
|
||||
/// 高延迟下强化的额外等待时间
|
||||
/// https://github.com/babalae/better-genshin-impact/issues/9
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _enhanceWaitDelay = 0;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 转圈圈鼠标右移长度
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _runaroundMouseXInterval = 500;
|
||||
|
||||
/// <summary>
|
||||
/// 空格连发时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _spaceFireInterval = 100;
|
||||
|
||||
/// <summary>
|
||||
/// 长按空格变空格连发
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _spacePressHoldToContinuationEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 一键战斗宏启用状态
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _combatMacroEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 一键战斗宏快捷键模式
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _combatMacroHotkeyMode = OneKeyFightTask.HoldOnMode;
|
||||
|
||||
/// <summary>
|
||||
/// 一键战斗宏优先级
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _combatMacroPriority = 1;
|
||||
}
|
||||
@@ -1,65 +1,81 @@
|
||||
using System;
|
||||
using System.Text.Json.Serialization;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using Point = System.Windows.Point;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class MaskWindowConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// 控件是否锁定(拖拽移动等)
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class MaskWindowConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用遮罩窗口
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _maskEnabled = true;
|
||||
[ObservableProperty]
|
||||
private bool _controlLocked = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否在遮罩窗口上显示识别结果
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _displayRecognitionResultsOnMask = true;
|
||||
/// <summary>
|
||||
/// 方位提示是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _directionsEnabled;
|
||||
|
||||
///// <summary>
|
||||
///// 显示遮罩窗口边框
|
||||
///// </summary>
|
||||
//[ObservableProperty] private bool _showMaskBorder = false;
|
||||
/// <summary>
|
||||
/// 是否在遮罩窗口上显示识别结果
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _displayRecognitionResultsOnMask = true;
|
||||
|
||||
/// <summary>
|
||||
/// 显示日志窗口
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _showLogBox = true;
|
||||
/// <summary>
|
||||
/// 日志窗口位置与大小
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private Rect _logBoxLocation;
|
||||
|
||||
/// <summary>
|
||||
/// 日志窗口位置与大小
|
||||
/// </summary>
|
||||
[ObservableProperty] private Rect _logBoxLocation = new();
|
||||
/// <summary>
|
||||
/// 是否启用遮罩窗口
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _maskEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 控件是否锁定(拖拽移动等)
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _controlLocked = true;
|
||||
///// <summary>
|
||||
///// 显示遮罩窗口边框
|
||||
///// </summary>
|
||||
//[ObservableProperty] private bool _showMaskBorder = false;
|
||||
|
||||
/// <summary>
|
||||
/// 显示日志窗口
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _showLogBox = true;
|
||||
|
||||
/// <summary>
|
||||
/// UID遮盖是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _uidCoverEnabled = false;
|
||||
/// <summary>
|
||||
/// 显示状态指示
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _showStatus = true;
|
||||
|
||||
/// <summary>
|
||||
/// 1080p下UID遮盖的位置与大小
|
||||
/// </summary>
|
||||
public Rect UidCoverRect { get; set; } = new(1695, 1052, 168, 22);
|
||||
/// <summary>
|
||||
/// UID遮盖是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _uidCoverEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 方位提示是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _directionsEnabled = false;
|
||||
/// <summary>
|
||||
/// 1080p下UID遮盖的位置与大小
|
||||
/// </summary>
|
||||
public Rect UidCoverRect { get; set; } = new(1690, 1052, 173, 22);
|
||||
|
||||
public System.Windows.Point EastPoint { get; set; } = new(274, 109);
|
||||
public System.Windows.Point SouthPoint { get; set; } = new(150, 233);
|
||||
public System.Windows.Point WestPoint { get; set; } = new(32, 109);
|
||||
public System.Windows.Point NorthPoint { get; set; } = new(150, -9);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 1080p下UID遮盖的位置与大小
|
||||
/// </summary>
|
||||
public Rect UidCoverRightBottomRect { get; set; } = new(1920 - 1690, 1080 - 1052, 173, 22);
|
||||
|
||||
public Point EastPoint { get; set; } = new(274, 109);
|
||||
public Point SouthPoint { get; set; } = new(150, 233);
|
||||
public Point WestPoint { get; set; } = new(32, 109);
|
||||
public Point NorthPoint { get; set; } = new(150, -9);
|
||||
}
|
||||
@@ -6,11 +6,6 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
[Obsolete("Replace with original OpenCvSharp.Rect")]
|
||||
public class RectConfig
|
||||
{
|
||||
public int X { get; set; }
|
||||
public int Y { get; set; }
|
||||
public int Width { get; set; }
|
||||
public int Height { get; set; }
|
||||
|
||||
public RectConfig()
|
||||
{
|
||||
}
|
||||
@@ -23,8 +18,13 @@ public class RectConfig
|
||||
Height = height;
|
||||
}
|
||||
|
||||
public int X { get; set; }
|
||||
public int Y { get; set; }
|
||||
public int Width { get; set; }
|
||||
public int Height { get; set; }
|
||||
|
||||
public Rect ToRect()
|
||||
{
|
||||
return new Rect(X, Y, Width, Height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,38 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Gma.System.MouseKeyHook;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Forms;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.QuickTeleport;
|
||||
using Vanara.PInvoke;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
namespace BetterGenshinImpact.Core;
|
||||
|
||||
public class MouseKeyMonitor
|
||||
{
|
||||
private IntPtr _hWnd;
|
||||
|
||||
private IKeyboardMouseEvents? _globalHook;
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
private readonly Timer _fTimer = new();
|
||||
|
||||
//private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// 长按空格变空格连发
|
||||
/// 长按空格变空格连发
|
||||
/// </summary>
|
||||
private readonly System.Timers.Timer _spaceTimer = new();
|
||||
private readonly Timer _spaceTimer = new();
|
||||
|
||||
private DateTime _firstFKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
private readonly System.Timers.Timer _fTimer = new();
|
||||
|
||||
/// <summary>
|
||||
/// DateTime.MaxValue 代表没有按下
|
||||
/// DateTime.MaxValue 代表没有按下
|
||||
/// </summary>
|
||||
private DateTime _firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
private DateTime _firstFKeyDownTime = DateTime.MaxValue;
|
||||
private IKeyboardMouseEvents? _globalHook;
|
||||
private IntPtr _hWnd;
|
||||
|
||||
public void Subscribe(IntPtr gameHandle)
|
||||
{
|
||||
@@ -40,10 +40,10 @@ public class MouseKeyMonitor
|
||||
// Note: for the application hook, use the Hook.AppEvents() instead
|
||||
_globalHook = Hook.GlobalEvents();
|
||||
|
||||
|
||||
_globalHook.KeyDown += GlobalHookKeyDown;
|
||||
_globalHook.KeyUp += GlobalHookKeyUp;
|
||||
//_globalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
_globalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
//_globalHook.KeyPress += GlobalHookKeyPress;
|
||||
|
||||
_firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
@@ -56,10 +56,13 @@ public class MouseKeyMonitor
|
||||
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_F); };
|
||||
}
|
||||
|
||||
|
||||
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
//Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
|
||||
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
|
||||
|
||||
// 热键按下事件
|
||||
HotKeyDown(sender, e);
|
||||
|
||||
if (e.KeyCode == Keys.Space)
|
||||
{
|
||||
if (_firstSpaceKeyDownTime == DateTime.MaxValue)
|
||||
@@ -70,12 +73,8 @@ public class MouseKeyMonitor
|
||||
{
|
||||
var timeSpan = DateTime.Now - _firstSpaceKeyDownTime;
|
||||
if (timeSpan.TotalMilliseconds > 300 && TaskContext.Instance().Config.MacroConfig.SpacePressHoldToContinuationEnabled)
|
||||
{
|
||||
if (!_spaceTimer.Enabled)
|
||||
{
|
||||
_spaceTimer.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (e.KeyCode == Keys.F)
|
||||
@@ -88,19 +87,19 @@ public class MouseKeyMonitor
|
||||
{
|
||||
var timeSpan = DateTime.Now - _firstFKeyDownTime;
|
||||
if (timeSpan.TotalMilliseconds > 200 && TaskContext.Instance().Config.MacroConfig.FPressHoldToContinuationEnabled)
|
||||
{
|
||||
if (!_fTimer.Enabled)
|
||||
{
|
||||
_fTimer.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
|
||||
{
|
||||
//Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
|
||||
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
|
||||
|
||||
// 热键松开事件
|
||||
HotKeyUp(sender, e);
|
||||
|
||||
if (e.KeyCode == Keys.Space)
|
||||
{
|
||||
if (_firstSpaceKeyDownTime != DateTime.MaxValue)
|
||||
@@ -123,20 +122,38 @@ public class MouseKeyMonitor
|
||||
}
|
||||
}
|
||||
|
||||
private void HotKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (KeyboardHook.AllKeyboardHooks.TryGetValue(e.KeyCode, out var hook)) hook.KeyDown(sender, e);
|
||||
}
|
||||
|
||||
private void HotKeyUp(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (KeyboardHook.AllKeyboardHooks.TryGetValue(e.KeyCode, out var hook)) hook.KeyUp(sender, e);
|
||||
}
|
||||
|
||||
//private void GlobalHookKeyPress(object? sender, KeyPressEventArgs e)
|
||||
//{
|
||||
// Debug.WriteLine("KeyPress: \t{0}", e.KeyChar);
|
||||
//}
|
||||
|
||||
//private void GlobalHookMouseDownExt(object? sender, MouseEventExtArgs e)
|
||||
//{
|
||||
// Debug.WriteLine("MouseDown: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
private void GlobalHookMouseDownExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseDown: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
|
||||
// // uncommenting the following line will suppress the middle mouse button click
|
||||
// if (e.Button == MouseButtons.Left)
|
||||
// {
|
||||
// }
|
||||
//}
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
hook.MouseDown(sender, e);
|
||||
}
|
||||
|
||||
private void GlobalHookMouseUpExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseUp: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
hook.MouseUp(sender, e);
|
||||
}
|
||||
|
||||
public void Unsubscribe()
|
||||
{
|
||||
@@ -144,9 +161,10 @@ public class MouseKeyMonitor
|
||||
{
|
||||
_globalHook.KeyDown -= GlobalHookKeyDown;
|
||||
_globalHook.KeyUp -= GlobalHookKeyUp;
|
||||
//_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
|
||||
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
|
||||
_globalHook.MouseUpExt -= GlobalHookMouseUpExt;
|
||||
//_globalHook.KeyPress -= GlobalHookKeyPress;
|
||||
_globalHook.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Drawing;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleOCR;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
@@ -11,4 +10,4 @@ public interface IOcrService
|
||||
public string OcrWithoutDetector(Mat mat);
|
||||
|
||||
public PaddleOcrResult OcrResult(Mat mat);
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Graphics.Imaging;
|
||||
using Windows.Media.Ocr;
|
||||
using Windows.Storage.Streams;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// : IOcrService
|
||||
/// </summary>
|
||||
[Obsolete]
|
||||
public class MediaOcrService
|
||||
{
|
||||
private static readonly OcrEngine Engine =
|
||||
OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("zh-Hans-CN"));
|
||||
|
||||
/// <summary>
|
||||
/// 图片太小的时候这个方法会报错,无法判断图片类型
|
||||
/// BitmapDecoder (0x88982F50)
|
||||
/// https://github.com/microsoft/CsWinRT/issues/682
|
||||
/// </summary>
|
||||
/// <param name="bitmap"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<OcrResult?> OcrAsync(Bitmap bitmap)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stream = new InMemoryRandomAccessStream();
|
||||
bitmap.Save(stream.AsStream(), ImageFormat.Png);
|
||||
var decoder = BitmapDecoder.CreateAsync(stream).GetAwaiter().GetResult();
|
||||
var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
|
||||
var ocrResult = await Engine.RecognizeAsync(softwareBitmap);
|
||||
softwareBitmap.Dispose();
|
||||
return ocrResult;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.WriteLine(e.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<OcrResult?> OcrAsyncByBytes(Bitmap bitmap)
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = BitmapToByte(bitmap);
|
||||
var stream = new MemoryStream(bytes);
|
||||
var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream());
|
||||
var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
|
||||
var ocrResult = await Engine.RecognizeAsync(softwareBitmap);
|
||||
softwareBitmap.Dispose();
|
||||
return ocrResult;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.WriteLine(e.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将BitMap转换成bytes数组
|
||||
/// </summary>
|
||||
/// <param name="bitmap">要转换的图像</param>
|
||||
/// <returns></returns>
|
||||
private byte[] BitmapToByte(Bitmap bitmap)
|
||||
{
|
||||
// 1.先将BitMap转成内存流
|
||||
var ms = new MemoryStream();
|
||||
bitmap.Save(ms, ImageFormat.Bmp);
|
||||
ms.Seek(0, SeekOrigin.Begin);
|
||||
// 2.再将内存流转成byte[]并返回
|
||||
byte[] bytes = new byte[ms.Length];
|
||||
var _ = ms.Read(bytes, 0, bytes.Length);
|
||||
ms.Dispose();
|
||||
return bytes;
|
||||
}
|
||||
|
||||
//public async Task<OcrResult?> OcrAsyncByFile(Bitmap bitmap)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "temp.png");
|
||||
// bitmap.Save(path);
|
||||
// var storageFile = await StorageFile.GetFileFromPathAsync(path);
|
||||
// IRandomAccessStream randomAccessStream = await storageFile.OpenReadAsync();
|
||||
// var decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
|
||||
// var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
|
||||
// var ocrResult = await Engine.RecognizeAsync(softwareBitmap);
|
||||
// softwareBitmap.Dispose();
|
||||
// return ocrResult;
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine(e.Message);
|
||||
// return null;
|
||||
// }
|
||||
//}
|
||||
|
||||
public string Ocr(Bitmap bitmap)
|
||||
{
|
||||
var ocrResult = OcrAsyncByBytes(bitmap).GetAwaiter().GetResult();
|
||||
|
||||
if (ocrResult == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine("MediaOcr结果: " + ocrResult.Text);
|
||||
return ocrResult.Text;
|
||||
}
|
||||
}
|
||||
|
||||
public string Ocr(Mat mat)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,18 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR
|
||||
{
|
||||
public class OcrFactory
|
||||
{
|
||||
public static IOcrService Create(OcrEngineTypes type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case OcrEngineTypes.Paddle:
|
||||
return new PaddleOcrService();
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(type), type, null);
|
||||
}
|
||||
}
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
// public static IOcrService Media = Create(OcrEngineTypes.Media);
|
||||
public static IOcrService Paddle = Create(OcrEngineTypes.Paddle);
|
||||
public class OcrFactory
|
||||
{
|
||||
// public static IOcrService Media = Create(OcrEngineTypes.Media);
|
||||
public static IOcrService Paddle { get; } = Create(OcrEngineTypes.Paddle);
|
||||
|
||||
public static IOcrService Create(OcrEngineTypes type)
|
||||
{
|
||||
return type switch
|
||||
{
|
||||
OcrEngineTypes.Paddle => new PaddleOcrService(),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleOCR;
|
||||
using static System.Net.Mime.MediaTypeNames;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public static class PaddleOcrResultExtension
|
||||
{
|
||||
public static bool RegionHasText(this PaddleOcrResult result, string text)
|
||||
public static bool RegionHasText(this PaddleOcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (var item in result.Regions)
|
||||
foreach (ref readonly PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.Contains(text))
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -28,36 +24,22 @@ public static class PaddleOcrResultExtension
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public static PaddleOcrResultRegion FindRegionByText(this PaddleOcrResult result, string text)
|
||||
public static PaddleOcrResultRegion FindRegionByText(this PaddleOcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (var item in result.Regions)
|
||||
foreach (ref readonly PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.Contains(text))
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
return new PaddleOcrResultRegion();
|
||||
return default;
|
||||
}
|
||||
|
||||
//public static RotatedRect FindRotatedRectByText(this PaddleOcrResult result, string text)
|
||||
//{
|
||||
// foreach (var item in result.Regions)
|
||||
// {
|
||||
// if (item.Text.Contains(text))
|
||||
// {
|
||||
// return item.Rect;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return new RotatedRect();
|
||||
//}
|
||||
|
||||
public static Rect FindRectByText(this PaddleOcrResult result, string text)
|
||||
{
|
||||
foreach (var item in result.Regions)
|
||||
foreach (ref PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.Contains(text))
|
||||
{
|
||||
@@ -65,7 +47,7 @@ public static class PaddleOcrResultExtension
|
||||
}
|
||||
}
|
||||
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableList(this PaddleOcrResult result, Pen? pen = null)
|
||||
@@ -82,4 +64,4 @@ public static class PaddleOcrResultExtension
|
||||
{
|
||||
return new PaddleOcrResultRect(region.Rect.BoundingRect(), region.Text, region.Score);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,26 +3,26 @@ using OpenCvSharp;
|
||||
using Sdcb.PaddleInference;
|
||||
using Sdcb.PaddleOCR;
|
||||
using Sdcb.PaddleOCR.Models;
|
||||
using SharpDX;
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using Path = System.IO.Path;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public class PaddleOcrService : IOcrService
|
||||
{
|
||||
private static readonly object locker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Usage:
|
||||
/// https://github.com/sdcb/PaddleSharp/blob/master/docs/ocr.md
|
||||
/// 模型列表:
|
||||
/// https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/doc/doc_ch/models_list.md
|
||||
/// Usage:
|
||||
/// https://github.com/sdcb/PaddleSharp/blob/master/docs/ocr.md
|
||||
/// 模型列表:
|
||||
/// https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/doc/doc_ch/models_list.md
|
||||
/// </summary>
|
||||
private readonly PaddleOcrAll _paddleOcrAll;
|
||||
|
||||
private static readonly object locker = new();
|
||||
|
||||
public PaddleOcrService()
|
||||
{
|
||||
var path = Global.Absolute("Assets\\Model\\PaddleOcr");
|
||||
@@ -30,10 +30,16 @@ public class PaddleOcrService : IOcrService
|
||||
var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
|
||||
var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
|
||||
var model = new FullOcrModel(localDetModel, localClsModel, localRecModel);
|
||||
_paddleOcrAll = new PaddleOcrAll(model, PaddleDevice.Onnx())
|
||||
Action<PaddleConfig> device = TaskContext.Instance().Config.InferenceDevice switch
|
||||
{
|
||||
"CPU" => PaddleDevice.Onnx(),
|
||||
"GPU" => PaddleDevice.Gpu(),
|
||||
_ => throw new InvalidEnumArgumentException("无效的推理设备")
|
||||
};
|
||||
_paddleOcrAll = new PaddleOcrAll(model, device)
|
||||
{
|
||||
AllowRotateDetection = false, /* 允许识别有角度的文字 */
|
||||
Enable180Classification = false, /* 允许识别旋转角度大于90度的文字 */
|
||||
Enable180Classification = false /* 允许识别旋转角度大于90度的文字 */
|
||||
};
|
||||
|
||||
// System.AccessViolationException
|
||||
@@ -50,11 +56,10 @@ public class PaddleOcrService : IOcrService
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
var stopwatch = new Stopwatch();
|
||||
stopwatch.Start();
|
||||
long startTime = Stopwatch.GetTimestamp();
|
||||
var result = _paddleOcrAll.Run(mat);
|
||||
stopwatch.Stop();
|
||||
Debug.WriteLine($"PaddleOcr 耗时 {stopwatch.ElapsedMilliseconds}ms 结果: {result.Text}");
|
||||
TimeSpan time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -68,4 +73,4 @@ public class PaddleOcrService : IOcrService
|
||||
return str;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public class BgiSessionOption : Singleton<BgiSessionOption>
|
||||
{
|
||||
public SessionOptions Options { get; set; } = TaskContext.Instance().Config.InferenceDevice switch
|
||||
{
|
||||
"CPU" => new SessionOptions(),
|
||||
"GPU" => SessionOptions.MakeSessionOptionWithCudaProvider(),
|
||||
_ => throw new InvalidEnumArgumentException("无效的推理设备")
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR
|
||||
{
|
||||
/// <summary>
|
||||
/// 文字识别推理(SVTR网络)
|
||||
/// </summary>
|
||||
public interface ITextInference
|
||||
{
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
|
||||
public string Inference(Mat mat);
|
||||
}
|
||||
/// <summary>
|
||||
/// 文字识别推理(SVTR网络)
|
||||
/// </summary>
|
||||
public interface ITextInference
|
||||
{
|
||||
public string Inference(Mat mat);
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
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;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
|
||||
/// <summary>
|
||||
/// 来自于 Yap 的拾取文字识别
|
||||
/// https://github.com/Alex-Beng/Yap
|
||||
/// 来自于 Yap 的拾取文字识别
|
||||
/// https://github.com/Alex-Beng/Yap
|
||||
/// </summary>
|
||||
public class PickTextInference : ITextInference
|
||||
{
|
||||
@@ -22,20 +27,13 @@ public class PickTextInference : ITextInference
|
||||
|
||||
public PickTextInference()
|
||||
{
|
||||
var options = new SessionOptions();
|
||||
var modelPath = Global.Absolute("Assets\\Model\\Yap\\model_training.onnx");
|
||||
if (!File.Exists(modelPath))
|
||||
{
|
||||
throw new FileNotFoundException("Yap模型文件不存在", modelPath);
|
||||
}
|
||||
if (!File.Exists(modelPath)) throw new FileNotFoundException("Yap模型文件不存在", modelPath);
|
||||
|
||||
_session = new InferenceSession(modelPath, options);
|
||||
_session = new InferenceSession(modelPath, BgiSessionOption.Instance.Options);
|
||||
|
||||
var wordJsonPath = Global.Absolute("Assets\\Model\\Yap\\index_2_word.json");
|
||||
if (!File.Exists(wordJsonPath))
|
||||
{
|
||||
throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
|
||||
}
|
||||
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
|
||||
|
||||
var json = File.ReadAllText(wordJsonPath);
|
||||
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ?? throw new Exception("index_2_word.json deserialize failed");
|
||||
@@ -43,52 +41,56 @@ public class PickTextInference : ITextInference
|
||||
|
||||
public string Inference(Mat mat)
|
||||
{
|
||||
var stopwatch = new Stopwatch();
|
||||
stopwatch.Start();
|
||||
// 将输入数据调整为 (1, 1, 32, 384) 形状的张量
|
||||
var reshapedInputData = ToTensorUnsafe(mat);
|
||||
long startTime = Stopwatch.GetTimestamp();
|
||||
// 将输入数据调整为 (1, 1, 32, 384) 形状的张量
|
||||
var reshapedInputData = ToTensorUnsafe(mat, out var owner);
|
||||
|
||||
// 创建输入 NamedOnnxValue
|
||||
var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor("input", reshapedInputData) };
|
||||
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
|
||||
|
||||
// 运行模型推理
|
||||
using var results = _session.Run(inputs);
|
||||
|
||||
// 获取输出数据
|
||||
var resultsArray = results.ToArray();
|
||||
var boxes = resultsArray[0].AsTensor<float>();
|
||||
|
||||
var ans = "";
|
||||
var lastWord = "";
|
||||
for (var i = 0; i < boxes.Dimensions[0]; i++)
|
||||
using (owner)
|
||||
{
|
||||
var maxIndex = 0;
|
||||
var maxValue = -1.0;
|
||||
for (var j = 0; j < _wordDictionary.Count; j++)
|
||||
{
|
||||
var value = boxes[i, 0, j];
|
||||
if (value > maxValue)
|
||||
{
|
||||
maxValue = value;
|
||||
maxIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
var word = _wordDictionary[maxIndex];
|
||||
if (word != lastWord && word != "|")
|
||||
{
|
||||
ans += word;
|
||||
}
|
||||
|
||||
lastWord = word;
|
||||
// 创建输入 NamedOnnxValue, 运行模型推理
|
||||
results = _session.Run([NamedOnnxValue.CreateFromTensor("input", reshapedInputData)]);
|
||||
}
|
||||
|
||||
stopwatch.Stop();
|
||||
Debug.WriteLine($"Yap模型识别 耗时{stopwatch.ElapsedMilliseconds}ms 结果: {ans}");
|
||||
return ans;
|
||||
using (results)
|
||||
{
|
||||
// 获取输出数据
|
||||
var boxes = results[0].AsTensor<float>();
|
||||
|
||||
var ans = new StringBuilder();
|
||||
var lastWord = default(string);
|
||||
for (var i = 0; i < boxes.Dimensions[0]; i++)
|
||||
{
|
||||
var maxIndex = 0;
|
||||
var maxValue = -1.0;
|
||||
for (var j = 0; j < _wordDictionary.Count; j++)
|
||||
{
|
||||
var value = boxes[[i, 0, j]];
|
||||
if (value > maxValue)
|
||||
{
|
||||
maxValue = value;
|
||||
maxIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
var word = _wordDictionary[maxIndex];
|
||||
if (word != lastWord && word != "|")
|
||||
{
|
||||
ans.Append(word);
|
||||
}
|
||||
|
||||
lastWord = word;
|
||||
}
|
||||
|
||||
TimeSpan time = Stopwatch.GetElapsedTime(startTime);
|
||||
string result = ans.ToString();
|
||||
Debug.WriteLine($"Yap模型识别 耗时{time.TotalMilliseconds}ms 结果: {result}");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static Tensor<float> ToTensorUnsafe(Mat src)
|
||||
public static Tensor<float> ToTensorUnsafe(Mat src, out IMemoryOwner<float> tensorMemoryOwnser)
|
||||
{
|
||||
var channels = src.Channels();
|
||||
var nRows = src.Rows;
|
||||
@@ -99,21 +101,21 @@ public class PickTextInference : ITextInference
|
||||
nRows = 1;
|
||||
}
|
||||
|
||||
var inputData = new float[nCols];
|
||||
//var inputData = new float[nCols];
|
||||
tensorMemoryOwnser = MemoryPool<float>.Shared.Rent(nCols);
|
||||
var memory = tensorMemoryOwnser.Memory[..nCols];
|
||||
unsafe
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
var p = src.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
var b = (byte*)src.Ptr(i);
|
||||
for (var j = 0; j < nCols; j++)
|
||||
{
|
||||
inputData[j] = b[j] / 255f;
|
||||
memory.Span[j] = b[j] / 255f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new DenseTensor<float>(new Memory<float>(inputData), new int[] { 1, 1, 32, 384 });
|
||||
;
|
||||
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,17 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
|
||||
public class TextInferenceFactory
|
||||
{
|
||||
public class TextInferenceFactory
|
||||
{
|
||||
public static ITextInference Create(OcrEngineTypes type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case OcrEngineTypes.YapModel:
|
||||
return new PickTextInference();
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(type), type, null);
|
||||
}
|
||||
}
|
||||
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
|
||||
|
||||
public static ITextInference Pick = Create(OcrEngineTypes.YapModel);
|
||||
public static ITextInference Create(OcrEngineTypes type)
|
||||
{
|
||||
return type switch
|
||||
{
|
||||
OcrEngineTypes.YapModel => new PickTextInference(),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.YOLO;
|
||||
|
||||
@@ -20,23 +16,14 @@ public class Predictor
|
||||
{
|
||||
var options = new SessionOptions();
|
||||
var modelPath = Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx");
|
||||
if (!File.Exists(modelPath))
|
||||
{
|
||||
throw new FileNotFoundException("自动钓鱼模型文件不存在", modelPath);
|
||||
}
|
||||
if (!File.Exists(modelPath)) throw new FileNotFoundException("自动钓鱼模型文件不存在", modelPath);
|
||||
|
||||
_session = new InferenceSession(modelPath, options);
|
||||
|
||||
|
||||
var wordJsonPath = Global.Absolute("Assets\\Model\\Fish\\label.json");
|
||||
if (!File.Exists(wordJsonPath))
|
||||
{
|
||||
throw new FileNotFoundException("自动钓鱼模型分类文件不存在", wordJsonPath);
|
||||
}
|
||||
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("自动钓鱼模型分类文件不存在", wordJsonPath);
|
||||
|
||||
var json = File.ReadAllText(wordJsonPath);
|
||||
labels = JsonSerializer.Deserialize<string[]>(json) ?? throw new Exception("label.json deserialize failed");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,6 @@ public enum OcrEngineTypes
|
||||
|
||||
// 特定模型
|
||||
YasModel,
|
||||
|
||||
YapModel
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
public class ArithmeticHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 水平投影
|
||||
/// 水平投影
|
||||
/// </summary>
|
||||
/// <param name="gray"></param>
|
||||
/// <returns></returns>
|
||||
@@ -14,23 +14,18 @@ public class ArithmeticHelper
|
||||
var projection = new int[gray.Height];
|
||||
//对每一行计算投影值
|
||||
for (var y = 0; y < gray.Height; ++y)
|
||||
{
|
||||
//遍历这一行的每一个像素,如果是有效的,累加投影值
|
||||
for (var x = 0; x < gray.Width; ++x)
|
||||
{
|
||||
var s = gray.Get<Vec2b>(y, x);
|
||||
if (s.Item0 == 255)
|
||||
{
|
||||
projection[y]++;
|
||||
}
|
||||
if (s.Item0 == 255) projection[y]++;
|
||||
}
|
||||
}
|
||||
|
||||
return projection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 垂直投影
|
||||
/// 垂直投影
|
||||
/// </summary>
|
||||
/// <param name="gray"></param>
|
||||
/// <returns></returns>
|
||||
@@ -39,17 +34,12 @@ public class ArithmeticHelper
|
||||
var projection = new int[gray.Width];
|
||||
//遍历每一列计算投影值
|
||||
for (var x = 0; x < gray.Width; ++x)
|
||||
{
|
||||
for (var y = 0; y < gray.Height; ++y)
|
||||
{
|
||||
var s = gray.Get<Vec2b>(y, x);
|
||||
if (s.Item0 == 255)
|
||||
{
|
||||
projection[x]++;
|
||||
}
|
||||
if (s.Item0 == 255) projection[x]++;
|
||||
}
|
||||
}
|
||||
|
||||
return projection;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,97 +1,90 @@
|
||||
using System;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Drawing;
|
||||
using OpenCvSharp;
|
||||
using Vanara.PInvoke;
|
||||
using Point = System.Drawing.Point;
|
||||
using Color = System.Windows.Media.Color;
|
||||
using Point = OpenCvSharp.Point;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public static class CommonExtension
|
||||
{
|
||||
public static class CommonExtension
|
||||
public static unsafe Point AsCvPoint(this System.Drawing.Point point)
|
||||
{
|
||||
public static unsafe OpenCvSharp.Point ToCvPoint(this Point point)
|
||||
{
|
||||
return *(OpenCvSharp.Point*)&point;
|
||||
}
|
||||
|
||||
public static unsafe Point ToDrawingPoint(this OpenCvSharp.Point point)
|
||||
{
|
||||
return *(Point*)&point;
|
||||
}
|
||||
|
||||
public static System.Windows.Point ToWindowsPoint(this OpenCvSharp.Point point)
|
||||
{
|
||||
return new System.Windows.Point(point.X, point.Y);
|
||||
}
|
||||
|
||||
public static unsafe OpenCvSharp.Rect ToCvRect(this Rectangle rectangle)
|
||||
{
|
||||
return *(OpenCvSharp.Rect*)&rectangle;
|
||||
}
|
||||
|
||||
public static System.Windows.Rect ToWindowsRectangle(this OpenCvSharp.Rect rect)
|
||||
{
|
||||
return new System.Windows.Rect(rect.X, rect.Y, rect.Width, rect.Height);
|
||||
}
|
||||
|
||||
public static System.Windows.Rect ToWindowsRectangleOffset(this OpenCvSharp.Rect rect, int offsetX, int offsetY)
|
||||
{
|
||||
return new System.Windows.Rect(rect.X + offsetX, rect.Y + offsetY, rect.Width, rect.Height);
|
||||
}
|
||||
|
||||
public static unsafe Rectangle ToDrawingRectangle(this OpenCvSharp.Rect rect)
|
||||
{
|
||||
return *(Rectangle*)▭
|
||||
}
|
||||
|
||||
public static Point GetCenterPoint(this Rectangle rectangle)
|
||||
{
|
||||
if (rectangle.IsEmpty)
|
||||
{
|
||||
throw new ArgumentException("rectangle is empty");
|
||||
}
|
||||
|
||||
return new Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
|
||||
public static OpenCvSharp.Point GetCenterPoint(this RECT rectangle)
|
||||
{
|
||||
if (rectangle.IsEmpty)
|
||||
{
|
||||
throw new ArgumentException("rectangle is empty");
|
||||
}
|
||||
|
||||
return new OpenCvSharp.Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static OpenCvSharp.Point GetCenterPoint(this Rect rectangle)
|
||||
{
|
||||
if (rectangle == Rect.Empty)
|
||||
{
|
||||
throw new ArgumentException("rectangle is empty");
|
||||
}
|
||||
|
||||
return new OpenCvSharp.Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static Rect Multiply(this Rect rect, double assetScale)
|
||||
{
|
||||
if (rect == Rect.Empty)
|
||||
{
|
||||
throw new ArgumentException("rect is empty");
|
||||
}
|
||||
|
||||
return new Rect((int)(rect.X * assetScale), (int)(rect.Y * assetScale), (int)(rect.Width * assetScale), (int)(rect.Height * assetScale));
|
||||
}
|
||||
|
||||
|
||||
public static System.Windows.Media.Color ToWindowsColor(this Color color)
|
||||
{
|
||||
return System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B);
|
||||
}
|
||||
return *(Point*)&point;
|
||||
}
|
||||
}
|
||||
|
||||
public static unsafe System.Drawing.Point AsDrawingPoint(this Point point)
|
||||
{
|
||||
return *(System.Drawing.Point*)&point;
|
||||
}
|
||||
|
||||
public static System.Windows.Point ToWindowsPoint(this Point point)
|
||||
{
|
||||
return new System.Windows.Point(point.X, point.Y);
|
||||
}
|
||||
|
||||
public static unsafe Rect AsCvRect(this Rectangle rectangle)
|
||||
{
|
||||
return *(Rect*)&rectangle;
|
||||
}
|
||||
|
||||
public static System.Windows.Rect ToWindowsRectangle(this Rect rect)
|
||||
{
|
||||
return new System.Windows.Rect(rect.X, rect.Y, rect.Width, rect.Height);
|
||||
}
|
||||
|
||||
public static System.Windows.Rect ToWindowsRectangleOffset(this Rect rect, int offsetX, int offsetY)
|
||||
{
|
||||
return new System.Windows.Rect(rect.X + offsetX, rect.Y + offsetY, rect.Width, rect.Height);
|
||||
}
|
||||
|
||||
public static unsafe Rectangle AsDrawingRectangle(this Rect rect)
|
||||
{
|
||||
return *(Rectangle*)▭
|
||||
}
|
||||
|
||||
public static System.Drawing.Point GetCenterPoint(this Rectangle rectangle)
|
||||
{
|
||||
if (rectangle.IsEmpty) throw new ArgumentException("rectangle is empty");
|
||||
|
||||
return new System.Drawing.Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static Point GetCenterPoint(this RECT rectangle)
|
||||
{
|
||||
if (rectangle.IsEmpty) throw new ArgumentException("rectangle is empty");
|
||||
|
||||
return new Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static Point GetCenterPoint(this Rect rectangle)
|
||||
{
|
||||
if (rectangle == Rect.Empty) throw new ArgumentException("rectangle is empty");
|
||||
|
||||
return new Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static Rect Multiply(this Rect rect, double assetScale)
|
||||
{
|
||||
if (rect == Rect.Empty) throw new ArgumentException("rect is empty");
|
||||
|
||||
return new Rect((int)(rect.X * assetScale), (int)(rect.Y * assetScale), (int)(rect.Width * assetScale), (int)(rect.Height * assetScale));
|
||||
}
|
||||
|
||||
public static Color ToWindowsColor(this System.Drawing.Color color)
|
||||
{
|
||||
return Color.FromArgb(color.A, color.R, color.G, color.B);
|
||||
}
|
||||
|
||||
public static Point2d ToPoint2d(this Point2f p)
|
||||
{
|
||||
return new Point2d(p.X, p.Y);
|
||||
}
|
||||
|
||||
public static List<Point2d> ToPoint2d(this List<Point2f> list)
|
||||
{
|
||||
return list.ConvertAll(ToPoint2d);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
using System;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class CommonRecognition
|
||||
{
|
||||
/// <summary>
|
||||
/// 寻找游戏内按钮
|
||||
/// 寻找游戏内按钮
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <returns></returns>
|
||||
@@ -28,7 +28,7 @@ public class CommonRecognition
|
||||
//Cv2.Dilate(src, src, kernel); //膨胀
|
||||
|
||||
Cv2.FindContours(src, out var contours, out _, RetrievalModes.External,
|
||||
ContourApproximationModes.ApproxSimple, null);
|
||||
ContourApproximationModes.ApproxSimple);
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var boxes = contours.Select(Cv2.BoundingRect).Where(r => r.Width > 50);
|
||||
@@ -40,6 +40,6 @@ public class CommonRecognition
|
||||
Debug.WriteLine(e);
|
||||
}
|
||||
|
||||
return new List<Rect>();
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class ContoursHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 找到指定颜色的矩形
|
||||
/// </summary>
|
||||
/// <param name="srcMat">图像</param>
|
||||
/// <param name="low">RGB色彩低位</param>
|
||||
/// <param name="high">RGB色彩高位</param>
|
||||
/// <param name="minWidth">矩形最小宽度</param>
|
||||
/// <param name="minHeight">矩形最小高度</param>
|
||||
/// <returns></returns>
|
||||
public static List<Rect> FindSpecifyColorRects(Mat srcMat, Scalar low, Scalar high, int minWidth = -1, int minHeight = -1)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var src = srcMat.Clone();
|
||||
Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(src, low, high, src);
|
||||
|
||||
Cv2.FindContours(src, out var contours, out _, RetrievalModes.External,
|
||||
ContourApproximationModes.ApproxSimple);
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var boxes = contours.Select(Cv2.BoundingRect).Where(r =>
|
||||
{
|
||||
if (minWidth > 0 && r.Width < minWidth)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (minHeight > 0 && r.Height < minHeight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return boxes.ToList();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.WriteLine(e);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
public static List<Rect> FindSpecifyColorRects(Mat srcMat, Scalar color, int minWidth = -1, int minHeight = -1)
|
||||
{
|
||||
return FindSpecifyColorRects(srcMat, color, color, minWidth, minHeight);
|
||||
}
|
||||
}
|
||||
@@ -1,64 +1,59 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
/// <summary>
|
||||
/// 图片剪裁
|
||||
/// </summary>
|
||||
[Obsolete]
|
||||
public class CropHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 图片剪裁
|
||||
/// </summary>
|
||||
public class CropHelper
|
||||
public static Mat CutRightTop(Mat srcMat, int saveRightWidth, int saveTopHeight)
|
||||
{
|
||||
public static Mat CutRightTop(Mat srcMat, int saveRightWidth, int saveTopHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, 0, saveRightWidth, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, 0, saveRightWidth, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutRightBottom(Mat srcMat, int saveRightWidth, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, srcMat.Height - saveBottomHeight, saveRightWidth, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutRightBottom(Mat srcMat, int saveRightWidth, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, srcMat.Height - saveBottomHeight, saveRightWidth, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutLeftTop(Mat srcMat, int saveLeftWidth, int saveTopHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, saveLeftWidth, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutLeftTop(Mat srcMat, int saveLeftWidth, int saveTopHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, saveLeftWidth, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutLeftBottom(Mat srcMat, int saveLeftWidth, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, srcMat.Height - saveBottomHeight, saveLeftWidth, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutLeftBottom(Mat srcMat, int saveLeftWidth, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, srcMat.Height - saveBottomHeight, saveLeftWidth, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutTop(Mat srcMat, int saveTopHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, srcMat.Width, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutTop(Mat srcMat, int saveTopHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, srcMat.Width, saveTopHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutBottom(Mat srcMat, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, srcMat.Height- saveBottomHeight, srcMat.Width, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutBottom(Mat srcMat, int saveBottomHeight)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, srcMat.Height - saveBottomHeight, srcMat.Width, saveBottomHeight));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutRight(Mat srcMat, int saveRightWidth)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, 0, saveRightWidth, srcMat.Height));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutLeft(Mat srcMat, int saveLeftWidth)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, saveLeftWidth, srcMat.Height));
|
||||
return srcMat;
|
||||
}
|
||||
public static Mat CutRight(Mat srcMat, int saveRightWidth)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(srcMat.Width - saveRightWidth, 0, saveRightWidth, srcMat.Height));
|
||||
return srcMat;
|
||||
}
|
||||
|
||||
public static Mat CutLeft(Mat srcMat, int saveLeftWidth)
|
||||
{
|
||||
srcMat = new Mat(srcMat, new Rect(0, 0, saveLeftWidth, srcMat.Height));
|
||||
return srcMat;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
|
||||
public enum Feature2DType
|
||||
{
|
||||
// ReSharper disable once InconsistentNaming
|
||||
SURF,
|
||||
|
||||
// ReSharper disable once InconsistentNaming
|
||||
SIFT
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.XFeatures2D;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
using OpenCvSharp.Features2D;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
|
||||
public class FeatureMatcher
|
||||
{
|
||||
private readonly double _threshold = 100; // SURF 100
|
||||
private readonly Feature2D _feature2D;
|
||||
private readonly Mat _trainMat; // 大图本身
|
||||
private readonly Mat _trainRet = new(); // 大图特征描述子
|
||||
private readonly KeyPoint[] _trainKeyPoints;
|
||||
|
||||
private readonly KeyPointFeatureBlock[][] _blocks; // 特征块存储
|
||||
private readonly int _splitRow = MapCoordinate.GameMapRows * 2; // 特征点拆分行数
|
||||
private readonly int _splitCol = MapCoordinate.GameMapCols * 2; // 特征点拆分列数
|
||||
private KeyPointFeatureBlock? _lastMergedBlock; // 上次合并的特征块
|
||||
|
||||
public FeatureMatcher(Mat trainMat, FeatureStorage? featureStorage = null, Feature2DType type = Feature2DType.SIFT, double threshold = 100)
|
||||
{
|
||||
_threshold = threshold;
|
||||
_trainMat = trainMat;
|
||||
if (Feature2DType.SURF == type)
|
||||
{
|
||||
_feature2D = SURF.Create(_threshold, 4, 3, false, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
_feature2D = SIFT.Create();
|
||||
}
|
||||
|
||||
if (featureStorage != null)
|
||||
{
|
||||
featureStorage.TypeName = type.ToString();
|
||||
var kpFromDisk = featureStorage.LoadKeyPointArray();
|
||||
if (kpFromDisk == null)
|
||||
{
|
||||
_feature2D.DetectAndCompute(trainMat, null, out _trainKeyPoints, _trainRet);
|
||||
featureStorage.SaveKeyPointArray(_trainKeyPoints);
|
||||
featureStorage.SaveDescMat(_trainRet);
|
||||
}
|
||||
else
|
||||
{
|
||||
_trainKeyPoints = kpFromDisk;
|
||||
_trainRet = featureStorage.LoadDescMat() ?? throw new Exception("加载特征描述矩阵失败");
|
||||
}
|
||||
}
|
||||
|
||||
Debug.WriteLine("被匹配的图像生成初始化KeyPoint完成");
|
||||
Stopwatch sw = new();
|
||||
sw.Start();
|
||||
_blocks = KeyPointFeatureBlockHelper.SplitFeatures(_trainMat, _splitRow, _splitCol, _trainKeyPoints, _trainRet);
|
||||
sw.Stop();
|
||||
Debug.WriteLine($"切割特征点耗时: {sw.ElapsedMilliseconds}ms");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 普通匹配(全图特征)
|
||||
/// </summary>
|
||||
/// <param name="queryMat"></param>
|
||||
/// <returns></returns>
|
||||
public Point2f[]? Match(Mat queryMat)
|
||||
{
|
||||
return Match(_trainKeyPoints, _trainRet, queryMat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并邻近的特征点后匹配(临近特征)
|
||||
/// </summary>
|
||||
/// <param name="queryMat"></param>
|
||||
/// <param name="prevX">上次匹配到的坐标x</param>
|
||||
/// <param name="prevY">上次匹配到的坐标y</param>
|
||||
/// <returns></returns>
|
||||
public Point2f[]? Match(Mat queryMat, int prevX, int prevY)
|
||||
{
|
||||
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(_trainMat, _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);
|
||||
}
|
||||
|
||||
return Match(_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!, queryMat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 普通匹配
|
||||
/// </summary>
|
||||
/// <param name="trainKeyPoints"></param>
|
||||
/// <param name="trainRet"></param>
|
||||
/// <param name="queryMat"></param>
|
||||
/// <returns></returns>
|
||||
public Point2f[]? Match(KeyPoint[] trainKeyPoints, Mat trainRet, Mat queryMat)
|
||||
{
|
||||
SpeedTimer speedTimer = new();
|
||||
|
||||
using var queryRet = new Mat();
|
||||
|
||||
_feature2D.DetectAndCompute(queryMat, null, out var queryKeyPoints, queryRet);
|
||||
speedTimer.Record("模板生成KeyPoint");
|
||||
|
||||
using var flnMatcher = new FlannBasedMatcher();
|
||||
var matches = flnMatcher.Match(queryRet, trainRet);
|
||||
//Finding the Minimum and Maximum Distance
|
||||
double minDistance = 1000; //Backward approximation
|
||||
double maxDistance = 0;
|
||||
for (int i = 0; i < queryRet.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 < queryRet.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");
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
speedTimer.DebugPrint();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// knn的方式匹配
|
||||
/// </summary>
|
||||
/// <param name="matSrc"></param>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
public Point2f[]? KnnMatch(Mat matSrc)
|
||||
{
|
||||
SpeedTimer speedTimer = new();
|
||||
|
||||
using var matSrcRet = new Mat();
|
||||
KeyPoint[] keyPointsSrc;
|
||||
using (var surf = SURF.Create(_threshold, 4, 3, false, true))
|
||||
{
|
||||
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)
|
||||
{
|
||||
pointsSrc.Add(keyPointsSrc[best.QueryIdx].Pt);
|
||||
pointsDst.Add(_trainKeyPoints[best.TrainIdx].Pt);
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
speedTimer.DebugPrint();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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;
|
||||
|
||||
public class FeatureStorage(string name)
|
||||
{
|
||||
private readonly string rootPath = Global.Absolute(@"User\Map\");
|
||||
|
||||
public void SetType(Feature2DType type)
|
||||
{
|
||||
TypeName = type.ToString();
|
||||
}
|
||||
|
||||
public string TypeName { get; set; } = "UNKNOWN";
|
||||
|
||||
public KeyPoint[]? LoadKeyPointArray()
|
||||
{
|
||||
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 SaveKeyPointArray(KeyPoint[] kpArray)
|
||||
{
|
||||
CreateFolder();
|
||||
string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
|
||||
File.WriteAllBytes(kpPath, ObjectUtils.Serialize(kpArray));
|
||||
}
|
||||
|
||||
private void CreateFolder()
|
||||
{
|
||||
if (Directory.Exists(rootPath) == false)
|
||||
{
|
||||
Directory.CreateDirectory(rootPath);
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
CreateFolder();
|
||||
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)}");
|
||||
}
|
||||
FileStorage fs = new(files[0], FileStorage.Modes.Read);
|
||||
var mat = fs["desc"]?.ReadMat();
|
||||
fs.Release();
|
||||
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 SaveDescMat(Mat descMat)
|
||||
{
|
||||
CreateFolder();
|
||||
// 删除旧文件
|
||||
var fileName = $"{name}_{TypeName}.mat";
|
||||
var files = Directory.GetFiles(rootPath, fileName, SearchOption.AllDirectories);
|
||||
foreach (var file in files)
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
|
||||
var descPath = Path.Combine(rootPath, fileName);
|
||||
FileStorage fs = new(descPath, FileStorage.Modes.Write);
|
||||
fs.Write("desc", descMat);
|
||||
fs.Release();
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
|
||||
public class KeyPointFeatureBlockHelper
|
||||
{
|
||||
public static KeyPointFeatureBlock[][] SplitFeatures(Mat originalImage, int rows, int cols, KeyPoint[] keyPoints, Mat matches)
|
||||
{
|
||||
var matchesCols = matches.Cols; // SURF 64 SIFT 128
|
||||
// Calculate grid size
|
||||
int cellWidth = originalImage.Width / cols;
|
||||
int cellHeight = originalImage.Height / rows;
|
||||
|
||||
// Initialize arrays to store split features and matches
|
||||
var splitKeyPoints = new KeyPointFeatureBlock[rows][];
|
||||
|
||||
// Initialize each row
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
splitKeyPoints[i] = new KeyPointFeatureBlock[cols];
|
||||
}
|
||||
|
||||
// Split features and matches
|
||||
for (int i = 0; i < keyPoints.Length; i++)
|
||||
{
|
||||
int row = (int)(keyPoints[i].Pt.Y / cellHeight);
|
||||
int col = (int)(keyPoints[i].Pt.X / cellWidth);
|
||||
|
||||
// Ensure row and col are within bounds
|
||||
row = Math.Min(Math.Max(row, 0), rows - 1);
|
||||
col = Math.Min(Math.Max(col, 0), cols - 1);
|
||||
|
||||
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
|
||||
if (splitKeyPoints[row][col] == null)
|
||||
{
|
||||
splitKeyPoints[row][col] = new KeyPointFeatureBlock();
|
||||
}
|
||||
|
||||
splitKeyPoints[row][col].KeyPointList.Add(keyPoints[i]);
|
||||
splitKeyPoints[row][col].KeyPointIndexList.Add(i);
|
||||
}
|
||||
|
||||
// 遍历每个特征块,计算描述子
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
for (int j = 0; j < cols; j++)
|
||||
{
|
||||
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
|
||||
if (splitKeyPoints[i][j] == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var block = splitKeyPoints[i][j];
|
||||
|
||||
var descriptor = new Mat(block.KeyPointIndexList.Count, matchesCols, MatType.CV_32FC1);
|
||||
InitBlockMat(block.KeyPointIndexList, descriptor, matches);
|
||||
|
||||
block.Descriptor = descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
return splitKeyPoints;
|
||||
}
|
||||
|
||||
public static (int, int) GetCellIndex(Mat originalImage, int rows, int cols, int x, int 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;
|
||||
|
||||
return (cellRow, cellCol);
|
||||
}
|
||||
|
||||
public static KeyPointFeatureBlock MergeNeighboringFeatures(KeyPointFeatureBlock[][] splitKeyPoints, Mat matches, int cellRow, int cellCol)
|
||||
{
|
||||
var matchesCols = matches.Cols; // SURF 64 SIFT 128
|
||||
// Initialize lists to store neighboring features and matches
|
||||
var neighboringKeyPoints = new List<KeyPoint>();
|
||||
var neighboringKeyPointIndices = new List<int>();
|
||||
|
||||
// Loop through 9 neighboring cells
|
||||
for (int i = Math.Max(cellRow - 1, 0); i <= Math.Min(cellRow + 1, splitKeyPoints.Length - 1); i++)
|
||||
{
|
||||
for (int j = Math.Max(cellCol - 1, 0); j <= Math.Min(cellCol + 1, splitKeyPoints[i].Length - 1); j++)
|
||||
{
|
||||
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
|
||||
if (splitKeyPoints[i][j] != null)
|
||||
{
|
||||
neighboringKeyPoints.AddRange(splitKeyPoints[i][j].KeyPointList);
|
||||
neighboringKeyPointIndices.AddRange(splitKeyPoints[i][j].KeyPointIndexList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge neighboring features
|
||||
var mergedKeyPointBlock = new KeyPointFeatureBlock
|
||||
{
|
||||
MergedCenterCellCol = cellCol,
|
||||
MergedCenterCellRow = cellRow,
|
||||
KeyPointList = neighboringKeyPoints,
|
||||
KeyPointIndexList = neighboringKeyPointIndices
|
||||
};
|
||||
mergedKeyPointBlock.Descriptor = new Mat(mergedKeyPointBlock.KeyPointIndexList.Count, matchesCols, MatType.CV_32FC1);
|
||||
InitBlockMat(mergedKeyPointBlock.KeyPointIndexList, mergedKeyPointBlock.Descriptor, matches);
|
||||
|
||||
return mergedKeyPointBlock;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按行拷贝matches到descriptor
|
||||
/// </summary>
|
||||
/// <param name="keyPointIndexList">记录了哪些行需要拷贝</param>
|
||||
/// <param name="descriptor">拷贝结果</param>
|
||||
/// <param name="matches">原始数据</param>
|
||||
private static unsafe void InitBlockMat(List<int> keyPointIndexList, Mat descriptor, Mat matches)
|
||||
{
|
||||
Size size = matches.Size();
|
||||
|
||||
Matrix<float> destMatrix = new(descriptor.DataPointer, size.Width, size.Height);
|
||||
Matrix<float> sourceMatrix = new(matches.DataPointer, size.Width, size.Height);
|
||||
|
||||
Span<int> keyPointIndexSpan = CollectionsMarshal.AsSpan(keyPointIndexList);
|
||||
ref int keyPointIndexRef = ref MemoryMarshal.GetReference(keyPointIndexSpan);
|
||||
for (int i = 0; i < keyPointIndexSpan.Length; i++)
|
||||
{
|
||||
ref int index = ref Unsafe.Add(ref keyPointIndexRef, i);
|
||||
sourceMatrix[index].CopyTo(destMatrix[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly ref struct Matrix<T>
|
||||
{
|
||||
private readonly ref T reference;
|
||||
private readonly int width;
|
||||
private readonly int height;
|
||||
|
||||
public unsafe Matrix(void* pointer, int width, int height)
|
||||
{
|
||||
reference = ref Unsafe.AsRef<T>(pointer);
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public Span<T> this[int row]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (row < 0 || row >= height)
|
||||
{
|
||||
throw new IndexOutOfRangeException();
|
||||
}
|
||||
|
||||
return MemoryMarshal.CreateSpan(ref Unsafe.Add(ref reference, row * width), width);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按行拷贝matches到descriptor
|
||||
/// </summary>
|
||||
/// <param name="keyPointIndexList">记录了哪些行需要拷贝</param>
|
||||
/// <param name="descriptor">拷贝结果</param>
|
||||
/// <param name="matches">原始数据</param>
|
||||
[Obsolete]
|
||||
private static unsafe void InitBlockMat2(IReadOnlyList<int> keyPointIndexList, Mat descriptor, Mat matches)
|
||||
{
|
||||
int cols = matches.Cols;
|
||||
float* ptrDest = (float*)descriptor.DataPointer;
|
||||
|
||||
for (int i = 0; i < keyPointIndexList.Count; i++)
|
||||
{
|
||||
var index = keyPointIndexList[i];
|
||||
float* ptrSrcRow = (float*)matches.Ptr(index);
|
||||
for (int j = 0; j < cols; j++)
|
||||
{
|
||||
*(ptrDest + i * cols + j) = ptrSrcRow[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +1,244 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using SharpDX;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using Point = OpenCvSharp.Point;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
/// <summary>
|
||||
/// 多目标模板匹配demo
|
||||
/// https://github.com/shimat/opencvsharp/issues/182
|
||||
/// </summary>
|
||||
public class MatchTemplateHelper
|
||||
{
|
||||
public class MatchTemplateHelper
|
||||
private static readonly ILogger<MatchTemplateHelper> _logger = App.GetLogger<MatchTemplateHelper>();
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配
|
||||
/// </summary>
|
||||
/// <param name="srcMat">原图像</param>
|
||||
/// <param name="dstMat">模板</param>
|
||||
/// <param name="matchMode">匹配方式</param>
|
||||
/// <param name="maskMat">遮罩</param>
|
||||
/// <param name="threshold">阈值</param>
|
||||
/// <returns>左上角的标点,由于(0,0)点作为未匹配的结果,所以不能做完全相同的模板匹配</returns>
|
||||
public static Point MatchTemplate(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat = null, double threshold = 0.8)
|
||||
{
|
||||
private static readonly ILogger<MatchTemplateHelper> _logger = App.GetLogger<MatchTemplateHelper>();
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配
|
||||
/// TODO 算法不一样的的时候找点的方法也不一样
|
||||
/// </summary>
|
||||
/// <param name="srcMat">原图像</param>
|
||||
/// <param name="dstMat">模板</param>
|
||||
/// <param name="matchMode">匹配方式</param>
|
||||
/// <param name="maskMat">遮罩</param>
|
||||
/// <param name="threshold">阈值</param>
|
||||
/// <returns>左上角的标点</returns>
|
||||
public static Point MatchTemplate(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat = null, double threshold = 0.8)
|
||||
try
|
||||
{
|
||||
try
|
||||
using var result = new Mat();
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode, maskMat!);
|
||||
|
||||
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.CCoeff or TemplateMatchModes.CCorr)
|
||||
{
|
||||
using var result = new Mat();
|
||||
if (maskMat == null)
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode);
|
||||
}
|
||||
else
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode, maskMat);
|
||||
}
|
||||
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax);
|
||||
}
|
||||
|
||||
Cv2.MinMaxLoc(result, out _, out var maxValue, out _, out var point);
|
||||
Cv2.MinMaxLoc(result, out var minValue, out var maxValue, out var minLoc, out var maxLoc);
|
||||
|
||||
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.SqDiffNormed)
|
||||
{
|
||||
if (minValue <= 1 - threshold)
|
||||
{
|
||||
return minLoc;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (maxValue >= threshold)
|
||||
{
|
||||
return point;
|
||||
return maxLoc;
|
||||
}
|
||||
}
|
||||
|
||||
return new Point();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.ToString());
|
||||
return new Point();
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配多个结果
|
||||
/// 不好用
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="dstMat"></param>
|
||||
/// <param name="maskMat"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <param name="maxCount"></param>
|
||||
/// <returns></returns>
|
||||
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8, int maxCount = 8)
|
||||
catch (Exception ex)
|
||||
{
|
||||
var points = new List<Point>();
|
||||
try
|
||||
_logger.LogError(ex.Message);
|
||||
_logger.LogDebug(ex, ex.Message);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配多个结果
|
||||
/// 不好用
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="dstMat"></param>
|
||||
/// <param name="maskMat"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <param name="maxCount"></param>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8, int maxCount = 8)
|
||||
{
|
||||
var points = new List<Point>();
|
||||
try
|
||||
{
|
||||
using var result = new Mat();
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed, maskMat!);
|
||||
|
||||
var mask = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.White);
|
||||
var maskSub = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.Black);
|
||||
while (true)
|
||||
{
|
||||
using var result = new Mat();
|
||||
if (maskMat == null)
|
||||
Cv2.MinMaxLoc(result, out _, out var maxValue, out _, out var maxLoc, mask);
|
||||
var maskRect = new Rect(maxLoc.X, maxLoc.Y, dstMat.Width, dstMat.Height);
|
||||
maskSub.Rectangle(maskRect, Scalar.White, -1);
|
||||
mask -= maskSub;
|
||||
if (maxValue >= threshold)
|
||||
points.Add(maxLoc);
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
_logger.LogDebug(ex, ex.Message);
|
||||
return points;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, double threshold)
|
||||
{
|
||||
return MatchTemplateMulti(srcMat, dstMat, null, threshold);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在一张图中查找多个模板
|
||||
/// 查到一个遮盖一个的笨方法,效率很低,但是很准确
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="imgSubDictionary"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<string, List<Point>> MatchMultiPicForOnePic(Mat srcMat, Dictionary<string, Mat> imgSubDictionary, double threshold = 0.8)
|
||||
{
|
||||
var dictionary = new Dictionary<string, List<Point>>();
|
||||
foreach (var kvp in imgSubDictionary)
|
||||
{
|
||||
var list = new List<Point>();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var point = MatchTemplate(srcMat, kvp.Value, TemplateMatchModes.CCoeffNormed, null, threshold);
|
||||
if (point != new Point())
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed);
|
||||
// 把结果给遮掩掉,避免重复识别
|
||||
Cv2.Rectangle(srcMat, point, new Point(point.X + kvp.Value.Width, point.Y + kvp.Value.Height), Scalar.Black, -1);
|
||||
list.Add(point);
|
||||
}
|
||||
else
|
||||
{
|
||||
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed, maskMat);
|
||||
break;
|
||||
}
|
||||
|
||||
//while (true)
|
||||
//{
|
||||
// Cv2.MinMaxLoc(result, out _, out var maxValue, out _, out var maxLoc);
|
||||
|
||||
// if (maxValue >= threshold)
|
||||
// {
|
||||
// points.Add(maxLoc);
|
||||
|
||||
// //Fill in the res Mat so you don't find the same area again in the MinMaxLoc
|
||||
// Cv2.FloodFill(result, maxLoc, new Scalar(0), out _, new Scalar(0.1), new Scalar(1.0));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// break;
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
var mask = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.White);
|
||||
var maskSub = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.Black);
|
||||
while (true)
|
||||
{
|
||||
Cv2.MinMaxLoc(result, out _, out var maxValue, out _, out var maxLoc, mask);
|
||||
var maskRect = new Rect(maxLoc.X, maxLoc.Y, dstMat.Width, dstMat.Height);
|
||||
maskSub.Rectangle(maskRect, Scalar.White, -1);
|
||||
mask -= maskSub;
|
||||
if (maxValue >= threshold)
|
||||
{
|
||||
points.Add(maxLoc);
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("{Ex}", ex);
|
||||
return points;
|
||||
}
|
||||
|
||||
dictionary.Add(kvp.Key, list);
|
||||
}
|
||||
|
||||
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, double threshold)
|
||||
{
|
||||
return MatchTemplateMulti(srcMat, dstMat, null, threshold);
|
||||
}
|
||||
return dictionary;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在一张图中查找多个模板
|
||||
/// 查到一个遮盖一个的笨方法,效率很低,但是很准确
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="imgSubList"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <returns></returns>
|
||||
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, List<Mat> imgSubList, double threshold = 0.8)
|
||||
{
|
||||
List<Rect> list = new();
|
||||
foreach (var sub in imgSubList)
|
||||
while (true)
|
||||
{
|
||||
var point = MatchTemplate(srcMat, sub, TemplateMatchModes.CCoeffNormed, null, threshold);
|
||||
if (point != new Point())
|
||||
{
|
||||
// 把结果给遮掩掉,避免重复识别
|
||||
Cv2.Rectangle(srcMat, point, new Point(point.X + sub.Width, point.Y + sub.Height), Scalar.Black, -1);
|
||||
list.Add(new Rect(point.X, point.Y, sub.Width, sub.Height));
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在一张图中查找一个个模板
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="dstMat"></param>
|
||||
/// <param name="maskMat"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <returns></returns>
|
||||
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8)
|
||||
{
|
||||
List<Rect> list = new();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var point = MatchTemplate(srcMat, dstMat, TemplateMatchModes.CCoeffNormed, maskMat, threshold);
|
||||
if (point != new Point())
|
||||
{
|
||||
// 把结果给遮掩掉,避免重复识别
|
||||
Cv2.Rectangle(srcMat, point, new Point(point.X + dstMat.Width, point.Y + dstMat.Height), Scalar.Black, -1);
|
||||
list.Add(new Rect(point.X, point.Y, dstMat.Width, dstMat.Height));
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在一张图中查找一个个模板
|
||||
/// </summary>
|
||||
/// <param name="srcMat"></param>
|
||||
/// <param name="dstMat"></param>
|
||||
/// <param name="matchMode"></param>
|
||||
/// <param name="maskMat"></param>
|
||||
/// <param name="threshold"></param>
|
||||
/// <param name="maxCount"></param>
|
||||
/// <returns></returns>
|
||||
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat, double threshold, int maxCount = -1)
|
||||
{
|
||||
List<Rect> list = new();
|
||||
|
||||
if (maxCount < 0)
|
||||
{
|
||||
maxCount = srcMat.Width * srcMat.Height / dstMat.Width / dstMat.Height;
|
||||
}
|
||||
|
||||
for (int i = 0; i < maxCount; i++)
|
||||
{
|
||||
var point = MatchTemplate(srcMat, dstMat, matchMode, maskMat, threshold);
|
||||
if (point != new Point())
|
||||
{
|
||||
// 把结果给遮掩掉,避免重复识别
|
||||
Cv2.Rectangle(srcMat, point, new Point(point.X + dstMat.Width, point.Y + dstMat.Height), Scalar.Black, -1);
|
||||
list.Add(new Rect(point.X, point.Y, dstMat.Width, dstMat.Height));
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Collections.Generic;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 特征块
|
||||
/// 对特征按图像区域进行划分
|
||||
/// </summary>
|
||||
public class KeyPointFeatureBlock
|
||||
{
|
||||
public List<KeyPoint> KeyPointList { get; set; } = new();
|
||||
|
||||
private KeyPoint[]? keyPointArray;
|
||||
|
||||
public KeyPoint[] KeyPointArray
|
||||
{
|
||||
get
|
||||
{
|
||||
keyPointArray ??= [.. KeyPointList];
|
||||
return keyPointArray;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在完整 KeyPoint[] 中的下标
|
||||
/// </summary>
|
||||
public List<int> KeyPointIndexList { get; set; } = new();
|
||||
|
||||
public Mat? Descriptor;
|
||||
|
||||
public int MergedCenterCellCol = -1;
|
||||
public int MergedCenterCellRow = -1;
|
||||
}
|
||||
@@ -1,78 +1,109 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class OpenCvCommonHelper
|
||||
{
|
||||
public class OpenCvCommonHelper
|
||||
/// <summary>
|
||||
/// 计算灰度图中某个颜色的像素个数
|
||||
/// 快速遍历方法来自于: https://blog.csdn.net/TyroneKing/article/details/129108838
|
||||
/// </summary>
|
||||
/// <param name="mat"></param>
|
||||
/// <param name="color"></param>
|
||||
/// <returns></returns>
|
||||
public static int CountGrayMatColor(Mat mat, byte color)
|
||||
{
|
||||
/// <summary>
|
||||
/// 计算灰度图中某个颜色的像素个数
|
||||
/// 快速遍历方法来自于: https://blog.csdn.net/TyroneKing/article/details/129108838
|
||||
/// </summary>
|
||||
/// <param name="mat"></param>
|
||||
/// <param name="color"></param>
|
||||
/// <returns></returns>
|
||||
public static int CountGrayMatColor(Mat mat, byte color)
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
var channels = mat.Channels();
|
||||
var nRows = mat.Rows;
|
||||
var nCols = mat.Cols * channels;
|
||||
if (mat.IsContinuous())
|
||||
{
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
var channels = mat.Channels();
|
||||
var nRows = mat.Rows;
|
||||
var nCols = mat.Cols * channels;
|
||||
if (mat.IsContinuous())
|
||||
nCols *= nRows;
|
||||
nRows = 1;
|
||||
}
|
||||
|
||||
var sum = 0;
|
||||
unsafe
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
nCols *= nRows;
|
||||
nRows = 1;
|
||||
var p = mat.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
for (var j = 0; j < nCols; j++)
|
||||
if (b[j] == color)
|
||||
sum++;
|
||||
}
|
||||
|
||||
var sum = 0;
|
||||
unsafe
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
var p = mat.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
for (var j = 0; j < nCols; j++)
|
||||
{
|
||||
if (b[j] == color)
|
||||
{
|
||||
sum++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static Mat Threshold(Mat src, Scalar low, Scalar high)
|
||||
{
|
||||
using var mask = new Mat();
|
||||
using var rgbMat = new Mat();
|
||||
|
||||
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(rgbMat, low, high, mask);
|
||||
Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化
|
||||
return mask.Clone();
|
||||
}
|
||||
|
||||
public static Mat InRangeHsv(Mat src, Scalar low, Scalar high)
|
||||
{
|
||||
using var mask = new Mat();
|
||||
using var rgbMat = new Mat();
|
||||
|
||||
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2HSV);
|
||||
Cv2.InRange(rgbMat, low, high, mask);
|
||||
return mask.Clone();
|
||||
}
|
||||
|
||||
public static Mat Threshold(Mat src, Scalar s)
|
||||
{
|
||||
return Threshold(src, s, s);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
public static int CountGrayMatColor(Mat mat, byte lowColor, byte highColor)
|
||||
{
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
var channels = mat.Channels();
|
||||
var nRows = mat.Rows;
|
||||
var nCols = mat.Cols * channels;
|
||||
if (mat.IsContinuous())
|
||||
{
|
||||
nCols *= nRows;
|
||||
nRows = 1;
|
||||
}
|
||||
|
||||
var sum = 0;
|
||||
unsafe
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
var p = mat.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
for (var j = 0; j < nCols; j++)
|
||||
if (b[j] >= lowColor && b[j] <= highColor)
|
||||
sum++;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static Mat Threshold(Mat src, Scalar low, Scalar high)
|
||||
{
|
||||
using var mask = new Mat();
|
||||
using var rgbMat = new Mat();
|
||||
|
||||
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(rgbMat, low, high, mask);
|
||||
Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化
|
||||
return mask.Clone();
|
||||
}
|
||||
|
||||
public static Mat InRangeHsv(Mat src, Scalar low, Scalar high)
|
||||
{
|
||||
using var mask = new Mat();
|
||||
using var rgbMat = new Mat();
|
||||
|
||||
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2HSV);
|
||||
Cv2.InRange(rgbMat, low, high, mask);
|
||||
return mask.Clone();
|
||||
}
|
||||
|
||||
public static Mat Threshold(Mat src, Scalar s)
|
||||
{
|
||||
return Threshold(src, s, s);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 和二值化的颜色刚好相反
|
||||
/// </summary>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="s"></param>
|
||||
/// <returns></returns>
|
||||
public static Mat CreateMask(Mat src, Scalar s)
|
||||
{
|
||||
var mask = new Mat();
|
||||
Cv2.InRange(src, s, s, mask);
|
||||
return 255 - mask;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,46 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class ResizeHelper
|
||||
{
|
||||
public class ResizeHelper
|
||||
/// <summary>
|
||||
/// 等比放大的
|
||||
/// </summary>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="scale"></param>
|
||||
/// <returns></returns>
|
||||
public static Mat Resize(Mat src, double scale)
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 等比放大的
|
||||
/// </summary>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="scale"></param>
|
||||
/// <returns></returns>
|
||||
public static Mat Resize(Mat src, double scale)
|
||||
if (Math.Abs(scale - 1) > 0.00001)
|
||||
{
|
||||
if (Math.Abs(scale - 1) > 0.00001)
|
||||
{
|
||||
return Resize(src, scale, scale);
|
||||
}
|
||||
return src;
|
||||
return Resize(src, scale, scale);
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
public static Mat Resize(Mat src, double widthScale, double heightScale)
|
||||
{
|
||||
if (Math.Abs(widthScale - 1) > 0.00001 || Math.Abs(heightScale - 1) > 0.00001)
|
||||
{
|
||||
var dst = new Mat();
|
||||
Cv2.Resize(src, dst, new Size(src.Width * widthScale, src.Height * heightScale));
|
||||
return dst;
|
||||
}
|
||||
|
||||
public static Mat Resize(Mat src, double widthScale, double heightScale)
|
||||
return src;
|
||||
}
|
||||
|
||||
public static Mat ResizeTo(Mat src, int width, int height)
|
||||
{
|
||||
if (src.Width != width || src.Height != height)
|
||||
{
|
||||
if (Math.Abs(widthScale - 1) > 0.00001 || Math.Abs(heightScale - 1) > 0.00001)
|
||||
{
|
||||
var dst = new Mat();
|
||||
Cv2.Resize(src, dst, new Size(src.Width * widthScale, src.Height * heightScale));
|
||||
return dst;
|
||||
}
|
||||
return src;
|
||||
var dst = new Mat();
|
||||
Cv2.Resize(src, dst, new Size(width, height));
|
||||
return dst;
|
||||
}
|
||||
|
||||
public static Mat ResizeTo(Mat src, int width, int height)
|
||||
{
|
||||
if (src.Width != width || src.Height != height)
|
||||
{
|
||||
var dst = new Mat();
|
||||
Cv2.Resize(src, dst, new Size(width, height));
|
||||
return dst;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition;
|
||||
|
||||
/// <summary>
|
||||
/// 识别对象
|
||||
/// 识别对象
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class RecognitionObject
|
||||
@@ -20,7 +16,7 @@ public class RecognitionObject
|
||||
public RecognitionTypes RecognitionType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 感兴趣的区域
|
||||
/// 感兴趣的区域
|
||||
/// </summary>
|
||||
public Rect RegionOfInterest { get; set; }
|
||||
|
||||
@@ -29,56 +25,61 @@ public class RecognitionObject
|
||||
#region 模板匹配
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配的对象(彩色)
|
||||
/// 模板匹配的对象(彩色)
|
||||
/// </summary>
|
||||
public Mat? TemplateImageMat { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配的对象(灰色)
|
||||
/// 模板匹配的对象(灰色)
|
||||
/// </summary>
|
||||
public Mat? TemplateImageGreyMat { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配阈值。可选,默认 0.8 。
|
||||
/// 模板匹配阈值。可选,默认 0.8 。
|
||||
/// </summary>
|
||||
public double Threshold { get; set; } = 0.8;
|
||||
|
||||
/// <summary>
|
||||
/// 是否使用 3 通道匹配。可选,默认 false 。
|
||||
/// 是否使用 3 通道匹配。可选,默认 false 。
|
||||
/// </summary>
|
||||
public bool Use3Channels { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 模板匹配算法。可选,默认 CCoeffNormed 。
|
||||
/// https://docs.opencv.org/4.x/df/dfb/group__imgproc__object.html
|
||||
/// 模板匹配算法。可选,默认 CCoeffNormed 。
|
||||
/// https://docs.opencv.org/4.x/df/dfb/group__imgproc__object.html
|
||||
/// </summary>
|
||||
public TemplateMatchModes TemplateMatchMode { get; set; } = TemplateMatchModes.CCoeffNormed;
|
||||
|
||||
/// <summary>
|
||||
/// 匹配模板遮罩,指定图片中的某种色彩不需要匹配
|
||||
/// 使用时,需要将模板图片的背景色设置为纯绿色,即 (0, 255, 0)
|
||||
/// 匹配模板遮罩,指定图片中的某种色彩不需要匹配
|
||||
/// 使用时,需要将模板图片的背景色设置为纯绿色,即 (0, 255, 0)
|
||||
/// </summary>
|
||||
public bool UseMask { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 不需要匹配的颜色,默认绿色
|
||||
/// UseMask = true 的时候有用
|
||||
/// 不需要匹配的颜色,默认绿色
|
||||
/// UseMask = true 的时候有用
|
||||
/// </summary>
|
||||
public Color MaskColor { get; set; } = Color.FromArgb(0, 255, 0);
|
||||
|
||||
public Mat? MaskMat { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 匹配成功时,是否在屏幕上绘制矩形框。可选,默认 false 。
|
||||
/// true 时 Name 必须有值。
|
||||
/// 匹配成功时,是否在屏幕上绘制矩形框。可选,默认 false 。
|
||||
/// true 时 Name 必须有值。
|
||||
/// </summary>
|
||||
public bool DrawOnWindow { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// DrawOnWindow 为 true 时,绘制的矩形框的颜色。可选,默认红色。
|
||||
/// DrawOnWindow 为 true 时,绘制的矩形框的颜色。可选,默认红色。
|
||||
/// </summary>
|
||||
public Pen DrawOnWindowPen = new(Color.Red, 2);
|
||||
|
||||
/// <summary>
|
||||
/// 一个模板匹配多个结果的时候最大匹配数量。可选,默认 -1,即不限制。
|
||||
/// </summary>
|
||||
public int MaxMatchCount { get; set; } = -1;
|
||||
|
||||
public RecognitionObject InitTemplate()
|
||||
{
|
||||
if (TemplateImageMat != null && TemplateImageGreyMat == null)
|
||||
@@ -87,64 +88,61 @@ public class RecognitionObject
|
||||
Cv2.CvtColor(TemplateImageMat, TemplateImageGreyMat, ColorConversionCodes.BGR2GRAY);
|
||||
}
|
||||
|
||||
if (UseMask && TemplateImageMat != null && MaskMat == null)
|
||||
{
|
||||
MaskMat = OpenCvCommonHelper.Threshold(TemplateImageMat, MaskColor.ToScalar());
|
||||
}
|
||||
if (UseMask && TemplateImageMat != null && MaskMat == null) MaskMat = OpenCvCommonHelper.CreateMask(TemplateImageMat, MaskColor.ToScalar());
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
#endregion 模板匹配
|
||||
|
||||
#region 颜色匹配
|
||||
|
||||
/// <summary>
|
||||
/// 颜色匹配方式。即 cv::ColorConversionCodes。可选,默认 4 (RGB)。
|
||||
/// 常用值:4 (RGB, 3 通道), 40 (HSV, 3 通道), 6 (GRAY, 1 通道)。
|
||||
/// https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html
|
||||
/// 颜色匹配方式。即 cv::ColorConversionCodes。可选,默认 4 (RGB)。
|
||||
/// 常用值:4 (RGB, 3 通道), 40 (HSV, 3 通道), 6 (GRAY, 1 通道)。
|
||||
/// https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html
|
||||
/// </summary>
|
||||
public ColorConversionCodes ColorConversionCode { get; set; } = ColorConversionCodes.BGR2RGB;
|
||||
|
||||
public Color LowerColor { get; set; }
|
||||
public Color UpperColor { get; set; }
|
||||
public Scalar LowerColor { get; set; }
|
||||
public Scalar UpperColor { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 符合的点的数量要求。可选,默认 1
|
||||
/// 符合的点的数量要求。可选,默认 1
|
||||
/// </summary>
|
||||
public int MatchCount { get; set; } = 1;
|
||||
|
||||
#endregion
|
||||
#endregion 颜色匹配
|
||||
|
||||
#region OCR文字识别
|
||||
|
||||
/// <summary>
|
||||
/// OCR 引擎。可选,默认 Media.Ocr。
|
||||
/// OCR 引擎。可选,只有 Paddle。
|
||||
/// </summary>
|
||||
public OcrEngineTypes OcrEngine { get; set; } = OcrEngineTypes.Paddle;
|
||||
|
||||
/// <summary>
|
||||
/// 部分文字识别结果不准确,进行替换。可选。
|
||||
/// 部分文字识别结果不准确,进行替换。可选。
|
||||
/// </summary>
|
||||
public Dictionary<string, string[]> ReplaceDictionary { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 包含匹配
|
||||
/// 多个值全匹配的情况下才算成功
|
||||
/// 复杂情况请用下面的正则匹配
|
||||
/// 包含匹配
|
||||
/// 多个值全匹配的情况下才算成功
|
||||
/// 复杂情况请用下面的正则匹配
|
||||
/// </summary>
|
||||
public List<string> AllContainMatchText { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 包含匹配
|
||||
/// 一个值匹配就算成功
|
||||
/// 包含匹配
|
||||
/// 一个值匹配就算成功
|
||||
/// </summary>
|
||||
public List<string> OneContainMatchText { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 正则匹配
|
||||
/// 多个值全匹配的情况下才算成功
|
||||
/// 正则匹配
|
||||
/// 多个值全匹配的情况下才算成功
|
||||
/// </summary>
|
||||
public List<string> RegexMatchText { get; set; } = new();
|
||||
|
||||
#endregion
|
||||
}
|
||||
#endregion OCR文字识别
|
||||
}
|
||||
@@ -1,16 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition;
|
||||
namespace BetterGenshinImpact.Core.Recognition;
|
||||
|
||||
public enum RecognitionTypes
|
||||
{
|
||||
None,
|
||||
TemplateMatch,
|
||||
ColorMatch,
|
||||
Ocr,
|
||||
TemplateMatch, // 模板匹配
|
||||
ColorMatch, // 颜色匹配
|
||||
OcrMatch, // 文字识别并匹配
|
||||
Ocr, // 仅文字识别
|
||||
ColorRangeAndOcr, // 提取指定颜色后进行文字识别
|
||||
Detect
|
||||
}
|
||||
}
|
||||
@@ -32,10 +32,7 @@ public class MouseEventSimulator
|
||||
|
||||
public bool Click(int x, int y)
|
||||
{
|
||||
if (x == 0 && y == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x == 0 && y == 0) return false;
|
||||
|
||||
Move(x, y);
|
||||
LeftButtonDown();
|
||||
@@ -55,4 +52,4 @@ public class MouseEventSimulator
|
||||
Thread.Sleep(200);
|
||||
return Click(point);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ using Vanara.PInvoke;
|
||||
namespace BetterGenshinImpact.Core.Simulator;
|
||||
|
||||
/// <summary>
|
||||
/// 虚拟键代码
|
||||
/// https://learn.microsoft.com/zh-cn/windows/win32/inputdev/virtual-key-codes
|
||||
/// User32.VK.VK_SPACE 键盘空格键
|
||||
/// 虚拟键代码
|
||||
/// https://learn.microsoft.com/zh-cn/windows/win32/inputdev/virtual-key-codes
|
||||
/// User32.VK.VK_SPACE 键盘空格键
|
||||
/// </summary>
|
||||
public class PostMessageSimulator
|
||||
{
|
||||
@@ -22,11 +22,11 @@ public class PostMessageSimulator
|
||||
|
||||
public PostMessageSimulator(IntPtr hWnd)
|
||||
{
|
||||
this._hWnd = hWnd;
|
||||
_hWnd = hWnd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置并按下左键
|
||||
/// 指定位置并按下左键
|
||||
/// </summary>
|
||||
/// <param name="x"></param>
|
||||
/// <param name="y"></param>
|
||||
@@ -39,6 +39,23 @@ public class PostMessageSimulator
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置并按下左键
|
||||
/// </summary>
|
||||
/// <param name="x"></param>
|
||||
/// <param name="y"></param>
|
||||
public PostMessageSimulator LeftButtonClickBackground(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
var p = MakeLParam(x, y);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, 1, p);
|
||||
Thread.Sleep(100);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONUP, 0, p);
|
||||
return this;
|
||||
}
|
||||
|
||||
public static int MakeLParam(int x, int y) => (y << 16) | (x & 0xFFFF);
|
||||
|
||||
public PostMessageSimulator LeftButtonClick()
|
||||
{
|
||||
IntPtr p = (16 << 16) | 16;
|
||||
@@ -49,7 +66,7 @@ public class PostMessageSimulator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 默认位置左键按下
|
||||
/// 默认位置左键按下
|
||||
/// </summary>
|
||||
public PostMessageSimulator LeftButtonDown()
|
||||
{
|
||||
@@ -58,7 +75,7 @@ public class PostMessageSimulator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 默认位置左键释放
|
||||
/// 默认位置左键释放
|
||||
/// </summary>
|
||||
public PostMessageSimulator LeftButtonUp()
|
||||
{
|
||||
@@ -67,7 +84,7 @@ public class PostMessageSimulator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 默认位置右键按下
|
||||
/// 默认位置右键按下
|
||||
/// </summary>
|
||||
public PostMessageSimulator RightButtonDown()
|
||||
{
|
||||
@@ -76,7 +93,7 @@ public class PostMessageSimulator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 默认位置右键释放
|
||||
/// 默认位置右键释放
|
||||
/// </summary>
|
||||
public PostMessageSimulator RightButtonUp()
|
||||
{
|
||||
@@ -132,9 +149,32 @@ public class PostMessageSimulator
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyPressBackground(User32.VK vk)
|
||||
{
|
||||
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);
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyDownBackground(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
return this;
|
||||
}
|
||||
|
||||
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);
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,16 @@
|
||||
using System;
|
||||
using WindowsInput;
|
||||
using Fischless.WindowsInput;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Simulator;
|
||||
|
||||
public class Simulation
|
||||
{
|
||||
public static InputSimulator SendInput { get; } = new();
|
||||
|
||||
public static MouseEventSimulator MouseEvent { get; } = new();
|
||||
|
||||
public static PostMessageSimulator PostMessage(IntPtr hWnd)
|
||||
{
|
||||
return new PostMessageSimulator(hWnd);
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
public static InputSimulator SendInput { get; } = new();
|
||||
|
||||
public static Fischless.WindowsInput.InputSimulator SendInputEx { get; } = new();
|
||||
|
||||
public static MouseEventSimulator MouseEvent { get; } = new();
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
public class AutoCookTrigger : ITaskTrigger
|
||||
{
|
||||
private readonly ILogger<AutoCookTrigger> _logger = App.GetLogger<AutoCookTrigger>();
|
||||
|
||||
public string Name => "自动烹饪";
|
||||
public bool IsEnabled { get; set; }
|
||||
public int Priority => 50;
|
||||
public bool IsExclusive { get; set; }
|
||||
|
||||
public void Init()
|
||||
{
|
||||
IsEnabled = TaskContext.Instance().Config.AutoCookConfig.Enabled;
|
||||
IsExclusive = false;
|
||||
}
|
||||
|
||||
public void OnCapture(CaptureContent content)
|
||||
{
|
||||
// 判断是否处于烹饪界面
|
||||
IsExclusive = false;
|
||||
content.CaptureRectArea.Find(ElementAssets.Instance.UiLeftTopCookIcon, _ =>
|
||||
{
|
||||
IsExclusive = true;
|
||||
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
using var region = content.CaptureRectArea.DeriveCrop(0, captureRect.Height / 2, captureRect.Width, captureRect.Height / 2);
|
||||
var perfectBarRects = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 192, 64), 0, 8);
|
||||
if (perfectBarRects.Count >= 2)
|
||||
{
|
||||
// 点击烹饪按钮
|
||||
var btnList = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 255, 192), 12, 12);
|
||||
if (btnList.Count >= 1)
|
||||
{
|
||||
if (btnList.Count > 1)
|
||||
{
|
||||
_logger.LogWarning("自动烹饪:{Text}", "识别到多个结束烹饪按钮");
|
||||
btnList = [.. btnList.OrderByDescending(r => r.Width)];
|
||||
}
|
||||
var btn = btnList[0];
|
||||
var x = btn.X + btn.Width / 2;
|
||||
var y = btn.Y + btn.Height / 2;
|
||||
region.ClickTo(x, y);
|
||||
_logger.LogInformation("自动烹饪:{Text}", "点击结束按钮");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
/// <summary>
|
||||
///自动烹饪配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class AutoCookConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 触发器是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
}
|
||||
@@ -11,4 +11,19 @@ public partial class AutoDomainConfig : ObservableObject
|
||||
/// 战斗结束后延迟几秒再开始寻找石化古树,秒
|
||||
/// </summary>
|
||||
[ObservableProperty] private double _fightEndDelay = 5;
|
||||
|
||||
/// <summary>
|
||||
/// 寻找古树时,短距离移动,用于识别速度过慢的计算机使用
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _shortMovement = false;
|
||||
|
||||
/// <summary>
|
||||
/// 寻找古树时,短距离移动,用于识别速度过慢的计算机使用
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _walkToF = false;
|
||||
|
||||
/// <summary>
|
||||
/// 寻找古树时,短距离移动的次数
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _leftRightMoveTimes = 3;
|
||||
}
|
||||
@@ -5,18 +5,17 @@ namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
|
||||
public class AutoDomainParam : BaseTaskParam
|
||||
{
|
||||
|
||||
public int DomainRoundNum { get; set; }
|
||||
|
||||
public string CombatStrategyContent { get; set; }
|
||||
public string CombatStrategyPath { get; set; }
|
||||
|
||||
public AutoDomainParam(CancellationTokenSource cts, int domainRoundNum, string content) : base(cts)
|
||||
public AutoDomainParam(CancellationTokenSource cts, int domainRoundNum, string path) : base(cts)
|
||||
{
|
||||
DomainRoundNum = domainRoundNum;
|
||||
if (domainRoundNum == 0)
|
||||
{
|
||||
DomainRoundNum = 9999;
|
||||
}
|
||||
CombatStrategyContent = content;
|
||||
CombatStrategyPath = path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.AutoPick.Assets;
|
||||
using BetterGenshinImpact.GameTask.Common.MiniMap;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
using BetterGenshinImpact.GameTask.Model.Enum;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using Compunet.YoloV8;
|
||||
@@ -21,42 +24,52 @@ using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using static Vanara.PInvoke.User32;
|
||||
using System.Windows.Media.Media3D;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
|
||||
public class AutoDomainTask
|
||||
{
|
||||
private readonly AutoPickAssets _autoPickAssets = new();
|
||||
|
||||
private readonly AutoDomainParam _taskParam;
|
||||
|
||||
private readonly PostMessageSimulator _simulator;
|
||||
|
||||
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"));
|
||||
private readonly YoloV8 _predictor;
|
||||
|
||||
private readonly ClickOffset _clickOffset;
|
||||
private readonly AutoDomainConfig _config;
|
||||
|
||||
private readonly List<CombatCommand> _combatCommands;
|
||||
private readonly CombatScriptBag _combatScriptBag;
|
||||
|
||||
public AutoDomainTask(AutoDomainParam taskParam)
|
||||
{
|
||||
_taskParam = taskParam;
|
||||
_simulator = AutoFightContext.Instance().Simulator;
|
||||
_simulator = AutoFightContext.Instance.Simulator;
|
||||
|
||||
var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
_clickOffset = new ClickOffset(captureArea.X, captureArea.Y, assetScale);
|
||||
_combatCommands = CombatScriptParser.Parse(_taskParam.CombatStrategyContent);
|
||||
_predictor = new(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"), BgiSessionOption.Instance.Options);
|
||||
|
||||
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
|
||||
}
|
||||
|
||||
public async void Start()
|
||||
{
|
||||
var hasLock = false;
|
||||
try
|
||||
{
|
||||
AutoFightAssets.DestroyInstance();
|
||||
hasLock = await TaskSemaphore.WaitAsync(0);
|
||||
if (!hasLock)
|
||||
{
|
||||
Logger.LogError("启动自动秘境功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
|
||||
return;
|
||||
}
|
||||
|
||||
Init();
|
||||
var combatScenes = new CombatScenes().InitializeTeam(GetContentFromDispatcher());
|
||||
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build());
|
||||
|
||||
var combatScenes = new CombatScenes().InitializeTeam(GetRectAreaFromDispatcher());
|
||||
|
||||
// 前置进入秘境
|
||||
EnterDomain();
|
||||
@@ -89,21 +102,32 @@ public class AutoDomainTask
|
||||
|
||||
// 5. 快速领取奖励并判断是否有下一轮
|
||||
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
|
||||
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999))
|
||||
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
|
||||
{
|
||||
Logger.LogInformation("体力已经耗尽,结束自动秘境");
|
||||
if (i == _taskParam.DomainRoundNum - 1)
|
||||
{
|
||||
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("体力已经耗尽,结束自动秘境");
|
||||
}
|
||||
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Success().Build());
|
||||
break;
|
||||
}
|
||||
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Progress().Build());
|
||||
}
|
||||
}
|
||||
catch (NormalEndException e)
|
||||
{
|
||||
Logger.LogInformation("自动秘境中断:" + e.Message);
|
||||
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Cancelled().Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogError(e.Message);
|
||||
Logger.LogDebug(e.StackTrace);
|
||||
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Failure().Build());
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -111,6 +135,11 @@ public class AutoDomainTask
|
||||
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyTrigger);
|
||||
TaskSettingsPageViewModel.SetSwitchAutoDomainButtonText(false);
|
||||
Logger.LogInformation("→ {Text}", "自动秘境结束");
|
||||
|
||||
if (hasLock)
|
||||
{
|
||||
TaskSemaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,15 +157,19 @@ public class AutoDomainTask
|
||||
|
||||
SystemControl.ActivateWindow();
|
||||
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
|
||||
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, _taskParam.Cts); // 等待缓存图像
|
||||
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
|
||||
}
|
||||
|
||||
private void LogScreenResolution()
|
||||
{
|
||||
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
|
||||
if (gameScreenSize.Width != 1920 || gameScreenSize.Height != 1080)
|
||||
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
|
||||
{
|
||||
Logger.LogWarning("游戏窗口分辨率不是 1920x1080 !当前分辨率为 {Width}x{Height} , 非 1920x1080 分辨率的游戏可能无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
}
|
||||
if (gameScreenSize.Width < 1920 || gameScreenSize.Height < 1080)
|
||||
{
|
||||
Logger.LogWarning("游戏窗口分辨率小于 1920x1080 !当前分辨率为 {Width}x{Height} , 小于 1920x1080 的分辨率的游戏可能无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +177,7 @@ public class AutoDomainTask
|
||||
{
|
||||
if (!combatScenes.CheckTeamInitialized())
|
||||
{
|
||||
combatScenes.InitializeTeam(GetContentFromDispatcher());
|
||||
combatScenes.InitializeTeam(GetRectAreaFromDispatcher());
|
||||
if (!combatScenes.CheckTeamInitialized())
|
||||
{
|
||||
throw new Exception("识别队伍角色失败,请在较暗背景下重试,比如游戏时间调整成夜晚。或者直接使用强制指定当前队伍角色的功能。");
|
||||
@@ -154,12 +187,12 @@ public class AutoDomainTask
|
||||
|
||||
private void EnterDomain()
|
||||
{
|
||||
var fightAssets = AutoFightContext.Instance().FightAssets;
|
||||
var fightAssets = AutoFightContext.Instance.FightAssets;
|
||||
|
||||
var fRectArea = GetContentFromDispatcher().CaptureRectArea.Find(_autoPickAssets.FRo);
|
||||
using var fRectArea = GetRectAreaFromDispatcher().Find(AutoPickAssets.Instance.FRo);
|
||||
if (!fRectArea.IsEmpty())
|
||||
{
|
||||
Simulation.SendInputEx.Keyboard.KeyDown(VK.VK_F);
|
||||
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
|
||||
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
|
||||
// 秘境开门动画 5s
|
||||
Sleep(5000, _taskParam.Cts);
|
||||
@@ -169,10 +202,10 @@ public class AutoDomainTask
|
||||
while (retryTimes < 20 && clickCount < 2)
|
||||
{
|
||||
retryTimes++;
|
||||
var confirmRectArea = GetContentFromDispatcher().CaptureRectArea.Find(fightAssets.ConfirmRa);
|
||||
using var confirmRectArea = GetRectAreaFromDispatcher().Find(fightAssets.ConfirmRa);
|
||||
if (!confirmRectArea.IsEmpty())
|
||||
{
|
||||
confirmRectArea.ClickCenter();
|
||||
confirmRectArea.Click();
|
||||
clickCount++;
|
||||
}
|
||||
|
||||
@@ -190,11 +223,11 @@ public class AutoDomainTask
|
||||
while (retryTimes < 120)
|
||||
{
|
||||
retryTimes++;
|
||||
var cactRectArea = GetContentFromDispatcher().CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.ClickAnyCloseTipRa);
|
||||
using var cactRectArea = GetRectAreaFromDispatcher().Find(AutoFightContext.Instance.FightAssets.ClickAnyCloseTipRa);
|
||||
if (!cactRectArea.IsEmpty())
|
||||
{
|
||||
Sleep(1000, _taskParam.Cts);
|
||||
cactRectArea.ClickCenter();
|
||||
cactRectArea.Click();
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -220,13 +253,16 @@ public class AutoDomainTask
|
||||
_simulator.KeyDown(VK.VK_W);
|
||||
Sleep(20);
|
||||
// 组合键好像不能直接用 postmessage
|
||||
Simulation.SendInputEx.Keyboard.KeyDown(VK.VK_SHIFT);
|
||||
if (!_config.WalkToF)
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyDown(VK.VK_SHIFT);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
while (!_taskParam.Cts.Token.IsCancellationRequested)
|
||||
{
|
||||
var content = GetContentFromDispatcher();
|
||||
var fRectArea = content.CaptureRectArea.Find(_autoPickAssets.FRo);
|
||||
using var fRectArea = GetRectAreaFromDispatcher().Find(AutoPickAssets.Instance.FRo);
|
||||
if (fRectArea.IsEmpty())
|
||||
{
|
||||
Sleep(100, _taskParam.Cts);
|
||||
@@ -234,7 +270,7 @@ public class AutoDomainTask
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("检测到交互键");
|
||||
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_F);
|
||||
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -243,13 +279,18 @@ public class AutoDomainTask
|
||||
{
|
||||
_simulator.KeyUp(VK.VK_W);
|
||||
Sleep(50);
|
||||
Simulation.SendInputEx.Keyboard.KeyUp(VK.VK_SHIFT);
|
||||
if (!_config.WalkToF)
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyUp(VK.VK_SHIFT);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Task StartFight(CombatScenes combatScenes)
|
||||
{
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
|
||||
|
||||
CancellationTokenSource cts = new CancellationTokenSource();
|
||||
_taskParam.Cts.Token.Register(cts.Cancel);
|
||||
combatScenes.BeforeTask(cts);
|
||||
@@ -261,21 +302,25 @@ public class AutoDomainTask
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
{
|
||||
// 通用化战斗策略
|
||||
foreach (var command in _combatCommands)
|
||||
foreach (var command in combatCommands)
|
||||
{
|
||||
command.Execute(combatScenes);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (NormalEndException)
|
||||
catch (NormalEndException e)
|
||||
{
|
||||
Logger.LogInformation("战斗操作结束");
|
||||
Logger.LogInformation("战斗操作中断:{Msg}", e.Message);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogWarning(e.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Logger.LogInformation("自动战斗线程结束");
|
||||
}
|
||||
}, cts.Token);
|
||||
|
||||
// 视角操作
|
||||
@@ -326,9 +371,9 @@ public class AutoDomainTask
|
||||
|
||||
private bool IsDomainEnd()
|
||||
{
|
||||
var content = GetContentFromDispatcher();
|
||||
using var ra = GetRectAreaFromDispatcher();
|
||||
|
||||
var endTipsRect = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.EndTipsUpperRect);
|
||||
var endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsUpperRect);
|
||||
var text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
|
||||
if (text.Contains("挑战") || text.Contains("达成"))
|
||||
{
|
||||
@@ -336,10 +381,9 @@ public class AutoDomainTask
|
||||
return true;
|
||||
}
|
||||
|
||||
endTipsRect = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.EndTipsRect);
|
||||
var result = OcrFactory.Paddle.OcrResult(endTipsRect.SrcGreyMat);
|
||||
var rect = result.FindRectByText("自动退出");
|
||||
if (rect != Rect.Empty)
|
||||
endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsRect);
|
||||
text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
|
||||
if (text.Contains("自动") || text.Contains("退出"))
|
||||
{
|
||||
Logger.LogInformation("检测到秘境结束提示(xxx秒后自动退出),结束秘境");
|
||||
return true;
|
||||
@@ -348,7 +392,6 @@ public class AutoDomainTask
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 旋转视角后寻找石化古树
|
||||
/// </summary>
|
||||
@@ -373,7 +416,7 @@ public class AutoDomainTask
|
||||
{
|
||||
return new Task(() =>
|
||||
{
|
||||
var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
|
||||
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
var middleX = captureArea.Width / 2;
|
||||
var leftKeyDown = false;
|
||||
var rightKeyDown = false;
|
||||
@@ -382,12 +425,11 @@ public class AutoDomainTask
|
||||
var backwardsAndForwardsCount = 0;
|
||||
while (!_taskParam.Cts.Token.IsCancellationRequested)
|
||||
{
|
||||
var treeRect = DetectTree(GetContentFromDispatcher());
|
||||
var treeRect = DetectTree(GetRectAreaFromDispatcher());
|
||||
if (treeRect != Rect.Empty)
|
||||
{
|
||||
var treeMiddleX = treeRect.X + treeRect.Width / 2;
|
||||
var distance = Math.Abs(middleX - treeMiddleX);
|
||||
if (treeRect.X + treeRect.Width < middleX)
|
||||
if (treeRect.X + treeRect.Width < middleX && !_config.ShortMovement)
|
||||
{
|
||||
backwardsAndForwardsCount = 0;
|
||||
// 树在左边 往左走
|
||||
@@ -405,7 +447,7 @@ public class AutoDomainTask
|
||||
leftKeyDown = true;
|
||||
}
|
||||
}
|
||||
else if (treeRect.X > middleX)
|
||||
else if (treeRect.X > middleX && !_config.ShortMovement)
|
||||
{
|
||||
backwardsAndForwardsCount = 0;
|
||||
// 树在右边 往右走
|
||||
@@ -449,6 +491,7 @@ public class AutoDomainTask
|
||||
}
|
||||
|
||||
_simulator.KeyPress(VK.VK_A, 60);
|
||||
prevKey = VK.VK_A;
|
||||
}
|
||||
else if (treeMiddleX > middleX)
|
||||
{
|
||||
@@ -458,6 +501,7 @@ public class AutoDomainTask
|
||||
}
|
||||
|
||||
_simulator.KeyPress(VK.VK_D, 60);
|
||||
prevKey = VK.VK_D;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -503,7 +547,7 @@ public class AutoDomainTask
|
||||
}
|
||||
}
|
||||
|
||||
if (backwardsAndForwardsCount > 4)
|
||||
if (backwardsAndForwardsCount >= _config.LeftRightMoveTimes)
|
||||
{
|
||||
// 左右移动5次说明已经在树中心了
|
||||
_simulator.KeyPress(VK.VK_W, 60);
|
||||
@@ -519,17 +563,17 @@ public class AutoDomainTask
|
||||
});
|
||||
}
|
||||
|
||||
private Rect DetectTree(CaptureContent content)
|
||||
private Rect DetectTree(ImageRegion region)
|
||||
{
|
||||
using var memoryStream = new MemoryStream();
|
||||
content.CaptureRectArea.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
|
||||
region.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
|
||||
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
var result = _predictor.Detect(memoryStream);
|
||||
var list = new List<RectDrawable>();
|
||||
foreach (var box in result.Boxes)
|
||||
{
|
||||
var rect = new System.Windows.Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
|
||||
list.Add(new RectDrawable(rect));
|
||||
var rect = new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
|
||||
list.Add(region.ToRectDrawable(rect, "tree"));
|
||||
}
|
||||
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList("TreeBox", list);
|
||||
@@ -551,7 +595,9 @@ public class AutoDomainTask
|
||||
var started = false;
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
{
|
||||
var angle = CameraOrientation.Compute(GetContentFromDispatcher());
|
||||
using var captureRegion = GetRectAreaFromDispatcher();
|
||||
var angle = CameraOrientation.Compute(captureRegion.SrcGreyMat);
|
||||
CameraOrientation.DrawDirection(captureRegion, angle);
|
||||
if (angle is >= 356 or <= 4)
|
||||
{
|
||||
// 算作对准了
|
||||
@@ -567,7 +613,7 @@ public class AutoDomainTask
|
||||
moveAngle *= 2;
|
||||
}
|
||||
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(-moveAngle, 0);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(-moveAngle, 0);
|
||||
continuousCount = 0;
|
||||
}
|
||||
else if (angle is > 180 and < 360)
|
||||
@@ -579,7 +625,7 @@ public class AutoDomainTask
|
||||
moveAngle *= 2;
|
||||
}
|
||||
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(moveAngle, 0);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
|
||||
continuousCount = 0;
|
||||
}
|
||||
else
|
||||
@@ -607,7 +653,8 @@ public class AutoDomainTask
|
||||
/// 领取奖励
|
||||
/// </summary>
|
||||
/// <param name="recognizeResin">是否识别树脂</param>
|
||||
private bool GettingTreasure(bool recognizeResin)
|
||||
/// <param name="isLastTurn">是否最后一轮</param>
|
||||
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
|
||||
{
|
||||
// 等待窗口弹出
|
||||
Sleep(1500, _taskParam.Cts);
|
||||
@@ -623,36 +670,49 @@ public class AutoDomainTask
|
||||
break;
|
||||
}
|
||||
|
||||
var useCondensedResinRa = GetContentFromDispatcher().CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.UseCondensedResinRa);
|
||||
var useCondensedResinRa = GetRectAreaFromDispatcher().Find(AutoFightContext.Instance.FightAssets.UseCondensedResinRa);
|
||||
if (!useCondensedResinRa.IsEmpty())
|
||||
{
|
||||
useCondensedResinRa.ClickCenter();
|
||||
useCondensedResinRa.Click();
|
||||
// 点两下 #224 #218
|
||||
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
|
||||
Sleep(400, _taskParam.Cts);
|
||||
useCondensedResinRa.Click();
|
||||
break;
|
||||
}
|
||||
|
||||
Sleep(800, _taskParam.Cts);
|
||||
}
|
||||
|
||||
|
||||
Sleep(600, _taskParam.Cts);
|
||||
|
||||
Sleep(1000, _taskParam.Cts);
|
||||
|
||||
var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
|
||||
while (true)
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
// 跳过领取动画
|
||||
_clickOffset.ClickWithoutScale(captureArea.Width - (int)(140 * _clickOffset.AssetScale), (int)(53 * _clickOffset.AssetScale));
|
||||
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
|
||||
Sleep(200, _taskParam.Cts);
|
||||
_clickOffset.ClickWithoutScale(captureArea.Width - (int)(140 * _clickOffset.AssetScale), (int)(53 * _clickOffset.AssetScale));
|
||||
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
|
||||
|
||||
// 优先点击继续
|
||||
var content = GetContentFromDispatcher();
|
||||
var confirmRectArea = content.CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.ConfirmRa);
|
||||
var ra = GetRectAreaFromDispatcher();
|
||||
var confirmRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
|
||||
if (!confirmRectArea.IsEmpty())
|
||||
{
|
||||
if (isLastTurn)
|
||||
{
|
||||
// 最后一回合 退出
|
||||
var exitRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ExitRa);
|
||||
if (!exitRectArea.IsEmpty())
|
||||
{
|
||||
exitRectArea.Click();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!recognizeResin)
|
||||
{
|
||||
confirmRectArea.ClickCenter();
|
||||
confirmRectArea.Click();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -660,25 +720,25 @@ public class AutoDomainTask
|
||||
if (condensedResinCount == 0 && fragileResinCount < 20)
|
||||
{
|
||||
// 没有体力了退出
|
||||
var exitRectArea = content.CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.ExitRa);
|
||||
var exitRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ExitRa);
|
||||
if (!exitRectArea.IsEmpty())
|
||||
{
|
||||
exitRectArea.ClickCenter();
|
||||
exitRectArea.Click();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 有体力继续
|
||||
confirmRectArea.ClickCenter();
|
||||
break;
|
||||
confirmRectArea.Click();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Sleep(300, _taskParam.Cts);
|
||||
}
|
||||
|
||||
return true;
|
||||
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -689,24 +749,24 @@ public class AutoDomainTask
|
||||
var condensedResinCount = 0;
|
||||
var fragileResinCount = 0;
|
||||
|
||||
var content = GetContentFromDispatcher();
|
||||
var ra = GetRectAreaFromDispatcher();
|
||||
// 浓缩树脂
|
||||
var condensedResinCountRa = content.CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.CondensedResinCountRa);
|
||||
var condensedResinCountRa = ra.Find(AutoFightContext.Instance.FightAssets.CondensedResinCountRa);
|
||||
if (!condensedResinCountRa.IsEmpty())
|
||||
{
|
||||
// 图像右侧就是浓缩树脂数量
|
||||
var countArea = content.CaptureRectArea.Crop(new Rect(condensedResinCountRa.X + condensedResinCountRa.Width, condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height));
|
||||
var countArea = ra.DeriveCrop(condensedResinCountRa.X + condensedResinCountRa.Width, condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height);
|
||||
// Cv2.ImWrite($"log/resin_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")}.png", countArea.SrcGreyMat);
|
||||
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
|
||||
condensedResinCount = StringUtils.TryParseInt(count);
|
||||
}
|
||||
|
||||
// 脆弱树脂
|
||||
var fragileResinCountRa = content.CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.FragileResinCountRa);
|
||||
var fragileResinCountRa = ra.Find(AutoFightContext.Instance.FightAssets.FragileResinCountRa);
|
||||
if (!fragileResinCountRa.IsEmpty())
|
||||
{
|
||||
// 图像右侧就是脆弱树脂数量
|
||||
var countArea = content.CaptureRectArea.Crop(new Rect(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y, (int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height));
|
||||
var countArea = ra.DeriveCrop(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y, (int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height);
|
||||
var count = OcrFactory.Paddle.Ocr(countArea.SrcGreyMat);
|
||||
fragileResinCount = StringUtils.TryParseInt(count);
|
||||
}
|
||||
@@ -714,4 +774,4 @@ public class AutoDomainTask
|
||||
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 脆弱树脂 {FragileResinCount}", condensedResinCount, fragileResinCount);
|
||||
return (condensedResinCount, fragileResinCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
|
||||
public class AutoFightAssets
|
||||
public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
public Rect TeamRectNoIndex;
|
||||
public Rect TeamRect;
|
||||
public List<Rect> AvatarSideIconRectList;
|
||||
public List<Rect> AvatarIndexRectList;
|
||||
public Rect ERect;
|
||||
public Rect QRect;
|
||||
@@ -22,35 +24,59 @@ public class AutoFightAssets
|
||||
|
||||
// 树脂状态
|
||||
public RecognitionObject CondensedResinCountRa;
|
||||
|
||||
public RecognitionObject FragileResinCountRa;
|
||||
|
||||
public AutoFightAssets()
|
||||
public Dictionary<string, string> AvatarCostumeMap;
|
||||
|
||||
private AutoFightAssets()
|
||||
{
|
||||
var info = TaskContext.Instance().SystemInfo;
|
||||
var captureRect = info.CaptureAreaRect;
|
||||
var assetScale = info.AssetScale;
|
||||
|
||||
TeamRectNoIndex = new Rect(captureRect.Width - (int)(355 * assetScale), (int)(220 * assetScale),
|
||||
(int)((355 - 85) * assetScale), (int)(465 * assetScale));
|
||||
TeamRect = new Rect(captureRect.Width - (int)(355 * assetScale), (int)(220 * assetScale),
|
||||
(int)(355 * assetScale), (int)(465 * assetScale));
|
||||
ERect = new Rect(captureRect.Width - (int)(267 * assetScale), captureRect.Height - (int)(132 * assetScale),
|
||||
(int)(77 * assetScale), (int)(77 * assetScale));
|
||||
QRect = new Rect(captureRect.Width - (int)(157 * assetScale), captureRect.Height - (int)(165 * assetScale),
|
||||
(int)(110 * assetScale), (int)(110 * assetScale));
|
||||
TeamRectNoIndex = new Rect(CaptureRect.Width - (int)(355 * AssetScale), (int)(220 * AssetScale),
|
||||
(int)((355 - 85) * AssetScale), (int)(465 * AssetScale));
|
||||
TeamRect = new Rect(CaptureRect.Width - (int)(355 * AssetScale), (int)(220 * AssetScale),
|
||||
(int)(355 * AssetScale), (int)(465 * AssetScale));
|
||||
ERect = new Rect(CaptureRect.Width - (int)(267 * AssetScale), CaptureRect.Height - (int)(132 * AssetScale),
|
||||
(int)(77 * AssetScale), (int)(77 * AssetScale));
|
||||
QRect = new Rect(CaptureRect.Width - (int)(157 * AssetScale), CaptureRect.Height - (int)(165 * AssetScale),
|
||||
(int)(110 * AssetScale), (int)(110 * AssetScale));
|
||||
// 结束提示从中间开始找相对位置
|
||||
EndTipsUpperRect = new Rect(captureRect.Width / 2 - (int)(100 * assetScale), (int)(243 * assetScale),
|
||||
(int)(200 * assetScale), (int)(50 * assetScale));
|
||||
EndTipsRect = new Rect(captureRect.Width / 2 - (int)(200 * assetScale), captureRect.Height - (int)(160 * assetScale),
|
||||
(int)(400 * assetScale), (int)(80 * assetScale));
|
||||
EndTipsUpperRect = new Rect(CaptureRect.Width / 2 - (int)(100 * AssetScale), (int)(243 * AssetScale),
|
||||
(int)(200 * AssetScale), (int)(50 * AssetScale));
|
||||
EndTipsRect = new Rect(CaptureRect.Width / 2 - (int)(200 * AssetScale), CaptureRect.Height - (int)(160 * AssetScale),
|
||||
(int)(400 * AssetScale), (int)(80 * AssetScale));
|
||||
|
||||
AvatarIndexRectList =
|
||||
[
|
||||
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(256 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(352 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(448 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(544 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
|
||||
];
|
||||
|
||||
AvatarIndexRectList = new List<Rect>
|
||||
AvatarSideIconRectList =
|
||||
[
|
||||
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(225 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(315 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(410 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(500 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
|
||||
];
|
||||
|
||||
AvatarCostumeMap = new Dictionary<string, string>
|
||||
{
|
||||
new(captureRect.Width - (int)(61 * assetScale), (int)(256 * assetScale), (int)(28 * assetScale), (int)(24 * assetScale)),
|
||||
new(captureRect.Width - (int)(61 * assetScale), (int)(352 * assetScale), (int)(28 * assetScale), (int)(24 * assetScale)),
|
||||
new(captureRect.Width - (int)(61 * assetScale), (int)(448 * assetScale), (int)(28 * assetScale), (int)(24 * assetScale)),
|
||||
new(captureRect.Width - (int)(61 * assetScale), (int)(544 * assetScale), (int)(28 * assetScale), (int)(24 * assetScale)),
|
||||
{ "Flamme", "殷红终夜" },
|
||||
{ "Bamboo", "雨化竹身" },
|
||||
{ "Dai", "冷花幽露" },
|
||||
{ "Yu", "玄玉瑶芳" },
|
||||
{ "Dancer", "帆影游风" },
|
||||
{ "Witch", "琪花星烛" },
|
||||
{ "Wic", "和谐" },
|
||||
{ "Studentin", "叶隐芳名" },
|
||||
{ "Fruhling", "花时来信" },
|
||||
{ "Highness", "极夜真梦" },
|
||||
{ "Feather", "霓裾翩跹" },
|
||||
{ "Floral", "纱中幽兰" },
|
||||
{ "Summertime", "闪耀协奏" },
|
||||
{ "Sea", "海风之梦" },
|
||||
};
|
||||
|
||||
WandererIconRa = new RecognitionObject
|
||||
@@ -74,7 +100,7 @@ public class AutoFightAssets
|
||||
Name = "Confirm",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "confirm.png"),
|
||||
RegionOfInterest = new Rect(captureRect.Width / 2, captureRect.Height / 2, captureRect.Width / 2, captureRect.Height / 2),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 2, CaptureRect.Width / 2, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
@@ -84,7 +110,7 @@ public class AutoFightAssets
|
||||
Name = "ClickAnyCloseTip",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "click_any_close_tip.png"),
|
||||
RegionOfInterest = new Rect(0, captureRect.Height / 2, captureRect.Width, captureRect.Height / 2),
|
||||
RegionOfInterest = new Rect(0, CaptureRect.Height / 2, CaptureRect.Width, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
@@ -93,7 +119,7 @@ public class AutoFightAssets
|
||||
Name = "UseCondensedResin",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "use_condensed_resin.png"),
|
||||
RegionOfInterest = new Rect(0, captureRect.Height / 2, captureRect.Width / 2, captureRect.Height / 2),
|
||||
RegionOfInterest = new Rect(0, CaptureRect.Height / 2, CaptureRect.Width / 2, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
@@ -102,7 +128,7 @@ public class AutoFightAssets
|
||||
Name = "Exit",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "exit.png"),
|
||||
RegionOfInterest = new Rect(0, captureRect.Height / 2, captureRect.Width / 2, captureRect.Height / 2),
|
||||
RegionOfInterest = new Rect(0, CaptureRect.Height / 2, CaptureRect.Width / 2, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
@@ -111,7 +137,7 @@ public class AutoFightAssets
|
||||
Name = "CondensedResinCount",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "condensed_resin_count.png"),
|
||||
RegionOfInterest = new Rect(captureRect.Width / 2, captureRect.Height / 3 * 2, captureRect.Width / 2, captureRect.Height / 3),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 3 * 2, CaptureRect.Width / 2, CaptureRect.Height / 3),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
FragileResinCountRa = new RecognitionObject
|
||||
@@ -119,8 +145,8 @@ public class AutoFightAssets
|
||||
Name = "FragileResinCount",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "fragile_resin_count.png"),
|
||||
RegionOfInterest = new Rect(captureRect.Width / 2, captureRect.Height / 3 * 2, captureRect.Width / 2, captureRect.Height / 3),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 3 * 2, CaptureRect.Width / 2, CaptureRect.Height / 3),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,18 +10,18 @@
|
||||
"alias": [ "荧", "女主", "女主角", "莹", "萤", "黄毛阿姨", "荧妹", "女爷" ],
|
||||
"id": "10000007",
|
||||
"name": "荧",
|
||||
"nameEn": "荧",
|
||||
"nameEn": "PlayerGirl",
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [ "空", "男主", "男主角", "龙哥", "空哥", "男爷" ],
|
||||
"id": "10000005",
|
||||
"name": "空",
|
||||
"nameEn": "空",
|
||||
"nameEn": "PlayerBoy",
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [ "神里绫华", "Kamisato Ayaka", "Ayaka", "ayaka", "神里", "绫华", "神里凌华", "凌华", "白鹭公主", "神里大小姐", "小乌龟", "龟龟" ],
|
||||
"alias": [ "神里绫华", "Kamisato Ayaka", "Ayaka", "ayaka", "神里", "绫华", "神里凌华", "凌华", "白鹭公主", "神里大小姐", "小乌龟", "龟龟", "山里灵活" ],
|
||||
"burstCD": 20.0,
|
||||
"id": "10000002",
|
||||
"name": "神里绫华",
|
||||
@@ -716,5 +716,41 @@
|
||||
"nameEn": "Navia",
|
||||
"skillCD": 9.0,
|
||||
"weapon": "11"
|
||||
},
|
||||
{
|
||||
"alias": [ "嘉明", "Gaming", "gaming", "佳明", "嘉铭", "镖师", "威水舞兽", "威水舞兽话事人", "舞狮少年", "雄狮少年", "嘉乐" ],
|
||||
"burstCD": 15.0,
|
||||
"id": "10000092",
|
||||
"name": "嘉明",
|
||||
"nameEn": "Gaming",
|
||||
"skillCD": 6.0,
|
||||
"weapon": "11"
|
||||
},
|
||||
{
|
||||
"alias": [ "闲云", "Xianyun", "xianyun", "留云", "流云", "留云借风", "留云借风真君", "仙鹤", "仙鸟", "那个女人", "哪个女人", "那只鸟", "那只鸡", "闲云阿姨", "机关仙人", "很会聊天真君", "很会说话真君", "两块禽肉真君", "鸟人" ],
|
||||
"burstCD": 18.0,
|
||||
"id": "10000093",
|
||||
"name": "闲云",
|
||||
"nameEn": "Liuyun",
|
||||
"skillCD": 12.0,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [ "千织", "Chiori", "chiori", "老板娘", "裁锦师", "裁缝" ],
|
||||
"burstCD": 13.5,
|
||||
"id": "10000094",
|
||||
"name": "千织",
|
||||
"nameEn": "Chiori",
|
||||
"skillCD": 16.0,
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [ "阿蕾奇诺", "Arlecchino", "阿雷奇诺", "仆人", "黑优菈", "黑暗优菈", "父亲", "佩露薇利" ],
|
||||
"burstCD": 15.0,
|
||||
"id": "10000096",
|
||||
"name": "阿蕾奇诺",
|
||||
"nameEn": "Arlecchino",
|
||||
"skillCD": 30.0,
|
||||
"weapon": "13"
|
||||
}
|
||||
]
|
||||
@@ -1,10 +1,6 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Model;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
@@ -12,37 +8,20 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
/// 自动战斗上下文
|
||||
/// 请在启动BetterGI以后再初始化
|
||||
/// </summary>
|
||||
public class AutoFightContext
|
||||
public class AutoFightContext : Singleton<AutoFightContext>
|
||||
{
|
||||
|
||||
private static AutoFightContext? _uniqueInstance;
|
||||
private static readonly object Locker = new();
|
||||
|
||||
private AutoFightContext()
|
||||
{
|
||||
FightAssets = new();
|
||||
Simulator = Simulation.PostMessage(TaskContext.Instance().GameHandle);
|
||||
}
|
||||
|
||||
public static AutoFightContext Instance()
|
||||
{
|
||||
if (_uniqueInstance == null)
|
||||
{
|
||||
lock (Locker)
|
||||
{
|
||||
_uniqueInstance ??= new AutoFightContext();
|
||||
}
|
||||
}
|
||||
return _uniqueInstance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// find资源
|
||||
/// </summary>
|
||||
public readonly AutoFightAssets FightAssets;
|
||||
public AutoFightAssets FightAssets => AutoFightAssets.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// 战斗专用的PostMessage模拟键鼠操作
|
||||
/// </summary>
|
||||
public readonly PostMessageSimulator Simulator;
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,10 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
public class AutoFightParam : BaseTaskParam
|
||||
{
|
||||
public string CombatStrategyContent { get; set; }
|
||||
public AutoFightParam(CancellationTokenSource cts, string content) : base(cts)
|
||||
public string CombatStrategyPath { get; set; }
|
||||
|
||||
public AutoFightParam(CancellationTokenSource cts, string path) : base(cts)
|
||||
{
|
||||
CombatStrategyContent = content;
|
||||
CombatStrategyPath = path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.Model.Enum;
|
||||
@@ -6,10 +7,8 @@ using BetterGenshinImpact.View.Drawable;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using static Vanara.PInvoke.Gdi32;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
@@ -17,24 +16,34 @@ public class AutoFightTask
|
||||
{
|
||||
private readonly AutoFightParam _taskParam;
|
||||
|
||||
private readonly List<CombatCommand> _combatCommands;
|
||||
private readonly CombatScriptBag _combatScriptBag;
|
||||
|
||||
public AutoFightTask(AutoFightParam taskParam)
|
||||
{
|
||||
_taskParam = taskParam;
|
||||
_combatCommands = CombatScriptParser.Parse(_taskParam.CombatStrategyContent);
|
||||
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
|
||||
}
|
||||
|
||||
public async void Start()
|
||||
{
|
||||
var hasLock = false;
|
||||
try
|
||||
{
|
||||
AutoFightAssets.DestroyInstance();
|
||||
hasLock = await TaskSemaphore.WaitAsync(0);
|
||||
if (!hasLock)
|
||||
{
|
||||
Logger.LogError("启动自动战斗功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
|
||||
return;
|
||||
}
|
||||
|
||||
Init();
|
||||
var combatScenes = new CombatScenes().InitializeTeam(GetContentFromDispatcher());
|
||||
var combatScenes = new CombatScenes().InitializeTeam(GetRectAreaFromDispatcher());
|
||||
if (!combatScenes.CheckTeamInitialized())
|
||||
{
|
||||
throw new Exception("识别队伍角色失败,请在较暗背景下重试,比如游戏时间调整成夜晚。或者直接使用强制指定当前队伍角色的功能。");
|
||||
throw new Exception("识别队伍角色失败");
|
||||
}
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
|
||||
|
||||
combatScenes.BeforeTask(_taskParam.Cts);
|
||||
|
||||
@@ -46,7 +55,7 @@ public class AutoFightTask
|
||||
while (!_taskParam.Cts.Token.IsCancellationRequested)
|
||||
{
|
||||
// 通用化战斗策略
|
||||
foreach (var command in _combatCommands)
|
||||
foreach (var command in combatCommands)
|
||||
{
|
||||
command.Execute(combatScenes);
|
||||
}
|
||||
@@ -65,7 +74,7 @@ public class AutoFightTask
|
||||
}
|
||||
catch (NormalEndException)
|
||||
{
|
||||
Logger.LogInformation("手动中断自动秘境");
|
||||
Logger.LogInformation("手动中断自动战斗");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -78,6 +87,11 @@ public class AutoFightTask
|
||||
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyTrigger);
|
||||
TaskSettingsPageViewModel.SetSwitchAutoFightButtonText(false);
|
||||
Logger.LogInformation("→ {Text}", "自动战斗结束");
|
||||
|
||||
if (hasLock)
|
||||
{
|
||||
TaskSemaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,15 +101,15 @@ public class AutoFightTask
|
||||
Logger.LogInformation("→ {Text}", "自动战斗,启动!");
|
||||
SystemControl.ActivateWindow();
|
||||
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
|
||||
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, _taskParam.Cts); // 等待缓存图像
|
||||
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
|
||||
}
|
||||
|
||||
private void LogScreenResolution()
|
||||
{
|
||||
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
|
||||
if (gameScreenSize.Width != 1920 || gameScreenSize.Height != 1080)
|
||||
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
|
||||
{
|
||||
Logger.LogWarning("游戏窗口分辨率不是 1920x1080 !当前分辨率为 {Width}x{Height} , 非 1920x1080 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ public class DefaultAutoFightConfig
|
||||
public static List<CombatAvatar> CombatAvatars { get; set; }
|
||||
public static List<string> CombatAvatarNames { get; set; }
|
||||
public static Dictionary<string, CombatAvatar> CombatAvatarMap { get; set; }
|
||||
public static Dictionary<string, CombatAvatar> CombatAvatarNameEnMap { get; set; }
|
||||
|
||||
static DefaultAutoFightConfig()
|
||||
{
|
||||
@@ -21,5 +22,17 @@ public class DefaultAutoFightConfig
|
||||
CombatAvatars = config ?? throw new Exception("combat_avatar.json deserialize failed");
|
||||
CombatAvatarNames = config.Select(x => x.Name).ToList();
|
||||
CombatAvatarMap = config.ToDictionary(x => x.Name);
|
||||
CombatAvatarNameEnMap = config.ToDictionary(x => x.NameEn);
|
||||
}
|
||||
}
|
||||
|
||||
public static string AvatarAliasToStandardName(string alias)
|
||||
{
|
||||
var avatar = CombatAvatars.Find(x => x.Alias.Contains(alias));
|
||||
if (avatar == null)
|
||||
{
|
||||
throw new Exception($"角色名称校验失败:{alias}");
|
||||
}
|
||||
|
||||
return avatar.Name;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
@@ -8,6 +9,8 @@ using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
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;
|
||||
@@ -98,16 +101,16 @@ public class Avatar
|
||||
/// 是否存在角色被击败
|
||||
/// 通过判断确认按钮
|
||||
/// </summary>
|
||||
/// <param name="content"></param>
|
||||
/// <param name="region"></param>
|
||||
/// <returns></returns>
|
||||
public void ThrowWhenDefeated(CaptureContent content)
|
||||
public void ThrowWhenDefeated(ImageRegion region)
|
||||
{
|
||||
var confirmRectArea = content.CaptureRectArea.Find(AutoFightContext.Instance().FightAssets.ConfirmRa);
|
||||
using var confirmRectArea = region.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
|
||||
if (!confirmRectArea.IsEmpty())
|
||||
{
|
||||
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
|
||||
Sleep(600, Cts);
|
||||
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_M);
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
|
||||
throw new Exception("存在角色被击败,按 M 键打开地图,并停止自动秘境。");
|
||||
}
|
||||
}
|
||||
@@ -118,24 +121,26 @@ public class Avatar
|
||||
/// </summary>
|
||||
public void Switch()
|
||||
{
|
||||
for (var i = 0; i < 40; i++)
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
if (Cts is { IsCancellationRequested: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var content = GetContentFromDispatcher();
|
||||
ThrowWhenDefeated(content);
|
||||
var region = GetRectAreaFromDispatcher();
|
||||
ThrowWhenDefeated(region);
|
||||
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(content));
|
||||
if (IsActive(content) && notActiveCount == 3)
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == 3)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
|
||||
Sleep(250, Cts); // 比1秒多一点,给截图留出时间
|
||||
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
|
||||
// Debug.WriteLine($"切换到{Index}号位");
|
||||
// Cv2.ImWrite($"log/切换.png", content.CaptureRectArea.SrcMat);
|
||||
Sleep(250, Cts);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +148,7 @@ public class Avatar
|
||||
/// 是否出战状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool IsActive(CaptureContent content)
|
||||
public bool IsActive(ImageRegion region)
|
||||
{
|
||||
if (IndexRect == Rect.Empty)
|
||||
{
|
||||
@@ -152,9 +157,9 @@ public class Avatar
|
||||
else
|
||||
{
|
||||
// 剪裁出IndexRect区域
|
||||
var indexRa = content.CaptureRectArea.Crop(IndexRect);
|
||||
// Cv2.ImWrite($"indexRa_{Name}.png", indexRa.SrcMat);
|
||||
var count = OpenCvCommonHelper.CountGrayMatColor(indexRa.SrcGreyMat, 255);
|
||||
var indexRa = region.DeriveCrop(IndexRect);
|
||||
// Cv2.ImWrite($"log/indexRa_{Name}.png", indexRa.SrcMat);
|
||||
var count = OpenCvCommonHelper.CountGrayMatColor(indexRa.SrcGreyMat, 251, 255);
|
||||
if (count * 1.0 / (IndexRect.Width * IndexRect.Height) > 0.5)
|
||||
{
|
||||
return false;
|
||||
@@ -171,16 +176,16 @@ public class Avatar
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
public bool IsActiveNoIndexRect(CaptureContent content)
|
||||
public bool IsActiveNoIndexRect(ImageRegion region)
|
||||
{
|
||||
// 通过寻找右侧人物编号来判断是否出战
|
||||
if (IndexRect == Rect.Empty)
|
||||
{
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
// 剪裁出队伍区域
|
||||
var teamRa = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.TeamRect);
|
||||
var teamRa = region.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRect);
|
||||
var blockX = NameRect.X + NameRect.Width * 2 - 10;
|
||||
var block = teamRa.Crop(new Rect(blockX, NameRect.Y, teamRa.Width - blockX, NameRect.Height * 2));
|
||||
var block = teamRa.DeriveCrop(new Rect(blockX, NameRect.Y, teamRa.Width - blockX, NameRect.Height * 2));
|
||||
// Cv2.ImWrite($"block_{Name}.png", block.SrcMat);
|
||||
// 取白色区域
|
||||
var bMat = OpenCvCommonHelper.Threshold(block.SrcMat, new Scalar(255, 255, 255), new Scalar(255, 255, 255));
|
||||
@@ -201,9 +206,9 @@ public class Avatar
|
||||
else
|
||||
{
|
||||
// 剪裁出IndexRect区域
|
||||
var teamRa = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.TeamRect);
|
||||
var teamRa = region.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRect);
|
||||
var blockX = NameRect.X + NameRect.Width * 2 - 10;
|
||||
var indexBlock = teamRa.Crop(new Rect(blockX + IndexRect.X, NameRect.Y + IndexRect.Y, IndexRect.Width, IndexRect.Height));
|
||||
var indexBlock = teamRa.DeriveCrop(new Rect(blockX + IndexRect.X, NameRect.Y + IndexRect.Y, IndexRect.Width, IndexRect.Height));
|
||||
// Cv2.ImWrite($"indexBlock_{Name}.png", indexBlock.SrcMat);
|
||||
var count = OpenCvCommonHelper.CountGrayMatColor(indexBlock.SrcGreyMat, 255);
|
||||
if (count * 1.0 / (IndexRect.Width * IndexRect.Height) > 0.5)
|
||||
@@ -229,7 +234,7 @@ public class Avatar
|
||||
return;
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.LeftButtonClick();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonClick();
|
||||
ms -= 200;
|
||||
Sleep(200, Cts);
|
||||
}
|
||||
@@ -251,32 +256,32 @@ public class Avatar
|
||||
{
|
||||
if (Name == "纳西妲")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.KeyDown(User32.VK.VK_E);
|
||||
AutoFightContext.Instance.Simulator.KeyDown(User32.VK.VK_E);
|
||||
Sleep(300, Cts);
|
||||
for (int j = 0; j < 10; j++)
|
||||
{
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(1000, 0);
|
||||
Sleep(50, Cts);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
|
||||
Sleep(50); // 持续操作不应该被cts取消
|
||||
}
|
||||
|
||||
Sleep(300, Cts);
|
||||
AutoFightContext.Instance().Simulator.KeyUp(User32.VK.VK_E);
|
||||
Sleep(300); // 持续操作不应该被cts取消
|
||||
AutoFightContext.Instance.Simulator.KeyUp(User32.VK.VK_E);
|
||||
}
|
||||
else
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LongKeyPress(User32.VK.VK_E);
|
||||
AutoFightContext.Instance.Simulator.LongKeyPress(User32.VK.VK_E);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.KeyPress(User32.VK.VK_E);
|
||||
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_E);
|
||||
}
|
||||
|
||||
Sleep(200, Cts);
|
||||
|
||||
var content = GetContentFromDispatcher();
|
||||
ThrowWhenDefeated(content);
|
||||
var cd = GetSkillCurrentCd(content);
|
||||
var region = GetRectAreaFromDispatcher();
|
||||
ThrowWhenDefeated(region);
|
||||
var cd = GetSkillCurrentCd(region);
|
||||
if (cd > 0)
|
||||
{
|
||||
Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd}" : "{Name} 点按元素战技,cd:{Cd}", Name, cd);
|
||||
@@ -291,9 +296,9 @@ public class Avatar
|
||||
/// 右下 267x132
|
||||
/// 77x77
|
||||
/// </summary>
|
||||
public double GetSkillCurrentCd(CaptureContent content)
|
||||
public double GetSkillCurrentCd(ImageRegion imageRegion)
|
||||
{
|
||||
var eRa = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.ERect);
|
||||
var eRa = imageRegion.DeriveCrop(AutoFightContext.Instance.FightAssets.ERect);
|
||||
var text = OcrFactory.Paddle.Ocr(eRa.SrcGreyMat);
|
||||
return StringUtils.TryParseDouble(text);
|
||||
}
|
||||
@@ -312,12 +317,12 @@ public class Avatar
|
||||
return;
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.KeyPress(User32.VK.VK_Q);
|
||||
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_Q);
|
||||
Sleep(200, Cts);
|
||||
|
||||
var content = GetContentFromDispatcher();
|
||||
ThrowWhenDefeated(content);
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(content));
|
||||
var region = GetRectAreaFromDispatcher();
|
||||
ThrowWhenDefeated(region);
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
if (notActiveCount == 0)
|
||||
{
|
||||
// isBurstReleased = true;
|
||||
@@ -340,17 +345,17 @@ public class Avatar
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 元素爆发是否正在CD中
|
||||
/// 右下 157x165
|
||||
/// 110x110
|
||||
/// </summary>
|
||||
public double GetBurstCurrentCd(CaptureContent content)
|
||||
{
|
||||
var qRa = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.QRect);
|
||||
var text = OcrFactory.Paddle.Ocr(qRa.SrcGreyMat);
|
||||
return StringUtils.TryParseDouble(text);
|
||||
}
|
||||
// /// <summary>
|
||||
// /// 元素爆发是否正在CD中
|
||||
// /// 右下 157x165
|
||||
// /// 110x110
|
||||
// /// </summary>
|
||||
// public double GetBurstCurrentCd(CaptureContent content)
|
||||
// {
|
||||
// var qRa = content.CaptureRectArea.Crop(AutoFightContext.Instance.FightAssets.QRect);
|
||||
// var text = OcrFactory.Paddle.Ocr(qRa.SrcGreyMat);
|
||||
// return StringUtils.TryParseDouble(text);
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 冲刺
|
||||
@@ -367,12 +372,11 @@ public class Avatar
|
||||
ms = 200;
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.RightButtonDown();
|
||||
Sleep(ms, Cts);
|
||||
AutoFightContext.Instance().Simulator.RightButtonUp();
|
||||
AutoFightContext.Instance.Simulator.RightButtonDown();
|
||||
Sleep(ms); // 冲刺不能被cts取消
|
||||
AutoFightContext.Instance.Simulator.RightButtonUp();
|
||||
}
|
||||
|
||||
|
||||
public void Walk(string key, int ms)
|
||||
{
|
||||
if (Cts is { IsCancellationRequested: true })
|
||||
@@ -403,9 +407,9 @@ public class Avatar
|
||||
return;
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.KeyDown(vk);
|
||||
Sleep(ms, Cts);
|
||||
AutoFightContext.Instance().Simulator.KeyUp(vk);
|
||||
AutoFightContext.Instance.Simulator.KeyDown(vk);
|
||||
Sleep(ms); // 行走不能被cts取消
|
||||
AutoFightContext.Instance.Simulator.KeyUp(vk);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -415,7 +419,7 @@ public class Avatar
|
||||
/// <param name="pixelDeltaY"></param>
|
||||
public void MoveCamera(int pixelDeltaX, int pixelDeltaY)
|
||||
{
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(pixelDeltaX, pixelDeltaY);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(pixelDeltaX, pixelDeltaY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -424,7 +428,7 @@ public class Avatar
|
||||
/// <param name="ms"></param>
|
||||
public void Wait(int ms)
|
||||
{
|
||||
Sleep(ms, Cts);
|
||||
Sleep(ms); // 由于存在宏操作,等待不应被cts取消
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -432,7 +436,7 @@ public class Avatar
|
||||
/// </summary>
|
||||
public void Jump()
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.KeyPress(User32.VK.VK_SPACE);
|
||||
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_SPACE);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -447,7 +451,7 @@ public class Avatar
|
||||
|
||||
if (Name == "那维莱特")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LeftButtonDown();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonDown();
|
||||
while (ms >= 0)
|
||||
{
|
||||
if (Cts is { IsCancellationRequested: true })
|
||||
@@ -455,32 +459,31 @@ public class Avatar
|
||||
return;
|
||||
}
|
||||
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(1000, 0);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
|
||||
ms -= 50;
|
||||
Sleep(50, Cts);
|
||||
Sleep(50); // 持续操作不应该被cts取消
|
||||
}
|
||||
|
||||
AutoFightContext.Instance().Simulator.LeftButtonUp();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LeftButtonDown();
|
||||
Sleep(ms, Cts);
|
||||
AutoFightContext.Instance().Simulator.LeftButtonUp();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonDown();
|
||||
Sleep(ms); // 持续操作不应该被cts取消
|
||||
AutoFightContext.Instance.Simulator.LeftButtonUp();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void MouseDown(string key = "left")
|
||||
{
|
||||
key = key.ToLower();
|
||||
if (key == "left")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LeftButtonDown();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonDown();
|
||||
}
|
||||
else if (key == "right")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.RightButtonDown();
|
||||
AutoFightContext.Instance.Simulator.RightButtonDown();
|
||||
}
|
||||
else if (key == "middle")
|
||||
{
|
||||
@@ -493,11 +496,11 @@ public class Avatar
|
||||
key = key.ToLower();
|
||||
if (key == "left")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LeftButtonUp();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonUp();
|
||||
}
|
||||
else if (key == "right")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.RightButtonUp();
|
||||
AutoFightContext.Instance.Simulator.RightButtonUp();
|
||||
}
|
||||
else if (key == "middle")
|
||||
{
|
||||
@@ -510,11 +513,11 @@ public class Avatar
|
||||
key = key.ToLower();
|
||||
if (key == "left")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.LeftButtonClick();
|
||||
AutoFightContext.Instance.Simulator.LeftButtonClick();
|
||||
}
|
||||
else if (key == "right")
|
||||
{
|
||||
AutoFightContext.Instance().Simulator.RightButtonClick();
|
||||
AutoFightContext.Instance.Simulator.RightButtonClick();
|
||||
}
|
||||
else if (key == "middle")
|
||||
{
|
||||
@@ -524,25 +527,25 @@ public class Avatar
|
||||
|
||||
public void MoveBy(int x, int y)
|
||||
{
|
||||
Simulation.SendInputEx.Mouse.MoveMouseBy(x, y);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
|
||||
}
|
||||
|
||||
public void KeyDown(string key)
|
||||
{
|
||||
var vk = ToVk(key);
|
||||
AutoFightContext.Instance().Simulator.KeyDown(vk);
|
||||
AutoFightContext.Instance.Simulator.KeyDown(vk);
|
||||
}
|
||||
|
||||
public void KeyUp(string key)
|
||||
{
|
||||
var vk = ToVk(key);
|
||||
AutoFightContext.Instance().Simulator.KeyUp(vk);
|
||||
AutoFightContext.Instance.Simulator.KeyUp(vk);
|
||||
}
|
||||
|
||||
public void KeyPress(string key)
|
||||
{
|
||||
var vk = ToVk(key);
|
||||
AutoFightContext.Instance().Simulator.KeyPress(vk);
|
||||
AutoFightContext.Instance.Simulator.KeyPress(vk);
|
||||
}
|
||||
|
||||
public static User32.VK ToVk(string key)
|
||||
@@ -555,4 +558,4 @@ public class Avatar
|
||||
|
||||
return (User32.VK)Enum.Parse(typeof(User32.VK), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
public class AvatarMacro
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string ScriptContent1 { get; set; } = string.Empty;
|
||||
public string ScriptContent2 { get; set; } = string.Empty;
|
||||
public string ScriptContent3 { get; set; } = string.Empty;
|
||||
public string ScriptContent4 { get; set; } = string.Empty;
|
||||
public string ScriptContent5 { get; set; } = string.Empty;
|
||||
|
||||
public string GetScriptContent(int index)
|
||||
{
|
||||
return index switch
|
||||
{
|
||||
1 => ScriptContent1,
|
||||
2 => ScriptContent2,
|
||||
3 => ScriptContent3,
|
||||
4 => ScriptContent4,
|
||||
5 => ScriptContent5,
|
||||
_ => string.Empty
|
||||
};
|
||||
}
|
||||
|
||||
public string GetScriptContent()
|
||||
{
|
||||
return GetScriptContent(TaskContext.Instance().Config.MacroConfig.CombatMacroPriority);
|
||||
}
|
||||
|
||||
public List<CombatCommand>? LoadCommands()
|
||||
{
|
||||
var content = GetScriptContent();
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return CombatScriptParser.ParseLineCommands(content, Name);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Compunet.YoloV8;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Extensions;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Xml.Linq;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
@@ -19,7 +26,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
/// <summary>
|
||||
/// 战斗场景
|
||||
/// </summary>
|
||||
public class CombatScenes
|
||||
public class CombatScenes : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 当前配队
|
||||
@@ -30,11 +37,13 @@ public class CombatScenes
|
||||
|
||||
public int AvatarCount { get; set; }
|
||||
|
||||
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Common\\avatar_side_classify_sim.onnx"));
|
||||
|
||||
/// <summary>
|
||||
/// 通过OCR识别队伍内角色
|
||||
/// 通过YOLO分类器识别队伍内角色
|
||||
/// </summary>
|
||||
/// <param name="content">完整游戏画面的捕获截图</param>
|
||||
public CombatScenes InitializeTeam(CaptureContent content)
|
||||
/// <param name="imageRegion">完整游戏画面的捕获截图</param>
|
||||
public CombatScenes InitializeTeam(ImageRegion imageRegion)
|
||||
{
|
||||
// 优先取配置
|
||||
if (!string.IsNullOrEmpty(TaskContext.Instance().Config.AutoFightConfig.TeamNames))
|
||||
@@ -43,17 +52,79 @@ public class CombatScenes
|
||||
return this;
|
||||
}
|
||||
|
||||
// 剪裁出队伍区域
|
||||
var teamRa = content.CaptureRectArea.Crop(AutoFightContext.Instance().FightAssets.TeamRectNoIndex);
|
||||
// 过滤出白色
|
||||
var hsvFilterMat = OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
|
||||
// 识别队伍
|
||||
var names = new string[4];
|
||||
var displayNames = new string[4];
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < AutoFightAssets.Instance.AvatarSideIconRectList.Count; i++)
|
||||
{
|
||||
var ra = imageRegion.DeriveCrop(AutoFightAssets.Instance.AvatarSideIconRectList[i]);
|
||||
var pair = ClassifyAvatarCnName(ra.SrcBitmap, i + 1);
|
||||
names[i] = pair.Item1;
|
||||
if (!string.IsNullOrEmpty(pair.Item2))
|
||||
{
|
||||
var costumeName = pair.Item2;
|
||||
if (AutoFightAssets.Instance.AvatarCostumeMap.ContainsKey(costumeName))
|
||||
{
|
||||
costumeName = AutoFightAssets.Instance.AvatarCostumeMap[costumeName];
|
||||
}
|
||||
|
||||
// 识别队伍内角色
|
||||
var result = OcrFactory.Paddle.OcrResult(hsvFilterMat);
|
||||
ParseTeamOcrResult(result, teamRa);
|
||||
displayNames[i] = $"{pair.Item1}({costumeName})";
|
||||
}
|
||||
else
|
||||
{
|
||||
displayNames[i] = pair.Item1;
|
||||
}
|
||||
}
|
||||
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
|
||||
Avatars = BuildAvatars(names.ToList());
|
||||
AvatarMap = Avatars.ToDictionary(x => x.Name);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogWarning(e.Message);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public (string, string) ClassifyAvatarCnName(Bitmap src, int index)
|
||||
{
|
||||
var className = ClassifyAvatarName(src, index);
|
||||
|
||||
var nameEn = className;
|
||||
var costumeName = "";
|
||||
var i = className.IndexOf("Costume", StringComparison.Ordinal);
|
||||
if (i > 0)
|
||||
{
|
||||
nameEn = className[..i];
|
||||
costumeName = className[(i + 7)..];
|
||||
}
|
||||
|
||||
var avatar = DefaultAutoFightConfig.CombatAvatarNameEnMap[nameEn];
|
||||
return (avatar.Name, costumeName);
|
||||
}
|
||||
|
||||
public string ClassifyAvatarName(Bitmap src, int index)
|
||||
{
|
||||
SpeedTimer speedTimer = new();
|
||||
using var memoryStream = new MemoryStream();
|
||||
src.Save(memoryStream, ImageFormat.Bmp);
|
||||
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
speedTimer.Record("角色侧面头像图像转换");
|
||||
var result = _predictor.Classify(memoryStream);
|
||||
speedTimer.Record("角色侧面头像分类识别");
|
||||
Debug.WriteLine($"角色侧面头像识别结果:{result}");
|
||||
speedTimer.DebugPrint();
|
||||
if (result.Confidence < 0.8)
|
||||
{
|
||||
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
|
||||
throw new Exception($"无法识别第{index}位角色,置信度{result.Confidence},结果:{result.Class.Name}");
|
||||
}
|
||||
|
||||
return result.Class.Name;
|
||||
}
|
||||
|
||||
private void InitializeTeamFromConfig(string teamNames)
|
||||
{
|
||||
var names = teamNames.Split(new[] { ",", "," }, StringSplitOptions.TrimEntries);
|
||||
@@ -61,10 +132,11 @@ public class CombatScenes
|
||||
{
|
||||
throw new Exception($"强制指定队伍角色数量不正确,必须是4个,当前{names.Length}个");
|
||||
}
|
||||
|
||||
// 别名转换为标准名称
|
||||
for (var i = 0; i < names.Length; i++)
|
||||
{
|
||||
names[i] = CombatScriptParser.AvatarAliasToStandardName(names[i]);
|
||||
names[i] = DefaultAutoFightConfig.AvatarAliasToStandardName(names[i]);
|
||||
}
|
||||
|
||||
Logger.LogInformation("强制指定队伍角色:{Text}", string.Join(",", names));
|
||||
@@ -83,7 +155,64 @@ public class CombatScenes
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ParseTeamOcrResult(PaddleOcrResult result, RectArea rectArea)
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null)
|
||||
{
|
||||
AvatarCount = names.Count;
|
||||
var avatars = new Avatar[AvatarCount];
|
||||
for (var i = 0; i < AvatarCount; i++)
|
||||
{
|
||||
var nameRect = nameRects?[i] ?? Rect.Empty;
|
||||
avatars[i] = new Avatar(this, names[i], i + 1, nameRect)
|
||||
{
|
||||
IndexRect = AutoFightContext.Instance.FightAssets.AvatarIndexRectList[i]
|
||||
};
|
||||
}
|
||||
|
||||
return avatars;
|
||||
}
|
||||
|
||||
public void BeforeTask(CancellationTokenSource cts)
|
||||
{
|
||||
for (var i = 0; i < AvatarCount; i++)
|
||||
{
|
||||
Avatars[i].Cts = cts;
|
||||
}
|
||||
}
|
||||
|
||||
public Avatar? SelectAvatar(string name)
|
||||
{
|
||||
return AvatarMap.TryGetValue(name, out var avatar) ? avatar : null;
|
||||
}
|
||||
|
||||
#region OCR识别队伍(已弃用)
|
||||
|
||||
/// <summary>
|
||||
/// 通过OCR识别队伍内角色
|
||||
/// </summary>
|
||||
/// <param name="content">完整游戏画面的捕获截图</param>
|
||||
[Obsolete]
|
||||
public CombatScenes InitializeTeamOldOcr(CaptureContent content)
|
||||
{
|
||||
// 优先取配置
|
||||
if (!string.IsNullOrEmpty(TaskContext.Instance().Config.AutoFightConfig.TeamNames))
|
||||
{
|
||||
InitializeTeamFromConfig(TaskContext.Instance().Config.AutoFightConfig.TeamNames);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 剪裁出队伍区域
|
||||
var teamRa = content.CaptureRectArea.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRectNoIndex);
|
||||
// 过滤出白色
|
||||
var hsvFilterMat = OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
|
||||
|
||||
// 识别队伍内角色
|
||||
var result = OcrFactory.Paddle.OcrResult(hsvFilterMat);
|
||||
ParseTeamOcrResult(result, teamRa);
|
||||
return this;
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
private void ParseTeamOcrResult(PaddleOcrResult result, ImageRegion rectArea)
|
||||
{
|
||||
List<string> names = new();
|
||||
List<Rect> nameRects = new();
|
||||
@@ -103,15 +232,14 @@ public class CombatScenes
|
||||
Logger.LogWarning("识别到的队伍角色数量不正确,当前识别结果:{Text}", string.Join(",", names));
|
||||
}
|
||||
|
||||
|
||||
if (names.Count == 3)
|
||||
{
|
||||
// 流浪者特殊处理
|
||||
// 4人以上的队伍,不支持流浪者的识别
|
||||
var wanderer = rectArea.Find(AutoFightContext.Instance().FightAssets.WandererIconRa);
|
||||
var wanderer = rectArea.Find(AutoFightContext.Instance.FightAssets.WandererIconRa);
|
||||
if (wanderer.IsEmpty())
|
||||
{
|
||||
wanderer = rectArea.Find(AutoFightContext.Instance().FightAssets.WandererIconNoActiveRa);
|
||||
wanderer = rectArea.Find(AutoFightContext.Instance.FightAssets.WandererIconNoActiveRa);
|
||||
}
|
||||
|
||||
if (wanderer.IsEmpty())
|
||||
@@ -152,6 +280,7 @@ public class CombatScenes
|
||||
AvatarMap = Avatars.ToDictionary(x => x.Name);
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
private bool IsGenshinAvatarName(string name)
|
||||
{
|
||||
if (DefaultAutoFightConfig.CombatAvatarNames.Contains(name))
|
||||
@@ -168,6 +297,7 @@ public class CombatScenes
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
public string ErrorOcrCorrection(string name)
|
||||
{
|
||||
if (name.Contains("纳西"))
|
||||
@@ -178,32 +308,10 @@ public class CombatScenes
|
||||
return name;
|
||||
}
|
||||
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null)
|
||||
{
|
||||
AvatarCount = names.Count;
|
||||
var avatars = new Avatar[AvatarCount];
|
||||
for (var i = 0; i < AvatarCount; i++)
|
||||
{
|
||||
var nameRect = nameRects?[i] ?? Rect.Empty;
|
||||
avatars[i] = new Avatar(this, names[i], i + 1, nameRect)
|
||||
{
|
||||
IndexRect = AutoFightContext.Instance().FightAssets.AvatarIndexRectList[i]
|
||||
};
|
||||
}
|
||||
#endregion OCR识别队伍(已弃用)
|
||||
|
||||
return avatars;
|
||||
}
|
||||
|
||||
public void BeforeTask(CancellationTokenSource cts)
|
||||
public void Dispose()
|
||||
{
|
||||
for (var i = 0; i < AvatarCount; i++)
|
||||
{
|
||||
Avatars[i].Cts = cts;
|
||||
}
|
||||
_predictor.Dispose();
|
||||
}
|
||||
|
||||
public Avatar? SelectAvatar(string name)
|
||||
{
|
||||
return AvatarMap.TryGetValue(name, out var avatar) ? avatar : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
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 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;
|
||||
|
||||
/// <summary>
|
||||
/// 一键战斗宏
|
||||
/// </summary>
|
||||
public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
public static readonly string HoldOnMode = "按住时重复";
|
||||
public static readonly string TickMode = "触发";
|
||||
|
||||
private Dictionary<string, List<CombatCommand>>? _avatarMacros;
|
||||
private CancellationTokenSource? _cts = null;
|
||||
private Task? _fightTask;
|
||||
|
||||
private bool _isKeyDown = false;
|
||||
private int activeMacroPriority = -1;
|
||||
private DateTime _lastUpdateTime = DateTime.MinValue;
|
||||
|
||||
private CombatScenes? _currentCombatScenes;
|
||||
|
||||
public void KeyDown()
|
||||
{
|
||||
if (_isKeyDown || !IsEnabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
_isKeyDown = true;
|
||||
if (activeMacroPriority != TaskContext.Instance().Config.MacroConfig.CombatMacroPriority || IsAvatarMacrosEdited())
|
||||
{
|
||||
activeMacroPriority = TaskContext.Instance().Config.MacroConfig.CombatMacroPriority;
|
||||
_avatarMacros = LoadAvatarMacros();
|
||||
Logger.LogInformation("加载一键宏配置完成");
|
||||
}
|
||||
|
||||
if (IsHoldOnMode())
|
||||
{
|
||||
if (_cts == null || _cts.Token.IsCancellationRequested)
|
||||
{
|
||||
_cts = new CancellationTokenSource();
|
||||
_fightTask = FightTask(_cts);
|
||||
if (!_fightTask.IsCompleted)
|
||||
{
|
||||
_fightTask.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (IsTickMode())
|
||||
{
|
||||
if (_cts == null || _cts.Token.IsCancellationRequested)
|
||||
{
|
||||
_cts = new CancellationTokenSource();
|
||||
_fightTask = FightTask(_cts);
|
||||
if (!_fightTask.IsCompleted)
|
||||
{
|
||||
_fightTask.Start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_cts.Cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void KeyUp()
|
||||
{
|
||||
_isKeyDown = false;
|
||||
if (!IsEnabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsHoldOnMode())
|
||||
{
|
||||
_cts?.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
// public void Run()
|
||||
// {
|
||||
// if (!IsEnabled())
|
||||
// {
|
||||
// return;
|
||||
// }
|
||||
// _avatarMacros ??= LoadAvatarMacros();
|
||||
//
|
||||
// if (IsHoldOnMode())
|
||||
// {
|
||||
// if (_fightTask == null || _fightTask.IsCompleted)
|
||||
// {
|
||||
// _fightTask = FightTask(_cts);
|
||||
// _fightTask.Start();
|
||||
// }
|
||||
// Thread.Sleep(100);
|
||||
// }
|
||||
// else if (IsTickMode())
|
||||
// {
|
||||
// if (_cts.Token.IsCancellationRequested)
|
||||
// {
|
||||
// _cts = new CancellationTokenSource();
|
||||
// Task.Run(() => FightTask(_cts));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// _cts.Cancel();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 循环执行战斗宏
|
||||
/// </summary>
|
||||
private Task FightTask(CancellationTokenSource cts)
|
||||
{
|
||||
// 切换截图模式
|
||||
var dispatcherCaptureMode = TaskTriggerDispatcher.Instance().GetCacheCaptureMode();
|
||||
if (dispatcherCaptureMode != DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
|
||||
{
|
||||
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
|
||||
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, cts); // 等待缓存图像
|
||||
}
|
||||
|
||||
var imageRegion = GetRectAreaFromDispatcher();
|
||||
var combatScenes = new CombatScenes().InitializeTeam(imageRegion);
|
||||
if (!combatScenes.CheckTeamInitialized())
|
||||
{
|
||||
if (_currentCombatScenes == null)
|
||||
{
|
||||
Logger.LogError("首次队伍角色识别失败");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("队伍角色识别失败,使用上次识别结果,队伍未切换时无影响");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentCombatScenes = combatScenes;
|
||||
}
|
||||
// 找到出战角色
|
||||
var activeAvatar = _currentCombatScenes.Avatars.First(avatar => avatar.IsActive(imageRegion));
|
||||
|
||||
if (_avatarMacros != null && _avatarMacros.TryGetValue(activeAvatar.Name, out var combatCommands))
|
||||
{
|
||||
return new Task(() =>
|
||||
{
|
||||
Logger.LogInformation("→ {Name}执行宏", activeAvatar.Name);
|
||||
while (!cts.Token.IsCancellationRequested && IsEnabled())
|
||||
{
|
||||
if (IsHoldOnMode() && !_isKeyDown)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// 通用化战斗策略
|
||||
foreach (var command in combatCommands)
|
||||
{
|
||||
command.Execute(activeAvatar);
|
||||
}
|
||||
}
|
||||
Logger.LogInformation("→ {Name}停止宏", activeAvatar.Name);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("→ {Name}配置[{Priority}]为空,请先配置一键宏", activeAvatar.Name, activeMacroPriority);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
public Dictionary<string, List<CombatCommand>> LoadAvatarMacros()
|
||||
{
|
||||
var jsonPath = Global.Absolute("User/avatar_macro.json");
|
||||
var json = File.ReadAllText(jsonPath);
|
||||
_lastUpdateTime = File.GetLastWriteTime(jsonPath);
|
||||
var avatarMacros = JsonSerializer.Deserialize<List<AvatarMacro>>(json, ConfigService.JsonOptions);
|
||||
if (avatarMacros == null)
|
||||
{
|
||||
return new Dictionary<string, List<CombatCommand>>();
|
||||
}
|
||||
var result = new Dictionary<string, List<CombatCommand>>();
|
||||
foreach (var avatarMacro in avatarMacros)
|
||||
{
|
||||
var commands = avatarMacro.LoadCommands();
|
||||
if (commands != null)
|
||||
{
|
||||
result.Add(avatarMacro.Name, commands);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool IsAvatarMacrosEdited()
|
||||
{
|
||||
// 通过修改时间判断是否编辑过
|
||||
var jsonPath = Global.Absolute("User/avatar_macro.json");
|
||||
var lastWriteTime = File.GetLastWriteTime(jsonPath);
|
||||
return lastWriteTime > _lastUpdateTime;
|
||||
}
|
||||
|
||||
public static bool IsEnabled()
|
||||
{
|
||||
return TaskContext.Instance().Config.MacroConfig.CombatMacroEnabled;
|
||||
}
|
||||
|
||||
public static bool IsHoldOnMode()
|
||||
{
|
||||
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == HoldOnMode;
|
||||
}
|
||||
|
||||
public static bool IsTickMode()
|
||||
{
|
||||
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == TickMode;
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,11 @@ public class CombatCommand
|
||||
avatar.Switch();
|
||||
}
|
||||
|
||||
Execute(avatar);
|
||||
}
|
||||
|
||||
public void Execute(Avatar avatar)
|
||||
{
|
||||
if (Method == Method.Skill)
|
||||
{
|
||||
var hold = Args != null && Args.Contains("hold");
|
||||
@@ -230,4 +235,4 @@ public class CombatCommand
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
|
||||
public class CombatScript(HashSet<string> avatarNames, List<CombatCommand> combatCommands)
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string Path { get; set; } = string.Empty;
|
||||
|
||||
public HashSet<string> AvatarNames { get; set; } = avatarNames;
|
||||
public List<CombatCommand> CombatCommands { get; set; } = combatCommands;
|
||||
|
||||
/// <summary>
|
||||
/// 用于记录和队伍角色匹配到的数量
|
||||
/// </summary>
|
||||
public int MatchCount { get; set; } = 0;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
|
||||
public class CombatScriptBag(List<CombatScript> combatScripts)
|
||||
{
|
||||
private List<CombatScript> CombatScripts { get; set; } = combatScripts;
|
||||
|
||||
public CombatScriptBag(CombatScript combatScript) : this([combatScript])
|
||||
{
|
||||
}
|
||||
|
||||
public List<CombatCommand> FindCombatScript(Avatar[] avatars)
|
||||
{
|
||||
foreach (var combatScript in CombatScripts)
|
||||
{
|
||||
var matchCount = 0;
|
||||
foreach (var avatar in avatars)
|
||||
{
|
||||
if (combatScript.AvatarNames.Contains(avatar.Name))
|
||||
{
|
||||
matchCount++;
|
||||
}
|
||||
|
||||
if (matchCount == avatars.Length)
|
||||
{
|
||||
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
|
||||
return combatScript.CombatCommands;
|
||||
}
|
||||
}
|
||||
|
||||
combatScript.MatchCount = matchCount;
|
||||
}
|
||||
|
||||
// 没有找到匹配的战斗脚本
|
||||
// 按照匹配数量降序排序
|
||||
CombatScripts.Sort((a, b) => b.MatchCount.CompareTo(a.MatchCount));
|
||||
if (CombatScripts[0].MatchCount == 0)
|
||||
{
|
||||
throw new Exception("未匹配到任何战斗脚本");
|
||||
}
|
||||
|
||||
Logger.LogWarning("未完整匹配到四人队伍,使用匹配度最高的队伍:{Name}", CombatScripts[0].Name);
|
||||
return CombatScripts[0].CombatCommands;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,55 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Config;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
|
||||
public class CombatScriptParser
|
||||
{
|
||||
public static List<CombatCommand> Parse(string script)
|
||||
public static CombatScriptBag ReadAndParse(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return new CombatScriptBag(Parse(path));
|
||||
}
|
||||
else if (Directory.Exists(path))
|
||||
{
|
||||
var files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
|
||||
if (files.Length == 0)
|
||||
{
|
||||
Logger.LogError("战斗脚本文件不存在:{Path}", path);
|
||||
throw new Exception("战斗脚本文件不存在");
|
||||
}
|
||||
|
||||
var combatScripts = new List<CombatScript>();
|
||||
foreach (var file in files)
|
||||
{
|
||||
try
|
||||
{
|
||||
combatScripts.Add(Parse(file));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogWarning("解析战斗脚本文件失败:{Path} , {Msg} ", file, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return new CombatScriptBag(combatScripts);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogError("战斗脚本文件不存在:{Path}", path);
|
||||
throw new Exception("战斗脚本文件不存在");
|
||||
}
|
||||
}
|
||||
|
||||
public static CombatScript Parse(string path)
|
||||
{
|
||||
var script = File.ReadAllText(path);
|
||||
var lines = script.Split(new[] { "\r\n", "\r", "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
var result = new List<string>();
|
||||
foreach (var line in lines)
|
||||
@@ -28,88 +66,93 @@ public class CombatScriptParser
|
||||
result.Add(l);
|
||||
}
|
||||
|
||||
return Parse(result);
|
||||
var combatScript = Parse(result);
|
||||
combatScript.Path = path;
|
||||
combatScript.Name = Path.GetFileNameWithoutExtension(path);
|
||||
return combatScript;
|
||||
}
|
||||
|
||||
public static List<CombatCommand> Parse(List<string> lines)
|
||||
public static CombatScript Parse(List<string> lines)
|
||||
{
|
||||
List<CombatCommand> combatCommands = new();
|
||||
HashSet<string> combatAvatarNames = new();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
// 以空格分隔角色和指令 截取第一个空格前的内容为角色名称,后面的为指令
|
||||
var firstSpaceIndex = line.IndexOf(' ');
|
||||
if (firstSpaceIndex < 0)
|
||||
{
|
||||
Logger.LogError("战斗脚本格式错误,必须以空格分隔角色和指令");
|
||||
throw new Exception("战斗脚本格式错误,必须以空格分隔角色和指令");
|
||||
}
|
||||
|
||||
|
||||
var character = line[..firstSpaceIndex];
|
||||
character = AvatarAliasToStandardName(character);
|
||||
var commands = line[(firstSpaceIndex + 1)..];
|
||||
var commandArray = commands.Split(",", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
for (var i = 0; i < commandArray.Length; i++)
|
||||
{
|
||||
var command = commandArray[i];
|
||||
if (string.IsNullOrEmpty(command))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (command.Contains("(") && !command.Contains(")"))
|
||||
{
|
||||
var j = i + 1;
|
||||
// 括号被逗号分隔,需要合并
|
||||
while (j < commandArray.Length)
|
||||
{
|
||||
command += "," + commandArray[j];
|
||||
if (command.Count("(".Contains) > 1)
|
||||
{
|
||||
Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号无法配对", command);
|
||||
throw new Exception("战斗脚本格式错误,指令括号无法配对");
|
||||
}
|
||||
|
||||
if (command.Contains(")"))
|
||||
{
|
||||
i = j;
|
||||
break;
|
||||
}
|
||||
|
||||
j++;
|
||||
}
|
||||
|
||||
if (!(command.Contains("(") && command.Contains(")")))
|
||||
{
|
||||
Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号不完整", command);
|
||||
throw new Exception("战斗脚本格式错误,指令括号不完整");
|
||||
}
|
||||
}
|
||||
|
||||
var combatCommand = new CombatCommand(character, command);
|
||||
combatCommands.Add(combatCommand);
|
||||
}
|
||||
|
||||
combatAvatarNames.Add(character);
|
||||
var oneLineCombatCommands = ParseLine(line, combatAvatarNames);
|
||||
combatCommands.AddRange(oneLineCombatCommands);
|
||||
}
|
||||
|
||||
var names = string.Join(",", combatAvatarNames);
|
||||
Logger.LogInformation("战斗脚本解析完成,共{Cnt}条指令,涉及角色:{Str}", combatCommands.Count, names);
|
||||
Logger.LogDebug("战斗脚本解析完成,共{Cnt}条指令,涉及角色:{Str}", combatCommands.Count, names);
|
||||
|
||||
return combatCommands;
|
||||
return new CombatScript(combatAvatarNames, combatCommands);
|
||||
}
|
||||
|
||||
|
||||
public static string AvatarAliasToStandardName(string alias)
|
||||
public static List<CombatCommand> ParseLine(string line, HashSet<string> combatAvatarNames)
|
||||
{
|
||||
var avatar = DefaultAutoFightConfig.CombatAvatars.Find(x => x.Alias.Contains(alias));
|
||||
if (avatar == null)
|
||||
var oneLineCombatCommands = new List<CombatCommand>();
|
||||
// 以空格分隔角色和指令 截取第一个空格前的内容为角色名称,后面的为指令
|
||||
var firstSpaceIndex = line.IndexOf(' ');
|
||||
if (firstSpaceIndex < 0)
|
||||
{
|
||||
throw new Exception($"角色名称校验失败:{alias}");
|
||||
Logger.LogError("战斗脚本格式错误,必须以空格分隔角色和指令");
|
||||
throw new Exception("战斗脚本格式错误,必须以空格分隔角色和指令");
|
||||
}
|
||||
|
||||
return avatar.Name;
|
||||
var character = line[..firstSpaceIndex];
|
||||
character = DefaultAutoFightConfig.AvatarAliasToStandardName(character);
|
||||
var commands = line[(firstSpaceIndex + 1)..];
|
||||
oneLineCombatCommands.AddRange(ParseLineCommands(commands, character));
|
||||
combatAvatarNames.Add(character);
|
||||
return oneLineCombatCommands;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<CombatCommand> ParseLineCommands(string lineWithoutAvatar, string avatarName)
|
||||
{
|
||||
var oneLineCombatCommands = new List<CombatCommand>();
|
||||
var commandArray = lineWithoutAvatar.Split(",", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
for (var i = 0; i < commandArray.Length; i++)
|
||||
{
|
||||
var command = commandArray[i];
|
||||
if (string.IsNullOrEmpty(command))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (command.Contains("(") && !command.Contains(")"))
|
||||
{
|
||||
var j = i + 1;
|
||||
// 括号被逗号分隔,需要合并
|
||||
while (j < commandArray.Length)
|
||||
{
|
||||
command += "," + commandArray[j];
|
||||
if (command.Count("(".Contains) > 1)
|
||||
{
|
||||
Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号无法配对", command);
|
||||
throw new Exception("战斗脚本格式错误,指令括号无法配对");
|
||||
}
|
||||
|
||||
if (command.Contains(")"))
|
||||
{
|
||||
i = j;
|
||||
break;
|
||||
}
|
||||
|
||||
j++;
|
||||
}
|
||||
|
||||
if (!(command.Contains("(") && command.Contains(")")))
|
||||
{
|
||||
Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号不完整", command);
|
||||
throw new Exception("战斗脚本格式错误,指令括号不完整");
|
||||
}
|
||||
}
|
||||
|
||||
var combatCommand = new CombatCommand(avatarName, command);
|
||||
oneLineCombatCommands.Add(combatCommand);
|
||||
}
|
||||
|
||||
return oneLineCombatCommands;
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -1,89 +1,82 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Assets
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Assets;
|
||||
|
||||
public class AutoFishingAssets : BaseAssets<AutoFishingAssets>
|
||||
{
|
||||
public class AutoFishingAssets
|
||||
public RecognitionObject SpaceButtonRo;
|
||||
|
||||
public RecognitionObject BaitButtonRo;
|
||||
public RecognitionObject WaitBiteButtonRo;
|
||||
public RecognitionObject LiftRodButtonRo;
|
||||
public RecognitionObject ExitFishingButtonRo;
|
||||
|
||||
private AutoFishingAssets()
|
||||
{
|
||||
public RecognitionObject SpaceButtonRo;
|
||||
|
||||
public RecognitionObject BaitButtonRo;
|
||||
public RecognitionObject WaitBiteButtonRo;
|
||||
public RecognitionObject LiftRodButtonRo;
|
||||
public RecognitionObject ExitFishingButtonRo;
|
||||
|
||||
public AutoFishingAssets()
|
||||
SpaceButtonRo = new RecognitionObject
|
||||
{
|
||||
var info = TaskContext.Instance().SystemInfo;
|
||||
SpaceButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "SpaceButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "space.png"),
|
||||
RegionOfInterest = new Rect(info.CaptureAreaRect.Width - info.CaptureAreaRect.Width / 3,
|
||||
info.CaptureAreaRect.Height - info.CaptureAreaRect.Height / 5,
|
||||
info.CaptureAreaRect.Width / 3,
|
||||
info.CaptureAreaRect.Height / 5),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
Name = "SpaceButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "space.png"),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 3,
|
||||
CaptureRect.Height - CaptureRect.Height / 5,
|
||||
CaptureRect.Width / 3,
|
||||
CaptureRect.Height / 5),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
BaitButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "BaitButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "switch_bait.png"),
|
||||
RegionOfInterest = new Rect(info.CaptureAreaRect.Width - info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height - info.CaptureAreaRect.Height / 4,
|
||||
info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
WaitBiteButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "WaitBiteButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "wait_bite.png"),
|
||||
RegionOfInterest = new Rect(info.CaptureAreaRect.Width - info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height - info.CaptureAreaRect.Height / 4,
|
||||
info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
LiftRodButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "LiftRodButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "lift_rod.png"),
|
||||
RegionOfInterest = new Rect(info.CaptureAreaRect.Width - info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height - info.CaptureAreaRect.Height / 4,
|
||||
info.CaptureAreaRect.Width / 2,
|
||||
info.CaptureAreaRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
BaitButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "BaitButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "switch_bait.png"),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 2,
|
||||
CaptureRect.Height - CaptureRect.Height / 4,
|
||||
CaptureRect.Width / 2,
|
||||
CaptureRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
WaitBiteButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "WaitBiteButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "wait_bite.png"),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 2,
|
||||
CaptureRect.Height - CaptureRect.Height / 4,
|
||||
CaptureRect.Width / 2,
|
||||
CaptureRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
LiftRodButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "LiftRodButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "lift_rod.png"),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 2,
|
||||
CaptureRect.Height - CaptureRect.Height / 4,
|
||||
CaptureRect.Width / 2,
|
||||
CaptureRect.Height / 4),
|
||||
Threshold = 0.7,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
var w = (int)(140 * info.AssetScale);
|
||||
var h = (int)(150 * info.AssetScale);
|
||||
ExitFishingButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "ExitFishingButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "exit_fishing.png"),
|
||||
RegionOfInterest = new Rect(info.CaptureAreaRect.Width - w,
|
||||
info.CaptureAreaRect.Height - h,
|
||||
w,
|
||||
h),
|
||||
Threshold = 0.8,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
}
|
||||
var w = (int)(140 * AssetScale);
|
||||
var h = (int)(150 * AssetScale);
|
||||
ExitFishingButtonRo = new RecognitionObject
|
||||
{
|
||||
Name = "ExitFishingButton",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", "exit_fishing.png"),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - w,
|
||||
CaptureRect.Height - h,
|
||||
w,
|
||||
h),
|
||||
Threshold = 0.8,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,5 +33,5 @@ public partial class AutoFishingConfig : ObservableObject
|
||||
/// <summary>
|
||||
/// 自动抛竿未上钩超时时间(秒)
|
||||
/// </summary>
|
||||
[ObservableProperty] private int _autoThrowRodTimeOut = 20;
|
||||
[ObservableProperty] private int _autoThrowRodTimeOut = 10;
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
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.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.Model;
|
||||
@@ -14,17 +15,16 @@ using BetterGenshinImpact.View.Drawable;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.Mvvm.Messaging.Messages;
|
||||
using Compunet.YoloV8;
|
||||
using Fischless.GameCapture;
|
||||
using GeniusInvokationAutoToy.Utils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
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;
|
||||
@@ -36,7 +36,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
private readonly ILogger<AutoFishingTrigger> _logger = App.GetLogger<AutoFishingTrigger>();
|
||||
private readonly IOcrService _ocrService = OcrFactory.Paddle;
|
||||
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx"));
|
||||
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx"), BgiSessionOption.Instance.Options);
|
||||
|
||||
public string Name => "自动钓鱼";
|
||||
public bool IsEnabled { get; set; }
|
||||
@@ -53,7 +53,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
|
||||
public AutoFishingTrigger()
|
||||
{
|
||||
_autoFishingAssets = new AutoFishingAssets();
|
||||
_autoFishingAssets = AutoFishingAssets.Instance;
|
||||
}
|
||||
|
||||
public void Init()
|
||||
@@ -86,6 +86,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_prevExecute = DateTime.Now;
|
||||
|
||||
// 进入独占模式判断
|
||||
@@ -104,9 +105,10 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_prevExecute = DateTime.Now;
|
||||
|
||||
_fishBoxRect = GetFishBoxArea(content.CaptureRectArea.SrcMat);
|
||||
_fishBoxRect = GetFishBoxArea(content.CaptureRectArea);
|
||||
CheckFishingUserInterface(content);
|
||||
}
|
||||
else
|
||||
@@ -117,78 +119,76 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 在“开始钓鱼”按钮上方安排一个我们的“开始自动钓鱼”按钮
|
||||
/// 点击按钮进入独占模式
|
||||
/// </summary>
|
||||
/// <param name="content"></param>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
private void DisplayButtonOnStartFishPageForExclusive(CaptureContent content)
|
||||
{
|
||||
VisionContext.Instance().DrawContent.RemoveRect("StartFishingButton");
|
||||
var info = TaskContext.Instance().SystemInfo;
|
||||
var srcMat = content.CaptureRectArea.SrcMat;
|
||||
var rightBottomMat = CropHelper.CutRightBottom(srcMat, srcMat.Width / 2, srcMat.Height / 2);
|
||||
var list = CommonRecognition.FindGameButton(rightBottomMat);
|
||||
if (list.Count > 0)
|
||||
{
|
||||
foreach (var rect in list)
|
||||
{
|
||||
var ro = new RecognitionObject()
|
||||
{
|
||||
Name = "StartFishingText",
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect(srcMat.Width / 2, srcMat.Height / 2, srcMat.Width - srcMat.Width / 2,
|
||||
srcMat.Height - srcMat.Height / 2),
|
||||
AllContainMatchText = new List<string>
|
||||
{
|
||||
"开始", "钓鱼"
|
||||
},
|
||||
DrawOnWindow = false
|
||||
};
|
||||
var ocrRaRes = content.CaptureRectArea.Find(ro);
|
||||
if (ocrRaRes.IsEmpty())
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
}
|
||||
else
|
||||
{
|
||||
VisionContext.Instance().DrawContent.PutRect("StartFishingButton", rect.ToWindowsRectangleOffset(srcMat.Width / 2, srcMat.Height / 2).ToRectDrawable());
|
||||
|
||||
var btnPosition = new Rect(rect.X + srcMat.Width / 2, rect.Y + srcMat.Height / 2 - rect.Height - 10, rect.Width, rect.Height);
|
||||
var maskButton = new MaskButton("开始自动钓鱼", btnPosition, () =>
|
||||
{
|
||||
VisionContext.Instance().DrawContent.RemoveRect("StartFishingButton");
|
||||
_logger.LogInformation("→ {Text}", "自动钓鱼,启动!");
|
||||
// 点击下面的按钮
|
||||
var rc = info.CaptureAreaRect;
|
||||
Simulation.SendInput
|
||||
.Mouse
|
||||
.MoveMouseTo(
|
||||
(rc.X + srcMat.Width * 1d / 2 + rect.X + rect.Width * 1d / 2) * 65535 / info.DesktopRectArea.Width,
|
||||
(rc.Y + srcMat.Height * 1d / 2 + rect.Y + rect.Height * 1d / 2) * 65535 / info.DesktopRectArea.Height)
|
||||
.LeftButtonClick();
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
// 启动要延时一会等待钓鱼界面切换
|
||||
Sleep(1000);
|
||||
IsExclusive = true;
|
||||
_switchBaitContinuouslyFrameNum = 0;
|
||||
_waitBiteContinuouslyFrameNum = 0;
|
||||
_noFishActionContinuouslyFrameNum = 0;
|
||||
_isThrowRod = false;
|
||||
});
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "AddButton", new object(), maskButton));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
}
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 在“开始钓鱼”按钮上方安排一个我们的“开始自动钓鱼”按钮
|
||||
// /// 点击按钮进入独占模式
|
||||
// /// </summary>
|
||||
// /// <param name="content"></param>
|
||||
// /// <returns></returns>
|
||||
// [Obsolete]
|
||||
// private void DisplayButtonOnStartFishPageForExclusive(CaptureContent content)
|
||||
// {
|
||||
// VisionContext.Instance().DrawContent.RemoveRect("StartFishingButton");
|
||||
// var info = TaskContext.Instance().SystemInfo;
|
||||
// var srcMat = content.CaptureRectArea.SrcMat;
|
||||
// var rightBottomMat = CropHelper.CutRightBottom(srcMat, srcMat.Width / 2, srcMat.Height / 2);
|
||||
// var list = CommonRecognition.FindGameButton(rightBottomMat);
|
||||
// if (list.Count > 0)
|
||||
// {
|
||||
// foreach (var rect in list)
|
||||
// {
|
||||
// var ro = new RecognitionObject()
|
||||
// {
|
||||
// Name = "StartFishingText",
|
||||
// RecognitionType = RecognitionTypes.OcrMatch,
|
||||
// RegionOfInterest = new Rect(srcMat.Width / 2, srcMat.Height / 2, srcMat.Width - srcMat.Width / 2,
|
||||
// srcMat.Height - srcMat.Height / 2),
|
||||
// AllContainMatchText = new List<string>
|
||||
// {
|
||||
// "开始", "钓鱼"
|
||||
// },
|
||||
// DrawOnWindow = false
|
||||
// };
|
||||
// var ocrRaRes = content.CaptureRectArea.Find(ro);
|
||||
// if (ocrRaRes.IsEmpty())
|
||||
// {
|
||||
// WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// VisionContext.Instance().DrawContent.PutRect("StartFishingButton", rect.ToWindowsRectangleOffset(srcMat.Width / 2, srcMat.Height / 2).ToRectDrawable());
|
||||
//
|
||||
// var btnPosition = new Rect(rect.X + srcMat.Width / 2, rect.Y + srcMat.Height / 2 - rect.Height - 10, rect.Width, rect.Height);
|
||||
// var maskButton = new MaskButton("开始自动钓鱼", btnPosition, () =>
|
||||
// {
|
||||
// VisionContext.Instance().DrawContent.RemoveRect("StartFishingButton");
|
||||
// _logger.LogInformation("→ {Text}", "自动钓鱼,启动!");
|
||||
// // 点击下面的按钮
|
||||
// var rc = info.CaptureAreaRect;
|
||||
// Simulation.SendInputEx
|
||||
// .Mouse
|
||||
// .MoveMouseTo(
|
||||
// (rc.X + srcMat.Width * 1d / 2 + rect.X + rect.Width * 1d / 2) * 65535 / info.DesktopRectArea.Width,
|
||||
// (rc.Y + srcMat.Height * 1d / 2 + rect.Y + rect.Height * 1d / 2) * 65535 / info.DesktopRectArea.Height)
|
||||
// .LeftButtonClick();
|
||||
// WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
// // 启动要延时一会等待钓鱼界面切换
|
||||
// Sleep(1000);
|
||||
// IsExclusive = true;
|
||||
// _switchBaitContinuouslyFrameNum = 0;
|
||||
// _waitBiteContinuouslyFrameNum = 0;
|
||||
// _noFishActionContinuouslyFrameNum = 0;
|
||||
// _isThrowRod = false;
|
||||
// });
|
||||
// WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "AddButton", new object(), maskButton));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "RemoveButton", new object(), "开始自动钓鱼"));
|
||||
// }
|
||||
// }
|
||||
|
||||
//private bool OcrStartFishingForExclusive(CaptureContent content)
|
||||
//{
|
||||
@@ -214,7 +214,6 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
return !content.CaptureRectArea.Find(_autoFishingAssets.ExitFishingButtonRo).IsEmpty();
|
||||
}
|
||||
|
||||
|
||||
private int _throwRodWaitFrameNum = 0; // 抛竿等待的时间(帧数)
|
||||
private int _switchBaitContinuouslyFrameNum = 0; // 切换鱼饵按钮图标的持续时间(帧数)
|
||||
private int _waitBiteContinuouslyFrameNum = 0; // 等待上钩的持续时间(帧数)
|
||||
@@ -231,7 +230,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
/// 前提:必须要正面面对鱼塘,没有识别到鱼的时候不会自动抛竿
|
||||
/// 1. 观察周围环境,判断鱼塘位置,视角对上鱼塘位置中心
|
||||
/// 2. 根据第一步的观察结果,提前选择鱼饵
|
||||
/// 3.
|
||||
/// 3.
|
||||
/// </summary>
|
||||
/// <param name="content"></param>
|
||||
private void ThrowRod(CaptureContent content)
|
||||
@@ -251,7 +250,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
_isThrowRod = false;
|
||||
_switchBaitContinuouslyFrameNum = 0;
|
||||
_logger.LogInformation("当前仍在抛竿页");
|
||||
_logger.LogInformation("当前处于未抛竿状态");
|
||||
}
|
||||
|
||||
if (!_isThrowRod)
|
||||
@@ -261,16 +260,17 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
content.CaptureRectArea.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
|
||||
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
var result = _predictor.Detect(memoryStream);
|
||||
Debug.WriteLine($"YOLOv8识别: {result.Speed}");
|
||||
var fishpond = new Fishpond(result);
|
||||
if (fishpond.FishpondRect == Rect.Empty)
|
||||
{
|
||||
Sleep(2000);
|
||||
Sleep(500);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
var centerX = content.SrcBitmap.Width / 2;
|
||||
var centerY = content.SrcBitmap.Height / 2;
|
||||
var centerX = content.CaptureRectArea.SrcBitmap.Width / 2;
|
||||
var centerY = content.CaptureRectArea.SrcBitmap.Height / 2;
|
||||
// 往左移动是正数,往右移动是负数
|
||||
if (fishpond.FishpondRect.Left > centerX)
|
||||
{
|
||||
@@ -288,7 +288,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, -100);
|
||||
}
|
||||
|
||||
if ((fishpond.FishpondRect.Left < centerX && fishpond.FishpondRect.Right > centerX) || fishpond.FishpondRect.Width < content.SrcBitmap.Width / 4)
|
||||
if ((fishpond.FishpondRect.Left < centerX && fishpond.FishpondRect.Right > centerX && fishpond.FishpondRect.Bottom >= centerY) || fishpond.FishpondRect.Width < content.CaptureRectArea.SrcBitmap.Width / 4)
|
||||
{
|
||||
// 鱼塘在中心,选择鱼饵
|
||||
if (string.IsNullOrEmpty(_selectedBaitName))
|
||||
@@ -312,14 +312,12 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
_noFishActionContinuouslyFrameNum = 0;
|
||||
_throwRodWaitFrameNum++;
|
||||
|
||||
|
||||
if (_waitBiteContinuouslyFrameNum >= content.FrameRate)
|
||||
{
|
||||
_isThrowRod = true;
|
||||
_waitBiteContinuouslyFrameNum = 0;
|
||||
}
|
||||
|
||||
|
||||
if (_isThrowRod)
|
||||
{
|
||||
// 30s 没有上钩,重新抛竿
|
||||
@@ -356,7 +354,6 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private string _selectedBaitName = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
@@ -370,27 +367,27 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
// 打开换饵界面
|
||||
Simulation.SendInput.Mouse.RightButtonClick();
|
||||
Sleep(100);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, 200); // 鼠标移走,防止干扰
|
||||
Sleep(500);
|
||||
|
||||
// 截图
|
||||
var bitmap = CaptureGameBitmap(content.Dispatcher.GameCapture);
|
||||
_selectedBaitName = fishpond.MostMatchBait(); // 选择最多鱼吃的饵料
|
||||
_selectedBaitName = fishpond.Fishes[0].FishType.BaitName; // 选择最多鱼吃的饵料
|
||||
_logger.LogInformation("选择鱼饵 {Text}", BaitType.FromName(_selectedBaitName).ChineseName);
|
||||
|
||||
// 寻找鱼饵
|
||||
var ro = new RecognitionObject()
|
||||
var ro = new RecognitionObject
|
||||
{
|
||||
Name = "ChooseBait",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFishing", $"bait\\{_selectedBaitName}.png"),
|
||||
Threshold = 0.9,
|
||||
Threshold = 0.8,
|
||||
Use3Channels = true,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
var systemInfo = TaskContext.Instance().SystemInfo;
|
||||
var ra = new RectArea(bitmap, systemInfo.CaptureAreaRect.X, systemInfo.CaptureAreaRect.Y, systemInfo.DesktopRectArea);
|
||||
var resRa = ra.Find(ro);
|
||||
// 截图
|
||||
using var captureRegion = TaskControl.CaptureToRectArea();
|
||||
using var resRa = captureRegion.Find(ro);
|
||||
if (resRa.IsEmpty())
|
||||
{
|
||||
_logger.LogWarning("没有找到目标鱼饵");
|
||||
@@ -399,21 +396,19 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
else
|
||||
{
|
||||
resRa.ClickCenter();
|
||||
Sleep(500);
|
||||
resRa.Click();
|
||||
Sleep(700);
|
||||
// 可能重复点击,所以固定界面点击下
|
||||
var rect = systemInfo.CaptureAreaRect;
|
||||
ClickExtension.Click(rect.X + 1300 * systemInfo.AssetScale, rect.Y + 400 * systemInfo.AssetScale);
|
||||
captureRegion.ClickTo((int)(captureRegion.Width * 0.675), (int)(captureRegion.Height / 3d));
|
||||
Sleep(200);
|
||||
// 偷懒 固定点击确定
|
||||
ClickExtension.Click(rect.X + 1180 * systemInfo.AssetScale, rect.Y + 760 * systemInfo.AssetScale);
|
||||
// 点击确定
|
||||
Bv.ClickWhiteConfirmButton(captureRegion);
|
||||
Sleep(500); // 等待界面切换
|
||||
}
|
||||
|
||||
return _selectedBaitName;
|
||||
}
|
||||
|
||||
|
||||
private readonly Random _rd = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -431,44 +426,45 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
var noTargetFishTimes = 0; // 没有目标鱼的次数
|
||||
var prevTargetFishRect = Rect.Empty; // 记录上一个目标鱼的位置
|
||||
|
||||
while (true)
|
||||
while (IsEnabled)
|
||||
{
|
||||
// 截图
|
||||
var bitmap = CaptureGameBitmap(content.Dispatcher.GameCapture);
|
||||
var ra = TaskControl.CaptureToRectArea();
|
||||
|
||||
// 找 鱼饵落点
|
||||
using var memoryStream = new MemoryStream();
|
||||
bitmap.Save(memoryStream, ImageFormat.Bmp);
|
||||
ra.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
|
||||
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
var result = _predictor.Detect(memoryStream);
|
||||
Debug.WriteLine($"YOLOv8识别: {result.Speed}");
|
||||
var fishpond = new Fishpond(result);
|
||||
if (fishpond.TargetRect == Rect.Empty)
|
||||
{
|
||||
noPlacementTimes++;
|
||||
Sleep(50);
|
||||
Debug.WriteLine("历次未找到鱼饵落点,随机移动");
|
||||
Debug.WriteLine("历次未找到鱼饵落点");
|
||||
|
||||
var cX = content.SrcBitmap.Width / 2;
|
||||
var cY = content.SrcBitmap.Height / 2;
|
||||
var rdX = _rd.Next(0, content.SrcBitmap.Width);
|
||||
var rdY = _rd.Next(0, content.SrcBitmap.Height);
|
||||
var cX = ra.SrcBitmap.Width / 2;
|
||||
var cY = ra.SrcBitmap.Height / 2;
|
||||
var rdX = _rd.Next(0, ra.SrcBitmap.Width);
|
||||
var rdY = _rd.Next(0, ra.SrcBitmap.Height);
|
||||
|
||||
var moveX = 100 * (cX - rdX) / content.SrcBitmap.Width;
|
||||
var moveY = 100 * (cY - rdY) / content.SrcBitmap.Height;
|
||||
var moveX = 100 * (cX - rdX) / ra.SrcBitmap.Width;
|
||||
var moveY = 100 * (cY - rdY) / ra.SrcBitmap.Height;
|
||||
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(moveX, moveY);
|
||||
|
||||
if (noPlacementTimes > 50)
|
||||
if (noPlacementTimes > 25)
|
||||
{
|
||||
_logger.LogInformation("未找到鱼饵落点,大概率是长按失败,直接抛竿收杆重试");
|
||||
Simulation.SendInput.Mouse.LeftButtonUp().Sleep(200).LeftButtonDown().Sleep(200).LeftButtonUp();
|
||||
Sleep(2000);
|
||||
Simulation.SendInput.Mouse.LeftButtonClick();
|
||||
_selectedBaitName = string.Empty;
|
||||
_isThrowRod = false;
|
||||
Sleep(2000);
|
||||
MoveViewpointDown();
|
||||
Sleep(300);
|
||||
_logger.LogInformation("未找到鱼饵落点,重试");
|
||||
// Simulation.SendInputEx.Mouse.LeftButtonUp();
|
||||
// // Sleep(2000);
|
||||
// // Simulation.SendInputEx.Mouse.LeftButtonClick();
|
||||
// _selectedBaitName = string.Empty;
|
||||
// _isThrowRod = false;
|
||||
// // Sleep(2000);
|
||||
// // MoveViewpointDown();
|
||||
// Sleep(300);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -501,10 +497,10 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
noTargetFishTimes++;
|
||||
//if (noTargetFishTimes == 30)
|
||||
//{
|
||||
// Simulation.SendInput.Mouse.MoveMouseBy(0, 100);
|
||||
// Simulation.SendInputEx.Mouse.MoveMouseBy(0, 100);
|
||||
//}
|
||||
|
||||
if (noTargetFishTimes > 80)
|
||||
if (noTargetFishTimes > 10)
|
||||
{
|
||||
// 没有找到目标鱼,重新选择鱼饵
|
||||
_logger.LogInformation("没有找到目标鱼,1.直接抛竿");
|
||||
@@ -512,12 +508,12 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
Sleep(1500);
|
||||
_logger.LogInformation("没有找到目标鱼,2.收杆");
|
||||
Simulation.SendInput.Mouse.LeftButtonClick();
|
||||
Sleep(1500);
|
||||
Sleep(800);
|
||||
_logger.LogInformation("没有找到目标鱼,3.准备重新选择鱼饵");
|
||||
_selectedBaitName = string.Empty;
|
||||
_isThrowRod = false;
|
||||
MoveViewpointDown();
|
||||
Sleep(500);
|
||||
Sleep(300);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -526,14 +522,59 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
else
|
||||
{
|
||||
noTargetFishTimes = 0;
|
||||
var min = MoveMouseToFish(fishpond.TargetRect, currentFish.Rect);
|
||||
VisionContext.Instance().DrawContent.PutRect("Target", fishpond.TargetRect.ToRectDrawable());
|
||||
VisionContext.Instance().DrawContent.PutRect("Fish", currentFish.Rect.ToRectDrawable());
|
||||
// 因为视角是斜着看向鱼的,所以Y轴抛竿距离要近一点
|
||||
if ((_selectedBaitName != "fruit paste bait" && min is { Item1: <= 50, Item2: <= 25 })
|
||||
|| _selectedBaitName == "fruit paste bait" && min is { Item1: <= 40, Item2: <= 25 })
|
||||
_currContent.CaptureRectArea.DrawRect(fishpond.TargetRect, "Target");
|
||||
_currContent.CaptureRectArea.Derive(currentFish.Rect).DrawSelf("Fish");
|
||||
// VisionContext.Instance().DrawContent.PutRect("Target", fishpond.TargetRect.ToRectDrawable());
|
||||
// VisionContext.Instance().DrawContent.PutRect("Fish", currentFish.Rect.ToRectDrawable());
|
||||
|
||||
// var min = MoveMouseToFish(fishpond.TargetRect, currentFish.Rect);
|
||||
// // 因为视角是斜着看向鱼的,所以Y轴抛竿距离要近一点
|
||||
// if ((_selectedBaitName != "fruit paste bait" && min is { Item1: <= 50, Item2: <= 25 })
|
||||
// || _selectedBaitName == "fruit paste bait" && min is { Item1: <= 40, Item2: <= 25 })
|
||||
// {
|
||||
// Sleep(100);
|
||||
// Simulation.SendInputEx.Mouse.LeftButtonUp();
|
||||
// _logger.LogInformation("尝试钓取 {Text}", currentFish.FishType.ChineseName);
|
||||
// _isThrowRod = true;
|
||||
// VisionContext.Instance().DrawContent.RemoveRect("Target");
|
||||
// VisionContext.Instance().DrawContent.RemoveRect("Fish");
|
||||
// break;
|
||||
// }
|
||||
|
||||
// 来自 HutaoFisher 的抛竿技术
|
||||
var rod = fishpond.TargetRect;
|
||||
var fish = currentFish.Rect;
|
||||
var dx = NormalizeXTo1024(fish.Left + fish.Right - rod.Left - rod.Right) / 2.0;
|
||||
var dy = NormalizeYTo576(fish.Top + fish.Bottom - rod.Top - rod.Bottom) / 2.0;
|
||||
var state = RodNet.GetRodState(new RodInput
|
||||
{
|
||||
Sleep(100);
|
||||
rod_x1 = NormalizeXTo1024(rod.Left),
|
||||
rod_x2 = NormalizeXTo1024(rod.Right),
|
||||
rod_y1 = NormalizeYTo576(rod.Top),
|
||||
rod_y2 = NormalizeYTo576(rod.Bottom),
|
||||
fish_x1 = NormalizeXTo1024(fish.Left),
|
||||
fish_x2 = NormalizeXTo1024(fish.Right),
|
||||
fish_y1 = NormalizeYTo576(fish.Top),
|
||||
fish_y2 = NormalizeYTo576(fish.Bottom),
|
||||
fish_label = BigFishType.GetIndex(currentFish.FishType)
|
||||
});
|
||||
if (state == -1)
|
||||
{
|
||||
// 失败 随机移动鼠标
|
||||
var cX = content.CaptureRectArea.SrcBitmap.Width / 2;
|
||||
var cY = content.CaptureRectArea.SrcBitmap.Height / 2;
|
||||
var rdX = _rd.Next(0, content.CaptureRectArea.SrcBitmap.Width);
|
||||
var rdY = _rd.Next(0, content.CaptureRectArea.SrcBitmap.Height);
|
||||
|
||||
var moveX = 100 * (cX - rdX) / content.CaptureRectArea.SrcBitmap.Width;
|
||||
var moveY = 100 * (cY - rdY) / content.CaptureRectArea.SrcBitmap.Height;
|
||||
|
||||
_logger.LogInformation("失败 随机移动 {DX}, {DY}", moveX, moveY);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(moveX, moveY);
|
||||
}
|
||||
else if (state == 0)
|
||||
{
|
||||
// 成功 抛竿
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
_logger.LogInformation("尝试钓取 {Text}", currentFish.FishType.ChineseName);
|
||||
_isThrowRod = true;
|
||||
@@ -541,12 +582,38 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
VisionContext.Instance().DrawContent.RemoveRect("Fish");
|
||||
break;
|
||||
}
|
||||
else if (state == 1)
|
||||
{
|
||||
// 太近
|
||||
var dl = Math.Sqrt(dx * dx + dy * dy);
|
||||
// set a minimum step
|
||||
dx = dx / dl * 30;
|
||||
dy = dy / dl * 30;
|
||||
// _logger.LogInformation("太近 移动 {DX}, {DY}", dx, dy);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)(-dx / 1.5), (int)(-dy * 1.5));
|
||||
}
|
||||
else if (state == 2)
|
||||
{
|
||||
// 太远
|
||||
// _logger.LogInformation("太远 移动 {DX}, {DY}", dx, dy);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)(dx / 1.5), (int)(dy * 1.5));
|
||||
}
|
||||
}
|
||||
|
||||
Sleep(80);
|
||||
Sleep(20);
|
||||
}
|
||||
}
|
||||
|
||||
private double NormalizeXTo1024(int x)
|
||||
{
|
||||
return x * 1.0 / TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect.Width * 1024;
|
||||
}
|
||||
|
||||
private double NormalizeYTo576(int y)
|
||||
{
|
||||
return y * 1.0 / TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect.Height * 576;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向下移动视角
|
||||
/// </summary>
|
||||
@@ -555,13 +622,14 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
if (TaskContext.Instance().Config.AutoFishingConfig.AutoThrowRodEnabled)
|
||||
{
|
||||
// 下移视角方便看鱼
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, 300);
|
||||
Sleep(500);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, 400);
|
||||
Sleep(500);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, 500);
|
||||
Sleep(500);
|
||||
}
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
private (int, int) MoveMouseToFish(Rect rect1, Rect rect2)
|
||||
{
|
||||
int minDistance;
|
||||
@@ -587,7 +655,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
moveY = 50;
|
||||
}
|
||||
|
||||
|
||||
if (c1.Y > c2.Y)
|
||||
{
|
||||
moveY = -moveY;
|
||||
@@ -635,6 +703,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
moveY = 50;
|
||||
}
|
||||
|
||||
if (c1.Y > c2.Y)
|
||||
{
|
||||
moveY = -moveY;
|
||||
@@ -659,34 +728,11 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
}
|
||||
|
||||
public Bitmap CaptureGameBitmap(IGameCapture? gameCapture)
|
||||
{
|
||||
var bitmap = gameCapture?.Capture();
|
||||
// wgc 缓冲区设置的2 所以至少截图3次
|
||||
if (gameCapture?.Mode == CaptureModes.WindowsGraphicsCapture)
|
||||
{
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
bitmap = gameCapture?.Capture();
|
||||
Sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
if (bitmap == null)
|
||||
{
|
||||
_logger.LogWarning("截图失败!");
|
||||
throw new Exception("截图失败");
|
||||
}
|
||||
// 更新当前捕获内容
|
||||
_currContent = new CaptureContent(bitmap, _currContent.FrameIndex, _currContent.TimerInterval, _currContent.Dispatcher);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
public void Sleep(int millisecondsTimeout)
|
||||
{
|
||||
Retry.Do(() =>
|
||||
NewRetry.Do(() =>
|
||||
{
|
||||
if (!SystemControl.IsGenshinImpactActiveByProcess())
|
||||
if (IsEnabled && !SystemControl.IsGenshinImpactActiveByProcess())
|
||||
{
|
||||
_logger.LogWarning("当前获取焦点的窗口不是原神,暂停");
|
||||
throw new RetryException("当前获取焦点的窗口不是原神");
|
||||
@@ -696,19 +742,19 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
Thread.Sleep(millisecondsTimeout);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取钓鱼框的位置
|
||||
/// </summary>
|
||||
private Rect GetFishBoxArea(Mat srcMat)
|
||||
private Rect GetFishBoxArea(ImageRegion captureRegion)
|
||||
{
|
||||
srcMat = CropHelper.CutTop(srcMat, srcMat.Height / 2);
|
||||
var rects = AutoFishingImageRecognition.GetFishBarRect(srcMat);
|
||||
using var topMat = new Mat(captureRegion.SrcMat, new Rect(0, 0, captureRegion.Width, captureRegion.Height / 2));
|
||||
;
|
||||
var rects = AutoFishingImageRecognition.GetFishBarRect(topMat);
|
||||
if (rects != null && rects.Count == 2)
|
||||
{
|
||||
if (Math.Abs(rects[0].Height - rects[1].Height) > 10)
|
||||
{
|
||||
Debug.WriteLine("两个矩形高度差距过大,未识别到钓鱼框");
|
||||
TaskControl.Logger.LogError("两个矩形高度差距过大,未识别到钓鱼框");
|
||||
VisionContext.Instance().DrawContent.RemoveRect("FishBox");
|
||||
return Rect.Empty;
|
||||
}
|
||||
@@ -724,11 +770,12 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
_left = rects[0];
|
||||
}
|
||||
|
||||
|
||||
if (_left.X < _cur.X // cur 是游标位置, 在初始状态下,cur 一定在left左边
|
||||
|| _cur.Width > _left.Width // left一定比cur宽
|
||||
|| _cur.X + _cur.Width > srcMat.Width / 2 // cur 一定在屏幕左侧
|
||||
|| !(_left.X < srcMat.Width / 2 && _left.X + _left.Width > srcMat.Width / 2) // left肯定穿过游戏中轴线
|
||||
|| _cur.X + _cur.Width > topMat.Width / 2 // cur 一定在屏幕左侧
|
||||
|| _cur.X + _cur.Width > _left.X - _left.Width / 2 // cur 一定在left左侧+left的一半宽度
|
||||
|| _cur.X + _cur.Width > topMat.Width / 2 - _left.Width // cur 一定在屏幕中轴线减去整个left的宽度的位置左侧
|
||||
|| !(_left.X < topMat.Width / 2 && _left.X + _left.Width > topMat.Width / 2) // left肯定穿过游戏中轴线
|
||||
)
|
||||
{
|
||||
VisionContext.Instance().DrawContent.RemoveRect("FishBox");
|
||||
@@ -738,8 +785,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
int hExtra = _cur.Height, vExtra = _cur.Height / 4;
|
||||
_fishBoxRect = new Rect(_cur.X - hExtra, _cur.Y - vExtra,
|
||||
(_left.X + _left.Width / 2 - _cur.X) * 2 + hExtra * 2, _cur.Height + vExtra * 2);
|
||||
VisionContext.Instance().DrawContent
|
||||
.PutRect("FishBox", _fishBoxRect.ToRectDrawable(new Pen(Color.LightPink, 2)));
|
||||
// VisionContext.Instance().DrawContent.PutRect("FishBox", _fishBoxRect.ToRectDrawable(new Pen(Color.LightPink, 2)));
|
||||
using var boxRa = captureRegion.Derive(_fishBoxRect);
|
||||
boxRa.DrawSelf("FishBox", new Pen(Color.LightPink, 2));
|
||||
return _fishBoxRect;
|
||||
}
|
||||
|
||||
@@ -747,11 +795,10 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
return Rect.Empty;
|
||||
}
|
||||
|
||||
|
||||
private bool _isFishingProcess = false; // 提杆后会设置为true
|
||||
int _biteTipsExitCount = 0; // 钓鱼提示持续时间
|
||||
int _notFishingAfterBiteCount = 0; // 提竿后没有钓鱼的时间
|
||||
Rect _baseBiteTips = Rect.Empty;
|
||||
private int _biteTipsExitCount = 0; // 钓鱼提示持续时间
|
||||
private int _notFishingAfterBiteCount = 0; // 提竿后没有钓鱼的时间
|
||||
private Rect _baseBiteTips = Rect.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 自动提竿
|
||||
@@ -787,15 +834,17 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
&& Math.Abs(_baseBiteTips.Height - currentBiteWordsTips.Height) < 10)
|
||||
{
|
||||
_biteTipsExitCount++;
|
||||
VisionContext.Instance().DrawContent.PutRect("FishBiteTips",
|
||||
currentBiteWordsTips
|
||||
.ToWindowsRectangleOffset(liftingWordsAreaRect.X, liftingWordsAreaRect.Y)
|
||||
.ToRectDrawable());
|
||||
// VisionContext.Instance().DrawContent.PutRect("FishBiteTips",
|
||||
// currentBiteWordsTips
|
||||
// .ToWindowsRectangleOffset(liftingWordsAreaRect.X, liftingWordsAreaRect.Y)
|
||||
// .ToRectDrawable());
|
||||
using var tipsRa = content.CaptureRectArea.Derive(currentBiteWordsTips + liftingWordsAreaRect.Location);
|
||||
tipsRa.DrawSelf("FishBiteTips");
|
||||
|
||||
if (_biteTipsExitCount >= content.FrameRate / 4d)
|
||||
{
|
||||
// 图像提竿判断
|
||||
var liftRodButtonRa = content.CaptureRectArea.Find(_autoFishingAssets.LiftRodButtonRo);
|
||||
using var liftRodButtonRa = content.CaptureRectArea.Find(_autoFishingAssets.LiftRodButtonRo);
|
||||
if (!liftRodButtonRa.IsEmpty())
|
||||
{
|
||||
Simulation.SendInput.Mouse.LeftButtonClick();
|
||||
@@ -809,9 +858,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
|
||||
// OCR 提竿判断
|
||||
var text = _ocrService.Ocr(new Mat(content.CaptureRectArea.SrcGreyMat,
|
||||
new Rect(currentBiteWordsTips.X+ liftingWordsAreaRect.X,
|
||||
currentBiteWordsTips.Y+liftingWordsAreaRect.Y,
|
||||
var text = _ocrService.Ocr(new Mat(content.CaptureRectArea.SrcGreyMat,
|
||||
new Rect(currentBiteWordsTips.X + liftingWordsAreaRect.X,
|
||||
currentBiteWordsTips.Y + liftingWordsAreaRect.Y,
|
||||
currentBiteWordsTips.Width, currentBiteWordsTips.Height)));
|
||||
if (!string.IsNullOrEmpty(text) && StringUtils.RemoveAllSpace(text).Contains("上钩"))
|
||||
{
|
||||
@@ -846,13 +895,11 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private int _noRectsCount = 0;
|
||||
private Rect _cur, _left, _right;
|
||||
private MOUSEEVENTF _prevMouseEvent = 0x0;
|
||||
private bool _findFishBoxTips;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 钓鱼拉条
|
||||
/// </summary>
|
||||
@@ -962,10 +1009,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
_logger.LogInformation(" 钓鱼结束");
|
||||
_logger.LogInformation(@"└------------------------┘");
|
||||
|
||||
if (_prevMouseEvent == MOUSEEVENTF.MOUSEEVENTF_LEFTDOWN)
|
||||
{
|
||||
simulator.Mouse.LeftButtonUp();
|
||||
}
|
||||
// 保证鼠标松开
|
||||
simulator.Mouse.LeftButtonUp();
|
||||
|
||||
Sleep(1000);
|
||||
|
||||
@@ -1003,15 +1048,15 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
{
|
||||
var prevIsExclusive = IsExclusive;
|
||||
IsExclusive = FindButtonForExclusive(content);
|
||||
if (!prevIsExclusive && IsExclusive)
|
||||
if (IsEnabled && !prevIsExclusive && IsExclusive)
|
||||
{
|
||||
_logger.LogInformation("→ {Text}", "自动钓鱼,启动!");
|
||||
var autoThrowRodEnabled = TaskContext.Instance().Config.AutoFishingConfig.AutoThrowRodEnabled;
|
||||
_logger.LogInformation("当前自动选饵抛竿状态[{Enabled}]", autoThrowRodEnabled.ToChinese());
|
||||
if (autoThrowRodEnabled)
|
||||
{
|
||||
_logger.LogInformation("枫丹、须弥地区暂不支持自动抛竿,如果在这两个地区钓鱼请关闭自动抛竿功能");
|
||||
}
|
||||
// if (autoThrowRodEnabled)
|
||||
// {
|
||||
// _logger.LogInformation("枫丹、须弥地区暂不支持自动抛竿,如果在这两个地区钓鱼请关闭自动抛竿功能");
|
||||
// }
|
||||
_switchBaitContinuouslyFrameNum = 0;
|
||||
_waitBiteContinuouslyFrameNum = 0;
|
||||
_noFishActionContinuouslyFrameNum = 0;
|
||||
@@ -1031,11 +1076,18 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
|
||||
private void PutRects(Rect left, Rect cur, Rect right)
|
||||
{
|
||||
//var list = new List<RectDrawable>
|
||||
//{
|
||||
// left.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen),
|
||||
// cur.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen),
|
||||
// right.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen)
|
||||
//};
|
||||
using var fishBoxRa = _currContent.CaptureRectArea.Derive(_fishBoxRect);
|
||||
var list = new List<RectDrawable>
|
||||
{
|
||||
left.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen),
|
||||
cur.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen),
|
||||
right.ToWindowsRectangleOffset(_fishBoxRect.X, _fishBoxRect.Y).ToRectDrawable(_pen)
|
||||
fishBoxRa.ToRectDrawable(left, "left", _pen),
|
||||
fishBoxRa.ToRectDrawable(cur, "cur", _pen),
|
||||
fishBoxRa.ToRectDrawable(right, "right", _pen),
|
||||
};
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList("FishingBarAll", list);
|
||||
}
|
||||
@@ -1061,4 +1113,4 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
// ClearDraw();
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 模仿Java实现的多属性枚举类
|
||||
/// 按形态大类分类的原神鱼类枚举
|
||||
/// </summary>
|
||||
public class BigFishType
|
||||
{
|
||||
public static readonly BigFishType Medaka = new("medaka", "fruit paste bait", "花鳉");
|
||||
public static readonly BigFishType LargeMedaka = new("large medaka", "fruit paste bait", "大花鳉");
|
||||
public static readonly BigFishType Stickleback = new("stickleback", "redrot bait", "棘鱼");
|
||||
public static readonly BigFishType Koi = new("koi", "fake fly bait", "假龙");
|
||||
public static readonly BigFishType Butterflyfish = new("butterflyfish", "false worm bait", "蝶鱼");
|
||||
public static readonly BigFishType Pufferfish = new("pufferfish", "fake fly bait", "炮鲀");
|
||||
public static readonly BigFishType FormaloRay = new("formalo ray", "fake fly bait", "佛玛洛鳐");
|
||||
public static readonly BigFishType DivdaRay = new("divda ray", "fake fly bait", "迪芙妲鳐");
|
||||
public static readonly BigFishType Angler = new("angler", "sugardew bait", "角鲀");
|
||||
public static readonly BigFishType AxeMarlin = new("axe marlin", "sugardew bait", "斧枪鱼");
|
||||
public static readonly BigFishType HeartfeatherBass = new("heartfeather bass", "sour bait", "心羽鲈");
|
||||
public static readonly BigFishType MaintenanceMek = new("maintenance mek", "flashing maintenance mek bait", "维护机关");
|
||||
|
||||
|
||||
public static IEnumerable<BigFishType> Values
|
||||
{
|
||||
get
|
||||
{
|
||||
yield return Medaka;
|
||||
yield return LargeMedaka;
|
||||
yield return Stickleback;
|
||||
yield return Koi;
|
||||
yield return Butterflyfish;
|
||||
yield return Pufferfish;
|
||||
yield return FormaloRay;
|
||||
yield return DivdaRay;
|
||||
yield return Angler;
|
||||
yield return AxeMarlin;
|
||||
yield return HeartfeatherBass;
|
||||
yield return MaintenanceMek;
|
||||
}
|
||||
}
|
||||
|
||||
public string Name { get; private set; }
|
||||
public string BaitName { get; private set; }
|
||||
public string ChineseName { get; private set; }
|
||||
|
||||
private BigFishType(string name, string baitName, string chineseName)
|
||||
{
|
||||
Name = name;
|
||||
BaitName = baitName;
|
||||
ChineseName = chineseName;
|
||||
}
|
||||
|
||||
public static BigFishType FromName(string name)
|
||||
{
|
||||
foreach (var fishType in Values)
|
||||
{
|
||||
if (fishType.Name == name)
|
||||
{
|
||||
return fishType;
|
||||
}
|
||||
}
|
||||
|
||||
throw new KeyNotFoundException($"BigFishType {name} not found");
|
||||
}
|
||||
|
||||
public static int GetIndex(BigFishType e)
|
||||
{
|
||||
for (int i = 0; i < Values.Count(); i++)
|
||||
{
|
||||
if (Values.ElementAt(i).Name == e.Name)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new KeyNotFoundException($"BigFishType {e.Name} not found index");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 模仿Java实现的多属性枚举类
|
||||
/// </summary>
|
||||
[Obsolete]
|
||||
public class FishType
|
||||
{
|
||||
public static readonly FishType AizenMedaka = new("aizen medaka", "fruit paste bait", "蓝染花鳉");
|
||||
@@ -27,7 +29,7 @@ public class FishType
|
||||
public static readonly FishType DivdaRay = new("divda ray", "fake fly bait", "迪芙妲鳐");
|
||||
public static readonly FishType FormaloRay = new("formalo ray", "fake fly bait", "佛玛洛鳐");
|
||||
public static readonly FishType GoldenKoi = new("golden koi", "fake fly bait", "金赤假龙");
|
||||
public static readonly FishType Pufferfish = new("pufferfish", "fake fly bait", "苦炮鲀2");
|
||||
public static readonly FishType Pufferfish = new("pufferfish", "fake fly bait", "炮鲀");
|
||||
public static readonly FishType RustyKoi = new("rusty koi", "fake fly bait", "锖假龙");
|
||||
public static readonly FishType HalcyonJadeAxeMarlin = new("halcyon jade axe marlin", "sugardew bait", "翡玉斧枪鱼");
|
||||
public static readonly FishType LazuriteAxeMarlin = new("lazurite axe marlin", "sugardew bait", "青金斧枪鱼");
|
||||
@@ -38,10 +40,12 @@ public class FishType
|
||||
public static readonly FishType TrueFruitAngler = new("true fruit angler", "sugardew bait", "真果角鲀");
|
||||
public static readonly FishType BlazingHeartfeatherBass = new("blazing heartfeather bass", "sour bait", "烘烘心羽鲈");
|
||||
public static readonly FishType RipplingHeartfeatherBass = new("rippling heartfeather bass", "sour bait", "波波心羽鲈");
|
||||
public static readonly FishType MaintenanceMekInitialConfiguration = new("maintenance mek: initial configuration", "flashing maintenance mek bait", "维护机关·初始能力型");
|
||||
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 MaintenanceMekInitialConfiguration = new("maintenance mek- initial configuration", "flashing maintenance mek bait", "维护机关·初始能力型");
|
||||
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 IEnumerable<FishType> Values
|
||||
{
|
||||
@@ -82,6 +86,7 @@ public class FishType
|
||||
yield return MaintenanceMekPlatinumCollection;
|
||||
yield return MaintenanceMekSituationController;
|
||||
yield return MaintenanceMekWaterBodyCleaner;
|
||||
yield return MaintenanceMekWaterGoldLeader;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Linq;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using Compunet.YoloV8.Data;
|
||||
using OpenCvSharp;
|
||||
using static OpenCvSharp.Cv2;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
|
||||
|
||||
@@ -29,20 +30,24 @@ public class Fishpond
|
||||
{
|
||||
foreach (var box in result.Boxes)
|
||||
{
|
||||
if (box.Class.Name == "moonfin")
|
||||
if (box.Class.Name == "rod")
|
||||
{
|
||||
TargetRect = new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
|
||||
continue;
|
||||
}
|
||||
else if (box.Class.Name == "target")
|
||||
else if (box.Class.Name == "err rod")
|
||||
{
|
||||
TargetRect = new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
|
||||
continue;
|
||||
}
|
||||
|
||||
var fish = new OneFish(box.Class.Name, new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height));
|
||||
var fish = new OneFish(box.Class.Name, new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height), box.Confidence);
|
||||
Fishes.Add(fish);
|
||||
}
|
||||
|
||||
// 可信度最高的鱼放在最前面
|
||||
Fishes = Fishes.OrderByDescending(fish => fish.Confidence).ToList();
|
||||
|
||||
FishpondRect = CalculateFishpondRect();
|
||||
}
|
||||
|
||||
@@ -94,7 +99,7 @@ public class Fishpond
|
||||
/// <returns></returns>
|
||||
public List<OneFish> FilterByBaitName(string baitName)
|
||||
{
|
||||
return Fishes.Where(fish => fish.FishType.BaitName == baitName).ToList();
|
||||
return Fishes.Where(fish => fish.FishType.BaitName == baitName).OrderByDescending(fish => fish.Confidence).ToList();
|
||||
}
|
||||
|
||||
public OneFish? FilterByBaitNameAndRecently(string baitName, Rect prevTargetFishRect)
|
||||
@@ -118,6 +123,7 @@ public class Fishpond
|
||||
result = fish;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -150,6 +156,7 @@ public class Fishpond
|
||||
result = key;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
|
||||
@@ -10,13 +6,16 @@ namespace BetterGenshinImpact.GameTask.AutoFishing.Model;
|
||||
public class OneFish
|
||||
{
|
||||
|
||||
public FishType FishType { get; set; }
|
||||
public BigFishType FishType { get; set; }
|
||||
|
||||
public Rect Rect { get; set; }
|
||||
|
||||
public OneFish(string name, Rect rect)
|
||||
public float Confidence { get; set; }
|
||||
|
||||
public OneFish(string name, Rect rect, float confidence)
|
||||
{
|
||||
FishType = FishType.FromName(name);
|
||||
FishType = BigFishType.FromName(name);
|
||||
Rect = rect;
|
||||
Confidence = confidence;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
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;
|
||||
}
|
||||
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user