Compare commits

...
114 Commits
Author SHA1 Message Date
辉鸭蛋 c4a7823c83 fix js pathingScript 2024-10-13 22:58:42 +08:00
辉鸭蛋 50aac5cea0 auto pathing opt 2024-10-13 22:12:07 +08:00
辉鸭蛋 228d50bb5d Revert "feat: 优化autopath MoveTo逻辑"
This reverts commit 504f853893.
2024-10-13 21:09:41 +08:00
辉鸭蛋 5e16f48cf2 update pating ui 2024-10-13 20:51:02 +08:00
辉鸭蛋 6fb29ddfad Xilonen 5.1 2024-10-13 20:46:56 +08:00
辉鸭蛋 ac4dde6bf0 Merge pull request #685 from gqzcl/main_path
feat: 优化autopath MoveTo逻辑
2024-10-13 18:50:49 +08:00
辉鸭蛋 6c643b2419 删除一些默认用户配置 2024-10-13 18:27:03 +08:00
辉鸭蛋 2f44905c27 rm script 2024-10-13 18:24:06 +08:00
辉鸭蛋 b2cf62a21c add local script repo web
重构了 `AvatarClassifyGen.cs` 中的图像读取逻辑,现在只读取一个图像文件。`AllConfig.cs` 中添加了 `ScriptConfig` 类的配置,并监听其属性变化。`ScriptRepoUpdater.cs` 中引入了多个新命名空间,添加了 `_logger` 和 `_webWindow` 字段,新增了 `AutoUpdate` 方法,修改了 `UpdateCenterRepo` 方法,新增了 `FindCenterRepoPath`、`ImportScriptFromUri` 和 `OpenLocalRepoInWebView` 方法。`WebpagePanel.cs` 中添加了 `OnWebViewInitializedAction` 属性。`WebpageWindow.cs` 中注释掉了背景色设置。`MainWindow.xaml` 中修改了标题栏图标路径。`JsListPage.xaml`、`KeyMouseRecordPage.xaml` 和 `MapPathingPage.xaml` 中修改了按钮命令绑定。`MainWindowViewModel.cs` 中添加了 `AutoUpdate` 方法调用。`JsListViewModel.cs`、`KeyMouseRecordPageViewModel.cs` 和 `MapPathingViewModel.cs` 中添加了 `Config` 属性和 `OnOpenLocalScriptRepo` 命令。新增了 `ScriptConfig.cs` 和 `RepoWebBridge.cs` 文件,定义了 `ScriptConfig` 和 `RepoWebBridge` 类。
2024-10-13 18:13:28 +08:00
辉鸭蛋 245c05b208 1st logo #671 2024-10-13 15:42:49 +08:00
辉鸭蛋 333ad6f0b4 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-13 13:36:10 +08:00
辉鸭蛋 c75dbbc241 add script repo downloader 2024-10-13 13:36:06 +08:00
ema 421b11504f fix: titlebar accent color #442 2024-10-13 03:02:19 +08:00
辉鸭蛋 bb18350457 fix mouse move for js 2024-10-11 03:12:38 +08:00
辉鸭蛋 831f28b2aa WPF-UI.Violeta 3.0.5.18 https://github.com/emako/wpfui.violeta/issues/5 2024-10-10 22:00:30 +08:00
辉鸭蛋 475b9bbd00 update ui text & ProxySpeedTester
删除了 `ClickOffset` 类及其相关代码。
在 `MainWindow.xaml` 中,将导航菜单项的内容从“脚本”更改为“JS 脚本”。
在 `JsListPage.xaml` 和 `KeyMouseRecordPage.xaml` 中,更新了文本内容,并添加了指向相关教程的超链接。
在 `JsListViewModel.cs` 和 `KeyMouseRecordPageViewModel.cs` 中,分别添加了 `OnGoToJsScriptUrl` 和 `OnGoToKmScriptUrl` 方法,用于打开对应的教程 URL。
新增了 `ProxySpeedTester.cs` 文件,包含一个用于测试代理速度的类 `ProxySpeedTester`,提供了获取最快代理地址的方法。
2024-10-10 21:58:35 +08:00
辉鸭蛋 a963a8595a auto pick: add black list
新增黑名单条目至 pick_black_lists.json
2024-10-10 01:20:41 +08:00
辉鸭蛋 5c712c5a31 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-09 23:56:01 +08:00
辉鸭蛋 8651ec74a6 update ui 2024-10-09 23:53:55 +08:00
辉鸭蛋 6fadd528f1 Merge pull request #690 from haokaiyang/main
auto tcg: update character card config to v5.1
2024-10-09 13:32:26 +08:00
haokaiyang f20cf89d5f auto tcg: update character card config to v5.1 2024-10-09 11:25:59 +08:00
辉鸭蛋 c13db0a501 rename 2024-10-08 00:21:56 +08:00
辉鸭蛋 7b80867bd1 update ui 2024-10-06 21:05:42 +08:00
辉鸭蛋 a2f877c455 increase the minimum waiting time for the transmission panel delay to 300 milliseconds
增加传送面板延迟的最小等待时间至 300 毫秒

将 `time` 的最小值从 100 毫秒增加到 300 毫秒。这意味着在等待传送面板延迟时,最小等待时间从 100 毫秒变为 300 毫秒。
2024-10-06 14:50:53 +08:00
gqzcl 504f853893 feat: 优化autopath MoveTo逻辑 2024-10-05 14:04:20 +08:00
辉鸭蛋 b1f6c062fb auto tp: add blocked click area
主要变更:
- 在 `TpTask` 构造函数中添加了两个新的私有只读字段 `_captureRect` 和 `_zoomOutMax1080PRatio`。
- 在 `TpOnce` 方法中,使用新的私有字段 `_zoomOutMax1080PRatio` 替代局部变量 `s`。
- 将 `while` 循环条件改为调用新的私有方法 `IsPointInBigMapWindow`。
- 删除了原来计算点击坐标的代码,改为调用新的私有方法 `ConvertToGameRegionPosition`。
- 添加了新的私有方法 `IsPointInBigMapWindow` 和 `ConvertToGameRegionPosition`。
- 更新了子项目的提交版本。

这些更改通过引入新的私有方法和字段,减少了重复代码,并使逻辑更加清晰,代码变得更加模块化,便于后续的维护和扩展。
2024-10-04 19:57:18 +08:00
辉鸭蛋 876a833590 fix: js script bug 2024-10-04 19:04:32 +08:00
辉鸭蛋 160e45c75a fix JustTp 2024-10-04 14:24:42 +08:00
辉鸭蛋 66f15488e1 add bgi version 2024-10-03 20:14:04 +08:00
辉鸭蛋 389dac879b js: add CaptureGameRegion 2024-10-03 16:24:56 +08:00
辉鸭蛋 8b6351cbd6 update: simulator for js 2024-10-03 00:40:07 +08:00
辉鸭蛋 ca126e0d66 js: +func 2024-10-02 19:20:25 +08:00
辉鸭蛋 6c0b293328 js: add solo task 2024-10-01 21:34:33 +08:00
辉鸭蛋 aee54cc115 js config 2024-10-01 20:25:39 +08:00
辉鸭蛋 2817479d33 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-01 20:10:51 +08:00
辉鸭蛋 8de5bcf987 auto pick: ForceInteraction 2024-10-01 20:10:46 +08:00
辉鸭蛋 a25cc951c9 new banner 2024-10-01 20:10:23 +08:00
辉鸭蛋 50ee1d1a3e Merge pull request #679 from lwh9346/main
添加了一些可靠的路径追踪捡狗粮路线
2024-10-01 19:15:22 +08:00
lwh9346 7f39062f14 添加了一些可靠的路径追踪捡狗粮路线 2024-10-01 16:56:31 +08:00
ema 619cb667cd chore: doc about game cli #665 2024-10-01 14:16:13 +08:00
ema 4da6efd54e fix the all about scrollable 2024-10-01 13:50:59 +08:00
辉鸭蛋 5fe3db52bf fix hotkey bug 2024-10-01 13:36:53 +08:00
辉鸭蛋 d760f2411a Merge pull request #676 from babalae/feat/btn
add TwoStateButton
2024-10-01 12:42:31 +08:00
辉鸭蛋 1706312957 wpfui.violeta 3.0.5.16 2024-10-01 12:35:08 +08:00
辉鸭蛋 d686fdcb5a auto skip black list #677 2024-10-01 12:17:01 +08:00
辉鸭蛋 a93839e0be refactor: hotkey UI to a tree view 2024-10-01 01:58:00 +08:00
辉鸭蛋 6e00e3f91e collect fight screenshots 2024-10-01 01:56:53 +08:00
qhy040404 41c5f4c226 fix wrong state 2024-10-01 00:04:35 +08:00
qhy040404 95f7b76a03 add TwoStateButton 2024-09-30 23:17:10 +08:00
辉鸭蛋 c137daec40 fix ui 2024-09-30 22:04:01 +08:00
辉鸭蛋 c89e2d4e84 upgrade build ps1
在 `upload_1_build_dist.cmd` 文件中:
- 添加了切换到当前脚本目录的命令 `cd /d %~dp0`。
- 添加了删除 `dist` 目录及其子目录的命令 `if exist dist rd /s /q dist`。
- 添加了创建 `dist\BetterGI` 目录的命令 `mkdir dist\BetterGI`。
- 添加了准备编译器的命令,使用 `vswhere.exe` 查找最新的 Visual Studio 安装路径并设置环境变量。
- 添加了准备版本信息的命令,使用 PowerShell 从 `BetterGenshinImpact.csproj` 文件中提取 `AssemblyVersion`。
- 添加了设置临时文件夹和归档文件名的命令。
- 添加了使用 Visual Studio 2022 构建应用程序的命令。
- 添加了使用 7z 打包应用程序的命令。
- 添加了删除特定文件(如 `.lib` 和 `ffmpeg` DLL 文件)的命令。
- 添加了从特定路径复制文件到临时文件夹的命令。
- 添加了暂停命令 `@pause`。

在 `upload_2_zip_dist.ps1` 文件中:
- 添加了导入 `Microsoft.PowerShell.Archive` 模块的命令。
- 添加了设置目录路径、输出 JSON 路径和目标目录路径的命令。
- 添加了将相对路径转换为绝对路径的命令。
- 添加了初始化排除目录列表的命令。
- 添加了初始化一个空的哈希表来存储文件路径和哈希值的命令。
- 添加了获取目录中所有文件的命令。
- 添加了遍历文件列表并计算每个文件的 SHA256 哈希值的命令。
- 添加了将文件路径和哈希值添加到哈希表中的命令。
- 添加了压缩文件并替换原文件的命令。
- 添加了将哈希表转换为 JSON 格式并写入文件的命令。
- 添加了获取所有 `.zip` 文件并复制到目标目录的命令。
- 添加了删除原始目录的命令。
2024-09-30 22:03:55 +08:00
辉鸭蛋 1901246bab Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-09-30 14:02:45 +08:00
辉鸭蛋 c15cb33c2c rename variables and properties, refactor code, add new configuration options
重命名变量和属性,重构代码,添加新配置选项

主要更改:
* 将 `AutoFightConfig` 和 `AutoFightParam` 类中的字段和属性重命名,以提高名称的清晰度和一致性。
* 移除不必要的 `using` 语句,并调整顺序。
* 重构 `AutoFightTask` 和 `AutoFightHandler` 类中的条件判断和方法逻辑。
* 调整 `CameraRotateTask` 类中的参数值。
* 在 `PathExecutor` 类中添加 `_rotateTask` 字段,并修改相关方法调用。
* 在 `TaskSettingsPage.xaml` 中添加新的配置选项。
* 在 `HotKeyPageViewModel` 类中添加 `using` 语句,并修改热键回调逻辑。
* 修改 `TaskSettingsPageViewModel` 类中 `AutoFightParam` 的初始化。
2024-09-30 13:42:11 +08:00
ema 377de9e244 update: use embedded pdb 2024-09-30 10:29:19 +08:00
ema 335b053b32 change: moved image assets to new folder 2024-09-30 10:12:13 +08:00
辉鸭蛋 2516f9b248 fix tp task 2024-09-30 00:30:00 +08:00
辉鸭蛋 d9e5f2f1dd add rotate task
在 `BgiYoloV8Predictor.cs` 文件中,添加了 `System.Diagnostics`、`System.Drawing.Imaging` 和 `System.IO` 的引用,并在 YOLOv8 识别结果返回前,添加了调试输出,使用 `JsonSerializer` 序列化识别结果并输出到调试窗口。

在 `AutoFightTask.cs` 文件中,添加了 `System.Collections.Generic` 和 `BetterGenshinImpact.GameTask.AutoPathing` 的引用,修改了 `combatScenes.BeforeTask` 方法的调用,使用新的取消令牌 `cts2`。在战斗操作的 `Task.Run` 中添加了 `try-catch` 块,以捕获并忽略异常。修改了战斗结束检测线程,使用 `async` 和 `await` 关键字,并在检测战斗结束时添加了 `try-catch` 块。修改了 `CheckFightFinish` 方法,改为异步方法 `CheckFightFinish`,并在检测战斗结束时添加了旋转视角的逻辑。

在 `PathExecutor.cs` 文件中,添加了关于 DPI 和分辨率影响转动速度的注释。

在 `TaskSettingsPageViewModel.cs` 文件中,在获取战斗策略后,创建了 `AutoFightParam` 对象,并设置了 `EndDetect` 和 `AutoPickAfterFight` 参数。修改了 `RunSoloTaskAsync` 方法的调用,传入了新的 `AutoFightParam` 对象。

在 `CameraRotateTask.cs` 文件中,添加了新的 `CameraRotateTask` 类,用于处理相机视角的旋转,实现了 `RotateToApproach` 方法,用于将视角旋转到接近目标角度,实现了 `WaitUntilRotatedTo` 异步方法,用于等待视角旋转到目标角度。
2024-09-30 00:10:08 +08:00
辉鸭蛋 0549df75b6 auto fight: init end detect
在 `BetterGenshinImpact.csproj` 文件中,删除了 `Assets\Model\World\` 和 `Script\JustTp\` 文件夹的包含项。

在 `AutoFightConfig.cs` 文件中,`AutoFightConfig` 类新增了两个属性:`_endDetect` 和 `_autoPickAfterFight`,并且默认值分别为 `true`。

在 `AutoFightParam.cs` 文件中,`AutoFightParam` 类新增了两个属性:`EndDetect` 和 `AutoPickAfterFight`,并且默认值分别为 `false`。

在 `AutoFightTask.cs` 文件中:
  * 修改了 `using` 引用,添加了 `BetterGenshinImpact.Core.Config` 和 `BetterGenshinImpact.GameTask.Model.Area`,删除了 `BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception`。
  * 在 `AutoFightTask` 类中,新增了 `_predictor` 和 `_lastFightFlagTime` 字段。
  * 在 `AutoFightTask` 构造函数中,增加了对 `EndDetect` 和 `AutoPickAfterFight` 属性的检查,并在满足条件时初始化 `_predictor`。
  * 修改了 `Start` 方法,增加了战斗结束检测线程和自动拾取掉落物的功能。
  * 新增了 `CheckFightFinish` 和 `HasFightFlag` 方法,用于检测战斗是否结束。

在 `BetterGenshinImpact.Core.Recognition.ONNX` 命名空间下新增了 `BgiYoloV8Predictor` 类,并实现了 `IDisposable` 接口。
  * 添加了一个只读字段 `_predictor`,并通过 `YoloV8Builder` 创建了一个默认的 YoloV8 预测器。
  * 添加了一个 `Predictor` 属性,用于获取 `_predictor`。
  * 添加了一个 `Detect` 方法,该方法接受一个 `ImageRegion` 对象作为参数,并返回一个包含类别和矩形框的字典。
  * 添加了 `Dispose` 方法,用于释放 `_predictor` 的资源。
2024-09-29 23:01:29 +08:00
辉鸭蛋 35264bc855 auto tp: throwing an exception when the tp point is not activated
在 `TpTask.cs` 文件中,添加了 `using BetterGenshinImpact.GameTask.Common.Exceptions;` 引用,并在 `TpTask` 类中添加了对 `TpPointNotActivate` 异常的处理逻辑,当传送点未激活或不存在时,按下 ESC 键返回大地图界面,并抛出异常。同时在 `ClickTpPoint` 方法中,修改了判断逻辑,增加了对传送点未激活或不存在的异常处理。

在 `MapAssets.cs`、`NewRetry.cs`、`TaskControl.cs` 文件中,将 `Exception` 修改为 `System.Exception`。

在 `NormalEndException.cs` 和 `RetryException.cs` 文件中,删除了旧的异常类定义,并重新添加了新的异常类定义。

在 `TpPointNotActivate.cs` 文件中,添加了新的异常类 `TpPointNotActivate`。
2024-09-29 21:37:54 +08:00
辉鸭蛋 5167ce0ba8 Merge pull request #658 from iris10086/iris-dev
在路径追踪中添加了一个AutoFightAction实现
2024-09-25 10:58:16 +08:00
辉鸭蛋 7df330a9fb 低分辨率缩放 2024-09-24 01:18:26 +08:00
辉鸭蛋 24c2d2cbf0 直接调用重构后的自动战斗独立任务
移除了 `AutoFightHandler` 类中的 `_combatScriptBag` 相关代码,并替换为新的 `AutoFightTask` 任务。
添加了新的命名空间引用,包括 `BetterGenshinImpact.GameTask.AutoFight`、`BetterGenshinImpact.GameTask.Common.TaskControl`、`System.IO` 和 `Wpf.Ui.Violeta.Controls`。
在 `StartFight` 方法中,替换了原有的战斗操作逻辑,使用 `AutoFightTask` 类来处理战斗任务。
添加了新的 `GetFightStrategy` 方法,用于获取战斗策略文件路径。
修改了战斗结束检测逻辑,将 `checkFightFinish` 方法重命名为 `CheckFightFinish`,并调整了检测逻辑。
调整了任务取消的逻辑,使用新的 `CancellationTokenSource` 实例 `cts2` 来管理任务取消。
将原有的 `Task` 实例替换为 `Task.Run` 方法来启动任务。
调整了任务等待逻辑,使用 `Task.WhenAll` 方法等待战斗任务和结束检测任务的完成。
2024-09-23 22:24:58 +08:00
辉鸭蛋 d51139025b 便携营养袋 的判断进行前置,减少无意义的性能损耗 2024-09-23 22:21:12 +08:00
辉鸭蛋 e7148f827d Merge branch 'iris-dev' of https://github.com/iris10086/better-genshin-impact into pr/658 2024-09-23 21:59:59 +08:00
辉鸭蛋 3d5d918d24 Merge branch 'main' into pr/658 2024-09-23 21:59:16 +08:00
何杰泽 ff969abbc7 自动吃药 添加了是否携带食物的检测 2024-09-23 21:18:24 +08:00
iris10086 541e9331c0 Merge branch 'babalae:main' into iris-dev 2024-09-23 20:44:10 +08:00
辉鸭蛋 f182e345c2 Merge pull request #660 from babalae/feat-solo-task
refactor: solo task
2024-09-23 10:07:59 +08:00
辉鸭蛋 5a0f7226ed update ISoloTask
更新 Start 方法以接受 CancellationTokenSource 参数

这些更改主要是为了使 `Start` 方法能够接受 `CancellationTokenSource` 参数,从而更好地控制任务的取消操作。通过传递 `CancellationTokenSource`,可以在需要时取消正在运行的任务,提高了代码的灵活性和可控性。

具体更改包括:
- 将 `Start` 方法的签名从无参数更改为接受 `CancellationTokenSource` 参数。
- 在多个任务类(如 `AutoDomainTask.cs`、`AutoFightTask.cs`、`AutoGeniusInvokationTask.cs`、`AutoMusicGameTask.cs`、`AutoWoodTask.cs`)中,更新 `Start` 方法以接受并使用传入的 `CancellationTokenSource`。
- 在 `Duel.cs` 中,更新 `RunAsync` 和 `Run` 方法的参数以接受 `CancellationTokenSource`,并将 `Cts` 赋值为传入的 `cts`。
- 在 `ISoloTask.cs` 接口中,更新 `Start` 方法的签名以接受 `CancellationTokenSource` 参数。
- 在 `TaskRunner.cs` 中,调用 `soloTask.Start` 时传入 `CancellationContext.Instance.Cts` 作为参数。
2024-09-23 00:04:09 +08:00
辉鸭蛋 8bb1d728ff refactor: solo task 2024-09-22 23:56:39 +08:00
辉鸭蛋 38e05830a2 nahida collect opt
优化 NahidaCollectHandler 逻辑并更新 HotKeyPageViewModel

在 NahidaCollectHandler.cs 文件中,调整了 RunAsync 方法的多个参数和延迟时间,增加了条件判断以优化逻辑。在 HotKeyPageViewModel.cs 文件中,添加了新的引用,并修改了 Test1Hotkey 的回调函数以调用 NahidaCollectHandler 的 RunAsync 方法。
2024-09-22 00:27:49 +08:00
辉鸭蛋 89340c42b0 code cleanup 2024-09-22 00:01:10 +08:00
辉鸭蛋 8e44643a51 auto eat #649 2024-09-21 23:41:20 +08:00
辉鸭蛋 7afbbee3e1 add more interrupt operation
在 KeyMouseMacroPlayer 类中添加取消请求检查

在 `KeyMouseMacroPlayer` 类中添加了一个检查取消请求的功能。
在处理每个宏事件之前,增加了以下代码:
    if (ct.IsCancellationRequested)
    {
        return;
    }
这段代码用于在取消请求被触发时,立即终止宏事件的重放。
2024-09-21 18:11:47 +08:00
iris10086 6cf96c71f3 Merge branch 'babalae:main' into iris-dev 2024-09-21 16:02:40 +08:00
何杰泽 997059dd4b 添加fight action。战斗结束策略比较low。 2024-09-21 15:56:37 +08:00
辉鸭蛋 b445cbf42f Merge pull request #649 from iris10086/iris-dev
添加了一个自动吃药的实时触发。
2024-09-21 15:47:00 +08:00
何杰泽 19e7c9d02e Merge branches 'main' and 'main' of github.com:iris10086/better-genshin-impact into iris-dev 2024-09-19 08:30:26 +08:00
何杰泽 d3f0f89da1 添加autoEat功能。 2024-09-19 08:24:41 +08:00
辉鸭蛋 70b1ed88bb auto pathing: add nahida_collect action
新增 Action 处理机制及相关类和方法

删除了 `PickHandler` 类及其相关的 `Obsolete` 特性。
在 `ActionEnum` 类中新增了两个静态只读字段:`NahidaCollect` 和 `PickAround`。
在 `PathExecutor` 类中引入了 `BetterGenshinImpact.GameTask.AutoPathing.Handler` 命名空间。
在 `PathExecutor` 类的 `MoveTo` 方法中,添加了一个调用 `AfterMoveToTarget` 方法的步骤,用于在到达点位后执行特定的动作。
在 `PathExecutor` 类中,修改了疑似卡死时的延迟时间,从 500 毫秒增加到 1500 毫秒。
在 `PathExecutor` 类中新增了 `AfterMoveToTarget` 方法,用于根据 `waypoint.Action` 执行相应的处理逻辑。
新增了 `ActionFactory` 类,用于根据 `handlerType` 获取相应的 `IActionHandler` 实例。
新增了 `IActionHandler` 接口,定义了 `RunAsync` 方法。
新增了 `NahidaCollectHandler` 类,实现了 `IActionHandler` 接口,用于执行纳西妲的收集操作。
新增了 `PickAroundHandler` 类,实现了 `IActionHandler` 接口,暂时未实现具体的拾取操作逻辑。
2024-09-19 00:36:14 +08:00
辉鸭蛋 1a4682bf29 Update README.md 2024-09-18 21:37:23 +08:00
ema 19fbcc48ab chore: hint audio resource for #640 2024-09-18 17:08:50 +08:00
辉鸭蛋 c63ac6947a fix big map shrink 2024-09-18 00:56:34 +08:00
何杰泽 98da4e072c Merge remote-tracking branch 'origin/main' into iris-dev 2024-09-17 22:24:44 +08:00
何杰泽 a2adfe5b6f 修改自动秘境战斗策略,添加自动吃药任务。但是没进行判断。 2024-09-17 22:18:00 +08:00
辉鸭蛋 9cc91b4568 test new pic 2024-09-17 18:18:31 +08:00
辉鸭蛋 068cbd6e20 删除重复点位 2024-09-17 17:54:27 +08:00
辉鸭蛋 f713847df2 add missing tp points #630 #603 #586 2024-09-17 16:29:47 +08:00
辉鸭蛋 c39a882272 auto tp: shrink big map #604 2024-09-17 15:24:09 +08:00
辉鸭蛋 5f9ca6b399 auto pathing: add force tp for tp point 2024-09-17 15:06:32 +08:00
辉鸭蛋 bfe6b69edd fix build bat 2024-09-17 12:24:58 +08:00
辉鸭蛋 8dbdf0840c add map pos editor 2024-09-17 01:41:20 +08:00
辉鸭蛋 4cba618722 edit ui text 2024-09-16 22:13:11 +08:00
辉鸭蛋 4cc4aa27f0 fix path recorder 2024-09-16 21:31:40 +08:00
辉鸭蛋 3e69e6c3ac fix map pos not reset during feature match #619 2024-09-16 21:15:59 +08:00
辉鸭蛋 6414210095 add log #631 2024-09-16 20:27:52 +08:00
辉鸭蛋 83e6798439 add an entry to open the log folder #632 2024-09-16 20:12:58 +08:00
辉鸭蛋 779fbaad86 add refresh context menu #627
添加刷新命令菜单项及刷新方法

在 `JsListPage.xaml` 和 `MapPathingPage.xaml` 中,添加了新的菜单项 `<MenuItem>`,用于绑定 `RefreshCommand` 命令,并设置了相应的 `CommandParameter` 和 `Header` 属性。

在 `JsListViewModel.cs` 中,添加了 `using BetterGenshinImpact.GameTask.AutoPathing.Model;` 语句,并修改了 `OnOpenScriptProjectFolder` 方法,将 `item` 为 `null` 时的处理逻辑改为使用 `scriptPath`。

在 `JsListViewModel.cs` 和 `MapPathingViewModel.cs` 中,添加了 `OnRefresh` 方法,该方法通过调用 `InitScriptListViewData` 来刷新脚本列表视图数据。
2024-09-16 10:52:34 +08:00
辉鸭蛋 962d47722d tp with retry
将 `Tp` 方法重命名为 `TpOnce`,以便区分新的 `Tp` 方法。
新增了一个 `Tp` 方法,该方法会重试调用 `TpOnce` 方法最多三次,如果三次都失败则抛出异常。
修改了一个重试机制的时间间隔,从 500 毫秒重试 10 次改为 500 毫秒重试 5 次。
2024-09-15 19:44:44 +08:00
辉鸭蛋 89079f74d8 if the current map location recognition fails, the national location will be directly used for large-scale map positioning
重构大地图中心点位置获取逻辑

在 `TpTask.cs` 文件中,添加了一个新的方法 `GetPositionFromBigMapNullable`,该方法在调用 `GetBigMapCenterPoint` 时使用了 `try-catch` 结构来捕获异常,并在发生异常时返回 `null`。

修改了原有代码中获取大地图中心点位置的逻辑。原先直接调用 `GetPositionFromBigMap` 方法,现在改为调用新的 `GetPositionFromBigMapNullable` 方法,并在获取到非空值时计算距离和记录日志。

将计算 `minDistance` 的逻辑从直接计算改为在获取到有效的大地图中心点位置后再进行计算。
2024-09-15 19:37:11 +08:00
辉鸭蛋 8dc074e987 tile map 2024-09-15 19:34:59 +08:00
辉鸭蛋 12d4c60f7a fix absolute path for pathing in dispatcher 2024-09-15 19:34:40 +08:00
何杰泽 fae49c4c3b 添加自动吃药的功能。 2024-09-12 15:34:53 +08:00
ema a4e55ab164 change: WindowBackdropType 2024-09-12 00:08:59 +08:00
辉鸭蛋 dc8c1e063e update the naming format for saving path files #600
将保存路径文件的命名格式从“yyyy-MM-dd HH:mm:ss:ffff”更改为“yyyyMMdd_HHmmss”。
2024-09-11 22:35:27 +08:00
辉鸭蛋 1d9168d96e Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-09-11 22:31:27 +08:00
辉鸭蛋 2d4a6192f2 fix #606 2024-09-11 22:30:34 +08:00
ema 7b51c018a7 feat: ExceptionReport 2024-09-11 22:28:59 +08:00
辉鸭蛋 121bfbaa8e fix #608 2024-09-11 21:50:17 +08:00
辉鸭蛋 8d2b36d5fd refactor: script run 2024-09-10 23:27:04 +08:00
辉鸭蛋 c83d3e336f Update README.md 2024-09-10 16:17:42 +08:00
辉鸭蛋 5f76749be7 use System.Windows.Forms.MessageBox for unhandled exception 2024-09-10 00:32:12 +08:00
辉鸭蛋 57d2257283 fix map hotkey not save 2024-09-10 00:20:07 +08:00
辉鸭蛋 1657beb9a8 fix open map viewer 2024-09-10 00:01:04 +08:00
166 changed files with 4854 additions and 4338 deletions

No files matched your search

@@ -19,17 +19,17 @@ public class AvatarClassifyGen
// 读取基础图像
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Emilie.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_MomokaCostumeErrantry.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_NilouCostumeFairy.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles3);
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kachina.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles4);
List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mualani.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles5);
List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kinich.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles6);
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Xilonen.png", SearchOption.TopDirectoryOnly).ToList();
// List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_MomokaCostumeErrantry.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles2);
// List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_NilouCostumeFairy.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles3);
// List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kachina.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles4);
// List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mualani.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles5);
// List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kinich.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles6);
// 生成训练集
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
+2 -6
View File
@@ -1,17 +1,13 @@
using System.Windows;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Test.Dataset;
using BetterGenshinImpact.Test.Simple;
using BetterGenshinImpact.Test.Simple.AllMap;
using BetterGenshinImpact.Test.Simple.Track;
using BetterGenshinImpact.Test.View;
using System.Windows;
namespace BetterGenshinImpact.Test;
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
@@ -157,8 +157,11 @@ public class MapPuzzle
Debug.WriteLine("");
}
// 地图图片块
SaveImagesAs1024X1024(arr, imageLocations, @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\地图块", minRow, minCol);
// 保存大图
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\map_50_2048.png", largeImage);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\map_50_2048.png", largeImage);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_sd4x.png", largeImage.Resize(new Size(largeImage.Width / 4, largeImage.Height / 4), 0, 0, InterpolationFlags.Cubic));
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_small.png", largeImage.Resize(new Size(1400, 1300), 0, 0, InterpolationFlags.Cubic));
@@ -170,6 +173,36 @@ public class MapPuzzle
}
}
public static void SaveImagesAs1024X1024(int[,] arr, Dictionary<(int row, int col), ImgInfo> imageLocations, string outputFolder, int minRow, int minCol)
{
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
for (int row = 0; row < arr.GetLength(0); row++)
{
for (int col = 0; col < arr.GetLength(1); col++)
{
if (arr[row, col] == 1)
{
var key = (row + minRow, col + minCol);
if (imageLocations.TryGetValue(key, out var imgInfo))
{
var img = imgInfo.Img;
if (img.Width != 1204 || img.Height != 1204)
{
img = imgInfo.Img.Resize(new Size(1024, 1024), 0, 0, InterpolationFlags.Nearest);
}
var outputPath = Path.Combine(outputFolder, $"{row}_{col}.png");
Cv2.ImWrite(outputPath, img);
img.Dispose();
}
}
}
}
}
public class ImgInfo
{
public Mat Img { get; set; }
@@ -13,11 +13,11 @@ public class MapTeleportPointDraw
{
public static void Draw()
{
var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\5.0");
pList.AddRange(MapAssets.Instance.TpPositions);
// var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\5.0");
// pList.AddRange(MapAssets.Instance.TpPositions);
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor.png");
DrawTeleportPoint(map, pList);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor_传送点.png", map);
DrawTeleportPoint(map, MapAssets.Instance.TpPositions);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\传送点_1024_0.34.3.png", map);
}
public static void DrawTeleportPoint(Mat map, List<GiWorldPosition> points)
+18 -1
View File
@@ -21,6 +21,7 @@ using System.IO;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact;
@@ -240,7 +241,23 @@ public partial class App : Application
e = e.InnerException;
}
MessageBox.Error("程序异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
try
{
ExceptionReport.Show(e);
}
catch
{
// Fallback.
System.Windows.Forms.MessageBox.Show(
$"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
);
}
// log
GetLogger<App>().LogDebug(e, "UnHandle Exception");
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

@@ -0,0 +1,21 @@
# 启动参数说明
启动参数本质是 Unity 独立平台播放器命令行参数 ,测试下来有用的参数大概如下:
- `-window-mode exclusive` 参数
- **独占全屏**,即选择游戏进程以独占全屏模式运行
- **该功能与游戏内浏览器功能不兼容,你应仅在能独立描述独占全屏的技术原理和效果的情况下开启本项**
- `-screen-fullscreen` 参数
- **全屏**,即选择启动游戏后的游戏界面是否设置为全屏
- `-popupwindow` 参数
- **无边框**,即选择启动游戏后的游戏界面是否设置为无边框窗口
- `-platform_type CLOUD_THIRD_PARTY_MOBILE` 参数
- **触摸屏模式**,即启用原神内置的触摸屏操作模式(键鼠输入将被忽略)
- 分辨率
- 该功能可以快速设置下方的覆盖屏幕宽度和高度选项,有一些常见的预设项可供选择
- `-screen-width` 参数
- **宽度**,即选择启动游戏后的游戏界面的宽度,例如 `1920`
- `-screen-height` 参数
- **高度**,即选择启动游戏后的游戏界面的高度,例如 `1080`
- `-monitor` 参数
- **显示器**,允许多显示器用户选择指定的显示器来运行游戏
Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

+17 -18
View File
@@ -8,27 +8,35 @@
<UseWindowsForms>true</UseWindowsForms>
<LangVersion>12.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\logo.ico</ApplicationIcon>
<ApplicationIcon>Assets\Images\Anniversary\logo_1st.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.34.6</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<None Remove="Assets\*.jpg" />
<None Remove="Assets\*.png" />
<None Remove="Assets\*.ico" />
<None Remove="Assets\Images\*.jpg" />
<None Remove="Assets\Images\*" />
<None Remove="Assets\Images\*.png" />
<None Remove="Assets\Images\*.ico" />
<None Remove="Assets\Fonts\*.ttf" />
<None Remove="Assets\Highlighting\*.xshd" />
<None Remove="Assets\Strings\*.html" />
<None Remove="Assets\Strings\*.md" />
<None Remove="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\*.jpg" />
<Resource Include="Assets\*.png" />
<Resource Include="Assets\*.ico" />
<Resource Include="Assets\Images\*.jpg" />
<Resource Include="Assets\Images\Anniversary\*" />
<Resource Include="Assets\Images\*.png" />
<Resource Include="Assets\Images\*.ico" />
<Resource Include="Assets\Fonts\*.ttf" />
<Resource Include="Assets\Highlighting\*.xshd" />
<Resource Include="Assets\Strings\*.html" />
<Resource Include="Assets\Strings\*.md" />
<Resource Include="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
@@ -61,7 +69,7 @@
<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.3" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.18" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
@@ -127,19 +135,10 @@
<None Update="User\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Script\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Script\JustTp\" />
</ItemGroup>
<ItemGroup>
<Compile Update="View\Pages\MapPathingPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Folder Include="User\AutoPathing\" />
</ItemGroup>
</Project>
+8 -1
View File
@@ -122,12 +122,17 @@ public partial class AllConfig : ObservableObject
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 脚本类配置
/// 宏配置
/// </summary>
public MacroConfig MacroConfig { get; set; } = new();
public RecordConfig RecordConfig { get; set; } = new();
/// <summary>
/// 脚本配置
/// </summary>
public ScriptConfig ScriptConfig { get; set; } = new();
/// <summary>
/// 快捷键配置
/// </summary>
@@ -160,6 +165,8 @@ public partial class AllConfig : ObservableObject
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
+3 -7
View File
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -7,7 +8,7 @@ namespace BetterGenshinImpact.Core.Config;
public class Global
{
public static string Version { get; } = "0.34.1";
public static string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version!.ToString(3);
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
@@ -28,12 +29,7 @@ public class Global
public static string ScriptPath()
{
return Absolute("Script");
}
public static string ScriptPath(string folderName)
{
return Path.Combine(Absolute("Script"), folderName);
return Absolute("User\\JsScript");
}
public static string? ReadAllTextIfExist(string relativePath)
@@ -172,10 +172,10 @@ public partial class HotKeyConfig : ObservableObject
// 路径记录开始
[ObservableProperty]
private string _getBigMapPosHotkey = "";
private string _recBigMapPosHotkey = "";
[ObservableProperty]
private string _getBigMapPosHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
private string _recBigMapPosHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 路径记录开始
[ObservableProperty]
@@ -0,0 +1,28 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Config;
/// <summary>
/// 脚本配置
/// </summary>
[Serializable]
public partial class ScriptConfig : ObservableObject
{
// 自动更新脚本仓库周期(天)
[ObservableProperty]
private int _autoUpdateScriptRepoPeriod = 1;
// 上次更新脚本仓库时间
[ObservableProperty]
private DateTime _lastUpdateScriptRepoTime = DateTime.MinValue;
// 脚本仓库按钮红点是否展示
[ObservableProperty]
private bool _scriptRepoHintDotVisible = false;
// 已订阅的脚本路径列表
[ObservableProperty]
private List<string> _subscribedScriptPaths = [];
}
@@ -23,7 +23,7 @@ public class PaddleOcrService : IOcrService
public PaddleOcrService()
{
var path = Global.Absolute("Assets\\Model\\PaddleOcr");
var path = Global.Absolute(@"Assets\Model\PaddleOcr");
var localDetModel = DetectionModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_det"), ModelVersion.V4);
var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
@@ -0,0 +1,55 @@
using System;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Model.Area;
using Compunet.YoloV8;
using OpenCvSharp;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Text.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX;
public class BgiYoloV8Predictor(string modelRelativePath) : IDisposable
{
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(modelRelativePath))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
public YoloV8Predictor Predictor => _predictor;
/// <summary>
/// 检测
/// </summary>
/// <param name="region">图像</param>
/// <returns>类别-矩形框</returns>
public Dictionary<string, List<Rect>> Detect(ImageRegion region)
{
using var memoryStream = new MemoryStream();
region.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
var result = _predictor.Detect(memoryStream);
var dict = new Dictionary<string, List<Rect>>();
foreach (var box in result.Boxes)
{
if (!dict.ContainsKey(box.Class.Name))
{
dict[box.Class.Name] = [new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height)];
}
else
{
dict[box.Class.Name].Add(new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height));
}
}
Debug.WriteLine("YOLOv8识别结果:" + JsonSerializer.Serialize(dict));
return dict;
}
public void Dispose()
{
_predictor.Dispose();
}
}
@@ -23,12 +23,12 @@ public class PickTextInference : ITextInference
public PickTextInference()
{
var modelPath = Global.Absolute("Assets\\Model\\Yap\\model_training.onnx");
var modelPath = Global.Absolute(@"Assets\Model\Yap\model_training.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("Yap模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, BgiSessionOption.Instance.Options);
var wordJsonPath = Global.Absolute("Assets\\Model\\Yap\\index_2_word.json");
var wordJsonPath = Global.Absolute(@"Assets\Model\Yap\index_2_word.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -15,12 +15,12 @@ public class Predictor
public Predictor()
{
var options = new SessionOptions();
var modelPath = Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx");
var modelPath = Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("自动钓鱼模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, options);
var wordJsonPath = Global.Absolute("Assets\\Model\\Fish\\label.json");
var wordJsonPath = Global.Absolute(@"Assets\Model\Fish\label.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("自动钓鱼模型分类文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -51,6 +51,11 @@ public class KeyMouseMacroPlayer
var startTime = DateTime.UtcNow;
foreach (var e in macroEvents)
{
if (ct.IsCancellationRequested)
{
return;
}
var timeToWait = (int)(e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds);
if (timeToWait < 0)
{
@@ -9,6 +9,15 @@ public class KeyMouseScriptInfo
public string Description { get; set; } = string.Empty;
public string? Author { get; set; }
public string? Version { get; set; }
/// <summary>
/// 制作时 BetterGI 的版本,用于兼容性检查
/// </summary>
public string? BgiVersion { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
@@ -1,19 +1,14 @@
using System.Threading.Tasks;
using System.Text.Json;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
internal class AutoPathing(string rootPath)
public class AutoPathingScript(string rootPath)
{
public async Task Run(string json)
{
var task = JsonSerializer.Deserialize<PathingTask>(json);
if (task == null)
{
return;
}
var task = PathingTask.BuildFromJson(json);
await new PathExecutor(CancellationContext.Instance.Cts).Pathing(task);
}
@@ -1,6 +1,9 @@
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.ViewModel.Pages;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoDomain;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -10,6 +13,11 @@ public class Dispatcher
{
}
/// <summary>
/// 添加实时任务
/// </summary>
/// <param name="timer">实时任务触发器</param>
/// <exception cref="ArgumentNullException"></exception>
public void AddTimer(RealtimeTimer timer)
{
var realtimeTimer = timer;
@@ -24,4 +32,60 @@ public class Dispatcher
TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config);
}
/// <summary>
/// 运行独立任务
/// </summary>
/// <param name="soloTask">
/// 支持的任务名称:
/// - AutoGeniusInvokation: 启动自动七圣召唤任务
/// - AutoWood: 启动自动伐木任务
/// - AutoFight: 启动自动战斗任务
/// - AutoDomain: 启动自动秘境任务
/// </param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public async Task RunTask(SoloTask soloTask)
{
if (soloTask == null)
{
throw new ArgumentNullException(nameof(soloTask), "独立任务对象不能为空");
}
var taskSettingsPageViewModel = App.GetService<TaskSettingsPageViewModel>();
if (taskSettingsPageViewModel == null)
{
throw new ArgumentNullException(nameof(taskSettingsPageViewModel), "内部视图模型对象为空");
}
// 根据名称执行任务
switch (soloTask.Name)
{
case "AutoGeniusInvokation":
taskSettingsPageViewModel.SwitchAutoGeniusInvokationCommand.Execute(null);
break;
case "AutoWood":
taskSettingsPageViewModel.SwitchAutoWoodCommand.Execute(null);
break;
case "AutoFight":
taskSettingsPageViewModel.SwitchAutoFightCommand.Execute(null);
break;
case "AutoDomain":
if (taskSettingsPageViewModel.GetFightStrategy(out var path))
{
return;
}
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(CancellationContext.Instance.Cts);
break;
case "AutoMusicGame":
taskSettingsPageViewModel.SwitchAutoMusicGameCommand.Execute(null);
break;
default:
throw new ArgumentException($"未知的任务名称: {soloTask.Name}", nameof(soloTask.Name));
}
}
}
@@ -1,15 +1,51 @@
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using System.Threading.Tasks;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
{
private RECT captureAreaRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
/// <summary>
/// 游戏宽度
/// </summary>
public int Width => captureAreaRect.Width;
/// <summary>
/// 游戏高度
/// </summary>
public int Height => captureAreaRect.Height;
/// <summary>
/// 游戏窗口大小相比1080P的缩放比例
/// </summary>
public double ScaleTo1080PRatio { get; } = TaskContext.Instance().SystemInfo.ScaleTo1080PRatio;
/// <summary>
/// 系统屏幕的DPI缩放比例
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(double x, double y)
{
await new TpTask(CancellationContext.Instance.Cts).Tp(x, y);
}
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(string x, string y)
{
double.TryParse(x, out var dx);
@@ -1,4 +1,11 @@
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -8,4 +15,138 @@ public class GlobalMethod
{
await Task.Delay(millisecondsTimeout, CancellationContext.Instance.Cts.Token);
}
#region 键盘操作
public static void KeyDown(string key)
{
Simulation.SendInput.Keyboard.KeyDown(ToVk(key));
}
public static void KeyUp(string key)
{
Simulation.SendInput.Keyboard.KeyUp(ToVk(key));
}
public static void KeyPress(string key)
{
Simulation.SendInput.Keyboard.KeyPress(ToVk(key));
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
#endregion 键盘操作
#region 鼠标操作
private static int _gameWidth = 1920;
private static int _gameHeight = 1080;
private static double _dpi = 1;
public static void SetGameMetrics(int width, int height, double dpi = 1)
{
// 必须16:9 的分辨率
if (width * 9 != height * 16)
{
throw new ArgumentException("游戏分辨率必须是16:9的分辨率");
}
_gameWidth = width;
_gameHeight = height;
_dpi = dpi;
}
public static void MoveMouseBy(int x, int y)
{
var realDpi = TaskContext.Instance().DpiScale;
x = (int)(x * realDpi / _dpi);
y = (int)(y * realDpi / _dpi);
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
}
public static void MoveMouseTo(int x, int y)
{
if (x < 0 || x > _gameWidth || y < 0 || y > _gameHeight)
{
throw new ArgumentException("鼠标坐标超出游戏窗口范围");
}
GameCaptureRegion.GameRegionMove((size, s2) =>
{
var scale = 1920.0 / _gameWidth;
return (x * scale * s2, y * scale * s2);
});
}
public static void Click(int x, int y)
{
MoveMouseTo(x, y);
Simulation.SendInput.Mouse.LeftButtonClick();
}
public static void LeftButtonClick()
{
Simulation.SendInput.Mouse.LeftButtonClick();
}
public static void LeftButtonDown()
{
Simulation.SendInput.Mouse.LeftButtonDown();
}
public static void LeftButtonUp()
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
public static void RightButtonClick()
{
Simulation.SendInput.Mouse.RightButtonClick();
}
public static void RightButtonDown()
{
Simulation.SendInput.Mouse.RightButtonDown();
}
public static void RightButtonUp()
{
Simulation.SendInput.Mouse.RightButtonUp();
}
public static void MiddleButtonClick()
{
Simulation.SendInput.Mouse.MiddleButtonClick();
}
public static void MiddleButtonDown()
{
Simulation.SendInput.Mouse.MiddleButtonDown();
}
public static void MiddleButtonUp()
{
Simulation.SendInput.Mouse.MiddleButtonUp();
}
#endregion 鼠标操作
#region 识图操作
public static ImageRegion CaptureGameRegion()
{
return TaskControl.CaptureToRectArea();
}
#endregion 识图操作
}
@@ -1,7 +1,10 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
using BetterGenshinImpact.Helpers;
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 实时任务计时器
/// 实时任务触发器
/// </summary>
public class RealtimeTimer
{
@@ -29,4 +32,13 @@ public class RealtimeTimer
{
Name = name;
}
public RealtimeTimer(string name, dynamic config)
{
Name = name;
if (Name == "AutoPick")
{
Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
}
}
}
@@ -0,0 +1,31 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 独立任务
/// </summary>
public class SoloTask
{
/// <summary>
/// 独立任务名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 独立任务配置
/// </summary>
public object? Config;
public SoloTask(string name)
{
Name = name;
}
public SoloTask(string name, dynamic config)
{
Name = name;
// if (Name == "AutoPick")
// {
// Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
// }
}
}
@@ -0,0 +1,44 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Helpers;
using System;
using BetterGenshinImpact.GameTask;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence.Simulator;
public class PostMessage
{
private readonly PostMessageSimulator _postMessageSimulator = TaskContext.Instance().PostMessageSimulator;
public void KeyDown(string key)
{
_postMessageSimulator.KeyDownBackground(ToVk(key));
}
public void KeyUp(string key)
{
_postMessageSimulator.KeyUpBackground(ToVk(key));
}
public void KeyPress(string key)
{
_postMessageSimulator.KeyPressBackground(ToVk(key));
}
public void Click()
{
_postMessageSimulator.LeftButtonClick();
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
}
@@ -1,31 +1,51 @@
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Reflection;
using System.Threading.Tasks;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
namespace BetterGenshinImpact.Core.Script;
public class EngineExtend
{
/// <summary>
/// !!! 注意:这个方法会添加一些全局方法和对象,不要随便添加,以免安全风险!!!
/// </summary>
/// <param name="engine"></param>
/// <param name="workDir"></param>
/// <param name="searchPaths"></param>
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null)
{
// engine.AddHostObject("xHost", new ExtendedHostFunctions()); // 有越权的安全风险
// 添加我的自定义实例化对象
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("autoPathing", new AutoPathing(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
// 实时任务调度器
// 任务调度器
engine.AddHostObject("dispatcher", new Dispatcher());
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
engine.AddHostType("SoloTask", typeof(SoloTask));
// PostMessage 作为类型实例化
engine.AddHostType("PostMessage", typeof(Dependence.Simulator.PostMessage));
// 直接添加方法
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
#pragma warning restore CS8974 // Converting method group to non-delegate type
AddAllGlobalMethod(engine);
// 识图模块相关
engine.AddHostType("Mat", typeof(Mat));
engine.AddHostType("RecognitionObject", typeof(RecognitionObject));
engine.AddHostType("DesktopRegion", typeof(DesktopRegion));
engine.AddHostType("GameCaptureRegion", typeof(GameCaptureRegion));
engine.AddHostType("ImageRegion", typeof(ImageRegion));
engine.AddHostType("Region", typeof(Region));
// 添加C#的类型
engine.AddHostType(typeof(Task));
@@ -39,4 +59,38 @@ public class EngineExtend
engine.DocumentSettings.SearchPath = string.Join(';', searchPaths);
}
}
public static void AddAllGlobalMethod(IScriptEngine engine)
{
// // 获取GlobalMethod类的所有静态方法
// var methods = typeof(GlobalMethod).GetMethods(BindingFlags.Static | BindingFlags.Public);
//
// foreach (var method in methods)
// {
// // 使用方法名首字母小写作为HostObject的名称
// var methodName = char.ToLowerInvariant(method.Name[0]) + method.Name[1..];
// engine.AddHostObject(methodName, method);
// }
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
engine.AddHostObject("keyDown", GlobalMethod.KeyDown);
engine.AddHostObject("keyUp", GlobalMethod.KeyUp);
engine.AddHostObject("keyPress", GlobalMethod.KeyPress);
engine.AddHostObject("setGameMetrics", GlobalMethod.SetGameMetrics);
engine.AddHostObject("moveMouseBy", GlobalMethod.MoveMouseBy);
engine.AddHostObject("moveMouseTo", GlobalMethod.MoveMouseTo);
engine.AddHostObject("click", GlobalMethod.Click);
engine.AddHostObject("leftButtonClick", GlobalMethod.LeftButtonClick);
engine.AddHostObject("leftButtonDown", GlobalMethod.LeftButtonDown);
engine.AddHostObject("leftButtonUp", GlobalMethod.LeftButtonUp);
engine.AddHostObject("rightButtonClick", GlobalMethod.RightButtonClick);
engine.AddHostObject("rightButtonDown", GlobalMethod.RightButtonDown);
engine.AddHostObject("rightButtonUp", GlobalMethod.RightButtonUp);
engine.AddHostObject("middleButtonClick", GlobalMethod.MiddleButtonClick);
engine.AddHostObject("middleButtonDown", GlobalMethod.MiddleButtonDown);
engine.AddHostObject("middleButtonUp", GlobalMethod.MiddleButtonUp);
engine.AddHostObject("captureGameRegion", GlobalMethod.CaptureGameRegion);
#pragma warning restore CS8974 // Converting method group to non-delegate type
}
}
@@ -34,6 +34,6 @@ public partial class ScriptGroup : ObservableObject
public static ScriptGroup FromJson(string json)
{
return JsonSerializer.Deserialize<ScriptGroup>(json, ConfigService.JsonOptions) ?? throw new Exception("解析配置组JSON配置失败");
return Newtonsoft.Json.JsonConvert.DeserializeObject<ScriptGroup>(json) ?? throw new Exception("解析配置组JSON配置失败");
}
}
@@ -20,8 +20,18 @@ public partial class ScriptGroupProject : ObservableObject
[ObservableProperty]
private int _index;
/// <summary>
/// 理论上是文件名
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 理论上是当前类型脚本根目录到脚本文件所在目录的相对路径
/// 但是:
/// 1. JS 脚本的文件名是内部的名称,文件夹名脚本所在文件夹,这个也是唯一标识
/// 2. KeyMouse 脚本的文件名和文件夹名相同,文件夹名暂时无意义
/// 3. Pathing 文件名就是实际脚本的文件名,文件夹名是脚本所在的相对目录
/// </summary>
public string FolderName { get; set; } = string.Empty;
[ObservableProperty]
@@ -14,6 +14,7 @@ public class Manifest
public int ManifestVersion { get; set; } = 1;
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string? BgiVersion { get; set; }
public string Description { get; set; } = string.Empty;
public List<Author> Authors { get; set; } = [];
public string Main { get; set; } = string.Empty;
@@ -0,0 +1,423 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.WebView;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers.Http;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Controls.Webview;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script;
public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
{
private readonly ILogger<ScriptRepoUpdater> _logger = App.GetLogger<ScriptRepoUpdater>();
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) };
// 仓储位置
public static readonly string ReposPath = Global.Absolute("Repos");
// 仓储临时目录 用于下载与解压
public static readonly string ReposTempPath = Path.Combine(ReposPath, "Temp");
// 中央仓库信息地址
public static readonly string CenterRepoInfoUrl = "https://raw.githubusercontent.com/babalae/bettergi-scripts-list/refs/heads/main/repo.json";
// 中央仓库解压后文件夹名
public static readonly string CenterRepoUnzipName = "bettergi-scripts-list-main";
public static readonly string CenterRepoPath = Path.Combine(ReposPath, CenterRepoUnzipName);
public static readonly Dictionary<string, string> PathMapper = new Dictionary<string, string>
{
{ "pathing", Global.Absolute("User\\AutoPathing") },
{ "js", Global.Absolute("User\\JsScript") },
{ "combat", Global.Absolute("User\\AutoFight") },
{ "tcg", Global.Absolute("User\\AutoGeniusInvokation") },
};
private WebpageWindow? _webWindow;
public void AutoUpdate()
{
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
// 判断更新周期是否到达
if (DateTime.Now - scriptConfig.LastUpdateScriptRepoTime >= TimeSpan.FromDays(scriptConfig.AutoUpdateScriptRepoPeriod))
{
// 更新仓库
Task.Run(async () =>
{
try
{
var (repoPath, updated) = await UpdateCenterRepo();
Debug.WriteLine($"脚本仓库更新完成,路径:{repoPath}");
scriptConfig.LastUpdateScriptRepoTime = DateTime.Now;
if (updated)
{
scriptConfig.ScriptRepoHintDotVisible = true;
}
}
catch (Exception e)
{
_logger.LogDebug(e, $"脚本仓库更新失败:{e.Message}");
}
});
}
}
public async Task<(string, bool)> UpdateCenterRepo()
{
// 测速并获取信息
var res = await ProxySpeedTester.GetFastestProxyAsync(CenterRepoInfoUrl);
// 解析信息
var fastProxyUrl = res.Item1;
var jsonString = res.Item2;
var (time, url, file) = ParseJson(jsonString);
var updated = false;
// 检查仓库是否存在,不存在则下载
if (!Directory.Exists(CenterRepoPath))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url));
updated = true;
}
// 搜索本地的 repo.json
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, file, SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
var (time2, url2, file2) = ParseJson(await File.ReadAllTextAsync(localRepoJsonPath));
// 检查是否需要更新
if (long.Parse(time) > long.Parse(time2))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url2));
updated = true;
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return (folderPath, updated);
}
public string FindCenterRepoPath()
{
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return folderPath;
}
private (string time, string url, string file) ParseJson(string jsonString)
{
var json = JObject.Parse(jsonString);
var time = json["time"]?.ToString();
var url = json["url"]?.ToString();
var file = json["file"]?.ToString();
// 检查是否有空值
if (time is null || url is null || file is null)
{
throw new Exception("repo.json 解析失败");
}
return (time, url, file);
}
public async Task DownloadRepoAndUnzip(string url)
{
// 下载
var res = await _httpClient.GetAsync(url);
if (!res.IsSuccessStatusCode)
{
throw new Exception("下载失败");
}
var bytes = await res.Content.ReadAsByteArrayAsync();
// 获取文件名
var contentDisposition = res.Content.Headers.ContentDisposition;
var fileName = contentDisposition is { FileName: not null } ? contentDisposition.FileName.Trim('"') : "temp.zip";
// 创建临时目录
if (!Directory.Exists(ReposTempPath))
{
Directory.CreateDirectory(ReposTempPath);
}
// 保存下载的文件
var zipPath = Path.Combine(ReposTempPath, fileName);
await File.WriteAllBytesAsync(zipPath, bytes);
// 删除旧文件夹
if (Directory.Exists(CenterRepoPath))
{
Directory.Delete(CenterRepoPath, true);
}
// 使用 System.IO.Compression 解压
ZipFile.ExtractToDirectory(zipPath, ReposPath, true);
}
public async Task ImportScriptFromClipboard()
{
// 获取剪切板内容
if (Clipboard.ContainsText())
{
string clipboardText = Clipboard.GetText();
await ImportScriptFromUri(clipboardText, true);
}
}
public async Task ImportScriptFromUri(string uri, bool formClipboard)
{
// 检查剪切板内容是否符合特定的URL格式
if (!string.IsNullOrEmpty(uri) && uri.Trim().ToLower().StartsWith("bettergi://script?import="))
{
Debug.WriteLine($"脚本订购内容:{uri}");
// 执行相关操作
var pathJson = ParseUri(uri);
if (!string.IsNullOrEmpty(pathJson))
{
var uiMessageBox = new Wpf.Ui.Controls.MessageBox
{
Title = "脚本订阅",
Content = $"检测到{(formClipboard ? "剪切板上存在" : "")}脚本订阅链接,解析后需要导入的脚本为:{pathJson}。\n是否导入并覆盖此文件或者文件夹下的脚本?",
CloseButtonText = "关闭",
PrimaryButtonText = "确认导入",
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Owner = Application.Current.MainWindow,
};
var result = await uiMessageBox.ShowDialogAsync();
if (result == Wpf.Ui.Controls.MessageBoxResult.Primary)
{
await ImportScriptFromPathJson(pathJson);
}
}
if (formClipboard)
{
// 清空剪切板内容
Clipboard.Clear();
}
}
}
private string? ParseUri(string uriString)
{
var uri = new Uri(uriString);
// 获取 query 参数
string query = uri.Query;
Debug.WriteLine($"Query: {query}");
// 解析 query 参数
var queryParams = System.Web.HttpUtility.ParseQueryString(query);
var import = queryParams["import"];
if (string.IsNullOrEmpty(import))
{
Debug.WriteLine("未找到 import 参数");
return null;
}
// Base64 解码后再使用url解码
byte[] data = Convert.FromBase64String(import);
return System.Web.HttpUtility.UrlDecode(System.Text.Encoding.UTF8.GetString(data));
}
public async Task ImportScriptFromPathJson(string pathJson)
{
var paths = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(pathJson);
if (paths is null || paths.Count == 0)
{
Toast.Warning("订阅脚本路径为空");
return;
}
// 保存订阅信息
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
scriptConfig.SubscribedScriptPaths.AddRange(paths);
Toast.Information("获取最新仓库信息中...");
// 更新仓库
var (repoPath, _) = await Task.Run(UpdateCenterRepo);
// // 收集将被覆盖的文件和文件夹
// var filesToOverwrite = new List<string>();
// foreach (var path in paths)
// {
// var first = GetFirstFolder(path);
// if (PathMapper.TryGetValue(first, out var userPath))
// {
// var scriptPath = Path.Combine(repoPath, path);
// var destPath = Path.Combine(userPath, path.Replace(first, ""));
// if (Directory.Exists(scriptPath))
// {
// if (Directory.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// else if (File.Exists(scriptPath))
// {
// if (File.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// }
// else
// {
// Toast.Warning($"未知的脚本路径:{path}");
// }
// }
//
// // 提示用户确认
// if (filesToOverwrite.Count > 0)
// {
// var message = "以下文件和文件夹将被覆盖:\n" + string.Join("\n", filesToOverwrite) + "\n是否覆盖所有文件和文件夹?";
// var uiMessageBox = new Wpf.Ui.Controls.MessageBox
// {
// Title = "确认覆盖",
// Content = message,
// CloseButtonText = "取消",
// PrimaryButtonText = "确认覆盖",
// WindowStartupLocation = WindowStartupLocation.CenterOwner,
// Owner = Application.Current.MainWindow,
// };
//
// var result = await uiMessageBox.ShowDialogAsync();
// if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
// {
// return;
// }
// }
// 拷贝文件
foreach (var path in paths)
{
var (first, remainingPath) = GetFirstFolderAndRemainingPath(path);
if (PathMapper.TryGetValue(first, out var userPath))
{
var scriptPath = Path.Combine(repoPath, path);
var destPath = Path.Combine(userPath, remainingPath);
if (Directory.Exists(scriptPath))
{
if (Directory.Exists(destPath))
{
Directory.Delete(destPath, true);
}
CopyDirectory(scriptPath, destPath);
}
else if (File.Exists(scriptPath))
{
if (File.Exists(destPath))
{
File.Delete(destPath);
}
File.Copy(scriptPath, destPath, true);
}
Toast.Success("脚本订阅链接导入完成");
}
else
{
Toast.Warning($"未知的脚本路径:{path}");
}
}
}
private void CopyDirectory(string sourceDir, string destDir)
{
// 创建目标目录
Directory.CreateDirectory(destDir);
// 拷贝文件
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
}
// 拷贝子目录
foreach (var dir in Directory.GetDirectories(sourceDir))
{
var destSubDir = Path.Combine(destDir, Path.GetFileName(dir));
CopyDirectory(dir, destSubDir);
}
}
private static (string firstFolder, string remainingPath) GetFirstFolderAndRemainingPath(string path)
{
// 检查路径是否为空或仅包含部分字符
if (string.IsNullOrEmpty(path))
{
return (string.Empty, string.Empty);
}
// 使用路径分隔符分割路径
string[] parts = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
// 返回第一个文件夹和剩余路径
return parts.Length > 0 ? (parts[0], string.Join(Path.DirectorySeparatorChar, parts.Skip(1))) : (string.Empty, string.Empty);
}
public void OpenLocalRepoInWebView()
{
if (_webWindow is not { IsVisible: true })
{
_webWindow = new WebpageWindow
{
Title = "enshin Copilot Scripts | BetterGI 脚本本地中央仓库",
Width = 1366,
Height = 768,
// Owner = Application.Current.MainWindow,
WindowState = WindowState.Maximized
};
_webWindow.Closed += (s, e) => _webWindow = null;
_webWindow.Panel!.DownloadFolderPath = MapPathingViewModel.PathJsonPath;
_webWindow.NavigateToFile(Global.Absolute(@"Assets\Web\ScriptRepo\index.html"));
_webWindow.Panel!.OnWebViewInitializedAction = () => _webWindow.Panel!.WebView.CoreWebView2.AddHostObjectToScript("repoWebBridge", new RepoWebBridge());
_webWindow.Show();
}
else
{
_webWindow.Activate();
}
}
}
@@ -0,0 +1,52 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Core.Script.WebView;
/// <summary>
/// 给 WebView 提供的桥接类
/// 用于调用 C# 方法
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class RepoWebBridge
{
public string GetRepoJson()
{
try
{
var localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
_ = ScriptRepoUpdater.Instance.UpdateCenterRepo().ConfigureAwait(false);
localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
}
var json = File.ReadAllText(localRepoJsonPath);
return json;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "获取仓库信息失败!");
return "";
}
}
public void ImportUri(string url)
{
try
{
ScriptRepoUpdater.Instance.ImportScriptFromUri(url, false).ConfigureAwait(false);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "订阅脚本链接失败!");
}
}
}
@@ -6,7 +6,6 @@ namespace BetterGenshinImpact.GameTask.AutoDomain;
[Serializable]
public partial class AutoDomainConfig : ObservableObject
{
/// <summary>
/// 战斗结束后延迟几秒再开始寻找石化古树,秒
/// </summary>
@@ -26,4 +25,10 @@ public partial class AutoDomainConfig : ObservableObject
/// 寻找古树时,短距离移动的次数
/// </summary>
[ObservableProperty] private int _leftRightMoveTimes = 3;
}
/// <summary>
/// 自动吃药
/// </summary>
[ObservableProperty]
private bool _autoEat = false;
}
@@ -9,7 +9,7 @@ public class AutoDomainParam : BaseTaskParam
public string CombatStrategyPath { get; set; }
public AutoDomainParam(CancellationTokenSource cts, int domainRoundNum, string path) : base(cts)
public AutoDomainParam(int domainRoundNum, string path)
{
DomainRoundNum = domainRoundNum;
if (domainRoundNum == 0)
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
@@ -10,11 +11,9 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoPick.Assets;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Compunet.YoloV8;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
@@ -25,12 +24,14 @@ using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.Gdi32;
using static Vanara.PInvoke.User32;
namespace BetterGenshinImpact.GameTask.AutoDomain;
public class AutoDomainTask
public class AutoDomainTask : ISoloTask
{
private readonly AutoDomainParam _taskParam;
@@ -42,13 +43,15 @@ public class AutoDomainTask
private readonly CombatScriptBag _combatScriptBag;
private CancellationTokenSource? _cts;
public AutoDomainTask(AutoDomainParam taskParam)
{
_taskParam = taskParam;
_simulator = AutoFightContext.Instance.Simulator;
_predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"))
.UseOnnxModel(Global.Absolute(@"Assets\Model\Domain\bgi_tree.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
@@ -57,96 +60,64 @@ public class AutoDomainTask
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
}
public async void Start()
public async Task Start(CancellationTokenSource cts)
{
var hasLock = false;
try
_cts = cts;
AutoFightAssets.DestroyInstance();
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build()); // TODO: 通知后续需要删除迁移
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
// 前置进入秘境
EnterDomain();
for (var i = 0; i < _taskParam.DomainRoundNum; i++)
{
AutoFightAssets.DestroyInstance();
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
// 0. 关闭秘境提示
Logger.LogDebug("0. 关闭秘境提示");
CloseDomainTip();
// 队伍没初始化成功则重试
RetryTeamInit(combatScenes);
// 0. 切换到第一个角色
var combatCommands = FindCombatScriptAndSwitchAvatar(combatScenes);
// 1. 走到钥匙处启动
Logger.LogInformation("自动秘境:{Text}", "1. 走到钥匙处启动");
await WalkToPressF();
// 2. 执行战斗(战斗线程、视角线程、检测战斗完成线程)
Logger.LogInformation("自动秘境:{Text}", "2. 执行战斗策略");
await StartFight(combatScenes, combatCommands);
EndFightWait();
// 3. 寻找石化古树 并左右移动直到石化古树位于屏幕中心
Logger.LogInformation("自动秘境:{Text}", "3. 寻找石化古树");
await FindPetrifiedTree();
// 4. 走到石化古树处
Logger.LogInformation("自动秘境:{Text}", "4. 走到石化古树处");
await WalkToPressF();
// 5. 快速领取奖励并判断是否有下一轮
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
{
Logger.LogError("启动自动秘境功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build());
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
// 前置进入秘境
EnterDomain();
for (var i = 0; i < _taskParam.DomainRoundNum; i++)
{
// 0. 关闭秘境提示
Logger.LogDebug("0. 关闭秘境提示");
CloseDomainTip();
// 队伍没初始化成功则重试
RetryTeamInit(combatScenes);
// 0. 切换到第一个角色
var combatCommands = FindCombatScriptAndSwitchAvatar(combatScenes);
// 1. 走到钥匙处启动
Logger.LogInformation("自动秘境:{Text}", "1. 走到钥匙处启动");
await WalkToPressF();
// 2. 执行战斗(战斗线程、视角线程、检测战斗完成线程)
Logger.LogInformation("自动秘境:{Text}", "2. 执行战斗策略");
await StartFight(combatScenes, combatCommands);
EndFightWait();
// 3. 寻找石化古树 并左右移动直到石化古树位于屏幕中心
Logger.LogInformation("自动秘境:{Text}", "3. 寻找石化古树");
await FindPetrifiedTree();
// 4. 走到石化古树处
Logger.LogInformation("自动秘境:{Text}", "4. 走到石化古树处");
await WalkToPressF();
// 5. 快速领取奖励并判断是否有下一轮
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
if (i == _taskParam.DomainRoundNum - 1)
{
if (i == _taskParam.DomainRoundNum - 1)
{
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
}
else
{
Logger.LogInformation("体力已经耗尽,结束自动秘境");
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Success().Build());
break;
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Progress().Build());
}
}
catch (NormalEndException e)
{
Logger.LogInformation("自动秘境中断:" + e.Message);
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Cancelled().Build());
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Failure().Build());
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
TaskSettingsPageViewModel.SetSwitchAutoDomainButtonText(false);
Logger.LogInformation("→ {Text}", "自动秘境结束");
if (hasLock)
{
TaskSemaphore.Release();
else
{
Logger.LogInformation("体力已经耗尽,结束自动秘境");
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Success().Build());
break;
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Progress().Build());
}
}
@@ -155,16 +126,12 @@ public class AutoDomainTask
LogScreenResolution();
if (_taskParam.DomainRoundNum == 9999)
{
Logger.LogInformation("→ {Text} 用尽所有体力后结束", "自动秘境,启动!");
Logger.LogInformation("→ {Text} 用尽所有体力后结束", "自动秘境,");
}
else
{
Logger.LogInformation("→ {Text} 设置总次数:{Cnt}", "自动秘境,启动!", _taskParam.DomainRoundNum);
Logger.LogInformation("→ {Text} 设置总次数:{Cnt}", "自动秘境,", _taskParam.DomainRoundNum);
}
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
}
private void LogScreenResolution()
@@ -202,7 +169,7 @@ public class AutoDomainTask
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
Sleep(5000, _taskParam.Cts);
Sleep(5000, _cts);
}
int retryTimes = 0, clickCount = 0;
@@ -216,11 +183,11 @@ public class AutoDomainTask
clickCount++;
}
Sleep(1500, _taskParam.Cts);
Sleep(1500, _cts);
}
// 载入动画
Sleep(3000, _taskParam.Cts);
Sleep(3000, _cts);
}
private void CloseDomainTip()
@@ -233,16 +200,16 @@ public class AutoDomainTask
using var cactRectArea = CaptureToRectArea().Find(AutoFightContext.Instance.FightAssets.ClickAnyCloseTipRa);
if (!cactRectArea.IsEmpty())
{
Sleep(1000, _taskParam.Cts);
Sleep(1000, _cts);
cactRectArea.Click();
break;
}
// todo 添加小地图角标位置检测 防止有人手点了
Sleep(1000, _taskParam.Cts);
Sleep(1000, _cts);
}
Sleep(1500, _taskParam.Cts);
Sleep(1500, _cts);
}
private List<CombatCommand> FindCombatScriptAndSwitchAvatar(CombatScenes combatScenes)
@@ -259,7 +226,7 @@ public class AutoDomainTask
/// </summary>
private async Task WalkToPressF()
{
if (_taskParam.Cts.Token.IsCancellationRequested)
if (_cts.Token.IsCancellationRequested)
{
return;
}
@@ -276,12 +243,12 @@ public class AutoDomainTask
try
{
while (!_taskParam.Cts.Token.IsCancellationRequested)
while (!_cts.Token.IsCancellationRequested)
{
using var fRectArea = Common.TaskControl.CaptureToRectArea().Find(AutoPickAssets.Instance.FRo);
if (fRectArea.IsEmpty())
{
Sleep(100, _taskParam.Cts);
Sleep(100, _cts);
}
else
{
@@ -306,7 +273,7 @@ public class AutoDomainTask
private Task StartFight(CombatScenes combatScenes, List<CombatCommand> combatCommands)
{
CancellationTokenSource cts = new();
_taskParam.Cts.Token.Register(cts.Cancel);
_cts.Token.Register(cts.Cancel);
combatScenes.BeforeTask(cts);
// 战斗操作
var combatTask = new Task(() =>
@@ -337,20 +304,19 @@ public class AutoDomainTask
}
}, cts.Token);
// 视角操作
// 对局结束检测
var domainEndTask = DomainEndDetectionTask(cts);
// 自动吃药
var autoEatRecoveryHpTask = AutoEatRecoveryHpTask(cts);
combatTask.Start();
domainEndTask.Start();
return Task.WhenAll(combatTask, domainEndTask);
autoEatRecoveryHpTask.Start();
return Task.WhenAll(combatTask, domainEndTask, autoEatRecoveryHpTask);
}
private void EndFightWait()
{
if (_taskParam.Cts.Token.IsCancellationRequested)
if (_cts.Token.IsCancellationRequested)
{
return;
}
@@ -359,7 +325,7 @@ public class AutoDomainTask
if (s > 0)
{
Logger.LogInformation("战斗结束后等待 {Second} 秒", s);
Sleep((int)(s * 1000), _taskParam.Cts);
Sleep((int)(s * 1000), _cts);
}
}
@@ -368,19 +334,25 @@ public class AutoDomainTask
/// </summary>
private Task DomainEndDetectionTask(CancellationTokenSource cts)
{
return new Task(() =>
return new Task(async () =>
{
while (!_taskParam.Cts.Token.IsCancellationRequested)
try
{
if (IsDomainEnd())
while (!_cts.Token.IsCancellationRequested)
{
cts.Cancel();
break;
}
if (IsDomainEnd())
{
await cts.CancelAsync();
break;
}
Sleep(1000);
await Delay(1000, cts);
}
}
});
catch
{
}
}, cts.Token);
}
private bool IsDomainEnd()
@@ -406,16 +378,74 @@ public class AutoDomainTask
return false;
}
private Task AutoEatRecoveryHpTask(CancellationTokenSource cts)
{
return new Task(async () =>
{
if (!_config.AutoEat)
{
return;
}
if (!IsTakeFood())
{
Logger.LogInformation("未装备 “{Tool}”,不启用红血自动吃药功能", "便携营养袋");
return;
}
try
{
while (!_cts.Token.IsCancellationRequested)
{
if (IsLowHealth())
{
// 模拟按键 "Z"
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_Z);
Logger.LogInformation("检测到红血,按Z吃药");
// TODO 吃饱了会一直吃
}
await Delay(500, cts);
}
}
catch
{
}
}, cts.Token);
}
private bool IsLowHealth()
{
// 获取图像
using var ra = CaptureToRectArea();
// 获取 (808, 1010) 位置的像素颜色
var pixelColor = ra.SrcMat.At<Vec3b>(1010, 808);
// 判断颜色是否是 (255, 90, 90)
return pixelColor is { Item2: 255, Item1: 90, Item0: 90 };
}
private bool IsTakeFood()
{
// 获取图像
using var ra = CaptureToRectArea();
// 识别道具图标下是否是数字
var s = TaskContext.Instance().SystemInfo.AssetScale;
var countArea = ra.DeriveCrop(1800 * s, 845 * s, 40 * s, 20 * s);
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
return int.TryParse(count, out _);
}
/// <summary>
/// 旋转视角后寻找石化古树
/// </summary>
private Task FindPetrifiedTree()
{
CancellationTokenSource treeCts = new();
_taskParam.Cts.Token.Register(treeCts.Cancel);
_cts.Token.Register(treeCts.Cancel);
// 中键回正视角
Simulation.SendInput.Mouse.MiddleButtonClick();
Sleep(900, _taskParam.Cts);
Sleep(900, _cts);
// 左右移动直到石化古树位于屏幕中心任务
var moveAvatarTask = MoveAvatarHorizontallyTask(treeCts);
@@ -437,7 +467,7 @@ public class AutoDomainTask
var noDetectCount = 0;
var prevKey = VK.VK_A;
var backwardsAndForwardsCount = 0;
while (!_taskParam.Cts.Token.IsCancellationRequested)
while (!_cts.Token.IsCancellationRequested)
{
var treeRect = DetectTree(CaptureToRectArea());
if (treeRect != Rect.Empty)
@@ -520,7 +550,7 @@ public class AutoDomainTask
else
{
_simulator.KeyPress(VK.VK_W, 60);
Sleep(500, _taskParam.Cts);
Sleep(500, _cts);
treeCts.Cancel();
break;
}
@@ -565,12 +595,12 @@ public class AutoDomainTask
{
// 左右移动5次说明已经在树中心了
_simulator.KeyPress(VK.VK_W, 60);
Sleep(500, _taskParam.Cts);
Sleep(500, _cts);
treeCts.Cancel();
break;
}
Sleep(60, _taskParam.Cts);
Sleep(60, _cts);
}
VisionContext.Instance().DrawContent.ClearAll();
@@ -618,7 +648,7 @@ public class AutoDomainTask
continuousCount++;
}
if (angle < 180)
if (angle <= 180)
{
// 左移视角
var moveAngle = angle;
@@ -671,7 +701,7 @@ public class AutoDomainTask
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
{
// 等待窗口弹出
Sleep(1500, _taskParam.Cts);
Sleep(1500, _cts);
// 优先使用浓缩树脂
var retryTimes = 0;
@@ -690,22 +720,22 @@ public class AutoDomainTask
useCondensedResinRa.Click();
// 点两下 #224 #218
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
Sleep(400, _taskParam.Cts);
Sleep(400, _cts);
useCondensedResinRa.Click();
break;
}
Sleep(800, _taskParam.Cts);
Sleep(800, _cts);
}
Sleep(1000, _taskParam.Cts);
Sleep(1000, _cts);
var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
for (var i = 0; i < 30; i++)
{
// 跳过领取动画
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
Sleep(200, _taskParam.Cts);
Sleep(200, _cts);
GameCaptureRegion.GameRegionClick((size, scale) => (size.Width - 140 * scale, 53 * scale));
// 优先点击继续
@@ -749,7 +779,7 @@ public class AutoDomainTask
}
}
Sleep(300, _taskParam.Cts);
Sleep(300, _cts);
}
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
@@ -800,7 +800,7 @@
"weapon": "13"
},
{
"alias": [ "基尼奇", "Kinich", "基哥" ],
"alias": [ "基尼奇", "Kinich", "基哥", "基尼齐" ],
"burstCD": 18.0,
"id": "10000101",
"name": "基尼奇",
@@ -817,5 +817,14 @@
"skillCD": 1.8,
"skillHoldCD": 6.0,
"weapon": "10"
},
{
"alias": [ "希诺宁", "Xilonen", "豹女", "岩大猫", "大岩猫", "岩猫", "岩猫猫", "西诺宁" ],
"burstCD": 15.0,
"id": "10000103",
"name": "希诺宁",
"nameEn": "Xilonen",
"skillCD": 7.0,
"weapon": "1"
}
]
@@ -15,4 +15,16 @@ public partial class AutoFightConfig : ObservableObject
/// 英文逗号分割 强制指定队伍角色
/// </summary>
[ObservableProperty] private string _teamNames = "";
}
/// <summary>
/// 检测战斗结束
/// </summary>
[ObservableProperty]
private bool _fightFinishDetectEnabled = true;
/// <summary>
/// 检测战斗结束
/// </summary>
[ObservableProperty]
private bool _pickDropsAfterFightEnabled = true;
}
@@ -1,14 +1,12 @@
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoFight;
public class AutoFightParam : BaseTaskParam
public class AutoFightParam(string path) : BaseTaskParam
{
public string CombatStrategyPath { get; set; }
public string CombatStrategyPath { get; set; } = path;
public AutoFightParam(CancellationTokenSource cts, string path) : base(cts)
{
CombatStrategyPath = path;
}
public bool FightFinishDetectEnabled { get; set; } = false;
public bool PickDropsAfterFightEnabled { get; set; } = false;
}
@@ -1,107 +1,118 @@
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight;
public class AutoFightTask
public class AutoFightTask : ISoloTask
{
private readonly AutoFightParam _taskParam;
private readonly CombatScriptBag _combatScriptBag;
private CancellationTokenSource? _cts;
private readonly BgiYoloV8Predictor _predictor;
private DateTime _lastFightFlagTime = DateTime.Now; // 战斗标志最近一次出现的时间
public AutoFightTask(AutoFightParam taskParam)
{
_taskParam = taskParam;
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
if (_taskParam.FightFinishDetectEnabled)
{
_predictor = new BgiYoloV8Predictor(@"Assets\Model\World\bgi_world.onnx");
}
}
public async void Start()
public async Task Start(CancellationTokenSource cts)
{
var hasLock = false;
try
_cts = cts;
LogScreenResolution();
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
if (!combatScenes.CheckTeamInitialized())
{
AutoFightAssets.DestroyInstance();
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
throw new Exception("识别队伍角色失败");
}
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
// 新的取消token
var cts2 = new CancellationTokenSource();
cts.Token.Register(cts2.Cancel);
combatScenes.BeforeTask(cts2);
// 战斗操作
var fightTask = Task.Run(() =>
{
try
{
while (!cts2.Token.IsCancellationRequested)
{
// 通用化战斗策略
foreach (var command in combatCommands)
{
command.Execute(combatScenes);
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
}, cts2.Token);
// 战斗结束检测线程
var endTask = Task.Run(async () =>
{
if (!_taskParam.FightFinishDetectEnabled)
{
Logger.LogError("启动自动战斗功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
Init();
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
if (!combatScenes.CheckTeamInitialized())
try
{
throw new Exception("识别队伍角色失败");
}
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
combatScenes.BeforeTask(_taskParam.Cts);
// 战斗操作
await Task.Run(() =>
{
try
while (!cts2.IsCancellationRequested)
{
while (!_taskParam.Cts.Token.IsCancellationRequested)
var finish = await CheckFightFinish();
if (finish)
{
// 通用化战斗策略
foreach (var command in combatCommands)
{
command.Execute(combatScenes);
}
await cts2.CancelAsync();
break;
}
}
catch (NormalEndException)
{
Logger.LogInformation("战斗操作结束");
}
catch (Exception e)
{
Logger.LogWarning(e.Message);
throw;
}
});
}
catch (NormalEndException)
{
Logger.LogInformation("手动中断自动战斗");
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
TaskSettingsPageViewModel.SetSwitchAutoFightButtonText(false);
Logger.LogInformation("→ {Text}", "自动战斗结束");
if (hasLock)
{
TaskSemaphore.Release();
Sleep(1000, cts2);
}
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
}, cts2.Token);
private void Init()
{
LogScreenResolution();
Logger.LogInformation("→ {Text}", "自动战斗,启动!");
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
await Task.WhenAll(fightTask, endTask);
if (_taskParam is { FightFinishDetectEnabled: true, PickDropsAfterFightEnabled: true })
{
// 执行自动拾取掉落物的功能
}
}
private void LogScreenResolution()
@@ -112,4 +123,47 @@ public class AutoFightTask
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
}
}
private async Task<bool> CheckFightFinish()
{
// YOLO 判断血条和怪物位置
if (HasFightFlag(CaptureToRectArea()))
{
_lastFightFlagTime = DateTime.Now;
return false;
}
// 几秒内没有检测到血条和怪物位置,则开始旋转视角重新检测
if ((DateTime.Now - _lastFightFlagTime).TotalSeconds > 5)
{
// 旋转完毕后都没有检测到血条和怪物位置,则按L键确认战斗结束
List<int> angles = [0, 90, 180, 270];
var rotateTask = new CameraRotateTask(_cts!);
foreach (var a in angles)
{
await rotateTask.WaitUntilRotatedTo(a, 5, 30);
await Delay(1000, _cts!); // 等待视角稳定
if (HasFightFlag(CaptureToRectArea()))
{
return false;
}
}
// 最终方案确认战斗结束
Logger.LogInformation("识别到战斗结束");
return true;
}
return false;
}
private bool HasFightFlag(ImageRegion imageRegion)
{
if (RuntimeHelper.IsDebug)
{
imageRegion.SrcMat.SaveImage(Global.Absolute(@"log\fight\" + $"{DateTime.Now:yyyyMMdd_HHmmss_ffff}.png"));
}
var dict = _predictor.Detect(imageRegion);
return dict.ContainsKey("health_bar") || dict.ContainsKey("enemy_identify");
}
}
@@ -39,7 +39,7 @@ public class CombatScenes : IDisposable
private readonly YoloV8Predictor _predictor =
YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute("Assets\\Model\\Common\\avatar_side_classify_sim.onnx"))
.UseOnnxModel(Global.Absolute(@"Assets\Model\Common\avatar_side_classify_sim.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
@@ -32,7 +32,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
private readonly ILogger<AutoFishingTrigger> _logger = App.GetLogger<AutoFishingTrigger>();
private readonly IOcrService _ocrService = OcrFactory.Paddle;
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
public string Name => "自动钓鱼";
public bool IsEnabled { get; set; }
@@ -4601,6 +4601,75 @@
}
]
},
{
"id": 1609,
"nameEn": "chiori",
"type": "character",
"name": "千织",
"hp": 10,
"energy": 2,
"element": "岩元素",
"weapon": "单手剑",
"skills": [
{
"nameEn": "weaving_blade",
"name": "心织刀流",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "fluttering_hasode",
"name": "羽袖一触",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
}
]
},
{
"nameEn": "hiyoku_twin_blades",
"name": "二刀之形·比翼",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
}
]
},
{
"id": 1701,
"nameEn": "collei",
@@ -6529,6 +6598,83 @@
}
]
},
{
"id": 2406,
"nameEn": "abyss_lector_violet_lightning",
"type": "character",
"name": "深渊咏者·紫电",
"hp": 6,
"energy": 2,
"element": "雷元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "den_of_thunder",
"name": "渊薮落雷",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "shock_of_the_enigmatic_abyss",
"name": "秘渊虚霆",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
}
]
},
{
"nameEn": "wild_thunderburst",
"name": "狂迸骇雷",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "electric_rebirth",
"name": "雷之新生",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 2501,
"nameEn": "maguu_kenki",
@@ -7081,5 +7227,82 @@
"cost": []
}
]
},
{
"id": 2703,
"nameEn": "eremite_floral_ringdancer",
"type": "character",
"name": "镀金旅团·叶轮舞者",
"hp": 10,
"energy": 2,
"element": "草元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "floralring_caress",
"name": "叶轮轻扫",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "spiraling_whirl",
"name": "蔓延旋舞",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
}
]
},
{
"nameEn": "spirit_of_omens_awakening_dendro_spiritserpent",
"name": "厄灵苏醒·草之灵蛇",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "spirit_of_omens_power",
"name": "厄灵之能",
"skillTag": [
"被动技能"
],
"cost": []
}
]
}
]
@@ -1,15 +1,15 @@
using BetterGenshinImpact.Helpers.Extensions;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
public class AutoGeniusInvokationTask
public class AutoGeniusInvokationTask(GeniusInvokationTaskParam taskParam) : ISoloTask
{
public static void Start(GeniusInvokationTaskParam taskParam)
public Task Start(CancellationTokenSource cts)
{
TaskTriggerDispatcher.Instance().StopTimer();
// 读取策略信息
var duel = ScriptParser.Parse(taskParam.StrategyContent);
SystemControl.ActivateWindow();
duel.RunAsync(taskParam).SafeForget();
duel.Run(cts);
return Task.CompletedTask;
}
}
}
@@ -67,9 +67,9 @@ public class GeniusInvokationControl
// private IGameCapture? _gameCapture;
public void Init(GeniusInvokationTaskParam taskParam)
public void Init(CancellationTokenSource cts)
{
_cts = taskParam.Cts;
_cts = cts;
// _gameCapture = taskParam.Dispatcher.GameCapture;
}
@@ -3,7 +3,7 @@ using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
public class GeniusInvokationTaskParam(CancellationTokenSource cts, string strategyContent) : BaseTaskParam(cts)
public class GeniusInvokationTaskParam(string strategyContent) : BaseTaskParam
{
public string StrategyContent { get; set; } = strategyContent;
}
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Assets;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Common;
@@ -53,31 +54,21 @@ public class Duel
private int _keqingECount = 0;
public async Task RunAsync(GeniusInvokationTaskParam taskParam)
public async Task RunAsync(CancellationTokenSource cts)
{
await Task.Run(() => { Run(taskParam); });
await Task.Run(() => { Run(cts); });
}
public void Run(GeniusInvokationTaskParam taskParam)
public void Run(CancellationTokenSource cts)
{
var hasLock = false;
Cts = taskParam.Cts;
Cts = cts;
try
{
AutoGeniusInvokationAssets.DestroyInstance();
hasLock = TaskControl.TaskSemaphore.Wait(0);
if (!hasLock)
{
_logger.LogError("启动自动七圣召唤功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
LogScreenResolution();
_logger.LogInformation("========================================");
_logger.LogInformation("→ {Text}", "全自动七圣召唤,启动!");
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Started().Build());
GeniusInvokationControl.GetInstance().Init(taskParam);
SystemControl.ActivateWindow();
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Started().Build()); // TODO 需要移动
GeniusInvokationControl.GetInstance().Init(Cts);
// 对局准备 选择初始手牌
GeniusInvokationControl.GetInstance().CommonDuelPrepare();
@@ -302,36 +293,23 @@ public class Duel
}
catch (TaskCanceledException ex)
{
_logger.LogInformation(ex.Message);
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Cancelled().Build());
throw;
}
catch (NormalEndException ex)
{
_logger.LogInformation(ex.Message);
_logger.LogInformation("对局结束");
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Success().Build());
throw;
}
catch (System.Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogDebug(ex.StackTrace);
if (TaskContext.Instance().Config.DetailedErrorLogs)
{
_logger.LogError(ex.StackTrace);
}
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Failure().Build());
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskSettingsPageViewModel.SetSwitchAutoGeniusInvokationButtonText(false);
_logger.LogInformation("← {Text}", "退出全自动七圣召唤");
TaskTriggerDispatcher.Instance().StartTimer();
if (hasLock)
{
TaskControl.TaskSemaphore.Release();
}
throw;
}
}
@@ -3,4 +3,4 @@ using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoMusicGame;
public class AutoMusicGameParam(CancellationTokenSource cts) : BaseTaskParam(cts);
public class AutoMusicGameParam : BaseTaskParam;
@@ -1,7 +1,5 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
@@ -14,7 +12,7 @@ using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoMusicGame;
public class AutoMusicGameTask(AutoMusicGameParam taskParam)
public class AutoMusicGameTask(AutoMusicGameParam taskParam) : ISoloTask
{
private readonly ConcurrentDictionary<User32.VK, int> _keyX = new()
{
@@ -30,57 +28,26 @@ public class AutoMusicGameTask(AutoMusicGameParam taskParam)
private readonly IntPtr _hWnd = TaskContext.Instance().GameHandle;
public async void Start()
public Task Start(CancellationTokenSource cts)
{
var hasLock = false;
try
Init();
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var taskFactory = new TaskFactory();
var taskList = new List<Task>();
// 计算按键位置
var gameCaptureRegion = CaptureToRectArea();
foreach (var keyValuePair in _keyX)
{
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
{
Logger.LogError("启动自动战斗功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
Init();
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var taskFactory = new TaskFactory();
var taskList = new List<Task>();
// 计算按键位置
var gameCaptureRegion = CaptureToRectArea();
foreach (var keyValuePair in _keyX)
{
var (x, y) = gameCaptureRegion.ConvertPositionToGameCaptureRegion((int)(keyValuePair.Value * assetScale), (int)(_keyY * assetScale));
// 添加任务
taskList.Add(taskFactory.StartNew(() => DoWhitePressWin32(taskParam.Cts, keyValuePair.Key, new Point(x, y))));
}
Task.WaitAll([.. taskList]);
var (x, y) = gameCaptureRegion.ConvertPositionToGameCaptureRegion((int)(keyValuePair.Value * assetScale), (int)(_keyY * assetScale));
// 添加任务
taskList.Add(taskFactory.StartNew(() => DoWhitePressWin32(cts, keyValuePair.Key, new Point(x, y))));
}
catch (NormalEndException)
{
Logger.LogInformation("手动中断自动活动音游");
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().StartTimer();
TaskSettingsPageViewModel.SetSwitchAutoFightButtonText(false);
Logger.LogInformation("→ {Text}", "自动活动音游结束");
if (hasLock)
{
TaskSemaphore.Release();
}
}
Task.WaitAll([.. taskList]);
return Task.CompletedTask;
}
private void DoWhitePressWin32(CancellationTokenSource cts, User32.VK key, Point point)
@@ -129,10 +96,6 @@ public class AutoMusicGameTask(AutoMusicGameParam taskParam)
private void Init()
{
LogScreenResolution();
Logger.LogInformation("→ {Text}", "活动音游,启动!");
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().StopTimer();
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, taskParam.Cts); // 等待缓存图像
}
private void LogScreenResolution()
@@ -0,0 +1,76 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoPathing;
public class CameraRotateTask(CancellationTokenSource cts)
{
private readonly double _dpi = TaskContext.Instance().DpiScale;
/// <summary>
/// 向目标角度旋转
/// </summary>
/// <param name="targetOrientation"></param>
/// <param name="imageRegion"></param>
/// <returns></returns>
public int RotateToApproach(int targetOrientation, ImageRegion imageRegion)
{
var cao = CameraOrientation.Compute(imageRegion.SrcGreyMat);
var diff = (cao - targetOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
if (diff == 0)
{
return diff;
}
// 平滑的旋转视角
// todo dpi 和分辨率都会影响转动速度
double controlRatio = 1;
if (Math.Abs(diff) > 90)
{
controlRatio = 4;
}
else if (Math.Abs(diff) > 30)
{
controlRatio = 3;
}
else if (Math.Abs(diff) > 5)
{
controlRatio = 2;
}
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(-controlRatio * diff * _dpi), 0);
return diff;
}
/// <summary>
/// 转动视角到目标角度
/// </summary>
/// <param name="targetOrientation">目标角度</param>
/// <param name="maxDiff">最大误差</param>
/// <param name="maxTryTimes">最大尝试次数(超时时间)</param>
/// <returns></returns>
public async Task WaitUntilRotatedTo(int targetOrientation, int maxDiff, int maxTryTimes = 50)
{
int count = 0;
while (!cts.IsCancellationRequested)
{
var screen = CaptureToRectArea();
if (Math.Abs(RotateToApproach(targetOrientation, screen)) < maxDiff)
{
break;
}
if (count > maxTryTimes)
{
Logger.LogWarning("视角转动到目标角度超时,停止转动");
break;
}
await Delay(50, cts);
count++;
}
}
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Concurrent;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
public class ActionFactory
{
private static readonly ConcurrentDictionary<string, IActionHandler> _handlers = new();
public static IActionHandler GetHandler(string handlerType)
{
return _handlers.GetOrAdd(handlerType, (key) =>
{
return key switch
{
"nahida_collect" => new NahidaCollectHandler(),
"pick_around" => new PickAroundHandler(),
"fight" => new AutoFightHandler(),
_ => throw new ArgumentException("未知的 action 类型")
};
});
}
}
@@ -0,0 +1,43 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoFight;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
internal class AutoFightHandler : IActionHandler
{
public async Task RunAsync(CancellationTokenSource cts)
{
await StartFight(cts);
}
private async Task StartFight(CancellationTokenSource cts)
{
// 爷们要战斗
var taskParams = new AutoFightParam(GetFightStrategy())
{
FightFinishDetectEnabled = true,
PickDropsAfterFightEnabled = true
};
var fightSoloTask = new AutoFightTask(taskParams);
await fightSoloTask.Start(cts);
}
private string GetFightStrategy()
{
var path = Global.Absolute(@"User\AutoFight\" + TaskContext.Instance().Config.AutoFightConfig.StrategyName + ".txt");
if ("根据队伍自动选择".Equals(TaskContext.Instance().Config.AutoFightConfig.StrategyName))
{
path = Global.Absolute(@"User\AutoFight\");
}
if (!File.Exists(path) && !Directory.Exists(path))
{
throw new Exception("战斗策略文件不存在");
}
return path;
}
}
@@ -0,0 +1,9 @@
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
public interface IActionHandler
{
Task RunAsync(CancellationTokenSource cts);
}
@@ -0,0 +1,57 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Simulator;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
/// <summary>
/// 使用纳西妲长按E技能进行收集,360°球形无死角扫码,`type = target`的情况才有效
/// </summary>
public class NahidaCollectHandler : IActionHandler
{
private DateTime lastETime = DateTime.MinValue;
public async Task RunAsync(CancellationTokenSource cts)
{
var cd = DateTime.Now - lastETime;
if (cd < TimeSpan.FromSeconds(10))
{
await Delay((int)((6 - cd.TotalSeconds + 0.5) * 1000), cts);
}
var dpi = TaskContext.Instance().DpiScale;
int x = (int)(200 * dpi), y = (int)(-50 * dpi);
int i = 80;
// 视角拉到最下面
Simulation.SendInput.Mouse.MoveMouseBy(0, 10000);
await Delay(200, cts);
// 按住E技能 无死角扫码
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_E);
await Delay(200, cts);
while (!cts.IsCancellationRequested && i > 0)
{
i--;
if (i == 40)
{
y -= (int)(20 * dpi);
}
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
await Delay(40, cts);
}
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_E);
lastETime = DateTime.Now;
await Delay(1000, cts);
// 恢复视角
Simulation.SendInput.Mouse.MiddleButtonClick();
await Delay(1000, cts);
}
}
@@ -0,0 +1,18 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
/// <summary>
/// 采集任务到达点位后执行拾取操作
/// 暂时不需要
/// </summary>
public class PickAroundHandler : IActionHandler
{
public async Task RunAsync(CancellationTokenSource cts)
{
await Task.Delay(1000, cts.Token);
throw new NotImplementedException();
}
}
@@ -1,12 +0,0 @@
using System;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
/// <summary>
/// 采集任务到达点位后执行拾取操作
/// 暂时不需要
/// </summary>
[Obsolete]
public class PickHandler
{
}
@@ -5,6 +5,11 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
public class ActionEnum(string code, string msg)
{
public static readonly ActionEnum StopFlying = new("stop_flying", "下落攻击");
public static readonly ActionEnum ForceTp = new("force_tp", "当前点传送");
public static readonly ActionEnum NahidaCollect = new("nahida_collect", "纳西妲长按E收集");
public static readonly ActionEnum PickAround = new("pick_around", "尝试在周围拾取");
public static readonly ActionEnum Fight = new("fight", "战斗");
// 还有要加入的其他动作
// 滚轮F
// 触发自动战斗任务
@@ -5,6 +5,8 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
public class MoveModeEnum(string code, string msg)
{
public static readonly MoveModeEnum Walk = new("walk", "步行");
public static readonly MoveModeEnum Run = new("run", "奔跑");
public static readonly MoveModeEnum Climb = new("climb", "攀爬");
public static readonly MoveModeEnum Fly = new("fly", "飞行");
public static readonly MoveModeEnum Jump = new("jump", "跳跃");
public static readonly MoveModeEnum Swim = new("swim", "游泳");
@@ -34,6 +34,12 @@ public class PathingTask
return task;
}
public static PathingTask BuildFromJson(string json)
{
var task = JsonSerializer.Deserialize<PathingTask>(json, PathRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize PathingTask");
return task;
}
public void SaveToFile(string filePath)
{
var json = JsonSerializer.Serialize(this, PathRecorder.JsonOptions);
@@ -8,7 +8,16 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
public class PathingTaskInfo
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string? Description { get; set; }
public string? Author { get; set; }
public string? Version { get; set; }
/// <summary>
/// 制作时 BetterGI 的版本,用于兼容性检查
/// </summary>
public string? BgiVersion { get; set; }
/// <summary>
/// 任务类型
@@ -0,0 +1,31 @@
using BetterGenshinImpact.GameTask.Common.Map;
using System;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
[Serializable]
public class WaypointForTrack : Waypoint
{
// 原神坐标系
public double GameX { get; set; }
public double GameY { get; set; }
// 全地图图像坐标系
public double MatX { get; set; }
public double MatY { get; set; }
public WaypointForTrack(Waypoint waypoint)
{
Type = waypoint.Type;
MoveMode = waypoint.MoveMode;
Action = waypoint.Action;
GameX = waypoint.X;
GameY = waypoint.Y;
// 坐标系转换
(MatX, MatY) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
X = MatX;
Y = MatY;
}
}
@@ -23,6 +23,12 @@ public class Navigation
TaskControl.Logger.LogInformation("地图特征点加载完成!");
}
_isWarmUp = true;
Reset();
}
public static void Reset()
{
EntireMap.Instance.SetPrevPosition(-1, -1);
}
public static Point2f GetPosition(ImageRegion imageRegion)
@@ -1,10 +1,10 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Extensions.Logging;
@@ -22,11 +22,10 @@ namespace BetterGenshinImpact.GameTask.AutoPathing;
public class PathExecutor(CancellationTokenSource cts)
{
private double _dpi = 1;
private readonly CameraRotateTask _rotateTask = new(cts);
public async Task Pathing(PathingTask task)
{
_dpi = TaskContext.Instance().DpiScale;
if (!task.Positions.Any())
{
Logger.LogWarning("没有路径点,寻路结束");
@@ -35,7 +34,7 @@ public class PathExecutor(CancellationTokenSource cts)
InitializePathing(task);
var waypoints = ConvertWaypoints(task.Positions);
var waypoints = ConvertWaypointsForTrack(task.Positions);
await Delay(100, cts);
Navigation.WarmUp(); // 提前加载地图特征点
@@ -56,6 +55,8 @@ public class PathExecutor(CancellationTokenSource cts)
if (waypoint.Type == WaypointType.Target.Code || !string.IsNullOrEmpty(waypoint.Action))
{
await MoveCloseTo(waypoint);
// 到达点位后执行 action
await AfterMoveToTarget(waypoint);
}
}
}
@@ -75,42 +76,27 @@ public class PathExecutor(CancellationTokenSource cts)
"UpdateCurrentPathing", new object(), task));
}
private List<Waypoint> ConvertWaypoints(List<Waypoint> positions)
private List<WaypointForTrack> ConvertWaypointsForTrack(List<Waypoint> positions)
{
var waypoints = new List<Waypoint>();
foreach (var waypoint in positions)
{
if (waypoint.Type == WaypointType.Teleport.Code)
{
waypoints.Add(waypoint);
continue;
}
var waypointCopy = new Waypoint
{
Action = waypoint.Action,
Type = waypoint.Type,
MoveMode = waypoint.MoveMode
};
(waypointCopy.X, waypointCopy.Y) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
waypoints.Add(waypointCopy);
}
return waypoints;
// 把 X Y 转换为 MatX MatY
return positions.Select(waypoint => new WaypointForTrack(waypoint)).ToList();
}
private async Task HandleTeleportWaypoint(Waypoint waypoint)
private async Task HandleTeleportWaypoint(WaypointForTrack waypoint)
{
var (tpX, tpY) = await new TpTask(cts).Tp(waypoint.X, waypoint.Y);
var forceTp = waypoint.Action == ActionEnum.ForceTp.Code;
var (tpX, tpY) = await new TpTask(cts).Tp(waypoint.GameX, waypoint.GameY, forceTp);
var (tprX, tprY) = MapCoordinate.GameToMain2048(tpX, tpY);
EntireMap.Instance.SetPrevPosition((float)tprX, (float)tprY); // 通过上一个位置直接进行局部特征匹配
}
private async Task MoveTo(Waypoint waypoint)
private async Task MoveTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = Navigation.GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("粗略接近途经点,位置({x2},{y2})", $"{waypoint.X:F1}", $"{waypoint.Y:F1}");
await WaitUntilRotatedTo(targetOrientation, 5);
Logger.LogInformation("粗略接近途经点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
var startTime = DateTime.UtcNow;
var lastPositionRecord = DateTime.UtcNow;
var fastMode = false;
@@ -120,11 +106,12 @@ public class PathExecutor(CancellationTokenSource cts)
while (!cts.IsCancellationRequested)
{
var now = DateTime.UtcNow;
if ((now - startTime).TotalSeconds > 60)
if ((now - startTime).TotalSeconds > 240)
{
Logger.LogWarning("执行超时,跳过路径点");
break;
}
screen = CaptureToRectArea();
position = Navigation.GetPosition(screen);
var distance = Navigation.GetDistance(waypoint, position);
@@ -134,38 +121,36 @@ public class PathExecutor(CancellationTokenSource cts)
Logger.LogInformation("到达路径点附近");
break;
}
if (distance > 500)
{
Logger.LogWarning("距离过远,跳过路径点");
break;
}
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
// 非爬行状态下,检测是否卡死
if (waypoint.MoveMode != MoveModeEnum.Climb.Code)
{
lastPositionRecord = now;
prevPositions.Add(position);
if (prevPositions.Count > 8)
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
{
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
lastPositionRecord = now;
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
Logger.LogWarning("疑似卡死,尝试脱离并跳过路径点");
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
await Delay(500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_S);
await Delay(500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_A);
await Delay(500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_D);
await Delay(500, cts);
return;
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
{
Logger.LogWarning("疑似卡死,尝试脱离并跳过路径点");
await EscapeTrap();
return;
}
}
}
}
// 旋转视角
targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
RotateTo(targetOrientation, screen);
_rotateTask.RotateToApproach(targetOrientation, screen);
// 根据指定方式进行移动
if (waypoint.MoveMode == MoveModeEnum.Fly.Code)
{
@@ -176,45 +161,97 @@ public class PathExecutor(CancellationTokenSource cts)
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Delay(200, cts);
}
continue;
}
// if (isFlying)
// {
// Simulation.SendInput.Mouse.LeftButtonClick();
// await Delay(1000, cts);
// continue;
// }
if (waypoint.MoveMode == MoveModeEnum.Jump.Code)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Delay(200, cts);
continue;
}
// 跑步或者游泳
if (distance > 20 != fastMode)// 距离大于20时可以使用疾跑/自由泳
// 只有设置为run才会疾跑
if (waypoint.MoveMode == MoveModeEnum.Run.Code)
{
if (fastMode)
if (distance > 20 != fastMode) // 距离大于20时可以使用疾跑/自由泳
{
Simulation.SendInput.Mouse.RightButtonUp();
if (fastMode)
{
Simulation.SendInput.Mouse.RightButtonUp();
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
await Delay(100, cts);
}
// 抬起w键
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
private async Task MoveCloseTo(Waypoint waypoint)
private bool IsStuck(DateTime now, DateTime lastPositionRecord, List<Point2f> prevPositions, Point2f position)
{
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
{
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
{
return true;
}
}
}
return false;
}
private async Task EscapeTrap()
{
// 脱离攀爬状态
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
await Delay(1500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 向后移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_S);
await Task.Delay(1500);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_S);
// 向左移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_A);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(1000);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_A);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 向右移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_D);
await Task.Delay(300);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(700);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_D);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 跳跃
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(200); // 等待跳跃动作
}
private async Task MoveCloseTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = Navigation.GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("精确接近目标点,位置({x2},{y2})", $"{waypoint.X:F1}", $"{waypoint.Y:F1}");
Logger.LogInformation("精确接近目标点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
if (waypoint.MoveMode == MoveModeEnum.Fly.Code && waypoint.Action == ActionEnum.StopFlying.Code)
{
//下落攻击接近目的地
@@ -222,17 +259,19 @@ public class PathExecutor(CancellationTokenSource cts)
Simulation.SendInput.Mouse.LeftButtonClick();
await Delay(1000, cts);
}
await WaitUntilRotatedTo(targetOrientation, 2);
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
var wPressed = false;
var stepsTaken = 0;
while (!cts.IsCancellationRequested)
{
stepsTaken++;
if (stepsTaken > 8)
if (stepsTaken > 12)
{
Logger.LogWarning("精确接近超时");
break;
}
screen = CaptureToRectArea();
position = Navigation.GetPosition(screen);
if (Navigation.GetDistance(waypoint, position) < 2)
@@ -240,7 +279,8 @@ public class PathExecutor(CancellationTokenSource cts)
Logger.LogInformation("已到达路径点");
break;
}
RotateTo(targetOrientation, screen); //不再改变视角
_rotateTask.RotateToApproach(targetOrientation, screen); //不再改变视角
if (waypoint.MoveMode == MoveModeEnum.Walk.Code)
{
// 小碎步接近
@@ -248,60 +288,29 @@ public class PathExecutor(CancellationTokenSource cts)
await Delay(200, cts);
continue;
}
if (!wPressed)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
}
await Delay(100, cts);
}
if (wPressed)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
}
private int RotateTo(int targetOrientation, ImageRegion imageRegion, double controlRatio = 1)
private async Task AfterMoveToTarget(Waypoint waypoint)
{
var cao = CameraOrientation.Compute(imageRegion.SrcGreyMat);
var diff = (cao - targetOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
if (diff == 0)
if (waypoint.Action == ActionEnum.NahidaCollect.Code
|| waypoint.Action == ActionEnum.PickAround.Code
|| waypoint.Action == ActionEnum.Fight.Code)
{
return diff;
}
// 平滑的旋转视角
if (Math.Abs(diff) > 90)
{
controlRatio = 5;
}
else if (Math.Abs(diff) > 30)
{
controlRatio = 3;
}
else if (Math.Abs(diff) > 5)
{
controlRatio = 2;
}
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(-controlRatio * diff * _dpi), 0);
return diff;
}
private async Task WaitUntilRotatedTo(int targetOrientation, int maxDiff)
{
int count = 0;
while (!cts.IsCancellationRequested)
{
var screen = CaptureToRectArea();
if (Math.Abs(RotateTo(targetOrientation, screen)) < maxDiff)
{
break;
}
if (count > 50)
{
break;
}
await Delay(50, cts);
count++;
var handler = ActionFactory.GetHandler(waypoint.Action);
await handler.RunAsync(cts);
}
}
}
@@ -3,17 +3,23 @@ using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.View.Controls.Webview;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using BetterGenshinImpact.Model;
using Microsoft.Web.WebView2.Core;
namespace BetterGenshinImpact.GameTask.AutoPathing;
public class PathRecorder
public class PathRecorder : Singleton<PathRecorder>
{
private WebpageWindow? _webWindow;
public static readonly JsonSerializerOptions JsonOptions = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
@@ -28,6 +34,7 @@ public class PathRecorder
public void Start()
{
Navigation.WarmUp();
_pathingTask = new PathingTask();
TaskControl.Logger.LogInformation("开始路径点记录");
var waypoint = new Waypoint();
@@ -39,7 +46,15 @@ public class PathRecorder
waypoint.Type = WaypointType.Teleport.Code;
waypoint.MoveMode = MoveModeEnum.Walk.Code;
_pathingTask.Positions.Add(waypoint);
TaskControl.Logger.LogInformation("已创建初始路径点({x},{y})", waypoint.X, waypoint.Y);
if (_webWindow == null)
{
TaskControl.Logger.LogInformation("已创建初始路径点({x},{y})", waypoint.X, waypoint.Y);
}
else
{
TaskControl.Logger.LogInformation("已添加途径点({x},{y})", waypoint.X, waypoint.Y);
AddPosToEditor(waypoint.X, waypoint.Y);
}
}
public void AddWaypoint(string waypointType = "")
@@ -51,27 +66,55 @@ public class PathRecorder
waypoint.X = position.X;
waypoint.Y = position.Y;
waypoint.Type = string.IsNullOrEmpty(waypointType) ? WaypointType.Path.Code : waypointType;
// var motionStatus = Bv.GetMotionStatus(screen);
// switch (motionStatus)
// {
// case MotionStatus.Fly:
// waypoint.MoveStatus = MoveStatusType.Fly.Code;
// break;
//
// case MotionStatus.Climb:
// waypoint.MoveStatus = MoveStatusType.Jump.Code;
// break;
//
// default:
// waypoint.MoveStatus = MoveStatusType.Walk.Code;
// break;
// }
_pathingTask.Positions.Add(waypoint);
TaskControl.Logger.LogInformation("已添加途径点({x},{y})", waypoint.X, waypoint.Y);
AddPosToEditor(waypoint.X, waypoint.Y);
}
public void Save()
{
_pathingTask.SaveToFile(Path.Combine(MapPathingViewModel.PathJsonPath, $@"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff}.json"));
if (_webWindow == null)
{
var name = $@"{DateTime.Now:yyyyMMdd_HHmmss}.json";
_pathingTask.SaveToFile(Path.Combine(MapPathingViewModel.PathJsonPath, name));
TaskControl.Logger.LogInformation("录制编辑器未打开,直接保存路径点记录:{Name}", name);
}
else
{
TaskControl.Logger.LogInformation("路径点记录结束,请在录制编辑器中查看并编辑结果");
TaskControl.Logger.LogInformation("如果要重新录制新的路径,请在录制编辑器中删除已有路径或创建新的路径");
TaskControl.Logger.LogInformation("修改完毕后请务必记得导出路径!");
}
}
public void AddPosToEditor(double x, double y)
{
if (_webWindow != null)
{
_webWindow.WebView.ExecuteScriptAsync($"addNewPoint({x},{y})");
}
}
public void OpenEditorInWebView()
{
if (_webWindow is not { IsVisible: true })
{
_webWindow = new WebpageWindow
{
Title = "地图路径点编辑器",
Width = 1366,
Height = 768,
// Owner = Application.Current.MainWindow,
WindowState = WindowState.Maximized
};
_webWindow.Closed += (s, e) => _webWindow = null;
_webWindow.Panel!.DownloadFolderPath = MapPathingViewModel.PathJsonPath;
_webWindow.NavigateToFile(Global.Absolute(@"Assets\Map\Editor\index.html"));
_webWindow.Show();
}
else
{
_webWindow.Activate();
}
}
}
@@ -134,6 +134,14 @@ public partial class AutoPickTrigger : ITaskTrigger
content.CaptureRectArea.Find(_pickRo, foundRectArea =>
{
speedTimer.Record($"识别到 {_pickKeyName} 拾取键");
if (_externalConfig is { ForceInteraction: true })
{
LogPick(content, "直接拾取");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F);
return;
}
var scale = TaskContext.Instance().SystemInfo.AssetScale;
var config = TaskContext.Instance().Config.AutoPickConfig;
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
@@ -19,6 +20,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -36,6 +38,8 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
/// </summary>
private Rect _missionDistanceRect = Rect.Empty;
private CancellationTokenSource? _cts;
public async void Start()
{
var hasLock = false;
@@ -52,6 +56,8 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
Logger.LogInformation("→ {Text}", "自动追踪,启动!");
_cts = CancellationContext.Instance.Cts;
TrackMission();
}
catch (NormalEndException e)
@@ -68,7 +74,6 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskSettingsPageViewModel.SetSwitchAutoTrackButtonText(false);
Logger.LogInformation("→ {Text}", "自动追踪结束");
if (hasLock)
@@ -85,20 +90,20 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
var paimonMenuRa = ra.Find(ElementAssets.Instance.PaimonMenuRo);
if (!paimonMenuRa.IsExist())
{
Sleep(5000, param.Cts);
Sleep(5000, _cts);
return;
}
// 任务文字有动效,等待2s重新截图
Simulation.SendInput.Mouse.MoveMouseBy(0, 7000);
Sleep(2000, param.Cts);
Sleep(2000, _cts);
// OCR 任务文字 在小地图下方
var textRaList = OcrMissionTextRaList(paimonMenuRa);
if (textRaList.Count == 0)
{
Logger.LogInformation("未找到任务文字");
Sleep(5000, param.Cts);
Sleep(5000, _cts);
return;
}
@@ -110,14 +115,14 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
// 距离大于150米,先传送到最近的传送点
// J 打开任务 切换追踪打开地图 中心点就是任务点
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_J);
Sleep(800, param.Cts);
Sleep(800, _cts);
// TODO 识别是否在任务界面
// 切换追踪
var btn = ra.Derive(CaptureRect.Width - 250, CaptureRect.Height - 60);
btn.Click();
Sleep(200, param.Cts);
Sleep(200, _cts);
btn.Click();
Sleep(1500, param.Cts);
Sleep(1500, _cts);
// 寻找所有传送点
ra = CaptureToRectArea();
@@ -141,7 +146,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
ra.Derive(nearestRect).Click();
// 等待自动传送完成
Sleep(2000, param.Cts);
Sleep(2000, _cts);
if (Bv.IsInBigMapUi(CaptureToRectArea()))
{
@@ -149,7 +154,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
}
else
{
Sleep(500, param.Cts);
Sleep(500, _cts);
NewRetry.Do(() =>
{
if (!Bv.IsInMainUi(CaptureToRectArea()))
@@ -176,7 +181,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
// V键直接追踪
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_V);
Sleep(3000, param.Cts);
Sleep(3000, _cts);
var ra = CaptureToRectArea();
var blueTrackPointRa = ra.Find(ElementAssets.Instance.BlueTrackPoint);
@@ -199,7 +204,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
// {
int prevMoveX = 0;
bool wDown = false;
while (!param.Cts.Token.IsCancellationRequested)
while (!_cts.Token.IsCancellationRequested)
{
var ra = CaptureToRectArea();
var blueTrackPointRa = ra.Find(ElementAssets.Instance.BlueTrackPoint);
@@ -5,7 +5,4 @@ namespace BetterGenshinImpact.GameTask.AutoSkip.Model;
public class AutoTrackParam : BaseTaskParam
{
public AutoTrackParam(CancellationTokenSource cts) : base(cts)
{
}
}
File diff suppressed because it is too large. Load diff
@@ -5,7 +5,4 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath;
public class AutoTrackPathParam : BaseTaskParam
{
public AutoTrackPathParam(CancellationTokenSource cts) : base(cts)
{
}
}
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
@@ -44,6 +45,8 @@ public class AutoTrackPathTask
// 视角偏移移动单位
private const int CharMovingUnit = 500;
private CancellationTokenSource? _cts;
public AutoTrackPathTask(AutoTrackPathParam taskParam)
{
_taskParam = taskParam;
@@ -64,6 +67,8 @@ public class AutoTrackPathTask
return;
}
_cts = CancellationContext.Instance.Cts;
Init();
// Tp(_tpPositions[260].X, _tpPositions[260].Y);
@@ -83,7 +88,6 @@ public class AutoTrackPathTask
{
VisionContext.Instance().DrawContent.ClearAll();
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.NormalTrigger);
TaskSettingsPageViewModel.SetSwitchAutoFightButtonText(false);
Logger.LogInformation("→ {Text}", "自动路线结束");
if (hasLock)
@@ -98,19 +102,19 @@ public class AutoTrackPathTask
SystemControl.ActivateWindow();
Logger.LogInformation("→ {Text}", "自动路线,启动!");
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _cts); // 等待缓存图像
}
public void Stop()
{
_taskParam.Cts.Cancel();
_cts.Cancel();
}
public async Task DoTask()
{
// 1. 传送到最近的传送点
var first = _way.WayPointList[0]; // 解析路线,第一个点为起点
await new TpTask(_taskParam.Cts).Tp(first.Pt.X, first.Pt.Y);
await new TpTask(_cts).Tp(first.Pt.X, first.Pt.Y);
// 2. 等待传送完成
Sleep(1000);
@@ -132,7 +136,7 @@ public class AutoTrackPathTask
// 4. 针对点位进行直线追踪
var trackCts = new CancellationTokenSource();
_taskParam.Cts.Token.Register(trackCts.Cancel);
_cts.Token.Register(trackCts.Cancel);
var trackTask = Track(_way.WayPointList, angleOffset, trackCts);
trackTask.Start();
var refreshStatusTask = RefreshStatus(trackCts);
@@ -148,7 +152,7 @@ public class AutoTrackPathTask
{
return new Task(() =>
{
while (!_taskParam.Cts.Token.IsCancellationRequested && !trackCts.Token.IsCancellationRequested)
while (!_cts.Token.IsCancellationRequested && !trackCts.Token.IsCancellationRequested)
{
if (_motionStatus == MotionStatus.Normal)
{
@@ -178,7 +182,7 @@ public class AutoTrackPathTask
{
return new Task(() =>
{
while (!_taskParam.Cts.Token.IsCancellationRequested && !trackCts.Token.IsCancellationRequested)
while (!_cts.Token.IsCancellationRequested && !trackCts.Token.IsCancellationRequested)
{
using var ra = CaptureToRectArea();
_motionStatus = Bv.GetMotionStatus(ra);
@@ -206,7 +210,7 @@ public class AutoTrackPathTask
return new Task(() =>
{
var currIndex = 0;
while (!_taskParam.Cts.IsCancellationRequested)
while (!_cts.IsCancellationRequested)
{
var ra = CaptureToRectArea();
var miniMapMat = GetMiniMapMat(ra) ?? throw new InvalidOperationException("当前不在主界面");
@@ -16,6 +16,7 @@ using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -28,16 +29,26 @@ public class TpTask(CancellationTokenSource cts)
{
private readonly QuickTeleportAssets _assets = QuickTeleportAssets.Instance;
private readonly Rect _captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
private readonly double _zoomOutMax1080PRatio = TaskContext.Instance().SystemInfo.ZoomOutMax1080PRatio;
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
/// </summary>
/// <param name="tpX"></param>
/// <param name="tpY"></param>
public async Task<(double, double)> Tp(double tpX, double tpY)
/// <param name="force">强制以当前的tpX,tpY坐标进行自动传送</param>
public async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false)
{
// 获取最近的传送点位置
var (x, y) = GetRecentlyTpPoint(tpX, tpY);
Logger.LogInformation("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", $"{tpX:F1}", $"{tpY:F1}", $"{x:F1}", $"{y:F1}");
var (x, y) = (tpX, tpY);
if (!force)
{
// 获取最近的传送点位置
(x, y) = GetRecentlyTpPoint(tpX, tpY);
Logger.LogDebug("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", $"{tpX:F1}", $"{tpY:F1}", $"{x:F1}", $"{y:F1}");
}
// M 打开地图识别当前位置,中心点为当前位置
using var ra1 = CaptureToRectArea();
@@ -52,7 +63,7 @@ public class TpTask(CancellationTokenSource cts)
// 计算坐标后点击
var bigMapInAllMapRect = GetBigMapRect();
while (!bigMapInAllMapRect.Contains(x, y))
while (!IsPointInBigMapWindow(bigMapInAllMapRect, x, y)) // 左上角 350x400也属于禁止点击区域
{
Debug.WriteLine($"({x},{y}) 不在 {bigMapInAllMapRect} 内,继续移动");
Logger.LogInformation("传送点不在当前大地图范围内,继续移动");
@@ -62,15 +73,10 @@ public class TpTask(CancellationTokenSource cts)
// Debug.WriteLine($"({x},{y}) 在 {bigMapInAllMapRect} 内,计算它在窗体内的位置");
// 注意这个坐标的原点是中心区域某个点,所以要转换一下点击坐标(点击坐标是左上角为原点的坐标系),不能只是缩放
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var clickX = (int)((picX - picRect.X) / picRect.Width * captureRect.Width);
var clickY = (int)((picY - picRect.Y) / picRect.Height * captureRect.Height);
Logger.LogInformation("点击传送点:({X},{Y})", clickX, clickY);
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
Logger.LogInformation("点击传送点");
using var ra = CaptureToRectArea();
ra.ClickTo(clickX, clickY);
ra.ClickTo((int)clickX, (int)clickY);
// 触发一次快速传送功能
await Delay(500, cts);
@@ -91,6 +97,82 @@ public class TpTask(CancellationTokenSource cts)
return (x, y);
}
/// <summary>
/// 传送点是否在大地图窗口内
/// </summary>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private bool IsPointInBigMapWindow(Rect bigMapInAllMapRect, double x, double y)
{
// 坐标不包含直接返回
if (!bigMapInAllMapRect.Contains(x, y))
{
return false;
}
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
// 屏蔽左上角350x400区域
if (clickX < 250 * _zoomOutMax1080PRatio && clickY < 400 * _zoomOutMax1080PRatio)
{
return false;
}
// 屏蔽周围 115 一圈的区域
if (clickX < 115 * _zoomOutMax1080PRatio
|| clickY < 115 * _zoomOutMax1080PRatio
|| clickX > _captureRect.Width - 115 * _zoomOutMax1080PRatio
|| clickY > _captureRect.Height - 115 * _zoomOutMax1080PRatio)
{
return false;
}
return true;
}
/// <summary>
/// 转换传送点坐标到窗体内需要点击的坐标
/// </summary>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private (double clickX, double clickY) ConvertToGameRegionPosition(Rect bigMapInAllMapRect, double x, double y)
{
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var clickX = (picX - picRect.X) / picRect.Width * _captureRect.Width;
var clickY = (picY - picRect.Y) / picRect.Height * _captureRect.Height;
return (clickX, clickY);
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false)
{
// 重试3次
for (var i = 0; i < 3; i++)
{
try
{
return await TpOnce(tpX, tpY, force);
}
catch (TpPointNotActivate)
{
// 传送点未激活或不存在 按ESC回到大地图界面
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(300, cts);
throw;
}
catch (Exception e)
{
Logger.LogError(e, "传送失败,重试 {I} 次", i + 1);
}
}
throw new InvalidOperationException("传送失败");
}
/// <summary>
/// 移动地图到指定传送点位置
/// 可能会移动不对,所以可以重试此方法
@@ -179,6 +261,18 @@ public class TpTask(CancellationTokenSource cts)
return GetBigMapCenterPoint();
}
public Point2f? GetPositionFromBigMapNullable()
{
try
{
return GetBigMapCenterPoint();
}
catch
{
return null;
}
}
public Rect GetBigMapRect()
{
var rect = new Rect();
@@ -202,7 +296,7 @@ public class TpTask(CancellationTokenSource cts)
{
throw new RetryException("当前不在地图界面");
}
}, TimeSpan.FromMilliseconds(500), 10);
}, TimeSpan.FromMilliseconds(500), 5);
if (rect == Rect.Empty)
{
@@ -272,10 +366,16 @@ public class TpTask(CancellationTokenSource cts)
}
// 识别当前位置
var bigMapCenterPoint = GetPositionFromBigMap();
Logger.LogInformation("识别当前位置:{Pos}", bigMapCenterPoint);
var minDistance = double.MaxValue;
var bigMapCenterPointNullable = GetPositionFromBigMapNullable();
if (bigMapCenterPointNullable != null)
{
var bigMapCenterPoint = bigMapCenterPointNullable.Value;
Logger.LogDebug("识别当前大地图位置:{Pos}", bigMapCenterPoint);
minDistance = Math.Sqrt(Math.Pow(bigMapCenterPoint.X - x, 2) + Math.Pow(bigMapCenterPoint.Y - y, 2));
}
var minDistance = Math.Sqrt(Math.Pow(bigMapCenterPoint.X - x, 2) + Math.Pow(bigMapCenterPoint.Y - y, 2));
var minCountry = "当前位置";
foreach (var (country, position) in MapAssets.Instance.CountryPositions)
{
@@ -287,7 +387,7 @@ public class TpTask(CancellationTokenSource cts)
}
}
Logger.LogInformation("离目标传送点最近的区域是:{Country}", minCountry);
Logger.LogDebug("离目标传送点最近的区域是:{Country}", minCountry);
if (minCountry != "当前位置")
{
GameCaptureRegion.GameRegionClick((rect, scale) => (rect.Width - 160 * scale, rect.Height - 60 * scale));
@@ -322,33 +422,37 @@ public class TpTask(CancellationTokenSource cts)
// 1.判断是否在地图界面
if (Bv.IsInBigMapUi(imageRegion))
{
// 2. 判断是否有传送按钮
// 2. 判断是否已经点出传送按钮
var hasTeleportButton = CheckTeleportButton(imageRegion);
if (!hasTeleportButton)
{
// 存在地图关闭按钮,说明未选中传送点,直接返回
var mapCloseRa = imageRegion.Find(_assets.MapCloseButtonRo);
if (!mapCloseRa.IsEmpty())
// 3. 没点出传送按钮,且不存在外部地图关闭按钮
// 说明只有两种可能,a. 点出来的是未激活传送点或者标点 b. 选择传送点选项列表
var mapCloseRa1 = imageRegion.Find(_assets.MapCloseButtonRo);
if (!mapCloseRa1.IsEmpty())
{
return;
throw new TpPointNotActivate("传送点未激活或不存在");
}
// 存在地图选择按钮,说明未选中传送点,直接返回
var mapChooseRa = imageRegion.Find(_assets.MapChooseRo);
if (!mapChooseRa.IsEmpty())
else
{
return;
}
// 3. 循环判断选项列表是否有传送点
var hasMapChooseIcon = CheckMapChooseIcon(imageRegion);
if (hasMapChooseIcon)
{
var time = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
time = time < 100 ? 100 : time;
await Delay(time, cts);
CheckTeleportButton(CaptureToRectArea());
// 3. 循环判断选项列表是否有传送点(未激活点位也在里面)
var hasMapChooseIcon = CheckMapChooseIcon(imageRegion);
if (hasMapChooseIcon)
{
var time = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
time = time < 300 ? 300 : time;
await Delay(time, cts);
if (!CheckTeleportButton(CaptureToRectArea()))
{
// 没传送确认图标说明点开的是未激活传送锚点
throw new TpPointNotActivate("传送点未激活或不存在");
}
}
else
{
// 没有传送点说明不是传送点
throw new TpPointNotActivate("传送点未激活或不存在");
}
}
}
}
@@ -399,7 +503,7 @@ public class TpTask(CancellationTokenSource cts)
Logger.LogInformation("传送:点击 {Option}", textRegion.Text);
var time = TaskContext.Instance().Config.QuickTeleportConfig.TeleportListClickDelay;
time = time < 200 ? 200 : time;
time = time < 500 ? 500 : time;
Thread.Sleep(time);
ra.Click();
hasMapChooseIcon = true;
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoWood.Assets;
@@ -15,6 +16,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.User32;
@@ -25,7 +28,7 @@ namespace BetterGenshinImpact.GameTask.AutoWood;
/// <summary>
/// 自动伐木
/// </summary>
public partial class AutoWoodTask
public partial class AutoWoodTask : ISoloTask
{
private readonly AutoWoodAssets _assets;
@@ -37,30 +40,29 @@ public partial class AutoWoodTask
private VK _zKey = VK.VK_Z;
public AutoWoodTask()
private readonly WoodTaskParam _taskParam;
private CancellationTokenSource? _cts;
public AutoWoodTask(WoodTaskParam taskParam)
{
this._taskParam = taskParam;
_login3rdParty = new();
AutoWoodAssets.DestroyInstance();
_assets = AutoWoodAssets.Instance;
_printer = new WoodStatisticsPrinter(_assets);
}
public void Start(WoodTaskParam taskParam)
public Task Start(CancellationTokenSource cts)
{
var hasLock = false;
var runTimeWatch = new Stopwatch();
_cts = cts;
_printer.Cts = _cts;
try
{
hasLock = TaskSemaphore.Wait(0);
if (!hasLock)
{
Logger.LogError("启动自动伐木功能失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
TaskTriggerDispatcher.Instance().StopTimer();
Kernel32.SetThreadExecutionState(Kernel32.EXECUTION_STATE.ES_CONTINUOUS | Kernel32.EXECUTION_STATE.ES_SYSTEM_REQUIRED | Kernel32.EXECUTION_STATE.ES_DISPLAY_REQUIRED);
Logger.LogInformation("→ {Text} 设置伐木总次数:{Cnt},设置木材数量上限:{MaxCnt}", "自动伐木,启动!", taskParam.WoodRoundNum, taskParam.WoodDailyMaxCount);
Logger.LogInformation("→ {Text} 设置伐木总次数:{Cnt},设置木材数量上限:{MaxCnt}", "自动伐木,启动!", _taskParam.WoodRoundNum, _taskParam.WoodDailyMaxCount);
_login3rdParty.RefreshAvailabled();
if (_login3rdParty.Type == Login3rdParty.The3rdPartyType.Bilibili)
@@ -86,7 +88,7 @@ public partial class AutoWoodTask
SystemControl.ActivateWindow();
// 伐木开始计时
runTimeWatch.Start();
for (var i = 0; i < taskParam.WoodRoundNum; i++)
for (var i = 0; i < _taskParam.WoodRoundNum; i++)
{
if (TaskContext.Instance().Config.AutoWoodConfig.WoodCountOcrEnabled)
{
@@ -98,48 +100,31 @@ public partial class AutoWoodTask
if (_printer.ReachedWoodMaxCount)
{
Logger.LogInformation("{Names}已达到设置的上限:{MaxCnt}", _printer.WoodTotalDict.Keys, taskParam.WoodDailyMaxCount);
Logger.LogInformation("{Names}已达到设置的上限:{MaxCnt}", _printer.WoodTotalDict.Keys, _taskParam.WoodDailyMaxCount);
break;
}
}
Logger.LogInformation("第{Cnt}次伐木", i + 1);
if (taskParam.Cts.IsCancellationRequested)
if (_cts.IsCancellationRequested)
{
break;
}
Felling(taskParam, i + 1 == taskParam.WoodRoundNum);
Felling(_taskParam, i + 1 == _taskParam.WoodRoundNum);
VisionContext.Instance().DrawContent.ClearAll();
Sleep(500, taskParam.Cts);
Sleep(500, _cts);
}
}
catch (NormalEndException e)
{
Logger.LogInformation(e.Message);
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
MessageBox.Error("自动伐木时异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
return Task.CompletedTask;
}
finally
{
VisionContext.Instance().DrawContent.ClearAll();
TaskSettingsPageViewModel.SetSwitchAutoWoodButtonText(false);
// 伐木结束计时
runTimeWatch.Stop();
Kernel32.SetThreadExecutionState(Kernel32.EXECUTION_STATE.ES_CONTINUOUS);
var elapsedTime = runTimeWatch.Elapsed;
Logger.LogInformation(@"本次伐木总耗时:{Time:hh\:mm\:ss}", elapsedTime);
Logger.LogInformation("← {Text}", "退出自动伐木");
TaskTriggerDispatcher.Instance().StartTimer();
if (hasLock)
{
TaskSemaphore.Release();
}
}
}
@@ -161,6 +146,8 @@ public partial class AutoWoodTask
"杉木", "竹节", "却砂木", "松木", "萃华木", "桦木", "孔雀木", "梦见木", "御伽木"
];
public CancellationTokenSource? Cts { get; set; }
[GeneratedRegex("([^\\d\\n]+)[×x](\\d+)")]
private static partial Regex _parseWoodStatisticsRegex();
@@ -230,7 +217,7 @@ public partial class AutoWoodTask
private void SleepDurationBetweenOcrs(WoodTaskParam taskParam)
{
Sleep(_firstWoodOcr ? 300 : 100, taskParam.Cts);
Sleep(_firstWoodOcr ? 300 : 100, Cts);
}
private string WoodTextAreaOcr()
@@ -446,7 +433,7 @@ public partial class AutoWoodTask
{
NewRetry.Do(() =>
{
Sleep(1, taskParam.Cts);
Sleep(1, _cts);
using var contentRegion = CaptureToRectArea();
using var ra = contentRegion.Find(_assets.TheBoonOfTheElderTreeRo);
if (ra.IsEmpty())
@@ -460,12 +447,12 @@ public partial class AutoWoodTask
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Debug.WriteLine("[AutoWood] Z");
Sleep(500, taskParam.Cts);
Sleep(500, _cts);
}, TimeSpan.FromSeconds(1), 120);
}
Sleep(300, taskParam.Cts);
Sleep(TaskContext.Instance().Config.AutoWoodConfig.AfterZSleepDelay, taskParam.Cts);
Sleep(300, _cts);
Sleep(TaskContext.Instance().Config.AutoWoodConfig.AfterZSleepDelay, _cts);
}
private void PressEsc(WoodTaskParam taskParam)
@@ -474,17 +461,17 @@ public partial class AutoWoodTask
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
// if (TaskContext.Instance().Config.AutoWoodConfig.PressTwoEscEnabled)
// {
// Sleep(1500, taskParam.Cts);
// Sleep(1500, _cts);
// Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
// }
Debug.WriteLine("[AutoWood] Esc");
Sleep(800, taskParam.Cts);
Sleep(800, _cts);
// 确认在菜单界面
try
{
NewRetry.Do(() =>
{
Sleep(1, taskParam.Cts);
Sleep(1, _cts);
using var contentRegion = CaptureToRectArea();
using var ra = contentRegion.Find(_assets.MenuBagRo);
if (ra.IsEmpty())
@@ -505,7 +492,7 @@ public partial class AutoWoodTask
Debug.WriteLine("[AutoWood] Click exit button");
Sleep(500, taskParam.Cts);
Sleep(500, _cts);
// 点击确认
using var contentRegion = CaptureToRectArea();
@@ -521,14 +508,14 @@ public partial class AutoWoodTask
{
if (_login3rdParty.IsAvailabled)
{
Sleep(1, taskParam.Cts);
_login3rdParty.Login(taskParam.Cts);
Sleep(1, _cts);
_login3rdParty.Login(_cts);
}
var clickCnt = 0;
for (var i = 0; i < 50; i++)
{
Sleep(1, taskParam.Cts);
Sleep(1, _cts);
using var contentRegion = CaptureToRectArea();
using var ra = contentRegion.Find(_assets.EnterGameRo);
@@ -542,12 +529,12 @@ public partial class AutoWoodTask
{
if (clickCnt > 2)
{
Sleep(5000, taskParam.Cts);
Sleep(5000, _cts);
break;
}
}
Sleep(1000, taskParam.Cts);
Sleep(1000, _cts);
}
if (clickCnt == 0)
@@ -8,7 +8,7 @@ public class WoodTaskParam : BaseTaskParam
public int WoodRoundNum { get; set; }
public int WoodDailyMaxCount { get; set; }
public WoodTaskParam(CancellationTokenSource cts, int woodRoundNum, int woodDailyMaxCount) : base(cts)
public WoodTaskParam(int woodRoundNum, int woodDailyMaxCount)
{
WoodRoundNum = woodRoundNum;
if (woodRoundNum == 0)
@@ -17,6 +17,6 @@ public class WoodTaskParam : BaseTaskParam
}
WoodDailyMaxCount = woodDailyMaxCount;
if (WoodDailyMaxCount is 0 or >= 2000) WoodDailyMaxCount = 2000;
if (WoodDailyMaxCount is 0 or >= 9999) WoodDailyMaxCount = 9999;
}
}
@@ -36,6 +36,6 @@ public class MapAssets : BaseAssets<MapAssets>
public MapAssets()
{
var json = File.ReadAllText(Global.Absolute(@"GameTask\AutoTrackPath\Assets\tp.json"));
TpPositions = JsonSerializer.Deserialize<List<GiWorldPosition>>(json, ConfigService.JsonOptions) ?? throw new Exception("tp.json deserialize failed");
TpPositions = JsonSerializer.Deserialize<List<GiWorldPosition>>(json, ConfigService.JsonOptions) ?? throw new System.Exception("tp.json deserialize failed");
}
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.GameTask.Common.Exceptions;
public class TpPointNotActivate(string message) : System.Exception(message)
{
}
@@ -22,7 +22,7 @@ public static class NewRetry
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
List<Exception> exceptions = [];
List<System.Exception> exceptions = [];
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
@@ -131,7 +131,7 @@ public class TaskControl
Sleep(30);
}
throw new Exception("尝试多次后,截图失败!");
throw new System.Exception("尝试多次后,截图失败!");
}
else
{
@@ -0,0 +1,9 @@
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask;
public interface ISoloTask
{
Task Start(CancellationTokenSource cts);
}
@@ -99,6 +99,15 @@ public class ImageRegion : Region
return new ImageRegion(new Mat(SrcMat, new Rect(x, y, w, h)), x, y, this, new TranslationConverter(x, y));
}
public ImageRegion DeriveCrop(double dx, double dy, double dw, double dh)
{
var x = (int)Math.Round(dx);
var y = (int)Math.Round(dy);
var w = (int)Math.Round(dw);
var h = (int)Math.Round(dh);
return new ImageRegion(new Mat(SrcMat, new Rect(x, y, w, h)), x, y, this, new TranslationConverter(x, y));
}
public ImageRegion DeriveCrop(Rect rect)
{
return DeriveCrop(rect.X, rect.Y, rect.Width, rect.Height);
@@ -8,17 +8,4 @@ namespace BetterGenshinImpact.GameTask.Model;
/// </summary>
public class BaseTaskParam
{
public string Name { get; set; } = string.Empty;
public CancellationTokenSource Cts { get; set; }
/// <summary>
/// 针对实时触发器的操作
/// </summary>
public DispatcherTimerOperationEnum TriggerOperation { get; set; } = DispatcherTimerOperationEnum.None;
protected BaseTaskParam(CancellationTokenSource cts)
{
this.Cts = cts;
}
}
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
using BetterGenshinImpact.Helpers;
using Wpf.Ui.Violeta.Controls;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Recorder;
namespace BetterGenshinImpact.GameTask;
@@ -99,6 +100,11 @@ public class TaskRunner
await Task.Run(() => RunAsync(action));
}
public async Task RunSoloTaskAsync(ISoloTask soloTask)
{
await Task.Run(() => RunAsync(async () => await soloTask.Start(CancellationContext.Instance.Cts)));
}
public void Init()
{
if (!TaskContext.Instance().IsInitialized)
@@ -191,48 +191,6 @@ namespace BetterGenshinImpact.GameTask
return _timer;
}
/// <summary>
/// 启动独立任务
/// </summary>
public void StartIndependentTask(IndependentTaskEnum taskType, BaseTaskParam param)
{
if (!_timer.Enabled)
{
throw new Exception("请先在启动页启动BetterGI,如果已经启动请重启");
}
var maskWindow = MaskWindow.Instance();
maskWindow.Invoke(() => { maskWindow.Show(); });
if (taskType == IndependentTaskEnum.AutoGeniusInvokation)
{
AutoGeniusInvokationTask.Start((GeniusInvokationTaskParam)param);
}
else if (taskType == IndependentTaskEnum.AutoWood)
{
Task.Run(() => { new AutoWoodTask().Start((WoodTaskParam)param); });
}
else if (taskType == IndependentTaskEnum.AutoFight)
{
Task.Run(() => { new AutoFightTask((AutoFightParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoDomain)
{
Task.Run(() => { new AutoDomainTask((AutoDomainParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoTrack)
{
Task.Run(() => { new AutoTrackTask((AutoTrackParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoTrackPath)
{
Task.Run(() => { new AutoTrackPathTask((AutoTrackPathParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoMusicGame)
{
Task.Run(() => { new AutoMusicGameTask((AutoMusicGameParam)param).Start(); });
}
}
public void Dispose()
{
Stop();
@@ -1,66 +0,0 @@
// using BetterGenshinImpact.GameTask;
// using BetterGenshinImpact.Helpers.Extensions;
// using System;
//
// namespace BetterGenshinImpact.Helpers;
//
// /// <summary>
// /// 不推荐使用
// /// 请使用 GameCaptureRegion.GameRegionClick 或 GameCaptureRegion.GameRegion1080PPosClick 替代
// /// </summary>
// [Obsolete]
// public class ClickOffset
// {
// public int OffsetX { get; set; }
// public int OffsetY { get; set; }
// public double AssetScale { get; set; }
//
// // public double CaptureAreaScale { get; set; }
//
// public ClickOffset()
// {
// if (!TaskContext.Instance().IsInitialized)
// {
// throw new Exception("请先启动");
// }
// var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
// var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
// OffsetX = captureArea.X;
// OffsetY = captureArea.Y;
// AssetScale = assetScale;
// // CaptureAreaScale = TaskContext.Instance().SystemInfo.CaptureAreaScale;
// }
//
// public ClickOffset(int offsetX, int offsetY, double assetScale)
// {
// if (!TaskContext.Instance().IsInitialized)
// {
// throw new Exception("请先启动");
// }
// // CaptureAreaScale = TaskContext.Instance().SystemInfo.CaptureAreaScale;
//
// OffsetX = offsetX;
// OffsetY = offsetY;
// AssetScale = assetScale;
// }
//
// public void Click(int x, int y)
// {
// ClickExtension.Click(OffsetX + (int)(x * AssetScale), OffsetY + (int)(y * AssetScale));
// }
//
// /// <summary>
// /// 输入的x,y 注意处理缩放
// /// </summary>
// /// <param name="x"></param>
// /// <param name="y"></param>
// public void ClickWithoutScale(int x, int y)
// {
// ClickExtension.Click(OffsetX + x, OffsetY + y);
// }
//
// public void Move(int x, int y)
// {
// ClickExtension.Move(OffsetX + (int)(x * AssetScale), OffsetY + (int)(y * AssetScale));
// }
// }
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;
using System.Text.Json;
namespace BetterGenshinImpact.Helpers;
public class ExpandoObjectConverter
{
private static readonly JsonSerializerOptions _options = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static T ConvertTo<T>(dynamic source)
{
var json = JsonSerializer.Serialize(source, _options);
return JsonSerializer.Deserialize<T>(json, _options);
}
}
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more