Compare commits

..
1 Commits
Author SHA1 Message Date
qhy040404 697dec12e0 fix relative path 2024-08-14 20:56:21 +08:00
401 changed files with 7949 additions and 29776 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
---
name: Bug report / 错误报告
about: Create a report to help us improve / 创建报告以帮助我们改进
title: "[bug]请补充标题内容"
title: "[bug] "
labels: bug
---
-3
View File
@@ -1,3 +0,0 @@
[submodule "BetterGenshinImpact/Script"]
path = BetterGenshinImpact/Script
url = https://github.com/babalae/bettergi-scripts.git
@@ -19,17 +19,9 @@ public class AvatarClassifyGen
// 读取基础图像
// 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_Chasca.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Olorun.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
// List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_NilouCostumeFairy.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles3);
// List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kachina.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles4);
// List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mualani.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles5);
// List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kinich.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles6);
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Sethos.png", SearchOption.TopDirectoryOnly).ToList();
// List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Clorinde.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles2);
// 生成训练集
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
@@ -1,193 +0,0 @@
using System.Diagnostics;
using System.IO;
using OpenCvSharp;
namespace BetterGenshinImpact.Test.Dataset;
public class AvatarClassifyTransparentGen
{
// 基础图像文件夹
private const string BaseDir = @"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\分类器\";
// 背景图像文件夹
private static readonly string BackgroundDir = Path.Combine(BaseDir, "background");
private static readonly Random Rd = new Random();
// 在类的开头添加一个新的常量
private const string SideSrcDir = "side_src";
private const string SideSrcTransportDir = "side_src_transport";
public static void GenAll()
{
// 调整透明度(可选,取消注释以启用)
AdjustTransparency(0.5f);
// 读取基础图像
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Chasca.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Olorun.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
// 生成训练集
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}_t_{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;
}
}
// 在类中添加以下新方法
public static void AdjustTransparency(float targetAlpha = 0.5f)
{
string sourcePath = Path.Combine(BaseDir, SideSrcDir);
string destinationPath = Path.Combine(BaseDir, SideSrcTransportDir);
Directory.CreateDirectory(destinationPath);
List<string> sideImageFiles = Directory.GetFiles(sourcePath, "*.png", SearchOption.TopDirectoryOnly).ToList();
foreach (string sideImageFile in sideImageFiles)
{
string fileName = Path.GetFileName(sideImageFile);
string destFile = Path.Combine(destinationPath, fileName);
Mat image = Cv2.ImRead(sideImageFile, ImreadModes.Unchanged);
Mat[] channels = Cv2.Split(image);
if (channels.Length == 4) // 确保图像有透明通道
{
Mat alphaChannel = channels[3];
Cv2.Multiply(alphaChannel, targetAlpha, alphaChannel);
Mat result = new Mat();
Cv2.Merge(channels, result);
Cv2.ImWrite(destFile, result);
}
else
{
Console.WriteLine($"警告:{fileName} 没有透明通道,将直接复制原文件。");
File.Copy(sideImageFile, destFile, true);
}
}
Console.WriteLine($"已完成透明度调整,结果保存在 {destinationPath}");
}
}
+4 -28
View File
@@ -4,7 +4,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Test"
Width="240"
Width="120"
Height="450"
mc:Ignorable="d">
<Canvas>
@@ -31,7 +31,7 @@
Width="100"
Height="23"
Click="DoMatchTest"
Content="生成特征点" />
Content="特征匹配测试" />
<Button Canvas.Left="10"
Canvas.Top="130"
Width="100"
@@ -43,21 +43,13 @@
Width="100"
Height="23"
Click="MapDrawTeleportPoint"
Content="画传送点" />
Content="超大地图标点" />
<Button Canvas.Left="10"
Canvas.Top="190"
Width="100"
Height="23"
Click="GenAvatarData"
Content="侧面头像数据集" />
<Button Canvas.Left="120"
Canvas.Top="190"
Width="100"
Height="23"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Click="GenAvatarDataT"
Content="透明头像数据集" />
Content="生成侧面头像数据集" />
<Button Canvas.Left="10"
Canvas.Top="220"
Width="100"
@@ -70,21 +62,5 @@
Height="23"
Click="MapPathView"
Content="路线地图查看" />
<Button Canvas.Left="120"
Canvas.Top="10"
Width="100"
Height="23"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Click="ZoomOut"
Content="缩小地图到256" />
<Button Canvas.Left="120"
Canvas.Top="40"
Width="100"
Height="23"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Click="CameraTest"
Content="新视角识别测试" />
</Canvas>
</Window>
+8 -44
View File
@@ -1,17 +1,17 @@
using System.Diagnostics;
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.Simple.Track;
using BetterGenshinImpact.Test.View;
using System.Windows;
using BetterGenshinImpact.GameTask.Common.Map;
using OpenCvSharp;
using Window = System.Windows.Window;
namespace BetterGenshinImpact.Test;
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
@@ -32,7 +32,7 @@ public partial class MainWindow : Window
private void DoMapPuzzle(object sender, System.Windows.RoutedEventArgs e)
{
MapPuzzle.PutAll();
MapPuzzle.Put();
}
private void DoOcrTest(object sender, System.Windows.RoutedEventArgs e)
@@ -48,16 +48,11 @@ public partial class MainWindow : Window
private void DoMatchTest(object sender, System.Windows.RoutedEventArgs e)
{
// KeyPointMatchTest.Test();
// EntireMapTest.Test();
EntireMapTest.Test();
// EntireMapTest.Storage();
// BigMapMatchTest.Test();
// FeatureTransfer.Transfer();
// var extractor = new LargeSiftExtractor();
// extractor.ExtractAndSaveSift(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\");
EntireMapTest.Storage256();
}
private void MapDrawTeleportPoint(object sender, RoutedEventArgs e)
@@ -79,35 +74,4 @@ public partial class MainWindow : Window
{
MapPathTest.Test();
}
private void ZoomOut(object sender, RoutedEventArgs e)
{
ScaleTest.ZoomOutTest();
}
private void GenAvatarDataT(object sender, RoutedEventArgs e)
{
AvatarClassifyTransparentGen.GenAll();
}
private void CameraTest(object sender, RoutedEventArgs e)
{
var path = @"E:\HuiTask\更好的原神\地图匹配\比较\小地图\Clip_20240323_185854.png";
var pic1 = new Mat(path);
CameraOrientationFromLimint cameraOrientation = new();
var f = cameraOrientation.PredictRotation(pic1);
Debug.WriteLine("C#版本 方向1:" + f);
// var pic2 = new Mat(path);
// CameraOrientationV2 cameraOrientation3 = new();
// var f3 = cameraOrientation3.PredictRotation(pic2);
// Debug.WriteLine("py直接翻译C#版本 方向1:" + f3);
var grey = new Mat(path, ImreadModes.Grayscale);
var f2 = CameraOrientation.ComputeMiniMap(grey);
Debug.WriteLine("老版本方向2:" + f2);
}
}
}
@@ -17,7 +17,7 @@ public class BigMapMatchTest
SpeedTimer speedTimer = new();
// var mainMap100BlockMat = new Mat(@"D:\HuiPrograming\Projects\CSharp\MiHoYo\BetterGenshinImpact\BetterGenshinImpact\Assets\Map\mainMap100Block.png", ImreadModes.Grayscale);
var map2048 = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", ImreadModes.Grayscale);
var map2048 = MapAssets.Instance.MainMap2048BlockMat.Value;
var mainMap100BlockMat = ResizeHelper.Resize(map2048, 1d / (4 * 2));
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\mainMap128Block.png", mainMap100BlockMat);
@@ -6,8 +6,6 @@ using OpenCvSharp;
using OpenCvSharp.Detail;
using System.Diagnostics;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.Map;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -53,13 +51,7 @@ public class EntireMapTest
public static void Storage()
{
var featureMatcher = new FeatureMatcher(new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", ImreadModes.Grayscale), new FeatureStorage("mainMap2048Block"));
var featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap2048BlockMat.Value, new FeatureStorage("mainMap2048Block"));
MessageBox.Show("特征点生成完成");
}
public static void Storage256()
{
FeatureMatcher _featureMatcher = new( new Mat(Global.Absolute(@"Assets\Map\mainMap256Block.png"), ImreadModes.Grayscale), new FeatureStorage("mainMap256Block"));
MessageBox.Show("256特征点生成完成");
}
}
@@ -1,150 +0,0 @@
using System.Diagnostics;
using System.IO;
using OpenCvSharp;
using OpenCvSharp.Features2D;
namespace BetterGenshinImpact.Test.Simple.AllMap;
public class LargeSiftExtractor
{
private const int BLOCK_SIZE = 1024;
private const int OVERLAP_SIZE = BLOCK_SIZE * 3;
private readonly Feature2D _sift = SIFT.Create();
public void ExtractAndSaveSift(string imagePath, string outputPath)
{
Debug.WriteLine($"开始提取图像的SIFT特征: {imagePath}");
var img = Cv2.ImRead(imagePath, ImreadModes.Grayscale);
var allKeypoints = new List<KeyPoint>();
var allDescriptors = new List<Mat>();
// 计算需要切分的块数
int rows = (int)Math.Ceiling(img.Height / (double)BLOCK_SIZE);
int cols = (int)Math.Ceiling(img.Width / (double)BLOCK_SIZE);
Debug.WriteLine($"图像被分成 {rows} 行 {cols} 列的块。");
// 遍历每个块
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
Debug.WriteLine($"处理第 {row} 行,第 {col} 列的块");
var (keypoints, descriptors) = ProcessBlock(img, row, col);
// 调整keypoints的坐标
// 修改这里:使用 for 循环而不是 foreach
for (int i = 0; i < keypoints.Length; i++)
{
var kp = keypoints[i];
kp.Pt.X += col * BLOCK_SIZE;
kp.Pt.Y += row * BLOCK_SIZE;
keypoints[i] = kp;
}
allKeypoints.AddRange(keypoints);
allDescriptors.Add(descriptors);
}
}
// 合并所有descriptors
var finalDescriptors = new Mat();
Cv2.VConcat(allDescriptors.ToArray(), finalDescriptors);
// 保存结果
SaveFeatures(allKeypoints, finalDescriptors, outputPath);
// 释放资源
foreach (var desc in allDescriptors)
{
desc.Dispose();
}
Debug.WriteLine("SIFT特征提取和保存完成。");
}
private (KeyPoint[] keypoints, Mat descriptors) ProcessBlock(Mat img, int row, int col)
{
// 计算当前块的范围
int startY = row * BLOCK_SIZE;
int startX = col * BLOCK_SIZE;
// 处理边缘情况
bool isEdgeRow = row == 0 || row == img.Height / BLOCK_SIZE;
bool isEdgeCol = col == 0 || col == img.Width / BLOCK_SIZE;
if (!isEdgeRow && !isEdgeCol)
{
// 非边缘区域,使用重叠区域
int overlapStartY = Math.Max(0, startY - BLOCK_SIZE);
int overlapStartX = Math.Max(0, startX - BLOCK_SIZE);
using var blockRegion = new Mat(img,
new Rect(overlapStartX, overlapStartY,
Math.Min(OVERLAP_SIZE, img.Width - overlapStartX),
Math.Min(OVERLAP_SIZE, img.Height - overlapStartY)));
KeyPoint[] kps;
var desc = new Mat();
_sift.DetectAndCompute(blockRegion, null, out kps, desc);
Debug.WriteLine($"Block at ({row},{col}) - Original keypoints count: {kps.Length}");
// 找出中心区域关键点的索引
var centralKeypointIndices = new List<int>();
var centralKeypoints = new List<KeyPoint>();
for (int i = 0; i < kps.Length; i++)
{
if (kps[i].Pt.X >= BLOCK_SIZE && kps[i].Pt.X < BLOCK_SIZE * 2 &&
kps[i].Pt.Y >= BLOCK_SIZE && kps[i].Pt.Y < BLOCK_SIZE * 2)
{
centralKeypointIndices.Add(i);
var kp = kps[i];
kp.Pt.X -= BLOCK_SIZE;
kp.Pt.Y -= BLOCK_SIZE;
centralKeypoints.Add(kp);
}
}
// 创建新的描述符矩阵,只包含中心区域关键点的描述符
var centralDesc = new Mat(centralKeypointIndices.Count, desc.Cols, desc.Type());
for (int i = 0; i < centralKeypointIndices.Count; i++)
{
var rowIndex = centralKeypointIndices[i];
var row2 = desc.Row(rowIndex);
row2.CopyTo(centralDesc.Row(i));
row2.Dispose();
}
Debug.WriteLine($"中心区域处理了 {centralKeypoints.Count} 个关键点。");
return (centralKeypoints.ToArray(), centralDesc);
}
else
{
// 边缘区域,直接处理
using var blockRegion = new Mat(img,
new Rect(startX, startY,
Math.Min(BLOCK_SIZE, img.Width - startX),
Math.Min(BLOCK_SIZE, img.Height - startY)));
var desc = new Mat();
_sift.DetectAndCompute(blockRegion, null, out var kps, desc);
Debug.WriteLine($"边缘区域处理了 {kps.Length} 个关键点。");
return (kps, desc);
}
}
private void SaveFeatures(List<KeyPoint> keypoints, Mat descriptors, string outputPath)
{
Debug.WriteLine($"保存 {keypoints.Count} 个关键点和描述符到 {outputPath}");
using var fs1 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.kp"), FileStorage.Modes.Write);
fs1.Write("kp", keypoints.ToArray());
fs1.Release();
using var fs2 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.mat"), FileStorage.Modes.Write);
fs2.Write("desc", descriptors);
fs2.Release();
Debug.WriteLine("特征保存成功。");
}
}
@@ -8,6 +8,7 @@ namespace BetterGenshinImpact.Test.Simple.AllMap;
public class MapPuzzle
{
public static readonly int block = 2048;
public static List<string> PicWhiteHashList = new List<string>
{
@@ -25,26 +26,9 @@ public class MapPuzzle
public static MD5 Md5Service = MD5.Create();
public static void PutAll()
public static void Put()
{
// 保存2048大图
// var img2048 = Put(2048);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", img2048);
// 保存1024
var img1024 = Put(1024);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_1024.png", img1024);
// 保存256
// var grayImage = new Mat();
// Cv2.CvtColor(img1024.Resize(new Size(img1024.Width / 4, img1024.Height / 4), 0, 0, InterpolationFlags.Cubic), grayImage, ColorConversionCodes.BGR2GRAY);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_256.png", grayImage);
}
public static Mat Put(int block = 2048)
{
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map_5.2"; // 图片文件夹路径
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map"; // 图片文件夹路径
string pattern = @"UI_MapBack_([-+]?\d+)_([-+]?\d+)(.*)";
var images = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly); // 获取所有图片文件路径
@@ -130,7 +114,6 @@ public class MapPuzzle
// 计算大图的总宽度和高度
var lenCol = maxCol - minCol;
var lenRow = maxRow - minRow;
Debug.WriteLine($"列数X: {lenCol+1}, 行数Y: {lenRow+1}");
int totalWidth = (lenCol + 1) * block;
int totalHeight = (lenRow + 1) * block;
@@ -174,43 +157,16 @@ public class MapPuzzle
Debug.WriteLine("");
}
// 地图图片块
// SaveImagesAs1024X1024(arr, imageLocations, @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\地图块", minRow, minCol);
// 保存大图
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));
// 释放资源
return largeImage;
}
public static void SaveImagesAs1024X1024(int[,] arr, Dictionary<(int row, int col), ImgInfo> imageLocations, string outputFolder, int minRow, int minCol)
{
if (!Directory.Exists(outputFolder))
largeImage.Dispose();
foreach (var img in imageLocations.Values)
{
Directory.CreateDirectory(outputFolder);
}
for (int row = 0; row < arr.GetLength(0); row++)
{
for (int col = 0; col < arr.GetLength(1); col++)
{
if (arr[row, col] == 1)
{
var key = (row + minRow, col + minCol);
if (imageLocations.TryGetValue(key, out var imgInfo))
{
var img = imgInfo.Img;
if (img.Width != 1204 || img.Height != 1204)
{
img = imgInfo.Img.Resize(new Size(1024, 1024), 0, 0, InterpolationFlags.Nearest);
}
var outputPath = Path.Combine(outputFolder, $"{row}_{col}.png");
Cv2.ImWrite(outputPath, img);
img.Dispose();
}
}
}
img.Img.Dispose();
}
}
@@ -1,11 +1,8 @@
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service;
using OpenCvSharp;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -13,28 +10,24 @@ public class MapTeleportPointDraw
{
public static void Draw()
{
// var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\5.0");
// pList.AddRange(MapAssets.Instance.TpPositions);
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor.png");
DrawTeleportPoint(map, MapLazyAssets.Instance.TpPositions);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\传送点_1024_0.34.3.png", map);
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, List<GiWorldPosition> points)
public static void DrawTeleportPoint(Mat map, Point[] points)
{
foreach (var point in points)
{
var p = MapCoordinate.GameToMain1024(point.Position);
Cv2.Circle(map, p, 4, Scalar.Red, 2);
// 写文字
Cv2.PutText(map, $"[{point.X:F2},{point.Y:F2}]", new Point(p.X + 10, p.Y + 5), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
Cv2.Circle(map, new Point(point.X, point.Y), 10, Scalar.Red, 2);
}
}
public static List<GiWorldPosition> LoadTeleportPoint(string folderPath)
public static List<Point> LoadTeleportPoint(string folderPath)
{
string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
List<GiWorldPosition> points = new();
List<Point> points = new();
foreach (var file in files)
{
var gamePoint = JsonSerializer.Deserialize<GamePoint>(File.ReadAllText(file), ConfigService.JsonOptions);
@@ -55,12 +48,17 @@ public class MapTeleportPointDraw
/// </summary>
/// <param name="position">[a,b,c]</param>
/// <returns></returns>
public static GiWorldPosition Transform(decimal[] position)
public static Point Transform(decimal[] position)
{
return new GiWorldPosition
{
Position = 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
@@ -1,16 +0,0 @@
using OpenCvSharp;
namespace BetterGenshinImpact.Test.Simple;
public class ScaleTest
{
public static void ZoomOutTest()
{
var mainMap2048BlockMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap2048Block.png", ImreadModes.Color);
// 缩小 2048/512 = 4
var targetFilePath = @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor.png";
// opencv 缩小
var mainMap256BlockMat = mainMap2048BlockMat.Resize(new Size(mainMap2048BlockMat.Width / 2, mainMap2048BlockMat.Height / 2));
mainMap256BlockMat.SaveImage(targetFilePath);
}
}
@@ -13,22 +13,22 @@ internal class MapPathTest
{
public static void Test()
{
// var wayJson = File.ReadAllText(Global.Absolute(@"log\way\yl3.json"));
// var way = JsonSerializer.Deserialize<GiPath>(wayJson, ConfigService.JsonOptions) ?? throw new Exception("way json deserialize failed");
//
// var points = way.WayPointList.Select(giPathPoint => giPathPoint.MatchRect.GetCenterPoint()).ToList();
//
// var pointsRect = Cv2.BoundingRect(points);
// var allMap = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\mainMap2048Block.png");
//
// // 按顺序连线,每个点都画圈
// for (var i = 0; i < points.Count - 1; i++)
// {
// Cv2.Line(allMap, points[i], points[i + 1], Scalar.Red, 1);
// Cv2.Circle(allMap, points[i], 3, Scalar.Red, -1);
// }
//
// var map = allMap[new Rect(pointsRect.X - 100, pointsRect.Y - 100, pointsRect.Width + 200, pointsRect.Height + 200)];
// Cv2.ImShow("map", map);
var wayJson = File.ReadAllText(Global.Absolute(@"log\way\yl3.json"));
var way = JsonSerializer.Deserialize<GiPath>(wayJson, ConfigService.JsonOptions) ?? throw new Exception("way json deserialize failed");
var points = way.WayPointList.Select(giPathPoint => giPathPoint.MatchRect.GetCenterPoint()).ToList();
var pointsRect = Cv2.BoundingRect(points);
var allMap = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\mainMap2048Block.png");
// 按顺序连线,每个点都画圈
for (var i = 0; i < points.Count - 1; i++)
{
Cv2.Line(allMap, points[i], points[i + 1], Scalar.Red, 1);
Cv2.Circle(allMap, points[i], 3, Scalar.Red, -1);
}
var map = allMap[new Rect(pointsRect.X - 100, pointsRect.Y - 100, pointsRect.Width + 200, pointsRect.Height + 200)];
Cv2.ImShow("map", map);
}
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
</PropertyGroup>
<ItemGroup>
<None Remove="NativeMethods.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.46-beta">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
@@ -0,0 +1,10 @@
{
"$schema": "https://raw.githubusercontent.com/microsoft/CsWin32/main/src/Microsoft.Windows.CsWin32/settings.schema.json",
"allowMarshaling": true,
"useSafeHandles": false,
"emitSingleFile": true,
"public": true,
"comInterop": {
"useIntPtrForComOutPointers": true
}
}
@@ -0,0 +1,38 @@
// D3D11
CreateDirect3D11DeviceFromDXGIDevice
CreateDirect3D11SurfaceFromDXGISurface
// GDI32
BitBlt
CreateCompatibleBitmap
CreateCompatibleDC
DeleteDC
GetDeviceCaps
SelectObject
// User32
GetClientRect
GetDC
GetForegroundWindow
GetSystemMetrics
GetWindowDC
GetWindowRect
GetWindowThreadProcessId
mouse_event
PostMessage
ReleaseDC
EnumWindows
GetWindowText
IsWindowVisible
GetWindowTextLength
// COM & WinRT
D3D11CreateDevice
ID3D11Device3
IDirect3DDxgiInterfaceAccess
// Constants
D3D11_SDK_VERSION
DXGI_ERROR_UNSUPPORTED
WM_LBUTTONDOWN
WM_LBUTTONUP
+40
View File
@@ -5,10 +5,18 @@ VisualStudioVersion = 17.6.33815.320
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact", "BetterGenshinImpact\BetterGenshinImpact.csproj", "{75EC89E2-413D-4725-BCEA-AFAC57708F07}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Vision.WindowCapture", "Vision.WindowCapture\Vision.WindowCapture.csproj", "{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Win32", "BetterGenshinImpact.Win32\BetterGenshinImpact.Win32.csproj", "{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.GameCapture", "Fischless.GameCapture\Fischless.GameCapture.csproj", "{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Vision.WindowCapture.Test", "Vision.WindowCapture.Test\Vision.WindowCapture.Test.csproj", "{D35CB953-C666-4E57-9A9A-3AAE5BF78402}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.HotkeyCapture", "Fischless.HotkeyCapture\Fischless.HotkeyCapture.csproj", "{08152E44-2564-46C5-B5B2-54DD43C01A79}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.KeyboardCapture", "Fischless.KeyboardCapture\Fischless.KeyboardCapture.csproj", "{10A48327-7E58-4B51-B1FC-55506C703C8F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Deploy", "Deploy", "{458E1106-43A4-47E6-B11B-D243035D4C76}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicaSetup", "Build\MicaSetup\MicaSetup.csproj", "{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}"
@@ -35,6 +43,22 @@ Global
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|Any CPU.Build.0 = Release|x64
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|x64.ActiveCfg = Release|x64
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|x64.Build.0 = Release|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|Any CPU.ActiveCfg = Debug|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|Any CPU.Build.0 = Debug|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|x64.ActiveCfg = Debug|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|x64.Build.0 = Debug|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|Any CPU.ActiveCfg = Release|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|Any CPU.Build.0 = Release|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|x64.ActiveCfg = Release|x64
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|x64.Build.0 = Release|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|Any CPU.ActiveCfg = Debug|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|Any CPU.Build.0 = Debug|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|x64.ActiveCfg = Debug|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|x64.Build.0 = Debug|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|Any CPU.ActiveCfg = Release|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|Any CPU.Build.0 = Release|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|x64.ActiveCfg = Release|x64
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|x64.Build.0 = Release|x64
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|Any CPU.ActiveCfg = Debug|x64
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|Any CPU.Build.0 = Debug|x64
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|x64.ActiveCfg = Debug|x64
@@ -43,6 +67,14 @@ Global
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|Any CPU.Build.0 = Release|x64
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|x64.ActiveCfg = Release|x64
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|x64.Build.0 = Release|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|Any CPU.ActiveCfg = Debug|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|Any CPU.Build.0 = Debug|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|x64.ActiveCfg = Debug|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|x64.Build.0 = Debug|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|Any CPU.ActiveCfg = Release|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|Any CPU.Build.0 = Release|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|x64.ActiveCfg = Release|x64
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|x64.Build.0 = Release|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|Any CPU.ActiveCfg = Debug|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|Any CPU.Build.0 = Debug|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|x64.ActiveCfg = Debug|x64
@@ -51,6 +83,14 @@ Global
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|Any CPU.Build.0 = Release|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.ActiveCfg = Release|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.Build.0 = Release|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|Any CPU.ActiveCfg = Debug|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|Any CPU.Build.0 = Debug|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|x64.ActiveCfg = Debug|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|x64.Build.0 = Debug|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|Any CPU.ActiveCfg = Release|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|Any CPU.Build.0 = Release|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|x64.ActiveCfg = Release|x64
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|x64.Build.0 = Release|x64
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|x64.ActiveCfg = Debug|x64
+1 -4
View File
@@ -2,21 +2,18 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bgivc="clr-namespace:BetterGenshinImpact.View.Converters"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<vio:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Assets/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<bgivc:NotNullConverter x:Key="NotNullConverter" />
</ResourceDictionary>
+4 -46
View File
@@ -1,7 +1,6 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Hutao;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.Service.Notification;
@@ -11,7 +10,6 @@ using BetterGenshinImpact.View.Pages;
using BetterGenshinImpact.ViewModel;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
@@ -22,11 +20,7 @@ using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using BetterGenshinImpact.View.Pages.View;
using BetterGenshinImpact.ViewModel.Pages.OneDragon;
using BetterGenshinImpact.ViewModel.Pages.View;
using Wpf.Ui;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact;
@@ -41,10 +35,6 @@ public partial class App : Application
.CheckIntegration()
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder =>
{
builder.ClearProviders();
})
.ConfigureServices(
(context, services) =>
{
@@ -75,6 +65,7 @@ public partial class App : Application
// App Host
services.AddHostedService<ApplicationHostService>();
// Page resolver service
services.AddSingleton<IPageService, PageService>();
@@ -94,32 +85,15 @@ public partial class App : Application
services.AddView<CommonSettingsPage, CommonSettingsPageViewModel>();
services.AddView<TaskSettingsPage, TaskSettingsPageViewModel>();
services.AddView<HotKeyPage, HotKeyPageViewModel>();
// services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
services.AddView<KeyMouseRecordPage, KeyMouseRecordPageViewModel>();
services.AddView<JsListPage, JsListViewModel>();
services.AddView<MapPathingPage, MapPathingViewModel>();
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
services.AddSingleton<PathingConfigViewModel>();
// services.AddView<PathingConfigView, PathingConfigViewModel>();
// 一条龙 ViewModels
// services.AddSingleton<CraftViewModel>();
// services.AddSingleton<DailyCommissionViewModel>();
// services.AddSingleton<DailyRewardViewModel>();
// services.AddSingleton<DomainViewModel>();
// services.AddSingleton<ForgingViewModel>();
// services.AddSingleton<LeyLineBlossomViewModel>();
// services.AddSingleton<MailViewModel>();
// services.AddSingleton<SereniteaPotViewModel>();
// services.AddSingleton<TcgViewModel>();
// services.AddView<DispatcherPage, DispatcherPageViewModel>();
// My Services
services.AddSingleton<TaskTriggerDispatcher>();
services.AddSingleton<NotificationService>();
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
services.AddSingleton<NotifierManager>();
services.AddSingleton<IScriptService, ScriptService>();
services.AddSingleton<HutaoNamedPipe>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
@@ -264,23 +238,7 @@ public partial class App : Application
e = e.InnerException;
}
try
{
ExceptionReport.Show(e);
}
catch
{
// Fallback.
System.Windows.Forms.MessageBox.Show(
$"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
);
}
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.

Before

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

@@ -1182,7 +1182,6 @@
"其老爷",
"关宏",
"关垂",
"杏仁长老",
"仲夏庭园",
"无妄引咎密宫",
"华池岩岫",
@@ -1342,21 +1341,6 @@
"残毁的剑柄",
"裂断的剑柄",
"未熄的剑柄",
"意志破碎的残片",
"意志明晰的寄偶",
"意志巡游的符像",
"聚燃的石块",
"聚燃的命种",
"聚燃的游像眼",
"秘源轴",
"秘源机鞘",
"秘源真芯",
"稚嫩的尖齿",
"老练的坚齿",
"横行霸者的利齿",
"卫从的木哨",
"战士的铁哨",
"龙冠武士的金哨",
"小灯草",
"慕风蘑菇",
"蒲公英籽",
@@ -1400,15 +1384,6 @@
"子探测单元",
"湖光铃兰",
"初露之源",
"颗粒果",
"烛伞蘑菇",
"烬芯花",
"澄晶实",
"苦种",
"肉龙掌",
"灼灼彩菊",
"浪沫羽鳃",
"青蜜莓",
"红莲蛾",
"蝴蝶",
"黑背鲈鱼",
@@ -1496,15 +1471,6 @@
"「公平」的教导",
"「正义」的教导",
"「秩序」的教导",
"「角逐」的哲学",
"「焚燔」的哲学",
"「纷争」的哲学",
"「角逐」的指引",
"「焚燔」的指引",
"「纷争」的指引",
"「角逐」的教导",
"「焚燔」的教导",
"「纷争」的教导",
"「金鱼草」的种子",
"「鸣草」的种子",
"「清心」的种子",
@@ -1585,9 +1551,6 @@
"魔晶块",
"奇异的「牙齿」",
"汲取了生命力的龙牙",
"牛奶",
"糖",
"固晶甲虫",
"新鲜的鸟蛋",
"新鲜的绯樱绣球",
"新鲜的海草",
@@ -1598,9 +1561,6 @@
"新鲜的绝云椒椒",
"新鲜的树莓",
"新鲜的香辛果",
"「永远高挂的落日」",
"「岸上游泳的鱼儿」",
"「夜晚显现的明月」",
"纯洁松果",
"碎星铁矿",
"烹饪",
@@ -1889,69 +1849,6 @@
"更改旋律",
"准备演出",
"继续演出",
"感谢信",
"开始演奏",
"募刻巧像",
"摆放巧像",
"绘想游迹",
"召唤激流",
"放入",
"旋转管道",
"让魔水流动吧!",
"就是现在",
"敲一敲…",
"我带你飞一次?",
"我来帮忙!",
"戳一戳",
"出发吧!",
"有点奇怪…",
"拉你一把",
"发生什么了?",
"交给我吧",
"已经安全了!",
"我需要那颗星星",
"用力拉",
"一起用力拉",
"你已经做得很好了",
"搭乘「空中列车」",
"这是什么比赛?",
"与纠结的小人结队",
"与贪吃的小人结队",
"与莽撞的小人结队",
"开始挑战",
"放置蘑菇",
"放置苹果",
"放置风车菊",
"放置鸟蛋",
"放置树莓",
"放置禽肉",
"放置蘑菇",
"放置甜甜花",
"放置绝云椒椒",
"走左边",
"走右边",
"走前面",
"算我一个!",
"找到你啦!",
"等待海上列车…",
"推一下",
"我来猜猜",
"是元能构装体?",
"是水深渊法师?",
"是穿蓝衣服的小兔子?",
"是超大松鼠?",
"是短鬓虎?",
"是穿绿衣服的狐狸?",
"我来试试",
"关于巨龙…",
"你还好吗?",
"魔线飞行",
"老旧的日记",
"发黄的信件",
"准备留影",
"用力拔",
"更加用力拔",
"污损的快件",
"无锋剑",
"银剑",
"训练大剑",
@@ -4648,817 +4545,6 @@
"布蕾斯特",
"苏定",
"玄理",
"奥比奇",
"波波拉诺",
"温柔的守卫",
"藏宝爱好者",
"卡佩",
"艾德加",
"席尔万",
"卢西恩",
"进入席尔万房间",
"进入卢西恩房间",
"进入艾德加房间",
"议论纷纷的群众",
"议论纷纷的群众",
"议论纷纷的群众",
"议论纷纷的群众",
"议论纷纷的群众",
"议论纷纷的群众",
"进入席尔万房间",
"艾德加",
"卡佩",
"奥比奇",
"波波拉诺",
"探长",
"埃斯诺尔",
"帕纽尔",
"罗泽尔",
"优雅的雕像",
"用力推!!!",
"用力拽!!!",
"用力抬!!!",
"温和的雕像",
"平静的雕像",
"福罗贝尔",
"奥雷卢",
"埃斯唐普",
"西梅",
"萨博兰",
"苏法什",
"陈旧的手稿",
"疲惫的手稿",
"兴奋的纸蛙",
"沉稳的纸蛙",
"好心的纸蛙",
"忧郁的纸蛙",
"123木头人",
"123木头人2",
"门后的声音",
"注脚",
"巨人卫兵",
"路人",
"星轨王城守卫",
"店长",
"粮油店长",
"巨人卫兵",
"巨人卫兵",
"巨人卫兵",
"巨人卫兵",
"星轨王城守卫",
"肖维涅",
"我来试试",
"我来试试",
"我来试试",
"我来试试",
"我来试试",
"我来试试",
"巨人卫兵",
"巨人卫兵",
"埃斯诺尔",
"失望的纸蛙",
"不满的纸蛙",
"发生什么了?",
"字迹歪歪扭扭的信",
"杏仁",
"溪泉",
"柑橘",
"翻看书页",
"布勒凡",
"布勒施",
"欧立威",
"毕塞尔特",
"搭乘「空中列车」",
"杜林",
"小杜林",
"拜希麦·五世",
"爆竹",
"板栗",
"白果",
"瑟杜尔",
"威尔",
"积木卫兵",
"蒙塔纳",
"魔女M",
"魔女B",
"冲在前面的士兵",
"冲在前面的士兵",
"门内的人",
"门内的人",
"门内的人",
"飞鼠",
"士兵",
"士兵",
"小飞鼠",
"飞鼠妈妈",
"老旧的日记",
"发黄的信件",
"进入「邪龙」的巢穴",
"德维特",
"许迪",
"克朗谢",
"埃洛夫",
"杏仁",
"溪泉",
"柑橘",
"等待海上列车…",
"前往提瓦特",
"前往星轨王城",
"前往破碎之海",
"前往提瓦特",
"「一篇未完成的手稿」",
"杏仁",
"溪泉",
"《提瓦特世界史·第一部分》",
"《枫丹香水广告集》",
"《白猫神探》",
"《薰衣草之花》",
"「伊利萨」",
"「半熟蛋」",
"「合成台」",
"「咕噜噜」",
"「大椰子」",
"「小波」",
"「此地的伟大精神」",
"「毛发如夜的野兽」",
"「灵道刻印门」",
"「炫彩呆子」",
"「狂图捕手」",
"「绿松石」",
"「翡翠」",
"「西弗安雅」",
"「金盏花」",
"「队长」",
"「黑曜石碑的影像」",
"丁戈内克",
"万奎洛",
"万杰鲁",
"不耐烦的贼匪",
"不耐烦的部族成员",
"专注的「花羽会」战士",
"为伙伴们烹饪料理",
"乌丘",
"乌兰塔",
"乌图伦库",
"乌尔",
"乌米",
"乌苏坎",
"乌茨勒",
"互动点",
"亚格贝乌",
"亚瓦尔",
"亚蕾琪",
"代杜古",
"伊克娜",
"伊兹娜",
"伊卡力",
"伊卡尤",
"伊图提娅",
"伊妮",
"伊扎帕",
"伊法",
"伊波莱",
"伊泽",
"伊瓦伊",
"伊约芭",
"伊茨昆",
"伊莫莎",
"伊莱帕",
"伊蒂莉",
"伊蕾尔",
"伊蜜",
"伊西多尔",
"伊西姆",
"伊赫卡",
"众人写成的记录",
"低语",
"佩蕾·努伊",
"依扎娜",
"依稀可以辨认的布告",
"克伊奈",
"克拉莉希娅",
"克瓦斯尼科夫",
"克维库",
"兰卡亚",
"兰维达",
"兰萨提",
"兰齐塔",
"兴奋的「回声之子」战士",
"冰冷的身躯",
"冷静的「回声之子」战士",
"凯塔",
"凯安",
"出魂试炼之所的留言",
"切妮",
"列扎诺夫",
"利别科",
"利洛",
"加勒弗大汪",
"加塔力",
"加杰雷",
"加纳尔",
"努乌",
"努斯妲",
"勇敢的匿叶龙",
"勇猛的嵴锋龙",
"勒拉",
"匿叶龙",
"南娜",
"卡乌帕",
"卡乌胡",
"卡乌鲁",
"卡伦雅",
"卡克斯",
"卡克斯的行装",
"卡兹加",
"卡力弗",
"卡卡妈妈",
"卡嘉",
"卡图马",
"卡安",
"卡帕可",
"卡拉穆鲁",
"卡纳鲁亚",
"卡胡那",
"卡胡鲁",
"卡马克",
"卡马加",
"卡齐娜",
"受困的匿叶龙",
"受困的嵴锋龙",
"古塞尼科夫",
"古寻梦祭司的记录·其之一",
"古寻梦祭司的记录·其之三",
"古寻梦祭司的记录·其之二",
"古寻梦祭司的记录·其之四",
"古瑟雷德",
"古老的布告",
"古老的日记",
"古老的碑刻",
"古雷马",
"叶莱菲",
"吉恩布",
"向下看",
"呆呆的小嵴锋龙",
"呆呆的绵驮兽",
"呼噜克",
"哈卡乌",
"哈蒂丝",
"哈隆加",
"唤灵师的手记·其一",
"唤灵师的手记·其二",
"商队成员",
"嗜岩·兽境幼兽",
"嘉乌兰妮",
"因卡纳克",
"因娜",
"团雀01",
"团雀02",
"团雀03",
"困倦的绒翼龙",
"图尼娜",
"图帕克",
"图蒂坦",
"图蕾娅",
"图达玛",
"圣王的手记·其一",
"圣王的手记·其七",
"圣王的手记·其三",
"圣王的手记·其九",
"圣王的手记·其二",
"圣王的手记·其五",
"圣王的手记·其八",
"圣王的手记·其六",
"圣王的手记·其四",
"坎内克",
"埃文苏",
"基尼奇",
"基斯庇",
"基班古",
"基维拉",
"基耶霍",
"塔力帕",
"塔卢加",
"塔尔科",
"塔恩加",
"塔洛娜",
"塔穆因",
"塔莫蕾",
"塔诺",
"塞奇托",
"塞巴尔",
"夏安卡",
"夏拉帕",
"夏温",
"夏芙米娅",
"夏萝·努伊",
"多巴",
"夜猫子",
"夜神",
"夜魂之灵",
"大家伙?",
"大胆的调查员",
"夸恩因",
"夸恩因的日记",
"夸梅",
"奇卡",
"奇怪的匿叶龙",
"奇普",
"奇梅",
"奇玛",
"奇科娅",
"奇马利",
"奈赫西",
"奎兹",
"奎泰克",
"奎皮亚",
"奥伯龙",
"奥坎比",
"奥奇坎",
"奥奇坎的残躯",
"奥娅",
"奥尔科",
"奥希娜",
"奥杜力",
"奥科兰",
"奥罗卢柯",
"奥西",
"奥贡",
"好奇的调查员",
"妮乌",
"妮佩卡",
"妮赫佳",
"威严的低语",
"娅特兰",
"娜恩希",
"娜玛卡",
"子澄",
"字迹模糊的笔记",
"孟尼力克",
"安切塔",
"安萨鲁",
"安蒂妮",
"家长般的大嵴锋龙",
"容韦勒",
"对话群演",
"小孩的笔记",
"小家伙?",
"小小蜜虫",
"尤季娜",
"尤庇娅",
"尤考姆",
"尼南",
"尼尼",
"尼赞贝",
"山王",
"嵴锋龙",
"嵴锋龙DJ",
"嵴锋龙斗舞女1",
"嵴锋龙斗舞女2",
"嵴锋龙斗舞男1",
"嵴锋龙斗舞男2",
"巡山客的手记",
"工匠的笔记·其一",
"工匠的笔记·其二",
"巴亚吉达",
"巴克",
"巴加约",
"巴哈蒂",
"巴拉诺夫",
"巴茨",
"布基纳",
"布尔莎",
"布纳马",
"布鲁",
"希乌休",
"希亚赫",
"希伊亚",
"希巴拉克",
"希库埃鲁",
"希皮利",
"希诺宁",
"帕兰",
"帕加尔",
"帕卡·努伊",
"帕尼娅",
"帕恰",
"帕朗",
"帕莉西娅",
"帕贾丹",
"年轻的行商",
"年长的行商",
"幻写灵",
"幼光",
"幼小的匿叶龙",
"幼嵴锋龙",
"幼年的暝视龙",
"庇兰",
"库伊米",
"库基亚",
"库娅",
"库希马纳",
"库延",
"库拉霍",
"库斯可",
"库特比",
"库珀·努伊",
"库约尼",
"库纳克",
"库西",
"库阿勒",
"库马约",
"庞塞",
"废弃-奇玛",
"废弃-希乌休",
"废弃-曼扎那",
"废弃-森塔加",
"废弃-阿乌伊娅",
"废弃-马察特利",
"延古",
"延塔莎",
"延索",
"待物3带背包",
"待物3带背包 深肤色",
"德乌特",
"德乌特(灵)",
"忧愁的绒翼龙",
"怪物2带背包",
"怪物2带背包 深肤色",
"怪物带背包",
"怪物带背包 深肤色",
"怯生生的小匿叶龙",
"恩加韦",
"恩古迪",
"恩孔加",
"恩托提亚",
"恩琳",
"恰斯卡",
"悠然的「花羽会」战士",
"愤怒的贩龙者",
"懒懒的鳍游龙",
"戈利科夫",
"战场情报",
"扎安娅",
"托奥",
"托尔特克",
"托托",
"托扬娜",
"托泰克",
"托赞",
"托赫兰妮",
"拉坎阿",
"拉密萨纳",
"拉斯塔恩",
"拉曼",
"拉比娜",
"拉马奈",
"挑战起点",
"振尘",
"提佐科",
"提凯伊",
"提帕诺",
"提莉乌娅",
"搭建帐篷",
"摩亚瓦",
"放置「古名」",
"斯塔杜欣",
"斯普赫",
"无名工匠的笔记",
"无名旅人的笔记·其一",
"无名旅人的笔记·其三",
"无名旅人的笔记·其二",
"无名旅人的笔记·其五",
"无名旅人的笔记·其四",
"无名祭司的笔记",
"昆纳乌",
"晕倒的匿叶龙",
"晕倒的鳍游龙",
"普玛",
"普玛莉",
"暝视龙",
"暴躁的部族战士",
"更换衣服",
"曼尤雅",
"曼扎那",
"曼科",
"曼萨",
"最佳飞行成绩记录",
"朗戈",
"木箱",
"未完成的乐稿",
"朱南",
"机灵的小嵴锋龙",
"来自过去的声音",
"松伽塔",
"某人留下的铭记·其一",
"某人留下的铭记·其三",
"某人留下的铭记·其二",
"某人留下的铭记·其五",
"某人留下的铭记·其四",
"某人遗落的风镜",
"柯奇妲",
"柯娅",
"柯林伍德",
"柯梯米",
"树上的小嵴锋龙",
"栖木普",
"格罗贝尔",
"格茜妮",
"格里斯潘",
"桑哈杰",
"桑科约克",
"梅兹莉",
"梅内娅",
"梅莎",
"梅西娜",
"森塔加",
"森珀娅",
"樋口铁矢",
"欣赏景色",
"欧洛伦",
"欧莎薇",
"残破的石碑",
"比于什",
"比奇津",
"比赛公告板",
"比赛选手",
"毛球",
"水豚",
"汉佩克",
"汉扎",
"沃蕾",
"波卡",
"波吉吉",
"波奇奇",
"波尼尼",
"波蒂莉",
"波蒂薇",
"泽伊拉",
"洛娅",
"活泼的绵驮兽",
"活跃的小嵴锋龙",
"海兹尔",
"海岳",
"涅兰",
"涅提",
"游学者的笔记",
"潘帕",
"灵体真女儿",
"爱可",
"爱梅拉",
"爱维莉",
"爱菲拉",
"爱雅",
"特佐佐",
"特佩潘",
"特帕切",
"特帕尔",
"特拉佐莉",
"特拉佐莉(表演用克隆人)",
"特拉帕尔",
"特拉忒",
"特拉波",
"特拉科",
"特沃德罗斯",
"特波兹",
"特立尼达",
"特纳华",
"特蒂赫莉",
"特诺切",
"特阿墨",
"特阿尤",
"特马乔",
"狄雷",
"献上供物",
"玛亚薇",
"玛伊蕾",
"玛兹嘉",
"玛拉妮",
"玛薇卡",
"玻娜",
"琪丝佩",
"琪希可",
"瓦伊妲",
"瓦伊纳",
"瓦兰卡",
"瓦凯·努伊",
"瓦卡尔",
"瓦图妲",
"瓦尔米",
"瓦托娅",
"瓦斯卡尔",
"瓦曼",
"瓦蕾",
"瓦达娜",
"界碑上的刻文",
"疑惑的调查员",
"疲惫的暝视龙",
"白浜",
"皮尔钦",
"皮希加",
"皮萨克",
"看向仪式台",
"研究中心紧急机械操作手册",
"磨损的记录",
"秋纽奥",
"科优尔",
"科奥劳",
"科奴拉芙",
"科帕",
"科斯特利茨基",
"科潘",
"科科庞",
"科米娜",
"科约帕",
"科莫奎",
"秘源哨机",
"穆伊萨",
"穆基",
"穆尔科",
"穆托塔",
"穆纳伊",
"穆蒲",
"竖立在旁的木牌",
"等待…",
"米卢·努伊",
"米奎克",
"米特尔",
"米齐卡",
"索尔涅夫",
"索莉马娜",
"约洛特莉",
"练习钻地的小嵴锋龙",
"细心的匿叶龙",
"绒翼龙",
"绒翼龙幼龙",
"维兰德",
"维图索夫",
"维护记录·其一",
"维护记录·其三",
"维护记录·其二",
"维查玛",
"维莎",
"羊驼",
"群演1",
"老鼠",
"耶里门",
"胆小的绵驮兽",
"胡妮",
"胡里约",
"自称「山下」之物",
"艾库瓦",
"苏娅",
"苏玛克",
"若娜瓦",
"茜特菈莉",
"荆和",
"莉乌娅",
"莉洛娅",
"莉琉",
"莉瓦",
"莉莉尤",
"莎乌莎",
"莎娜",
"莎维娅",
"莎迪蕾",
"莫乌",
"菲欣妮",
"菲耶蒂娜",
"萨加图拉",
"萨卡乌",
"萨科巴",
"萨约尔",
"萨费伊",
"葵可",
"葵莉娅",
"蒂亚戈",
"蒂图",
"蒂尔妲",
"蒂索克",
"蓬普",
"薇尔恰",
"虚弱的声音",
"虚弱的大灵显化身",
"虚弱的绒翼龙",
"虚弱的膨膨兽",
"被困的匿叶龙",
"被困的嵴锋龙",
"被困的幼暝视龙",
"被救出的匿叶龙",
"被救的鳍游龙",
"装饰花车",
"西坎",
"西布",
"西帕克",
"西蒂娜",
"西薇",
"观察护身符",
"观察武器",
"观察罐子",
"观察腰带",
"观察钓具",
"警示者的记录",
"记录用秘源哨机",
"谁人的手记",
"调查用投喂点",
"谜画涂鸦中的意志",
"谨慎的调查员",
"贝坎",
"贝雷哈努",
"贤龙",
"贪吃的绵驮兽",
"赫伯德",
"赫瓦特莉",
"辛佳",
"辛奇",
"达伊妲",
"达尔戈",
"达布亚",
"达祖玛",
"进行比赛",
"迷惑的调查员",
"迷灰中的石碑·其一",
"迷灰中的石碑·其三",
"迷灰中的石碑·其二",
"通皮斯",
"醒目的标语",
"钦特利",
"闪亮亮的贝壳",
"阿乌伊娅",
"阿乌琪",
"阿乔",
"阿伽娅",
"阿凯蒂",
"阿卡坦加",
"阿卡马",
"阿图科",
"阿坎蒂",
"阿基约",
"阿奇亚库",
"阿妮拉",
"阿姆鲁",
"阿孔",
"阿尔妲",
"阿尔帕",
"阿尤",
"阿布帕隆",
"阿希莉",
"阿斯基娅",
"阿斯麦隆",
"阿格莫",
"阿梅妲",
"阿特琪",
"阿科米蒂",
"阿米娜",
"阿纳",
"阿蕾梅",
"阿达玛",
"阿邦迪",
"阿隆",
"阿霍伊图",
"阿马佐利",
"阿鲁吉",
"陀罗诘利",
"陀达罗",
"难过的嵴锋龙",
"雅库普",
"雅蕾希",
"雅诺斯基",
"雇主",
"雷格巴",
"霍图鲁",
"霍娅",
"霍莱",
"韦尼埃米诺夫",
"顾客",
"马伊塔",
"马兹拉",
"马凯莫",
"马努阿",
"马塔伽",
"马塔伽!记得!!",
"马塔拉",
"马察特利",
"马尼菲科",
"马扎坦",
"马提库伊",
"马洛考",
"马特兰",
"马穆勒",
"马蒂亚斯",
"马西娜·努伊",
"马陶霍",
"驻扎日记",
"验收与维修记录",
"鳍游龙",
"鳍游龙夏威夷吉他",
"鳍游龙尤克里里",
"鳍游龙木吉他",
"鳍游龙箱鼓",
"麦斯欧德",
"黛希特莉",
"龙铭刻",
"(翻找箱子…)",
"亡国的美奈姬·卷五",
"少女薇拉的忧郁·卷一",
"少女薇拉的忧郁·卷二",
File diff suppressed because it is too large. Load diff
@@ -1,21 +0,0 @@
# 启动参数说明
启动参数本质是 Unity 独立平台播放器命令行参数 ,测试下来有用的参数大概如下:
- `-window-mode exclusive` 参数
- **独占全屏**,即选择游戏进程以独占全屏模式运行
- **该功能与游戏内浏览器功能不兼容,你应仅在能独立描述独占全屏的技术原理和效果的情况下开启本项**
- `-screen-fullscreen` 参数
- **全屏**,即选择启动游戏后的游戏界面是否设置为全屏
- `-popupwindow` 参数
- **无边框**,即选择启动游戏后的游戏界面是否设置为无边框窗口
- `-platform_type CLOUD_THIRD_PARTY_MOBILE` 参数
- **触摸屏模式**,即启用原神内置的触摸屏操作模式(键鼠输入将被忽略)
- 分辨率
- 该功能可以快速设置下方的覆盖屏幕宽度和高度选项,有一些常见的预设项可供选择
- `-screen-width` 参数
- **宽度**,即选择启动游戏后的游戏界面的宽度,例如 `1920`
- `-screen-height` 参数
- **高度**,即选择启动游戏后的游戏界面的高度,例如 `1080`
- `-monitor` 参数
- **显示器**,允许多显示器用户选择指定的显示器来运行游戏
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

@@ -1,148 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<LangVersion>12.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.36.2</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<None Remove="Assets\Images\*.jpg" />
<None Remove="Assets\Images\*" />
<None Remove="Assets\Images\*.png" />
<None Remove="Assets\Images\*.ico" />
<None Remove="Assets\Fonts\*.ttf" />
<None Remove="Assets\Highlighting\*.xshd" />
<None Remove="Assets\Strings\*.html" />
<None Remove="Assets\Strings\*.md" />
<None Remove="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\Images\*.jpg" />
<Resource Include="Assets\Images\Anniversary\*" />
<Resource Include="Assets\Images\*.png" />
<Resource Include="Assets\Images\*.ico" />
<Resource Include="Assets\Fonts\*.ttf" />
<Resource Include="Assets\Highlighting\*.xshd" />
<Resource Include="Assets\Strings\*.html" />
<Resource Include="Assets\Strings\*.md" />
<Resource Include="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.18.1" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.18.1" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.8.0.20230708" />
<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.122" />
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
<PackageReference Include="Sdcb.PaddleOCR.Models.Online" Version="2.7.0.1" />
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<PackageReference Include="System.IO.Hashing" Version="8.0.0" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.23" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Fischless.GameCapture\Fischless.GameCapture.csproj" />
<ProjectReference Include="..\Fischless.HotkeyCapture\Fischless.HotkeyCapture.csproj" />
<ProjectReference Include="..\Fischless.WindowsInput\Fischless.WindowsInput.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Assets\Map\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\Model\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoFight\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoGeniusInvokation\Assets\tcg_character_card.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoPick\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoSkip\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoSkip\Assets\hangout.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoTrackPath\Assets\tp.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\Common\Element\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoWood\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\GameLoading\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\QuickTeleport\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\QuickSereniteaPot\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="GameTask\Common\Element\Assets\新文件夹\" />
<Folder Include="GameTask\OneDragon\" />
<Folder Include="User\AutoPathing\" />
</ItemGroup>
</Project>
+37 -26
View File
@@ -5,38 +5,30 @@
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<UseWindowsForms>True</UseWindowsForms>
<LangVersion>12.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<ApplicationIcon>Assets\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.38.0</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<None Remove="Assets\Images\*.jpg" />
<None Remove="Assets\Images\*" />
<None Remove="Assets\Images\*.png" />
<None Remove="Assets\Images\*.ico" />
<None Remove="Assets\*.jpg" />
<None Remove="Assets\*.png" />
<None Remove="Assets\*.ico" />
<None Remove="Assets\Fonts\*.ttf" />
<None Remove="Assets\Highlighting\*.xshd" />
<None Remove="Assets\Strings\*.html" />
<None Remove="Assets\Strings\*.md" />
<None Remove="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\Images\*.jpg" />
<Resource Include="Assets\Images\Anniversary\*" />
<Resource Include="Assets\Images\*.png" />
<Resource Include="Assets\Images\*.ico" />
<Resource Include="Assets\*.jpg" />
<Resource Include="Assets\*.png" />
<Resource Include="Assets\*.ico" />
<Resource Include="Assets\Fonts\*.ttf" />
<Resource Include="Assets\Highlighting\*.xshd" />
<Resource Include="Assets\Strings\*.html" />
<Resource Include="Assets\Strings\*.md" />
<Resource Include="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
@@ -49,34 +41,31 @@
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.18.1" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.8.0.20230708" />
<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.122" />
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="PresentMonFps" Version="2.0.1" />
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
<PackageReference Include="Sdcb.PaddleOCR.Models.Online" Version="2.7.0.1" />
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<PackageReference Include="System.IO.Hashing" Version="8.0.0" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.23" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
</ItemGroup>
<ItemGroup>
@@ -85,6 +74,27 @@
<ProjectReference Include="..\Fischless.WindowsInput\Fischless.WindowsInput.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="GameTask\TaskContext.cs">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Compile>
<Compile Update="View\MaskWindow.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Pages\HotkeyPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Pages\TriggerSettingsPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\PickerWindow.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="View\Windows\MapViewer.xaml.cs">
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="Assets\Map\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@@ -122,9 +132,6 @@
<None Update="GameTask\Common\Element\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\Common\Element\Assets\Json\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoWood\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -140,11 +147,15 @@
<None Update="User\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Script\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="GameTask\OneDragon\" />
<Folder Include="User\AutoPathing\" />
<Folder Include="GameTask\Common\Element\Assets\MapPoint\" />
<Folder Include="Script\AutoCrystalfly\" />
<Folder Include="View\Controls\WpfUi\" />
</ItemGroup>
</Project>
+2 -32
View File
@@ -12,10 +12,8 @@ using BetterGenshinImpact.Service.Notification;
using CommunityToolkit.Mvvm.ComponentModel;
using Fischless.GameCapture;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Config;
@@ -57,27 +55,12 @@ public partial class AllConfig : ObservableObject
[ObservableProperty]
private bool _wgcUseBitmapCache = true;
/// <summary>
/// 自动修复Win11下BitBlt截图方式不可用的问题
/// </summary>
[ObservableProperty]
private bool _autoFixWin11BitBlt = true;
/// <summary>
/// 推理使用的设备
/// </summary>
[ObservableProperty]
private string _inferenceDevice = "CPU";
[ObservableProperty]
private List<ValueTuple<string, int, string, string>> _nextScheduledTask = [];
/// <summary>
/// 一条龙选中使用的配置
/// </summary>
[ObservableProperty]
private string _selectedOneDragonFlowConfigName = string.Empty;
/// <summary>
/// 遮罩窗口配置
/// </summary>
@@ -139,22 +122,12 @@ public partial class AllConfig : ObservableObject
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 宏配置
/// 脚本类配置
/// </summary>
public MacroConfig MacroConfig { get; set; } = new();
public RecordConfig RecordConfig { get; set; } = new();
/// <summary>
/// 脚本配置
/// </summary>
public ScriptConfig ScriptConfig { get; set; } = new();
/// <summary>
/// 路径追踪配置
/// </summary>
public PathingConditionConfig PathingConditionConfig { get; set; } = PathingConditionConfig.Default;
/// <summary>
/// 快捷键配置
/// </summary>
@@ -187,9 +160,6 @@ public partial class AllConfig : ObservableObject
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -202,4 +172,4 @@ public partial class AllConfig : ObservableObject
{
NotificationService.Instance().RefreshNotifiers();
}
}
}
@@ -9,11 +9,11 @@ namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class GenshinStartConfig : ObservableObject
{
// /// <summary>
// /// 自动点击月卡
// /// </summary>
// [ObservableProperty]
// private bool _autoClickBlessingOfTheWelkinMoonEnabled;
/// <summary>
/// 自动点击月卡
/// </summary>
[ObservableProperty]
private bool _autoClickBlessingOfTheWelkinMoonEnabled;
/// <summary>
/// 自动进入游戏(开门)
+7 -15
View File
@@ -1,27 +1,14 @@
using System;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Core.Config;
public class Global
{
public static string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version!.ToString(3);
public static string Version { get; } = "0.32.5";
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
public static readonly JsonSerializerOptions ManifestJsonOptions = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
WriteIndented = true,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};
public static string Absolute(string relativePath)
{
return Path.Combine(StartUpPath, relativePath);
@@ -29,7 +16,12 @@ public class Global
public static string ScriptPath()
{
return Absolute("User\\JsScript");
return Absolute("Script");
}
public static string ScriptPath(string folderName)
{
return Path.Combine(Absolute("Script"), folderName);
}
public static string? ReadAllTextIfExist(string relativePath)
@@ -170,34 +170,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _test2HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径记录开始
[ObservableProperty]
private string _recBigMapPosHotkey = "";
[ObservableProperty]
private string _recBigMapPosHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径记录开始
[ObservableProperty]
private string _pathRecorderHotkey = "";
[ObservableProperty]
private string _pathRecorderHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 添加路径记录点
[ObservableProperty]
private string _addWaypointHotkey = "";
[ObservableProperty]
private string _addWaypointHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径执行
[ObservableProperty]
private string _executePathHotkey = "";
[ObservableProperty]
private string _executePathHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 日志与状态窗口展示
[ObservableProperty]
private string _logBoxDisplayHotkey = "";
@@ -211,12 +183,7 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _keyMouseMacroRecordHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 暂停
[ObservableProperty]
private string _suspendHotkey = "";
[ObservableProperty]
private string _suspendHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 停止任意独立任务
[ObservableProperty]
private string _cancelTaskHotkey = "";
@@ -1,89 +0,0 @@
using System;
using System.Collections.Generic;
using CommunityToolkit.Mvvm.ComponentModel;
namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class OneDragonFlowConfig : ObservableObject
{
// 配置名
[ObservableProperty]
private string _name = string.Empty;
/// <summary>
/// 所有任务的开关状态
/// </summary>
public Dictionary<string, bool> TaskEnabledList { get; set; } = new();
// 合成树脂的国家
[ObservableProperty]
private string _craftingBenchCountry = "枫丹";
// 冒险者协会的国家
[ObservableProperty]
private string _adventurersGuildCountry = "枫丹";
// 自动战斗配置的队伍名称
[ObservableProperty]
private string _partyName = string.Empty;
// 自动战斗配置的策略名称
[ObservableProperty]
private string _domainName = string.Empty;
[ObservableProperty]
private bool _weeklyDomainEnabled = false;
#region 每周秘境配置
[ObservableProperty]
private string _mondayThursdayPartyName = string.Empty;
[ObservableProperty]
private string _mondayThursdayDomainName = string.Empty;
[ObservableProperty]
private string _tuesdayFridayPartyName = string.Empty;
[ObservableProperty]
private string _tuesdayFridayDomainName = string.Empty;
[ObservableProperty]
private string _wednesdaySaturdayPartyName = string.Empty;
[ObservableProperty]
private string _wednesdaySaturdayDomainName = string.Empty;
[ObservableProperty]
private string _sundayPartyName = string.Empty;
[ObservableProperty]
private string _sundayDomainName = string.Empty;
// 通过当天是哪一天来返回配置
public (string partyName, string domainName) GetDomainConfig()
{
if (WeeklyDomainEnabled)
{
var dayOfWeek = DateTime.Now.DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => (MondayThursdayPartyName, MondayThursdayDomainName),
DayOfWeek.Tuesday => (TuesdayFridayPartyName, TuesdayFridayDomainName),
DayOfWeek.Wednesday => (WednesdaySaturdayPartyName, WednesdaySaturdayDomainName),
DayOfWeek.Thursday => (MondayThursdayPartyName, MondayThursdayDomainName),
DayOfWeek.Friday => (TuesdayFridayPartyName, TuesdayFridayDomainName),
DayOfWeek.Saturday => (WednesdaySaturdayPartyName, WednesdaySaturdayDomainName),
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName),
_ => (PartyName, DomainName)
};
}
else
{
return (PartyName, DomainName);
}
}
#endregion
}
@@ -1,185 +0,0 @@
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class PathingConditionConfig : ObservableObject
{
// 路径追踪条件配置
[ObservableProperty]
private ObservableCollection<Condition> _partyConditions = [];
[ObservableProperty]
private ObservableCollection<Condition> _avatarConditions = [];
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 使用小道具的间隔时间(ms)
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
public static PathingConditionConfig Default => new()
{
AvatarConditions =
[
new Condition
{
Subject = "队伍中角色",
Object = ["绮良良", "莱依拉", "芭芭拉", "七七"],
Result = "循环短E"
},
new Condition
{
Subject = "队伍中角色",
Object = ["钟离"],
Result = "循环长E"
}
]
};
/// <summary>
/// 找出当前应该切换的队伍名称
/// </summary>
/// <param name="materialName">采集物名称</param>
/// <param name="specialActions">特殊动作</param>
/// <returns></returns>
public string? FilterPartyName(string? materialName, List<string?> specialActions)
{
if (specialActions is { Count: > 0 })
{
// 特殊动作匹配队伍名
foreach (var action in specialActions)
{
if (string.IsNullOrEmpty(action))
{
continue;
}
if (!ConditionDefinitions.ActionCnDic.TryGetValue(action, out var actionCn))
{
continue; // 不校验
}
var condition = PartyConditions.FirstOrDefault(c => c.Subject == "动作" && c.Object.Contains(actionCn));
if (condition is { Result: not null })
{
return condition.Result;
}
}
}
// 采集物匹配队伍名
Condition? materialCondition = null;
if (!string.IsNullOrEmpty(materialName))
{
materialCondition = PartyConditions.FirstOrDefault(c => c.Subject == "采集物" && c.Object.Contains(materialName));
}
if (materialCondition is { Result: not null })
{
return materialCondition.Result;
}
else
{
materialCondition = PartyConditions.FirstOrDefault(c => c.Subject == "采集物" && c.Object.Contains("全部"));
if (materialCondition is { Result: not null })
{
return materialCondition.Result;
}
}
return null;
}
/// <summary>
/// 通过条件配置生成队伍配置
/// </summary>
/// <returns></returns>
public PathingPartyConfig BuildPartyConfigByCondition(CombatScenes combatScenes)
{
PathingPartyConfig partyConfig = PathingPartyConfig.BuildDefault();
// 使用最优先匹配上的条件
foreach (var avatarCondition in AvatarConditions)
{
if (avatarCondition.Result == "循环短E" || avatarCondition.Result == "循环长E")
{
foreach (var avatar in combatScenes.Avatars)
{
if (avatarCondition is { Object: not null } && avatarCondition.Object.Contains(avatar.Name))
{
partyConfig.GuardianAvatarIndex = avatar.Index.ToString();
if (avatarCondition.Result == "循环长E")
{
partyConfig.GuardianElementalSkillLongPress = true;
partyConfig.GuardianElementalSkillSecondInterval = avatar.SkillHoldCd.ToString(CultureInfo.CurrentCulture);
}
else
{
partyConfig.GuardianElementalSkillLongPress = false;
partyConfig.GuardianElementalSkillSecondInterval = avatar.SkillCd.ToString(CultureInfo.CurrentCulture);
}
break;
}
}
if (!string.IsNullOrEmpty(partyConfig.GuardianAvatarIndex))
{
break;
}
}
}
foreach (var avatarCondition in AvatarConditions)
{
if (avatarCondition.Result == "作为主要行走角色")
{
foreach (var avatar in combatScenes.Avatars)
{
if (avatarCondition is { Object: not null } && avatarCondition.Object.Contains(avatar.Name))
{
partyConfig.MainAvatarIndex = avatar.Index.ToString();
break;
}
}
if (!string.IsNullOrEmpty(partyConfig.MainAvatarIndex))
{
break;
}
}
}
// 默认元素力采集角色
// var elementalCollectAvatars = ElementalCollectAvatarConfigs.Lists;
// foreach (var avatar in combatScenes.Avatars)
// {
// var elementalCollectAvatar = elementalCollectAvatars.FirstOrDefault(x => x.Name == avatar.Name);
// if (elementalCollectAvatar != null)
// {
// if (elementalCollectAvatar.ElementalType == ElementalType.Hydro)
// {
// partyConfig.HydroCollectAvatarIndex = avatar.Index.ToString();
// }
// else if (elementalCollectAvatar.ElementalType == ElementalType.Electro)
// {
// partyConfig.ElectroCollectAvatarIndex = avatar.Index.ToString();
// }
// else if (elementalCollectAvatar.ElementalType == ElementalType.Anemo)
// {
// partyConfig.AnemoCollectAvatarIndex = avatar.Index.ToString();
// }
// }
// }
return partyConfig;
}
}
@@ -1,89 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoFight;
namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class PathingPartyConfig : ObservableObject
{
// 配置是否启用,不启用会使用路径追踪内的条件配置
[ObservableProperty]
private bool _enabled = false;
// 切换到队伍的名称
[ObservableProperty]
private string _partyName = string.Empty;
// 主要行走追踪的角色编号
[ObservableProperty]
private string _mainAvatarIndex = string.Empty;
// [盾角]使用元素战技的角色编号
[ObservableProperty]
private string _guardianAvatarIndex = string.Empty;
// [盾角]使用元素战技的时间间隔(s)
[ObservableProperty]
private string _guardianElementalSkillSecondInterval = string.Empty;
// [盾角]使用元素战技的方式 长按/短按
[ObservableProperty]
private bool _guardianElementalSkillLongPress = false;
// // normal_attack 配置几号位
// [ObservableProperty]
// private string _normalAttackAvatarIndex = string.Empty;
//
// // elemental_skill 配置几号位
// [ObservableProperty]
// private string _elementalSkillAvatarIndex = string.Empty;
// // hydro_collect 配置几号位
// [ObservableProperty]
// private string _hydroCollectAvatarIndex = string.Empty;
//
// // electro_collect 配置几号位
// [ObservableProperty]
// private string _electroCollectAvatarIndex = string.Empty;
//
// // anemo_collect 配置几号位
// [ObservableProperty]
// private string _anemoCollectAvatarIndex = string.Empty;
[JsonIgnore]
public List<string> AvatarIndexList { get; } = ["", "1", "2", "3", "4"];
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 使用小道具的间隔时间
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
// 启用进入剧情自动脱离
[ObservableProperty]
private bool _autoSkipEnabled = true;
//启用自动战斗配置
[ObservableProperty]
private bool _autoFightEabled = false;
[ObservableProperty]
private AutoFightConfig _autoFightConfig = new();
public static PathingPartyConfig BuildDefault()
{
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
var pathingConditionConfig = TaskContext.Instance().Config.PathingConditionConfig;
return new PathingPartyConfig
{
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs
};
}
}
@@ -1,28 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Config;
/// <summary>
/// 脚本配置
/// </summary>
[Serializable]
public partial class ScriptConfig : ObservableObject
{
// 自动更新脚本仓库周期(天)
[ObservableProperty]
private int _autoUpdateScriptRepoPeriod = 1;
// 上次更新脚本仓库时间
[ObservableProperty]
private DateTime _lastUpdateScriptRepoTime = DateTime.MinValue;
// 脚本仓库按钮红点是否展示
[ObservableProperty]
private bool _scriptRepoHintDotVisible = false;
// 已订阅的脚本路径列表
[ObservableProperty]
private List<string> _subscribedScriptPaths = [];
}
@@ -3,7 +3,6 @@ using SharpDX.DirectInput;
using System;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Monitor;
@@ -12,8 +11,6 @@ public class DirectInputMonitor : IDisposable
private bool _isRunning = true;
private readonly Mouse _mouse;
public static int Interval = 5;
public DirectInputMonitor()
{
@@ -37,8 +34,8 @@ public class DirectInputMonitor : IDisposable
_mouse.Acquire();
MouseState state = _mouse.GetCurrentState();
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state, Kernel32.GetTickCount());
Thread.Sleep(Interval); // 10ms, equivalent to CLOCKS_PER_SEC/100
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state);
Thread.Sleep(5); // 10ms, equivalent to CLOCKS_PER_SEC/100
}
});
}
@@ -46,7 +46,6 @@ public class MouseKeyMonitor
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
_globalHook.MouseUpExt += GlobalHookMouseUpExt;
_globalHook.MouseMoveExt += GlobalHookMouseMoveExt;
_globalHook.MouseWheelExt += GlobalHookMouseWheelExt;
//_globalHook.KeyPress += GlobalHookKeyPress;
_firstSpaceKeyDownTime = DateTime.MaxValue;
@@ -62,7 +61,7 @@ public class MouseKeyMonitor
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e);
// 热键按下事件
HotKeyDown(sender, e);
@@ -100,7 +99,7 @@ public class MouseKeyMonitor
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, Kernel32.GetTickCount());
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e);
// 热键松开事件
HotKeyUp(sender, e);
@@ -167,12 +166,6 @@ public class MouseKeyMonitor
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e);
}
private void GlobalHookMouseWheelExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e);
}
public void Unsubscribe()
{
@@ -183,7 +176,6 @@ public class MouseKeyMonitor
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
_globalHook.MouseUpExt -= GlobalHookMouseUpExt;
_globalHook.MouseMoveExt -= GlobalHookMouseMoveExt;
_globalHook.MouseWheelExt -= GlobalHookMouseWheelExt;
//_globalHook.KeyPress -= GlobalHookKeyPress;
_globalHook.Dispose();
}
@@ -23,7 +23,7 @@ public class PaddleOcrService : IOcrService
public PaddleOcrService()
{
var path = Global.Absolute(@"Assets\Model\PaddleOcr");
var path = Global.Absolute("Assets\\Model\\PaddleOcr");
var localDetModel = DetectionModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_det"), ModelVersion.V4);
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);
@@ -1,66 +0,0 @@
using System;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Model.Area;
using Compunet.YoloV8;
using OpenCvSharp;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.View.Drawable;
namespace BetterGenshinImpact.Core.Recognition.ONNX;
public class BgiYoloV8Predictor(string modelRelativePath) : IDisposable
{
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(modelRelativePath))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
public YoloV8Predictor Predictor => _predictor;
/// <summary>
/// 检测
/// </summary>
/// <param name="region">图像</param>
/// <returns>类别-矩形框</returns>
public Dictionary<string, List<Rect>> Detect(ImageRegion region)
{
using var memoryStream = new MemoryStream();
region.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
var result = _predictor.Detect(memoryStream);
var dict = new Dictionary<string, List<Rect>>();
foreach (var box in result.Boxes)
{
if (!dict.ContainsKey(box.Class.Name))
{
dict[box.Class.Name] = [new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height)];
}
else
{
dict[box.Class.Name].Add(new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height));
}
}
Debug.WriteLine("YOLOv8识别结果:" + JsonSerializer.Serialize(dict));
var list = new List<RectDrawable>();
foreach (var box in result.Boxes)
{
var rect = new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
list.Add(region.ToRectDrawable(rect, modelRelativePath));
}
VisionContext.Instance().DrawContent.PutOrRemoveRectList(modelRelativePath, list);
return dict;
}
public void Dispose()
{
_predictor.Dispose();
}
}
@@ -1,18 +0,0 @@
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Recognition.ONNX;
public class BgiYoloV8PredictorFactory
{
static Dictionary<string, BgiYoloV8Predictor> _predictors = new();
public static BgiYoloV8Predictor GetPredictor(string modelRelativePath)
{
if (!_predictors.ContainsKey(modelRelativePath))
{
_predictors[modelRelativePath] = new BgiYoloV8Predictor(modelRelativePath);
}
return _predictors[modelRelativePath];
}
}
@@ -23,12 +23,12 @@ public class PickTextInference : ITextInference
public PickTextInference()
{
var modelPath = Global.Absolute(@"Assets\Model\Yap\model_training.onnx");
var modelPath = Global.Absolute("Assets\\Model\\Yap\\model_training.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("Yap模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, BgiSessionOption.Instance.Options);
var wordJsonPath = Global.Absolute(@"Assets\Model\Yap\index_2_word.json");
var wordJsonPath = Global.Absolute("Assets\\Model\\Yap\\index_2_word.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -15,12 +15,12 @@ public class Predictor
public Predictor()
{
var options = new SessionOptions();
var modelPath = Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx");
var modelPath = Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("自动钓鱼模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, options);
var wordJsonPath = Global.Absolute(@"Assets\Model\Fish\label.json");
var wordJsonPath = Global.Absolute("Assets\\Model\\Fish\\label.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("自动钓鱼模型分类文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -1,31 +0,0 @@
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
/// <summary>
/// FlannMatch
/// 优点:
/// 1. 速度快:FlannMatch 使用的是近似最近邻搜索算法,适合处理大规模数据集,速度比暴力匹配器快得多。
/// 2. 可扩展性好:适用于高维特征空间,能够处理大量特征点。
/// 缺点:
/// 1. 精度较低:由于是近似搜索,匹配的精度可能不如暴力匹配器高。
/// 2. 复杂性高:需要对参数进行调优,以获得最佳性能。
/// BfMatch
/// 优点:
/// 1. 精度高:BfMatch 进行的是精确匹配,能够找到最优的匹配对。
/// 2. 简单易用:不需要复杂的参数调优,适合初学者和简单应用。
/// 缺点:
/// 1. 速度慢:对于大规模数据集,暴力匹配器的速度较慢,因为它需要计算所有特征点之间的距离。
/// 2. 不适合高维数据:在高维特征空间中,计算量会显著增加,性能下降明显。
/// 选择建议
/// • 大规模数据集:如果你需要处理大量特征点,且对速度要求较高,FlannMatch 是一个更好的选择。
/// • 高精度要求:如果你的应用对匹配精度要求很高,且数据规模较小,BfMatch 会更合适。
/// </summary>
public enum DescriptorMatcherType
{
// 快速近似最近邻搜索库
BruteForce,
// 暴力匹配器
FlannBased
// 更多类型命名见 DescriptorMatcher.Create
}
@@ -7,21 +7,15 @@ using OpenCvSharp.XFeatures2D;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public class FeatureMatcher
{
private readonly double _threshold = 100; // SURF 100
private readonly double _threshold; // SURF 100
private readonly Feature2D _feature2D;
private readonly Dictionary<DescriptorMatcherType, DescriptorMatcher> _matcherFactory = new()
{
{ DescriptorMatcherType.BruteForce, DescriptorMatcher.Create(DescriptorMatcherType.BruteForce.ToString()) },
{ DescriptorMatcherType.FlannBased, DescriptorMatcher.Create(DescriptorMatcherType.FlannBased.ToString()) }
};
private readonly FlannBasedMatcher flnMatcher = new();
private readonly Size _trainMatSize; // 大图大小
@@ -40,9 +34,11 @@ public class FeatureMatcher
/// <param name="trainMat"></param>
/// <param name="featureStorage"></param>
/// <param name="type"></param>
/// <param name="threshold"></param>
/// <exception cref="Exception"></exception>
public FeatureMatcher(Mat trainMat, FeatureStorage? featureStorage = null, Feature2DType type = Feature2DType.SIFT)
public FeatureMatcher(Mat trainMat, FeatureStorage? featureStorage = null, Feature2DType type = Feature2DType.SIFT, double threshold = 100)
{
_threshold = threshold;
_trainMatSize = trainMat.Size();
if (Feature2DType.SURF == type)
{
@@ -90,9 +86,11 @@ public class FeatureMatcher
/// <param name="trainMatSize"></param>
/// <param name="featureStorage"></param>
/// <param name="type"></param>
/// <param name="threshold"></param>
/// <exception cref="Exception"></exception>
public FeatureMatcher(Size trainMatSize, FeatureStorage featureStorage, Feature2DType type = Feature2DType.SIFT)
public FeatureMatcher(Size trainMatSize, FeatureStorage featureStorage, Feature2DType type = Feature2DType.SIFT, double threshold = 100)
{
_threshold = threshold;
_trainMatSize = trainMatSize;
if (Feature2DType.SURF == type)
{
@@ -116,13 +114,6 @@ public class FeatureMatcher
Debug.WriteLine($"切割特征点耗时: {sw.ElapsedMilliseconds}ms");
}
public DescriptorMatcher GetMatcher(DescriptorMatcherType type)
{
return _matcherFactory[type];
}
#region 普通匹配
/// <summary>
/// 普通匹配(全图特征)
/// </summary>
@@ -159,13 +150,11 @@ public class FeatureMatcher
/// 普通匹配
/// </summary>
/// <param name="trainKeyPoints"></param>
/// <param name="trainDescriptors"></param>
/// <param name="trainRet"></param>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <param name="matcherType"></param>
/// <returns></returns>
public Point2f Match(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
public Point2f Match(KeyPoint[] trainKeyPoints, Mat trainRet, Mat queryMat, Mat? queryMatMask = null)
{
SpeedTimer speedTimer = new();
@@ -175,7 +164,7 @@ public class FeatureMatcher
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).Match(queryDescriptors, trainDescriptors);
var matches = flnMatcher.Match(queryDescriptors, trainRet);
//Finding the Minimum and Maximum Distance
double minDistance = 1000; //Backward approximation
double maxDistance = 0;
@@ -248,13 +237,11 @@ public class FeatureMatcher
/// 普通匹配
/// </summary>
/// <param name="trainKeyPoints"></param>
/// <param name="trainDescriptors"></param>
/// <param name="trainRet"></param>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <param name="matcherType"></param>
/// <returns></returns>
public Point2f[] MatchCorners(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
public Point2f[] MatchCorners(KeyPoint[] trainKeyPoints, Mat trainRet, Mat queryMat, Mat? queryMatMask = null)
{
SpeedTimer speedTimer = new();
@@ -264,7 +251,7 @@ public class FeatureMatcher
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).Match(queryDescriptors, trainDescriptors);
var matches = flnMatcher.Match(queryDescriptors, trainRet);
//Finding the Minimum and Maximum Distance
double minDistance = 1000; //Backward approximation
double maxDistance = 0;
@@ -341,46 +328,91 @@ public class FeatureMatcher
return Cv2.BoundingRect(corners);
}
#endregion 普通匹配
#region Knn匹配
public Point2f KnnMatch(Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
return KnnMatch(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask, matcherType);
}
public Point2f KnnMatch(Mat queryMat, float prevX, float prevY, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(_trainMatSize, _splitRow, _splitCol, prevX, prevY);
Debug.WriteLine($"当前坐标({prevX},{prevY})在特征块({cellRow},{cellCol})中");
if (_lastMergedBlock == null || _lastMergedBlock.MergedCenterCellRow != cellRow || _lastMergedBlock.MergedCenterCellCol != cellCol)
{
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainDescriptors, cellRow, cellCol);
}
return KnnMatch(_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!, queryMat, queryMatMask, matcherType);
}
// /// <summary>
// /// knn的方式匹配
// /// </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");
// }
//
// var knnMatches = flnMatcher.KnnMatch(matSrcRet, _trainDescriptors, 2);
// const float minRatio = 0.75f;
//
// 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);
// }
// }
//
// if (pointsSrc.Count < 7)
// {
// Debug.WriteLine("匹配点过少");
// return null;
// }
//
// 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;
// }
/// <summary>
/// https://github.com/tignioj/minimap/blob/main/matchmap/sifttest/sifttest5.py
/// Copilot 生成
/// </summary>
/// <returns></returns>
private Point2f KnnMatch(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
private Point2f? KnnMatch(KeyPoint[] trainKeyPoints, Mat trainRet, Mat queryMat, Mat? queryMatMask = null)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
var matches = flnMatcher.KnnMatch(queryDescriptors, _trainDescriptors, k: 2);
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
@@ -394,101 +426,29 @@ public class FeatureMatcher
if (goodMatches.Count < 7)
{
return new Point2f();
return null;
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
var dstPts = goodMatches.Select(m => _trainKeyPoints[m.TrainIdx].Pt).ToArray();
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
var M = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (M.Empty())
{
return new Point2f();
return null;
}
speedTimer.Record("FindHomography");
// 计算小地图的中心点
var h = queryMat.Rows;
var w = queryMat.Cols;
var centerPoint = new Point2f(w / 2f, h / 2f);
Point2f[] centerPoints = [centerPoint];
Point2f[] transformedCenter = Cv2.PerspectiveTransform(centerPoints, hMat);
Point2f[] transformedCenter = Cv2.PerspectiveTransform(centerPoints, M);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
// 返回小地图在大地图中的中心坐标
return transformedCenter[0];
}
public Point2f[] KnnMatchCorners(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
_feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
foreach (var match in matches)
{
if (match.Length == 2 && match[0].Distance < 0.75 * match[1].Distance)
{
goodMatches.Add(match[0]);
}
}
if (goodMatches.Count < 7)
{
return [];
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
{
return [];
}
speedTimer.Record("FindHomography");
// 返回四个角点
var objCorners = new Point2f[4];
objCorners[0] = new Point2f(0, 0);
objCorners[1] = new Point2f(0, queryMat.Rows);
objCorners[2] = new Point2f(queryMat.Cols, queryMat.Rows);
objCorners[3] = new Point2f(queryMat.Cols, 0);
var sceneCorners = Cv2.PerspectiveTransform(objCorners, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return sceneCorners;
}
public Rect KnnMatchRect(Mat queryMat, Mat? queryMatMask = null)
{
var corners = KnnMatchCorners(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
if (corners.Length == 0)
{
return Rect.Empty;
}
return Cv2.BoundingRect(corners);
}
#endregion Knn匹配
}
@@ -7,7 +7,7 @@ namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public class FeatureStorage(string name)
{
private readonly string rootPath = Global.Absolute(@"Assets\Map\");
private readonly string rootPath = Global.Absolute(@"User\Map\");
public void SetType(Feature2DType type)
{
@@ -144,28 +144,5 @@ public class RecognitionObject
/// </summary>
public List<string> RegexMatchText { get; set; } = [];
public static RecognitionObject Ocr(double x, double y, double w, double h)
{
return new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect((int)Math.Round(x), (int)Math.Round(y), (int)Math.Round(w), (int)Math.Round(h))
};
}
public static RecognitionObject Ocr(Rect rect)
{
return new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = rect
};
}
public static RecognitionObject OcrThis = new()
{
RecognitionType = RecognitionTypes.Ocr
};
#endregion OCR文字识别
}
@@ -8,10 +8,8 @@ using Microsoft.Extensions.Logging;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
@@ -41,13 +39,13 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
MessageBox.Show("请先在启动页,启动截图器再使用本功能");
return;
}
if (Status != KeyMouseRecorderStatus.Stop)
{
Toast.Warning("已经在录制状态,请不要重复启动录制功能");
MessageBox.Show("已经在录制状态,请不要重复启动录制功能");
return;
}
@@ -115,7 +113,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
ra.Dispose();
}
public void GlobalHookKeyDown(KeyEventArgs e, uint time)
public void GlobalHookKeyDown(KeyEventArgs e)
{
// 排除热键
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.KeyMouseMacroRecordHotkey)
@@ -139,10 +137,10 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_keyDownState.Add(e.KeyCode, true);
}
// Debug.WriteLine($"KeyDown: {e.KeyCode}");
_recorder?.KeyDown(e, time);
_recorder?.KeyDown(e);
}
public void GlobalHookKeyUp(KeyEventArgs e, uint time)
public void GlobalHookKeyUp(KeyEventArgs e)
{
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.Test1Hotkey)
{
@@ -153,7 +151,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
{
// Debug.WriteLine($"KeyUp: {e.KeyCode}");
_keyDownState[e.KeyCode] = false;
_recorder?.KeyUp(e, time);
_recorder?.KeyUp(e);
}
}
@@ -178,21 +176,15 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
// Debug.WriteLine($"MouseMove: {e.X}, {e.Y}");
_recorder?.MouseMoveTo(e);
}
public void GlobalHookMouseWheel(MouseEventExtArgs e)
{
// Debug.WriteLine($"MouseWheel: {e.Delta}");
_recorder?.MouseWheel(e);
}
public void GlobalHookMouseMoveBy(MouseState state, uint time)
public void GlobalHookMouseMoveBy(MouseState state)
{
if (state is { X: 0, Y: 0 } || !_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMoveBy: {state.X}, {state.Y}");
_recorder?.MouseMoveBy(state, time);
_recorder?.MouseMoveBy(state);
}
}
@@ -12,9 +12,7 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fischless.WindowsInput;
using Vanara.PInvoke;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
@@ -24,12 +22,12 @@ public class KeyMouseMacroPlayer
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
MessageBox.Show("请先在启动页,启动截图器再使用本功能");
return;
}
var script = JsonSerializer.Deserialize<KeyMouseScript>(macro, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro");
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect, TaskContext.Instance().DpiScale);
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect);
SystemControl.ActivateWindow();
if (withDelay)
@@ -49,50 +47,26 @@ public class KeyMouseMacroPlayer
public static async Task PlayMacro(List<MacroEvent> macroEvents, CancellationToken ct)
{
WorkingArea = PrimaryScreen.WorkingArea;
var startTime = Kernel32.GetTickCount();
var startTime = DateTime.UtcNow;
foreach (var e in macroEvents)
{
if (ct.IsCancellationRequested)
{
return;
}
var timeToWait = e.Time - (Kernel32.GetTickCount() - startTime);
var timeToWait = (int)(e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds);
if (timeToWait < 0)
{
TaskControl.Logger.LogDebug("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), (-timeToWait).ToString("F0"));
TaskControl.Logger.LogWarning("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), -timeToWait);
}
else
{
await Task.Delay((int)timeToWait, ct);
await Task.Delay(timeToWait, ct);
}
switch (e.Type)
{
case MacroEventType.KeyDown:
var vkDown = (User32.VK)e.KeyCode!;
if (InputBuilder.IsExtendedKey(vkDown))
{
Simulation.SendInput.Keyboard.KeyDown(false, vkDown);
}
else
{
Simulation.SendInput.Keyboard.KeyDown(vkDown);
}
Simulation.SendInput.Keyboard.KeyDown((User32.VK)e.KeyCode!);
break;
case MacroEventType.KeyUp:
var vkUp = (User32.VK)e.KeyCode!;
if (InputBuilder.IsExtendedKey(vkUp))
{
Simulation.SendInput.Keyboard.KeyUp(false, vkUp);
}
else
{
Simulation.SendInput.Keyboard.KeyUp(vkUp);
}
Simulation.SendInput.Keyboard.KeyUp((User32.VK)e.KeyCode!);
break;
case MacroEventType.MouseDown:
@@ -165,21 +139,11 @@ public class KeyMouseMacroPlayer
Simulation.SendInput.Mouse.MoveMouseTo(ToVirtualDesktopX(e.MouseX), ToVirtualDesktopY(e.MouseY));
break;
case MacroEventType.MouseWheel:
var num = (int)(e.MouseY / 120.0);
if (num != 0)
{
// 不支持多次的场景,但是不会出现这种情况
Simulation.SendInput.Mouse.VerticalScroll(num);
}
break;
case MacroEventType.MouseMoveBy:
if (e.CameraOrientation != null)
{
var cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcMat);
var diff = ((int)Math.Round(cao) - (int)e.CameraOrientation + 180) % 360 - 180;
var cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcGreyMat);
var diff = (cao - (int)e.CameraOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
//过滤一下特别大的角度偏差
if (diff != 0 && diff < 8 && diff > -8)
@@ -188,7 +152,6 @@ public class KeyMouseMacroPlayer
e.MouseX -= diff;
}
}
Simulation.SendInput.Mouse.MoveMouseBy(e.MouseX, e.MouseY);
break;
@@ -209,4 +172,4 @@ public class KeyMouseMacroPlayer
{
return y * 65535 * 1d / WorkingArea.Height;
}
}
}
@@ -9,7 +9,6 @@ using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Recorder;
@@ -17,7 +16,7 @@ public class KeyMouseRecorder
{
public List<MacroEvent> MacroEvents { get; } = [];
public uint StartTime { get; set; } = Kernel32.GetTickCount();
public DateTime StartTime { get; set; } = DateTime.UtcNow;
public DateTime LastOrientationDetection { get; set; } = DateTime.UtcNow;
@@ -35,11 +34,6 @@ public class KeyMouseRecorder
public string ToJsonMacro()
{
// MacroEvents 需要以实际时间进行排序
MacroEvents.Sort((a, b) => a.Time.CompareTo(b.Time));
// 删除为负数的时间
MacroEvents.RemoveAll(m => m.Time < 0);
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
// 合并鼠标移动事件
var mergedMacroEvents = new List<MacroEvent>();
@@ -103,30 +97,29 @@ public class KeyMouseRecorder
X = rect.X,
Y = rect.Y,
Width = rect.Width,
Height = rect.Height,
RecordDpi = TaskContext.Instance().DpiScale
Height = rect.Height
}
};
return JsonSerializer.Serialize(keyMouseScript, JsonOptions);
}
public void KeyDown(KeyEventArgs e, uint time)
public void KeyDown(KeyEventArgs e)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = time - StartTime
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
}
public void KeyUp(KeyEventArgs e, uint time)
public void KeyUp(KeyEventArgs e)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = time - StartTime
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
}
@@ -138,7 +131,7 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = e.Timestamp - StartTime
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
}
@@ -150,7 +143,7 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = e.Timestamp - StartTime
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
}
@@ -161,40 +154,28 @@ public class KeyMouseRecorder
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = e.Timestamp - StartTime
});
}
public void MouseWheel(MouseEventExtArgs e)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseWheel,
MouseY = e.Delta, // 120 的倍率
Time = e.Timestamp - StartTime
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
}
public void MouseMoveBy(MouseState state, uint time)
public void MouseMoveBy(MouseState state)
{
var now = DateTime.UtcNow;
int? cao = null;
if (TaskContext.Instance().Config.RecordConfig.IsRecordCameraOrientation)
{
var now = DateTime.UtcNow;
if ((now - LastOrientationDetection).TotalMilliseconds > 100.0)
{
LastOrientationDetection = now;
cao = (int)Math.Round(CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcMat));
cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcGreyMat);
}
}
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = state.X,
MouseY = state.Y,
Time = time - 5 - StartTime,
Time = (now - StartTime).TotalMilliseconds,
CameraOrientation = cao,
});
}
@@ -14,28 +14,24 @@ public class KeyMouseScript
/// <summary>
/// 转换原始脚本为适应当前分辨率的脚本
/// </summary>
public void Adapt(RECT captureRect, double dpiScale)
/// <param name="captureRect"></param>
public void Adapt(RECT captureRect)
{
foreach (var macroEvent in MacroEvents)
{
if (Info == null || Info.Width == 0 || Info.Height == 0)
{
Debug.WriteLine("错误的脚本数据 Info.Width == 0 || Info.Height == 0");
break;
}
if (macroEvent.Type == MacroEventType.MouseMoveTo
|| macroEvent.Type == MacroEventType.MouseDown
|| macroEvent.Type == MacroEventType.MouseUp)
{
if (Info == null || Info.Width == 0 || Info.Height == 0)
{
Debug.WriteLine("错误的脚本数据 Info.Width == 0 || Info.Height == 0");
break;
}
macroEvent.MouseX = (int)(captureRect.X + (macroEvent.MouseX - Info.X) * captureRect.Width * 1d / Info.Width);
macroEvent.MouseY = (int)(captureRect.Y + (macroEvent.MouseY - Info.Y) * captureRect.Height * 1d / Info.Height);
}
else if (macroEvent.Type == MacroEventType.MouseMoveBy)
{
macroEvent.MouseX = (int)Math.Round(macroEvent.MouseX / Info.RecordDpi * dpiScale, 0);
macroEvent.MouseY = (int)Math.Round(macroEvent.MouseY / Info.RecordDpi * dpiScale, 0);
}
}
}
}
@@ -9,19 +9,8 @@ public class KeyMouseScriptInfo
public string Description { get; set; } = string.Empty;
public string? Author { get; set; }
public string? Version { get; set; }
/// <summary>
/// 制作时 BetterGI 的版本,用于兼容性检查
/// </summary>
public string? BgiVersion { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public double RecordDpi { get; set; } = 1.0;
}
@@ -22,6 +22,5 @@ public enum MacroEventType
MouseMoveTo,
MouseMoveBy,
MouseDown,
MouseUp,
MouseWheel
MouseUp
}
@@ -1,31 +0,0 @@
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class AutoPathingScript(string rootPath)
{
public async Task Run(string json)
{
var task = PathingTask.BuildFromJson(json);
await new PathExecutor(CancellationContext.Instance.Cts.Token).Pathing(task);
}
public async Task RunFile(string path)
{
var json = await new LimitedFile(rootPath).ReadText(path);
await Run(json);
}
/// <summary>
/// 从已订阅的内容中获取文件
/// </summary>
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
public async Task RunFileFromUser(string path)
{
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
await Run(json);
}
}
@@ -1,13 +1,6 @@
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.ViewModel.Pages;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoWood;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -17,11 +10,6 @@ public class Dispatcher
{
}
/// <summary>
/// 添加实时任务
/// </summary>
/// <param name="timer">实时任务触发器</param>
/// <exception cref="ArgumentNullException"></exception>
public void AddTimer(RealtimeTimer timer)
{
var realtimeTimer = timer;
@@ -36,70 +24,4 @@ public class Dispatcher
TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config);
}
/// <summary>
/// 运行独立任务
/// </summary>
/// <param name="soloTask">
/// 支持的任务名称:
/// - AutoGeniusInvokation: 启动自动七圣召唤任务
/// - AutoWood: 启动自动伐木任务
/// - AutoFight: 启动自动战斗任务
/// - AutoDomain: 启动自动秘境任务
/// </param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public async Task RunTask(SoloTask soloTask)
{
if (soloTask == null)
{
throw new ArgumentNullException(nameof(soloTask), "独立任务对象不能为空");
}
var taskSettingsPageViewModel = App.GetService<TaskSettingsPageViewModel>();
if (taskSettingsPageViewModel == null)
{
throw new ArgumentNullException(nameof(taskSettingsPageViewModel), "内部视图模型对象为空");
}
// 根据名称执行任务
switch (soloTask.Name)
{
case "AutoGeniusInvokation":
if (taskSettingsPageViewModel.GetTcgStrategy(out var content))
{
return;
}
await new AutoGeniusInvokationTask(new GeniusInvokationTaskParam(content)).Start(CancellationContext.Instance.Cts.Token);
break;
case "AutoWood":
await new AutoWoodTask(new WoodTaskParam(taskSettingsPageViewModel.AutoWoodRoundNum, taskSettingsPageViewModel.AutoWoodDailyMaxCount)).Start(CancellationContext.Instance.Cts.Token);
break;
case "AutoFight":
if (taskSettingsPageViewModel.GetFightStrategy(out var path1))
{
return;
}
var autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
var param = new AutoFightParam(path1, autoFightConfig);
await new AutoFightTask(param).Start(CancellationContext.Instance.Cts.Token);
break;
case "AutoDomain":
if (taskSettingsPageViewModel.GetFightStrategy(out var path))
{
return;
}
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(CancellationContext.Instance.Cts.Token);
break;
// case "AutoMusicGame":
// taskSettingsPageViewModel.SwitchAutoMusicGameCommand.Execute(null);
// break;
default:
throw new ArgumentException($"未知的任务名称: {soloTask.Name}", nameof(soloTask.Name));
}
}
}
@@ -1,147 +1,12 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Job;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
{
private RECT captureAreaRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
/// <summary>
/// 游戏宽度
/// </summary>
public int Width => captureAreaRect.Width;
/// <summary>
/// 游戏高度
/// </summary>
public int Height => captureAreaRect.Height;
/// <summary>
/// 游戏窗口大小相比1080P的缩放比例
/// </summary>
public double ScaleTo1080PRatio { get; } = TaskContext.Instance().SystemInfo.ScaleTo1080PRatio;
/// <summary>
/// 系统屏幕的DPI缩放比例
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(double x, double y)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y);
await new TpTask(CancellationContext.Instance.Cts).Tp(x, y);
}
public async Task Tp(double x, double y, bool force)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, force);
}
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(string x, string y)
{
double.TryParse(x, out var dx);
double.TryParse(y, out var dy);
await Tp(dx, dy);
}
public async Task Tp(string x, string y, bool force)
{
double.TryParse(x, out var dx);
double.TryParse(y, out var dy);
await Tp(dx, dy, force);
}
/// <summary>
/// 切换队伍
/// </summary>
/// <param name="partyName">队伍界面自定义的队伍名称</param>
/// <returns></returns>
public async Task SwitchParty(string partyName)
{
await new SwitchPartyTask().Start(partyName, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 自动点击空月祝福
/// </summary>
/// <returns></returns>
public async Task BlessingOfTheWelkinMoon()
{
await new BlessingOfTheWelkinMoonTask().Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 持续对话并选择目标选项
/// </summary>
/// <param name="option">选项文本</param>
/// <param name="skipTimes">跳过次数</param>
/// <param name="isOrange">是否为橙色选项</param>
/// <returns></returns>
public async Task ChooseTalkOption(string option, int skipTimes = 10, bool isOrange = false)
{
await new ChooseTalkOptionTask().SingleSelectText(option, CancellationContext.Instance.Cts.Token, skipTimes, isOrange);
}
/// <summary>
/// 一键领取纪行奖励
/// </summary>
/// <returns></returns>
public async Task ClaimBattlePassRewards()
{
await new ClaimBattlePassRewardsTask().Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 领取长效历练点奖励
/// </summary>
/// <returns></returns>
public async Task ClaimEncounterPointsRewards()
{
await new ClaimEncounterPointsRewardsTask().Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 前往冒险家协会领取奖励
/// </summary>
/// <param name="country">国家名称</param>
/// <returns></returns>
public async Task GoToAdventurersGuild(string country)
{
await new GoToAdventurersGuildTask().Start(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 前往合成台
/// </summary>
/// <param name="country">国家名称</param>
/// <returns></returns>
public async Task GoToCraftingBench(string country)
{
await new GoToCraftingBenchTask().Start(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 返回主界面
/// </summary>
/// <returns></returns>
public async Task ReturnMainUi()
{
await new ReturnMainUiTask().Start(CancellationContext.Instance.Cts.Token);
}
}
}
@@ -1,11 +1,4 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common;
using Vanara.PInvoke;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -15,138 +8,4 @@ public class GlobalMethod
{
await Task.Delay(millisecondsTimeout, CancellationContext.Instance.Cts.Token);
}
#region 键盘操作
public static void KeyDown(string key)
{
Simulation.SendInput.Keyboard.KeyDown(ToVk(key));
}
public static void KeyUp(string key)
{
Simulation.SendInput.Keyboard.KeyUp(ToVk(key));
}
public static void KeyPress(string key)
{
Simulation.SendInput.Keyboard.KeyPress(ToVk(key));
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
#endregion 键盘操作
#region 鼠标操作
private static int _gameWidth = 1920;
private static int _gameHeight = 1080;
private static double _dpi = 1;
public static void SetGameMetrics(int width, int height, double dpi = 1)
{
// 必须16:9 的分辨率
if (width * 9 != height * 16)
{
throw new ArgumentException("游戏分辨率必须是16:9的分辨率");
}
_gameWidth = width;
_gameHeight = height;
_dpi = dpi;
}
public static void MoveMouseBy(int x, int y)
{
var realDpi = TaskContext.Instance().DpiScale;
x = (int)(x * realDpi / _dpi);
y = (int)(y * realDpi / _dpi);
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
}
public static void MoveMouseTo(int x, int y)
{
if (x < 0 || x > _gameWidth || y < 0 || y > _gameHeight)
{
throw new ArgumentException("鼠标坐标超出游戏窗口范围");
}
GameCaptureRegion.GameRegionMove((size, s2) =>
{
var scale = 1920.0 / _gameWidth;
return (x * scale * s2, y * scale * s2);
});
}
public static void Click(int x, int y)
{
MoveMouseTo(x, y);
LeftButtonClick();
}
public static void LeftButtonClick()
{
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(60).LeftButtonUp();
}
public static void LeftButtonDown()
{
Simulation.SendInput.Mouse.LeftButtonDown();
}
public static void LeftButtonUp()
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
public static void RightButtonClick()
{
Simulation.SendInput.Mouse.RightButtonDown().Sleep(60).RightButtonUp();
}
public static void RightButtonDown()
{
Simulation.SendInput.Mouse.RightButtonDown();
}
public static void RightButtonUp()
{
Simulation.SendInput.Mouse.RightButtonUp();
}
public static void MiddleButtonClick()
{
Simulation.SendInput.Mouse.MiddleButtonClick();
}
public static void MiddleButtonDown()
{
Simulation.SendInput.Mouse.MiddleButtonDown();
}
public static void MiddleButtonUp()
{
Simulation.SendInput.Mouse.MiddleButtonUp();
}
#endregion 鼠标操作
#region 识图操作
public static ImageRegion CaptureGameRegion()
{
return TaskControl.CaptureToRectArea();
}
#endregion 识图操作
}
@@ -1,10 +1,7 @@
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
using BetterGenshinImpact.Helpers;
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 实时任务触发器
/// 实时任务计时器
/// </summary>
public class RealtimeTimer
{
@@ -32,13 +29,4 @@ public class RealtimeTimer
{
Name = name;
}
public RealtimeTimer(string name, dynamic config)
{
Name = name;
if (Name == "AutoPick")
{
Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
}
}
}
@@ -1,31 +0,0 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 独立任务
/// </summary>
public class SoloTask
{
/// <summary>
/// 独立任务名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 独立任务配置
/// </summary>
public object? Config;
public SoloTask(string name)
{
Name = name;
}
public SoloTask(string name, dynamic config)
{
Name = name;
// if (Name == "AutoPick")
// {
// Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
// }
}
}
@@ -1,44 +0,0 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Helpers;
using System;
using BetterGenshinImpact.GameTask;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence.Simulator;
public class PostMessage
{
private readonly PostMessageSimulator _postMessageSimulator = TaskContext.Instance().PostMessageSimulator;
public void KeyDown(string key)
{
_postMessageSimulator.KeyDownBackground(ToVk(key));
}
public void KeyUp(string key)
{
_postMessageSimulator.KeyUpBackground(ToVk(key));
}
public void KeyPress(string key)
{
_postMessageSimulator.KeyPressBackground(ToVk(key));
}
public void Click()
{
_postMessageSimulator.LeftButtonClick();
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
}
@@ -1,51 +1,30 @@
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Reflection;
using System.Threading.Tasks;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
namespace BetterGenshinImpact.Core.Script;
public class EngineExtend
{
/// <summary>
/// !!! 注意:这个方法会添加一些全局方法和对象,不要随便添加,以免安全风险!!!
/// </summary>
/// <param name="engine"></param>
/// <param name="workDir"></param>
/// <param name="searchPaths"></param>
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null)
{
// engine.AddHostObject("xHost", new ExtendedHostFunctions()); // 有越权的安全风险
// 添加我的自定义实例化对象
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
// 任务调度器
// 实时任务调度器
engine.AddHostObject("dispatcher", new Dispatcher());
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
engine.AddHostType("SoloTask", typeof(SoloTask));
// PostMessage 作为类型实例化
engine.AddHostType("PostMessage", typeof(Dependence.Simulator.PostMessage));
// 直接添加方法
AddAllGlobalMethod(engine);
// 识图模块相关
engine.AddHostType("Mat", typeof(Mat));
engine.AddHostType("RecognitionObject", typeof(RecognitionObject));
engine.AddHostType("DesktopRegion", typeof(DesktopRegion));
engine.AddHostType("GameCaptureRegion", typeof(GameCaptureRegion));
engine.AddHostType("ImageRegion", typeof(ImageRegion));
engine.AddHostType("Region", typeof(Region));
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
#pragma warning restore CS8974 // Converting method group to non-delegate type
// 添加C#的类型
engine.AddHostType(typeof(Task));
@@ -59,38 +38,4 @@ public class EngineExtend
engine.DocumentSettings.SearchPath = string.Join(';', searchPaths);
}
}
public static void AddAllGlobalMethod(IScriptEngine engine)
{
// // 获取GlobalMethod类的所有静态方法
// var methods = typeof(GlobalMethod).GetMethods(BindingFlags.Static | BindingFlags.Public);
//
// foreach (var method in methods)
// {
// // 使用方法名首字母小写作为HostObject的名称
// var methodName = char.ToLowerInvariant(method.Name[0]) + method.Name[1..];
// engine.AddHostObject(methodName, method);
// }
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
engine.AddHostObject("keyDown", GlobalMethod.KeyDown);
engine.AddHostObject("keyUp", GlobalMethod.KeyUp);
engine.AddHostObject("keyPress", GlobalMethod.KeyPress);
engine.AddHostObject("setGameMetrics", GlobalMethod.SetGameMetrics);
engine.AddHostObject("moveMouseBy", GlobalMethod.MoveMouseBy);
engine.AddHostObject("moveMouseTo", GlobalMethod.MoveMouseTo);
engine.AddHostObject("click", GlobalMethod.Click);
engine.AddHostObject("leftButtonClick", GlobalMethod.LeftButtonClick);
engine.AddHostObject("leftButtonDown", GlobalMethod.LeftButtonDown);
engine.AddHostObject("leftButtonUp", GlobalMethod.LeftButtonUp);
engine.AddHostObject("rightButtonClick", GlobalMethod.RightButtonClick);
engine.AddHostObject("rightButtonDown", GlobalMethod.RightButtonDown);
engine.AddHostObject("rightButtonUp", GlobalMethod.RightButtonUp);
engine.AddHostObject("middleButtonClick", GlobalMethod.MiddleButtonClick);
engine.AddHostObject("middleButtonDown", GlobalMethod.MiddleButtonDown);
engine.AddHostObject("middleButtonUp", GlobalMethod.MiddleButtonUp);
engine.AddHostObject("captureGameRegion", GlobalMethod.CaptureGameRegion);
#pragma warning restore CS8974 // Converting method group to non-delegate type
}
}
@@ -1,16 +1,12 @@
using BetterGenshinImpact.Service;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text.Json;
namespace BetterGenshinImpact.Core.Script.Group;
/// <summary>
/// 调度器 配置组
/// </summary>
public partial class ScriptGroup : ObservableObject
{
public int Index { get; set; }
@@ -18,9 +14,6 @@ public partial class ScriptGroup : ObservableObject
[ObservableProperty]
private string _name = string.Empty;
[ObservableProperty]
private ScriptGroupConfig _config = new();
[ObservableProperty]
private ObservableCollection<ScriptGroupProject> _projects = [];
@@ -41,22 +34,6 @@ public partial class ScriptGroup : ObservableObject
public static ScriptGroup FromJson(string json)
{
var group = Newtonsoft.Json.JsonConvert.DeserializeObject<ScriptGroup>(json) ?? throw new Exception("解析配置组JSON配置失败");
ResetGroupInfo(group);
return group;
}
public static void ResetGroupInfo(ScriptGroup group)
{
foreach (var project in group.Projects)
{
project.GroupInfo = group;
}
}
public void AddProject(ScriptGroupProject project)
{
project.GroupInfo = this;
Projects.Add(project);
return JsonSerializer.Deserialize<ScriptGroup>(json, ConfigService.JsonOptions) ?? throw new Exception("解析脚本组JSON配置失败");
}
}
@@ -1,12 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Group;
[Serializable]
public partial class ScriptGroupConfig : ObservableObject
{
[ObservableProperty]
private PathingPartyConfig _pathingConfig = new();
}
@@ -1,17 +1,8 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Script.Project;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.Core.Script.Project;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Group;
@@ -20,26 +11,12 @@ public partial class ScriptGroupProject : ObservableObject
[ObservableProperty]
private int _index;
/// <summary>
/// 理论上是文件名
/// </summary>
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
/// <summary>
/// 理论上是当前类型脚本根目录到脚本文件所在目录的相对路径
/// 但是:
/// 1. JS 脚本的文件名是内部的名称,文件夹名脚本所在文件夹,这个也是唯一标识
/// 2. KeyMouse 脚本的文件名和文件夹名相同,文件夹名暂时无意义
/// 3. Pathing 文件名就是实际脚本的文件名,文件夹名是脚本所在的相对目录
/// </summary>
public string FolderName { get; set; } = string.Empty;
[ObservableProperty]
private string _type = string.Empty;
[JsonIgnore]
public string TypeDesc => ScriptGroupProjectExtensions.TypeDescriptions[Type];
[ObservableProperty]
private string _status = string.Empty;
@@ -50,71 +27,26 @@ public partial class ScriptGroupProject : ObservableObject
/// 执行周期
/// 不在 ScheduleDescriptions 中则会被视为自定义Cron表达式
/// </summary>
[ObservableProperty]
private string _schedule = string.Empty;
public string Schedule { get; set; } = string.Empty;
[JsonIgnore]
public string ScheduleDesc => ScriptGroupProjectExtensions.ScheduleDescriptions.GetValueOrDefault(Schedule, "自定义周期");
[ObservableProperty]
private int _runNum = 1;
[JsonIgnore]
public ScriptProject? Project { get; set; }
public ExpandoObject? JsScriptSettingsObject { get; set; }
/// <summary>
/// 所属配置组
/// </summary>
[JsonIgnore]
public ScriptGroup? GroupInfo { get; set; }
/// <summary>
/// 下一个从此执行标志
/// </summary>
[JsonIgnore]
[ObservableProperty]
public bool? _nextFlag = false;
public ScriptGroupProject()
{
}
public ScriptGroupProject(ScriptProject project)
{
Id = project.Manifest.Id;
Name = project.Manifest.Name;
FolderName = project.FolderName;
Status = "Enabled";
Schedule = "Daily";
Project = project;
Type = "Javascript";
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="folder"></param>
/// <param name="type">KeyMouse|Pathing</param>
public ScriptGroupProject(string name, string folder, string type)
{
Name = name;
FolderName = folder;
Status = "Enabled";
Schedule = "Daily";
Project = null; // 不是JS脚本
Type = type;
}
public static ScriptGroupProject BuildKeyMouseProject(string name)
{
return new ScriptGroupProject(name, name, "KeyMouse");
}
public static ScriptGroupProject BuildPathingProject(string name, string folder)
{
return new ScriptGroupProject(name, folder, "Pathing");
}
/// <summary>
@@ -128,75 +60,16 @@ public partial class ScriptGroupProject : ObservableObject
}
Project = new ScriptProject(FolderName);
}
public async Task Run()
{
if (Type == "Javascript")
{
if (Project == null)
{
throw new Exception("JS脚本未初始化");
}
JsScriptSettingsObject ??= new ExpandoObject();
await Project.ExecuteAsync(JsScriptSettingsObject);
}
if (Type == "KeyMouse")
{
// 加载并执行
var json = await File.ReadAllTextAsync(Global.Absolute(@$"User\KeyMouseScript\{Name}"));
await KeyMouseMacroPlayer.PlayMacro(json, CancellationContext.Instance.Cts.Token, false);
}
if (Type == "Pathing")
{
// 加载并执行
var task = PathingTask.BuildFromFilePath(Path.Combine(MapPathingViewModel.PathJsonPath, FolderName, Name));
TaskTriggerDispatcher.Instance().AddTrigger("AutoPick", null);
var pathingTask = new PathExecutor(CancellationContext.Instance.Cts.Token);
pathingTask.PartyConfig = GroupInfo?.Config.PathingConfig;
await pathingTask.Pathing(task);
}
else
{
//throw new Exception("不支持的脚本类型");
}
}
partial void OnTypeChanged(string value)
{
OnPropertyChanged(nameof(TypeDesc));
}
partial void OnStatusChanged(string value)
{
OnPropertyChanged(nameof(StatusDesc));
}
partial void OnScheduleChanged(string value)
{
OnPropertyChanged(nameof(ScheduleDesc));
}
}
public class ScriptGroupProjectExtensions
public static class ScriptGroupProjectExtensions
{
public static readonly Dictionary<string, string> TypeDescriptions = new()
{
{ "Javascript", "JS脚本" },
{ "KeyMouse", "键鼠脚本" },
{ "Pathing", "路径追踪" }
};
public static readonly Dictionary<string, string> StatusDescriptions = new()
{
{ "Enabled", "启用" },
{ "Disabled", "禁用" }
};
public Dictionary<string, string> GetStatusDescriptions()
{
return StatusDescriptions;
}
public static readonly Dictionary<string, string> ScheduleDescriptions = new()
{
{ "Daily", "每日" },
@@ -209,9 +82,4 @@ public class ScriptGroupProjectExtensions
{ "Saturday", "每周六" },
{ "Sunday", "每周日" }
};
public Dictionary<string, string> GetScheduleDescriptions()
{
return ScheduleDescriptions;
}
}
@@ -3,10 +3,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Model;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Project;
@@ -14,24 +10,29 @@ namespace BetterGenshinImpact.Core.Script.Project;
public class Manifest
{
public int ManifestVersion { get; set; } = 1;
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string? BgiVersion { get; set; }
public string Description { get; set; } = string.Empty;
public List<Author> Authors { get; set; } = [];
public string Main { get; set; } = string.Empty;
public string SettingsUi { get; set; } = string.Empty;
public string[] Scripts { get; set; } = [];
public string[] Library { get; set; } = [];
public static Manifest FromJson(string json)
{
var manifest = JsonSerializer.Deserialize<Manifest>(json, Global.ManifestJsonOptions) ?? throw new Exception("Failed to deserialize JSON.");
var manifest = JsonSerializer.Deserialize<Manifest>(json, ConfigService.JsonOptions) ?? throw new Exception("Failed to deserialize JSON.");
return manifest;
}
public void Validate(string path)
{
if (string.IsNullOrWhiteSpace(Id))
{
throw new Exception("manifest.json: id is not supported.");
}
if (string.IsNullOrWhiteSpace(Name))
{
throw new Exception("manifest.json: name is required.");
@@ -51,29 +52,5 @@ public class Manifest
{
throw new FileNotFoundException("main js file not found.");
}
// 比较版本号大小 BgiVersion
if (!string.IsNullOrWhiteSpace(BgiVersion) && Global.IsNewVersion(BgiVersion))
{
TaskControl.Logger.LogError("脚本 {Name} 版本号要求 {BgiVersion} 大于当前 BetterGI 版本号 {CurrentVersion} , 脚本可能无法正常工作,请更新 BetterGI 版本!", Name, BgiVersion, Global.Version);
}
}
public List<SettingItem> LoadSettingItems(string path)
{
if (string.IsNullOrWhiteSpace(SettingsUi))
{
return [];
}
var settingItems = new List<SettingItem>();
var settingFile = Path.Combine(path, SettingsUi);
if (File.Exists(settingFile))
{
var json = File.ReadAllText(settingFile);
settingItems = JsonSerializer.Deserialize<List<SettingItem>>(json, ConfigService.JsonOptions) ?? [];
}
return settingItems;
}
}
@@ -5,8 +5,6 @@ using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Controls;
using BetterGenshinImpact.Core.Script.Dependence;
namespace BetterGenshinImpact.Core.Script.Project;
@@ -23,40 +21,16 @@ public class ScriptProject
{
FolderName = folderName;
ProjectPath = Path.Combine(Global.ScriptPath(), folderName);
if (!Directory.Exists(ProjectPath))
{
throw new DirectoryNotFoundException("脚本文件夹不存在:" + ProjectPath);
}
ManifestFile = Path.GetFullPath(Path.Combine(ProjectPath, "manifest.json"));
if (!File.Exists(ManifestFile))
{
throw new FileNotFoundException("manifest.json文件不存在,请确认此脚本是JS脚本类型。" + ManifestFile);
throw new FileNotFoundException("manifest.json file not found.");
}
Manifest = Manifest.FromJson(File.ReadAllText(ManifestFile));
Manifest.Validate(ProjectPath);
}
public StackPanel? LoadSettingUi(dynamic context)
{
var settingItems = Manifest.LoadSettingItems(ProjectPath);
if (settingItems.Count == 0)
{
return null;
}
var stackPanel = new StackPanel();
foreach (var item in settingItems)
{
var controls = item.ToControl(context);
foreach (var control in controls)
{
stackPanel.Children.Add(control);
}
}
return stackPanel;
}
public IScriptEngine BuildScriptEngine()
{
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
@@ -64,18 +38,10 @@ public class ScriptProject
return engine;
}
public async Task ExecuteAsync(dynamic? context = null)
public async Task ExecuteAsync()
{
// 默认值
GlobalMethod.SetGameMetrics(1920, 1080);
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine();
if (context != null)
{
// 写入配置的内容
engine.AddHostObject("settings", context);
}
try
{
await (Task)engine.Evaluate(code);
@@ -1,490 +0,0 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.WebView;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Http;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Controls.Webview;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using Vanara.PInvoke;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script;
public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
{
private readonly ILogger<ScriptRepoUpdater> _logger = App.GetLogger<ScriptRepoUpdater>();
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) };
// 仓储位置
public static readonly string ReposPath = Global.Absolute("Repos");
// 仓储临时目录 用于下载与解压
public static readonly string ReposTempPath = Path.Combine(ReposPath, "Temp");
// 中央仓库信息地址
public static readonly string CenterRepoInfoUrl = "https://raw.githubusercontent.com/babalae/bettergi-scripts-list/refs/heads/main/repo.json";
// 中央仓库解压后文件夹名
public static readonly string CenterRepoUnzipName = "bettergi-scripts-list-main";
public static readonly string CenterRepoPath = Path.Combine(ReposPath, CenterRepoUnzipName);
public static readonly Dictionary<string, string> PathMapper = new Dictionary<string, string>
{
{ "pathing", Global.Absolute("User\\AutoPathing") },
{ "js", Global.Absolute("User\\JsScript") },
{ "combat", Global.Absolute("User\\AutoFight") },
{ "tcg", Global.Absolute("User\\AutoGeniusInvokation") },
};
private WebpageWindow? _webWindow;
public void AutoUpdate()
{
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
if (!Directory.Exists(ReposPath))
{
Directory.CreateDirectory(ReposPath);
}
// 判断更新周期是否到达
if (DateTime.Now - scriptConfig.LastUpdateScriptRepoTime >= TimeSpan.FromDays(scriptConfig.AutoUpdateScriptRepoPeriod))
{
// 更新仓库
Task.Run(async () =>
{
try
{
var (repoPath, updated) = await UpdateCenterRepo();
Debug.WriteLine($"脚本仓库更新完成,路径:{repoPath}");
scriptConfig.LastUpdateScriptRepoTime = DateTime.Now;
if (updated)
{
scriptConfig.ScriptRepoHintDotVisible = true;
}
}
catch (Exception e)
{
_logger.LogDebug(e, $"脚本仓库更新失败:{e.Message}");
}
});
}
}
public async Task<(string, bool)> UpdateCenterRepo()
{
// 测速并获取信息
var res = await ProxySpeedTester.GetFastestProxyAsync(CenterRepoInfoUrl);
// 解析信息
var fastProxyUrl = res.Item1;
var jsonString = res.Item2;
var (time, url, file) = ParseJson(jsonString);
var updated = false;
// 检查仓库是否存在,不存在则下载
var needDownload = false;
if (Directory.Exists(CenterRepoPath))
{
var p = Directory.GetFiles(CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (p is null)
{
needDownload = true;
}
}
else
{
needDownload = true;
}
if (needDownload)
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url));
updated = true;
}
// 搜索本地的 repo.json
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, file, SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
var (time2, url2, file2) = ParseJson(await File.ReadAllTextAsync(localRepoJsonPath));
// 检查是否需要更新
if (long.Parse(time) > long.Parse(time2))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url2));
updated = true;
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return (folderPath, updated);
}
public string FindCenterRepoPath()
{
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return folderPath;
}
private (string time, string url, string file) ParseJson(string jsonString)
{
var json = JObject.Parse(jsonString);
var time = json["time"]?.ToString();
var url = json["url"]?.ToString();
var file = json["file"]?.ToString();
// 检查是否有空值
if (time is null || url is null || file is null)
{
throw new Exception("repo.json 解析失败");
}
return (time, url, file);
}
public async Task DownloadRepoAndUnzip(string url)
{
// 下载
var res = await _httpClient.GetAsync(url);
if (!res.IsSuccessStatusCode)
{
throw new Exception("下载失败");
}
var bytes = await res.Content.ReadAsByteArrayAsync();
// 获取文件名
var contentDisposition = res.Content.Headers.ContentDisposition;
var fileName = contentDisposition is { FileName: not null } ? contentDisposition.FileName.Trim('"') : "temp.zip";
// 创建临时目录
if (!Directory.Exists(ReposTempPath))
{
Directory.CreateDirectory(ReposTempPath);
}
// 保存下载的文件
var zipPath = Path.Combine(ReposTempPath, fileName);
await File.WriteAllBytesAsync(zipPath, bytes);
// 删除旧文件夹
if (Directory.Exists(CenterRepoPath))
{
DirectoryHelper.DeleteReadOnlyDirectory(CenterRepoPath);
}
// 使用 System.IO.Compression 解压
ZipFile.ExtractToDirectory(zipPath, ReposPath, true);
}
public async Task ImportScriptFromClipboard()
{
// 获取剪切板内容
try
{
if (Clipboard.ContainsText())
{
string clipboardText = Clipboard.GetText();
await ImportScriptFromUri(clipboardText, true);
}
}
catch (Exception e)
{
// 剪切板内容可能获取会失败
Console.WriteLine(e);
}
}
public async Task ImportScriptFromUri(string uri, bool formClipboard)
{
// 检查剪切板内容是否符合特定的URL格式
if (!string.IsNullOrEmpty(uri) && uri.Trim().ToLower().StartsWith("bettergi://script?import="))
{
Debug.WriteLine($"脚本订购内容:{uri}");
// 执行相关操作
var pathJson = ParseUri(uri);
if (!string.IsNullOrEmpty(pathJson))
{
var uiMessageBox = new Wpf.Ui.Controls.MessageBox
{
Title = "脚本订阅",
Content = $"检测到{(formClipboard ? "剪切板上存在" : "")}脚本订阅链接,解析后需要导入的脚本为:{pathJson}。\n是否导入并覆盖此文件或者文件夹下的脚本?",
CloseButtonText = "关闭",
PrimaryButtonText = "确认导入",
WindowStartupLocation = WindowStartupLocation.CenterOwner,
};
var result = await uiMessageBox.ShowDialogAsync();
if (result == Wpf.Ui.Controls.MessageBoxResult.Primary)
{
await ImportScriptFromPathJson(pathJson);
}
// ContentDialog dialog = new()
// {
// Title = "脚本订阅",
// Content = $"检测到{(formClipboard ? "剪切板上存在" : "")}脚本订阅链接,解析后需要导入的脚本为:{pathJson}。\n是否导入并覆盖此文件或者文件夹下的脚本?",
// CloseButtonText = "关闭",
// PrimaryButtonText = "确认导入",
// };
//
// var result = await dialog.ShowAsync();
// if (result == ContentDialogResult.Primary)
// {
// await ImportScriptFromPathJson(pathJson);
// }
}
if (formClipboard)
{
// 清空剪切板内容
Clipboard.Clear();
}
}
}
private string? ParseUri(string uriString)
{
var uri = new Uri(uriString);
// 获取 query 参数
string query = uri.Query;
Debug.WriteLine($"Query: {query}");
// 解析 query 参数
var queryParams = System.Web.HttpUtility.ParseQueryString(query);
var import = queryParams["import"];
if (string.IsNullOrEmpty(import))
{
Debug.WriteLine("未找到 import 参数");
return null;
}
// Base64 解码后再使用url解码
byte[] data = Convert.FromBase64String(import);
return System.Web.HttpUtility.UrlDecode(System.Text.Encoding.UTF8.GetString(data));
}
public async Task ImportScriptFromPathJson(string pathJson)
{
var paths = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(pathJson);
if (paths is null || paths.Count == 0)
{
Toast.Warning("订阅脚本路径为空");
return;
}
// 保存订阅信息
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
scriptConfig.SubscribedScriptPaths.AddRange(paths);
Toast.Information("获取最新仓库信息中...");
// 更新仓库
var (repoPath, _) = await Task.Run(UpdateCenterRepo);
// // 收集将被覆盖的文件和文件夹
// var filesToOverwrite = new List<string>();
// foreach (var path in paths)
// {
// var first = GetFirstFolder(path);
// if (PathMapper.TryGetValue(first, out var userPath))
// {
// var scriptPath = Path.Combine(repoPath, path);
// var destPath = Path.Combine(userPath, path.Replace(first, ""));
// if (Directory.Exists(scriptPath))
// {
// if (Directory.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// else if (File.Exists(scriptPath))
// {
// if (File.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// }
// else
// {
// Toast.Warning($"未知的脚本路径:{path}");
// }
// }
//
// // 提示用户确认
// if (filesToOverwrite.Count > 0)
// {
// var message = "以下文件和文件夹将被覆盖:\n" + string.Join("\n", filesToOverwrite) + "\n是否覆盖所有文件和文件夹?";
// var uiMessageBox = new Wpf.Ui.Controls.MessageBox
// {
// Title = "确认覆盖",
// Content = message,
// CloseButtonText = "取消",
// PrimaryButtonText = "确认覆盖",
// WindowStartupLocation = WindowStartupLocation.CenterOwner,
// Owner = Application.Current.MainWindow,
// };
//
// var result = await uiMessageBox.ShowDialogAsync();
// if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
// {
// return;
// }
// }
// 拷贝文件
foreach (var path in paths)
{
var (first, remainingPath) = GetFirstFolderAndRemainingPath(path);
if (PathMapper.TryGetValue(first, out var userPath))
{
var scriptPath = Path.Combine(repoPath, path);
var destPath = Path.Combine(userPath, remainingPath);
if (Directory.Exists(scriptPath))
{
if (Directory.Exists(destPath))
{
DirectoryHelper.DeleteDirectoryWithReadOnlyCheck(destPath);
}
CopyDirectory(scriptPath, destPath);
// 图标处理
DealWithIconFolder(destPath);
}
else if (File.Exists(scriptPath))
{
if (File.Exists(destPath))
{
File.Delete(destPath);
}
File.Copy(scriptPath, destPath, true);
}
Toast.Success("脚本订阅链接导入完成");
}
else
{
Toast.Warning($"未知的脚本路径:{path}");
}
}
}
private void CopyDirectory(string sourceDir, string destDir)
{
// 创建目标目录
Directory.CreateDirectory(destDir);
// 拷贝文件
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
}
// 拷贝子目录
foreach (var dir in Directory.GetDirectories(sourceDir))
{
var destSubDir = Path.Combine(destDir, Path.GetFileName(dir));
CopyDirectory(dir, destSubDir);
// 图标处理
DealWithIconFolder(destSubDir);
}
}
private static (string firstFolder, string remainingPath) GetFirstFolderAndRemainingPath(string path)
{
// 检查路径是否为空或仅包含部分字符
if (string.IsNullOrEmpty(path))
{
return (string.Empty, string.Empty);
}
// 使用路径分隔符分割路径
string[] parts = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
// 返回第一个文件夹和剩余路径
return parts.Length > 0 ? (parts[0], string.Join(Path.DirectorySeparatorChar, parts.Skip(1))) : (string.Empty, string.Empty);
}
public void OpenLocalRepoInWebView()
{
if (_webWindow is not { IsVisible: true })
{
_webWindow = new WebpageWindow
{
Title = "enshin Copilot Scripts | BetterGI 脚本本地中央仓库",
Width = 1366,
Height = 768,
};
_webWindow.Closed += (s, e) => _webWindow = null;
_webWindow.Panel!.DownloadFolderPath = MapPathingViewModel.PathJsonPath;
_webWindow.NavigateToFile(Global.Absolute(@"Assets\Web\ScriptRepo\index.html"));
_webWindow.Panel!.OnWebViewInitializedAction = () => _webWindow.Panel!.WebView.CoreWebView2.AddHostObjectToScript("repoWebBridge", new RepoWebBridge());
_webWindow.Show();
}
else
{
_webWindow.Activate();
}
}
/// <summary>
/// 处理带有 icon.ico 和 desktop.ini 的文件夹
/// </summary>
/// <param name="folderPath"></param>
private void DealWithIconFolder(string folderPath)
{
if (Directory.Exists(folderPath)
&& File.Exists(Path.Combine(folderPath, "desktop.ini")))
{
// 使用 Vanara 库中的 SetFileAttributes 函数设置文件夹属性
if (Kernel32.SetFileAttributes(folderPath, FileFlagsAndAttributes.FILE_ATTRIBUTE_READONLY))
{
Debug.WriteLine($"成功将文件夹设置为只读: {folderPath}");
}
else
{
Debug.WriteLine($"无法设置文件夹为只读: {folderPath}");
}
}
}
}
@@ -1,73 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Threading.Tasks;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
namespace BetterGenshinImpact.Core.Script.WebView;
/// <summary>
/// 给 WebView 提供的桥接类
/// 用于调用 C# 方法
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class RepoWebBridge
{
public async Task<string> GetRepoJson()
{
try
{
// var needUpdate = false;
// string? localRepoJsonPath = null;
// if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
// {
// localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
// if (localRepoJsonPath is null)
// {
// needUpdate = true;
// }
// }
// else
// {
// needUpdate = true;
// }
//
// if (needUpdate)
// {
// await ScriptRepoUpdater.Instance.UpdateCenterRepo();
// }
await ScriptRepoUpdater.Instance.UpdateCenterRepo();
var localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("repo.json 不存在,可能是更新仓库信息失败!");
}
var json = await File.ReadAllTextAsync(localRepoJsonPath);
return json;
}
catch (Exception e)
{
await MessageBox.ShowAsync(e.Message, "获取仓库信息失败!");
return "";
}
}
public async void ImportUri(string url)
{
try
{
await ScriptRepoUpdater.Instance.ImportScriptFromUri(url, false);
WeakReferenceMessenger.Default.Send(new RefreshDataMessage("Refresh"));
}
catch (Exception e)
{
await MessageBox.ShowAsync(e.Message, "订阅脚本链接失败!");
}
}
}
@@ -6,50 +6,24 @@ namespace BetterGenshinImpact.GameTask.AutoDomain;
[Serializable]
public partial class AutoDomainConfig : ObservableObject
{
/// <summary>
/// 战斗结束后延迟几秒再开始寻找石化古树,秒
/// </summary>
[ObservableProperty]
private double _fightEndDelay = 5;
[ObservableProperty] private double _fightEndDelay = 5;
/// <summary>
/// 寻找古树时,短距离移动,用于识别速度过慢的计算机使用
/// </summary>
[ObservableProperty]
private bool _shortMovement = false;
[ObservableProperty] private bool _shortMovement = false;
/// <summary>
/// 寻找古树时,短距离移动,用于识别速度过慢的计算机使用
/// </summary>
[ObservableProperty]
private bool _walkToF = true;
[ObservableProperty] private bool _walkToF = false;
/// <summary>
/// 寻找古树时,短距离移动的次数
/// </summary>
[ObservableProperty]
private int _leftRightMoveTimes = 3;
/// <summary>
/// 自动吃药
/// </summary>
[ObservableProperty]
private bool _autoEat = false;
// 刷副本使用的队伍名称
[ObservableProperty]
private string _partyName = string.Empty;
// 需要刷取的副本名称
[ObservableProperty]
private string _domainName = string.Empty;
// 结束后是否自动分解圣遗物
[ObservableProperty]
private bool _autoArtifactSalvage = false;
// 分解圣遗物的最大星级
// 1~4
[ObservableProperty]
private string _maxArtifactStar = "4";
[ObservableProperty] private int _leftRightMoveTimes = 3;
}
@@ -9,37 +9,13 @@ public class AutoDomainParam : BaseTaskParam
public string CombatStrategyPath { get; set; }
// 刷副本使用的队伍名称
public string PartyName { get; set; } = string.Empty;
// 需要刷取的副本名称
public string DomainName { get; set; } = string.Empty;
// 结束后是否自动分解圣遗物
public bool AutoArtifactSalvage { get; set; } = false;
// 分解圣遗物的最大星级
// 1~4
public string MaxArtifactStar { get; set; } = "4";
public AutoDomainParam(int domainRoundNum, string path)
public AutoDomainParam(CancellationTokenSource cts, int domainRoundNum, string path) : base(cts)
{
DomainRoundNum = domainRoundNum;
if (domainRoundNum == 0)
{
DomainRoundNum = 9999;
}
CombatStrategyPath = path;
SetDefault();
}
public void SetDefault()
{
var config = TaskContext.Instance().Config.AutoDomainConfig;
PartyName = config.PartyName;
DomainName = config.DomainName;
AutoArtifactSalvage = config.AutoArtifactSalvage;
MaxArtifactStar = config.MaxArtifactStar;
}
}
}
@@ -10,9 +10,11 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoPick.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Compunet.YoloV8;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
@@ -21,25 +23,15 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Job;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.Kernel32;
using static Vanara.PInvoke.User32;
namespace BetterGenshinImpact.GameTask.AutoDomain;
public class AutoDomainTask : ISoloTask
public class AutoDomainTask
{
public string Name => "自动秘境";
private readonly AutoDomainParam _taskParam;
private readonly PostMessageSimulator _simulator;
@@ -50,15 +42,13 @@ public class AutoDomainTask : ISoloTask
private readonly CombatScriptBag _combatScriptBag;
private CancellationToken _ct;
public AutoDomainTask(AutoDomainParam taskParam)
{
_taskParam = taskParam;
_simulator = AutoFightContext.Instance.Simulator;
_predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(@"Assets\Model\Domain\bgi_tree.onnx"))
.UseOnnxModel(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
@@ -67,106 +57,96 @@ public class AutoDomainTask : ISoloTask
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
}
public async Task Start(CancellationToken ct)
public async void Start()
{
_ct = ct;
AutoFightAssets.DestroyInstance();
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build()); // TODO: 通知后续需要删除迁移
// 3次复活重试
for (int i = 0; i < 3; i++)
var hasLock = false;
try
{
try
AutoFightAssets.DestroyInstance();
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
{
await DoDomain();
// 其他场景不重试
break;
Logger.LogError("启动自动秘境功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
catch (Exception e)
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build());
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
// 前置进入秘境
EnterDomain();
for (var i = 0; i < _taskParam.DomainRoundNum; i++)
{
if (e.Message.Contains("复活") && !string.IsNullOrEmpty(_taskParam.DomainName))
// 0. 关闭秘境提示
Logger.LogDebug("0. 关闭秘境提示");
CloseDomainTip();
// 队伍没初始化成功则重试
RetryTeamInit(combatScenes);
// 0. 切换到第一个角色
var combatCommands = FindCombatScriptAndSwitchAvatar(combatScenes);
// 1. 走到钥匙处启动
Logger.LogInformation("自动秘境:{Text}", "1. 走到钥匙处启动");
await WalkToPressF();
// 2. 执行战斗(战斗线程、视角线程、检测战斗完成线程)
Logger.LogInformation("自动秘境:{Text}", "2. 执行战斗策略");
await StartFight(combatScenes, combatCommands);
EndFightWait();
// 3. 寻找石化古树 并左右移动直到石化古树位于屏幕中心
Logger.LogInformation("自动秘境:{Text}", "3. 寻找石化古树");
await FindPetrifiedTree();
// 4. 走到石化古树处
Logger.LogInformation("自动秘境:{Text}", "4. 走到石化古树处");
await WalkToPressF();
// 5. 快速领取奖励并判断是否有下一轮
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
{
Logger.LogWarning("自动秘境:{Text}", "复活后重试秘境...");
await Delay(2000, ct);
continue;
}
else
{
throw;
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());
}
}
await Delay(2000, ct);
await Bv.WaitForMainUi(_ct, 30);
await Delay(2000, ct);
await ArtifactSalvage();
}
private async Task DoDomain()
{
// 传送到秘境
await TpDomain();
// 切换队伍
await SwitchParty(_taskParam.PartyName);
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
// 前置进入秘境
EnterDomain();
for (var i = 0; i < _taskParam.DomainRoundNum; i++)
catch (NormalEndException e)
{
// 0. 关闭秘境提示
Logger.LogDebug("0. 关闭秘境提示");
CloseDomainTip();
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
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
TaskSettingsPageViewModel.SetSwitchAutoDomainButtonText(false);
Logger.LogInformation("→ {Text}", "自动秘境结束");
// 队伍没初始化成功则重试
RetryTeamInit(combatScenes);
// 0. 切换到第一个角色
var combatCommands = FindCombatScriptAndSwitchAvatar(combatScenes);
// 1. 走到钥匙处启动
Logger.LogInformation("自动秘境:{Text}", "1. 走到钥匙处启动");
await WalkToPressF();
// 2. 执行战斗(战斗线程、视角线程、检测战斗完成线程)
Logger.LogInformation("自动秘境:{Text}", "2. 执行战斗策略");
await StartFight(combatScenes, combatCommands);
EndFightWait();
// 3. 寻找石化古树 并左右移动直到石化古树位于屏幕中心
Logger.LogInformation("自动秘境:{Text}", "3. 寻找石化古树");
await FindPetrifiedTree();
// 4. 走到石化古树处
Logger.LogInformation("自动秘境:{Text}", "4. 走到石化古树处");
await WalkToPressF();
// 5. 快速领取奖励并判断是否有下一轮
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
if (hasLock)
{
if (i == _taskParam.DomainRoundNum - 1)
{
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
}
else
{
Logger.LogInformation("体力已经耗尽,结束自动秘境");
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Success().Build());
break;
TaskSemaphore.Release();
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Progress().Build());
}
}
@@ -175,12 +155,16 @@ public class AutoDomainTask : ISoloTask
LogScreenResolution();
if (_taskParam.DomainRoundNum == 9999)
{
Logger.LogInformation("→ {Text} 用尽所有体力后结束", "自动秘境,");
Logger.LogInformation("→ {Text} 用尽所有体力后结束", "自动秘境,启动!");
}
else
{
Logger.LogInformation("→ {Text} 设置总次数:{Cnt}", "自动秘境,", _taskParam.DomainRoundNum);
Logger.LogInformation("→ {Text} 设置总次数:{Cnt}", "自动秘境,启动!", _taskParam.DomainRoundNum);
}
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
}
private void LogScreenResolution()
@@ -188,9 +172,8 @@ public class AutoDomainTask : ISoloTask
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
{
Logger.LogError("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏无法正常使用自动秘境功能 !", 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);
@@ -209,65 +192,17 @@ public class AutoDomainTask : ISoloTask
}
}
private async Task TpDomain()
{
// 传送到秘境
if (!string.IsNullOrEmpty(_taskParam.DomainName))
{
if (MapLazyAssets.Instance.DomainPositionMap.TryGetValue(_taskParam.DomainName, out var domainPosition))
{
Logger.LogInformation("自动秘境:传送到秘境{Text}", _taskParam.DomainName);
await new TpTask(_ct).Tp(domainPosition.X, domainPosition.Y);
await Delay(1000, _ct);
await Bv.WaitForMainUi(_ct);
await Delay(1000, _ct);
var walkKey = User32.VK.VK_W;
if (MapLazyAssets.Instance.DomainBackwardList.Contains(_taskParam.DomainName))
{
walkKey = User32.VK.VK_S;
}
Simulation.SendInput.Keyboard.KeyDown(walkKey);
Thread.Sleep(3500);
Simulation.SendInput.Keyboard.KeyUp(walkKey);
}
else
{
Logger.LogError("自动秘境:未找到对应的秘境{Text}的传送点", _taskParam.DomainName);
throw new Exception($"未找到对应的秘境{_taskParam.DomainName}的传送点");
}
}
}
/// <summary>
/// 切换队伍
/// </summary>
/// <param name="partyName"></param>
/// <returns></returns>
private async Task<bool> SwitchParty(string? partyName)
{
if (!string.IsNullOrEmpty(partyName))
{
var b = await new SwitchPartyTask().Start(partyName, _ct);
await Delay(500, _ct);
return b;
}
return true;
}
private void EnterDomain()
{
var fightAssets = AutoFightContext.Instance.FightAssets;
// 进入秘境
using var fRectArea = CaptureToRectArea().Find(AutoPickAssets.Instance.FRo);
if (!fRectArea.IsEmpty())
{
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
Sleep(5000, _ct);
Sleep(5000, _taskParam.Cts);
}
int retryTimes = 0, clickCount = 0;
@@ -281,11 +216,11 @@ public class AutoDomainTask : ISoloTask
clickCount++;
}
Sleep(1500, _ct);
Sleep(1500, _taskParam.Cts);
}
// 载入动画
Sleep(3000, _ct);
Sleep(3000, _taskParam.Cts);
}
private void CloseDomainTip()
@@ -298,16 +233,16 @@ public class AutoDomainTask : ISoloTask
using var cactRectArea = CaptureToRectArea().Find(AutoFightContext.Instance.FightAssets.ClickAnyCloseTipRa);
if (!cactRectArea.IsEmpty())
{
Sleep(1000, _ct);
Sleep(1000, _taskParam.Cts);
cactRectArea.Click();
break;
}
// todo 添加小地图角标位置检测 防止有人手点了
Sleep(1000, _ct);
Sleep(1000, _taskParam.Cts);
}
Sleep(1500, _ct);
Sleep(1500, _taskParam.Cts);
}
private List<CombatCommand> FindCombatScriptAndSwitchAvatar(CombatScenes combatScenes)
@@ -324,7 +259,7 @@ public class AutoDomainTask : ISoloTask
/// </summary>
private async Task WalkToPressF()
{
if (_ct.IsCancellationRequested)
if (_taskParam.Cts.Token.IsCancellationRequested)
{
return;
}
@@ -341,12 +276,12 @@ public class AutoDomainTask : ISoloTask
try
{
while (!_ct.IsCancellationRequested)
while (!_taskParam.Cts.Token.IsCancellationRequested)
{
using var fRectArea = Common.TaskControl.CaptureToRectArea().Find(AutoPickAssets.Instance.FRo);
if (fRectArea.IsEmpty())
{
Sleep(100, _ct);
Sleep(100, _taskParam.Cts);
}
else
{
@@ -365,14 +300,14 @@ public class AutoDomainTask : ISoloTask
Simulation.SendInput.Keyboard.KeyUp(VK.VK_SHIFT);
}
}
}), _ct);
}));
}
private Task StartFight(CombatScenes combatScenes, List<CombatCommand> combatCommands)
{
CancellationTokenSource cts = new();
_ct.Register(cts.Cancel);
combatScenes.BeforeTask(cts.Token);
_taskParam.Cts.Token.Register(cts.Cancel);
combatScenes.BeforeTask(cts);
// 战斗操作
var combatTask = new Task(() =>
{
@@ -402,19 +337,20 @@ public class AutoDomainTask : ISoloTask
}
}, cts.Token);
// 视角操作
// 对局结束检测
var domainEndTask = DomainEndDetectionTask(cts);
// 自动吃药
var autoEatRecoveryHpTask = AutoEatRecoveryHpTask(cts.Token);
combatTask.Start();
domainEndTask.Start();
autoEatRecoveryHpTask.Start();
return Task.WhenAll(combatTask, domainEndTask, autoEatRecoveryHpTask);
return Task.WhenAll(combatTask, domainEndTask);
}
private void EndFightWait()
{
if (_ct.IsCancellationRequested)
if (_taskParam.Cts.Token.IsCancellationRequested)
{
return;
}
@@ -423,7 +359,7 @@ public class AutoDomainTask : ISoloTask
if (s > 0)
{
Logger.LogInformation("战斗结束后等待 {Second} 秒", s);
Sleep((int)(s * 1000), _ct);
Sleep((int)(s * 1000), _taskParam.Cts);
}
}
@@ -432,25 +368,19 @@ public class AutoDomainTask : ISoloTask
/// </summary>
private Task DomainEndDetectionTask(CancellationTokenSource cts)
{
return new Task(async () =>
return new Task(() =>
{
try
while (!_taskParam.Cts.Token.IsCancellationRequested)
{
while (!_ct.IsCancellationRequested)
if (IsDomainEnd())
{
if (IsDomainEnd())
{
await cts.CancelAsync();
break;
}
await Delay(1000, cts.Token);
cts.Cancel();
break;
}
Sleep(1000);
}
catch
{
}
}, cts.Token);
});
}
private bool IsDomainEnd()
@@ -476,64 +406,16 @@ public class AutoDomainTask : ISoloTask
return false;
}
private Task AutoEatRecoveryHpTask(CancellationToken ct)
{
return new Task(async () =>
{
if (!_config.AutoEat)
{
return;
}
if (!IsTakeFood())
{
Logger.LogInformation("未装备 “{Tool}”,不启用红血自动吃药功能", "便携营养袋");
return;
}
try
{
while (!_ct.IsCancellationRequested)
{
if (Bv.CurrentAvatarIsLowHp(CaptureToRectArea()))
{
// 模拟按键 "Z"
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_Z);
Logger.LogInformation("检测到红血,按Z吃药");
// TODO 吃饱了会一直吃
}
await Delay(500, ct);
}
}
catch (Exception e)
{
Logger.LogDebug(e, "红血自动吃药检测时发生异常");
}
}, ct);
}
private bool IsTakeFood()
{
// 获取图像
using var ra = CaptureToRectArea();
// 识别道具图标下是否是数字
var s = TaskContext.Instance().SystemInfo.AssetScale;
var countArea = ra.DeriveCrop(1800 * s, 845 * s, 40 * s, 20 * s);
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
return int.TryParse(count, out _);
}
/// <summary>
/// 旋转视角后寻找石化古树
/// </summary>
private Task FindPetrifiedTree()
{
CancellationTokenSource treeCts = new();
_ct.Register(treeCts.Cancel);
_taskParam.Cts.Token.Register(treeCts.Cancel);
// 中键回正视角
Simulation.SendInput.Mouse.MiddleButtonClick();
Sleep(900, _ct);
Sleep(900, _taskParam.Cts);
// 左右移动直到石化古树位于屏幕中心任务
var moveAvatarTask = MoveAvatarHorizontallyTask(treeCts);
@@ -555,7 +437,7 @@ public class AutoDomainTask : ISoloTask
var noDetectCount = 0;
var prevKey = VK.VK_A;
var backwardsAndForwardsCount = 0;
while (!_ct.IsCancellationRequested)
while (!_taskParam.Cts.Token.IsCancellationRequested)
{
var treeRect = DetectTree(CaptureToRectArea());
if (treeRect != Rect.Empty)
@@ -638,7 +520,7 @@ public class AutoDomainTask : ISoloTask
else
{
_simulator.KeyPress(VK.VK_W, 60);
Sleep(500, _ct);
Sleep(500, _taskParam.Cts);
treeCts.Cancel();
break;
}
@@ -683,12 +565,12 @@ public class AutoDomainTask : ISoloTask
{
// 左右移动5次说明已经在树中心了
_simulator.KeyPress(VK.VK_W, 60);
Sleep(500, _ct);
Sleep(500, _taskParam.Cts);
treeCts.Cancel();
break;
}
Sleep(60, _ct);
Sleep(60, _taskParam.Cts);
}
VisionContext.Instance().DrawContent.ClearAll();
@@ -728,12 +610,40 @@ public class AutoDomainTask : ISoloTask
while (!cts.Token.IsCancellationRequested)
{
using var captureRegion = CaptureToRectArea();
var angle = CameraOrientation.Compute(captureRegion.SrcMat);
var angle = CameraOrientation.Compute(captureRegion.SrcGreyMat);
CameraOrientation.DrawDirection(captureRegion, angle);
if (angle is >= 356 or <= 4)
{
// 算作对准了
continuousCount++;
}
if (angle < 180)
{
// 左移视角
var moveAngle = angle;
if (moveAngle > 2)
{
moveAngle *= 2;
}
Simulation.SendInput.Mouse.MoveMouseBy(-moveAngle, 0);
continuousCount = 0;
}
else if (angle is > 180 and < 360)
{
// 右移视角
var moveAngle = 360 - angle;
if (moveAngle > 2)
{
moveAngle *= 2;
}
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
continuousCount = 0;
}
else
{
// 360 度 东方向视角
if (continuousCount > 5)
{
@@ -744,33 +654,6 @@ public class AutoDomainTask : ISoloTask
}
}
}
else
{
continuousCount = 0;
}
if (angle <= 180)
{
// 左移视角
var moveAngle = (int)Math.Round(angle);
if (moveAngle > 2)
{
moveAngle *= 2;
}
Simulation.SendInput.Mouse.MoveMouseBy(-moveAngle, 0);
}
else if (angle is > 180 and < 360)
{
// 右移视角
var moveAngle = 360 - (int)Math.Round(angle);
if (moveAngle > 2)
{
moveAngle *= 2;
}
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
}
Sleep(100);
}
@@ -788,7 +671,7 @@ public class AutoDomainTask : ISoloTask
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
{
// 等待窗口弹出
Sleep(1500, _ct);
Sleep(1500, _taskParam.Cts);
// 优先使用浓缩树脂
var retryTimes = 0;
@@ -807,41 +690,27 @@ public class AutoDomainTask : ISoloTask
useCondensedResinRa.Click();
// 点两下 #224 #218
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
Sleep(400, _ct);
Sleep(400, _taskParam.Cts);
useCondensedResinRa.Click();
break;
}
Sleep(800, _ct);
Sleep(800, _taskParam.Cts);
}
Sleep(1000, _ct);
Sleep(1000, _taskParam.Cts);
var hasSkip = false;
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
for (var i = 0; i < 30; i++)
{
// 跳过领取动画
if (!hasSkip)
{
TaskContext.Instance().PostMessageSimulator.LeftButtonClick(); // 先随便点一个地方使得跳过出现
}
using var ra = CaptureToRectArea();
// OCR识别是否有跳过
var ocrList = ra.FindMulti(RecognitionObject.Ocr(captureArea.Width - 230 * assetScale, 0, 230 * assetScale - 5, 80 * assetScale));
var skipTextRa = ocrList.FirstOrDefault(t => t.Text.Contains("跳过"));
if (skipTextRa != null)
{
hasSkip = true;
skipTextRa.Click(); // 有则点击
}
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
Sleep(200, _taskParam.Cts);
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
// 优先点击继续
using var confirmRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
var ra = CaptureToRectArea();
var confirmRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
if (isLastTurn)
@@ -880,7 +749,7 @@ public class AutoDomainTask : ISoloTask
}
}
Sleep(300, _ct);
Sleep(300, _taskParam.Cts);
}
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
@@ -919,19 +788,4 @@ public class AutoDomainTask : ISoloTask
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 脆弱树脂 {FragileResinCount}", condensedResinCount, fragileResinCount);
return (condensedResinCount, fragileResinCount);
}
private async Task ArtifactSalvage()
{
if (!_taskParam.AutoArtifactSalvage)
{
return;
}
if (!int.TryParse(_taskParam.MaxArtifactStar, out var star))
{
star = 4;
}
await new ArtifactSalvageTask().Start(star, _ct);
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 607 B

@@ -9,8 +9,8 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
{
public Rect TeamRectNoIndex;
public Rect TeamRect;
public List<Rect> AvatarSideIconRectList; // 侧边栏角色头像 非联机状态下
public List<Rect> AvatarIndexRectList; // 侧边栏角色头像对应的白色块 非联机状态下
public List<Rect> AvatarSideIconRectList;
public List<Rect> AvatarIndexRectList;
public Rect ERect;
public Rect QRect;
public Rect EndTipsUpperRect; // 挑战达成提示
@@ -29,16 +29,6 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
public Dictionary<string, string> AvatarCostumeMap;
// 联机
public RecognitionObject OnePRa;
public RecognitionObject PRa;
public Dictionary<string, List<Rect>> AvatarSideIconRectListMap; // 侧边栏角色头像 联机状态下
public Dictionary<string, List<Rect>> AvatarIndexRectListMap; // 侧边栏角色头像对应的白色块 联机状态下
// 小道具位置
public Rect GadgetRect;
private AutoFightAssets()
{
TeamRectNoIndex = new Rect(CaptureRect.Width - (int)(355 * AssetScale), (int)(220 * AssetScale),
@@ -49,9 +39,6 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
(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));
// 小道具位置 1920-133,800,60,50
GadgetRect = new Rect(CaptureRect.Width - (int)(133 * AssetScale), (int)(800 * AssetScale),
(int)(60 * AssetScale), (int)(50 * AssetScale));
// 结束提示从中间开始找相对位置
EndTipsUpperRect = new Rect(CaptureRect.Width / 2 - (int)(100 * AssetScale), (int)(243 * AssetScale),
(int)(200 * AssetScale), (int)(50 * AssetScale));
@@ -92,78 +79,6 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
{ "Sea", "海风之梦" },
};
// 联机
// 1p_2 与 p_2 为同一位置
// 1p_4 与 p_4 为同一位置
AvatarSideIconRectListMap = new Dictionary<string, List<Rect>>
{
{
"1p_2", [
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(375 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(470 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
]
},
{
"1p_3", [
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(375 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(470 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
]
},
{ "1p_4", [new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(515 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale))] },
{
"p_2", [
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(375 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(470 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
]
},
{ "p_3", [new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(475 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale))] },
{ "p_4", [new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(515 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale))] },
};
AvatarIndexRectListMap = new Dictionary<string, List<Rect>>
{
{
"1p_2", [
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(412 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(508 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
]
},
{
"1p_3", [
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(459 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(555 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
]
},
{ "1p_4", [new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(552 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale))] },
{
"p_2", [
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(412 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(508 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
]
},
{ "p_3", [new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(412 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale))] },
{ "p_4", [new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(507 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale))] },
};
// 左上角的 1P 图标
OnePRa = new RecognitionObject
{
Name = "1P",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "1p.png"),
RegionOfInterest = new Rect(0, 0, CaptureRect.Width / 4, CaptureRect.Height / 7),
DrawOnWindow = false
}.InitTemplate();
// 右侧联机的 P 图标
PRa = new RecognitionObject
{
Name = "P",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "p.png"),
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 7, CaptureRect.Height / 5, CaptureRect.Width / 7, CaptureRect.Height / 2 - CaptureRect.Width / 7),
DrawOnWindow = false
}.InitTemplate();
WandererIconRa = new RecognitionObject
{
Name = "WandererIcon",
File diff suppressed because it is too large. Load diff
@@ -3,10 +3,6 @@ using System;
namespace BetterGenshinImpact.GameTask.AutoFight;
/// <summary>
/// 自动战斗配置
/// </summary>
@@ -19,70 +15,4 @@ public partial class AutoFightConfig : ObservableObject
/// 英文逗号分割 强制指定队伍角色
/// </summary>
[ObservableProperty] private string _teamNames = "";
/// <summary>
/// 检测战斗结束
/// </summary>
[ObservableProperty]
private bool _fightFinishDetectEnabled = true;
[Serializable]
public partial class FightFinishDetectConfig : ObservableObject
{
/// <summary>
/// 判断战斗结束读条颜色,不同帧率可能下会有些不同,默认为95,235,255
/// </summary>
[ObservableProperty]
private string _battleEndProgressBarColor = "";
/// <summary>
/// 对于上方颜色地偏差值,即±某个值,例如 6或6,6,6,前者表示所有偏差值都一样,后者则可以分别设置
/// </summary>
[ObservableProperty]
private string _battleEndProgressBarColorTolerance = "";
/// <summary>
/// 快速检查战斗结束,在一轮脚本中,可以每隔一定秒数(默认为5)或指定角色操作后,去检查(在每个角色完成该轮脚本时)。
/// </summary>
[ObservableProperty]
private bool _fastCheckEnabled = false;
/// <summary>
/// 快速检查战斗结束的参数,可填入数字和人名,多种用分号分隔,例如:15,白术;钟离;,如果是数字(小于等于0则不会根据时间去检查),则指定检查间隔,如果是人名,则该角色执行一轮操作后进行检查。同时每轮结束后检查不变。
/// </summary>
[ObservableProperty]
private string _fastCheckParams = "";
/// <summary>
/// 检查战斗结束的延时,即角色,默认为1.5秒。也可以指定特定角色之后延时多少时间检查。格式如:2.5;白术,1.5;钟离,1.0;
/// </summary>
[ObservableProperty]
private string _checkEndDelay = "";
}
/// <summary>
/// 战斗结束相关配置
/// </summary>
[ObservableProperty]
private FightFinishDetectConfig _finishDetectConfig = new();
/// <summary>
/// 检测战斗结束,默认为每轮脚本后检查
/// </summary>
[ObservableProperty]
private bool _pickDropsAfterFightEnabled = true;
/// <summary>
/// 战斗结束后,如果存在枫原万叶,则使用该角色捡材料
/// </summary>
[ObservableProperty]
private bool _kazuhaPickupEnabled = true;
/// <summary>
/// 战斗超时,单位秒
/// </summary>
[ObservableProperty]
private int _timeout = 120;
}
}
@@ -1,52 +1,14 @@
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoFight;
public class AutoFightParam : BaseTaskParam
{
public class FightFinishDetectConfig
{
public string BattleEndProgressBarColor { get; set; }= "";
public string BattleEndProgressBarColorTolerance { get; set; }= "";
public bool FastCheckEnabled = false;
public string FastCheckParams = "";
public string CheckEndDelay = "";
}
public AutoFightParam(string path, AutoFightConfig autoFightConfig)
{
CombatStrategyPath = path;
Timeout = autoFightConfig.Timeout;
FightFinishDetectEnabled = autoFightConfig.FightFinishDetectEnabled;
PickDropsAfterFightEnabled = autoFightConfig.PickDropsAfterFightEnabled;
KazuhaPickupEnabled = autoFightConfig.KazuhaPickupEnabled;
FinishDetectConfig.FastCheckEnabled = autoFightConfig.FinishDetectConfig.FastCheckEnabled;
FinishDetectConfig.FastCheckParams = autoFightConfig.FinishDetectConfig.FastCheckParams;
FinishDetectConfig.CheckEndDelay = autoFightConfig.FinishDetectConfig.CheckEndDelay;
//下面参数固定,只取自动战斗里面的
FinishDetectConfig.BattleEndProgressBarColor = TaskContext.Instance().Config.AutoFightConfig.FinishDetectConfig.BattleEndProgressBarColor;
FinishDetectConfig.BattleEndProgressBarColorTolerance = TaskContext.Instance().Config.AutoFightConfig.FinishDetectConfig.BattleEndProgressBarColorTolerance;
}
public FightFinishDetectConfig FinishDetectConfig { get; set; } = new();
public string CombatStrategyPath { get; set; }
public bool FightFinishDetectEnabled { get; set; } = false;
public bool PickDropsAfterFightEnabled { get; set; } = false;
public int Timeout { get; set; } = 120;
public bool KazuhaPickupEnabled = true;
}
public AutoFightParam(CancellationTokenSource cts, string path) : base(cts)
{
CombatStrategyPath = path;
}
}
@@ -1,345 +1,107 @@
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.Common.Job;
using OpenCvSharp;
using Vanara;
using Vanara.PInvoke;
namespace BetterGenshinImpact.GameTask.AutoFight;
public class AutoFightTask : ISoloTask
public class AutoFightTask
{
public string Name => "自动战斗";
private readonly AutoFightParam _taskParam;
private readonly CombatScriptBag _combatScriptBag;
private CancellationToken _ct;
private readonly BgiYoloV8Predictor _predictor;
private DateTime _lastFightFlagTime = DateTime.Now; // 战斗标志最近一次出现的时间
private readonly double _dpi = TaskContext.Instance().DpiScale;
private class TaskFightFinishDetectConfig
{
public int DelayTime=1500;
public Dictionary<string, int> DelayTimes = new();
public double CheckTime = 5;
public List<string> CheckNames = new();
public bool FastCheckEnabled;
public TaskFightFinishDetectConfig(AutoFightParam.FightFinishDetectConfig finishDetectConfig)
{
FastCheckEnabled=finishDetectConfig.FastCheckEnabled;
ParseCheckTimeString(finishDetectConfig.FastCheckParams,out CheckTime,CheckNames);
ParseFastCheckEndDelayString(finishDetectConfig.CheckEndDelay,out DelayTime,DelayTimes);
BattleEndProgressBarColor = ParseStringToTuple(finishDetectConfig.BattleEndProgressBarColor, (95, 235, 255));
BattleEndProgressBarColorTolerance = ParseSingleOrCommaSeparated(finishDetectConfig.BattleEndProgressBarColorTolerance, (6, 6, 6));
}
public (int, int, int) BattleEndProgressBarColor{ get; }
public (int, int, int) BattleEndProgressBarColorTolerance{ get; }
public static void ParseCheckTimeString(
string input,
out double checkTime,
List<string> names)
{
checkTime = 5;
if (string.IsNullOrEmpty(input))
{
return; // 直接返回
}
var uniqueNames = new HashSet<string>(); // 用于临时去重的集合
// 按分号分割字符串
var segments = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in segments)
{
var trimmedSegment = segment.Trim();
// 如果是纯数字部分
if (double.TryParse(trimmedSegment, NumberStyles.Float, CultureInfo.InvariantCulture, out double number))
{
checkTime = number * 1000; // 更新 CheckTime
}
else if (!uniqueNames.Contains(trimmedSegment)) // 如果是非数字且不重复
{
uniqueNames.Add(trimmedSegment); // 添加到集合
}
}
names.AddRange(uniqueNames); // 将集合转换为列表
}
public static void ParseFastCheckEndDelayString(
string input,
out int delayTime,
Dictionary<string, int> nameDelayMap)
{
delayTime = 1500;
if (string.IsNullOrEmpty(input))
{
return; // 直接返回
}
// 分割字符串,以分号为分隔符
var segments = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in segments)
{
var parts = segment.Split(',');
// 如果是纯数字部分
if (parts.Length == 1)
{
if (double.TryParse(parts[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double number))
{
delayTime = (int)(number * 1000); // 更新 delayTime
}
}
// 如果是名字,数字格式
else if (parts.Length == 2)
{
string name = parts[0].Trim();
if (double.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double value))
{
nameDelayMap[name] = (int)(value * 1000); // 更新字典,取最后一个值
}
}
// 其他格式,跳过不处理
}
}
static bool IsSingleNumber(string input, out int result)
{
return int.TryParse(input, out result);
}
static (int, int, int) ParseSingleOrCommaSeparated(string input, (int, int, int) defaultValue)
{
// 如果是单个数字
if (IsSingleNumber(input, out var singleNumber))
{
return (singleNumber, singleNumber, singleNumber);
}
return ParseStringToTuple(input, defaultValue);
}
static (int, int, int) ParseStringToTuple(string input, (int, int, int) defaultValue)
{
// 尝试按逗号分割字符串
var parts = input.Split(',');
if (parts.Length == 3 &&
int.TryParse(parts[0], out var num1) &&
int.TryParse(parts[1], out var num2) &&
int.TryParse(parts[2], out var num3))
{
return (num1, num2, num3);
}
// 如果解析失败,返回默认值
return defaultValue;
}
}
private TaskFightFinishDetectConfig _finishDetectConfig;
public AutoFightTask(AutoFightParam taskParam)
{
_taskParam = taskParam;
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
if (_taskParam.FightFinishDetectEnabled)
{
_predictor = BgiYoloV8PredictorFactory.GetPredictor(@"Assets\Model\World\bgi_world.onnx");
}
_finishDetectConfig=new TaskFightFinishDetectConfig(_taskParam.FinishDetectConfig);
}
// 方法1:判断是否是单个数字
/*public int delayTime=1500;
public Dictionary<string, int> delayTimes = new();
public double checkTime = 5;
public List<string> checkNames = new();*/
public async Task Start(CancellationToken ct)
public async void Start()
{
_ct = ct;
var hasLock = false;
try
{
AutoFightAssets.DestroyInstance();
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
{
Logger.LogError("启动自动战斗功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
Init();
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
if (!combatScenes.CheckTeamInitialized())
{
throw new Exception("识别队伍角色失败");
}
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
combatScenes.BeforeTask(_taskParam.Cts);
// 战斗操作
await Task.Run(() =>
{
try
{
while (!_taskParam.Cts.Token.IsCancellationRequested)
{
// 通用化战斗策略
foreach (var command in combatCommands)
{
command.Execute(combatScenes);
}
}
}
catch (NormalEndException)
{
Logger.LogInformation("战斗操作结束");
}
catch (Exception e)
{
Logger.LogWarning(e.Message);
throw;
}
});
}
catch (NormalEndException)
{
Logger.LogInformation("手动中断自动战斗");
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
TaskSettingsPageViewModel.SetSwitchAutoFightButtonText(false);
Logger.LogInformation("→ {Text}", "自动战斗结束");
if (hasLock)
{
TaskSemaphore.Release();
}
}
}
private void Init()
{
LogScreenResolution();
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
if (!combatScenes.CheckTeamInitialized())
{
throw new Exception("识别队伍角色失败");
}
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
// 新的取消token
var cts2 = new CancellationTokenSource();
ct.Register(cts2.Cancel);
combatScenes.BeforeTask(cts2.Token);
TimeSpan fightTimeout = TimeSpan.FromSeconds(_taskParam.Timeout); // 战斗超时时间
Stopwatch timeoutStopwatch = Stopwatch.StartNew();
Stopwatch checkFightFinishStopwatch = Stopwatch.StartNew();
TimeSpan checkFightFinishTime = TimeSpan.FromSeconds(_finishDetectConfig.CheckTime); //检查战斗超时时间的超时时间
//战斗前检查,可做成配置
/* if (await CheckFightFinish()) {
return;
}*/
var fightEndFlag = false;
// 战斗操作
var fightTask = Task.Run(async () =>
{
try
{
while (!cts2.Token.IsCancellationRequested)
{
// 通用化战斗策略
for (var i = 0; i < combatCommands.Count; i++)
{
var command = combatCommands[i];
if (timeoutStopwatch.Elapsed > fightTimeout)
{
Logger.LogInformation("战斗超时结束");
fightEndFlag = true;
break;
}
command.Execute(combatScenes);
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true } )
{
//处于最后一个位置,或者当前执行人和下一个人名字不一样的情况,满足一定条件(开启快速检查,并且检查时间大于0或人名存在配置)检查战斗
if (i==combatCommands.Count - 1
|| ((
_finishDetectConfig.FastCheckEnabled && command.Name!=combatCommands[i+1].Name &&
(_finishDetectConfig.CheckTime>0 && checkFightFinishStopwatch.Elapsed>checkFightFinishTime)
|| _finishDetectConfig.CheckNames.Contains(command.Name)
) ))
{
checkFightFinishStopwatch.Restart();
var delayTime = _finishDetectConfig.DelayTime;
if (_finishDetectConfig.DelayTimes.TryGetValue(command.Name, out var time))
{
delayTime = time;
Logger.LogInformation($"{command.Name}结束后,延时检查为{delayTime}毫秒");
}
else
{
Logger.LogInformation($"延时检查为{delayTime}毫秒");
}
fightEndFlag = await CheckFightFinish(delayTime);
}
}
if (fightEndFlag)
{
break;
}
}
if (fightEndFlag)
{
break;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
throw;
}
}, cts2.Token);
await fightTask;
// 战斗结束检测线程
// var endTask = Task.Run(async () =>
// {
// if (!_taskParam.FightFinishDetectEnabled)
// {
// return;
// }
//
// try
// {
// while (!cts2.IsCancellationRequested)
// {
// var finish = await CheckFightFinish();
// if (finish)
// {
// await cts2.CancelAsync();
// break;
// }
//
// Sleep(1000, cts2.Token);
// }
// }
// catch (Exception e)
// {
// Debug.WriteLine(e.Message);
// Debug.WriteLine(e.StackTrace);
// }
// }, cts2.Token);
//
// await Task.WhenAll(fightTask, endTask);
if (_taskParam.KazuhaPickupEnabled)
{
// 队伍中存在万叶的时候使用一次长E
var kazuha = combatScenes.Avatars.FirstOrDefault(a => a.Name == "枫原万叶");
if (kazuha != null)
{
Logger.LogInformation("使用枫原万叶长E拾取掉落物");
var time = DateTime.UtcNow - kazuha.LastSkillTime;
if (time.TotalMilliseconds > 0 && time.TotalSeconds <= kazuha.SkillHoldCd)
{
Logger.LogInformation("枫原万叶长E技能可能处于冷却中,等待 {Time} s",time.TotalSeconds);
await Delay((int)Math.Ceiling(time.TotalMilliseconds), ct);
}
kazuha.UseSkill(true);
}
}
if (_taskParam is { PickDropsAfterFightEnabled: true })
{
// 执行自动拾取掉落物的功能
await new ScanPickTask().Start(ct);
}
Logger.LogInformation("→ {Text}", "自动战斗,启动!");
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
}
private void LogScreenResolution()
@@ -350,92 +112,4 @@ public class AutoFightTask : ISoloTask
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
}
}
static bool AreDifferencesWithinBounds((int, int, int) a, (int, int, int) b, (int, int, int) c)
{
// 计算每个位置的差值绝对值并进行比较
return Math.Abs(a.Item1 - b.Item1) < c.Item1 &&
Math.Abs(a.Item2 - b.Item2) < c.Item2 &&
Math.Abs(a.Item3 - b.Item3) < c.Item3;
}
private async Task<bool> CheckFightFinish(int delayTime=1500)
{
// YOLO 判断血条和怪物位置
// if (HasFightFlagByYolo(CaptureToRectArea()))
// {
// _lastFightFlagTime = DateTime.Now;
// return false;
// }
//
//Random random = new Random();
//double randomFraction = random.NextDouble(); // 生成 0 到 1 之间的随机小数
//此处随机数,防止固定招式下,使按L正好处于招式下,导致无法准确判断战斗结束
// double randomNumber = 1 + (randomFraction * (3 - 1));
// 几秒内没有检测到血条和怪物位置,则开始旋转视角重新检测
//if ((DateTime.Now - _lastFightFlagTime).TotalSeconds > randomNumber)
//{
// 旋转完毕后都没有检测到血条和怪物位置,则按L键确认战斗结束
/**
Simulation.SendInput.Mouse.MiddleButtonClick();
await Delay(300, _ct);
for (var i = 0; i < 8; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy((int)(500 * _dpi), 0);
await Delay(800, _ct); // 等待视角稳定
if (HasFightFlagByYolo(CaptureToRectArea()))
{
_lastFightFlagTime = DateTime.Now;
return false;
}
}
**/
await Delay(delayTime, _ct);
Logger.LogInformation("按L检查战斗是否结束");
// 最终方案确认战斗结束
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_L);
await Delay(450, _ct);
var ra = CaptureToRectArea();
var b3 = ra.SrcMat.At<Vec3b>(50, 790);
if (AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance))
{
Logger.LogInformation("识别到战斗结束");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
return true;
}
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Logger.LogInformation($"未识别到战斗结束{b3.Item0},{b3.Item1},{b3.Item2}");
_lastFightFlagTime = DateTime.Now;
return false;
// }
return false;
}
private bool HasFightFlagByYolo(ImageRegion imageRegion)
{
// if (RuntimeHelper.IsDebug)
// {
// imageRegion.SrcMat.SaveImage(Global.Absolute(@"log\fight\" + $"{DateTime.Now:yyyyMMdd_HHmmss_ffff}.png"));
// }
var dict = _predictor.Detect(imageRegion);
return dict.ContainsKey("health_bar") || dict.ContainsKey("enemy_identify");
}
// 无用
// [Obsolete]
// private bool HasFightFlagByGadget(ImageRegion imageRegion)
// {
// // 小道具位置 1920-133,800,60,50
// var gadgetMat = imageRegion.DeriveCrop(AutoFightAssets.Instance.GadgetRect).SrcMat;
// var list = ContoursHelper.FindSpecifyColorRects(gadgetMat, new Scalar(225, 220, 225), new Scalar(255, 255, 255));
// // 要大于 gadgetMat 的 1/2
// return list.Any(r => r.Width > gadgetMat.Width / 2 && r.Height > gadgetMat.Height / 2);
// }
}
}
@@ -18,7 +18,7 @@ public class DefaultAutoFightConfig
static DefaultAutoFightConfig()
{
var json = File.ReadAllText(Global.Absolute(@"GameTask\AutoFight\Assets\combat_avatar.json"));
var config = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CombatAvatar>>(json);
var config = JsonSerializer.Deserialize<List<CombatAvatar>>(json, ConfigService.JsonOptions);
CombatAvatars = config ?? throw new Exception("combat_avatar.json deserialize failed");
CombatAvatarNames = config.Select(x => x.Name).ToList();
CombatAvatarMap = config.ToDictionary(x => x.Name);
@@ -1,5 +1,4 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Config;
@@ -8,11 +7,8 @@ using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -52,11 +48,6 @@ public class Avatar
/// 长按元素战技CD
/// </summary>
public double SkillHoldCd { get; set; }
/// <summary>
/// 最近一次使用元素战技的时间
/// </summary>
public DateTime LastSkillTime { get; set; }
/// <summary>
/// 元素爆发CD
@@ -81,7 +72,7 @@ public class Avatar
/// <summary>
/// 任务取消令牌
/// </summary>
public CancellationToken Ct { get; set; }
public CancellationTokenSource? Cts { get; set; }
/// <summary>
/// 战斗场景
@@ -111,18 +102,13 @@ public class Avatar
/// <returns></returns>
public void ThrowWhenDefeated(ImageRegion region)
{
if (Bv.IsInRevivePrompt(region))
using var confirmRectArea = region.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
Logger.LogWarning("检测到复苏界面,存在角色被击败,前往七天神像复活");
// 先打开地图
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
Sleep(600, Ct);
Sleep(600, Cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
// tp 到七天神像复活
var tpTask = new TpTask(Ct);
tpTask.Tp(TpTask.ReviveStatueOfTheSevenPointX, TpTask.ReviveStatueOfTheSevenPointY, true).Wait(Ct);
throw new Exception("检测到复苏界面,存在角色被击败,前往七天神像复活");
throw new Exception("存在角色被击败,按 M 键打开地图,并停止自动秘境。");
}
}
@@ -134,7 +120,7 @@ public class Avatar
{
for (var i = 0; i < 30; i++)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
@@ -143,55 +129,18 @@ public class Avatar
ThrowWhenDefeated(region);
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
if (IsActive(region) && notActiveCount == 3)
{
return;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
// Debug.WriteLine($"切换到{Index}号位");
// Cv2.ImWrite($"log/切换.png", region.SrcMat);
Sleep(250, Ct);
// Cv2.ImWrite($"log/切换.png", content.CaptureRectArea.SrcMat);
Sleep(250, Cts);
}
}
/// <summary>
/// 尝试切换到本角色
/// </summary>
/// <param name="tryTimes"></param>
/// <param name="needLog"></param>
/// <returns></returns>
public bool TrySwitch(int tryTimes = 4, bool needLog = true)
{
for (var i = 0; i < 3; i++)
{
if (Ct is { IsCancellationRequested: true })
{
return false;
}
var region = CaptureToRectArea();
ThrowWhenDefeated(region);
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
{
if (needLog && i > 0)
{
Logger.LogInformation("成功切换角色:{Name}", Name);
}
return true;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
Sleep(250, Ct);
}
return false;
}
/// <summary>
/// 切换到本角色
/// 切换cd是1秒,如果切换失败,会尝试再次切换,最多尝试5次
@@ -299,14 +248,14 @@ public class Avatar
{
while (ms >= 0)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
AutoFightContext.Instance.Simulator.LeftButtonClick();
ms -= 200;
Sleep(200, Ct);
Sleep(200, Cts);
}
}
@@ -317,7 +266,7 @@ public class Avatar
{
for (var i = 0; i < 1; i++)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
@@ -327,7 +276,7 @@ public class Avatar
if (Name == "纳西妲")
{
AutoFightContext.Instance.Simulator.KeyDown(User32.VK.VK_E);
Sleep(300, Ct);
Sleep(300, Cts);
for (int j = 0; j < 10; j++)
{
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
@@ -337,12 +286,6 @@ public class Avatar
Sleep(300); // 持续操作不应该被cts取消
AutoFightContext.Instance.Simulator.KeyUp(User32.VK.VK_E);
}
else if (Name == "坎蒂丝")
{
AutoFightContext.Instance.Simulator.KeyDown(User32.VK.VK_E);
Thread.Sleep(3000);
AutoFightContext.Instance.Simulator.KeyUp(User32.VK.VK_E);
}
else
{
AutoFightContext.Instance.Simulator.LongKeyPress(User32.VK.VK_E);
@@ -353,7 +296,7 @@ public class Avatar
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_E);
}
Sleep(200, Ct);
Sleep(200, Cts);
var region = CaptureToRectArea();
ThrowWhenDefeated(region);
@@ -362,7 +305,6 @@ public class Avatar
{
Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd}" : "{Name} 点按元素战技,cd:{Cd}", Name, cd);
// todo 把cd加入执行队列
LastSkillTime = DateTime.UtcNow;
return;
}
}
@@ -389,13 +331,13 @@ public class Avatar
// var isBurstReleased = false;
for (var i = 0; i < 10; i++)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_Q);
Sleep(200, Ct);
Sleep(200, Cts);
var region = CaptureToRectArea();
ThrowWhenDefeated(region);
@@ -403,7 +345,7 @@ public class Avatar
if (notActiveCount == 0)
{
// isBurstReleased = true;
Sleep(1500, Ct);
Sleep(1500, Cts);
return;
}
// else
@@ -439,7 +381,7 @@ public class Avatar
/// </summary>
public void Dash(int ms = 0)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
@@ -456,7 +398,7 @@ public class Avatar
public void Walk(string key, int ms)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
@@ -528,16 +470,15 @@ public class Avatar
if (Name == "那维莱特")
{
var dpi = TaskContext.Instance().DpiScale;
AutoFightContext.Instance.Simulator.LeftButtonDown();
while (ms >= 0)
{
if (Ct is { IsCancellationRequested: true })
if (Cts is { IsCancellationRequested: true })
{
return;
}
Simulation.SendInput.Mouse.MoveMouseBy((int)(1000 * dpi), 0);
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
ms -= 50;
Sleep(50); // 持续操作不应该被cts取消
}
@@ -31,7 +31,7 @@ public class CombatScenes : IDisposable
/// <summary>
/// 当前配队
/// </summary>
public Avatar[] Avatars { get; set; } = Array.Empty<Avatar>();
public Avatar[] Avatars { get; set; } = new Avatar[1];
public Dictionary<string, Avatar> AvatarMap { get; set; } = [];
@@ -39,12 +39,10 @@ public class CombatScenes : IDisposable
private readonly YoloV8Predictor _predictor =
YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(@"Assets\Model\Common\avatar_side_classify_sim.onnx"))
.UseOnnxModel(Global.Absolute("Assets\\Model\\Common\\avatar_side_classify_sim.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
public int ExpectedTeamAvatarNum { get; private set; } = 4;
/// <summary>
/// 通过YOLO分类器识别队伍内角色
/// </summary>
@@ -58,49 +56,14 @@ public class CombatScenes : IDisposable
return this;
}
// 判断当前是否处于联机状态
List<Rect> avatarSideIconRectList;
List<Rect> avatarIndexRectList;
var pRaList = imageRegion.FindMulti(AutoFightAssets.Instance.PRa);
if (pRaList.Count > 0)
{
var num = pRaList.Count + 1;
if (num > 4)
{
throw new Exception("当前处于联机状态,但是队伍人数超过4人,无法识别");
}
// 联机状态下判断
var onePRa = imageRegion.Find(AutoFightAssets.Instance.OnePRa);
var p = "p";
if (!onePRa.IsEmpty())
{
Logger.LogInformation("当前处于联机状态,且当前账号是房主,联机人数{Num}人", num);
p = "1p";
}
else
{
Logger.LogInformation("当前处于联机状态,且在别人世界中,联机人数{Num}人", num);
}
avatarSideIconRectList = AutoFightAssets.Instance.AvatarSideIconRectListMap[$"{p}_{num}"];
avatarIndexRectList = AutoFightAssets.Instance.AvatarIndexRectListMap[$"{p}_{num}"];
ExpectedTeamAvatarNum = avatarSideIconRectList.Count;
}
else
{
avatarSideIconRectList = AutoFightAssets.Instance.AvatarSideIconRectList;
avatarIndexRectList = AutoFightAssets.Instance.AvatarIndexRectList;
}
// 识别队伍
var names = new string[avatarSideIconRectList.Count];
var displayNames = new string[avatarSideIconRectList.Count];
var names = new string[4];
var displayNames = new string[4];
try
{
for (var i = 0; i < avatarSideIconRectList.Count; i++)
for (var i = 0; i < AutoFightAssets.Instance.AvatarSideIconRectList.Count; i++)
{
var ra = imageRegion.DeriveCrop(avatarSideIconRectList[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))
@@ -118,16 +81,14 @@ public class CombatScenes : IDisposable
displayNames[i] = pair.Item1;
}
}
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
Avatars = BuildAvatars([.. names], null, avatarIndexRectList);
Avatars = BuildAvatars([.. names]);
AvatarMap = Avatars.ToDictionary(x => x.Name);
}
catch (Exception e)
{
Logger.LogWarning(e.Message);
}
return this;
}
@@ -163,7 +124,7 @@ public class CombatScenes : IDisposable
if (result.TopClass.Name.Name.StartsWith("Qin") || result.TopClass.Name.Name.Contains("Costume"))
{
// 降低琴和衣装角色的识别率要求
if (result.TopClass.Confidence < 0.51)
if (result.TopClass.Confidence < 0.6)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
@@ -203,7 +164,7 @@ public class CombatScenes : IDisposable
public bool CheckTeamInitialized()
{
if (Avatars.Length != ExpectedTeamAvatarNum)
if (Avatars.Length < 4)
{
return false;
}
@@ -211,18 +172,8 @@ public class CombatScenes : IDisposable
return true;
}
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null, List<Rect>? avatarIndexRectList = null)
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null)
{
if (avatarIndexRectList == null && ExpectedTeamAvatarNum == 4)
{
avatarIndexRectList = AutoFightContext.Instance.FightAssets.AvatarIndexRectList;
}
if (avatarIndexRectList == null)
{
throw new Exception("联机状态下,此方法必须传入队伍角色编号位置信息");
}
AvatarCount = names.Count;
var avatars = new Avatar[AvatarCount];
for (var i = 0; i < AvatarCount; i++)
@@ -230,24 +181,24 @@ public class CombatScenes : IDisposable
var nameRect = nameRects?[i] ?? Rect.Empty;
avatars[i] = new Avatar(this, names[i], i + 1, nameRect)
{
IndexRect = avatarIndexRectList[i]
IndexRect = AutoFightContext.Instance.FightAssets.AvatarIndexRectList[i]
};
}
return avatars;
}
public void BeforeTask(CancellationToken ct)
public void BeforeTask(CancellationTokenSource cts)
{
for (var i = 0; i < AvatarCount; i++)
{
Avatars[i].Ct = ct;
Avatars[i].Cts = cts;
}
}
public Avatar? SelectAvatar(string name)
{
return AvatarMap.GetValueOrDefault(name);
return AvatarMap.TryGetValue(name, out var avatar) ? avatar : null;
}
#region OCR识别队伍(已弃用)
@@ -53,7 +53,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
if (_cts == null || _cts.Token.IsCancellationRequested)
{
_cts = new CancellationTokenSource();
_fightTask = FightTask(_cts.Token);
_fightTask = FightTask(_cts);
if (!_fightTask.IsCompleted)
{
_fightTask.Start();
@@ -65,7 +65,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
if (_cts == null || _cts.Token.IsCancellationRequested)
{
_cts = new CancellationTokenSource();
_fightTask = FightTask(_cts.Token);
_fightTask = FightTask(_cts);
if (!_fightTask.IsCompleted)
{
_fightTask.Start();
@@ -126,14 +126,14 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
/// <summary>
/// 循环执行战斗宏
/// </summary>
private Task FightTask(CancellationToken ct)
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, ct); // 等待缓存图像
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, cts); // 等待缓存图像
}
var imageRegion = CaptureToRectArea();
@@ -162,7 +162,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
return new Task(() =>
{
Logger.LogInformation("→ {Name}执行宏", activeAvatar.Name);
while (!ct.IsCancellationRequested && IsEnabled())
while (!cts.Token.IsCancellationRequested && IsEnabled())
{
if (IsHoldOnMode() && !_isKeyDown)
{
@@ -64,22 +64,12 @@ public class CombatCommand
public void Execute(CombatScenes combatScenes)
{
// 如果是当前角色
Avatar? avatar;
if (Name == CombatScriptParser.CurrentAvatarName)
{
avatar = combatScenes.Avatars[0]; // 随便取一个角色
}
else
{
avatar = combatScenes.SelectAvatar(Name);
}
var avatar = combatScenes.SelectAvatar(Name);
if (avatar == null)
{
return;
}
// 非宏类脚本,等待切换角色成功
if (Method != Method.Wait
&& Method != Method.MouseDown
@@ -245,4 +235,4 @@ public class CombatCommand
throw new NotImplementedException();
}
}
}
}
@@ -10,8 +10,6 @@ namespace BetterGenshinImpact.GameTask.AutoFight.Script;
public class CombatScriptParser
{
public static string CurrentAvatarName = "当前角色";
public static CombatScriptBag ReadAndParse(string path)
{
if (File.Exists(path))
@@ -52,15 +50,7 @@ public class CombatScriptParser
public static CombatScript Parse(string path)
{
var script = File.ReadAllText(path);
var combatScript = ParseContext(script);
combatScript.Path = path;
combatScript.Name = Path.GetFileNameWithoutExtension(path);
return combatScript;
}
public static CombatScript ParseContext(string context, bool validate = true)
{
var lines = context.Split(["\r\n", "\r", "\n", ";"], StringSplitOptions.RemoveEmptyEntries);
var lines = script.Split(["\r\n", "\r", "\n", ";"], StringSplitOptions.RemoveEmptyEntries);
var result = new List<string>();
foreach (var line in lines)
{
@@ -76,16 +66,19 @@ public class CombatScriptParser
result.Add(l);
}
return ParseLines(result, validate);
var combatScript = Parse(result);
combatScript.Path = path;
combatScript.Name = Path.GetFileNameWithoutExtension(path);
return combatScript;
}
private static CombatScript ParseLines(List<string> lines, bool validate = true)
public static CombatScript Parse(List<string> lines)
{
List<CombatCommand> combatCommands = [];
HashSet<string> combatAvatarNames = [];
foreach (var line in lines)
{
var oneLineCombatCommands = ParseLine(line, combatAvatarNames, validate);
var oneLineCombatCommands = ParseLine(line, combatAvatarNames);
combatCommands.AddRange(oneLineCombatCommands);
}
@@ -95,29 +88,20 @@ public class CombatScriptParser
return new CombatScript(combatAvatarNames, combatCommands);
}
private static List<CombatCommand> ParseLine(string line, HashSet<string> combatAvatarNames, bool validate = true)
public static List<CombatCommand> ParseLine(string line, HashSet<string> combatAvatarNames)
{
var oneLineCombatCommands = new List<CombatCommand>();
// 以空格分隔角色和指令 截取第一个空格前的内容为角色名称,后面的为指令
// 20241116更新 不输入角色名称时,直接以当前角色为准
var firstSpaceIndex = line.IndexOf(' ');
var character = CurrentAvatarName;
var commands = line;
if (firstSpaceIndex > 0)
if (firstSpaceIndex < 0)
{
character = line[..firstSpaceIndex];
character = DefaultAutoFightConfig.AvatarAliasToStandardName(character);
commands = line[(firstSpaceIndex + 1)..];
}
else
{
if (validate)
{
Logger.LogError("战斗脚本格式错误,必须以空格分隔角色和指令");
throw new Exception("战斗脚本格式错误,必须以空格分隔角色和指令");
}
Logger.LogError("战斗脚本格式错误,必须以空格分隔角色和指令");
throw new Exception("战斗脚本格式错误,必须以空格分隔角色和指令");
}
var character = line[..firstSpaceIndex];
character = DefaultAutoFightConfig.AvatarAliasToStandardName(character);
var commands = line[(firstSpaceIndex + 1)..];
oneLineCombatCommands.AddRange(ParseLineCommands(commands, character));
combatAvatarNames.Add(character);
return oneLineCombatCommands;
@@ -171,4 +155,4 @@ public class CombatScriptParser
return oneLineCombatCommands;
}
}
}
@@ -32,7 +32,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
private readonly ILogger<AutoFishingTrigger> _logger = App.GetLogger<AutoFishingTrigger>();
private readonly IOcrService _ocrService = OcrFactory.Paddle;
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
public string Name => "自动钓鱼";
public bool IsEnabled { get; set; }
@@ -382,7 +382,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}.InitTemplate();
// 截图
using var captureRegion = TaskControl.CaptureToRectArea(forceNew: true);
using var captureRegion = TaskControl.CaptureToRectArea();
using var resRa = captureRegion.Find(ro);
if (resRa.IsEmpty())
{
@@ -425,7 +425,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
while (IsEnabled)
{
// 截图
var ra = TaskControl.CaptureToRectArea(forceNew: true);
var ra = TaskControl.CaptureToRectArea();
// 找 鱼饵落点
using var memoryStream = new MemoryStream();
@@ -728,13 +728,11 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
NewRetry.Do(() =>
{
TaskControl.TrySuspend();
if (IsEnabled && !SystemControl.IsGenshinImpactActiveByProcess())
{
_logger.LogWarning("当前获取焦点的窗口不是原神,暂停");
throw new RetryException("当前获取焦点的窗口不是原神");
}
}, TimeSpan.FromSeconds(1), 100);
CheckFishingUserInterface(_currContent);
Thread.Sleep(millisecondsTimeout);
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff. Show more