Compare commits

...
Author SHA1 Message Date
辉鸭蛋 8143a48d23 Merge branch 'main' into refactor/captureMat 2025-03-15 13:17:59 +08:00
辉鸭蛋 3fe3acb61c 清理无用的截图器模式 2025-03-15 12:57:23 +08:00
辉鸭蛋 e5d6e146f3 HDR Support 2025-03-15 12:52:32 +08:00
辉鸭蛋 2f9e254dc1 修复单测的编译错误 2025-03-15 10:48:27 +08:00
辉鸭蛋 600b7aeaa4 清除所有 DispatcherTimerOperationEnum 内容 2025-03-15 10:46:05 +08:00
f7903f8e9b webhook添加了sendto发送对象,修复了webhook通知ui显示错误问题,修复了websocket服务端错误关闭链接问题 (#1300)
* 新增图片作为email附件发送功能

* feat(notification): 为 WebhookNotifier 添加 send_to 功能

- 在 WebhookNotifier 类中添加 send_to 属性
- 修改 TransformData 方法,增加 send_to 字段
- 在 NotificationConfig 中添加 webhook_endpoint 和 websocket_endpoint 属性

* refactor(WebhookNotifier): 添加 send_to 属性并调整访问修饰符

* refactor(notification): 重构 WebhookNotifier 并更新 NotificationConfig

- 在 NotificationConfig 中添加 WebhookSendTo 属性
- 重构 WebhookNotifier 构造函数,使用 NotificationConfig 对象进行初始化
- 更新 WebhookNotifier 发送逻辑,使用新的配置属性

* feat: add webhook ui.

* refactor(WebhookNotifier): 重构 TransformData 方法以优化数据结构- 将 notification_data 的内容合并到外层字典,以便于 webhook 接收端获取数据- 新增 event、result、timestamp 等字段,使数据结构

* fix(WebSocketNotifier): 添加消息发送后关闭连接的功能

- 在 SendAsync 方法中添加了 CloseAsync() 调用,确保消息发送后关闭 WebSocket 连接
- 此修改解决了消息发送后未关闭连接的问题,提高了资源利用率和系统稳定性

* fix: implement unified webhook ui

* fix: typos.

---------

Co-authored-by: DR-lin-eng <@DR-lin-eng>
Co-authored-by: 秋云 <[email protected]>
2025-03-15 10:33:33 +08:00
DR-lin-engandDR-lin-eng 45fc9fe7f4 新增图片作为email附件发送功能 (#1298)
Co-authored-by: DR-lin-eng <@DR-lin-eng>
2025-03-15 10:33:13 +08:00
辉鸭蛋 302aff9216 队伍中没有对应元素角色修复日志问题 2025-03-15 02:32:38 +08:00
辉鸭蛋 0257d548f2 dwm加锁并返回mat 2025-03-15 02:23:17 +08:00
辉鸭蛋 6e80999817 使用读写锁重构 Windows.Graphics.Capture,删除BGI自己命名的缓存设置 2025-03-15 01:48:17 +08:00
辉鸭蛋 8db7183488 BitBlt 加锁 2025-03-14 23:37:25 +08:00
a662791b6b Tgbot推送机器人 (#1296)
* feat: add email and websocket notification

* fix typos.

* refactor(notifiers): 重构邮件和 WebSocket 通知器

- 提升 EmailNotifier 中的 SmtpClient 为类的成员变量,并在构造函数中初始化,优化资源使用
- 改进 WebSocketNotifier 的连接和重连逻辑,提高稳定性
- 优化通知器的错误处理和日志记录,增强可维护性

* Create BarkNotifier.cs

* Update NotificationConfig.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/Notifier/BarkNotifier.cs

* Add files via upload

* Update BarkNotifier.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/BarkNotifier.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* fix: 回退部分代码,修复了程序崩溃的错误

* fix: remove api.day.app

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Update CommonSettingsPage.xaml

* Update CommonSettingsPageViewModel.cs

* Update EmailNotifier.cs

* Update EmailNotifier.cs

* Update BarkNotifier.cs

* 修正并更新前端介绍

* Revert "1"

* 修正公益服务器请求兼容性

* Revert "Revert "1""

This reverts commit 8c6effb1

* 新增tg推送但是有发送问题?(疑似我的电脑问题,稍后解决)

Signed-off-by: DR-lin-eng <@DR-lin-eng>

* feat: Telegram notification and ui.

* 修正tgbot推送,修正变量

Signed-off-by: DR-lin-eng <@DR-lin-eng>

---------

Signed-off-by: DR-lin-eng <@DR-lin-eng>
Co-authored-by: 秋云 <[email protected]>
Co-authored-by: 禹仔二号 <[email protected]>
Co-authored-by: yuzai <[email protected]>
Co-authored-by: DR-lin-eng <@DR-lin-eng>
Co-authored-by: 辉鸭蛋 <[email protected]>
2025-03-14 19:39:16 +08:00
秋云 76445ab19d fix: 修复换队时爬七天神像导致换队失败的问题 (#1295) 2025-03-14 11:43:58 +08:00
起个名字好难 3df45ea6ed 统计增加卡死和异常 (#1293) 2025-03-14 09:50:24 +08:00
辉鸭蛋 1cc889c6f2 to mat init 2025-03-14 01:57:54 +08:00
辉鸭蛋 616293432d Update README.md 2025-03-14 00:39:59 +08:00
辉鸭蛋 7250ef111d Update README.md 2025-03-14 00:37:23 +08:00
辉鸭蛋 19fb0022c1 Merge remote-tracking branch 'origin/main' 2025-03-14 00:26:45 +08:00
辉鸭蛋 f284a5331a 0.43.2 2025-03-14 00:23:27 +08:00
FishmanTheMurloc 29a2c0069e bug fix:拉条过程中内存没有及时释放 (#1266)
* bug fix:拉条过程中内存没有及时释放

* 新增LiftAndHold行为用于举竿、检测预抛竿时鼠标左键是否被意外松开、终止任务;抛竿开始后5秒内如从未找到落点,则返回失败,并配有单元测试;添加抛竿时无鱼饵适用鱼的单元测试;调整变量名

* 新增一个钓鱼昼夜设置枚举DontChange及其逻辑(枚举值为3),表示不调整时间直接开钓

* 针对可能是游戏中的雾气/滤镜/小黄鸭之类不明原因干扰了钓鱼拉条框的识别,修改了CV算法,使其不严格按照黄色(255,255,192)找矩形,而是按一定HSV范围寻找,并加强过滤;添加上述不明原因案例的测试用例

* 将MySimpleParallel改造为支持两个以上子行为;将“检查抛竿结果”行为合并到“下杆中”并行节点,以去除检查的等待时间,由此希望能应对鱼过快上钩的情况
2025-03-14 00:17:37 +08:00
秋云and辉鸭蛋 22fe431880 feat: add action_params(StopFlyingWaitTime) to stop_flying (#1277)
* feat: add action_params(StopFlyingWaitTime) to stop_flying;
fix: ensure next step only proceeds after stop_flying.

* add StopFlyingHandler

* use int.TryParse

---------

Co-authored-by: 辉鸭蛋 <[email protected]>
2025-03-14 00:15:17 +08:00
a172ba6941 修正bark推送参数和前端 (#1289)
* feat: add email and websocket notification

* fix typos.

* refactor(notifiers): 重构邮件和 WebSocket 通知器

- 提升 EmailNotifier 中的 SmtpClient 为类的成员变量,并在构造函数中初始化,优化资源使用
- 改进 WebSocketNotifier 的连接和重连逻辑,提高稳定性
- 优化通知器的错误处理和日志记录,增强可维护性

* Create BarkNotifier.cs

* Update NotificationConfig.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/Notifier/BarkNotifier.cs

* Add files via upload

* Update BarkNotifier.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/BarkNotifier.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* fix: 回退部分代码,修复了程序崩溃的错误

* fix: remove api.day.app

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Update CommonSettingsPage.xaml

* Update CommonSettingsPageViewModel.cs

* Update EmailNotifier.cs

* Update EmailNotifier.cs

* Update BarkNotifier.cs

* 修正并更新前端介绍

* Revert "1"

* 修正公益服务器请求兼容性

* Revert "Revert "1""

This reverts commit 8c6effb1

---------

Co-authored-by: 秋云 <[email protected]>
Co-authored-by: 禹仔二号 <[email protected]>
Co-authored-by: yuzai <[email protected]>
Co-authored-by: DR-lin-eng <@DR-lin-eng>
Co-authored-by: 辉鸭蛋 <[email protected]>
2025-03-14 00:04:58 +08:00
80b8c968d4 校对修复所有邀约文本 (#1290)
* feat: add email and websocket notification

* fix typos.

* refactor(notifiers): 重构邮件和 WebSocket 通知器

- 提升 EmailNotifier 中的 SmtpClient 为类的成员变量,并在构造函数中初始化,优化资源使用
- 改进 WebSocketNotifier 的连接和重连逻辑,提高稳定性
- 优化通知器的错误处理和日志记录,增强可维护性

* Create BarkNotifier.cs

* Update NotificationConfig.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/Notifier/BarkNotifier.cs

* Add files via upload

* Update BarkNotifier.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/BarkNotifier.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* fix: 回退部分代码,修复了程序崩溃的错误

* fix: remove api.day.app

---------

Co-authored-by: 秋云 <[email protected]>
Co-authored-by: DR-lin-eng <[email protected]>
2025-03-13 22:48:02 +08:00
辉鸭蛋 bad6db6e8a WPF-UI.Violeta 4.0.0 2025-03-13 22:44:20 +08:00
辉鸭蛋 46ebdfc452 wpfui 4.0.0 (#1255)
* new INavigationAware, remove PageService

* fix run

* fix title bar

* override OnNavigatedTo

* try fix WindowStartupLocation
2025-03-13 00:33:31 +08:00
6becb9dd5a 添加websocket和smtp通知方法,添加bark通知,websocket为qq机器人预留。 (#1254)
* feat: add email and websocket notification

* fix typos.

* refactor(notifiers): 重构邮件和 WebSocket 通知器

- 提升 EmailNotifier 中的 SmtpClient 为类的成员变量,并在构造函数中初始化,优化资源使用
- 改进 WebSocketNotifier 的连接和重连逻辑,提高稳定性
- 优化通知器的错误处理和日志记录,增强可维护性

* Create BarkNotifier.cs

* Update NotificationConfig.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/Notifier/BarkNotifier.cs

* Add files via upload

* Update BarkNotifier.cs

* Update NotificationService.cs

* Update CommonSettingsPageViewModel.cs

* Update CommonSettingsPage.xaml

* Delete BetterGenshinImpact/Service/BarkNotifier.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Update CommonSettingsPage.xaml

* fix: 回退部分代码,修复了程序崩溃的错误

* fix: remove api.day.app

---------

Co-authored-by: 秋云 <[email protected]>
Co-authored-by: DR-lin-eng <[email protected]>
2025-03-13 00:06:09 +08:00
辉鸭蛋 3312837129 Merge pull request #1274 from MisakaAldrich/main
小改正则表达以支持JS脚本统计
2025-03-13 00:02:10 +08:00
起个名字好难 5272c44a44 Mining新增凝光平A 2025-03-12 23:16:44 +08:00
起个名字好难 61d635d2e2 日志分析:小改正则表达以支持JS脚本统计 2025-03-11 23:53:26 +08:00
73 changed files with 3057 additions and 1015 deletions

No files matched your search

+3 -4
View File
@@ -11,7 +11,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,10 +21,9 @@ 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.DependencyInjection;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact;
@@ -73,10 +71,11 @@ public partial class App : Application
Log.Logger = loggerConfiguration.CreateLogger();
services.AddLogging(c => c.AddSerilog());
services.AddNavigationViewPageProvider();
// App Host
services.AddHostedService<ApplicationHostService>();
// Page resolver service
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<INavigationService, NavigationService>();
services.AddSingleton<IUpdateService, UpdateService>();
// Service containing navigation, same as INavigationWindow... but without window
@@ -10,7 +10,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.43.1</AssemblyVersion>
<AssemblyVersion>0.43.2</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
@@ -75,9 +75,10 @@
<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.26" />
<PackageReference Include="WPF-UI" Version="4.0.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.0.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.0.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.0.0" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
@@ -152,6 +153,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="GameTask\Model\Enum\" />
<Folder Include="GameTask\OneDragon\" />
<Folder Include="Service\Notification\Builder\" />
<Folder Include="User\AutoPathing\" />
+7 -7
View File
@@ -51,13 +51,13 @@ public partial class AllConfig : ObservableObject
[ObservableProperty]
private int _triggerInterval = 50;
/// <summary>
/// WGC使用位图缓存
/// 高帧率情况下,可能会导致卡顿
/// 云原神可能会出现黑屏
/// </summary>
[ObservableProperty]
private bool _wgcUseBitmapCache = true;
// /// <summary>
// /// WGC使用位图缓存
// /// 高帧率情况下,可能会导致卡顿
// /// 云原神可能会出现黑屏
// /// </summary>
// [ObservableProperty]
// private bool _wgcUseBitmapCache = true;
/// <summary>
/// 自动修复Win11下BitBlt截图方式不可用的问题
@@ -8,7 +8,7 @@
// using BetterGenshinImpact.GameTask.Common.Element.Assets;
// using BetterGenshinImpact.GameTask.Common.Map;
// using BetterGenshinImpact.GameTask.Model.Area;
// using BetterGenshinImpact.GameTask.Model.Enum;
//
// using BetterGenshinImpact.View.Drawable;
// using BetterGenshinImpact.ViewModel.Pages;
// using Microsoft.Extensions.Logging;
@@ -4,10 +4,8 @@ using BetterGenshinImpact.ViewModel.Pages;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoWood;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
@@ -30,7 +30,7 @@ public class Simulation
}
}
private static bool IsKeyDown(User32.VK key)
public static bool IsKeyDown(User32.VK key)
{
// 获取按键状态
var state = User32.GetAsyncKeyState((int)key);
@@ -1,7 +1,7 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service;
using Microsoft.Extensions.Logging;
@@ -128,14 +128,6 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
/// </summary>
private Task FightTask(CancellationToken ct)
{
// 切换截图模式
var dispatcherCaptureMode = TaskTriggerDispatcher.Instance().GetCacheCaptureMode();
if (dispatcherCaptureMode != DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, ct); // 等待缓存图像
}
var imageRegion = CaptureToRectArea();
var combatScenes = new CombatScenes().InitializeTeam(imageRegion);
if (!combatScenes.CheckTeamInitialized())
@@ -17,21 +17,25 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
try
{
using var mask = new Mat();
using var rgbMat = new Mat();
// 拉条框的黄色是:RGB 255, 255, 192 ~ HSV 43, 63, 255
// var testPixel = rgbMat.At<Vec3b>(105, 968);
using Mat rgbMat = src.CvtColor(ColorConversionCodes.BGR2HSV_FULL);
var lowYellow = new Scalar(43 - 3, 63 - 20, 255 - 10);
var highYellow = new Scalar(43 + 3, 63 + 40, 255);
using Mat mask = rgbMat.InRange(lowYellow, highYellow);
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2RGB);
var lowPurple = new Scalar(255, 255, 192);
var highPurple = new Scalar(255, 255, 192);
Cv2.InRange(rgbMat, lowPurple, highPurple, mask);
Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化
Cv2.FindContours(mask, out var contours, out _, RetrievalModes.External,
ContourApproximationModes.ApproxSimple, null);
if (contours.Length > 0)
{
var boxes = contours.Select(Cv2.BoundingRect).Where(w => w.Height >= 10);
return boxes.ToList();
var boxes = contours.Select(Cv2.MinAreaRect).Where(r => r.Angle % 90 <= 1) // 剔除倾斜的
.Select(r => r.BoundingRect()).ToList();
boxes = boxes.Where(r => r.Height >= 10 && r.Width >= 5).ToList(); // 剔除太小的
return boxes;
}
}
catch (Exception e)
@@ -71,15 +71,20 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
.PushLeaf(() => new FindFishTimeout("等10秒", 10, blackboard, _logger, param.SaveScreenshotOnKeyTick))
.End()
.PushLeaf(() => new ChooseBait("选择鱼饵", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.UntilSuccess("重复抛竿")
.Sequence("重复抛竿序列")
.PushLeaf(() => new MoveViewpointDown("调整视角至俯视", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.PushLeaf(() => new ThrowRod("抛竿", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.MySimpleParallel("抛竿直到成功或出错", policy: SimpleParallelPolicy.OnlyOneMustSucceed)
.UntilSuccess("重复抛竿")
.Sequence("重复抛竿序列")
.PushLeaf(() => new MoveViewpointDown("调整视角至俯视", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.MySimpleParallel("举起鱼竿并抛竿", policy: SimpleParallelPolicy.OnlyOneMustSucceed)
.PushLeaf(() => new LiftAndHold("举起鱼竿", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.PushLeaf(() => new ThrowRod("抛竿", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.End()
.End()
.End()
.Do("抛竿检查", _ => (blackboard.abort || blackboard.throwRodNoTarget || blackboard.throwRodNoBaitFish) ? BehaviourStatus.Failed : BehaviourStatus.Running)
.End()
.Do("冒泡-抛竿-缺鱼检查", _ => blackboard.throwRodNoTargetFish ? BehaviourStatus.Failed : BehaviourStatus.Succeeded)
.PushLeaf(() => new CheckThrowRod("检查抛竿结果", _logger, param.SaveScreenshotOnKeyTick))
.MySimpleParallel("下杆中", SimpleParallelPolicy.OnlyOneMustSucceed)
.PushLeaf(() => new CheckThrowRod("检查抛竿结果", _logger, param.SaveScreenshotOnKeyTick))
.PushLeaf(() => new FishBite("自动提竿", _logger, param.SaveScreenshotOnKeyTick, input))
.PushLeaf(() => new FishBiteTimeout("下杆超时检查", param.ThrowRodTimeOutTimeoutSeconds, _logger, param.SaveScreenshotOnKeyTick, input))
.End()
@@ -87,7 +92,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
.PushLeaf(() => new Fishing("钓鱼拉条", blackboard, _logger, param.SaveScreenshotOnKeyTick, input))
.End()
.End()
.Do("冒泡-找鱼-没鱼检查", _ => blackboard.noFish ? BehaviourStatus.Failed : BehaviourStatus.Succeeded)
.Do("冒泡-终止检查", _ => blackboard.abort ? BehaviourStatus.Failed : BehaviourStatus.Succeeded)
.End()
.End()
.End()
@@ -116,7 +121,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
break;
}
using var bitmap = TaskControl.CaptureGameBitmapNoRetry(TaskTriggerDispatcher.Instance().GameCapture);
using var bitmap = TaskControl.CaptureGameImageNoRetry(TaskTriggerDispatcher.Instance().GameCapture);
if (bitmap == null)
{
_logger.LogWarning("截图失败");
@@ -147,6 +152,10 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
_logger.LogInformation("当前处于联机状态,不使用昼夜设置");
tickARound();
}
else if (param.FishingTimePolicy == FishingTimePolicy.DontChange)
{
tickARound();
}
else
{
SetTimeTask setTimeTask = new SetTimeTask();
@@ -228,7 +237,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
if (DateTime.Now >= timeout)
{
blackboard.noFish = true;
blackboard.abort = true;
logger.LogInformation($"{seconds}秒没有找到鱼,退出钓鱼界面");
return BehaviourStatus.Failed;
}
@@ -10,6 +10,7 @@ using System.IO;
using Microsoft.Extensions.Logging;
using BetterGenshinImpact.GameTask.Model.Area;
using System.Threading.Tasks;
using System.Linq;
namespace BetterGenshinImpact.GameTask.AutoFishing
{
@@ -17,51 +18,41 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
public static FluentBuilder<TContext> MySimpleParallel<TContext>(this FluentBuilder<TContext> builder, string name, SimpleParallelPolicy policy = SimpleParallelPolicy.BothMustSucceed)
{
return builder.PushComposite((IBehaviour<TContext>[] children) => new MySimpleParallel<TContext>(name, policy, children[0], children[1]));
return builder.PushComposite((IBehaviour<TContext>[] children) => new MySimpleParallel<TContext>(name, policy, children));
}
}
/// <summary>
/// MySimpleParallel
/// 和SimpleParallel的区别是,任一子行为返回失败则返回失败
/// 和SimpleParallel的区别是,任一子行为返回失败则返回失败;并且支持两个以上子行为
/// </summary>
/// <typeparam name="TContext"></typeparam>
public class MySimpleParallel<TContext> : CompositeBehaviour<TContext>
{
private readonly IBehaviour<TContext> _first;
private readonly IBehaviour<TContext> _second;
private BehaviourStatus _firstStatus;
private BehaviourStatus _secondStatus;
private readonly Func<TContext, BehaviourStatus> _behave;
public readonly SimpleParallelPolicy Policy;
public MySimpleParallel(SimpleParallelPolicy policy, IBehaviour<TContext> first, IBehaviour<TContext> second)
: this("SimpleParallel", policy, first, second)
public MySimpleParallel(SimpleParallelPolicy policy, IBehaviour<TContext>[] children)
: this("SimpleParallel", policy, children)
{
}
public MySimpleParallel(string name, SimpleParallelPolicy policy, IBehaviour<TContext> first, IBehaviour<TContext> second)
: base(name, new IBehaviour<TContext>[2] { first, second })
public MySimpleParallel(string name, SimpleParallelPolicy policy, IBehaviour<TContext>[] children)
: base(name, children)
{
Policy = policy;
_first = first;
_second = second;
_behave = ((policy == SimpleParallelPolicy.BothMustSucceed) ? new Func<TContext, BehaviourStatus>(BothMustSucceedBehaviour) : new Func<TContext, BehaviourStatus>(OnlyOneMustSucceedBehaviour));
}
private BehaviourStatus OnlyOneMustSucceedBehaviour(TContext context)
{
if (_firstStatus == BehaviourStatus.Succeeded || _secondStatus == BehaviourStatus.Succeeded)
if (Children.Any(c => c.Status == BehaviourStatus.Succeeded))
{
return BehaviourStatus.Succeeded;
}
if (_firstStatus == BehaviourStatus.Failed && _secondStatus == BehaviourStatus.Failed)
if (Children.All(c => c.Status == BehaviourStatus.Failed))
{
return BehaviourStatus.Failed;
}
@@ -71,12 +62,12 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
private BehaviourStatus BothMustSucceedBehaviour(TContext context)
{
if (_firstStatus == BehaviourStatus.Succeeded && _secondStatus == BehaviourStatus.Succeeded)
if (Children.All(c => c.Status == BehaviourStatus.Succeeded))
{
return BehaviourStatus.Succeeded;
}
if (_firstStatus == BehaviourStatus.Failed || _secondStatus == BehaviourStatus.Failed)
if (Children.Any(c => c.Status == BehaviourStatus.Failed))
{
return BehaviourStatus.Failed;
}
@@ -88,23 +79,23 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
if (base.Status != BehaviourStatus.Running)
{
_firstStatus = _first.Tick(context);
_secondStatus = _second.Tick(context);
foreach (var child in Children)
{
child.Tick(context);
}
}
else
{
if (_firstStatus == BehaviourStatus.Ready || _firstStatus == BehaviourStatus.Running)
foreach (var child in Children)
{
_firstStatus = _first.Tick(context);
}
if (_secondStatus == BehaviourStatus.Ready || _secondStatus == BehaviourStatus.Running)
{
_secondStatus = _second.Tick(context);
if (child.Status == BehaviourStatus.Ready || child.Status == BehaviourStatus.Running)
{
child.Tick(context);
}
}
}
if (_firstStatus == BehaviourStatus.Failed || _secondStatus == BehaviourStatus.Failed)
if (Children.Any(c => c.Status == BehaviourStatus.Failed))
{
return BehaviourStatus.Failed;
}
@@ -116,8 +107,6 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
protected override void DoReset(BehaviourStatus status)
{
_firstStatus = BehaviourStatus.Ready;
_secondStatus = BehaviourStatus.Ready;
base.DoReset(status);
}
}
@@ -21,6 +21,7 @@ using Pen = System.Drawing.Pen;
using System.Linq;
using Fischless.WindowsInput;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
namespace BetterGenshinImpact.GameTask.AutoFishing
{
@@ -59,8 +60,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
blackboard.fishpond = fishpond;
string[] chooseBaitfailuresIgnoredBaits = blackboard.chooseBaitfailures.GroupBy(f => f).Where(g => g.Count() >= ChooseBait.MAX_FAILED_TIMES).Select(g => g.Key).ToArray();
string[] throwRodNoTargetFishfailuresIgnoredBaits = blackboard.throwRodNoTargetFishfailures.GroupBy(f => f).Where(g => g.Count() >= ThrowRod.MAX_NO_TARGET_FISH_TIMES).Select(g => g.Key).ToArray();
string[] chooseBaitfailuresIgnoredBaits = blackboard.chooseBaitFailures.GroupBy(f => f).Where(g => g.Count() >= ChooseBait.MAX_FAILED_TIMES).Select(g => g.Key).ToArray();
string[] throwRodNoTargetFishfailuresIgnoredBaits = blackboard.throwRodNoBaitFishFailures.GroupBy(f => f).Where(g => g.Count() >= ThrowRod.MAX_NO_BAIT_FISH_TIMES).Select(g => g.Key).ToArray();
logger.LogInformation("定位到鱼塘:" + string.Join('、', fishpond.Fishes.GroupBy(f => f.FishType)
.Select(g => $"{g.Key.ChineseName}{g.Count()}条" + ((chooseBaitfailuresIgnoredBaits.Contains(g.Key.BaitName) || throwRodNoTargetFishfailuresIgnoredBaits.Contains(g.Key.BaitName)) ? "(忽略)" : ""))
@@ -128,7 +129,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
blackboard.selectedBaitName = blackboard.fishpond.Fishes.GroupBy(f => f.FishType.BaitName)
.Where(b => !blackboard.chooseBaitfailures.GroupBy(f => f).Where(g => g.Count() >= MAX_FAILED_TIMES).Any(g => g.Key == b.Key)) // 不能是已经失败两次的饵
.Where(b => !blackboard.chooseBaitFailures.GroupBy(f => f).Where(g => g.Count() >= MAX_FAILED_TIMES).Any(g => g.Key == b.Key)) // 不能是已经失败两次的饵
.OrderByDescending(g => g.Count()).First().Key; // 选择最多鱼吃的饵料
logger.LogInformation("选择鱼饵 {Text}", BaitType.FromName(blackboard.selectedBaitName).ChineseName);
@@ -154,8 +155,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
blackboard.chooseBaitUIOpening = false;
logger.LogInformation("退出换饵界面");
blackboard.chooseBaitfailures.Add(blackboard.selectedBaitName);
if (blackboard.chooseBaitfailures.Count(f => f == blackboard.selectedBaitName) >= MAX_FAILED_TIMES)
blackboard.chooseBaitFailures.Add(blackboard.selectedBaitName);
if (blackboard.chooseBaitFailures.Count(f => f == blackboard.selectedBaitName) >= MAX_FAILED_TIMES)
{
logger.LogWarning($"本次将忽略{BaitType.FromName(blackboard.selectedBaitName).ChineseName}");
}
@@ -177,7 +178,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
captureRegion.ClickTo((int)(captureRegion.Width * 0.675), (int)(captureRegion.Height / 3d));
blackboard.Sleep(200);
// 点击确定
var ra = captureRegion.Find(new RecognitionObject
using var ra = captureRegion.Find(new RecognitionObject
{
Name = "BtnWhiteConfirm",
RecognitionType = RecognitionTypes.TemplateMatch,
@@ -197,6 +198,40 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
}
/// <summary>
/// 《How to Cast a Fly Rod: Step-by-Step Guide for Beginners》:https://hookedonfly.fishing/2024/10/how-to-cast-a-fly-rod/
/// </summary>
public class LiftAndHold : BaseBehaviour<ImageRegion>
{
private readonly Blackboard blackboard;
private readonly IInputSimulator input;
public LiftAndHold(string name, Blackboard blackboard, ILogger logger, bool saveScreenshotOnTerminate, IInputSimulator input) : base(name, logger, saveScreenshotOnTerminate)
{
this.blackboard = blackboard;
this.input = input;
}
protected override void OnInitialize()
{
input.Mouse.LeftButtonDown();
blackboard.pitchReset = true;
logger.LogInformation("长按举起鱼竿");
}
protected override BehaviourStatus Update(ImageRegion context)
{
// todo 这个方案不能令人满意,应该是底层做一个事件监听来记录被点击,底层向上暴露一个和Timer用起来差不多的东西,它应该有个开始记录方法、有个获取从开始到目前是否被点击的方法
// 但说到底,检查是否鼠标被干扰,不是一个必选的方法。做一个精确度高的图形检测方案,来检测当前位于哪个步骤,会更好。
if (!Simulation.IsKeyDown(VK.VK_LBUTTON))
{
logger.LogWarning("检测到当前鼠标左键状态不符合要求,可能受到干扰,退出任务");
blackboard.abort = true;
return BehaviourStatus.Failed;
}
return BehaviourStatus.Running;
}
}
/// <summary>
/// 抛竿
/// </summary>
@@ -207,7 +242,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
private readonly DrawContent drawContent;
private readonly TimeProvider timeProvider;
private DateTimeOffset? ignoreObtainedEndTime;
public const int MAX_NO_TARGET_FISH_TIMES = 2;
public const int MAX_NO_BAIT_FISH_TIMES = 2;
private DateTimeOffset? findTargetEndTime;
private bool foundTarget;
private int noPlacementTimes; // 没有落点的次数
private int noTargetFishTimes; // 没有目标鱼的次数
@@ -223,21 +260,19 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
noPlacementTimes = 0;
noTargetFishTimes = 0;
blackboard.throwRodNoTargetFish = false;
input.Mouse.LeftButtonDown();
blackboard.pitchReset = true;
logger.LogInformation("长按预抛竿");
blackboard.Sleep(3000);
logger.LogInformation("开始抛竿");
blackboard.throwRodNoBaitFish = false;
ignoreObtainedEndTime = timeProvider.GetLocalNow().AddSeconds(6);
blackboard.throwRodNoTarget = false;
findTargetEndTime = timeProvider.GetLocalNow().AddSeconds(5);
foundTarget = false;
mouseMoveI *= -1;
mouseMoveR = 0d;
}
protected override void OnTerminate(BehaviourStatus status)
{
drawContent.RemoveRect("Target");
drawContent.RemoveRect("Fish");
drawContent.RemoveRect("PrevFish");
}
/// <summary>
@@ -245,13 +280,14 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
/// </summary>
public OneFish? currentFish { get; private set; }
private int mouseMoveI = 1; // 上下移动视角的初始方向控制参数
private double mouseMoveR; // 上下移动视角的切换频率控制参数
protected override BehaviourStatus Update(ImageRegion imageRegion)
{
var ra = imageRegion;
// 找 鱼饵落点
using var memoryStream = new MemoryStream();
ra.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
imageRegion.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
var result = blackboard.predictor.Detect(memoryStream);
Debug.WriteLine($"YOLOv8识别: {result.Speed}");
@@ -260,23 +296,47 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
Random _rd = new();
if (fishpond.TargetRect == null || fishpond.TargetRect == Rect.Empty)
{
if (!foundTarget)
{
if (timeProvider.GetLocalNow() <= findTargetEndTime)
{
// 上下移动视角方便看落点
mouseMoveR += Math.PI / 16d;
input.Mouse.MoveMouseBy(0, mouseMoveI * 80 * Math.Sign(Math.Cos(mouseMoveR)));
blackboard.Sleep(100);
return BehaviourStatus.Running;
}
else
{
logger.LogInformation("举起鱼竿失败,始终没有找到落点");
input.Mouse.LeftButtonUp();
blackboard.Sleep(2000);
input.Mouse.LeftButtonClick();
blackboard.Sleep(800);
blackboard.throwRodNoTarget = true;
return BehaviourStatus.Failed;
}
}
noPlacementTimes++;
blackboard.Sleep(50);
Debug.WriteLine($"{noPlacementTimes}次未找到鱼饵落点");
var cX = ra.SrcBitmap.Width / 2;
var cY = ra.SrcBitmap.Height / 2;
var rdX = _rd.Next(0, ra.SrcBitmap.Width);
var rdY = _rd.Next(0, ra.SrcBitmap.Height);
var cX = imageRegion.SrcBitmap.Width / 2;
var cY = imageRegion.SrcBitmap.Height / 2;
var rdX = _rd.Next(0, imageRegion.SrcBitmap.Width);
var rdY = _rd.Next(0, imageRegion.SrcBitmap.Height);
var moveX = 100 * (cX - rdX) / ra.SrcBitmap.Width;
var moveY = 100 * (cY - rdY) / ra.SrcBitmap.Height;
var moveX = 100 * (cX - rdX) / imageRegion.SrcBitmap.Width;
var moveY = 100 * (cY - rdY) / imageRegion.SrcBitmap.Height;
input.Mouse.MoveMouseBy(moveX, moveY);
if (noPlacementTimes > 25)
{
logger.LogInformation("未找到鱼饵落点,重试");
logger.LogInformation("中途丢失鱼饵落点,重试");
input.Mouse.LeftButtonUp();
blackboard.Sleep(2000);
input.Mouse.LeftButtonClick();
@@ -286,12 +346,16 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
return BehaviourStatus.Running;
}
else
{
foundTarget = true;
}
Rect fishpondTargetRect = (Rect)fishpond.TargetRect;
// 找到落点最近的鱼
currentFish = null;
string[] ignoredBaits = blackboard.throwRodNoTargetFishfailures.GroupBy(f => f).Where(g => g.Count() >= MAX_NO_TARGET_FISH_TIMES).Select(g => g.Key).ToArray();
string[] ignoredBaits = blackboard.throwRodNoBaitFishFailures.GroupBy(f => f).Where(g => g.Count() >= MAX_NO_BAIT_FISH_TIMES).Select(g => g.Key).ToArray();
var list = fishpond.Fishes
.Where(f => !ignoredBaits.Contains(f.FishType.BaitName)) // 不能是已经失败两次的饵;
.Where(f => f.FishType.BaitName == blackboard.selectedBaitName).OrderByDescending(f => f.Confidence)
@@ -303,24 +367,23 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
if (currentFish == null)
{
Debug.WriteLine("无目标鱼");
Debug.WriteLine("无鱼饵适用鱼");
noTargetFishTimes++;
if (noTargetFishTimes > 10)
{
// 没有找到目标鱼,重新选择鱼饵
blackboard.throwRodNoTargetFish = true;
blackboard.throwRodNoTargetFishfailures.Add(blackboard.selectedBaitName);
if (blackboard.throwRodNoTargetFishfailures.Count(f => f == blackboard.selectedBaitName) >= MAX_NO_TARGET_FISH_TIMES)
// 没有找到鱼饵适用鱼,重新选择鱼饵
blackboard.throwRodNoBaitFish = true;
blackboard.throwRodNoBaitFishFailures.Add(blackboard.selectedBaitName);
if (blackboard.throwRodNoBaitFishFailures.Count(f => f == blackboard.selectedBaitName) >= MAX_NO_BAIT_FISH_TIMES)
{
logger.LogWarning($"本次将忽略{BaitType.FromName(blackboard.selectedBaitName).ChineseName}");
}
blackboard.selectedBaitName = string.Empty;
logger.LogInformation("没有找到目标鱼,1.直接抛竿");
logger.LogInformation("没有找到鱼饵适用鱼");
input.Mouse.LeftButtonUp();
blackboard.Sleep(2000);
logger.LogInformation("没有找到目标鱼,2.收杆");
input.Mouse.LeftButtonClick();
blackboard.Sleep(800);
@@ -452,6 +515,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
public class CheckThrowRod : BaseBehaviour<ImageRegion>
{
private DateTime? timeDelay;
private bool hasChecked;
/// <summary>
/// 检查抛竿结果
@@ -464,19 +528,21 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
protected override void OnInitialize()
{
timeDelay = DateTime.Now.AddSeconds(3);
hasChecked = false;
}
protected override BehaviourStatus Update(ImageRegion imageRegion)
{
if (DateTime.Now < timeDelay)
if (DateTime.Now < timeDelay || hasChecked)
{
return BehaviourStatus.Running;
}
Region baitRectArea = imageRegion.Find(AutoFishingAssets.Instance.BaitButtonRo);
using Region baitRectArea = imageRegion.Find(AutoFishingAssets.Instance.BaitButtonRo);
if (baitRectArea.IsEmpty())
{
return BehaviourStatus.Succeeded;
hasChecked = true;
return BehaviourStatus.Running;
}
else
{
@@ -661,7 +727,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
Rect _cur, _left;
if (Math.Abs(rects[0].Height - rects[1].Height) > 10)
{
TaskControl.Logger.LogError("两个矩形高度差距过大,未识别到钓鱼框");
logger.LogError("两个矩形高度差距过大,未识别到钓鱼框");
return BehaviourStatus.Running;
}
@@ -723,7 +789,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
protected override BehaviourStatus Update(ImageRegion imageRegion)
{
var fishBarMat = new Mat(imageRegion.SrcMat, blackboard.fishBoxRect);
using var fishBarMat = new Mat(imageRegion.SrcMat, blackboard.fishBoxRect);
var rects = AutoFishingImageRecognition.GetFishBarRect(fishBarMat);
if (rects != null && rects.Count > 0)
{
@@ -13,9 +13,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
public class Blackboard
{
/// <summary>
/// 没鱼啦,不钓了
/// 不钓啦
/// </summary>
public bool noFish = false;
public bool abort = false;
/// <summary>
/// 已选择的鱼饵名
@@ -28,15 +28,20 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
public Fishpond fishpond;
/// <summary>
/// 是否没有目标鱼
/// 是否没有抛竿落点
/// </summary>
public bool throwRodNoTargetFish;
public bool throwRodNoTarget;
/// <summary>
/// 是否没有鱼饵适用的鱼
/// </summary>
public bool throwRodNoBaitFish;
/// <summary>
/// 抛竿无目标鱼失败列表
/// 失败一次就加入一次鱼饵名,列表中同名鱼饵的数量代表该种失败了几次
/// </summary>
public List<string> throwRodNoTargetFishfailures = new List<string>();
public List<string> throwRodNoBaitFishFailures = new List<string>();
/// <summary>
/// 拉条位置的识别框
@@ -53,7 +58,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
/// 选鱼饵失败列表
/// 失败一次就加入一次鱼饵名,列表中同名鱼饵的数量代表该种失败了几次
/// </summary>
public List<string> chooseBaitfailures = new List<string>();
public List<string> chooseBaitFailures = new List<string>();
/// <summary>
/// 镜头俯仰是否被行为重置
@@ -74,12 +79,11 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
internal virtual void Reset()
{
noFish = false;
throwRodNoTargetFish = false;
throwRodNoTargetFishfailures = new List<string>();
abort = false;
throwRodNoBaitFishFailures = new List<string>();
fishBoxRect = Rect.Empty;
chooseBaitUIOpening = false;
chooseBaitfailures = new List<string>();
chooseBaitFailures = new List<string>();
pitchReset = true;
selectedBaitName = string.Empty;
}
@@ -12,6 +12,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
[Description("白天")]
Daytime,
[Description("夜晚")]
Nighttime
Nighttime,
[Description("不调")]
DontChange
}
}
@@ -38,6 +38,7 @@ public class ActionFactory
return key switch
{
"up_down_grab_leaf" => new UpDownGrabLeaf(),
"stop_flying" => new StopFlyingHandler(),
_ => throw new ArgumentException("未知的前置 action 类型")
};
});
@@ -22,6 +22,7 @@ public class MiningHandler : IActionHandler
雷泽 e(hold)
卡齐娜 e(hold),a(0.2),a(0.2),a(0.2),a(0.2)
坎蒂丝 e(hold)
凝光 a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2)
""");
private readonly ScanPickTask _scanPickTask = new();
@@ -0,0 +1,51 @@
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
public class StopFlyingHandler : IActionHandler
{
public async Task RunAsync(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
{
if (waypointForTrack != null
&& !string.IsNullOrEmpty(waypointForTrack.ActionParams)
&& int.TryParse(waypointForTrack.ActionParams, out var stopFlyingWaitTime))
{
Simulation.SendInput.SimulateAction(GIActions.Jump);
await Delay(stopFlyingWaitTime, ct);
}
//下落攻击接近目的地
Logger.LogInformation("动作:下落攻击");
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
int i;
for (i = 0; i < 50; i++)
{
var screen = CaptureToRectArea();
var isFlying = Bv.GetMotionStatus(screen) == MotionStatus.Fly;
if (isFlying)
{
await Delay(200, ct);
}
else
{
break;
}
}
if (i == 50)
{
Logger.LogWarning("动作:下落攻击 超时结束");
}
else
{
Logger.LogInformation("动作:下落攻击 结束");
}
}
}
@@ -2,7 +2,6 @@
using System;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using System.Diagnostics.Eventing.Reader;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
@@ -24,7 +23,7 @@ public class WaypointForTrack : Waypoint
/// </summary>
public CombatScript? CombatScript { get; set; }
public string? LogInfo { get; set; }
public WaypointForTrack(Waypoint waypoint)
{
Type = waypoint.Type;
@@ -358,7 +358,7 @@ public class PathExecutor
if (forceTp) // 强制传送模式
{
await new TpTask(ct).TpToStatueOfTheSeven(); // fix typos
await new TpTask(ct).TpToStatueOfTheSeven(); // fix typos
success = await new SwitchPartyTask().Start(partyName, ct);
}
else // 优先原地切换模式
@@ -385,7 +385,6 @@ public class PathExecutor
}
private static string? FilterPartyNameByConditionConfig(PathingTask task)
{
var pathingConditionConfig = TaskContext.Instance().Config.PathingConditionConfig;
@@ -464,7 +463,7 @@ public class PathExecutor
}
}
Logger.LogError("此路径存在 {action} 收集动作,队伍中没有对应元素角色:{},无法执行此路径!", action, string.Join(",", ElementalCollectAvatarConfigs.GetAvatarNameList(el)));
Logger.LogError("此路径存在 {El}元素采集 动作,队伍中没有对应元素角色:{Names},无法执行此路径!", el.ToChinese(), string.Join(",", ElementalCollectAvatarConfigs.GetAvatarNameList(el)));
return false;
}
else
@@ -606,7 +605,9 @@ public class PathExecutor
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
await Delay(500, ct);
}
public DateTime moveToStartTime;
public async Task MoveTo(WaypointForTrack waypoint)
{
// 切人
@@ -895,10 +896,7 @@ public class PathExecutor
{
if (waypoint.MoveMode == MoveModeEnum.Fly.Code && waypoint.Action == ActionEnum.StopFlying.Code)
{
//下落攻击接近目的地
Logger.LogInformation("动作:下落攻击");
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1000, ct);
await ActionFactory.GetBeforeHandler(ActionEnum.StopFlying.Code).RunAsync(ct, waypoint);
}
}
@@ -50,12 +50,12 @@
],
"卡维结局3:闲时小聚": [
"做些别的事转换心情",
"卡维为什么要当设计师呢",
"卡维为什么当设计师呢",
"去找熟人问问"
],
"卡维结局4:群星之下": [
"做些别的事转换心情",
"卡维为什么要当设计师呢",
"卡维为什么当设计师呢",
"还是先别管这个了"
],
"卡维结局5:第1堂课": [
@@ -63,8 +63,8 @@
"找份其他工作赚钱"
],
"莱依拉结局1:不可说之事": [
"虽然有些不靠谱",
"它可能只能是捉弄你",
"虽然有点不靠谱",
"它可能只是在用这种说法捉弄你",
"解读[书籍]",
"解读[真实想法]",
"联想[真实身份]",
@@ -72,23 +72,23 @@
"提交[行为逻辑]"
],
"莱依拉结局2:代价与回报": [
"虽然有些不靠谱",
"我陪你去找答案",
"虽然有点不靠谱",
"我陪你去找它藏起来的答案吧",
"仙灵应该不只是想苛责你"
],
"莱依拉结局3:不愿重蹈覆辙": [
"虽然有些不靠谱",
"我陪你去找答案",
"虽然有点不靠谱",
"我陪你去找它藏起来的答案吧",
"别再找仙灵的线索了"
],
"莱依拉结局4:水到渠成": [
"依靠这种不靠谱",
"依靠这种不靠谱的传说",
"干脆正面迎战吧",
"只是讲一些你学到的知识",
"三轨偏移推算法则"
],
"莱依拉结局5:星空的期望": [
"依靠这种不靠谱",
"依靠这种不靠谱的传说",
"干脆正面迎战吧",
"只是讲一些你学到的知识",
"你知道大工机吗"
@@ -135,7 +135,7 @@
],
"鹿野院平藏结局4:有一个秘密": [
"但我得先把你带回去",
"关于你的投诉信",
"在意你的投诉信",
"我有一些结论了",
"鹰司勇的留言",
"毒药的调查报告",
@@ -143,7 +143,7 @@
],
"鹿野院平藏结局5:名侦探法则": [
"但我得先把你带回去",
"关于你的投诉信",
"在意你的投诉信",
"我有一些结论了",
"鹰司勇的留言",
"毒药的调查报告",
@@ -170,7 +170,7 @@
"我帮你藏好吧"
],
"久岐忍结局5:荒泷派町街服务记录": [
"默默后退半步"
"默默退后半步"
],
"凝光结局1:趁着光景正好": [
"认真地试试看吧",
@@ -186,12 +186,12 @@
],
"凝光结局4:有福同享": [
"尽量避开专业性的事项吧",
"去做一直都没有机会做的事吧",
"去做一直都没有机会做的事",
"那就从不需要本金的工作开始做吧"
],
"凝光结局5:回马枪": [
"尽量避开专业性的事项吧",
"去做一直都没有机会做的事吧",
"去做一直都没有机会做的事",
"那就去北国银行打工吧"
],
"云堇结局1:只可叹世路风波险": [
@@ -244,7 +244,7 @@
"南十字之盾",
"最适合的模特就是",
"听说望舒客栈有个小渔村",
"随意就好"
"随意的姿势"
],
"北斗结局2:妩媚": [
"其实我对大家说的船员生活也蛮有兴趣的",
@@ -266,24 +266,24 @@
"但是我认为应该是在轻策庄"
],
"早柚结局1:凡事都需节制": [
"这样最令人放心",
"更在乎的是身高是吧",
"光睡觉是没法长高的",
"这样最让人放心",
"更在乎的是身高",
"睡觉是没办法长高的",
"你还愿意继续吗"
],
"早柚结局2:如翱翔在天际": [
"这样最令人放心",
"更在乎的是身高是吧",
"光睡觉是没法长高的",
"试试其他办法吧"
"这样最让人放心",
"更在乎的是身高",
"睡觉是没办法长高的",
"感觉吃东西会影响"
],
"早柚结局3:早柚绝不工作": [
"这样最令人放心",
"更在乎的是身高是吧",
"这样最让人放心",
"更在乎的是身高",
"应该是睡眠质量不够好"
],
"早柚结局4:与树同行": [
"这样最令人放心",
"这样最让人放心",
"但逃避责任不太好哦"
],
"早柚结局5:最安稳的休息": [
@@ -302,19 +302,19 @@
"托马结局2:独处的时光": [
"随他们说去吧",
"想在室内",
"只在社奉行里宣传下吧"
"只在社奉行所里宣传一下吧"
],
"托马结局3:寄托思念的海风": [
"随他们说去吧",
"想出去走走",
"对猫猫狗狗感兴趣",
"不如一起去看看它?"
"不如一起去看看它"
],
"托马结局4:新衣服": [
"随他们说去吧",
"想出去走走",
"对猫猫狗狗感兴趣",
"让它冷静一段时间比较好"
"冷静一段时间比较好"
],
"托马结局5:手有余香": [
"随他们说去吧",
@@ -332,22 +332,22 @@
],
"迪奥娜结局2:难测的猫咪们": [
"我是来看小猫的",
"毕竟很可爱的嘛",
"毕竟很可爱嘛",
"迪奥娜是想",
"这样也行能更赚钱"
],
"迪奥娜结局3:迪奥娜的特制饮品": [
"我想尝试下新型特调",
"我想尝试一下新型特调",
"基底饮品特别一点",
"杜拉夫先生说他已经找到了"
],
"迪奥娜结局4:我……只喝了……1点点": [
"我想尝试下新型特调",
"我想尝试一下新型特调",
"基底饮品特别一点",
"我很擅长对付那些魔物"
],
"迪奥娜结局5:终极特调": [
"我想尝试下新型特调",
"我想尝试一下新型特调",
"调酒辅料特别一点"
],
"诺艾尔第二幕结局1:岩间休憩": [
@@ -359,7 +359,7 @@
"三碗不过港"
],
"诺艾尔第二幕结局3:满分答卷": [
"直面考试压力吧",
"直面考试的压力吧",
"可以多参加一些考试来熟悉氛围",
"风车菊",
"罗尔德",
@@ -367,48 +367,48 @@
"烤肉排"
],
"诺艾尔第二幕结局4:错题漏分": [
"直面考试压力吧",
"直面考试的压力吧",
"可以多参加一些考试来熟悉氛围",
"小灯草",
"王尔德",
"寂灭海"
],
"诺艾尔第二幕结局5:独1无2的诺艾尔": [
"直面考试压力吧",
"直面考试的压力吧",
"可以多想象一下考试成功的样子",
"琴那样"
],
"诺艾尔第二幕结局6:女仆的本职工作": [
"直面考试压力吧",
"直面考试的压力吧",
"可以多想象一下考试成功的样子",
"凯亚那样"
],
"诺艾尔第一幕结局1:遇冷的盛情": [
"并不一定非要成为骑士啊",
"不一定非要成为骑士啊",
"是特地为你准备的",
"是特地为你准备的",
"是特地为你准备的"
],
"诺艾尔第一幕结局2:再见女仆小姐": [
"并不一定非要成为骑士啊",
"不一定非要成为骑士啊",
"是诺艾尔的待客之道",
"是诺艾尔的待客之道",
"是诺艾尔的待客之道"
],
"诺艾尔第一幕结局3:守护之心即是力量": [
"你想从哪方面开始修行呢",
"你缺乏的是力量",
"你欠缺的是力量",
"因为缺乏实战经验"
],
"诺艾尔第一幕结局4:女仆屹立于大地之上": [
"你想从哪方面开始修行呢",
"你缺乏的是力量",
"因为力量还不够"
"你欠缺的是力量",
"力量还不够"
],
"诺艾尔第一幕结局5:恋爱这道难题": [
"你想从哪方面开始修行呢",
"你缺乏的是休息",
"心意到了就可以,随便送什么都没有关系"
"心意到了就可以,随便送什么都没关系"
],
"诺艾尔第一幕结局6:纸玫瑰的低语": [
"你想从哪方面开始修行呢",
@@ -425,13 +425,13 @@
"那我们再往里走走吧",
"芭芭拉亲手做的辣味饮料",
"那我们分头采集材料吧",
"尝尝璃月的辣味饮料"
"尝尝璃月港的辣味饮料"
],
"芭芭拉结局3:努力的味道": [
"那我们再往里走走吧",
"芭芭拉亲手做的辣味饮料",
"那我们分头采集材料吧",
"正想采集一些甜甜花"
"正想采一些甜甜花"
],
"芭芭拉结局4:未完成的治愈": [
"那我们再往里走走吧",
@@ -444,11 +444,11 @@
"了不起的梦幻忧郁珊瑚汽泡茶"
],
"班尼特结局1:徒劳的等待": [
"是但我们可以做些别的",
"就在城里转转吧"
"我们可以点些别的",
"就在城里"
],
"班尼特结局2:匆忙的道别": [
"但我们可以做些别的",
"我们可以点些别的",
"去野外走走"
],
"班尼特结局3:试菜员罗伊斯": [
@@ -488,13 +488,13 @@
"重云结局4:一无所获": [
"还是别拆穿吧",
"我陪你一起喝",
"我一个人一起去调查下"
"我一个人去调查"
],
"重云结局5:告别": [
"还是别拆穿吧",
"我陪你一起喝",
"我帮你找个休息的地方",
"还记得那个雾气吗"
"还记得那个雾气"
],
"重云结局6:小小的遗憾": [
"还是别拆穿吧",
@@ -9,7 +9,7 @@ using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Service;
@@ -87,7 +87,6 @@ public class AutoTrackPathTask
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
Logger.LogInformation("→ {Text}", "自动路线结束");
if (hasLock)
@@ -101,8 +100,6 @@ public class AutoTrackPathTask
{
SystemControl.ActivateWindow();
Logger.LogInformation("→ {Text}", "自动路线,启动!");
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _ct); // 等待缓存图像
}
public async Task DoTask()
@@ -4,7 +4,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service;
@@ -34,16 +34,12 @@ public class PathPointRecorder : Singleton<PathPointRecorder>
{
if (_recordTask == null)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
_recordTaskCts = new CancellationTokenSource();
_recordTask = RecordTask(_recordTaskCts.Token);
_recordTask.Start();
}
else
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
_recordTaskCts?.Cancel();
_recordTask = null;
}
@@ -57,6 +57,8 @@ public class TpTask(CancellationToken ct)
public async Task TpToStatueOfTheSeven()
{
await CheckInBigMapUi();
// 提前调整至恰当的缩放以更快的传送
if (_tpConfig.MapZoomEnabled)
{
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
@@ -73,22 +75,23 @@ public class TpTask(CancellationToken ct)
string? area = _tpConfig.ReviveStatueOfTheSevenArea;
double x = _tpConfig.ReviveStatueOfTheSevenPointX;
double y = _tpConfig.ReviveStatueOfTheSevenPointY;
GiTpPosition revivePoint = _tpConfig.ReviveStatueOfTheSeven ?? GetNearestGoddess(x, y);
if (_tpConfig.IsReviveInNearestStatueOfTheSeven)
{
var center = GetBigMapCenterPoint();
var giTpPoint = GetNearestGoddess(center.X, center.Y);
if (giTpPoint != null)
{
country = giTpPoint.Country;
area = giTpPoint.Area;
x = giTpPoint.X;
y = giTpPoint.Y;
}
country = giTpPoint.Country;
area = giTpPoint.Area;
x = giTpPoint.X;
y = giTpPoint.Y;
revivePoint = giTpPoint;
}
Logger.LogInformation("将传送至 {country} {area} 七天神像", country, area);
await Tp(x, y);
if (_tpConfig.ShouldMove || _tpConfig.IsReviveInNearestStatueOfTheSeven)
{
(x, y) = GetClosestPoint(revivePoint.TranX, revivePoint.TranY, x, y, 5);
var waypoint = new Waypoint
{
X = x,
@@ -98,18 +101,45 @@ public class TpTask(CancellationToken ct)
};
var waypointForTrack = new WaypointForTrack(waypoint);
await new PathExecutor(ct).MoveTo(waypointForTrack);
Simulation.SendInput.SimulateAction(GIActions.Drop);
}
await Delay((int)(_tpConfig.HpRestoreDuration * 1000), ct);
}
/// <summary>
///
/// </summary>
/// <param name="tranX"> 传送后实际到达的点X坐标 </param>
/// <param name="tranY"> 传送后实际到达的点Y坐标 </param>
/// <param name="x"> 传送点 X 坐标 </param>
/// <param name="y"> 传送点 Y 坐标 </param>
/// <param name="d"> 期望最终离传送点的距离 </param>
/// <returns> </returns>
private static (double X, double Y) GetClosestPoint(double tranX, double tranY, double x, double y, double d)
{
double dx = x - tranX;
double dy = y - tranY;
double distanceSquared = dx * dx + dy * dy;
double distance = Math.Sqrt(distanceSquared);
d = d > 0 ? d : 0;
if (distance < d)
{
return (tranX, tranY);
}
double ratio = d / distance;
double px = (x - dx * ratio);
double py = (y - dy * ratio);
return (px, py);
}
/// <summary>
/// 获取离 x,y 最近的七天神像
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private GiTpPosition? GetNearestGoddess(double x, double y)
private GiTpPosition GetNearestGoddess(double x, double y)
{
GiTpPosition? nearestGiTpPosition = null;
double minDistance = double.MaxValue;
@@ -123,7 +153,7 @@ public class TpTask(CancellationToken ct)
}
}
// 获取最近的神像位置
return nearestGiTpPosition;
return nearestGiTpPosition ?? throw new InvalidOperationException("没找到最近的七天神像");;
}
/// <summary>
@@ -1,6 +1,7 @@
using BetterGenshinImpact.GameTask.Model.Area;
using System;
using System.Drawing;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask;
@@ -11,7 +12,6 @@ namespace BetterGenshinImpact.GameTask;
public class CaptureContent : IDisposable
{
public static readonly int MaxFrameIndexSecond = 60;
private Bitmap? SrcBitmap { get; }
public int FrameIndex { get; }
public double TimerInterval { get; }
@@ -19,14 +19,13 @@ public class CaptureContent : IDisposable
public ImageRegion CaptureRectArea { get; private set; }
public CaptureContent(Bitmap srcBitmap, int frameIndex, double interval)
public CaptureContent(Mat image, int frameIndex, double interval)
{
SrcBitmap = srcBitmap;
FrameIndex = frameIndex;
TimerInterval = interval;
var systemInfo = TaskContext.Instance().SystemInfo;
var gameCaptureRegion = systemInfo.DesktopRectArea.Derive(srcBitmap, systemInfo.CaptureAreaRect.X, systemInfo.CaptureAreaRect.Y);
var gameCaptureRegion = systemInfo.DesktopRectArea.Derive(image, systemInfo.CaptureAreaRect.X, systemInfo.CaptureAreaRect.Y);
CaptureRectArea = gameCaptureRegion.DeriveTo1080P();
}
@@ -42,6 +41,5 @@ public class CaptureContent : IDisposable
public void Dispose()
{
CaptureRectArea.Dispose();
SrcBitmap?.Dispose();
}
}
}
@@ -7,6 +7,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Area;
using Fischless.GameCapture;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using Vanara.PInvoke;
namespace BetterGenshinImpact.GameTask.Common;
@@ -16,8 +17,6 @@ public class TaskControl
public static ILogger Logger { get; } = App.GetLogger<TaskControl>();
public static readonly SemaphoreSlim TaskSemaphore = new(1, 1);
public static void CheckAndSleep(int millisecondsTimeout)
@@ -177,88 +176,45 @@ public class TaskControl
}
}
public static Bitmap CaptureGameBitmap(IGameCapture? gameCapture)
public static Mat CaptureGameImage(IGameCapture? gameCapture)
{
var bitmap = gameCapture?.Capture();
// wgc 缓冲区设置的2 所以至少截图3次
if (gameCapture?.Mode == CaptureModes.WindowsGraphicsCapture)
{
for (int i = 0; i < 2; i++)
{
bitmap = gameCapture?.Capture();
Sleep(50);
}
}
if (bitmap == null)
var image = gameCapture?.Capture();
if (image == null)
{
Logger.LogWarning("截图失败!");
// 重试5次
for (var i = 0; i < 5; i++)
// 重试3次
for (var i = 0; i < 3; i++)
{
bitmap = gameCapture?.Capture();
if (bitmap != null)
image = gameCapture?.Capture();
if (image != null)
{
return bitmap;
return image;
}
Sleep(30);
}
throw new Exception("尝试多次后,截图失败!");
}
else
{
return bitmap;
return image;
}
}
public static Bitmap? CaptureGameBitmapNoRetry(IGameCapture? gameCapture)
public static Mat? CaptureGameImageNoRetry(IGameCapture? gameCapture)
{
return gameCapture?.Capture();
}
// private static CaptureContent CaptureToContent(IGameCapture? gameCapture)
// {
// var bitmap = CaptureGameBitmap(gameCapture);
// return new CaptureContent(bitmap, 0, 0);
// }
//
// public static CaptureContent CaptureToContent()
// {
// return CaptureToContent(TaskTriggerDispatcher.GlobalGameCapture);
// }
// public static ImageRegion CaptureToRectArea()
// {
// return CaptureToContent(TaskTriggerDispatcher.GlobalGameCapture).CaptureRectArea;
// }
// /// <summary>
// /// 此方法 TaskDispatcher至少处于 DispatcherCaptureModeEnum.CacheCaptureWithTrigger 状态才能使用
// /// </summary>
// /// <returns></returns>
// [Obsolete]
// public static CaptureContent GetContentFromDispatcher()
// {
// return TaskTriggerDispatcher.Instance().GetLastCaptureContent();
// }
// /// <summary>
// /// 此方法 TaskDispatcher至少处于 DispatcherCaptureModeEnum.CacheCaptureWithTrigger 状态才能使用
// /// </summary>
// /// <returns></returns>
// public static ImageRegion GetRectAreaFromDispatcher()
// {
// return TaskTriggerDispatcher.Instance().GetLastCaptureContent().CaptureRectArea;
// }
/// <summary>
/// 自动判断当前运行上下文中截图方式,并选择合适的截图方式返回
/// </summary>
/// <returns></returns>
public static ImageRegion CaptureToRectArea(bool forceNew = false)
{
return TaskTriggerDispatcher.Instance().CaptureToRectArea(forceNew);
var image =CaptureGameImage(TaskTriggerDispatcher.GlobalGameCapture);
var content = new CaptureContent(image, 0, 0);
return content.CaptureRectArea;
}
}
@@ -91,7 +91,7 @@ namespace LogParse
if (configGroupEntity != null)
{
result = parseBgiLine(@"→ 开始执行地图追踪任务: ""(.+?)""", logstr);
result = parseBgiLine(@"→ 开始执行(?:地图追踪任务|JS脚本): ""(.+?)""", logstr);
if (result.Item1)
{
configTask = new();
@@ -108,6 +108,7 @@ namespace LogParse
{
configTask.Fault.ReviveCount++;
}
//传送失败,重试 n 次
result = parseBgiLine($@"传送失败,重试 (\d+) 次", logstr);
if (result.Item1)
@@ -115,19 +116,31 @@ namespace LogParse
configTask.Fault.TeleportFailCount = int.Parse(result.Item2[1]);
}
//战斗超时结束
if (logstr == "战斗超时结束")
{
configTask.Fault.BattleTimeoutCount ++;
}
}
//重试一次路线或放弃此路线!
if (logstr.EndsWith("重试一次路线或放弃此路线!"))
{
configTask.Fault.RetryCount++;
configTask.Fault.RetryCount ++;
}
//疑似卡死,尝试脱离...
if (logstr == "疑似卡死,尝试脱离...")
{
configTask.Fault.StuckCount ++;
}
//One or more errors occurred
result = parseBgiLine(@"执行脚本时发生异常: ""(.+?)""", logstr);
if (result.Item1)
{
configTask.Fault.ErrCount ++;
}
if (logstr.StartsWith("→ 脚本执行结束: \"" + configTask.Name + "\""))
{
@@ -241,11 +254,14 @@ namespace LogParse
public int ReviveCount { get; set; } = 0;
//传送失败次数
public int TeleportFailCount { get; set; } = 0;
//疑似卡死次数
public int StuckCount { get; set; } = 0;
//重试次数
public int RetryCount { get; set; } = 0;
//战斗超时
public int BattleTimeoutCount { get; set; } = 0;
//异常发生次数
public int ErrCount { get; set; } = 0;
}
}
@@ -401,8 +417,10 @@ namespace LogParse
{
colConfigList.Add((name: "复活次数", value: task => FormatNumberWithStyle(task.Fault.ReviveCount)));
colConfigList.Add((name: "重试次数", value: task => FormatNumberWithStyle(task.Fault.RetryCount)));
colConfigList.Add((name: "疑似卡死次数", value: task => FormatNumberWithStyle(task.Fault.StuckCount)));
colConfigList.Add((name: "战斗超时次数", value: task => FormatNumberWithStyle(task.Fault.BattleTimeoutCount)));
colConfigList.Add((name: "传送失败次数", value: task => FormatNumberWithStyle(task.Fault.TeleportFailCount)));
colConfigList.Add((name: "异常发生次数", value: task => FormatNumberWithStyle(task.Fault.ErrCount)));
}
@@ -3,6 +3,7 @@ using BetterGenshinImpact.GameTask.Model.Area.Converter;
using BetterGenshinImpact.Helpers;
using Fischless.WindowsInput;
using System.Drawing;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Model.Area;
@@ -67,8 +68,8 @@ public class DesktopRegion : Region
Simulation.SendInput.Mouse.MoveMouseBy((int)dx, (int)dy);
}
public GameCaptureRegion Derive(Bitmap captureBitmap, int x, int y)
public GameCaptureRegion Derive(Mat captureMat, int x, int y)
{
return new GameCaptureRegion(captureBitmap, x, y, this, new TranslationConverter(x, y));
return new GameCaptureRegion(captureMat, x, y, this, new TranslationConverter(x, y));
}
}
@@ -11,7 +11,7 @@ namespace BetterGenshinImpact.GameTask.Model.Area;
/// 游戏捕获区域类
/// 主要用于转换到遮罩窗口的坐标
/// </summary>
public class GameCaptureRegion(Bitmap bitmap, int initX, int initY, Region? owner = null, INodeConverter? converter = null, DrawContent? drawContent = null) : ImageRegion(bitmap, initX, initY, owner, converter, drawContent)
public class GameCaptureRegion(Mat mat, int initX, int initY, Region? owner = null, INodeConverter? converter = null, DrawContent? drawContent = null) : ImageRegion(mat, initX, initY, owner, converter, drawContent)
{
/// <summary>
/// 在游戏捕获图像的坐标维度进行转换到遮罩窗口的坐标维度
@@ -76,7 +76,7 @@ public class ImageRegion : Region
_srcBitmap = bitmap;
}
public ImageRegion(Mat mat, int x, int y, Region? owner = null, INodeConverter? converter = null) : base(x, y, mat.Width, mat.Height, owner, converter)
public ImageRegion(Mat mat, int x, int y, Region? owner = null, INodeConverter? converter = null, DrawContent? drawContent = null) : base(x, y, mat.Width, mat.Height, owner, converter)
{
_srcMat = mat;
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.Model.Enum;

using System.Threading;
namespace BetterGenshinImpact.GameTask.Model;
@@ -1,29 +0,0 @@
namespace BetterGenshinImpact.GameTask.Model.Enum;
/// <summary>
/// 调度器捕获模式, 影响以下内容:
/// 1. 是否缓存图像
/// 2. 是否执行触发器
/// </summary>
public enum DispatcherCaptureModeEnum
{
// 正常运行调度器
NormalTrigger,
// 正常运行调度器,但不执行触发器,仅捕获并缓存图像模式
OnlyCacheCapture,
// 正常运行调度器,捕获并缓存图像模式,并执行触发器
CacheCaptureWithTrigger,
// --------------------------------------------
// 下面两个模式无法直接设置,只能通过调度器的 StartTimer 和 StopTimer 方法来设置
// 停止运行整个调度器
Stop,
// 启动整个调度器
Start,
// --------------------------------------------
}
@@ -1,24 +0,0 @@
namespace BetterGenshinImpact.GameTask.Model.Enum;
/// <summary>
/// 存在触发器运行的情况下,优先使用触发器的缓存图像
/// 此枚举会影响调度器使用的 DispatcherCaptureModeEnum 模式
/// </summary>
public enum DispatcherTimerOperationEnum
{
// 关闭实时触发器,自己主动获取图像
UseSelfCaptureImage,
// 使用实时触发器的缓存图模式,但是不执行触发器
UseCacheImage,
// 使用实时触发器的缓存图模式,并执行触发器
UseCacheImageWithTrigger,
// 使用实时触发器的缓存图模式,并清空当前已有触发器,执行触发器
// 清空触发器是为了让js脚本手动添加触发器
UseCacheImageWithTriggerEmpty,
// 不做任何操作
None
}
+7 -49
View File
@@ -1,6 +1,6 @@
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.View;
using BetterGenshinImpact.View.Drawable;
using Microsoft.Extensions.Logging;
@@ -23,7 +23,7 @@ public class TaskRunner
{
private readonly ILogger<TaskRunner> _logger = App.GetLogger<TaskRunner>();
private readonly DispatcherTimerOperationEnum _timerOperation = DispatcherTimerOperationEnum.None;
// private readonly DispatcherTimerOperationEnum _timerOperation = DispatcherTimerOperationEnum.None;
private readonly string _name = string.Empty;
@@ -31,11 +31,11 @@ public class TaskRunner
{
}
public TaskRunner(DispatcherTimerOperationEnum timerOperation)
{
_timerOperation = timerOperation;
}
// public TaskRunner(DispatcherTimerOperationEnum timerOperation)
// {
// _timerOperation = timerOperation;
// }
/// <summary>
/// 加锁并独立运行任务
/// </summary>
@@ -134,27 +134,6 @@ public class TaskRunner
var maskWindow = MaskWindow.Instance();
SystemControl.ActivateWindow();
maskWindow.Invoke(maskWindow.Show);
if (_timerOperation == DispatcherTimerOperationEnum.UseSelfCaptureImage)
{
Thread.Sleep(TaskContext.Instance().Config.TriggerInterval * 5); // 等待日志窗口被激活
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.Stop);
}
else if (_timerOperation == DispatcherTimerOperationEnum.UseCacheImage)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Thread.Sleep(TaskContext.Instance().Config.TriggerInterval * 5); // 等待缓存图像
}
else if (_timerOperation == DispatcherTimerOperationEnum.UseCacheImageWithTrigger)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
Thread.Sleep(TaskContext.Instance().Config.TriggerInterval * 5); // 等待缓存图像
}
else if (_timerOperation == DispatcherTimerOperationEnum.UseCacheImageWithTriggerEmpty)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
TaskTriggerDispatcher.Instance().ClearTriggers();
Thread.Sleep(TaskContext.Instance().Config.TriggerInterval * 5); // 等待缓存图像
}
}
public void End()
@@ -165,27 +144,6 @@ public class TaskRunner
}
VisionContext.Instance().DrawContent.ClearAll();
if (_timerOperation == DispatcherTimerOperationEnum.UseSelfCaptureImage)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.Start);
}
else if (_timerOperation is DispatcherTimerOperationEnum.UseCacheImage or DispatcherTimerOperationEnum.UseCacheImageWithTrigger or DispatcherTimerOperationEnum.UseCacheImageWithTriggerEmpty)
{
// 还原到原来的模式
if (TaskContext.Instance().Config.CommonConfig.ScreenshotEnabled || TaskContext.Instance().Config.MacroConfig.CombatMacroEnabled)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
}
else
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
}
if (_timerOperation == DispatcherTimerOperationEnum.UseCacheImageWithTriggerEmpty)
{
TaskTriggerDispatcher.Instance().SetTriggers(GameTaskManager.LoadInitialTriggers());
}
}
}
}
@@ -1,31 +1,18 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoMusicGame;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.AutoWood;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.View;
using Fischless.GameCapture;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Fischless.GameCapture.Graphics;
using Vanara.PInvoke;
namespace BetterGenshinImpact.GameTask
@@ -49,19 +36,6 @@ namespace BetterGenshinImpact.GameTask
private DateTime _prevManualGc = DateTime.MinValue;
/// <summary>
/// 捕获结果队列
/// </summary>
private Bitmap _bitmap = new(10, 10);
/// <summary>
/// 调度器捕获模式, 影响以下内容:
/// 1. 是否缓存图像
/// 2. 是否执行触发器
/// </summary>
private DispatcherCaptureModeEnum _dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.NormalTrigger;
private static readonly object _bitmapLocker = new();
private static readonly object _triggerListLocker = new();
public event EventHandler? UiTaskStopTickEvent;
@@ -138,22 +112,20 @@ namespace BetterGenshinImpact.GameTask
// 初始化触发器(一定要在任务上下文初始化完毕后使用)
_triggers = GameTaskManager.LoadInitialTriggers();
if (GraphicsCapture.IsHdrEnabled(hWnd))
{
_logger.LogError("游戏窗口在HDR模式下无法获取正常颜色的截图,请关闭HDR模式!");
}
// 启动截图
GameCapture.Start(hWnd,
new Dictionary<string, object>()
{
{ "useBitmapCache", TaskContext.Instance().Config.WgcUseBitmapCache },
{ "autoFixWin11BitBlt", OsVersionHelper.IsWindows11_OrGreater && TaskContext.Instance().Config.AutoFixWin11BitBlt }
}
);
// 捕获模式初始化配置
if (TaskContext.Instance().Config.CommonConfig.ScreenshotEnabled || TaskContext.Instance().Config.MacroConfig.CombatMacroEnabled)
{
_dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.CacheCaptureWithTrigger;
}
// 启动定时器
_frameIndex = 0;
_timer.Interval = interval;
@@ -187,11 +159,6 @@ namespace BetterGenshinImpact.GameTask
}
}
public System.Timers.Timer GetTimer()
{
return _timer;
}
public void Dispose()
{
Stop();
@@ -284,13 +251,13 @@ namespace BetterGenshinImpact.GameTask
{
// if (!_prevGameActive)
// {
maskWindow.Invoke(() =>
maskWindow.Invoke(() =>
{
if (maskWindow.IsExist())
{
if (maskWindow.IsExist())
{
maskWindow.Show();
}
});
maskWindow.Show();
}
});
// }
}
@@ -305,10 +272,9 @@ namespace BetterGenshinImpact.GameTask
// 帧序号自增 1分钟后归零(MaxFrameIndexSecond)
_frameIndex = (_frameIndex + 1) % (int)(CaptureContent.MaxFrameIndexSecond * 1000d / _timer.Interval);
if (_dispatcherCacheCaptureMode == DispatcherCaptureModeEnum.NormalTrigger
&& (_triggers == null || !_triggers.Exists(t => t.IsEnabled)))
if (_triggers == null || !_triggers.Exists(t => t.IsEnabled))
{
// Debug.WriteLine("没有可用的触发器且不处于仅截屏状态, 不再进行截屏");
Debug.WriteLine("没有可用的触发器且不处于仅截屏状态, 不再进行截屏");
return;
}
@@ -323,11 +289,6 @@ namespace BetterGenshinImpact.GameTask
return;
}
if (IsOnlyCacheCapture(bitmap))
{
return;
}
// 循环执行所有触发器 有独占状态的触发器的时候只执行独占触发器
var content = new CaptureContent(bitmap, _frameIndex, _timer.Interval);
@@ -336,7 +297,6 @@ namespace BetterGenshinImpact.GameTask
var exclusiveTrigger = _triggers!.FirstOrDefault(t => t is { IsEnabled: true, IsExclusive: true });
if (exclusiveTrigger != null)
{
exclusiveTrigger.OnCapture(content);
speedTimer.Record(exclusiveTrigger.Name);
}
@@ -350,13 +310,12 @@ namespace BetterGenshinImpact.GameTask
foreach (var trigger in runningTriggers)
{
trigger.OnCapture(content);
speedTimer.Record(trigger.Name);
}
}
}
speedTimer.DebugPrint();
content.Dispose();
}
@@ -413,118 +372,38 @@ namespace BetterGenshinImpact.GameTask
return rect.Width == 0 || rect.Height == 0;
}
/// <summary>
/// 是否仅缓存截图
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
private bool IsOnlyCacheCapture(Bitmap bitmap)
{
lock (_bitmapLocker)
{
if (_dispatcherCacheCaptureMode is DispatcherCaptureModeEnum.OnlyCacheCapture or DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
{
_bitmap = new Bitmap(bitmap);
if (_dispatcherCacheCaptureMode == DispatcherCaptureModeEnum.OnlyCacheCapture)
{
return true;
}
}
return false;
}
}
public void SetCacheCaptureMode(DispatcherCaptureModeEnum mode)
{
if (mode is DispatcherCaptureModeEnum.Start)
{
this.StartTimer();
}
else if (mode is DispatcherCaptureModeEnum.Stop)
{
this.StopTimer();
}
else
{
_dispatcherCacheCaptureMode = mode;
}
}
public DispatcherCaptureModeEnum GetCacheCaptureMode()
{
return _dispatcherCacheCaptureMode;
}
public Bitmap GetLastCaptureBitmap()
{
lock (_bitmapLocker)
{
return new Bitmap(_bitmap);
}
}
public CaptureContent GetLastCaptureContent()
{
var bitmap = GetLastCaptureBitmap();
return new CaptureContent(bitmap, _frameIndex, _timer.Interval);
}
public ImageRegion CaptureToRectArea(bool forceNew = false)
{
// 触发器启动的情况下优先使用触发器的截图
if (!forceNew && _timer.Enabled && _dispatcherCacheCaptureMode is DispatcherCaptureModeEnum.OnlyCacheCapture or DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
{
return GetLastCaptureContent().CaptureRectArea;
}
else
{
var bitmap = TaskControl.CaptureGameBitmap(GameCapture);
var content = new CaptureContent(bitmap, 0, 0);
return content.CaptureRectArea;
}
}
public void TakeScreenshot()
{
if (_dispatcherCacheCaptureMode is DispatcherCaptureModeEnum.OnlyCacheCapture or DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
try
{
try
var path = Global.Absolute($@"log\screenshot\");
if (!Directory.Exists(path))
{
var path = Global.Absolute($@"log\screenshot\");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var bitmap = GetLastCaptureBitmap();
var name = $@"{DateTime.Now:yyyyMMddHHmmssffff}.png";
var savePath = Global.Absolute($@"log\screenshot\{name}");
if (TaskContext.Instance().Config.CommonConfig.ScreenshotUidCoverEnabled)
{
var mat = bitmap.ToMat();
var rect = TaskContext.Instance().Config.MaskWindowConfig.UidCoverRect;
mat.Rectangle(rect, Scalar.White, -1);
Cv2.ImWrite(savePath, mat);
}
else
{
bitmap.Save(savePath, ImageFormat.Png);
}
_logger.LogInformation("截图已保存: {Name}", name);
Directory.CreateDirectory(path);
}
catch (Exception e)
var bitmap = TaskControl.CaptureGameImage(GameCapture);
var name = $@"{DateTime.Now:yyyyMMddHHmmssffff}.png";
var savePath = Global.Absolute($@"log\screenshot\{name}");
if (TaskContext.Instance().Config.CommonConfig.ScreenshotUidCoverEnabled)
{
_logger.LogError("截图保存失败: {Message}", e.Message);
_logger.LogDebug("截图保存失败: {StackTrace}", e.StackTrace);
var rect = TaskContext.Instance().Config.MaskWindowConfig.UidCoverRect;
bitmap.Rectangle(rect, Scalar.White, -1);
Cv2.ImWrite(savePath, bitmap);
}
else
{
Cv2.ImWrite(savePath, bitmap);
}
_logger.LogInformation("截图已保存: {Name}", name);
}
else
catch (Exception e)
{
_logger.LogWarning("当前不处于截图模式,无法保存截图");
_logger.LogError("截图保存失败: {Message}", e.Message);
_logger.LogDebug("截图保存失败: {StackTrace}", e.StackTrace);
}
}
}
}
}
@@ -13,16 +13,10 @@ namespace BetterGenshinImpact.Service;
/// <summary>
/// Managed host of the application.
/// </summary>
public class ApplicationHostService : IHostedService
public class ApplicationHostService(IServiceProvider serviceProvider) : IHostedService
{
private readonly IServiceProvider _serviceProvider;
private INavigationWindow? _navigationWindow;
public ApplicationHostService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
@@ -50,12 +44,10 @@ public class ApplicationHostService : IHostedService
if (!Application.Current.Windows.OfType<MainWindow>().Any())
{
_navigationWindow = (
_serviceProvider.GetService(typeof(INavigationWindow)) as INavigationWindow
)!;
_navigationWindow = (serviceProvider.GetService(typeof(INavigationWindow)) as INavigationWindow)!;
_navigationWindow!.ShowWindow();
_navigationWindow.Navigate(typeof(HomePage));
_ = _navigationWindow.Navigate(typeof(HomePage));
}
await Task.CompletedTask;
@@ -1,72 +1,182 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using CommunityToolkit.Mvvm.ComponentModel;
namespace BetterGenshinImpact.Service.Notification;
/// <summary>
/// Notification
/// 通知配置管理器
/// </summary>
[Serializable]
public partial class NotificationConfig : ObservableObject
{
[ObservableProperty]
private string _notificationEventSubscribe = string.Empty;
/// <summary>
///
/// 传"none"时,点击推送不会弹窗
/// </summary>
[ObservableProperty]
private bool _webhookEnabled;
[ObservableProperty] private string _barkAction = string.Empty;
[ObservableProperty] private string _barkApiEndpoint = string.Empty;
/// <summary>
///
/// iOS14.5以下自动复制推送内容,1为开启
/// </summary>
[ObservableProperty]
private string _webhookEndpoint = string.Empty;
[ObservableProperty] private string _barkAutoCopy = string.Empty;
/// <summary>
/// 推送角标,可以是任意数字
/// </summary>
[ObservableProperty] private int _barkBadge = 1;
/// <summary>
/// 通知铃声重复播放,1为开启
/// </summary>
[ObservableProperty] private string _barkCall = string.Empty;
[ObservableProperty] private string _barkCiphertext = string.Empty;
/// <summary>
/// 复制推送时指定复制的内容
/// </summary>
[ObservableProperty] private string _barkCopy = string.Empty;
[ObservableProperty] private string _barkDeviceKeys = string.Empty;
/// <summary>
/// 对消息进行分组,推送将按group分组显示在通知中心中
/// </summary>
[ObservableProperty] private string _barkGroup = "default";
/// <summary>
/// 为推送设置自定义图标URL
/// </summary>
[ObservableProperty] private string _barkIcon = string.Empty;
/// <summary>
/// 传1保存推送,传其他的不保存推送
/// </summary>
[ObservableProperty] private string _barkIsArchive = "1";
/// <summary>
/// 推送中断级别:critical(重要警告), active(默认值), timeSensitive(时效性通知), passive(仅添加到通知列表)
/// </summary>
[ObservableProperty] private string _barkLevel = "active";
/// <summary>
/// Bark移动推送通知配置
/// </summary>
[ObservableProperty] private bool _barkNotificationEnabled;
/// <summary>
/// 通知声音
/// </summary>
[ObservableProperty] private string _barkSound = "minuet";
// Bark 通知附加参数配置
/// <summary>
/// 推送副标题
/// </summary>
[ObservableProperty] private string _barkSubtitle = string.Empty;
/// <summary>
/// 点击推送时跳转的URL
/// </summary>
[ObservableProperty] private string _barkUrl = string.Empty;
/// <summary>
/// 重要警告的通知音量,取值范围: 0-10
/// </summary>
[ObservableProperty] private int _barkVolume = 5;
// Email 通知配置
[ObservableProperty] private bool _emailNotificationEnabled;
// 飞书通知
/// <summary>
/// 飞书通知是否启用
/// </summary>
[ObservableProperty] private bool _feishuNotificationEnabled;
/// <summary>
/// 是否包含截图
/// 飞书通知地址
/// </summary>
[ObservableProperty]
private bool _includeScreenShot = true;
[ObservableProperty] private string _feishuWebhookUrl = string.Empty;
[ObservableProperty] private string _fromEmail = string.Empty;
[ObservableProperty] private string _fromName = string.Empty;
/// <summary>
/// 是否包含截图
/// </summary>
[ObservableProperty] private bool _includeScreenShot = true;
[ObservableProperty] private string _notificationEventSubscribe = string.Empty;
[ObservableProperty] private string _smtpPassword = string.Empty;
[ObservableProperty] private int _smtpPort;
[ObservableProperty] private string _smtpServer = string.Empty;
[ObservableProperty] private string _smtpUsername = string.Empty;
/// <summary>
/// Telegram API基础URL(可选,留空使用官方API)
/// </summary>
[ObservableProperty] private string _telegramApiBaseUrl = string.Empty;
/// <summary>
/// Telegram机器人Token
/// </summary>
[ObservableProperty] private string _telegramBotToken = string.Empty;
/// <summary>
/// Telegram聊天ID
/// </summary>
[ObservableProperty] private string _telegramChatId = string.Empty;
// Telegram通知
/// <summary>
/// Telegram通知是否启用
/// </summary>
[ObservableProperty] private bool _telegramNotificationEnabled;
[ObservableProperty] private string _toEmail = string.Empty;
/// <summary>
/// </summary>
[ObservableProperty] private bool _webhookEnabled;
/// <summary>
/// </summary>
[ObservableProperty] private string _webhookEndpoint = string.Empty;
[ObservableProperty] private string _webhookSendTo = string.Empty; // 修改属性名
[ObservableProperty] private string _webSocketEndpoint = string.Empty;
[ObservableProperty] private bool _webSocketNotificationEnabled;
/// <summary>
/// windows uwp 通知是否启用
/// </summary>
[ObservableProperty]
private bool _windowsUwpNotificationEnabled = false;
// 飞书通知
/// <summary>
/// 飞书通知是否启用
/// </summary>
[ObservableProperty]
private bool _feishuNotificationEnabled = false;
/// <summary>
/// 飞书通知地址
/// </summary>
[ObservableProperty]
private string _feishuWebhookUrl = string.Empty;
[ObservableProperty] private bool _windowsUwpNotificationEnabled;
// 企业微信通知
/// <summary>
/// 企业微信通知是否启用
/// 企业微信通知是否启用
/// </summary>
[ObservableProperty]
private bool _workweixinNotificationEnabled = false;
[ObservableProperty] private bool _workweixinNotificationEnabled;
/// <summary>
/// 企业微信通知通知地址
/// 企业微信通知通知地址
/// </summary>
[ObservableProperty]
private string _workweixinWebhookUrl = string.Empty;
}
[ObservableProperty] private string _workweixinWebhookUrl = string.Empty;
}
@@ -6,12 +6,20 @@ using Microsoft.Extensions.Hosting;
using System;
using System.Drawing;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using BetterGenshinImpact.Service.Notifier;
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using OpenCvSharp.Extensions;
namespace BetterGenshinImpact.Service.Notification;
@@ -29,16 +37,6 @@ public class NotificationService : IHostedService
InitializeNotifiers();
}
public static NotificationService Instance()
{
if (_instance == null)
{
throw new Exception("Not instantiated");
}
return _instance;
}
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
@@ -49,12 +47,20 @@ public class NotificationService : IHostedService
return Task.CompletedTask;
}
public static NotificationService Instance()
{
if (_instance == null) throw new Exception("Not instantiated");
return _instance;
}
private void InitializeNotifiers()
{
if (TaskContext.Instance().Config.NotificationConfig.WebhookEnabled)
{
_notifierManager.RegisterNotifier(new WebhookNotifier(NotifyHttpClient, TaskContext.Instance().Config.NotificationConfig.WebhookEndpoint));
_notifierManager.RegisterNotifier(new WebhookNotifier(NotifyHttpClient,
TaskContext.Instance().Config.NotificationConfig));
}
if (TaskContext.Instance().Config.NotificationConfig.WindowsUwpNotificationEnabled)
@@ -64,13 +70,60 @@ public class NotificationService : IHostedService
if (TaskContext.Instance().Config.NotificationConfig.FeishuNotificationEnabled)
{
_notifierManager.RegisterNotifier(new FeishuNotifier(NotifyHttpClient, TaskContext.Instance().Config.NotificationConfig.FeishuWebhookUrl));
_notifierManager.RegisterNotifier(new FeishuNotifier(NotifyHttpClient,
TaskContext.Instance().Config.NotificationConfig.FeishuWebhookUrl));
}
if (TaskContext.Instance().Config.NotificationConfig.WorkweixinNotificationEnabled)
{
_notifierManager.RegisterNotifier(new WorkWeixinNotifier(NotifyHttpClient, TaskContext.Instance().Config.NotificationConfig.WorkweixinWebhookUrl));
_notifierManager.RegisterNotifier(new WorkWeixinNotifier(NotifyHttpClient,
TaskContext.Instance().Config.NotificationConfig.WorkweixinWebhookUrl));
}
// WebSocket通知初始化
if (TaskContext.Instance().Config.NotificationConfig.WebSocketNotificationEnabled)
{
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};
var cts = new CancellationTokenSource();
_notifierManager.RegisterNotifier(new WebSocketNotifier(
TaskContext.Instance().Config.NotificationConfig.WebSocketEndpoint,
jsonSerializerOptions,
cts
));
}
// Bark通知初始化
if (TaskContext.Instance().Config.NotificationConfig.BarkNotificationEnabled)
_notifierManager.RegisterNotifier(new BarkNotifier(
TaskContext.Instance().Config.NotificationConfig.BarkDeviceKeys,
TaskContext.Instance().Config.NotificationConfig.BarkApiEndpoint
));
// 邮件通知初始化
if (TaskContext.Instance().Config.NotificationConfig.EmailNotificationEnabled)
{
_notifierManager.RegisterNotifier(new EmailNotifier(
TaskContext.Instance().Config.NotificationConfig.SmtpServer,
TaskContext.Instance().Config.NotificationConfig.SmtpPort,
TaskContext.Instance().Config.NotificationConfig.SmtpUsername,
TaskContext.Instance().Config.NotificationConfig.SmtpPassword,
TaskContext.Instance().Config.NotificationConfig.FromEmail,
TaskContext.Instance().Config.NotificationConfig.FromName,
TaskContext.Instance().Config.NotificationConfig.ToEmail
));
}
// Telegram通知初始化
if (TaskContext.Instance().Config.NotificationConfig.TelegramNotificationEnabled)
_notifierManager.RegisterNotifier(new TelegramNotifier(
NotifyHttpClient, // 使用共享的HttpClient
TaskContext.Instance().Config.NotificationConfig.TelegramBotToken,
TaskContext.Instance().Config.NotificationConfig.TelegramChatId,
TaskContext.Instance().Config.NotificationConfig.TelegramApiBaseUrl
));
}
public void RefreshNotifiers()
@@ -124,10 +177,10 @@ public class NotificationService : IHostedService
{
if (TaskContext.Instance().Config.NotificationConfig.IncludeScreenShot)
{
var bitmap = TaskControl.CaptureGameBitmapNoRetry(TaskTriggerDispatcher.GlobalGameCapture);
var bitmap = TaskControl.CaptureGameImageNoRetry(TaskTriggerDispatcher.GlobalGameCapture);
if (bitmap != null)
{
notificationData.Screenshot = (Bitmap)bitmap.Clone();
notificationData.Screenshot = bitmap.ToBitmap();
}
}
}
@@ -143,4 +196,12 @@ public class NotificationService : IHostedService
{
Task.Run(() => NotifyAllNotifiersAsync(notificationData));
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
NotifyHttpClient.Dispose();
}
}
@@ -0,0 +1,345 @@
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
namespace BetterGenshinImpact.Service.Notifier
{
/// <summary>
/// Bark通知配置选项
/// </summary>
public class BarkOptions
{
/// <summary>
/// 推送标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 推送副标题
/// </summary>
public string Subtitle { get; set; }
/// <summary>
/// 推送内容
/// </summary>
public string Body { get; set; }
/// <summary>
/// 设备Key
/// </summary>
public string DeviceKey { get; set; }
/// <summary>
/// 推送中断级别:critical(重要警告), active(默认值), timeSensitive(时效性通知), passive(仅添加到通知列表)
/// </summary>
public string Level { get; set; } = "active";
/// <summary>
/// 通知声音,填1时铃声重复播放
/// </summary>
public string Sound { get; set; } = "minuet";
/// <summary>
/// 重要警告的通知音量,取值范围: 0-10, 不传默认值为5
/// </summary>
public int? Volume { get; set; }
/// <summary>
/// 推送角标,可以是任意数字
/// </summary>
public int? Badge { get; set; }
/// <summary>
/// 通知铃声重复播放,传1开启
/// </summary>
public string Call { get; set; }
/// <summary>
/// iOS14.5以下自动复制推送内容,传1开启
/// </summary>
public string AutoCopy { get; set; }
/// <summary>
/// 复制推送时指定复制的内容
/// </summary>
public string Copy { get; set; }
/// <summary>
/// 为推送设置自定义图标,设置的图标将替换默认Bark图标
/// </summary>
public string Icon { get; set; }
/// <summary>
/// 对消息进行分组,推送将按group分组显示在通知中心中
/// </summary>
public string Group { get; set; } = "default";
/// <summary>
/// 加密推送的密文
/// </summary>
public string Ciphertext { get; set; }
/// <summary>
/// 传1保存推送,传其他的不保存推送
/// </summary>
public string IsArchive { get; set; }
/// <summary>
/// 点击推送时跳转的URL
/// </summary>
public string Url { get; set; }
/// <summary>
/// 传"none"时,点击推送不会弹窗
/// </summary>
public string Action { get; set; }
}
public class BarkNotifier : INotifier
{
public string Name { get; set; } = "Bark";
// Bark API配置
private readonly string _apiBaseUrl;
private readonly string[] _deviceKeys;
private readonly HttpClient _httpClient;
private readonly BarkOptions _defaultOptions;
/// <summary>
/// Bark通知器构造函数
/// </summary>
/// <param name="deviceKeys">设备密钥,多个设备使用逗号、分号或空格分隔</param>
/// <param name="apiHost">Bark API基础URL</param>
/// <param name="options">Bark通知默认选项</param>
public BarkNotifier(
string deviceKeys,
string apiHost,
BarkOptions options = null)
{
// 输入验证
if (string.IsNullOrEmpty(deviceKeys))
throw new ArgumentException("必须提供至少一个设备密钥", nameof(deviceKeys));
// 确保主机名格式正确
apiHost = apiHost.TrimEnd('/');
if (!apiHost.StartsWith("http://") && !apiHost.StartsWith("https://"))
apiHost = "https://" + apiHost;
_apiBaseUrl = apiHost;
// 将逗号分隔的设备密钥字符串转换为数组
_deviceKeys = deviceKeys.Split(new[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (_deviceKeys.Length == 0)
throw new ArgumentException("必须提供至少一个有效的设备密钥", nameof(deviceKeys));
// 初始化默认选项
_defaultOptions = options ?? new BarkOptions();
// 使用HttpClient进行API调用
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromSeconds(10); // 设置合理的超时时间
}
/// <summary>
/// 异步发送通知(使用默认选项)
/// </summary>
/// <param name="content">通知内容</param>
public async Task SendAsync(BaseNotificationData content)
{
await SendAsync(content, null);
}
/// <summary>
/// 异步发送通知(自定义选项)
/// </summary>
/// <param name="content">通知内容</param>
/// <param name="options">自定义Bark选项</param>
public async Task SendAsync(BaseNotificationData content, BarkOptions options)
{
try
{
// 合并默认选项和自定义选项
var mergedOptions = MergeOptions(_defaultOptions, options);
// 格式化通知数据
var payload = new Dictionary<string, object>
{
["title"] = mergedOptions.Title ?? FormatNotificationTitle(content),
["body"] = mergedOptions.Body ?? FormatNotificationBody(content)
};
// 添加其他可选参数
if (!string.IsNullOrEmpty(mergedOptions.Subtitle))
payload["subtitle"] = mergedOptions.Subtitle;
if (!string.IsNullOrEmpty(mergedOptions.Level))
payload["level"] = mergedOptions.Level;
if (!string.IsNullOrEmpty(mergedOptions.Sound))
payload["sound"] = mergedOptions.Sound;
if (mergedOptions.Volume.HasValue)
payload["volume"] = mergedOptions.Volume.Value;
if (mergedOptions.Badge.HasValue)
payload["badge"] = mergedOptions.Badge.Value;
if (!string.IsNullOrEmpty(mergedOptions.Call))
payload["call"] = mergedOptions.Call;
if (!string.IsNullOrEmpty(mergedOptions.AutoCopy))
payload["autoCopy"] = mergedOptions.AutoCopy;
if (!string.IsNullOrEmpty(mergedOptions.Copy))
payload["copy"] = mergedOptions.Copy;
if (!string.IsNullOrEmpty(mergedOptions.Icon))
payload["icon"] = mergedOptions.Icon;
if (!string.IsNullOrEmpty(mergedOptions.Group))
payload["group"] = mergedOptions.Group;
if (!string.IsNullOrEmpty(mergedOptions.Ciphertext))
payload["ciphertext"] = mergedOptions.Ciphertext;
if (!string.IsNullOrEmpty(mergedOptions.IsArchive))
payload["isArchive"] = mergedOptions.IsArchive;
if (!string.IsNullOrEmpty(mergedOptions.Url))
payload["url"] = mergedOptions.Url;
if (!string.IsNullOrEmpty(mergedOptions.Action))
payload["action"] = mergedOptions.Action;
// 序列化通知数据
var jsonPayload = JsonSerializer.Serialize(payload);
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 为每个设备发送单独的请求
var tasks = new List<Task>();
foreach (var deviceKey in _deviceKeys)
{
tasks.Add(SendToDeviceAsync(deviceKey, httpContent, jsonPayload));
}
// 等待所有请求完成
await Task.WhenAll(tasks);
// 检查任务是否有异常
foreach (var task in tasks)
{
if (task.Exception != null)
{
throw task.Exception;
}
}
}
catch (System.Exception ex)
{
throw new NotifierException($"Bark通知发送失败: {ex.Message}");
}
}
/// <summary>
/// 向单个设备发送请求
/// </summary>
private async Task SendToDeviceAsync(string deviceKey, HttpContent httpContent, string jsonPayload)
{
try
{
// 构建URL(按照API要求,设备Key放在URL路径中)
var requestUrl = $"{_apiBaseUrl}/{deviceKey}";
// 输出请求信息用于调试
Console.WriteLine($"发送通知到: {requestUrl}");
Console.WriteLine($"请求内容: {jsonPayload}");
// 发送到API端点
var response = await _httpClient.PostAsync(requestUrl, httpContent);
// 读取响应内容
var responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.Error.WriteLine($"服务器返回错误: {(int)response.StatusCode} {response.StatusCode}");
Console.Error.WriteLine($"响应内容: {responseContent}");
throw new HttpRequestException($"服务器返回错误: {(int)response.StatusCode} {response.StatusCode}, 响应内容: {responseContent}");
}
Console.WriteLine($"通知发送成功: {responseContent}");
}
catch (HttpRequestException ex)
{
// 记录发送失败
Console.Error.WriteLine($"设备 {deviceKey} 通知发送失败: {ex.Message}");
throw new NotifierException($"Bark通知发送失败 (设备: {deviceKey}): {ex.Message}");
}
}
/// <summary>
/// 合并默认选项和自定义选项
/// </summary>
private BarkOptions MergeOptions(BarkOptions defaultOptions, BarkOptions customOptions)
{
if (customOptions == null)
return defaultOptions;
return new BarkOptions
{
Title = customOptions.Title ?? defaultOptions.Title,
Subtitle = customOptions.Subtitle ?? defaultOptions.Subtitle,
Body = customOptions.Body ?? defaultOptions.Body,
DeviceKey = customOptions.DeviceKey ?? defaultOptions.DeviceKey,
Level = customOptions.Level ?? defaultOptions.Level,
Sound = customOptions.Sound ?? defaultOptions.Sound,
Volume = customOptions.Volume ?? defaultOptions.Volume,
Badge = customOptions.Badge ?? defaultOptions.Badge,
Call = customOptions.Call ?? defaultOptions.Call,
AutoCopy = customOptions.AutoCopy ?? defaultOptions.AutoCopy,
Copy = customOptions.Copy ?? defaultOptions.Copy,
Icon = customOptions.Icon ?? defaultOptions.Icon,
Group = customOptions.Group ?? defaultOptions.Group,
Ciphertext = customOptions.Ciphertext ?? defaultOptions.Ciphertext,
IsArchive = customOptions.IsArchive ?? defaultOptions.IsArchive,
Url = customOptions.Url ?? defaultOptions.Url,
Action = customOptions.Action ?? defaultOptions.Action
};
}
/// <summary>
/// 格式化通知标题
/// </summary>
private string FormatNotificationTitle(BaseNotificationData content)
{
return $"通知 - {content.GetType().Name}";
}
/// <summary>
/// 格式化通知正文
/// </summary>
private string FormatNotificationBody(BaseNotificationData content)
{
var bodyBuilder = new StringBuilder();
foreach (var prop in content.GetType().GetProperties())
{
var value = prop.GetValue(content);
if (value != null)
{
bodyBuilder.AppendLine($"{prop.Name}: {value}");
}
}
return bodyBuilder.ToString();
}
}
}
@@ -0,0 +1,167 @@
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
namespace BetterGenshinImpact.Service.Notifier
{
public class EmailNotifier : INotifier
{
// 发件人配置
private readonly string _fromEmail;
private readonly string _fromName;
private readonly string _smtpPassword;
private readonly int _smtpPort;
// SMTP服务器配置
private readonly string _smtpServer;
private readonly string _smtpUsername;
public EmailNotifier(
string smtpServer,
int smtpPort,
string smtpUsername,
string smtpPassword,
string fromEmail,
string fromName,
string toEmail = "")
{
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_smtpUsername = smtpUsername;
_smtpPassword = smtpPassword;
_fromEmail = fromEmail;
_fromName = fromName;
ToEmail = toEmail;
// 忽略SSL证书验证错误
ServicePointManager.ServerCertificateValidationCallback =
delegate { return true; };
}
// 收件人邮箱
public string ToEmail { get; set; }
public string Name { get; set; } = "Email";
public async Task SendAsync(BaseNotificationData content)
{
if (string.IsNullOrEmpty(ToEmail))
{
throw new NotifierException("收件人邮箱地址为空");
}
// 创建一个新的SmtpClient实例(不复用)
using (var smtpClient = new SmtpClient())
{
try
{
// 配置SMTP客户端
smtpClient.Host = _smtpServer;
smtpClient.Port = _smtpPort;
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
smtpClient.Timeout = 30000; // 30秒超时
// 创建邮件
using (var mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(_fromEmail, _fromName);
mailMessage.To.Add(ToEmail);
mailMessage.Subject = FormatEmailSubject(content);
mailMessage.Body = FormatEmailBody(content);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.SubjectEncoding = Encoding.UTF8;
// 添加图片附件(如果存在)
if (content.Screenshot != null)
{
var tempPath = Path.GetTempFileName() + ".jpg";
try
{
// 保存图片到临时文件
content.Screenshot.Save(tempPath, ImageFormat.Jpeg);
// 从文件添加附件
var attachment = new Attachment(tempPath);
mailMessage.Attachments.Add(attachment);
// 发送邮件
await smtpClient.SendMailAsync(mailMessage);
// 清理附件和临时文件
attachment.Dispose();
if (File.Exists(tempPath)) File.Delete(tempPath);
}
catch (System.Exception ex)
{
// 尝试清理临时文件
try
{
if (File.Exists(tempPath)) File.Delete(tempPath);
}
catch
{
/* 忽略清理错误 */
}
throw new NotifierException($"发送邮件失败: {ex.Message}");
}
}
else
{
// 没有图片时直接发送
await smtpClient.SendMailAsync(mailMessage);
}
}
}
catch (System.Exception ex)
{
var errorMessage = $"发送邮件失败: {ex.Message}";
throw new NotifierException(errorMessage);
}
}
}
private string FormatEmailSubject(BaseNotificationData content)
{
// 可以根据实际需求自定义邮件主题格式
return $"通知 - {content.GetType().Name}";
}
private string FormatEmailBody(BaseNotificationData content)
{
var builder = new StringBuilder();
builder.AppendLine("<html><body style='font-family: Arial, sans-serif;'>");
// 添加通知标题
builder.AppendLine("<h2 style='color: #333;'>通知详情</h2>");
// 添加通知内容
foreach (var prop in content.GetType().GetProperties())
{
// 跳过Screenshot属性,它会单独处理
if (prop.Name == "Screenshot")
continue;
var value = prop.GetValue(content);
if (value != null)
{
builder.AppendFormat("<p><strong>{0}:</strong> {1}</p>", prop.Name, value);
}
}
// 添加提示信息
builder.AppendLine("<p><em>如有截图,请查看附件。</em></p>");
builder.AppendLine("</body></html>");
return builder.ToString();
}
}
}
@@ -0,0 +1,226 @@
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
namespace BetterGenshinImpact.Service.Notifier;
public class TelegramNotifier : INotifier, IDisposable
{
// 永远不更改此URL常量,这是Telegram API的标准URL前缀
private const string TELEGRAM_API_URL = "https://api.telegram.org/bot";
private readonly bool _createdHttpClient;
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};
/// <summary>
/// 创建一个新的Telegram通知器实例
/// </summary>
/// <param name="httpClient">可选的HttpClient,如果不提供则创建新的</param>
/// <param name="telegramBotToken">Telegram机器人Token</param>
/// <param name="telegramChatId">Telegram聊天ID</param>
/// <param name="telegramApiBaseUrl">不再使用,保留参数仅为兼容性</param>
public TelegramNotifier(HttpClient httpClient = null, string telegramBotToken = "", string telegramChatId = "",
string telegramApiBaseUrl = "")
{
TelegramBotToken = telegramBotToken;
TelegramChatId = telegramChatId;
if (httpClient != null)
{
_httpClient = httpClient;
_createdHttpClient = false;
}
else
{
_httpClient = new HttpClient();
_createdHttpClient = true;
_httpClient.Timeout = TimeSpan.FromSeconds(30);
}
// 忽略自定义API URL,始终使用标准Telegram API URL
TelegramApiBaseUrl = TELEGRAM_API_URL;
}
/// <summary>
/// Telegram机器人Token
/// </summary>
public string TelegramBotToken { get; set; }
/// <summary>
/// Telegram聊天ID
/// </summary>
public string TelegramChatId { get; set; }
/// <summary>
/// Telegram API基础URL - 内部使用
/// </summary>
private string TelegramApiBaseUrl { get; set; }
public void Dispose()
{
if (_createdHttpClient)
{
_httpClient?.Dispose();
}
}
/// <summary>
/// 通知器名称
/// </summary>
public string Name { get; set; } = "Telegram";
public async Task SendAsync(BaseNotificationData content)
{
if (string.IsNullOrEmpty(TelegramBotToken))
{
throw new NotifierException("Telegram bot token is not set");
}
if (string.IsNullOrEmpty(TelegramChatId))
{
throw new NotifierException("Telegram chat ID is not set");
}
try
{
var message = content.Message;
var fullMessage = !string.IsNullOrEmpty(message) ? message : "";
if (!string.IsNullOrEmpty(fullMessage))
{
await SendTextMessageAsync(fullMessage);
}
else
{
throw new NotifierException("No message content to send");
}
}
catch (HttpRequestException ex)
{
throw new NotifierException("Network error sending Telegram notification: " + ex.Message);
}
catch (TaskCanceledException)
{
throw new NotifierException("Telegram API request timed out. Check your internet connection.");
}
catch (NotifierException)
{
throw;
}
catch (System.Exception ex)
{
throw new NotifierException("Error sending Telegram notification: " + ex.Message);
}
}
private async Task SendTextMessageAsync(string message)
{
// 构建Telegram API URL - 固定格式:https://api.telegram.org/bot{token}/sendMessage
var endpoint = $"{TELEGRAM_API_URL}{TelegramBotToken}/sendMessage";
try
{
var jsonContent = new
{
chat_id = TelegramChatId,
text = message,
disable_web_page_preview = true
};
var json = JsonSerializer.Serialize(jsonContent, _jsonSerializerOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, endpoint)
{
Content = content
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.UserAgent.Add(new ProductInfoHeaderValue("BetterGenshinImpact", "1.0"));
var response = await _httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new NotifierException(
$"Telegram message failed with code: {response.StatusCode}, Error: {responseContent}");
}
// Check for API errors in the response
var (isSuccess, errorCode, errorDescription) = ValidateApiResponse(responseContent);
if (!isSuccess)
{
if (errorCode == 400)
{
throw new NotifierException(
"Please send a message to the bot first and check that the chat ID is correct.");
}
if (errorCode == 401)
{
throw new NotifierException("Telegram bot token is incorrect.");
}
if (errorCode == 404)
throw new NotifierException(
$"Telegram API not found (404). Please verify your bot token is correct. URL: {endpoint}");
throw new NotifierException($"Telegram API error: {errorDescription} (Code: {errorCode})");
}
}
catch (System.Exception ex) when (!(ex is NotifierException))
{
throw new NotifierException("Error sending Telegram notification: " + ex.Message);
}
}
private (bool isSuccess, int errorCode, string errorDescription) ValidateApiResponse(string responseJson)
{
try
{
using (var doc = JsonDocument.Parse(responseJson))
{
var root = doc.RootElement;
// Telegram API returns "ok": true for success
if (root.TryGetProperty("ok", out var okElement))
{
var isOk = okElement.GetBoolean();
if (!isOk)
{
var errorDescription = "Unknown Telegram API error";
if (root.TryGetProperty("description", out var descriptionElement))
errorDescription = descriptionElement.GetString();
var errorCode = 0;
if (root.TryGetProperty("error_code", out var errorCodeElement))
errorCode = errorCodeElement.GetInt32();
return (false, errorCode, errorDescription);
}
return (true, 0, string.Empty);
}
return (false, 0, "Invalid API response: 'ok' field missing");
}
}
catch (JsonException ex)
{
return (false, 0, "Failed to parse API response: " + ex.Message);
}
}
}
@@ -0,0 +1,86 @@
using System;
using System.Net.WebSockets;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notifier.Interface;
namespace BetterGenshinImpact.Service.Notifier
{
public class WebSocketNotifier : IDisposable, INotifier
{
private ClientWebSocket _webSocket;
private readonly string _endpoint;
private readonly JsonSerializerOptions _jsonSerializerOptions;
private readonly CancellationTokenSource _cts;
public WebSocketNotifier(string endpoint, JsonSerializerOptions jsonSerializerOptions, CancellationTokenSource cts)
{
_endpoint = endpoint;
_jsonSerializerOptions = jsonSerializerOptions;
_cts = cts;
_webSocket = new ClientWebSocket();
}
public string Name => "WebSocketNotifier";
private async Task EnsureConnectedAsync()
{
if (_webSocket.State == WebSocketState.Open)
return;
_webSocket.Dispose();
_webSocket = new ClientWebSocket();
try
{
Console.WriteLine("Connecting to WebSocket...");
await _webSocket.ConnectAsync(new Uri(_endpoint), _cts.Token);
Console.WriteLine("WebSocket connected.");
}
catch (SystemException ex)
{
Console.WriteLine($"WebSocket connection failed: {ex.Message}");
}
}
public async Task SendAsync(BaseNotificationData notificationData)
{
try
{
await EnsureConnectedAsync();
var json = JsonSerializer.Serialize(notificationData, _jsonSerializerOptions);
var buffer = System.Text.Encoding.UTF8.GetBytes(json);
await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, _cts.Token);
await CloseAsync(); // 添加关闭连接的代码
}
catch (WebSocketException ex)
{
Console.WriteLine($"WebSocket send failed: {ex.Message}");
await EnsureConnectedAsync(); // Attempt to reconnect
}
}
public async Task CloseAsync()
{
if (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.CloseReceived)
{
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", _cts.Token);
}
_webSocket.Dispose();
_webSocket = new ClientWebSocket();
}
public void Dispose()
{
_webSocket.Dispose();
_cts.Cancel();
}
public async Task SendNotificationAsync(BaseNotificationData notificationData)
{
await SendAsync(notificationData);
}
}
}
@@ -1,10 +1,13 @@
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model;
using System.Collections.Generic;
using BetterGenshinImpact.Service.Notification; // 添加对 System.Collections.Generic 命名空间的引用
using BetterGenshinImpact.Service.Notification; // 添加对 NotificationConfig 类型的引用
namespace BetterGenshinImpact.Service.Notifier;
@@ -14,6 +17,9 @@ public class WebhookNotifier : INotifier
public string Endpoint { get; set; }
// 添加 send_to 属性
private string SendTo { get; set; }
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
@@ -21,10 +27,12 @@ public class WebhookNotifier : INotifier
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
};
public WebhookNotifier(HttpClient httpClient, string endpoint = "")
public WebhookNotifier(HttpClient httpClient, NotificationConfig config)
{
_httpClient = httpClient;
Endpoint = endpoint;
Endpoint = config.WebhookEndpoint;
SendTo = config.WebhookSendTo; // 初始化 send_to 属性
}
public async Task SendAsync(BaseNotificationData content)
@@ -53,11 +61,21 @@ public class WebhookNotifier : INotifier
}
}
private StringContent TransformData(BaseNotificationData notificationData)
{
// using object type here so it serializes the interface correctly
var serializedData = JsonSerializer.Serialize<object>(notificationData, _jsonSerializerOptions);
// 使用 SendTo 属性来设置 send_to 字段,并将 notification_data 的内容合并到外层字典
var dataToSend = new Dictionary<string, object>
{
{ "send_to", SendTo },
{ "event", notificationData.Event },
{ "result", notificationData.Result },
{ "timestamp", notificationData.Timestamp },
{ "screenshot", notificationData.Screenshot },
{ "message", notificationData.Message },
{ "data", notificationData.Data }
};
var serializedData = JsonSerializer.Serialize(dataToSend, _jsonSerializerOptions);
return new StringContent(serializedData, Encoding.UTF8, "application/json");
}
+46 -46
View File
@@ -1,46 +1,46 @@
using System;
using System.Windows;
using Wpf.Ui;
namespace BetterGenshinImpact.Service;
/// <summary>
/// Service that provides pages for navigation.
/// </summary>
public class PageService : IPageService
{
/// <summary>
/// Service which provides the instances of pages.
/// </summary>
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Creates new instance and attaches the <see cref="IServiceProvider"/>.
/// </summary>
public PageService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <inheritdoc />
public T? GetPage<T>() where T : class
{
if (!typeof(FrameworkElement).IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException("The page should be a WPF control.");
}
return (T?)_serviceProvider.GetService(typeof(T));
}
/// <inheritdoc />
public FrameworkElement? GetPage(Type pageType)
{
if (!typeof(FrameworkElement).IsAssignableFrom(pageType))
{
throw new InvalidOperationException("The page should be a WPF control.");
}
return _serviceProvider.GetService(pageType) as FrameworkElement;
}
}
// using System;
// using System.Windows;
// using Wpf.Ui;
//
// namespace BetterGenshinImpact.Service;
//
// /// <summary>
// /// Service that provides pages for navigation.
// /// </summary>
// public class PageService : IPageService
// {
// /// <summary>
// /// Service which provides the instances of pages.
// /// </summary>
// private readonly IServiceProvider _serviceProvider;
//
// /// <summary>
// /// Creates new instance and attaches the <see cref="IServiceProvider"/>.
// /// </summary>
// public PageService(IServiceProvider serviceProvider)
// {
// _serviceProvider = serviceProvider;
// }
//
// /// <inheritdoc />
// public T? GetPage<T>() where T : class
// {
// if (!typeof(FrameworkElement).IsAssignableFrom(typeof(T)))
// {
// throw new InvalidOperationException("The page should be a WPF control.");
// }
//
// return (T?)_serviceProvider.GetService(typeof(T));
// }
//
// /// <inheritdoc />
// public FrameworkElement? GetPage(Type pageType)
// {
// if (!typeof(FrameworkElement).IsAssignableFrom(pageType))
// {
// throw new InvalidOperationException("The page should be a WPF control.");
// }
//
// return _serviceProvider.GetService(pageType) as FrameworkElement;
// }
// }
+45 -45
View File
@@ -2,7 +2,7 @@
using BetterGenshinImpact.Core.Script.Group;
using BetterGenshinImpact.Core.Script.Project;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
@@ -23,6 +23,7 @@ namespace BetterGenshinImpact.Service;
public partial class ScriptService : IScriptService
{
private readonly ILogger<ScriptService> _logger = App.GetLogger<ScriptService>();
private static bool IsCurrentHourEqual(string input)
{
// 尝试将输入字符串转换为整数
@@ -41,52 +42,51 @@ public partial class ScriptService : IScriptService
// 如果输入非数字或不合法,返回 false
return false;
}
public async Task RunMulti(IEnumerable<ScriptGroupProject> projectList, string? groupName = null)
{
groupName ??= "默认";
var hasTimer = false;
var list = ReloadScriptProjects(projectList, ref hasTimer);
var list = ReloadScriptProjects(projectList);
// 针对JS 脚本,检查是否包含定时器操作
var jsProjects = ExtractJsProjects(list);
if (!hasTimer && jsProjects.Count > 0)
{
var codeList = await ReadCodeList(jsProjects);
hasTimer = HasTimerOperation(codeList);
}
// // 针对JS 脚本,检查是否包含定时器操作
// var jsProjects = ExtractJsProjects(list);
// if (!hasTimer && jsProjects.Count > 0)
// {
// var codeList = await ReadCodeList(jsProjects);
// hasTimer = HasTimerOperation(codeList);
// }
// 没启动时候,启动截图器
await StartGameTask();
if (!string.IsNullOrEmpty(groupName))
{
if (hasTimer)
{
_logger.LogInformation("配置组 {Name} 包含实时任务操作调用", groupName);
}
// if (hasTimer)
// {
// _logger.LogInformation("配置组 {Name} 包含实时任务操作调用", groupName);
// }
_logger.LogInformation("配置组 {Name} 加载完成,共{Cnt}个脚本,开始执行", groupName, list.Count);
}
var timerOperation = hasTimer ? DispatcherTimerOperationEnum.UseCacheImageWithTriggerEmpty : DispatcherTimerOperationEnum.UseSelfCaptureImage;
// var timerOperation = hasTimer ? DispatcherTimerOperationEnum.UseCacheImageWithTriggerEmpty : DispatcherTimerOperationEnum.UseSelfCaptureImage;
Notify.Event(NotificationEvent.GroupStart).Success($"配置组{groupName}启动");
await new TaskRunner(timerOperation)
await new TaskRunner()
.RunThreadAsync(async () =>
{
var stopwatch = new Stopwatch();
foreach (var project in list)
{
if (project.GroupInfo is { Config.PathingConfig.Enabled: true } && IsCurrentHourEqual(project.GroupInfo.Config.PathingConfig.SkipDuring))
{
_logger.LogInformation($"{project.Name}任务已到禁止执行时段,将跳过!");
continue;
}
if (project.Status != "Enabled")
{
_logger.LogInformation("脚本 {Name} 状态为禁用,跳过执行", project.Name);
@@ -103,24 +103,21 @@ public partial class ScriptService : IScriptService
{
try
{
if (hasTimer)
{
TaskTriggerDispatcher.Instance().ClearTriggers();
}
TaskTriggerDispatcher.Instance().ClearTriggers();
_logger.LogInformation("------------------------------");
stopwatch.Reset();
stopwatch.Start();
await ExecuteProject(project);
//多次执行时及时中断
if (project.GroupInfo is { Config.PathingConfig.Enabled: true } && IsCurrentHourEqual(project.GroupInfo.Config.PathingConfig.SkipDuring))
{
_logger.LogInformation($"{project.Name}任务已到禁止执行时段,将跳过!");
break;
}
}
catch (NormalEndException e)
{
@@ -144,7 +141,6 @@ public partial class ScriptService : IScriptService
_logger.LogInformation("→ 脚本执行结束: {Name}, 耗时: {Minutes}分{Seconds:0.000}秒", project.Name,
elapsedTime.Hours * 60 + elapsedTime.Minutes, elapsedTime.TotalSeconds % 60);
_logger.LogInformation("------------------------------");
}
await Task.Delay(2000);
@@ -152,14 +148,18 @@ public partial class ScriptService : IScriptService
}
});
// 还原定时器
TaskTriggerDispatcher.Instance().SetTriggers(GameTaskManager.LoadInitialTriggers());
if (!string.IsNullOrEmpty(groupName))
{
_logger.LogInformation("配置组 {Name} 执行结束", groupName);
}
Notify.Event(NotificationEvent.GroupEnd).Success($"配置组{groupName}结束");
}
private List<ScriptGroupProject> ReloadScriptProjects(IEnumerable<ScriptGroupProject> projectList, ref bool hasTimer)
private List<ScriptGroupProject> ReloadScriptProjects(IEnumerable<ScriptGroupProject> projectList)
{
var list = new List<ScriptGroupProject>();
foreach (var project in projectList)
@@ -181,14 +181,14 @@ public partial class ScriptService : IScriptService
var newProject = ScriptGroupProject.BuildPathingProject(project.Name, project.FolderName);
CopyProjectProperties(project, newProject);
list.Add(newProject);
hasTimer = true;
// hasTimer = true;
}
else if (project.Type == "Shell")
{
var newProject = ScriptGroupProject.BuildShellProject(project.Name);
CopyProjectProperties(project, newProject);
list.Add(newProject);
hasTimer = true;
// hasTimer = true;
}
}
@@ -204,23 +204,22 @@ public partial class ScriptService : IScriptService
target.GroupInfo = source.GroupInfo;
}
private List<ScriptProject> ExtractJsProjects(List<ScriptGroupProject> list)
{
var jsProjects = new List<ScriptProject>();
foreach (var project in list)
{
if (project is { Type: "Javascript", Project: not null })
{
jsProjects.Add(project.Project);
}
}
return jsProjects;
}
// private List<ScriptProject> ExtractJsProjects(List<ScriptGroupProject> list)
// {
// var jsProjects = new List<ScriptProject>();
// foreach (var project in list)
// {
// if (project is { Type: "Javascript", Project: not null })
// {
// jsProjects.Add(project.Project);
// }
// }
//
// return jsProjects;
// }
private async Task ExecuteProject(ScriptGroupProject project)
{
if (project.Type == "Javascript")
{
if (project.Project == null)
@@ -241,7 +240,8 @@ public partial class ScriptService : IScriptService
_logger.LogInformation("→ 开始执行地图追踪任务: {Name}", project.Name);
await project.Run();
}
else if (project.Type == "Shell"){
else if (project.Type == "Shell")
{
_logger.LogInformation("→ 开始执行shell: {Name}", project.Name);
await project.Run();
}
@@ -7,6 +7,7 @@ using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using BetterGenshinImpact.Helpers;
using OpenCvSharp.WpfExtensions;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.View;
@@ -49,7 +50,6 @@ public partial class CaptureTestWindow : Window
_capture.Start(hWnd,
new Dictionary<string, object>()
{
{ "useBitmapCache", TaskContext.Instance().Config.WgcUseBitmapCache },
{ "autoFixWin11BitBlt", OsVersionHelper.IsWindows11 && TaskContext.Instance().Config.AutoFixWin11BitBlt }
}
);
@@ -72,7 +72,7 @@ public partial class CaptureTestWindow : Window
_captureCount++;
sw.Reset();
sw.Start();
DisplayCaptureResultImage.Source = bitmap.ToBitmapImage();
DisplayCaptureResultImage.Source = bitmap.ToBitmapSource();
sw.Stop();
Debug.WriteLine("转换耗时:" + sw.ElapsedMilliseconds);
_transferTime += sw.ElapsedMilliseconds;
+2 -2
View File
@@ -177,7 +177,7 @@
<ui:TitleBar.Icon>
<ui:ImageIcon Source="pack://application:,,,/Assets/Images/logo.png" />
</ui:TitleBar.Icon>
<ui:TitleBar.Header>
<ui:TitleBar.TrailingContent>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<ui:Button Width="46"
Height="32"
@@ -197,7 +197,7 @@
Icon="{ui:SymbolIcon CaretDown24}"
ToolTip="最小化到托盘" />
</StackPanel>
</ui:TitleBar.Header>
</ui:TitleBar.TrailingContent>
</ui:TitleBar>
<tray:NotifyIcon Grid.Row="0"
+5 -7
View File
@@ -7,18 +7,19 @@ using System.Windows.Media;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers.Ui;
using Wpf.Ui;
using Wpf.Ui.Abstractions;
using Wpf.Ui.Controls;
using Wpf.Ui.Tray.Controls;
namespace BetterGenshinImpact.View;
public partial class MainWindow : FluentWindow, INavigationWindow
public partial class MainWindow : INavigationWindow
{
private readonly ILogger<MainWindow> _logger = App.GetLogger<MainWindow>();
public MainWindowViewModel ViewModel { get; }
public MainWindow(MainWindowViewModel viewModel, IPageService pageService, INavigationService navigationService, ISnackbarService snackbarService)
public MainWindow(MainWindowViewModel viewModel, INavigationService navigationService, ISnackbarService snackbarService)
{
_logger.LogDebug("主窗体实例化");
DataContext = ViewModel = viewModel;
@@ -26,7 +27,6 @@ public partial class MainWindow : FluentWindow, INavigationWindow
InitializeComponent();
this.InitializeDpiAwareness();
SetPageService(pageService);
snackbarService.SetSnackbarPresenter(SnackbarPresenter);
navigationService.SetNavigationControl(RootNavigation);
@@ -62,10 +62,8 @@ public partial class MainWindow : FluentWindow, INavigationWindow
throw new NotImplementedException();
}
public void SetPageService(IPageService pageService)
{
RootNavigation.SetPageService(pageService);
}
public void SetPageService(INavigationViewPageProvider navigationViewPageProvider) =>
RootNavigation.SetPageProviderService(navigationViewPageProvider);
public void ShowWindow() => Show();
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -176,7 +176,7 @@
Margin="0,0,36,0"
Text="{Binding Config.TriggerInterval, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<!--<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -201,7 +201,7 @@
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.WgcUseBitmapCache, Mode=TwoWay}" />
</Grid>
</Grid>-->
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
@@ -1564,7 +1564,7 @@
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="钓全天的鱼、还是只钓白天或夜晚的鱼"
Text="钓全天的鱼、还是只钓白天或夜晚的鱼、亦或不调整时间"
TextWrapping="Wrap" />
<ComboBox Grid.Row="0"
Grid.RowSpan="2"
@@ -1,7 +1,6 @@
using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.View.Pages;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -27,20 +26,13 @@ using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class CommonSettingsPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class CommonSettingsPageViewModel : ViewModel
{
public AllConfig Config { get; set; }
private readonly INavigationService _navigationService;
private readonly NotificationService _notificationService;
[ObservableProperty]
private bool _isLoading;
[ObservableProperty]
private string _webhookStatus = string.Empty;
public ObservableCollection<string> CountryList { get; } = new();
public ObservableCollection<string> Areas { get; } = new();
private readonly TpConfig _tpConfig = TaskContext.Instance().Config.TpConfig;
@@ -136,14 +128,6 @@ public partial class CommonSettingsPageViewModel : ObservableObject, INavigation
InitializeCountries();
}
public void OnNavigatedTo()
{
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnRefreshMaskSettings()
{
@@ -172,13 +156,6 @@ public partial class CommonSettingsPageViewModel : ObservableObject, INavigation
[RelayCommand]
public void OnSwitchTakenScreenshotEnabled()
{
if (Config.CommonConfig.ScreenshotEnabled)
{
if (TaskTriggerDispatcher.Instance().GetCacheCaptureMode() == DispatcherCaptureModeEnum.NormalTrigger)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
}
}
}
[RelayCommand]
@@ -208,14 +185,15 @@ public partial class CommonSettingsPageViewModel : ObservableObject, INavigation
[RelayCommand]
private async Task OnTestWebhook()
{
IsLoading = true;
WebhookStatus = string.Empty;
var res = await _notificationService.TestNotifierAsync<WebhookNotifier>();
WebhookStatus = res.Message;
IsLoading = false;
if(res.IsSuccess)
{
Toast.Success(res.Message);
}
else
{
Toast.Error(res.Message);
}
}
[RelayCommand]
@@ -260,6 +238,63 @@ public partial class CommonSettingsPageViewModel : ObservableObject, INavigation
}
}
[RelayCommand]
private async Task OnTestWebSocketNotification()
{
var res = await _notificationService.TestNotifierAsync<WebSocketNotifier>();
if(res.IsSuccess)
{
Toast.Success(res.Message);
}
else
{
Toast.Error(res.Message);
}
}
[RelayCommand]
private async Task OnTestEmailNotification()
{
var res = await _notificationService.TestNotifierAsync<EmailNotifier>();
if(res.IsSuccess)
{
Toast.Success(res.Message);
}
else
{
Toast.Error(res.Message);
}
}
[RelayCommand]
private async Task OnTestBarkNotification()
{
var res = await _notificationService.TestNotifierAsync<BarkNotifier>();
if(res.IsSuccess)
{
Toast.Success(res.Message);
}
else
{
Toast.Error(res.Message);
}
}
[RelayCommand]
private async Task OnTestTelegramNotification()
{
var res = await _notificationService.TestNotifierAsync<TelegramNotifier>();
if(res.IsSuccess)
{
Toast.Success(res.Message);
}
else
{
Toast.Error(res.Message);
}
}
[RelayCommand]
private void ImportLocalScriptsRepoZip()
{
@@ -27,7 +27,7 @@ using Wpf.Ui.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class HomePageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class HomePageViewModel : ViewModel
{
[ObservableProperty]
private string[] _modeNames = GameCaptureFactory.ModeNames();
@@ -293,14 +293,6 @@ public partial class HomePageViewModel : ObservableObject, INavigationAware, IVi
UIDispatcherHelper.Invoke(() => Start(_hWnd));
}
public void OnNavigatedTo()
{
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnGoToWikiUrl()
{
@@ -21,7 +21,7 @@ using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class JsListViewModel : ObservableObject, INavigationAware, IViewModel
public partial class JsListViewModel : ViewModel
{
private readonly ILogger<JsListViewModel> _logger = App.GetLogger<JsListViewModel>();
private readonly string scriptPath = Global.ScriptPath();
@@ -71,15 +71,11 @@ public partial class JsListViewModel : ObservableObject, INavigationAware, IView
return di.GetDirectories();
}
public void OnNavigatedTo()
public override void OnNavigatedTo()
{
InitScriptListViewData();
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnOpenScriptsFolder()
{
@@ -18,7 +18,7 @@ using static Vanara.PInvoke.User32;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class KeyBindingsSettingsPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class KeyBindingsSettingsPageViewModel : ViewModel
{
private readonly ILogger<KeyBindingsSettingsPageViewModel> _logger;
@@ -30,14 +30,6 @@ public partial class KeyBindingsSettingsPageViewModel : ObservableObject, INavig
[ObservableProperty]
private ObservableCollection<KeyBindingSettingModel> _keyBindingSettingModels = [];
public void OnNavigatedFrom()
{
}
public void OnNavigatedTo()
{
}
public KeyBindingsSettingsPageViewModel(IConfigService configService, ILogger<KeyBindingsSettingsPageViewModel> logger)
{
_logger = logger;
@@ -2,7 +2,6 @@
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.View.Windows;
@@ -22,7 +21,7 @@ using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class KeyMouseRecordPageViewModel : ViewModel
{
private readonly ILogger<KeyMouseRecordPageViewModel> _logger = App.GetLogger<KeyMouseRecordPageViewModel>();
private readonly string scriptPath = Global.Absolute(@"User\KeyMouseScript");
@@ -74,15 +73,11 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
return files.Select(file => new FileInfo(file)).ToList();
}
public void OnNavigatedTo()
public override void OnNavigatedTo()
{
InitScriptListViewData();
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public async Task OnStartRecord()
{
@@ -129,7 +124,7 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
{
var s = await File.ReadAllTextAsync(path);
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunThreadAsync(async () => await KeyMouseMacroPlayer.PlayMacro(s, CancellationContext.Instance.Cts.Token));
}
catch (Exception e)
@@ -11,7 +11,7 @@ using Wpf.Ui.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class MacroSettingsPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class MacroSettingsPageViewModel : ViewModel
{
public AllConfig Config { get; set; }
@@ -25,15 +25,7 @@ public partial class MacroSettingsPageViewModel : ObservableObject, INavigationA
Config = configService.Get();
_navigationService = navigationService;
}
public void OnNavigatedTo()
{
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnGoToHotKeyPage()
{
@@ -17,17 +17,14 @@ using System.Threading.Tasks;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
using Wpf.Ui.Controls;
using Wpf.Ui.Violeta.Controls;
using System.Windows;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.View.Pages.View;
using BetterGenshinImpact.ViewModel.Pages.View;
using Wpf.Ui.Violeta.Win32;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class MapPathingViewModel : ObservableObject, INavigationAware, IViewModel
public partial class MapPathingViewModel : ViewModel
{
private readonly ILogger<MapPathingViewModel> _logger = App.GetLogger<MapPathingViewModel>();
public static readonly string PathJsonPath = Global.Absolute(@"User\AutoPathing");
@@ -74,15 +71,11 @@ public partial class MapPathingViewModel : ObservableObject, INavigationAware, I
}
}
public void OnNavigatedTo()
public override void OnNavigatedTo()
{
InitScriptListViewData();
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnOpenScriptsFolder()
{
@@ -15,7 +15,7 @@ using BetterGenshinImpact.Core.Script.Group;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.Notification;
@@ -28,7 +28,7 @@ using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class OneDragonFlowViewModel : ObservableObject, INavigationAware, IViewModel
public partial class OneDragonFlowViewModel : ViewModel
{
private readonly ILogger<OneDragonFlowViewModel> _logger = App.GetLogger<OneDragonFlowViewModel>();
@@ -97,7 +97,7 @@ public partial class OneDragonFlowViewModel : ObservableObject, INavigationAware
InitConfigList();
}
public void OnNavigatedTo()
public override void OnNavigatedTo()
{
InitConfigList();
}
@@ -213,7 +213,7 @@ public partial class OneDragonFlowViewModel : ObservableObject, INavigationAware
// 没启动的时候先启动
await ScriptService.StartGameTask();
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunThreadAsync(async () =>
{
Notify.Event(NotificationEvent.DragonStart).Success("一条龙启动");
@@ -41,7 +41,7 @@ using TextBlock = Wpf.Ui.Controls.TextBlock;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class ScriptControlViewModel : ObservableObject, INavigationAware, IViewModel
public partial class ScriptControlViewModel : ViewModel
{
private readonly ISnackbarService _snackbarService;
@@ -63,12 +63,9 @@ public partial class ScriptControlViewModel : ObservableObject, INavigationAware
public readonly string ScriptGroupPath = Global.Absolute(@"User\ScriptGroup");
public readonly string LogPath = Global.Absolute(@"log");
public void OnNavigatedFrom()
{
}
public void OnNavigatedTo()
public override void OnNavigatedTo()
{
ReadScriptGroup();
}
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
using Windows.System;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using Wpf.Ui;
using Wpf.Ui.Controls;
@@ -35,7 +35,7 @@ using Vanara.Extensions;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class TaskSettingsPageViewModel : ViewModel
{
public AllConfig Config { get; set; }
@@ -168,14 +168,6 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
_autoFightViewModel.OnStrategyDropDownOpened(type);
}
public void OnNavigatedTo()
{
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
public void OnGoToHotKeyPage()
{
@@ -191,7 +183,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
}
SwitchAutoGeniusInvokationEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoGeniusInvokationTask(new GeniusInvokationTaskParam(content)));
SwitchAutoGeniusInvokationEnabled = false;
}
@@ -227,7 +219,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
public async Task OnSwitchAutoWood()
{
SwitchAutoWoodEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoWoodTask(new WoodTaskParam(AutoWoodRoundNum, AutoWoodDailyMaxCount)));
SwitchAutoWoodEnabled = false;
}
@@ -249,7 +241,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
var param = new AutoFightParam(path, Config.AutoFightConfig);
SwitchAutoFightEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseCacheImageWithTrigger)
await new TaskRunner()
.RunSoloTaskAsync(new AutoFightTask(param));
SwitchAutoFightEnabled = false;
}
@@ -269,7 +261,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
}
SwitchAutoDomainEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseCacheImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoDomainTask(new AutoDomainParam(AutoDomainRoundNum, path)));
SwitchAutoDomainEnabled = false;
}
@@ -384,7 +376,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
private async Task OnSwitchAutoMusicGame()
{
SwitchAutoMusicGameEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoMusicGameTask(new AutoMusicGameParam()));
SwitchAutoMusicGameEnabled = false;
}
@@ -399,7 +391,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
private async Task OnSwitchAutoAlbum()
{
SwitchAutoAlbumEnabled = true;
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoAlbumTask(new AutoMusicGameParam()));
SwitchAutoAlbumEnabled = false;
}
@@ -409,7 +401,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
{
SwitchAutoFishingEnabled = true;
var param = AutoFishingTaskParam.BuildFromConfig(TaskContext.Instance().Config.AutoFishingConfig, SaveScreenshotOnKeyTick);
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
await new TaskRunner()
.RunSoloTaskAsync(new AutoFishingTask(param));
SwitchAutoFishingEnabled = false;
}
@@ -14,7 +14,7 @@ using Wpf.Ui.Controls;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class TriggerSettingsPageViewModel : ObservableObject, INavigationAware, IViewModel
public partial class TriggerSettingsPageViewModel : ViewModel
{
[ObservableProperty]
private string[] _clickChatOptionNames = ["优先选择第一个选项", "随机选择选项", "优先选择最后一个选项", "不选择选项"];
@@ -51,14 +51,6 @@ public partial class TriggerSettingsPageViewModel : ObservableObject, INavigatio
}
}
public void OnNavigatedTo()
{
}
public void OnNavigatedFrom()
{
}
[RelayCommand]
private void OnEditBlacklist()
{
@@ -0,0 +1,36 @@
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Wpf.Ui.Abstractions.Controls;
namespace BetterGenshinImpact.ViewModel;
public abstract partial class ViewModel : ObservableObject, INavigationAware, IViewModel
{
/// <inheritdoc />
public virtual Task OnNavigatedToAsync()
{
OnNavigatedTo();
return Task.CompletedTask;
}
/// <summary>
/// Handles the event that is fired after the component is navigated to.
/// </summary>
// ReSharper disable once MemberCanBeProtected.Global
public virtual void OnNavigatedTo() { }
/// <inheritdoc />
public virtual Task OnNavigatedFromAsync()
{
OnNavigatedFrom();
return Task.CompletedTask;
}
/// <summary>
/// Handles the event that is fired before the component is navigated from.
/// </summary>
// ReSharper disable once MemberCanBeProtected.Global
public virtual void OnNavigatedFrom() { }
}
+70 -22
View File
@@ -1,4 +1,6 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using OpenCvSharp;
using Vanara.PInvoke;
namespace Fischless.GameCapture.BitBlt;
@@ -7,6 +9,9 @@ public class BitBltCapture : IGameCapture
{
private nint _hWnd;
private static readonly object LockObject = new object();
public CaptureModes Mode => CaptureModes.BitBlt;
public bool IsCapturing { get; private set; }
@@ -26,36 +31,79 @@ public class BitBltCapture : IGameCapture
}
}
public Bitmap? Capture()
public Mat? Capture()
{
if (_hWnd == IntPtr.Zero)
{
return null;
}
try
// 加锁
lock (LockObject)
{
User32.GetClientRect(_hWnd, out var windowRect);
int x = default, y = default;
var width = windowRect.right - windowRect.left;
var height = windowRect.bottom - windowRect.top;
User32.SafeReleaseHDC hdcSrc = User32.SafeReleaseHDC.Null;
Gdi32.SafeHDC hdcDest = Gdi32.SafeHDC.Null;
Gdi32.SafeHBITMAP hBitmap = Gdi32.SafeHBITMAP.Null;
try
{
User32.GetClientRect(_hWnd, out var windowRect);
int x = 0, y = 0;
var width = windowRect.right - windowRect.left;
var height = windowRect.bottom - windowRect.top;
Bitmap bitmap = new(width, height);
using System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
var hdcDest = g.GetHdc();
var hdcSrc = User32.GetDC(_hWnd == IntPtr.Zero ? User32.GetDesktopWindow() : _hWnd);
Gdi32.StretchBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, width, height, Gdi32.RasterOperationMode.SRCCOPY);
g.ReleaseHdc();
Gdi32.DeleteDC(hdcDest);
Gdi32.DeleteDC(hdcSrc);
return bitmap;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
hdcSrc = User32.GetDC(_hWnd == IntPtr.Zero ? User32.GetDesktopWindow() : _hWnd);
hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
return null!;
var bmi = new Gdi32.BITMAPINFO
{
bmiHeader = new Gdi32.BITMAPINFOHEADER
{
biSize = (uint)Marshal.SizeOf<Gdi32.BITMAPINFOHEADER>(),
biWidth = width,
biHeight = -height, // Top-down image
biPlanes = 1,
biBitCount = 32,
biCompression = 0, // BI_RGB
biSizeImage = 0
}
};
nint bits = 0;
hBitmap = Gdi32.CreateDIBSection(hdcDest, bmi, Gdi32.DIBColorMode.DIB_RGB_COLORS, out bits, IntPtr.Zero, 0);
var oldBitmap = Gdi32.SelectObject(hdcDest, hBitmap);
Gdi32.StretchBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, width, height, Gdi32.RasterOperationMode.SRCCOPY);
var mat = new Mat(height, width, MatType.CV_8UC4, bits);
Mat bgrMat = new Mat();
Cv2.CvtColor(mat, bgrMat, ColorConversionCodes.BGRA2BGR);
Gdi32.SelectObject(hdcDest, oldBitmap);
return bgrMat;
}
catch (Exception e)
{
Debug.WriteLine(e);
return null!;
}
finally
{
if (hBitmap != Gdi32.SafeHBITMAP.Null)
{
Gdi32.DeleteObject(hBitmap);
}
if (hdcDest != Gdi32.SafeHDC.Null)
{
Gdi32.DeleteDC(hdcDest);
}
if (_hWnd != IntPtr.Zero)
{
User32.ReleaseDC(_hWnd, hdcSrc);
}
}
}
}
public void Stop()
@@ -63,4 +111,4 @@ public class BitBltCapture : IGameCapture
_hWnd = IntPtr.Zero;
IsCapturing = false;
}
}
}
@@ -3,6 +3,8 @@ using Fischless.GameCapture.Graphics.Helpers;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using System.Diagnostics;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using Vanara.PInvoke;
using Device = SharpDX.Direct3D11.Device;
@@ -11,6 +13,7 @@ namespace Fischless.GameCapture.DwmSharedSurface
public class SharedSurfaceCapture : IGameCapture
{
private nint _hWnd;
private static readonly object LockObject = new object();
private Device? _d3dDevice;
public void Dispose() => Stop();
@@ -64,34 +67,45 @@ namespace Fischless.GameCapture.DwmSharedSurface
return region;
}
public Bitmap? Capture()
public Mat? Capture()
{
if (_hWnd == nint.Zero)
{
return null;
}
NativeMethods.DwmGetDxSharedSurface(_hWnd, out var phSurface, out _, out _, out _, out _);
if (phSurface == nint.Zero)
lock (LockObject)
{
return null;
}
NativeMethods.DwmGetDxSharedSurface(_hWnd, out var phSurface, out _, out _, out _, out _);
if (phSurface == nint.Zero)
{
return null;
}
return ToBitmap(phSurface);
if (_d3dDevice == null)
{
Debug.WriteLine("D3Device is null.");
return null;
}
using var surfaceTexture = _d3dDevice.OpenSharedResource<Texture2D>(phSurface);
using var stagingTexture = CreateStagingTexture(surfaceTexture, _d3dDevice);
var mat = stagingTexture.CreateMat(_d3dDevice, surfaceTexture, _region);
if (mat == null)
{
return null;
}
var bgrMat = new Mat();
Cv2.CvtColor(mat, bgrMat, ColorConversionCodes.BGRA2BGR);
return bgrMat;
}
}
private Bitmap? ToBitmap(nint phSurface)
private Texture2D CreateStagingTexture(Texture2D surfaceTexture, Device device)
{
if (_d3dDevice == null)
{
Debug.WriteLine("D3Device is null.");
return null;
}
using var surfaceTexture = _d3dDevice.OpenSharedResource<Texture2D>(phSurface);
var staging = new Texture2D(_d3dDevice, new Texture2DDescription
return new Texture2D(device, new Texture2DDescription
{
Width = _region == null ? surfaceTexture.Description.Width : _region.Value.Right - _region.Value.Left,
Height = _region == null ? surfaceTexture.Description.Height : _region.Value.Bottom - _region.Value.Top,
@@ -104,9 +118,6 @@ namespace Fischless.GameCapture.DwmSharedSurface
CpuAccessFlags = CpuAccessFlags.Read,
OptionFlags = ResourceOptionFlags.None
});
return staging.CreateBitmap(_d3dDevice, surfaceTexture, _region);
}
public void Stop()
@@ -19,6 +19,8 @@
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
<PackageReference Include="Vanara.Windows.Extensions" Version="4.0.2" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
</ItemGroup>
</Project>
+187 -37
View File
@@ -5,6 +5,11 @@ using Vanara.PInvoke;
using Windows.Foundation.Metadata;
using Windows.Graphics.Capture;
using Windows.Graphics.DirectX;
using Windows.Graphics.DirectX.Direct3D11;
using OpenCvSharp;
using SharpDX.DXGI;
using Device = SharpDX.Direct3D11.Device;
using MapFlags = SharpDX.Direct3D11.MapFlags;
namespace Fischless.GameCapture.Graphics;
@@ -14,15 +19,27 @@ public class GraphicsCapture : IGameCapture
private Direct3D11CaptureFramePool _captureFramePool = null!;
private GraphicsCaptureItem _captureItem = null!;
private GraphicsCaptureSession _captureSession = null!;
private IDirect3DDevice _d3dDevice = null!;
public CaptureModes Mode => CaptureModes.WindowsGraphicsCapture;
public bool IsCapturing { get; private set; }
private ResourceRegion? _region;
private bool _useBitmapCache = false;
private Bitmap? _currentBitmap;
// HDR相关
private bool _isHdrEnabled;
private DirectXPixelFormat _pixelFormat = DirectXPixelFormat.B8G8R8A8UIntNormalized;
// 最新帧的存储
private Mat? _latestFrame;
private readonly ReaderWriterLockSlim _frameAccessLock = new();
// 用于获取帧数据的临时纹理和暂存资源
private Texture2D? _stagingTexture;
public void Dispose() => Stop();
@@ -41,24 +58,31 @@ public class GraphicsCapture : IGameCapture
throw new InvalidOperationException("Failed to create capture item.");
}
_captureItem.Closed += CaptureItemOnClosed;
var device = Direct3D11Helper.CreateDevice();
// 创建D3D设备
_d3dDevice = Direct3D11Helper.CreateDevice();
_captureFramePool = Direct3D11CaptureFramePool.Create(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2,
// 检测HDR状态
_isHdrEnabled = IsHdrEnabled(_hWnd);
_pixelFormat = _isHdrEnabled ? DirectXPixelFormat.R16G16B16A16Float : DirectXPixelFormat.B8G8R8A8UIntNormalized;
// 创建帧池
_captureFramePool = Direct3D11CaptureFramePool.Create(
_d3dDevice,
_pixelFormat,
2,
_captureItem.Size);
if (settings != null && settings.TryGetValue("useBitmapCache", out object? value) && (bool)value)
{
_useBitmapCache = true;
_captureFramePool.FrameArrived += OnFrameArrived;
}
_captureItem.Closed += CaptureItemOnClosed;
_captureFramePool.FrameArrived += OnFrameArrived;
_captureSession = _captureFramePool.CreateCaptureSession(_captureItem);
if (ApiInformation.IsPropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession", "IsCursorCaptureEnabled"))
{
_captureSession.IsCursorCaptureEnabled = false;
}
if (ApiInformation.IsWriteablePropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession", "IsBorderRequired"))
{
_captureSession.IsBorderRequired = false;
@@ -98,55 +122,165 @@ public class GraphicsCapture : IGameCapture
return region;
}
private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
public static bool IsHdrEnabled(nint hWnd)
{
using var frame = _captureFramePool?.TryGetNextFrame();
if (frame != null)
try
{
var b = frame.ToBitmap(_region);
if (b != null)
var hdc = User32.GetDC(hWnd);
if (hdc != IntPtr.Zero)
{
_currentBitmap = b;
int bitsPerPixel = Gdi32.GetDeviceCaps(hdc, Gdi32.DeviceCap.BITSPIXEL);
User32.ReleaseDC(hWnd, hdc);
// 如果位深大于等于32位,认为支持HDR
return bitsPerPixel >= 32;
}
return false;
}
catch
{
return false;
}
}
public Bitmap? Capture()
private Texture2D CreateStagingTexture(Direct3D11CaptureFrame frame, Device device)
{
if (_hWnd == IntPtr.Zero)
// 创建可以用于CPU读取的暂存纹理
var textureDesc = new Texture2DDescription
{
return null;
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = _isHdrEnabled ? Format.R16G16B16A16_Float : Format.B8G8R8A8_UNorm,
Width = _region == null ? frame.ContentSize.Width : _region.Value.Right - _region.Value.Left,
Height = _region == null ? frame.ContentSize.Height : _region.Value.Bottom - _region.Value.Top,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
return new Texture2D(device, textureDesc);
}
private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
{
using var frame = sender.TryGetNextFrame();
if (frame == null)
{
return;
}
if (!_useBitmapCache)
var frameSize = _captureItem.Size;
// 检查帧大小是否变化 // 不会被访问到的代码
if (frameSize.Width != frame.ContentSize.Width ||
frameSize.Height != frame.ContentSize.Height)
{
try
{
using var frame = _captureFramePool?.TryGetNextFrame();
frameSize = frame.ContentSize;
_captureFramePool.Recreate(
_d3dDevice,
_pixelFormat,
2,
frameSize
);
_stagingTexture = null;
}
if (frame == null)
{
return null;
}
// 从捕获的帧创建一个可以被访问的纹理
using var surfaceTexture = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface);
var d3dDevice = surfaceTexture.Device;
return frame.ToBitmap(_region);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
_stagingTexture ??= CreateStagingTexture(frame, d3dDevice);
var stagingTexture = _stagingTexture;
return null;
// 将捕获的纹理复制到暂存纹理
if (_region != null)
{
d3dDevice.ImmediateContext.CopySubresourceRegion(surfaceTexture, 0, _region, stagingTexture, 0);
}
else
{
if (_currentBitmap == null)
d3dDevice.ImmediateContext.CopyResource(surfaceTexture, stagingTexture);
}
// 映射纹理以便CPU读取
var dataBox = d3dDevice.ImmediateContext.MapSubresource(
stagingTexture,
0,
MapMode.Read,
MapFlags.None);
try
{
// 创建一个新的Mat
var newFrame = new Mat(stagingTexture.Description.Height, stagingTexture.Description.Width,
_isHdrEnabled ? MatType.MakeType(7, 4) : MatType.CV_8UC4, dataBox.DataPointer);
// 如果是HDR,进行HDR到SDR的转换
if (_isHdrEnabled)
{
// rgb -> bgr
newFrame = ConvertHdrToSdr(newFrame);
}
// 使用写锁更新最新帧
_frameAccessLock.EnterWriteLock();
try
{
// 释放之前的帧
_latestFrame?.Dispose();
// 克隆新帧以保持对其的引用(因为dataBox.DataPointer将被释放)
_latestFrame = newFrame.Clone();
}
finally
{
newFrame.Dispose();
_frameAccessLock.ExitWriteLock();
}
}
finally
{
// 取消映射纹理
d3dDevice.ImmediateContext.UnmapSubresource(surfaceTexture, 0);
}
}
private static Mat ConvertHdrToSdr(Mat hdrMat)
{
// 创建一个目标 8UC4 Mat
Mat sdkMat = new Mat(hdrMat.Size(), MatType.CV_8UC4);
// 将 32FC4 缩放到 0-255 范围并转换为 8UC4
// 注意:这种简单缩放可能不会保留 HDR 的所有细节
hdrMat.ConvertTo(sdkMat, MatType.CV_8UC4, 255.0);
// 将 HDR 的 RGB 通道转换为 BGR
Cv2.CvtColor(sdkMat, sdkMat, ColorConversionCodes.RGBA2BGRA);
return sdkMat;
}
public Mat? Capture()
{
// 使用读锁获取最新帧
_frameAccessLock.EnterReadLock();
try
{
// 如果没有可用帧则返回null
if (_latestFrame == null)
{
return null;
}
return (Bitmap)_currentBitmap.Clone();
// 返回最新帧的副本(这里我们必须克隆,因为Mat是不线程安全的)
return _latestFrame.Clone();
}
finally
{
_frameAccessLock.ExitReadLock();
}
}
@@ -157,9 +291,25 @@ public class GraphicsCapture : IGameCapture
_captureSession = null!;
_captureFramePool = null!;
_captureItem = null!;
_stagingTexture?.Dispose();
_d3dDevice?.Dispose();
_hWnd = IntPtr.Zero;
IsCapturing = false;
// 释放最新帧
_frameAccessLock.EnterWriteLock();
try
{
_latestFrame?.Dispose();
_latestFrame = null;
}
finally
{
_frameAccessLock.ExitWriteLock();
}
_frameAccessLock.Dispose();
}
private void CaptureItemOnClosed(GraphicsCaptureItem sender, object args)
@@ -4,6 +4,7 @@ using SharpDX.DXGI;
using System.Diagnostics;
using System.Drawing.Imaging;
using Windows.Graphics.Capture;
using OpenCvSharp;
namespace Fischless.GameCapture.Graphics.Helpers;
@@ -67,4 +68,40 @@ public static class Texture2DExtensions
staging.Dispose();
}
}
public static Mat? CreateMat(this Texture2D staging, SharpDX.Direct3D11.Device d3dDevice, Texture2D surfaceTexture, ResourceRegion? region = null)
{
try
{
// Copy data
if (region != null)
{
d3dDevice.ImmediateContext.CopySubresourceRegion(surfaceTexture, 0, region, staging, 0);
}
else
{
d3dDevice.ImmediateContext.CopyResource(surfaceTexture, staging);
}
// 映射纹理以便CPU读取
var dataBox = d3dDevice.ImmediateContext.MapSubresource(
staging,
0,
MapMode.Read,
SharpDX.Direct3D11.MapFlags.None);
var mat = new Mat(staging.Description.Height, staging.Description.Width, MatType.CV_8UC4, dataBox.DataPointer);
return mat;
}
catch (Exception e)
{
Debug.WriteLine("Failed to copy texture to mat.");
Debug.WriteLine(e.StackTrace);
return null;
}
finally
{
staging.Dispose();
}
}
}
+4 -2
View File
@@ -1,4 +1,6 @@
namespace Fischless.GameCapture;
using OpenCvSharp;
namespace Fischless.GameCapture;
public interface IGameCapture : IDisposable
{
@@ -7,7 +9,7 @@ public interface IGameCapture : IDisposable
public void Start(nint hWnd, Dictionary<string, object>? settings = null);
public Bitmap? Capture();
public Mat? Capture();
public void Stop();
}
+12
View File
@@ -17,6 +17,18 @@
<br/>
<div align="center">
🌟 点一下右上角的 Star,Github 主页就能收到软件更新通知了哦~
</div>
<div align="center">
<img src="https://img.alicdn.com/imgextra/i1/2042484851/O1CN01OL1E1v1lhoM7Wdmup_!!2042484851.gif" alt="Star" width="186" height="60">
</a>
</div>
<br/>
BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原神变的更好的项目。
## 功能
@@ -127,7 +127,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Single(blackboard.chooseBaitfailures.Where(f => f == "fake fly bait"));
Assert.Single(blackboard.chooseBaitFailures.Where(f => f == "fake fly bait"));
#endregion
#region 第2次失败
@@ -143,8 +143,8 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Equal(2, blackboard.chooseBaitfailures.Where(f => f == "fake fly bait").Count());
Assert.False(blackboard.noFish);
Assert.Equal(2, blackboard.chooseBaitFailures.Where(f => f == "fake fly bait").Count());
Assert.False(blackboard.abort);
#endregion
#region medaka受到遮挡,第3次失败
@@ -162,7 +162,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Single(blackboard.chooseBaitfailures.Where(f => f == "spinelgrain bait"));
Assert.Single(blackboard.chooseBaitFailures.Where(f => f == "spinelgrain bait"));
#endregion
#region sunfish受到遮挡,medaka再次出现,第4次成功,并钓起medaka
@@ -180,7 +180,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.False(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Succeeded, actual);
Assert.Single(blackboard.chooseBaitfailures.Where(f => f == "spinelgrain bait"));
Assert.Single(blackboard.chooseBaitFailures.Where(f => f == "spinelgrain bait"));
#endregion
#region sunfish再次出现,第5次失败
@@ -198,7 +198,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Equal(2, blackboard.chooseBaitfailures.Where(f => f == "spinelgrain bait").Count());
Assert.Equal(2, blackboard.chooseBaitFailures.Where(f => f == "spinelgrain bait").Count());
#endregion
}
@@ -232,7 +232,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Single(blackboard.chooseBaitfailures.Where(f => f == "fake fly bait"));
Assert.Single(blackboard.chooseBaitFailures.Where(f => f == "fake fly bait"));
#endregion
#region koi受到遮挡,第2次失败
@@ -250,8 +250,8 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Single(blackboard.chooseBaitfailures.Where(f => f == "spinelgrain bait"));
Assert.False(blackboard.noFish);
Assert.Single(blackboard.chooseBaitFailures.Where(f => f == "spinelgrain bait"));
Assert.False(blackboard.abort);
#endregion
#region koi再次出现,第3次失败
@@ -269,7 +269,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Equal(2, blackboard.chooseBaitfailures.Where(f => f == "fake fly bait").Count());
Assert.Equal(2, blackboard.chooseBaitFailures.Where(f => f == "fake fly bait").Count());
#endregion
#region 第4次失败
@@ -287,7 +287,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
Assert.True(String.IsNullOrEmpty(blackboard.selectedBaitName));
Assert.Equal(BehaviourStatus.Failed, actual);
Assert.Equal(2, blackboard.chooseBaitfailures.Where(f => f == "spinelgrain bait").Count());
Assert.Equal(2, blackboard.chooseBaitFailures.Where(f => f == "spinelgrain bait").Count());
#endregion
}
}
@@ -6,6 +6,7 @@ using System.Drawing;
using BehaviourTree.Composites;
using BehaviourTree.FluentBuilder;
using Microsoft.Extensions.Time.Testing;
using OpenCvSharp;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
@@ -20,7 +21,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void FishBite_ShouldSuccess(string screenshot1080p)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
//
@@ -39,7 +40,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void FishBite_Tree_Timeout_ShouldSuccess(string screenshot1080pCheckThrowRod, string screenshot1080pFishBite)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080pCheckThrowRod}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080pCheckThrowRod}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
DateTimeOffset dateTime = new DateTimeOffset(2025, 2, 26, 16, 13, 54, 285, TimeSpan.FromHours(8));
@@ -70,7 +71,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
//
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(16));
bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080pFishBite}");
bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080pFishBite}");
imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
//
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
using System.Drawing;
using BetterGenshinImpact.Core.Recognition.ONNX.YOLO;
using Microsoft.Extensions.Time.Testing;
using OpenCvSharp;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
@@ -17,13 +18,15 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
[Theory]
[InlineData(@"20250306111752769_GetFishBoxArea_Succeeded.png")]
[InlineData(@"20250313-0442-39.4967763.mp4_20250313_132441.664.png")] // 网友反馈的案例,有偏色
[InlineData(@"20250313-0442-39.4967763.mp4_20250313_132441.969.png")]
/// <summary>
/// 测试获取钓鱼拉扯框,结果为成功
/// </summary>
public void GetFishBoxArea_ShouldSuccess(string screenshot1080p)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, drawContent: new FakeDrawContent());
var blackboard = new Blackboard(null, sleep: i => { });
@@ -45,7 +48,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void GetFishBoxArea_ShouldFail(string screenshot1080p)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, drawContent: new FakeDrawContent());
var blackboard = new Blackboard(null, sleep: i => { });
@@ -10,6 +10,7 @@ using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Core.Config;
using Compunet.YoloV8;
using BetterGenshinImpact.GameTask.AutoFishing.Model;
using OpenCvSharp;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
@@ -25,7 +26,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void GetFishpondTest_VariousFishExist_ShouldSuccess(string screenshot1080p, IEnumerable<string> fishNames)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
@@ -53,14 +54,14 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void GetFishpondTest_AllIgnored_ShouldBeRunning(string screenshot1080p, IEnumerable<string> chooseBaitfailures, IEnumerable<string> throwRodNoTargetFishfailures)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
var blackboard = new Blackboard(predictor, sleep: i => { });
blackboard.chooseBaitfailures = chooseBaitfailures.ToList();
blackboard.throwRodNoTargetFishfailures = throwRodNoTargetFishfailures.ToList();
blackboard.chooseBaitFailures = chooseBaitfailures.ToList();
blackboard.throwRodNoBaitFishFailures = throwRodNoTargetFishfailures.ToList();
//
GetFishpond sut = new GetFishpond("-", blackboard, new FakeLogger(), false, drawContent: new FakeDrawContent());
@@ -88,7 +89,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void GetFishpondTest_FishCount_ShouldSuccess(string screenshot1080p, string fishName, int count)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
@@ -12,6 +12,7 @@ using System.Drawing;
using BetterGenshinImpact.Core.Config;
using Compunet.YoloV8;
using Microsoft.Extensions.Time.Testing;
using OpenCvSharp;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
@@ -26,7 +27,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void ThrowRodTest_VariousFish_ShouldSuccess(string screenshot1080p, string selectedBaitName)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
@@ -43,21 +44,20 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
BehaviourStatus actual = sut.Tick(imageRegion);
//
Assert.False(blackboard.throwRodNoTargetFish);
Assert.False(blackboard.throwRodNoBaitFish);
Assert.Equal(BehaviourStatus.Succeeded, actual);
}
[Theory]
[InlineData(@"20250225101304534_ThrowRod_Succeeded.png", "fruit paste bait")]
[InlineData(@"20250225101304534_ThrowRod_Succeeded.png", "redrot bait")]
[InlineData(@"20250225101304534_ThrowRod_Succeeded.png", "fake fly bait")]
/// <summary>
/// 测试各种抛竿,结果为运行中
/// 测试各种抛竿,未满足HutaoFisher判定,结果为运行中
/// </summary>
public void ThrowRodTest_VariousFish_ShouldFail(string screenshot1080p, string selectedBaitName)
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
@@ -74,10 +74,51 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
BehaviourStatus actual = sut.Tick(imageRegion);
//
Assert.False(blackboard.throwRodNoTargetFish);
Assert.False(blackboard.throwRodNoBaitFish);
Assert.Equal(BehaviourStatus.Running, actual);
}
[Theory]
[InlineData(@"20250225101304534_ThrowRod_Succeeded.png", "flashing maintenance mek bait")]
/// <summary>
/// 测试各种抛竿,无鱼饵适用鱼,结果为失败
/// </summary>
public void ThrowRodTest_NoBaitFish_ShouldFail(string screenshot1080p, string selectedBaitName)
{
//
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
var blackboard = new Blackboard(predictor, sleep: i => { })
{
selectedBaitName = selectedBaitName
};
FakeTimeProvider fakeTimeProvider = new FakeTimeProvider();
//
ThrowRod sut = new ThrowRod("-", blackboard, new FakeLogger(), false, new FakeInputSimulator(), fakeTimeProvider, drawContent: new FakeDrawContent());
BehaviourStatus actual = sut.Tick(imageRegion);
//
Assert.False(blackboard.throwRodNoBaitFish);
Assert.Equal(BehaviourStatus.Running, actual);
//
// Do nothing
//
for (int i = 0; i < 10; i++)
{
sut.Tick(imageRegion);
}
//
Assert.True(blackboard.throwRodNoBaitFish);
}
/// <summary>
/// 抛竿时,给定三条炮鲀鱼,并且确定算法能将下杆点从鱼的左侧移动到最左侧的炮鲀鱼上,此时希望“当前鱼”能始终锁定在最左侧的鱼上
/// 由于偶尔观测到“摇摆”行为的出现,故设计此测试
@@ -86,7 +127,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
public void ThrowRodTest_Target_ShouldBeTheLeftOne()
{
//
Bitmap bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\202503082114541115.png");
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\202503082114541115.png");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
@@ -107,7 +148,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
Assert.Equal(blackboard.fishpond.Fishes.OrderBy(f => f.Rect.X).First(), actual);
//
bitmap = new Bitmap(@$"..\..\..\Assets\AutoFishing\202503082114560489.png");
bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\202503082114560489.png");
imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
//
@@ -118,5 +159,42 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
Assert.Equal(3, blackboard.fishpond.Fishes.Count(f => f.FishType.Name == "pufferfish"));
Assert.Equal(blackboard.fishpond.Fishes.OrderBy(f => f.Rect.X).First(), actual);
}
[Theory]
[InlineData(@"202502252347412417.png")]
[InlineData(@"[email protected]")]
/// <summary>
/// 测试各种抛竿,超时未找到落点,结果为失败
/// </summary>
public void ThrowRodTest_NoTarget_ShouldFail(string screenshot1080p)
{
//
Mat bitmap = new Mat(@$"..\..\..\Assets\AutoFishing\{screenshot1080p}");
var imageRegion = new GameCaptureRegion(bitmap, 0, 0, new DesktopRegion(new FakeMouseSimulator()), converter: new ScaleConverter(1d), drawContent: new FakeDrawContent());
var predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).Build();
var blackboard = new Blackboard(predictor, sleep: i => { });
FakeTimeProvider fakeTimeProvider = new FakeTimeProvider();
//
ThrowRod sut = new ThrowRod("-", blackboard, new FakeLogger(), false, new FakeInputSimulator(), fakeTimeProvider, drawContent: new FakeDrawContent());
BehaviourStatus actual = sut.Tick(imageRegion);
//
Assert.False(blackboard.throwRodNoTarget);
Assert.Equal(BehaviourStatus.Running, actual);
//
fakeTimeProvider.Advance(TimeSpan.FromSeconds(5.1));
//
actual = sut.Tick(imageRegion);
//
Assert.True(blackboard.throwRodNoTarget);
Assert.Equal(BehaviourStatus.Failed, actual);
}
}
}