Compare commits

..
Author SHA1 Message Date
ema bfb83c957e 修复部分组件未随主题变更颜色 #2644 2026-01-27 00:11:32 +08:00
1226 changed files with 12097 additions and 109047 deletions

No files matched your search

-270
View File
@@ -1,270 +0,0 @@
---
name: "release-note-generator"
description: "基于 BetterGI 本地 git 历史和实际 diff,按 GitHub 已发布 Releases 的中文更新日志风格生成发布说明。用于生成 Release Note、版本更新日志、从上一个非 alpha 正式版本到 HEAD 的变更汇总;不得使用 git tag 作为版本依据。"
---
# Release Note Generator
基于本地 git 历史和实际代码 diff 生成 BetterGI 发布说明。发布说明的结构、分类和措辞应贴近 GitHub 已发布 Releases 的历史风格;生成具体内容时不依赖网络,所有变更信息从本地仓库获取。
## 历史 Release 风格
已发布日志的稳定特征:
- 标题通常为 `## <version> <简短主题>`,例如 `0.61.0 原神6.6`、`0.61.2 优化`、`0.60.1 修复老问题`、`0.59 自动烹饪与BUG修复`。
- 大版本或内容较多时,标题下可有一句总览;补丁版本或内容很少时可以直接列 bullet。
- 分类标题使用产品主功能语义,而不是 Conventional Commits 类型。历史分类可以作为参考,但不是固定枚举;`实时任务`、`独立任务`、`新功能`等组织性名称不能替代更准确的主功能名称。
- 版本适配类通常放在最前面,包含新角色识别、新地图、传送点/锚点、七圣召唤元数据等。
- `其他` 分类保留,用于 UI、通知、配置、稳定性、OCR、启动器、仓库、文档等无法归入核心模块的内容。
- 条目语言偏简洁直白,可以用“新增/修复/优化/支持/更新/回滚/适配”,不需要营销化。
- PR 号与作者使用纯文本,例如 `(#3132) @haokaiyang`;多个 PR 可以写在同一括号组里,例如 `(#3101 #3108)`。
- 不输出 GitHub 自动生成的 `Contributors`、`Assets`、reaction 等区块。
## 版本边界
禁止执行或参考 `git tag`、`git describe --tags`。版本边界和输出版本号都不能使用 tag 作为依据。
从 HEAD 向后遍历提交历史,匹配**明确以版本号发布为主题的提交**:
- 提交消息必须匹配以下模式之一(大小写不敏感):
- `Update version to X.Y.Z`
- `bump version to X.Y.Z`
- `release X.Y.Z`
- `vX.Y.Z`
- 版本号正则:`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?`
- 版本号**必须是提交消息的核心主题**,不能只是顺带提及(如 "fix: update package version to 1.0.19" 这种子包更新不算)
- 排除包含 `alpha` 的提交
- 排除仅更新子包/依赖版本的提交
### 通用规则
- 统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入
- 如果 HEAD 附近已经存在当前目标版本的正式版本提交,不要把它作为边界;继续向父提交方向寻找上一个正式版本提交
- 若未找到边界版本,明确说明并使用兜底范围
## 信息采集
### 提交列表
- 使用 `git -c i18n.logOutputEncoding=utf8 -c core.quotepath=false log` 获取提交序列
- 普通提交使用 `--no-merges`,合并提交使用 `--merges` 单独获取;两组提交均限制在完全相同的统计区间内
- 格式:`--pretty=format:"%H%x00%h%x00%P%x00%an%x00%ae%x00%s%x00%b%x1e"`,字段用 `\x00` 分隔,commit 用 `\x1e` 分隔
- 分别使用 `git rev-list --count --no-merges` 和 `git rev-list --count --merges` 校验采集数量
- 读取 commit body,用于提取 `Co-authored-by`、PR、Issue、其他关联编号和补充说明
### Diff 查阅(必须)
- 对每个普通 commit 必须查阅实际 diff:`git diff <sha>^..<sha>`
- 不要把 merge commit 当作普通 commit 再次统计。对 merge commit 使用 `git show --cc --stat <sha>` 和 `git show --cc <sha>`,只识别合并时额外产生的冲突解决或手工修改
- 纯合并且没有额外用户可见改动的 merge commit 不生成日志条目;被合并分支中的普通 commit 仍按各自 diff 检查
- **不允许仅基于 commit 消息生成说明**,必须结合实际代码改动理解变更内容
- 同一功能的新增 + 后续优化/修复应合并为一条,只记"新增 xxx"
### 作者信息
- 所有作者名前统一加 `@` 前缀
- 从 commit 的 `author email` 解析标识:
- `数字[email protected]` → `@login`
- `[email protected]` → `@login`
- `[email protected]` 等非 noreply 邮箱 → `@author name`(即提交中的 `an` 字段值前加 `@`)
- 从 commit body 的 `Co-authored-by: name <email>` 提取共同作者,并按同样规则解析
- 当作者为 `huiyadanli`(含邮箱 `[email protected]`)时省略 `@author`(项目维护者,无需标注)
- 不需要调用 GitHub API,纯本地解析
## 内容提炼规则
### 强制处理顺序
必须先完成全部分析,再开始写 Release Note。禁止一边遍历 commit 一边直接生成条目,否则会把同一功能的后续提交拆成多条。
1. 查阅统计区间内所有 commit 的实际 diff,不生成最终文案
2. 将 commit 按用户可感知的功能对象归并为**功能簇**
3. 对每个功能簇还原 HEAD 时的最终状态,删除已被后续提交取代、回滚或修复的中间状态
4. 以整个功能簇为单位确定唯一分类
5. 最后才生成标题、总览和条目
commit 数量、PR 数量和作者数量都不等于日志条目数量。一个功能簇可以包含多个 commit、多个 PR 和多个作者。
### 合并策略
- 后续 commit 若是在补全、修复、优化或重构本周期内刚新增的功能,必须并入该新增功能,只描述 HEAD 时的最终能力
- 即使 PR 号、作者、提交日期或 commit 前缀不同,只要服务于同一个用户工作流、配置项、API、窗口或任务,就应合并
- 同一 issue/PR 的多个 commit 必须合并;不同 issue/PR 只要属于同一功能演进,也必须合并
- 多个 commit 修改相同核心类型、配置、入口或调用链,并且用户无法把它们视为独立功能时,必须合并
- 后续提交推翻或替代前一提交的实现时,不单列旧行为;条目使用最终行为,并合并保留相关编号与作者
- 为新功能提供输入、通信、错误提示、配置界面、兼容修复和稳定性修复的配套提交,归入该新功能,不拆成“支持”“错误提示”“协议升级”等独立条目
- 只有两项改动能够独立使用、独立描述且删除其中一项不影响另一项成立时,才允许拆成两条
- 可省略纯内部重构、CI、调试日志清理、无用户影响的格式化,但这些 commit 仍必须被检查并纳入内部覆盖记录
合并校准示例:
| 同一周期内的提交 | 正确处理 |
|------------------|----------|
| 新增桌面分身、增加 RawInput、补充 RDP 错误提示、增加组合键切换、升级通信协议 | 合并为一条“新增桌面分身”,描述最终支持的能力 |
| 新增战技赶路、修复体力判断、优化下车角度、修复按键残留 | 合并为一条“新增角色战技赶路”,不要再列三条修复或优化 |
| 指标栏快捷键先绑定日志快捷键,后改为独立快捷键 | 只描述最终的独立快捷键,并合并相关提交 |
| 重构截图与识别区域,后续修复裁剪区域导致的点击偏移 | 合并为一条识别基础设施改进,不跨分类拆成两条 |
| 页面布局统一、随后补充导航选中动画和 Footer 菜单兼容 | 合并为一条界面体验优化 |
### 分类
分类不是固定枚举,也不由目录表机械决定。先完成 commit 合并,再由 AI 根据实际 diff 判断每个功能簇所属的**产品主功能**。历史 Release 中出现过的分类只是命名参考,不是白名单。
#### 分类粒度
- 分类应对应用户能够识别的产品主功能,通常具有独立入口、独立开关、独立配置根节点、独立任务生命周期或完整工作流
- 子能力、算法、处理器、配置项和实现步骤归入其上级主功能,不单独提升为分类
- `地图追踪`是主功能;战技赶路、路径执行、地图传送、下车判定和传送识别都是其下的条目,不能分别建立分类
- `自动战斗`是主功能;战斗策略、角色识别、技能释放、战后拾取等紧密服务于战斗流程的内容归入其中
- `遮罩窗口`是主功能;准星、指标栏、日志框和窗口行为归入其中
- `自动拾取`、`自动吃药`、`自动剧情`、`秘境`、`首领讨伐`、`钓鱼`等具有独立入口或独立工作流,应直接使用自身功能名,不能统一塞入`实时任务`或`独立任务`
- 单个主功能即使只有一条日志,也允许单独建立分类;不要为了减少分类数量而使用大杂烩分类
- 不要过度细分:若某项改动离开上级功能无法独立使用或无法被用户单独识别,就保留在上级功能分类中
以下名称通常只是组织容器,不应作为默认分类:`实时任务`、`独立任务`、`新功能`、`功能优化`、`问题修复`。只有用户界面或项目历史确实把它作为独立产品概念时才允许使用。
对所有功能簇统一使用“最近的独立上级主功能”原则:从具体改动向上追溯,选择距离最近、同时具备独立产品入口或完整用户工作流的上级功能作为分类。不要选择更高层的组织容器,也不要停留在更低层的实现或子功能。
| 具体改动 | 应归入的上级主功能 | 不应使用的分类 |
|----------|--------------------|----------------|
| 战技赶路、传送定位、路径处理器 | `地图追踪` | `战技赶路`、`地图传送`、`独立任务` |
| 自动拾取黑名单、拾取触发和拾取识别 | `自动拾取` | `黑名单`、`实时任务` |
| 首领路线、首领配置和战前等待 | `首领讨伐` | `路线优化`、`独立任务` |
| 遮罩准星、指标栏和日志框 | `遮罩窗口` | `准星`、`指标栏`、`其他` |
| 桌面分身的 RawInput、RDP 错误提示和通信协议 | `桌面分身` | `RawInput`、`RDP`、`其他` |
此表只用于说明层级关系,不是分类白名单。其他功能必须由 AI 按同一原则从代码、界面和调用关系中判断。
#### AI 判定依据
按以下证据从强到弱确定主功能,允许 AI 创建历史中未出现过但符合项目语义的新分类:
1. 用户界面中的页面、卡片、设置分组、开关和任务名称
2. 独立配置对象、任务入口、服务生命周期和用户操作流程
3. 主要调用方、API 使用者和最终受影响功能
4. 类型名、命名空间和代码目录
5. commit 标题和正文
- 目录只提供线索,不能覆盖功能语义;`GameTask/Common`、共享 ViewModel、设置页和 `.csproj` 均不能直接决定分类
- 直接面向脚本开发者的 `genshin.*`、`dispatcher.*` 等公共 API 归入`JS脚本`,即使底层实现位于战斗、地图或通用目录
- 仅更新资源包或数据包版本时,根据提交说明、包用途和相邻变更判断实际主功能,不按 `.csproj` 路径归入`其他`,也不得编造本地无法确认的细节
- 横跨多个主功能的截图、识别资源、OCR、基础 UI 和捕获接口重构归入`其他`;明确服务于单一主功能时跟随该主功能
- 当一个 commit 同时包含两个能够独立使用的主功能改动时,可以拆成两条并分别分类;否则以整个功能簇的主要用户工作流为准
分类完成后反向检查:分类名必须能自然回答“这是哪个主功能的更新?”。若答案只能是一个组织容器或技术层,重新判断。
#### 遮罩相关变更的分类边界
只有变更的核心行为与**地图位置或地图标点在遮罩窗口中的展示和交互**直接相关时,才归入`地图遮罩`。通常至少需要一项地图专属证据:
- 修改 `GameTask/MapMask`、`Model/MaskMap`、`MaskMapPointService` 等地图遮罩专属模块
- diff 中的核心对象是地图坐标、地图数据源、地图标点、标签筛选、点位隐藏、小地图资源点或地图点位交互
- 修改 `MaskWindow`、`MaskWindowViewModel` 等共享文件时,同时能从属性、命令、调用链或配套文件确认改动服务于地图标点展示
以下内容即使名称或文件中含有 `Mask` / “遮罩”,也**不能仅因此**归入`地图遮罩`:
- 通用遮罩窗口能力:日志框、指标栏、准星、窗口位置、透明度、DPI、置顶、点击穿透、快捷键、UID 遮盖等,归入`遮罩窗口`
- JS 的 HTML 遮罩、`HtmlMaskWindow`、`Core/Script/Dependence/HtmlMask*`,归入`JS脚本`
- OCR、模板匹配、图像识别中的 mask/掩膜,归入其所属业务分类;无明确业务归属时放入`其他`
- 自动战斗、独立任务、实时任务内部用于识别或显示的遮罩,归入对应任务分类
- 只修改 `View/MaskWindow*`、`ViewModel/MaskWindow*`、`Core/Config/MaskWindowConfig*`、设置页或快捷键配置,不构成`地图遮罩`的充分证据
冲突时使用以下优先顺序:专属业务模块和调用链 > diff 中的功能对象 > 配置项/命令语义 > 共享文件路径 > 提交标题关键词。证据不足时放入`其他`,不要猜测为`地图遮罩`。
校准示例:
| 变更 | 正确分类 | 原因 |
|------|----------|------|
| 为遮罩窗口新增准星样式 | `遮罩窗口` | 修改的是通用遮罩窗口显示能力,与地图位置或标点无关 |
| 为遮罩指标栏增加独立快捷键 | `遮罩窗口` | 修改的是指标栏和快捷键配置,不能因“遮罩”一词归入地图遮罩 |
| 修改 HTML 遮罩资源拦截或 JS 响应 | `JS脚本` | HTML 遮罩是脚本 API 能力 |
| 增加地图遮罩标点的隐藏、筛选或数据源隔离 | `地图遮罩` | 核心对象是地图标点及其数据 |
| 为模板匹配增加颜色掩膜 | 所属业务分类或`其他` | 这是图像识别掩膜,不是地图遮罩 |
- 版本适配类命名:若能从变更或用户要求明确对应原神版本/月之版本,可用 `<月之X适配>`;否则使用 `版本适配`
- 禁止用`新功能`、`实时任务`或`独立任务`代替能够识别出的上级主功能
- 历史分类未覆盖时,由 AI 根据独立入口、配置和工作流创建新的主功能分类,分类名必须使用项目中的用户语义,不要使用 `feat/fix/refactor`
- 只有无法对应到任何独立主功能的跨模块基础设施和通用改动才放入`其他`
每条记录格式:
```
描述内容 (#编号) @author
```
- 编号和作者名均使用纯文本,不加超链接
- 当作者为 `huiyadanli` 时省略 `@author`(项目维护者,无需标注)
- 描述用自然语言,不直接复制 commit 原文
- 移除 `feat:`、`fix:` 等 Conventional Commits 前缀
- 只有 `(#3111)`、`Merge pull request #3111` 或明确的 `/pull/3111` 链接可以判定为 PR 号
- `fixes #3111`、`closes #3111`、`resolved #3111` 或明确的 `/issues/3111` 链接按 Issue 关联处理
- 无法从本地信息判断类型的裸 `#3111` 只称为“关联编号”,不得擅自标记为 PR
- 同一个编号在 subject、body 和合并信息中重复出现时只保留一次
- 多人参与的记录:`@id1 @id2`
- 合并多个 PR、Issue 或关联编号时格式为 `(#3101 #3108)`,不要写成多个分散条目
### 描述质量与长度
- 每条日志默认只写一句,正文控制在约 25~60 个中文字符;复杂的核心新增功能最多约 90 个中文字符
- 合并多个 commit 后先概括最终用户效果,不得把每个 commit 的描述用分号拼接成长句
- 每条只保留最终效果和最多 2 个关键能力;省略实现算法、内部协议、重试次数、完整配置列表和穷举式支持对象
- 描述必须准确,不缩小也不夸大;只改一个配置项时不能写成整个功能重构
- 面向用户使用功能、体验和问题现象描述;只有脚本 API 或开发者功能保留必要的技术标识符
- 纯内部重构、CI、依赖整理和无用户影响的格式化可以省略
- 总览句控制在约 60 个中文字符内,只概括最重要的 2~4 个变化
## 输出格式
输出到 `.claude/documents/ReleaseNotes-<version>.md`(文件名 ASCII)。
输出文件的版本号规则:取边界版本号的**次版本号(minor)加 1**,补丁版本归零。即 `major.(minor+1).0`。例如边界为 `0.60.1`,输出版本号为 `0.61.0`。
若用户明确指定版本号或发布主题,以用户指定为准;否则按上述规则推导。
```markdown
## <version> <版本主题>
<一句话版本主题>
### 分类名1
- 变更描述 (#PR号) @author
- 变更描述 @author
### 分类名2
- 变更描述 (#PR号) @author
### 其他
- 变更描述 @author
```
补丁版本或少量修复可以不分分类,直接输出 bullet;但如果使用分类,仍必须保留 `其他` 分类。
## 兜底验证(必须)
初稿不能直接输出。依次执行以下验证;任一项失败都必须退回功能簇合并、分类或文案阶段重写,然后重新验证。
### 分类验证
- 出现`实时任务`、`独立任务`或`新功能`时,逐条检查是否存在更准确的独立上级主功能;存在则判定失败
- `其他`中的条目只要能识别出自动拾取、钓鱼、一条龙、进入游戏等具体主功能,就判定失败并重新分类
- `其他`达到 4 条或超过全部条目的 25% 时,强制逐条重新检查;只有确属跨模块基础设施的内容才能保留
- 分类名若是子功能、算法、配置项或实现技术,而代码中存在独立上级主功能,判定失败
- 同一 commit 或功能簇包含两个独立主功能时,必须拆条;不可在一个分类中混写另一个主功能的修复
### 合并验证
- 跨分类比较全部条目;相同入口、配置、核心类型或用户工作流出现两次时,判定为未合并
- 本周期新增功能若同时存在独立的修复、优化、v2、错误提示、输入支持或协议升级条目,判定为未合并
- 后续提交只是补全新功能时,必须并入新增条目;不得因 PR、作者或提交时间不同而拆分
- merge commit 的汇总 diff 不得与其中的普通 commit 重复生成条目
### 精简验证
- 普通条目超过约 60 个中文字符、核心新增条目超过约 90 个中文字符时,重新压缩
- 一个条目出现多句、超过 2 个关键能力或明显罗列实现细节时,重新概括
- 总览句超过约 60 个中文字符或机械罗列所有分类时,重新压缩
### 最终确认
- 统计区间内所有 commit 均已检查实际 diff;无用户影响的 commit 可以不输出
- 每条内容描述 HEAD 时的最终状态,不保留被回滚、替换或修复的中间状态
- 所有相关编号和作者已合并去重,`地图遮罩`条目具备地图坐标、标点或数据源等专属证据
- `其他`分类必须存在;全部信息仅从本地 git 获取,不依赖网络
+22
View File
@@ -0,0 +1,22 @@
---
name: Bug report / 错误报告
about: Create a report to help us improve / 创建报告以帮助我们改进
title: "[bug]请补充标题内容"
labels: bug
---
<!--
请提供下述完整信息以便快速定位问题 / Please provide the following information to quickly locate the problem
-->
- 系统环境 / System Environment:
- BetterGI版本号 / BetterGI Version:
- 问题描述 / Description of the issue:
- 复现步骤 / Reproduction steps:
-74
View File
@@ -1,74 +0,0 @@
name: Bug report / 错误报告
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
title: "[bug] "
labels:
- BUG
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Checklist before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- label: 我愿意为了解决这个问题尽自己所能 / I am willing to do my part to help resolve this issue
- type: textarea
id: environment
attributes:
label: 系统环境
description: System environment,例如操作系统版本、运行时版本、显卡驱动版本
placeholder: Windows 11 24H2 (26100.3775) / .NET Desktop Runtime 8.0.15 / NVIDIA 572.83
validations:
required: true
- type: input
id: version
attributes:
label: BetterGI 版本号
description: BetterGI Version
placeholder: e.g. 0.58.0
validations:
required: true
- type: textarea
id: description
attributes:
label: 问题描述
description: Describe the actual behavior and impact
placeholder: 请描述实际出现的问题,以及这个问题对使用造成了什么影响 / Describe the actual behavior and impact
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望结果
description: Expected behavior
placeholder: 请描述你期望出现的正确行为或结果 / Describe the expected behavior or result
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
description: Reproduction steps
placeholder: |-
1. 打开…… / Open ...
2. 点击…… / Click ...
3. 出现…… / Observe ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: 日志与附件
description: Logs and attachments,可直接拖拽上传日志文件、压缩包、截图或视频
placeholder: |-
可在这里补充日志和附件说明 / Add logs and attachment notes here:
- 可直接粘贴关键日志片段 / Paste key log snippets directly
- 可拖拽上传日志文件或压缩包 / Drag and drop log files or archives
- 可拖拽上传截图、录屏或演示视频 / Drag and drop screenshots or videos
- 若附件较多,请说明对应的时间点、任务名称或异常现象 / If there are many files, explain the relevant timestamps or symptoms
- 提交前请注意移除账号、路径等隐私信息 / Remove private information before submitting
validations:
required: false
+2 -2
View File
@@ -1,9 +1,9 @@
blank_issues_enabled: false
contact_links:
- name: 官方文档 / Document
url: https://www.bettergi.com/doc.html
url: https://bgi.huiyadan.com/doc.html
about: 请在提出问题前阅读文档 / Read the document before submit the issue
- name: 常见问题 / FAQ
url: https://www.bettergi.com/faq.html
url: https://bgi.huiyadan.com/faq.html
about: 常见的用户提出的问题 / Common questions asked by users
+9
View File
@@ -0,0 +1,9 @@
---
name: I have feature requesting / 我有新功能请求
about: Your request may come as a surprise. / 你的请求也许成为惊喜
title: "[feature] "
labels: feature 功能请求
---
- Your feature requesting / 你的新功能请求
-52
View File
@@ -1,52 +0,0 @@
name: I have feature requesting / 我有功能需求
description: 提出新的功能想法 / Share a feature request
title: "[feature] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate request
required: true
- label: 我已确认当前版本中尚未提供该功能,或至少没有等价实现 / I have confirmed this feature, or an equivalent one, is not already available in the current version
required: true
- label: 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好 / I believe this request provides clear value to a broader group of users, not just my personal preference
required: true
- label: 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳 / I understand this request may not be accepted due to implementation cost, maintenance cost, or project direction
required: true
- type: textarea
id: request
attributes:
label: 功能请求
description: Feature Request
placeholder: 请简要说明你希望新增什么能力 / Briefly describe the capability you want to add
validations:
required: true
- type: textarea
id: scenario
attributes:
label: 使用场景
description: Use Case
placeholder: 这个功能要解决什么问题?在哪些场景下使用? / What problem does this feature solve, and when would it be used?
validations:
required: true
- type: textarea
id: impact
attributes:
label: 潜在影响
description: Potential Impact
placeholder: 请说明这个功能是否可能带来新的问题、维护成本、使用门槛或兼容性影响;如果没有,请填写“无” / Describe any potential downsides such as new issues, maintenance cost, usability barriers, or compatibility impact. Write "None" if there are no obvious downsides.
validations:
required: true
- type: textarea
id: extra
attributes:
label: 补充信息
description: Optional
placeholder: "可选,补充示意图、交互草图、参考链接或相关背景信息 / Optional: add mockups, interaction sketches, reference links, or other background information"
validations:
required: false
+5
View File
@@ -0,0 +1,5 @@
---
name: Feel free to express / 随便写写
about: Record something / 简单写写记录记录
---
-22
View File
@@ -1,22 +0,0 @@
name: Feel free to express / 自由描述
description: 记录你想反馈的内容 / Share general feedback
title: "[feedback] "
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复反馈 / I have searched existing issues and confirmed this is not duplicate feedback
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的反馈 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my feedback"
required: true
- type: textarea
id: description
attributes:
label: 描述
description: Description
placeholder: 请描述你想反馈的内容 / Describe what you want to share
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have a question / 我有疑问
about: Solve your problem / 解决你的疑问
title: "[question] "
labels: question
---
- Problem Description / 问题描述
- 请尽量提供问题相关的截图/日志等内容
-32
View File
@@ -1,32 +0,0 @@
name: I have a question / 我有疑问
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
title: "[question] "
labels:
- 问题咨询
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate question
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- type: textarea
id: question
attributes:
label: 问题描述
description: Problem Description
placeholder: 请清楚描述你的问题 / Clearly describe your question
validations:
required: true
- type: textarea
id: tried
attributes:
label: 已尝试内容
description: Screenshots / logs / what you already tried
placeholder: 可附上截图、日志,以及你已经尝试过的排查过程 / Add screenshots, logs, and what you have already tried
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have suggestions / 我有建议
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
title: "[suggestion] "
labels: suggestion
---
- Your suggestions / 你的建议
-32
View File
@@ -1,32 +0,0 @@
name: I have suggestions / 我有建议
description: 分享对项目的改进建议 / Share an improvement suggestion
title: "[suggestion] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate suggestion
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的建议 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my suggestion"
required: true
- type: textarea
id: suggestion
attributes:
label: 建议内容
description: Suggestion
placeholder: 请描述你的建议内容 / Describe your suggestion
validations:
required: true
- type: textarea
id: benefit
attributes:
label: 预期收益
description: Expected Benefit
placeholder: 这个建议会给用户或项目带来什么帮助? / What benefits would this suggestion bring to users or the project?
validations:
required: true
-229
View File
@@ -1,229 +0,0 @@
runtime:
languageMode: auto
dryRun: false
providers:
openAiCompatible:
enabled: true
baseUrl: https://api.openai.com/v1
model: gpt-5.4
apiStyle: responses
timeoutMs: 30000
issues:
autoProcessing:
skipCreatedBefore: auto
validation:
enabled: true
fallbackTemplateKey: normal
commentAnchor: issue-bot:validation
templates:
- key: bug
detect:
markers:
- bug
titlePrefixes:
- "[bug]"
requiredSections:
- id: environment
aliases:
- 系统环境
- System Environment
- id: version
aliases:
- BetterGI 版本号
- BetterGI Version
- id: description
aliases:
- 问题描述
- Description of the issue
- id: steps
aliases:
- 复现步骤
- Reproduction steps
labels:
whenValid:
- BUG
whenInvalid:
- 需要更多信息
- key: feature
detect:
markers:
- feature
titlePrefixes:
- "[feature]"
requiredSections:
- id: request
aliases:
- 功能请求
- Feature Request
- id: scenario
aliases:
- 使用场景
- Use Case
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: suggestion
detect:
markers:
- suggestion
titlePrefixes:
- "[suggestion]"
requiredSections:
- id: suggestion
aliases:
- 建议内容
- Suggestion
- id: benefit
aliases:
- 预期收益
- Expected Benefit
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: question
detect:
markers:
- question
titlePrefixes:
- "[question]"
requiredSections:
- id: question
aliases:
- 问题描述
- Problem Description
- id: tried
aliases:
- 已尝试内容
- What I Tried
labels:
whenValid:
- 问题咨询
whenInvalid:
- 需要更多信息
- key: normal
detect:
markers:
- normal
titlePrefixes:
- "[feedback]"
- "[normal]"
requiredSections:
- id: description
aliases:
- 描述
- Description
labels:
whenValid: []
whenInvalid:
- 需要更多信息
duplicateDetection:
enabled: true
bypassLabels:
- 跳过重复检测
duplicateLabel: 重复
searchResultLimit: 50
candidateLimit: 20
aiReviewMaxCandidates: 3
thresholds:
exact: 0.995
highConfidence: 0.93
reviewMin: 0.82
similarityComment:
enabled: false
commentAnchor: issue-bot:similar-issues
minScore: 0.3
maxCandidates: 3
labeling:
enabled: true
autoCreateMissing: true
managed:
- BUG
- 功能建议
- 问题咨询
- 需要更多信息
- 重复
definitions:
BUG:
color: d73a4a
description: 程序存在缺陷或异常行为。
功能建议:
color: a2eeef
description: 新功能建议或现有功能改进。
问题咨询:
color: d876e3
description: 使用问题、求助或咨询。
# 需要更多信息:
# color: fbca04
# description: 当前 Issue 缺少必要信息。
重复:
color: cfd3d7
description: 已存在相同或高度相似的问题。
keywordRules: []
aiClassification:
enabled: false
maxLabels: 3
minConfidence: 0.65
include: []
exclude:
- BUG
- 功能请求
- 重复
- 不会修复
- 使用问题
- 需要帮助
- 已完成
- 未解决
- 待确认
- P0
- P1
- 需要文档
- 优化点
- 急急急
prompt: 优先给 BetterGI Issue 选择能反映具体功能模块、子系统或使用场景的标签,例如一条龙、调度器、脚本、设置项、地图追踪;避免只选择宽泛的流程或状态标签。
sourceRepository:
owner: babalae
repo: better-genshin-impact
aiHelp:
enabled: true
triggerLabels: []
commentAnchor: issue-bot:ai
projectContext:
enabled: true
includeRepositoryMetadata: true
includeReadme: true
readmeMaxChars: 3000
profile:
name: BetterGI
aliases:
- BGI
- Better Genshin Impact
summary: BetterGI is a desktop automation assistant for Genshin Impact.
techStack:
- C#
- WPF
- .NET
commands:
enabled: true
mentions:
- "@bot"
- "@bettergi-repo-bot"
access: collaborators
fix:
enabled: true
commentAnchor: issue-bot:fix
refresh:
enabled: true
pullRequests:
review:
enabled: false
labeling:
enabled: false
summary:
enabled: false
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan_release_note:
if: github.repository_owner == 'babalae'
runs-on: macos-latest
steps:
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan:
if: github.repository_owner == 'babalae'
runs-on: windows-latest
steps:
- name: 📥 Download release
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
repository: zaodonganqi/bettergi-script-web
repository: A-Little-AnQi/bettergi-script-web
- uses: actions/setup-node@v4
with:
node-version: 20
-55
View File
@@ -1,55 +0,0 @@
name: Repo Bot
on:
issues:
types:
- opened
- edited
- reopened
- labeled
issue_comment:
types:
- created
- edited
jobs:
repo-bot:
runs-on: ubuntu-latest
permissions:
issues: write
contents: read
steps:
- name: Detect GitHub App configuration
id: auth-mode
shell: bash
env:
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
run: |
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
echo "use_app=true" >> "$GITHUB_OUTPUT"
else
echo "use_app=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Create GitHub App token
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
- name: Run Repo Bot
uses: ddaodan/bettergi-github-bot@v1
env:
GITHUB_TOKEN: ${{ github.token }}
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
with:
config-path: .github/repo-bot.yml
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
+3 -12
View File
@@ -9,7 +9,6 @@
*.userprefs
# Build results
Build/
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
@@ -31,16 +30,8 @@ github_actions_cache/
# Rider
.idea
.trae
.claude
CLAUDE.md
__pycache__/
# Trae
.trae/*
!.trae/rules/
!.trae/rules/**
!.trae/skills/
!.trae/skills/**
# Claude
.claude/*
-86
View File
@@ -1,86 +0,0 @@
本项目使用了 WPF-UI、 CommunityToolkit.Mvvm、Microsoft.Xaml.Behaviors.Wpf 来实现 MVVM 架构。在编写代码的时候请注意:
### 主要依赖框架
#### UI 框架
- **WPF-UI (4.0.2)** - 现代化 WPF UI 框架
- **gong-wpf-dragdrop(3.2.1)** - 拖拽框架
#### MVVM 框架
- **CommunityToolkit.Mvvm (8.2.2)** - 微软官方 MVVM 工具包
- 所有 ViewModel 必须继承自 `ObservableObject`
- 使用 `[ObservableProperty]` 特性自动生成属性
- 使用 `[RelayCommand]` 特性自动生成命令
- **Microsoft.Xaml.Behaviors.Wpf(1.1.122)** - WPF 行为扩展库
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
### 基础架构
### ViewModel 编写规范
1. **继承规则**
```csharp
public partial class ExampleViewModel : ViewModel
{
[ObservableProperty]
private string _title = "";
[RelayCommand]
private void DoSomething()
{
// 实现逻辑
}
}
```
2. **属性命名**
- 私有字段使用下划线前缀: `_fieldName`
- 公共属性使用 PascalCase: `PropertyName`
- 使用 `[ObservableProperty]` 自动生成属性
3. **命令实现**
- 使用 `[RelayCommand]` 特性
- 异步命令使用 `[RelayCommand]` + `async Task`
### View 编写规范
1. **代码后置**
```csharp
public partial class ExamplePage : UserControl
{
public ExampleViewModel ViewModel { get; }
public ExamplePage(ExampleViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
InitializeComponent();
}
}
```
2. **XAML 绑定**
- 使用 `{Binding}` 语法绑定 ViewModel 属性
- 命令绑定: `Command="{Binding ExampleCommand}"`
- 避免在 XAML 中编写复杂逻辑
### 依赖注入规范
1. **服务注册**
```csharp
// 在 App.xaml.cs 中注册
services.AddView<ExamplePage, ExampleViewModel>();
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
-62
View File
@@ -1,62 +0,0 @@
---
name: "github-issue-triage"
description: "Reads GitHub issues, extracts reporter details and <=10MB attachments/images, then decides discuss/research vs direct fix vs implementation plan. Invoke when user shares an issue URL."
---
# GitHub Issue Triage
用于处理 GitHub issue 链接,并在结合当前仓库代码后给出执行路径。
## 触发时机
- 用户提供 GitHub issue URL,并希望你分析内容后继续行动
- 需要先读取 issue 创建者信息、附件或图片,再决定如何推进
- 需要判断是先讨论研究、直接修复,还是先制定方案
## 输入
- 必填:GitHub issue URL,例如 `https://github.com/<owner>/<repo>/issues/<id>`
- 可选:用户额外上下文(复现步骤、期望行为、优先级)
## 执行流程
1. 读取 issue 内容
- 获取标题、正文、标签、状态、创建者、创建时间
- 提取创建者在 issue 中提供的关键信息(正文 + 创建者本人评论)
- 区分“创建者信息”与“其他参与者讨论”
2. 收集附件与图片(限制 10MB)
- 从 issue 正文和创建者评论中提取附件/图片链接
- 对每个链接获取文件大小与类型,只有 `<= 10MB` 才下载
- 优先下载图片(png/jpg/jpeg/webp/gif)与问题复现相关附件
- 记录已下载与跳过原因(超限、类型不符、不可访问)
3. 结合代码库研判
- 先做高层语义检索定位相关模块,再做符号/关键字精查
- 找到与 issue 直接相关的代码路径、入口点、可能影响范围
- 判断是否已有类似问题处理逻辑、开关、兜底或已知限制
4. 路径决策
- 讨论研究问题:信息不足、无法稳定复现、需求存在歧义、外部依赖阻塞
- 直接修复问题:根因清晰、改动范围可控、验收标准明确
- 计划方案:涉及跨模块改造、兼容性权衡、需要分阶段实施
5. 执行动作
- 若“直接修复问题”:直接修改代码并完成必要验证
- 若“计划方案”:输出分步计划、影响面、风险与验证策略
- 若“讨论研究问题”:给出需要补充的信息与建议实验步骤
## 输出格式
- Issue 摘要:标题、创建者、关键诉求、复现线索
- 创建者信息提炼:仅保留创建者提供的有效信息
- 附件处理结果:下载清单(<=10MB)与跳过清单(含原因)
- 代码关联分析:相关模块、关键函数、潜在根因
- 决策结论:讨论研究 / 直接修复 / 计划方案
- 下一步:立即执行项
## 质量要求
- 必须优先依据创建者提供的信息,不被无关评论干扰
- 必须在代码层面给出证据,不做纯主观结论
- 决策应可执行,并且与当前仓库结构一致
@@ -1,142 +0,0 @@
---
name: "release-note-generator"
description: "Generates release notes from git commits/diffs and outputs one Chinese MD file. Invoke when user asks for release notes bounded by previous non-alpha version."
---
# Release Note Generator
用于基于当前仓库的 git 历史自动生成发布说明,确保不遗漏提交,并为每条变更记录追加提交人的 GitHub ID(`@id`)。默认输出一个 Markdown 文件到 `.trae/documents` 目录:变更内容。
## 触发时机
- 用户要求生成 Release Note / 更新日志
- 用户要求基于最近提交和实际代码变更做汇总
- 用户要求以“上一个非 alpha 版本”为边界统计变更
## 输入约定
- 默认分支当前 `HEAD`
- 版本边界规则:从最新提交向后遍历,遇到“提交信息包含版本号且不含 alpha”的最近一个提交作为边界
- 若用户指定分支、Tag 或版本正则,优先使用用户指定
- 未指定时,默认输出文档路径为:`.trae/documents/release_notes-<version>.md`
## 实战经验(本项目)
- 不直接依赖终端长输出:大量 `git log` 在终端中容易被截断,导致误判“提交缺失”
- 不用 `|` 等普通分隔符解析:提交标题可能包含分隔符,必须使用 NUL 分隔(`\x00`)保证可解析
- 统一 UTF-8:PowerShell 下中文提交信息可能乱码,调用 git 时需显式设置输出编码
- 避免在 `RunCommand` 的内联脚本中直接硬编码中文常量(标题、分类名、文件名):在 Windows/PowerShell 链路中可能被替换为 `?`
- 发布文件名使用 ASCII:不要在文件名中使用中文(如 `ReleaseNotes-变更内容-<version>.md`),否则编码异常时会变成非法字符 `?` 导致写文件失败
- 中文文案仅放在 Markdown 内容里,并在写入后做一次乱码校验:若出现 `???`、`### ??` 等占位符,必须重新生成
- 明确分支范围:优先使用 `HEAD` 可达历史,必要时用 `--first-parent` 辅助核对发布主线
- 先计数再明细:先取 `rev-list --count`,再逐条采集,最后做数量一致性校验
- 版本边界要可回退:目标版本不存在时,自动回退到最近可识别的“上一非 alpha 版本”并在结果中声明
## 日志采集方式(强制)
- 必须使用 Python 脚本拉取 commit 与 diff,不直接用终端拼接命令产出最终结果
- Python 内通过 `subprocess.run([...], check=True, capture_output=True, text=True, encoding="utf-8", errors="replace")` 调 git
- git 命令需附加编码参数:`-c i18n.logOutputEncoding=utf8 -c core.quotepath=false`
- 提交元数据推荐格式:`--pretty=format:%H%x00%h%x00%an%x00%ae%x00%ad%x00%s%x00`,按 `\x00` 解析
- diff 证据至少包含:
- 区间总览:`git diff --shortstat <base>..<head>`
- 文件变更:`git diff --name-status <base>..<head>`
- 行级统计:`git diff --numstat <base>..<head>`
- 必要时单提交详情:`git show --name-status --numstat --format= <sha>`
- Python 脚本需输出结构化数据(JSON/对象)后再生成 release note 文本
- 若通过终端执行 Python,优先将中文文案写成 `\\uXXXX` 形式或由程序运行期拼接,避免命令传输阶段损坏字符
## 执行流程
1. 获取提交序列(防遗漏)
- 从 `HEAD` 向后扫描提交,定位边界提交 `boundary_commit`
- 使用可识别 SemVer 的正则提取版本号(例如 `v1.2.3`、`1.2.3`)
- 判断“非 alpha”时使用大小写不敏感匹配:提交信息不包含 `alpha`
- 生成统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入变更列表
- 使用 Python 执行 git 并解析 NUL 分隔结果,禁止依赖终端显示内容做解析
2. 完整性校验(必须)
- 先取区间提交总数 `N`
- 再逐条收集区间内每个 commit 的详情
- 输出前校验“已收集条数 == N”,不一致则重新拉取,直到一致
- 若存在 merge,额外给出 `--first-parent` 视角的校验结果,避免发布主线理解偏差
3. 采集每条提交的证据
- 提交元数据:hash、标题、作者、时间
- 实际改动:由 Python 采集 `--name-status`、`--numstat`、`--shortstat` 与必要 diff 片段
- 将提交按功能模块归类(如 UI、任务、配置、脚本、基础设施等)
4. 提炼发布内容
- 先按用户指定分类规则归类;若未指定,使用更接近 GitHub Releases 页面的默认分类顺序:
1) 新功能
2) 地图遮罩
3) 独立任务
4) JS相关
5) 其他
- 分类名尽量贴近业务语义:例如“地图追踪”“自动剧情”“七圣召唤”等可作为二级小节并入对应一级分类
- 无法稳定归类的小变更统一放入“其他”
- 每条摘要都要可追溯到至少一个 commit
- 识别“变更最大点”并在首屏摘要中突出展示
- 主体正文只展示可读的变更描述,不在分类正文中堆叠 hash
- 完整提交清单放在文末,避免正文可读性下降
- 输出文案需去掉 Conventional Commits 前缀:至少移除 `feat:`、`fix:`(区分大小写不敏感),再写入分类正文与完整提交清单
5. 生成提交人 GitHub ID(逐条记录追加 `@id`)
- 必须以“当前方式”解析:对区间内每个 commit 逐条调用 GitHub 提交接口,禁止仅依赖本地 `author name`:
- 接口:`https://api.github.com/repos/<owner>/<repo>/commits/<sha>`
- 请求头至少包含:`Accept: application/vnd.github+json`、`User-Agent: <custom>`
- 解析顺序固定:优先 `author.login`,为空时取 `committer.login`
- 必须保证覆盖全量区间提交:
- 对每个 SHA 单独请求并记录结果
- 输出前校验“已解析 login 数 == 区间提交数”,不一致则进入回退链
- 回退链(仅当 API 某条未命中时):
- 先用“同区间内已解析结果”做映射回填(同 author email / 同 author name)
- 再解析 GitHub noreply 邮箱:
- `[email protected]` -> `@login`
- `[email protected]` -> `@login`
- 再回退 `.atom`:`https://github.com/<owner>/<repo>/commits/<branch>.atom` 按 SHA 匹配 `<entry>` 获取 `<author><name>`
- 最后才允许作者名标准化兜底,并明确标记为推断
- 为每条变更记录绑定对应作者的 `@id`
- 若一条汇总涉及多个 commit,按去重后多作者格式追加:`@id1 @id2`
## 输出格式(强制,需贴近 GitHub Releases 风格)
必须产出 1 个文件:
1. 变更内容文件(全中文)
- 文件路径:`.trae/documents/ReleaseNotes-<version>.md`(文件名必须 ASCII)
- 内容结构(推荐模板):
- 一级标题:`## <version> <版本主题>`(示例:`## 0.58 月之五适配`)
- 开场一句话:版本背景或问候语(可选,1~2 句)
- 分类正文:按以下顺序输出存在内容的分类:
- `新功能`
- `地图遮罩`
- `独立任务`
- `JS相关`
- `其他`(必须保留,即使只有 1 条)
- 分类内每条为单行 bullet,格式:
- `<变更描述> (#PR号可选) @githubId`
- 若某条由多人提交,使用:`@id1 @id2`
- 文末追加“完整提交清单”(倒序,不能缺项,每条带 `@id`)
- 在标题下方补充统计信息:`边界提交 / 区间 / 提交数 / shortstat`
补充要求:
- 变更内容文件必须全中文
- 仅内容全中文;文件名必须为 ASCII,避免 Windows 下出现 `?` 非法路径
- 风格贴近 GitHub Releases:简洁分段、先讲用户可感知变化,再给完整清单
- 正文优先使用自然语言,不直接复制 commit 原文
- 分类不允许缺失“其他”
- 内容中不保留 `feat:`、`fix:` 前缀
- 生成后必须执行乱码检查:若命中 `\\?{2,}` 或 `### \\?+`,视为失败并重生成
## 质量门槛
- 不允许遗漏区间内任意 commit
- 不允许仅基于 commit 标题,必须结合实际代码改动
- 每条变更记录必须带作者 `@id`,不允许只在末尾集中列出
- 必须通过 Python 脚本获取日志与 diff,禁止直接依赖终端长输出结果
- 解析 `@id` 时必须逐条调用 GitHub Commit API(`/repos/<owner>/<repo>/commits/<sha>`),不得以本地昵称直接替代
- 未找到边界版本时,必须明确说明并给出当前采用的兜底范围
- 分类默认遵循“新功能 / 地图遮罩 / 独立任务 / JS相关 / 其他”,其中“其他”必须出现
- Markdown 文件必须实际落盘到仓库中的 `.trae/documents` 目录
- 不允许输出出现乱码占位符(如 `???`、`??` 分类名);发现即判定为不合格
-113
View File
@@ -1,113 +0,0 @@
本项目使用了 WPF-UI、 CommunityToolkit.Mvvm、Microsoft.Xaml.Behaviors.Wpf 来实现 MVVM 架构。在编写代码的时候请注意:
### 主要依赖框架
#### UI 框架
- **WPF-UI (4.0.2)** - 现代化 WPF UI 框架
- **gong-wpf-dragdrop(3.2.1)** - 拖拽框架
#### MVVM 框架
- **CommunityToolkit.Mvvm (8.2.2)** - 微软官方 MVVM 工具包
- 所有 ViewModel 必须继承自 `ObservableObject`
- 使用 `[ObservableProperty]` 特性自动生成属性
- 使用 `[RelayCommand]` 特性自动生成命令
- **Microsoft.Xaml.Behaviors.Wpf(1.1.122)** - WPF 行为扩展库
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
### 基础架构
### ViewModel 编写规范
1. **继承规则**
```csharp
public partial class ExampleViewModel : ViewModel
{
[ObservableProperty]
private string _title = "";
[RelayCommand]
private void DoSomething()
{
// 实现逻辑
}
}
```
2. **属性命名**
- 私有字段使用下划线前缀: `_fieldName`
- 公共属性使用 PascalCase: `PropertyName`
- 使用 `[ObservableProperty]` 自动生成属性
3. **命令实现**
- 使用 `[RelayCommand]` 特性
- 异步命令使用 `[RelayCommand]` + `async Task`
### View 编写规范
1. **代码后置**
```csharp
public partial class ExamplePage : UserControl
{
public ExampleViewModel ViewModel { get; }
public ExamplePage(ExampleViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
InitializeComponent();
}
}
```
2. **XAML 绑定**
- 使用 `{Binding}` 语法绑定 ViewModel 属性
- 命令绑定: `Command="{Binding ExampleCommand}"`
- 避免在 XAML 中编写复杂逻辑
### 依赖注入规范
1. **服务注册**
```csharp
// 在 App.xaml.cs 中注册
services.AddView<ExamplePage, ExampleViewModel>();
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
## Code Review Rules
### Output language
- 必须使用简体中文输出代码审查结果。
- 问题标题、问题描述、影响分析和修复建议必须使用中文。
- 类名、方法名、变量名、文件路径、代码片段和错误消息保持原文。
- 专业术语第一次出现时可以采用“中文(English)”格式。
### Review priorities
- 优先检查可能造成崩溃、死锁、资源泄漏和数据竞争的问题。
- 重点检查异步任务、CancellationToken、线程切换和 STA UI 线程使用。
- 重点检查 Mat、Bitmap、Stream、CancellationTokenSource 等 IDisposable 对象是否正确释放。
- 检查游戏输入、截图和多实例场景是否存在共享状态冲突。
- 不要只提出风格问题,除非它会影响正确性、可维护性或性能。
### Finding format
每个问题按以下结构输出:
1. 严重程度
2. 问题位置
3. 问题原因
4. 可能造成的影响
5. 推荐修复方案
+2 -17
View File
@@ -1,4 +1,4 @@
<Application x:Class="BetterGenshinImpact.App"
<Application x:Class="BetterGenshinImpact.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
@@ -13,20 +13,10 @@
<vio:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
<ResourceDictionary Source="/View/Controls/Drawer/DrawerStyles.xaml" />
<ResourceDictionary Source="/View/Controls/Markdown/Resources/MarkdownStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- ===== 字体 ===== -->
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<!-- ===== 设计令牌 ===== -->
<CornerRadius x:Key="ControlCornerRadius">6</CornerRadius>
<Thickness x:Key="PagePadding">48,20,48,28</Thickness>
<!-- ===== 全局 Converter ===== -->
<bgivc:DomainNameToCascadingItemConverter x:Key="DomainNameConverter" />
<bgivc:AutoBossNameToCascadingItemConverter x:Key="AutoBossNameConverter" />
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
@@ -34,11 +24,6 @@
<bgivc:NotNullConverter x:Key="NotNullConverter" />
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
<bgivc:TrConverter x:Key="TrConverter" />
<bgivc:AdaptiveUniformGridColumnsConverter x:Key="AdaptiveUniformGridColumnsConverter" />
<!-- ===== 全局 TextBox 安全剪贴板 ===== -->
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
@@ -47,4 +32,4 @@
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
</Application>
+18 -90
View File
@@ -7,24 +7,20 @@ using System.Windows;
using System.Windows.Threading;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Helpers.Win32;
using BetterGenshinImpact.Hutao;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.ChildSession;
using BetterGenshinImpact.Service.Instance;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.Service.Notifier;
using BetterGenshinImpact.View;
using BetterGenshinImpact.View.Pages;
using BetterGenshinImpact.View.Windows;
using BetterGenshinImpact.ViewModel;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.ViewModel.Pages.View;
using BetterGenshinImpact.ViewModel.Windows;
using LazyCache;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
@@ -54,9 +50,10 @@ public partial class App : Application
private static readonly IHost _host = Host.CreateDefaultBuilder()
.CheckIntegration()
.UseElevated()
.UseInstanceIpc()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureServices((context, services) =>
.ConfigureServices(
(context, services) =>
{
// 提前初始化配置
var configService = new ConfigService();
@@ -66,61 +63,34 @@ public partial class App : Application
var logFolder = Path.Combine(AppContext.BaseDirectory, "log");
Directory.CreateDirectory(logFolder);
var logFile = Path.Combine(logFolder, "better-genshin-impact.log");
var instanceContext = InstanceBootstrap.Current.Context;
var instanceIdentity =
$"{instanceContext.InstanceType}:S{instanceContext.WindowsSessionId}:P{instanceContext.ProcessId}:T{instanceContext.StartedAt.ToUnixTimeMilliseconds()}";
var richTextBox = new RichTextBoxImpl();
services.AddSingleton<IRichTextBox>(richTextBox);
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.Logger(fileLoggerConfiguration => fileLoggerConfiguration
.Enrich.WithProperty("BgiInstance", instanceIdentity)
.WriteTo.File(logFile,
outputTemplate:
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] [{BgiInstance}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
rollingInterval: RollingInterval.Day,
shared: true,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21)))
.WriteTo.Console(outputTemplate:
.WriteTo.File(logFile,
outputTemplate:
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21))
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
if (all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true })
if (all.MaskWindowConfig.MaskEnabled)
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
Log.Logger = loggerConfiguration.CreateLogger();
services.AddSingleton<IMissingTranslationReporter, SupabaseMissingTranslationReporter>();
services.AddSingleton<ITranslationService, JsonTranslationService>();
services.AddLogging(c => c.AddSerilog());
// if ("zh-Hans".Equals(all.OtherConfig.UiCultureInfoName, StringComparison.OrdinalIgnoreCase))
// {
// services.AddLogging(c => c.AddSerilog());
// }
// else
// {
// services.AddLogging(logging =>
// {
// logging.ClearProviders();
// logging.SetMinimumLevel(LogLevel.Debug);
// logging.AddFilter("Microsoft", LogLevel.Warning);
// logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);
// logging.Services.AddSingleton<ILoggerProvider, TranslatingSerilogLoggerProvider>();
// });
// }
services.AddLocalization();
services.AddNavigationViewPageProvider();
services.AddSingleton(InstanceBootstrap.Current);
services.AddSingleton<InstanceService>();
services.AddHostedService(sp => sp.GetRequiredService<InstanceService>());
// App Host
services.AddHostedService<ApplicationHostService>();
// Page resolver service
@@ -134,9 +104,6 @@ public partial class App : Application
// Main window with navigation
services.AddView<INavigationWindow, MainWindow, MainWindowViewModel>();
services.AddSingleton<NotifyIconViewModel>();
services.AddSingleton<ChildSessionService>();
services.AddTransient<ChildSessionWindowViewModel>();
services.AddTransient<ChildSessionWindow>();
// Views
services.AddView<HomePage, HomePageViewModel>();
@@ -152,8 +119,6 @@ public partial class App : Application
services.AddView<MapPathingPage, MapPathingViewModel>();
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
services.AddSingleton<PathingConfigViewModel>();
services.AddSingleton<IBannerImageService, BannerImageService>();
services.AddTransient<WebImageInputViewModel>();
// services.AddView<PathingConfigView, PathingConfigViewModel>();
services.AddView<KeyBindingsSettingsPage, KeyBindingsSettingsPageViewModel>();
@@ -169,16 +134,12 @@ public partial class App : Application
// services.AddSingleton<TcgViewModel>();
// My Services
services.AddSingleton<DirectInputMonitor>();
services.AddSingleton<RawInputMonitor>();
services.AddSingleton<IRelativeMouseInputMonitorFactory, RelativeMouseInputMonitorFactory>();
services.AddSingleton<OverlayMetricsService>();
services.AddSingleton<CustomHtmlMaskService>();
services.AddSingleton<TaskTriggerDispatcher>();
services.AddSingleton<NotificationService>();
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
services.AddSingleton<NotifierManager>();
services.AddSingleton<IScriptService, ScriptService>();
services.AddSingleton<HutaoNamedPipe>();
services.AddSingleton<BgiOnnxFactory>();
services.AddSingleton<OcrFactory>();
services.AddMemoryCache();
@@ -186,15 +147,14 @@ public partial class App : Application
services.AddSingleton<MemoryFileCache>();
services.AddSingleton<IMihoyoMapApiService, MihoyoMapApiService>();
services.AddSingleton<IKongyingTavernApiService, KongyingTavernApiService>();
services.AddSingleton<IHoYoLabMapApiService, HoYoLabMapApiService>();
services.AddSingleton<IMaskMapPointService, MaskMapPointService>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
I18N.Culture = new CultureInfo("zh-Hans"); // #1846
}
)
@@ -232,7 +192,6 @@ public partial class App : Application
/// </summary>
protected override async void OnStartup(StartupEventArgs e)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
// Wine 平台适配
WinePlatformAddon.ApplyApplicationConfig();
base.OnStartup(e);
@@ -248,19 +207,10 @@ public partial class App : Application
}
catch (Exception ex)
{
// DEBUG only, no overhead
Debug.WriteLine(ex);
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
try
{
HandleException(ex);
}
catch (Exception ex2)
{
Debug.WriteLine(ex2);
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
}
if (Debugger.IsAttached)
{
Debugger.Break();
@@ -276,13 +226,12 @@ public partial class App : Application
base.OnExit(e);
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
Log.CloseAndFlush();
// 释放控制台窗口
ConsoleHelper.FreeConsoleWindow();
}
@@ -306,12 +255,6 @@ public partial class App : Application
{
try
{
// 忽略V8引擎释放后pending的Task回调抛出的异常
if (IsV8EngineReleasedException(e.Exception))
{
return;
}
HandleException(e.Exception);
}
catch (Exception ex)
@@ -324,21 +267,6 @@ public partial class App : Application
}
}
private static bool IsV8EngineReleasedException(Exception? ex)
{
while (ex != null)
{
if (ex.Message?.Contains("V8 object has been released") == true)
{
return true;
}
ex = ex.InnerException;
}
return false;
}
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
+1 -3
View File
@@ -1,7 +1,5 @@
using System.Windows;
using System.Windows.Media;
using System.Runtime.CompilerServices;
[assembly: DisableDpiAwareness]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: InternalsVisibleTo("BetterGenshinImpact.UnitTest")]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
+14 -40
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.63.0</Version>
<Version>0.55.2-alpha.1</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -43,21 +43,18 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.20" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.29" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.10" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="DeviceId" Version="6.9.0" />
<PackageReference Include="DeviceId.Windows" Version="6.9.0" />
<PackageReference Include="DeviceId.Windows.Wmi" Version="6.9.0" />
<PackageReference Include="Emoji.Wpf" Version="0.3.4" />
<PackageReference Include="HungarianAlgorithm" Version="2.3.5" />
<PackageReference Include="LibGit2Sharp" Version="0.31.0" />
<PackageReference Include="LazyCache" Version="2.4.0" />
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.6" />
<PackageReference Include="MailKit" Version="4.16.0" />
<PackageReference Include="Markdig" Version="1.3.2" />
<PackageReference Include="MailKit" Version="4.14.0" />
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
@@ -70,7 +67,7 @@
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.21.0" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="MimeKit" Version="4.16.0" />
<PackageReference Include="MimeKit" Version="4.14.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
@@ -80,7 +77,6 @@
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="NCalc" Version="6.2.0" />
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
<PackageReference Include="Semver" Version="3.0.0" />
@@ -88,18 +84,17 @@
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<!-- <PackageReference Include="supabase-csharp" Version="0.16.2" />-->
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
<PackageReference Include="XamlAnimatedGif" Version="2.3.1" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.3.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.3" />
<PackageReference Include="WPF-UI" Version="4.2.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.2.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.2.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.2.0.1" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
@@ -115,9 +110,6 @@
</ItemGroup>
<ItemGroup>
<None Update="GameTask\**\Recognition.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Assets\Map\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
@@ -133,13 +125,7 @@
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\CharacterDevelopment\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoFishing\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\LogParse\Assets\**">
@@ -157,7 +143,7 @@
<None Update="GameTask\AutoSkip\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoSkip\Assets\*.json">
<None Update="GameTask\AutoSkip\Assets\hangout.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoTrackPath\Assets\tp.json">
@@ -190,9 +176,6 @@
<None Update="GameTask\QuickBuy\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\QuickClaimReward\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\UseRedeemCode\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -211,15 +194,6 @@
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoBoss\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\I18n\en.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
@@ -1,592 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
namespace BetterGenshinImpact.Core.BgiVision;
public sealed class BvFlow
{
private readonly BvPage _page;
private readonly BvFlowServices _services;
private readonly List<BvFlowStep> _steps = [];
private readonly object _syncRoot = new();
private bool _hasSteps;
private bool _hasStarted;
private int _isRunning;
internal int DefaultTimeout { get; private set; }
internal int DefaultRetryInterval { get; private set; }
internal BvFlow(BvPage page, int defaultTimeout, int defaultRetryInterval)
: this(page, defaultTimeout, defaultRetryInterval, BvFlowServices.Create(page))
{
}
internal BvFlow(BvPage page, int defaultTimeout, int defaultRetryInterval, BvFlowServices services)
{
_page = page;
_services = services;
DefaultTimeout = ValidatePositive(defaultTimeout, nameof(defaultTimeout));
DefaultRetryInterval = ValidatePositive(defaultRetryInterval, nameof(defaultRetryInterval));
}
public BvFlow WithDefaultTimeout(int milliseconds)
{
var timeout = ValidatePositive(milliseconds, nameof(milliseconds));
lock (_syncRoot)
{
EnsureDefaultsCanChange();
DefaultTimeout = timeout;
}
return this;
}
public BvFlow WithDefaultRetryInterval(int milliseconds)
{
var retryInterval = ValidatePositive(milliseconds, nameof(milliseconds));
lock (_syncRoot)
{
EnsureDefaultsCanChange();
DefaultRetryInterval = retryInterval;
}
return this;
}
public BvFlowAction Do(dynamic action)
{
ArgumentNullException.ThrowIfNull(action);
return CreateAction("Do", async _ =>
{
object? result;
try
{
result = action is Delegate callback ? callback.DynamicInvoke() : action();
}
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
if (result is Task task)
{
await task;
}
});
}
public BvFlowAction KeyPress(string key)
{
var virtualKey = User32Helper.ToVk(key);
return CreateAction($"KeyPress({key})", _ =>
{
_services.KeyPress(virtualKey);
return Task.CompletedTask;
});
}
public BvFlowAction Click()
{
return CreateImplicitPointAction("Click(previous)", _services.LeftClick);
}
public BvFlowAction Click(double x, double y)
{
return CreatePointAction($"Click({x}, {y})", x, y, _services.LeftClick);
}
public BvFlowAction RightClick()
{
return CreateImplicitPointAction("RightClick(previous)", _services.RightClick);
}
public BvFlowAction RightClick(double x, double y)
{
return CreatePointAction($"RightClick({x}, {y})", x, y, _services.RightClick);
}
public BvFlowAction MiddleClick()
{
return CreateImplicitPointAction("MiddleClick(previous)", _services.MiddleClick);
}
public BvFlowAction MiddleClick(double x, double y)
{
return CreatePointAction($"MiddleClick({x}, {y})", x, y, _services.MiddleClick);
}
public BvFlowAction MoveTo()
{
return CreateImplicitPointAction("MoveTo(previous)", _services.MoveTo);
}
public BvFlowAction MoveTo(double x, double y)
{
return CreatePointAction($"MoveTo({x}, {y})", x, y, _services.MoveTo);
}
public BvFlowAction Drag(double fromX, double fromY, double toX, double toY, int duration = 300)
{
ValidatePositive(duration, nameof(duration));
return CreateAction($"Drag({fromX}, {fromY}, {toX}, {toY})",
_ => _services.Drag(fromX, fromY, toX, toY, duration));
}
public BvFlowAction DragTo(double toX, double toY, int duration = 300)
{
ValidatePositive(duration, nameof(duration));
return CreateAction($"DragTo({toX}, {toY})", context =>
{
var (fromX, fromY) = context.GetLastMatchCenter();
return _services.Drag(fromX, fromY, toX, toY, duration);
});
}
public BvFlowAction DragFrom(double fromX, double fromY, int duration = 300)
{
ValidatePositive(duration, nameof(duration));
return CreateAction($"DragFrom({fromX}, {fromY})", context =>
{
var (toX, toY) = context.GetLastMatchCenter();
return _services.Drag(fromX, fromY, toX, toY, duration);
});
}
public BvFlow WaitUntilText(string text, Rect rect = default, int? timeout = null, int? retryInterval = null)
{
return WaitUntil(CreateTextLocator(text, rect), timeout, retryInterval);
}
public BvFlow WaitUntilAnyText(
object texts,
Rect rect = default,
int? timeout = null,
int? retryInterval = null)
{
return WaitUntil(CreateAnyTextLocator(texts, rect), timeout, retryInterval);
}
public BvFlow WaitUntil(BvLocator target, int? timeout = null, int? retryInterval = null)
{
ArgumentNullException.ThrowIfNull(target);
return AddWaitStep([target.Clone()], BvFlowCondition.AnyAppear, timeout, retryInterval);
}
public BvFlow WaitUntilAny(object targets, int? timeout = null, int? retryInterval = null)
{
return AddWaitStep(ParseTargets(targets, nameof(targets)), BvFlowCondition.AnyAppear,
timeout, retryInterval);
}
public BvFlow WaitUntilDisappear(BvLocator target, int? timeout = null, int? retryInterval = null)
{
ArgumentNullException.ThrowIfNull(target);
return AddWaitStep([target.Clone()], BvFlowCondition.AllDisappear, timeout, retryInterval);
}
public BvFlow WaitUntilAllDisappear(object targets, int? timeout = null, int? retryInterval = null)
{
return AddWaitStep(ParseTargets(targets, nameof(targets)), BvFlowCondition.AllDisappear,
timeout, retryInterval);
}
public BvFlow Wait(int milliseconds)
{
if (milliseconds < 0)
{
throw new ArgumentOutOfRangeException(nameof(milliseconds), "milliseconds 不能小于 0");
}
return AddStep($"Wait({milliseconds})", _ => _services.Delay(milliseconds));
}
public async Task<BvPage> Run()
{
if (Interlocked.CompareExchange(ref _isRunning, 1, 0) != 0)
{
throw new InvalidOperationException("同一个 BvFlow 不能并发执行");
}
try
{
BvFlowStep[] steps;
lock (_syncRoot)
{
_hasStarted = true;
steps = _steps.ToArray();
}
var context = new BvFlowExecutionContext();
for (var i = 0; i < steps.Length; i++)
{
var step = steps[i];
try
{
_services.ThrowIfCancellationRequested();
await step.Action(context);
}
catch (OperationCanceledException)
{
throw;
}
catch (NormalEndException)
{
throw;
}
catch (Exception ex)
{
throw new InvalidOperationException($"BvFlow 第 {i + 1} 步执行失败:{step.Description}", ex);
}
}
return _page;
}
finally
{
Volatile.Write(ref _isRunning, 0);
}
}
internal BvFlow AddActionStep(BvFlowActionSnapshot snapshot)
{
return AddStep(snapshot.Description, context => ExecuteActionStep(snapshot, context));
}
internal BvFlow AddOnceActionStep(string description, Func<BvFlowExecutionContext, Task> action)
{
return AddStep(description, action);
}
internal BvFlowAction CreateAction(string description, Func<BvFlowExecutionContext, Task> action)
{
lock (_syncRoot)
{
if (_hasStarted)
{
throw new InvalidOperationException("BvFlow 已经开始执行,不能再添加步骤");
}
}
return new BvFlowAction(this, description, action);
}
internal BvLocator CreateTextLocator(string text, Rect rect)
{
return _page.Locator(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = rect,
Text = text
});
}
internal BvLocator CreateAnyTextLocator(object texts, Rect rect)
{
return _page.GetByAnyText(texts, rect);
}
internal static IReadOnlyList<BvLocator> ParseTargets(object targets, string paramName)
{
return BvPage.ParseCollection<BvLocator>(targets, paramName)
.Select(target => target.Clone())
.ToArray();
}
internal static int ValidatePositive(int value, string paramName)
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(paramName, $"{paramName} 必须大于 0");
}
return value;
}
private BvFlowAction CreateImplicitPointAction(string description, Action<double, double> action)
{
return CreateAction(description, context =>
{
var (x, y) = context.GetLastMatchCenter();
action(x, y);
return Task.CompletedTask;
});
}
private BvFlowAction CreatePointAction(string description, double x, double y, Action<double, double> action)
{
return CreateAction(description, _ =>
{
action(x, y);
return Task.CompletedTask;
});
}
private async Task ExecuteActionStep(BvFlowActionSnapshot snapshot, BvFlowExecutionContext context)
{
var startedAt = _services.GetTimestamp();
var attempts = 0;
while (true)
{
_services.ThrowIfCancellationRequested();
attempts++;
await snapshot.Action(context);
var remainingMilliseconds = snapshot.Timeout - _services.GetElapsedMilliseconds(startedAt);
if (remainingMilliseconds <= 0)
{
throw new TimeoutException(
$"动作 {snapshot.Description} 执行 {attempts} 次后,等待 {snapshot.TargetDescription} 超时({snapshot.Timeout}ms)");
}
await _services.Delay(GetDelayMilliseconds(snapshot.RetryInterval, remainingMilliseconds));
if (_services.GetElapsedMilliseconds(startedAt) >= snapshot.Timeout)
{
throw new TimeoutException(
$"动作 {snapshot.Description} 执行 {attempts} 次后,等待 {snapshot.TargetDescription} 超时({snapshot.Timeout}ms)");
}
var result = FindTargets(snapshot.Targets, snapshot.Condition);
_services.ThrowIfCancellationRequested();
if (_services.GetElapsedMilliseconds(startedAt) >= snapshot.Timeout)
{
throw new TimeoutException(
$"动作 {snapshot.Description} 执行 {attempts} 次后,等待 {snapshot.TargetDescription} 超时({snapshot.Timeout}ms)");
}
if (result.Succeeded)
{
context.LastMatchRect = result.Match is null
? null
: _services.GetMatchRect(result.Match);
return;
}
}
}
private BvFlow AddWaitStep(
IReadOnlyList<BvLocator> targets,
BvFlowCondition condition,
int? timeout,
int? retryInterval)
{
var actualTimeout = timeout is { } timeoutValue
? ValidatePositive(timeoutValue, nameof(timeout))
: DefaultTimeout;
var actualRetryInterval = retryInterval is { } retryIntervalValue
? ValidatePositive(retryIntervalValue, nameof(retryInterval))
: DefaultRetryInterval;
var targetDescription = BvFlowAction.DescribeTargets(targets, condition);
return AddStep($"WaitUntil {targetDescription}",
context => ExecuteWaitStep(targets, targetDescription, condition,
actualTimeout, actualRetryInterval, context));
}
private async Task ExecuteWaitStep(
IReadOnlyList<BvLocator> targets,
string targetDescription,
BvFlowCondition condition,
int timeout,
int retryInterval,
BvFlowExecutionContext context)
{
var startedAt = _services.GetTimestamp();
while (true)
{
_services.ThrowIfCancellationRequested();
var elapsedMilliseconds = _services.GetElapsedMilliseconds(startedAt);
if (elapsedMilliseconds >= timeout)
{
throw new TimeoutException($"等待 {targetDescription} 超时({timeout}ms)");
}
var result = FindTargets(targets, condition);
_services.ThrowIfCancellationRequested();
if (_services.GetElapsedMilliseconds(startedAt) >= timeout)
{
throw new TimeoutException($"等待 {targetDescription} 超时({timeout}ms)");
}
if (result.Succeeded)
{
context.LastMatchRect = result.Match is null
? null
: _services.GetMatchRect(result.Match);
return;
}
var remainingMilliseconds = timeout - _services.GetElapsedMilliseconds(startedAt);
if (remainingMilliseconds <= 0)
{
throw new TimeoutException($"等待 {targetDescription} 超时({timeout}ms)");
}
await _services.Delay(GetDelayMilliseconds(retryInterval, remainingMilliseconds));
}
}
private BvFlowConditionResult FindTargets(
IReadOnlyList<BvLocator> targets,
BvFlowCondition condition)
{
return _services.FindTargets(targets, condition);
}
private static int GetDelayMilliseconds(int retryInterval, double remainingMilliseconds)
{
return Math.Min(retryInterval, Math.Max(1, (int)Math.Ceiling(remainingMilliseconds)));
}
private BvFlow AddStep(string description, Func<BvFlowExecutionContext, Task> action)
{
lock (_syncRoot)
{
if (_hasStarted)
{
throw new InvalidOperationException("BvFlow 已经开始执行,不能再添加步骤");
}
_hasSteps = true;
_steps.Add(new BvFlowStep(description, action));
}
return this;
}
private void EnsureDefaultsCanChange()
{
if (_hasSteps)
{
throw new InvalidOperationException("添加流程步骤后不能修改流程默认配置");
}
}
private sealed record BvFlowStep(string Description, Func<BvFlowExecutionContext, Task> Action);
}
internal sealed record BvFlowConditionResult(bool Succeeded, Region? Match);
internal sealed class BvFlowExecutionContext
{
public Rect? LastMatchRect { get; set; }
public (double X, double Y) GetLastMatchCenter()
{
if (LastMatchRect is not { } rect)
{
throw new InvalidOperationException("没有可用的上一步识别位置,无法执行隐式坐标操作");
}
return (rect.X + rect.Width / 2d, rect.Y + rect.Height / 2d);
}
}
internal sealed class BvFlowServices
{
public required Action ThrowIfCancellationRequested { get; set; }
public required Func<IReadOnlyList<BvLocator>, BvFlowCondition, BvFlowConditionResult> FindTargets { get; set; }
public required Func<Region, Rect> GetMatchRect { get; set; }
public required Func<int, Task> Delay { get; set; }
public required Func<long> GetTimestamp { get; set; }
public required Func<long, double> GetElapsedMilliseconds { get; set; }
public required Action<Vanara.PInvoke.User32.VK> KeyPress { get; set; }
public required Action<double, double> LeftClick { get; set; }
public required Action<double, double> RightClick { get; set; }
public required Action<double, double> MiddleClick { get; set; }
public required Action<double, double> MoveTo { get; set; }
public required Func<double, double, double, double, int, Task> Drag { get; set; }
public static BvFlowServices Create(BvPage page)
{
return new BvFlowServices
{
ThrowIfCancellationRequested = page.ThrowIfCancellationRequested,
FindTargets = (targets, condition) =>
{
using var screen = page.Screenshot();
return EvaluateTargets(targets, condition, target => target.FindAll(screen));
},
GetMatchRect = region =>
{
var rect = region.ConvertPositionToGameCaptureRegion(0, 0, region.Width, region.Height);
var scale = TaskContext.Instance().SystemInfo.ScaleTo1080PRatio;
return new Rect(
(int)Math.Round(rect.X / scale),
(int)Math.Round(rect.Y / scale),
(int)Math.Round(rect.Width / scale),
(int)Math.Round(rect.Height / scale));
},
Delay = async milliseconds => await page.Wait(milliseconds),
GetTimestamp = System.Diagnostics.Stopwatch.GetTimestamp,
GetElapsedMilliseconds = startedAt => System.Diagnostics.Stopwatch.GetElapsedTime(startedAt).TotalMilliseconds,
KeyPress = key => Simulation.SendInput.Keyboard.KeyPress(key),
LeftClick = GameCaptureRegion.GameRegion1080PPosClick,
RightClick = (x, y) =>
{
GameCaptureRegion.GameRegion1080PPosMove(x, y);
Simulation.SendInput.Mouse.RightButtonClick();
},
MiddleClick = (x, y) =>
{
GameCaptureRegion.GameRegion1080PPosMove(x, y);
Simulation.SendInput.Mouse.MiddleButtonClick();
},
MoveTo = GameCaptureRegion.GameRegion1080PPosMove,
Drag = async (fromX, fromY, toX, toY, duration) =>
{
GameCaptureRegion.GameRegion1080PPosMove(fromX, fromY);
Simulation.SendInput.Mouse.LeftButtonDown();
try
{
var firstDelay = duration / 2;
await page.Wait(firstDelay);
GameCaptureRegion.GameRegion1080PPosMove(toX, toY);
await page.Wait(duration - firstDelay);
}
finally
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
}
};
}
internal static BvFlowConditionResult EvaluateTargets(
IReadOnlyList<BvLocator> targets,
BvFlowCondition condition,
Func<BvLocator, List<Region>> findAll)
{
foreach (var target in targets)
{
var matches = findAll(target);
if (condition == BvFlowCondition.AnyAppear && matches.Count > 0)
{
return new BvFlowConditionResult(true, matches[0]);
}
if (condition == BvFlowCondition.AllDisappear && matches.Count > 0)
{
return new BvFlowConditionResult(false, null);
}
}
return condition == BvFlowCondition.AllDisappear
? new BvFlowConditionResult(true, null)
: new BvFlowConditionResult(false, null);
}
}
@@ -1,321 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
namespace BetterGenshinImpact.Core.BgiVision;
public sealed class BvFlowAction
{
private readonly BvFlow _flow;
private readonly string _description;
private readonly Func<BvFlowExecutionContext, Task> _action;
private readonly object _syncRoot = new();
private int? _timeout;
private int? _retryInterval;
private bool _completed;
internal BvFlowAction(BvFlow flow, string description, Func<BvFlowExecutionContext, Task> action)
{
_flow = flow;
_description = description;
_action = action;
}
public BvFlowAction WithTimeout(int milliseconds)
{
var timeout = BvFlow.ValidatePositive(milliseconds, nameof(milliseconds));
lock (_syncRoot)
{
EnsureNotCompleted();
_timeout = timeout;
}
return this;
}
public BvFlowAction WithRetryInterval(int milliseconds)
{
var retryInterval = BvFlow.ValidatePositive(milliseconds, nameof(milliseconds));
lock (_syncRoot)
{
EnsureNotCompleted();
_retryInterval = retryInterval;
}
return this;
}
public BvFlowAction Do(dynamic action)
{
ArgumentNullException.ThrowIfNull(action);
return CompleteOnce().Do(action);
}
public BvFlowAction KeyPress(string key)
{
_ = User32Helper.ToVk(key);
return CompleteOnce().KeyPress(key);
}
public BvFlowAction Click()
{
return CompleteOnce().Click();
}
public BvFlowAction Click(double x, double y)
{
return CompleteOnce().Click(x, y);
}
public BvFlowAction RightClick()
{
return CompleteOnce().RightClick();
}
public BvFlowAction RightClick(double x, double y)
{
return CompleteOnce().RightClick(x, y);
}
public BvFlowAction MiddleClick()
{
return CompleteOnce().MiddleClick();
}
public BvFlowAction MiddleClick(double x, double y)
{
return CompleteOnce().MiddleClick(x, y);
}
public BvFlowAction MoveTo()
{
return CompleteOnce().MoveTo();
}
public BvFlowAction MoveTo(double x, double y)
{
return CompleteOnce().MoveTo(x, y);
}
public BvFlowAction Drag(double fromX, double fromY, double toX, double toY, int duration = 300)
{
BvFlow.ValidatePositive(duration, nameof(duration));
return CompleteOnce().Drag(fromX, fromY, toX, toY, duration);
}
public BvFlowAction DragTo(double toX, double toY, int duration = 300)
{
BvFlow.ValidatePositive(duration, nameof(duration));
return CompleteOnce().DragTo(toX, toY, duration);
}
public BvFlowAction DragFrom(double fromX, double fromY, int duration = 300)
{
BvFlow.ValidatePositive(duration, nameof(duration));
return CompleteOnce().DragFrom(fromX, fromY, duration);
}
public BvFlow WaitUntilText(string text, Rect rect = default, int? timeout = null, int? retryInterval = null)
{
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntilText(text, rect, timeout, retryInterval);
}
public BvFlow WaitUntilAnyText(
object texts,
Rect rect = default,
int? timeout = null,
int? retryInterval = null)
{
_ = _flow.CreateAnyTextLocator(texts, rect);
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntilAnyText(texts, rect, timeout, retryInterval);
}
public BvFlow WaitUntil(BvLocator target, int? timeout = null, int? retryInterval = null)
{
ArgumentNullException.ThrowIfNull(target);
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntil(target, timeout, retryInterval);
}
public BvFlow WaitUntilAny(object targets, int? timeout = null, int? retryInterval = null)
{
_ = BvFlow.ParseTargets(targets, nameof(targets));
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntilAny(targets, timeout, retryInterval);
}
public BvFlow WaitUntilDisappear(BvLocator target, int? timeout = null, int? retryInterval = null)
{
ArgumentNullException.ThrowIfNull(target);
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntilDisappear(target, timeout, retryInterval);
}
public BvFlow WaitUntilAllDisappear(object targets, int? timeout = null, int? retryInterval = null)
{
_ = BvFlow.ParseTargets(targets, nameof(targets));
ValidateWaitOptions(timeout, retryInterval);
return CompleteOnce().WaitUntilAllDisappear(targets, timeout, retryInterval);
}
public BvFlow Wait(int milliseconds)
{
if (milliseconds < 0)
{
throw new ArgumentOutOfRangeException(nameof(milliseconds), "milliseconds 不能小于 0");
}
return CompleteOnce().Wait(milliseconds);
}
public BvFlow UntilText(string text, Rect rect = default)
{
return Until(_flow.CreateTextLocator(text, rect));
}
public BvFlow UntilAnyText(object texts, Rect rect = default)
{
return Until(_flow.CreateAnyTextLocator(texts, rect));
}
public BvFlow Until(BvLocator target)
{
ArgumentNullException.ThrowIfNull(target);
return Complete([target.Clone()], BvFlowCondition.AnyAppear);
}
public BvFlow UntilAny(object targets)
{
return Complete(BvFlow.ParseTargets(targets, nameof(targets)), BvFlowCondition.AnyAppear);
}
public BvFlow UntilDisappear(BvLocator target)
{
ArgumentNullException.ThrowIfNull(target);
return Complete([target.Clone()], BvFlowCondition.AllDisappear);
}
public BvFlow UntilAllDisappear(object targets)
{
return Complete(BvFlow.ParseTargets(targets, nameof(targets)), BvFlowCondition.AllDisappear);
}
public Task<BvPage> Run()
{
return CompleteOnce().Run();
}
private BvFlow CompleteOnce()
{
lock (_syncRoot)
{
EnsureNotCompleted();
if (_timeout is not null || _retryInterval is not null)
{
throw new InvalidOperationException(
"一次性动作不支持 WithTimeout 或 WithRetryInterval,请使用 Until 系列方法设置重试条件");
}
_completed = true;
}
return _flow.AddOnceActionStep(_description, _action);
}
private BvFlow Complete(IReadOnlyList<BvLocator> targets, BvFlowCondition condition)
{
int timeout;
int retryInterval;
lock (_syncRoot)
{
EnsureNotCompleted();
_completed = true;
timeout = _timeout ?? _flow.DefaultTimeout;
retryInterval = _retryInterval ?? _flow.DefaultRetryInterval;
}
var targetDescription = DescribeTargets(targets, condition);
return _flow.AddActionStep(new BvFlowActionSnapshot(
_description,
_action,
targets,
targetDescription,
timeout,
retryInterval,
condition));
}
private void EnsureNotCompleted()
{
if (_completed)
{
throw new InvalidOperationException("当前动作已经设置完成条件,不能再次修改或添加");
}
}
private static void ValidateWaitOptions(int? timeout, int? retryInterval)
{
if (timeout is { } timeoutValue)
{
BvFlow.ValidatePositive(timeoutValue, nameof(timeout));
}
if (retryInterval is { } retryIntervalValue)
{
BvFlow.ValidatePositive(retryIntervalValue, nameof(retryInterval));
}
}
internal static string DescribeTargets(IReadOnlyList<BvLocator> targets, BvFlowCondition condition)
{
var descriptions = targets.Select(DescribeTarget);
var targetDescription = targets.Count == 1
? descriptions.First()
: $"目标[{string.Join(" | ", descriptions)}]";
if (condition == BvFlowCondition.AllDisappear)
{
return targets.Count == 1
? $"{targetDescription}消失"
: $"{targetDescription}全部消失";
}
return targets.Count == 1 && targets[0].AnyTexts.Count == 0
? $"{targetDescription}出现"
: $"{targetDescription}中的任意一个出现";
}
private static string DescribeTarget(BvLocator locator)
{
if (locator.AnyTexts.Count > 0)
{
return $"文字[{string.Join('|', locator.AnyTexts)}]";
}
return locator.RecognitionObject.RecognitionType switch
{
RecognitionTypes.Ocr => $"文字[{locator.RecognitionObject.Text}]",
RecognitionTypes.TemplateMatch => $"图像[{locator.RecognitionObject.Name}]",
_ => "识别元素"
};
}
}
internal enum BvFlowCondition
{
AnyAppear,
AllDisappear
}
internal sealed record BvFlowActionSnapshot(
string Description,
Func<BvFlowExecutionContext, Task> Action,
IReadOnlyList<BvLocator> Targets,
string TargetDescription,
int Timeout,
int RetryInterval,
BvFlowCondition Condition);
+21 -136
View File
@@ -21,38 +21,19 @@ public class BvLocator
{
private static readonly ILogger Logger = App.GetLogger<BvLocator>();
private readonly CancellationToken _cancellationToken;
private readonly IReadOnlyList<string> _anyTexts;
private int? _timeout;
private int? _retryInterval;
public RecognitionObject RecognitionObject { get; }
public Func<List<Region>, Task>? RetryAction { get; set; }
public Action<List<Region>>? RetryAction { get; set; }
public static int DefaultTimeout { get; set; } = 10000;
public static int DefaultRetryInterval { get; set; } = 250;
public BvLocator(RecognitionObject recognitionObject, CancellationToken cancellationToken)
: this(recognitionObject, cancellationToken, [])
{
}
internal BvLocator(
RecognitionObject recognitionObject,
CancellationToken cancellationToken,
IReadOnlyList<string> anyTexts)
{
RecognitionObject = recognitionObject.Clone();
_cancellationToken = cancellationToken;
_anyTexts = anyTexts.ToArray();
}
internal IReadOnlyList<string> AnyTexts => _anyTexts;
internal BvLocator Clone()
{
return new BvLocator(RecognitionObject, _cancellationToken, _anyTexts);
}
/// <summary>
@@ -64,11 +45,7 @@ public class BvLocator
public List<Region> FindAll()
{
using var screen = CaptureToRectArea();
return FindAll(screen);
}
internal List<Region> FindAll(ImageRegion screen)
{
if (RecognitionObject.RecognitionType == RecognitionTypes.TemplateMatch)
{
var region = screen.Find(RecognitionObject);
@@ -82,7 +59,12 @@ public class BvLocator
else if (RecognitionObject.RecognitionType == RecognitionTypes.Ocr)
{
var results = screen.FindMulti(RecognitionObject);
return FilterOcrResults(results, _anyTexts, RecognitionObject.Text);
if (!string.IsNullOrEmpty(RecognitionObject.Text))
{
return results.FindAll(r => r.Text.Contains(RecognitionObject.Text));
}
return results;
}
else
{
@@ -90,22 +72,6 @@ public class BvLocator
}
}
internal static List<Region> FilterOcrResults(
List<Region> results,
IReadOnlyList<string> anyTexts,
string text)
{
if (anyTexts.Count > 0)
{
return results.FindAll(region =>
anyTexts.Any(candidate => region.Text.Contains(candidate, StringComparison.Ordinal)));
}
return string.IsNullOrEmpty(text)
? results
: results.FindAll(region => region.Text.Contains(text, StringComparison.Ordinal));
}
public bool IsExist()
{
return FindAll().Count > 0;
@@ -119,7 +85,7 @@ public class BvLocator
public async Task<Region> ClickUntilDisappears(int? timeout = null)
{
var region = (await WaitFor(timeout)).First().Click();
await Clone()
await new BvLocator(RecognitionObject, _cancellationToken)
.WithRetryAction(resList => { resList.First().Click(); }).WaitForDisappear();
return region;
}
@@ -132,21 +98,17 @@ public class BvLocator
public async Task<List<Region>> WaitFor(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
List<Region> results = [];
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
results = FindAll();
var b = results.Count > 0;
if (!b && RetryAction != null)
{
await RetryAction(results);
}
RetryAction?.Invoke(results);
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (retryRes)
{
@@ -162,12 +124,6 @@ public class BvLocator
{
if (RecognitionObject.RecognitionType == RecognitionTypes.Ocr)
{
if (_anyTexts.Count > 0)
{
return new TimeoutException(
$"识别任意文字[{string.Join('|', _anyTexts)}]在 {actualTimeout}ms 后超时未出现!");
}
return new TimeoutException($"识别文字[{RecognitionObject.Text}]在 {actualTimeout}ms 后超时未出现!");
}
else if (RecognitionObject.RecognitionType == RecognitionTypes.TemplateMatch)
@@ -194,21 +150,20 @@ public class BvLocator
public async Task WaitForDisappear(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
var results = FindAll();
var b = results.Count == 0;
if (!b && RetryAction != null)
if (!b)
{
await RetryAction(results);
RetryAction?.Invoke(results);
}
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (!retryRes)
{
@@ -250,77 +205,7 @@ public class BvLocator
public BvLocator WithRetryAction(Action<List<Region>>? action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = (results) =>
{
action(results);
return Task.CompletedTask;
};
}
RetryAction = action;
return this;
}
/// <summary>
/// 设置超时时间(毫秒)
/// </summary>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns></returns>
public BvLocator WithTimeout(int timeout)
{
if (timeout <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout), "timeout 必须大于 0");
}
_timeout = timeout;
return this;
}
/// <summary>
/// 设置重试间隔(毫秒)
/// </summary>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns></returns>
public BvLocator WithRetryInterval(int retryInterval)
{
if (retryInterval <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retryInterval), "retryInterval 必须大于 0");
}
_retryInterval = retryInterval;
return this;
}
/// <summary>
/// 为 JavaScript 提供的动态参数重载
/// 解决 ClearScript 无法将 JS 函数隐式转换为 Action 委托的问题
/// 支持同步和异步 JS 函数
/// </summary>
/// <param name="action">JS 回调函数</param>
/// <returns></returns>
public BvLocator WithRetryAction(dynamic action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = async (results) =>
{
var taskResult = action(results);
// 如果 JS 返回的是 Promise/Task,等待其完成
if (taskResult is Task task)
{
await task;
}
};
}
return this;
}
}
}
+1 -61
View File
@@ -1,12 +1,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model.Area;
using Fischless.WindowsInput;
@@ -39,11 +35,6 @@ public class BvPage
_cancellationToken = cancellationToken;
}
public BvFlow Flow()
{
return new BvFlow(this, DefaultTimeout, DefaultRetryInterval);
}
/// <summary>
/// 截图
/// </summary>
@@ -64,14 +55,6 @@ public class BvPage
return this;
}
internal void ThrowIfCancellationRequested()
{
if (_cancellationToken.IsCancellationRequested)
{
throw new NormalEndException("取消自动任务");
}
}
/// <summary>
/// 定位图片位置
/// </summary>
@@ -114,22 +97,6 @@ public class BvPage
return Locator(text, rect);
}
public BvLocator GetByAnyText(object texts, Rect rect = default)
{
var matchTexts = ParseCollection<string>(texts, nameof(texts));
if (matchTexts.Any(string.IsNullOrWhiteSpace))
{
throw new ArgumentException("候选文本不能包含空字符串或纯空白字符串", nameof(texts));
}
matchTexts = matchTexts.Distinct(StringComparer.Ordinal).ToList();
return new BvLocator(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = rect
}, _cancellationToken, matchTexts);
}
public BvLocator GetByImage(BvImage image)
{
return Locator(image);
@@ -151,31 +118,4 @@ public class BvPage
{
GameCaptureRegion.GameRegion1080PPosClick(x, y);
}
internal static List<T> ParseCollection<T>(object values, string paramName)
{
ArgumentNullException.ThrowIfNull(values, paramName);
if (values is string || values is not IEnumerable enumerable)
{
throw new ArgumentException($"{paramName} 必须是集合或 JS Array", paramName);
}
List<T> result = [];
foreach (var value in enumerable)
{
if (value is not T typedValue)
{
throw new ArgumentException($"{paramName} 中的每个元素都必须是 {typeof(T).Name}", paramName);
}
result.Add(typedValue);
}
if (result.Count == 0)
{
throw new ArgumentException($"{paramName} 不能为空", paramName);
}
return result;
}
}
}
+9 -33
View File
@@ -1,6 +1,6 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -22,10 +22,7 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.GetGridIcons;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.MapMask;
using BetterGenshinImpact.GameTask.SkillCd;
using BetterGenshinImpact.GameTask.UseRedeemCode;
namespace BetterGenshinImpact.Core.Config;
@@ -130,6 +127,11 @@ public partial class AllConfig : ObservableObject
/// </summary>
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
/// <summary>
/// 自动烹饪配置
/// </summary>
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 自动打牌配置
/// </summary>
@@ -154,11 +156,6 @@ public partial class AllConfig : ObservableObject
/// 自动秘境配置
/// </summary>
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 自动首领讨伐配置
/// </summary>
public AutoBossConfig AutoBossConfig { get; set; } = new();
/// <summary>
@@ -175,24 +172,12 @@ public partial class AllConfig : ObservableObject
/// 自动吃药配置
/// </summary>
public AutoEatConfig AutoEatConfig { get; set; } = new();
/// <summary>
/// 自动地脉花配置
/// </summary>
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 地图遮罩
/// </summary>
public MapMaskConfig MapMaskConfig { get; set; } = new();
/// <summary>
/// 技能 CD 提示
/// </summary>
public SkillCdConfig SkillCdConfig { get; set; } = new();
/// <summary>
/// 自动使用
/// </summary>
@@ -256,11 +241,6 @@ public partial class AllConfig : ObservableObject
/// </summary>
public HardwareAccelerationConfig HardwareAccelerationConfig { get; set; } = new();
/// <summary>
/// 桌面分身配置
/// </summary>
public ChildSessionConfig ChildSessionConfig { get; set; } = new();
[JsonIgnore]
public Action? OnAnyChangedAction { get; set; }
@@ -277,18 +257,16 @@ public partial class AllConfig : ObservableObject
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
AutoBossConfig.PropertyChanged += OnAnyPropertyChanged;
AutoStygianOnslaughtConfig.PropertyChanged += OnAnyPropertyChanged;
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
TpConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -296,8 +274,6 @@ public partial class AllConfig : ObservableObject
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
DevConfig.PropertyChanged += OnAnyPropertyChanged;
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
ChildSessionConfig.PropertyChanged += OnAnyPropertyChanged;
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -310,4 +286,4 @@ public partial class AllConfig : ObservableObject
{
NotificationService.Instance().RefreshNotifiers();
}
}
}
@@ -1,38 +0,0 @@
using System;
using CommunityToolkit.Mvvm.ComponentModel;
namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class ChildSessionConfig : ObservableObject
{
/// <summary>
/// 桌面分身窗口是否置顶。
/// </summary>
[ObservableProperty]
private bool _topmostEnabled = false;
/// <summary>
/// RDP 画面是否自适应窗口。关闭时使用 1:1 显示。
/// </summary>
[ObservableProperty]
private bool _smartSizingEnabled = true;
/// <summary>
/// 桌面分身窗口是否保持 16:9 宽高比。
/// </summary>
[ObservableProperty]
private bool _keepAspectRatio = true;
/// <summary>
/// Alt+Tab、Windows 键等系统组合键是否发送到桌面分身。
/// </summary>
[ObservableProperty]
private bool _sendSystemShortcutsToRemote = true;
/// <summary>
/// 桌面分身是否启用游戏鼠标模式。默认使用普通鼠标模式。
/// </summary>
[ObservableProperty]
private bool _gameMouseModeEnabled = false;
}
@@ -38,12 +38,6 @@ public partial class CommonConfig : ObservableObject
[ObservableProperty]
private bool _screenshotUidCoverEnabled = true;
/// <summary>
/// 是否保存奖励识别调试截图
/// </summary>
[ObservableProperty]
private bool _rewardRecognitionScreenshotEnabled;
/// <summary>
/// 退出时最小化至托盘
/// </summary>
@@ -86,22 +80,4 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _redeemCodeFeedsUpdateVersion = "20251013";
/// <summary>
/// 国服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeCnFeedsNotificationEnabled = true;
/// <summary>
/// 国际服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeGlobalFeedsNotificationEnabled;
/// <summary>
/// 当前看过的国际服兑换码推送版本
/// </summary>
[ObservableProperty]
private string _redeemCodeGlobalFeedsUpdateVersion = string.Empty;
}
@@ -47,10 +47,4 @@ public partial class GenshinStartConfig : ObservableObject
[ObservableProperty]
private bool _startGameWithCmd = false;
/// <summary>
/// 启动前自动关闭原神 HDR(删除原神 HDR 对应注册表键)
/// </summary>
[ObservableProperty]
private bool _autoDisableGenshinHdrEnabled = true;
}
@@ -14,10 +14,10 @@ public partial class HardwareAccelerationConfig : ObservableObject
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
/// <summary>
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
/// </summary>
[ObservableProperty]
private bool _cpuOcr = true;
private bool _cpuOcr = false;
#region 一般GPU加速设置
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -82,12 +82,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickBuyHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
[ObservableProperty]
private string _oneKeyClaimRewardHotkey = "";
[ObservableProperty]
private string _oneKeyClaimRewardHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
[ObservableProperty]
private string _quickSereniteaPotHotkey = "";
@@ -106,13 +100,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 技能CD提示开关
[ObservableProperty]
private string _skillCdEnabledHotkey = "";
[ObservableProperty]
private string _skillCdEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 截图
[ObservableProperty]
@@ -169,13 +156,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _autoFishingGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动烹饪开始/停止
[ObservableProperty]
private string _autoCookGameHotkey = "";
[ObservableProperty]
private string _autoCookGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动寻路
[ObservableProperty]
private string _autoTrackPathHotkey = "";
@@ -232,13 +212,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _logBoxDisplayHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 遮罩指标栏展示
[ObservableProperty]
private string _overlayMetricsDisplayHotkey = "";
[ObservableProperty]
private string _overlayMetricsDisplayHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 键鼠录制/停止
[ObservableProperty]
private string _keyMouseMacroRecordHotkey = "";
@@ -264,11 +237,4 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 地图遮罩开关
[ObservableProperty]
private string _mapMaskEnabledHotkey = "";
[ObservableProperty]
private string _mapMaskEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -1,5 +1,4 @@
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.QuickClaimReward;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -68,22 +67,4 @@ public partial class MacroConfig : ObservableObject
/// </summary>
[ObservableProperty]
private int _combatMacroPriority = 1;
/// <summary>
/// 一键领取奖励快捷键模式
/// </summary>
[ObservableProperty]
private string _oneKeyClaimRewardHotkeyMode = OneKeyClaimRewardTask.ClickOnceMode;
/// <summary>
/// 一键领取奖励未找到领取图标时滚轮下滑
/// </summary>
[ObservableProperty]
private bool _oneKeyClaimRewardScrollDownEnabled;
/// <summary>
/// 一键领取奖励滚轮下滑幅度
/// </summary>
[ObservableProperty]
private int _oneKeyClaimRewardScrollDownAmount = 2;
}
@@ -1,8 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
@@ -12,44 +10,6 @@ namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class MaskWindowConfig : ObservableObject
{
public const string DefaultOverlayWindowBackgroundColor = "#01000000";
public const string DefaultWineOverlayBackgroundColor = "#11000000";
public const string DefaultTransparentColor = "#00000000";
public const string DefaultPanelBorderColor = "#33000000";
public const string DefaultLogTextColor = "LightGray";
public const string DefaultStatusDisabledTextColor = "LightGray";
public const string DefaultStatusEnabledTextColor = "LightGreen";
public const string DefaultMetricsTextColor = "LightGray";
public const string DefaultDirectionTextColor = "White";
public const string DefaultShadowColor = "#FF000000";
public const string DefaultStatusShadowColor = "LightGray";
public const string DefaultRecognitionStrokeColor = "Red";
public const string DefaultRecognitionTextColor = "Black";
public const string DefaultOverlayMonoFontFamily = "Cascadia Mono, Consolas, Courier New, monospace, /Resources/Fonts/MiSans-Regular.ttf#MiSans";
public const int MinCrosshairLineWidth = 1;
public const int MaxCrosshairLineWidth = 100;
public const int MinCrosshairSize = 1;
public const int MaxCrosshairSize = 1000;
public const int MinCrosshairGap = 0;
public const int MaxCrosshairGap = 1000;
// 指标栏布局和遮罩里其它元素一样按 1920x1080 折算比例保存,默认放在状态栏/日志上方以避开游戏底部 UI。
public const double DefaultMetricsLeftRatio = 20.0 / 1920;
public const double DefaultMetricsTopRatio = 744.0 / 1080;
public const double DefaultMetricsWidthRatio = 477.0 / 1920;
public const double DefaultMetricsHeightRatio = 58.0 / 1080;
// 这些是开发评审过程中曾下发过的默认布局;用户没有手动调整时迁移到最新默认值,避免旧默认继续挡住游戏 UI。
private static readonly (double Left, double Top, double Width, double Height)[] LegacyMetricsLayouts =
[
(4.0 / 1920, 4.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(600.0 / 1920, 16.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 58.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 58.0 / 1080)
];
/// <summary>
/// 方位提示是否启用
/// </summary>
@@ -97,81 +57,6 @@ public partial class MaskWindowConfig : ObservableObject
[NonSerialized]
public static readonly Rect UidCoverRightBottomRect = new(1920 - 1685, 1080 - 1053, 178, 22);
/// <summary>
/// 准星是否启用
/// </summary>
[ObservableProperty]
private bool _crosshairEnabled;
/// <summary>
/// 准星类型
/// </summary>
[ObservableProperty]
private CrosshairType _crosshairType = CrosshairType.Crosshair;
/// <summary>
/// 准星颜色(十六进制)
/// </summary>
[ObservableProperty]
private string _crosshairColor = "#FFFFFF";
/// <summary>
/// 准星线宽
/// </summary>
[ObservableProperty]
private int _crosshairLineWidth = 4;
/// <summary>
/// 准星大小
/// </summary>
[ObservableProperty]
private int _crosshairSize = 30;
/// <summary>
/// 中心点与十字线的间隔(仅 DotCrosshair 类型)
/// </summary>
[ObservableProperty]
private int _crosshairGap = 10;
partial void OnCrosshairLineWidthChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairLineWidth, MaxCrosshairLineWidth);
if (value != clampedValue)
{
CrosshairLineWidth = clampedValue;
}
}
partial void OnCrosshairSizeChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairSize, MaxCrosshairSize);
if (value != clampedValue)
{
CrosshairSize = clampedValue;
}
}
partial void OnCrosshairGapChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairGap, MaxCrosshairGap);
if (value != clampedValue)
{
CrosshairGap = clampedValue;
}
}
/// <summary>
/// 自定义准星图片路径
/// </summary>
[ObservableProperty]
private string? _crosshairImagePath;
/// <summary>
/// 自定义图片缩放方式
/// </summary>
[ObservableProperty]
private CrosshairScaleMode _crosshairScaleMode = CrosshairScaleMode.Original;
/// <summary>
/// 显示FPS
/// </summary>
@@ -179,13 +64,11 @@ public partial class MaskWindowConfig : ObservableObject
private bool _showFps = false;
/// <summary>
/// 显示遮罩指标栏
/// 作为原神子窗体
/// 有些bug没解决
/// </summary>
[ObservableProperty]
private bool _showOverlayMetrics = false;
// 配置文件里使用 string key 便于兼容旧版本,读取后由 EnsureOverlayMetricItems 约束回固定枚举集合。
public Dictionary<string, bool> OverlayMetricItems { get; set; } = OverlayMetricItemDefaults.CreateDefaultItems();
private bool _useSubform = false;
/// <summary>
/// 遮罩文本透明度 (0.0-1.0)
@@ -193,243 +76,6 @@ public partial class MaskWindowConfig : ObservableObject
[ObservableProperty]
private double _textOpacity = 1.0;
/// <summary>
/// 是否启用遮罩 UI 缩放。关闭后直接使用各遮罩元素的基础尺寸。
/// </summary>
[ObservableProperty]
private bool _overlayScalingEnabled = true;
/// <summary>
/// 遮罩 UI 缩放率 (0.5-3.0),叠加到日志、状态和 FPS 的基础字号上。
/// </summary>
[ObservableProperty]
private double _logFontScale = 1.0;
/// <summary>
/// 指标栏缩放率 (0.5-3.0),叠加到指标栏的基础字号和布局尺寸上。
/// 独立于遮罩 UI 缩放率。
/// </summary>
[ObservableProperty]
private double _metricsFontScale = 1.0;
/// <summary>遮罩日志缩放率允许的最小值。</summary>
public const double MinLogFontScale = 0.5;
/// <summary>遮罩日志缩放率允许的最大值。</summary>
public const double MaxLogFontScale = 3.0;
/// <summary>
/// 纯函数:把任意缩放率夹取到 [MinLogFontScale, MaxLogFontScale]。无副作用,供 PBT。
/// NaN 视为非法,回落到 1.0。
/// </summary>
public static double ComputeClampedScale(double scale)
{
if (double.IsNaN(scale))
{
return 1.0;
}
return Math.Clamp(scale, MinLogFontScale, MaxLogFontScale);
}
/// <summary>
/// 纯函数:计算遮罩 UI 实际渲染尺寸。
/// 禁用缩放时直接返回有效的基础尺寸。
/// = baseSize × clamp(scale) × scaleTo1080pRatio / displayDpiScale,AwayFromZero 四舍五入。
/// 乘以 ScaleTo1080PRatio 适配不同游戏分辨率,除以 DisplayDpiScale 抵消 WPF 自动 DPI 缩放。
/// </summary>
public static double ComputeEffectiveSize(double baseSize, double scale, double scaleTo1080pRatio,
double displayDpiScale, bool scalingEnabled)
{
var safeBaseSize = double.IsFinite(baseSize) && baseSize > 0 ? baseSize : 1.0;
if (!scalingEnabled)
{
return safeBaseSize;
}
var resolutionScale = double.IsFinite(scaleTo1080pRatio) ? Math.Max(scaleTo1080pRatio, 0.1) : 1.0;
var dpiScale = double.IsFinite(displayDpiScale) ? Math.Max(displayDpiScale, 0.1) : 1.0;
var result = Math.Round(safeBaseSize * ComputeClampedScale(scale) * resolutionScale / dpiScale,
MidpointRounding.AwayFromZero);
return Math.Max(result, 1.0);
}
/// <summary>
/// 缩放率变更钩子:仅当传入值越界时回写夹取后的值(防 setter 递归)。
/// </summary>
partial void OnLogFontScaleChanged(double value)
{
var clamped = ComputeClampedScale(value);
if (value != clamped)
{
LogFontScale = clamped;
}
}
/// <summary>
/// 指标栏缩放率变更钩子:仅当传入值越界时回写夹取后的值(防 setter 递归)。
/// </summary>
partial void OnMetricsFontScaleChanged(double value)
{
var clamped = ComputeClampedScale(value);
if (value != clamped)
{
MetricsFontScale = clamped;
}
}
[ObservableProperty]
private string _overlayWindowBackgroundColor = DefaultOverlayWindowBackgroundColor;
[ObservableProperty]
private string _wineOverlayBackgroundColor = DefaultWineOverlayBackgroundColor;
[ObservableProperty]
private string _logPanelBackgroundColor = DefaultTransparentColor;
[ObservableProperty]
private string _logPanelBorderColor = DefaultPanelBorderColor;
[ObservableProperty]
private double _logPanelBorderThickness = 0;
[ObservableProperty]
private string _logTextColor = DefaultLogTextColor;
[ObservableProperty]
private string _logFontFamily = DefaultOverlayMonoFontFamily;
[ObservableProperty]
private double _logFontSize = 12;
[ObservableProperty]
private bool _logShadowEnabled = true;
[ObservableProperty]
private string _logShadowColor = DefaultShadowColor;
[ObservableProperty]
private double _logShadowOpacity = 0.4;
[ObservableProperty]
private double _logShadowBlurRadius = 4;
[ObservableProperty]
private string _statusPanelBackgroundColor = DefaultTransparentColor;
[ObservableProperty]
private string _statusPanelBorderColor = DefaultPanelBorderColor;
[ObservableProperty]
private double _statusPanelBorderThickness = 0;
[ObservableProperty]
private string _statusDisabledTextColor = DefaultStatusDisabledTextColor;
[ObservableProperty]
private string _statusEnabledTextColor = DefaultStatusEnabledTextColor;
[ObservableProperty]
private double _statusFontSize = 12;
[ObservableProperty]
private bool _statusShadowEnabled = true;
[ObservableProperty]
private string _statusShadowColor = DefaultStatusShadowColor;
[ObservableProperty]
private double _statusShadowOpacity = 0.4;
[ObservableProperty]
private double _statusShadowBlurRadius = 4;
[ObservableProperty]
private string _metricsPanelBackgroundColor = DefaultTransparentColor;
[ObservableProperty]
private string _metricsPanelBorderColor = DefaultTransparentColor;
[ObservableProperty]
private double _metricsPanelBorderThickness = 0;
[ObservableProperty]
private string _metricsTextColor = DefaultMetricsTextColor;
[ObservableProperty]
private string _metricsFontFamily = DefaultOverlayMonoFontFamily;
[ObservableProperty]
private double _metricsFontSize = 12;
[ObservableProperty]
private double _metricsLineHeight = 15;
[ObservableProperty]
private double _metricsItemWidth = 116;
[ObservableProperty]
private double _metricsNameColumnWidth = 68;
[ObservableProperty]
private bool _metricsShadowEnabled = true;
[ObservableProperty]
private string _metricsShadowColor = DefaultShadowColor;
[ObservableProperty]
private double _metricsShadowOpacity = 0.4;
[ObservableProperty]
private double _metricsShadowBlurRadius = 4;
[ObservableProperty]
private string _directionTextColor = DefaultDirectionTextColor;
[ObservableProperty]
private double _directionFontSize = 34;
[ObservableProperty]
private bool _directionShadowEnabled = true;
[ObservableProperty]
private string _directionShadowColor = DefaultShadowColor;
[ObservableProperty]
private double _directionShadowOpacity = 0.4;
[ObservableProperty]
private double _directionShadowBlurRadius = 8;
[ObservableProperty]
private bool _recognitionUseDrawableStyle = false;
[ObservableProperty]
private string _recognitionRectStrokeColor = DefaultRecognitionStrokeColor;
[ObservableProperty]
private double _recognitionRectStrokeThickness = 2;
[ObservableProperty]
private string _recognitionLineStrokeColor = DefaultRecognitionStrokeColor;
[ObservableProperty]
private double _recognitionLineStrokeThickness = 2;
[ObservableProperty]
private string _recognitionTextColor = DefaultRecognitionTextColor;
[ObservableProperty]
private double _recognitionTextFontSize = 36;
[ObservableProperty]
private bool _customHtmlMaskEnabled = false;
[ObservableProperty]
private bool _customHtmlMaskClickThrough = true;
[ObservableProperty]
private bool _customHtmlMaskAutoReloadOnSave = true;
[ObservableProperty]
private bool _overlayLayoutEditEnabled = false;
@@ -437,10 +83,10 @@ public partial class MaskWindowConfig : ObservableObject
private double _logTextBoxLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _logTextBoxTopRatio = 822.0 / 1080;
private double _logTextBoxTopRatio = 832.0 / 1080;
[ObservableProperty]
private double _logTextBoxWidthRatio = 480.0 / 1920;
private double _logTextBoxWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _logTextBoxHeightRatio = 188.0 / 1080;
@@ -449,182 +95,11 @@ public partial class MaskWindowConfig : ObservableObject
private double _statusListLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _statusListTopRatio = 790.0 / 1080;
private double _statusListTopRatio = 807.0 / 1080;
[ObservableProperty]
private double _statusListWidthRatio = 480.0 / 1920;
private double _statusListWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _statusListHeightRatio = 24.0 / 1080;
[ObservableProperty]
private double _metricsLeftRatio = DefaultMetricsLeftRatio;
[ObservableProperty]
private double _metricsTopRatio = DefaultMetricsTopRatio;
[ObservableProperty]
private double _metricsWidthRatio = DefaultMetricsWidthRatio;
[ObservableProperty]
private double _metricsHeightRatio = DefaultMetricsHeightRatio;
public void ResetOverlayMetricsLayout()
{
MetricsLeftRatio = DefaultMetricsLeftRatio;
MetricsTopRatio = DefaultMetricsTopRatio;
MetricsWidthRatio = DefaultMetricsWidthRatio;
MetricsHeightRatio = DefaultMetricsHeightRatio;
}
public void ResetOverlayStyle()
{
TextOpacity = 1.0;
OverlayScalingEnabled = true;
LogFontScale = 1.0;
MetricsFontScale = 1.0;
OverlayWindowBackgroundColor = DefaultOverlayWindowBackgroundColor;
WineOverlayBackgroundColor = DefaultWineOverlayBackgroundColor;
LogPanelBackgroundColor = DefaultTransparentColor;
LogPanelBorderColor = DefaultPanelBorderColor;
LogPanelBorderThickness = 0;
LogTextColor = DefaultLogTextColor;
LogFontFamily = DefaultOverlayMonoFontFamily;
LogFontSize = 12;
LogShadowEnabled = true;
LogShadowColor = DefaultShadowColor;
LogShadowOpacity = 0.4;
LogShadowBlurRadius = 4;
StatusPanelBackgroundColor = DefaultTransparentColor;
StatusPanelBorderColor = DefaultPanelBorderColor;
StatusPanelBorderThickness = 0;
StatusDisabledTextColor = DefaultStatusDisabledTextColor;
StatusEnabledTextColor = DefaultStatusEnabledTextColor;
StatusFontSize = 12;
StatusShadowEnabled = true;
StatusShadowColor = DefaultStatusShadowColor;
StatusShadowOpacity = 0.4;
StatusShadowBlurRadius = 4;
MetricsPanelBackgroundColor = DefaultTransparentColor;
MetricsPanelBorderColor = DefaultTransparentColor;
MetricsPanelBorderThickness = 0;
MetricsTextColor = DefaultMetricsTextColor;
MetricsFontFamily = DefaultOverlayMonoFontFamily;
MetricsFontSize = 12;
MetricsLineHeight = 15;
MetricsItemWidth = 116;
MetricsNameColumnWidth = 68;
MetricsShadowEnabled = true;
MetricsShadowColor = DefaultShadowColor;
MetricsShadowOpacity = 0.4;
MetricsShadowBlurRadius = 4;
DirectionTextColor = DefaultDirectionTextColor;
DirectionFontSize = 34;
DirectionShadowEnabled = true;
DirectionShadowColor = DefaultShadowColor;
DirectionShadowOpacity = 0.4;
DirectionShadowBlurRadius = 8;
RecognitionUseDrawableStyle = false;
RecognitionRectStrokeColor = DefaultRecognitionStrokeColor;
RecognitionRectStrokeThickness = 2;
RecognitionLineStrokeColor = DefaultRecognitionStrokeColor;
RecognitionLineStrokeThickness = 2;
RecognitionTextColor = DefaultRecognitionTextColor;
RecognitionTextFontSize = 36;
}
public void MigrateLegacyOverlayMetricsLayout()
{
if (LegacyMetricsLayouts.Any(layout =>
IsSameRatio(MetricsLeftRatio, layout.Left)
&& IsSameRatio(MetricsTopRatio, layout.Top)
&& IsSameRatio(MetricsWidthRatio, layout.Width)
&& IsSameRatio(MetricsHeightRatio, layout.Height)))
{
ResetOverlayMetricsLayout();
}
}
private static bool IsSameRatio(double left, double right)
{
return Math.Abs(left - right) < 0.0000001;
}
public void EnsureOverlayMetricItems()
{
// 旧配置可能缺少新指标或残留废弃指标,这里统一补默认项并移除非法 key,避免 UI 渲染任意字符串。
OverlayMetricItems ??= [];
// TriggerInterval 第一版展示的是配置值,现已替换为 PeakProcessingCost;保留用户原来的勾选状态。
const string legacyTriggerIntervalKey = "TriggerInterval";
var peakProcessingCostKey = OverlayMetricItem.PeakProcessingCost.ToString();
if (OverlayMetricItems.TryGetValue(legacyTriggerIntervalKey, out var legacyEnabled)
&& !OverlayMetricItems.ContainsKey(peakProcessingCostKey))
{
OverlayMetricItems[peakProcessingCostKey] = legacyEnabled;
}
foreach (var item in OverlayMetricItemDefaults.AllItems)
{
var key = item.ToString();
if (!OverlayMetricItems.ContainsKey(key))
{
OverlayMetricItems[key] = OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
}
var validKeys = OverlayMetricItemDefaults.AllItems.Select(item => item.ToString()).ToHashSet();
foreach (var key in OverlayMetricItems.Keys.Where(key => !validKeys.Contains(key)).ToList())
{
OverlayMetricItems.Remove(key);
}
if (ShowFps)
{
ShowOverlayMetrics = true;
OverlayMetricItems[OverlayMetricItem.GameFps.ToString()] = true;
ShowFps = false;
OnPropertyChanged(nameof(OverlayMetricItems));
}
}
public bool IsOverlayMetricEnabled(OverlayMetricItem item)
{
return OverlayMetricItems != null && OverlayMetricItems.TryGetValue(item.ToString(), out var enabled)
? enabled
: OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
public void SetOverlayMetricEnabled(OverlayMetricItem item, bool enabled)
{
EnsureOverlayMetricItems();
OverlayMetricItems[item.ToString()] = enabled;
OnPropertyChanged(nameof(OverlayMetricItems));
}
}
/// <summary>
/// 准星类型
/// </summary>
public enum CrosshairType
{
Crosshair,
Diagonal,
Dot,
DotCrosshair,
Custom
}
/// <summary>
/// 自定义准星图片缩放方式
/// </summary>
public enum CrosshairScaleMode
{
Original,
Fit
}
@@ -1,7 +1,6 @@
using System;
using System;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.Helpers;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -14,24 +13,11 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _name = string.Empty;
// 下次执行的任务 Id(为空表示从头开始)
[ObservableProperty]
private string _nextTaskId = string.Empty;
/// <summary>
/// 所有任务的开关状态(键为任务 Id)
/// 所有任务的开关状态
/// </summary>
public Dictionary<string, bool> TaskEnabledList { get; set; } = new();
/// <summary>
/// 任务执行顺序(任务 Id 列表),用于显式恢复 TaskList 顺序
/// </summary>
public List<string> TaskOrder { get; set; } = new();
/// <summary>
/// 任务定义(Id → 任务名),用于支持同名任务重复添加
/// </summary>
public Dictionary<string, string> TaskDefinitions { get; set; } = new();
// 合成树脂的国家
[ObservableProperty]
private string _craftingBenchCountry = "枫丹";
@@ -50,69 +36,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private bool _weeklyDomainEnabled = false;
#region 自动首领讨伐配置
[ObservableProperty]
private string _autoBossName = string.Empty;
[ObservableProperty]
private string _autoBossStrategyName = "根据队伍自动选择";
[ObservableProperty]
private string _autoBossTeamName = string.Empty;
[ObservableProperty]
private bool _autoBossSpecifyRunCount = false;
[ObservableProperty]
private int _autoBossRunCount = 1;
[ObservableProperty]
private bool _autoBossUseTransientResin = false;
[ObservableProperty]
private bool _autoBossUseFragileResin = false;
[ObservableProperty]
private int _autoBossReviveRetryCount = 3;
[ObservableProperty]
private bool _autoBossReturnToStatueAfterEachRound = false;
[ObservableProperty]
private bool _autoBossRewardRecognitionEnabled = false;
[ObservableProperty]
private int _autoBossTimeout = 240;
partial void OnAutoBossSpecifyRunCountChanged(bool value)
{
if (value)
{
return;
}
AutoBossUseTransientResin = false;
AutoBossUseFragileResin = false;
}
partial void OnAutoBossRunCountChanged(int value)
{
if (value < 1)
{
AutoBossRunCount = 1;
}
}
partial void OnAutoBossReviveRetryCountChanged(int value)
{
if (value < 0)
{
AutoBossReviveRetryCount = 0;
}
}
#endregion
// 领取每日奖励的好感队伍名称
[ObservableProperty]
@@ -122,13 +45,13 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private int _minResinToKeep = 0;
// 普通周日或限时奖励选项
// 领取每日奖励的好感数量
[ObservableProperty]
private string _sundayEverySelectedValue = "0";
// 每周秘境的全局限时奖励选项,单日留空时使用
// 领取每日奖励的好感数量
[ObservableProperty]
private string _sundayWeeklySelectedValue = "0";
private string _sundaySelectedValue = "0";
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
[ObservableProperty]
@@ -138,87 +61,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private List<string> _secretTreasureObjects = new();
// 地脉花一条龙模式(跳过部分准备流程)
[ObservableProperty]
private bool _leyLineOneDragonMode = false;
// 地脉花运行日期设置
[ObservableProperty]
private bool _leyLineRunMonday = true;
[ObservableProperty]
private bool _leyLineRunTuesday = true;
[ObservableProperty]
private bool _leyLineRunWednesday = true;
[ObservableProperty]
private bool _leyLineRunThursday = true;
[ObservableProperty]
private bool _leyLineRunFriday = true;
[ObservableProperty]
private bool _leyLineRunSaturday = true;
[ObservableProperty]
private bool _leyLineRunSunday = true;
// 地脉花每日类型与国家配置(为空则使用独立任务配置)
[ObservableProperty]
private string _leyLineMondayType = string.Empty;
[ObservableProperty]
private string _leyLineMondayCountry = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayType = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayType = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineThursdayType = string.Empty;
[ObservableProperty]
private string _leyLineThursdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineFridayType = string.Empty;
[ObservableProperty]
private string _leyLineFridayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayType = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSundayType = string.Empty;
[ObservableProperty]
private string _leyLineSundayCountry = string.Empty;
// 地脉花刷取次数(0 表示使用独立任务配置)
[ObservableProperty]
private int _leyLineRunCount = 0;
// 地脉花树脂耗尽模式
[ObservableProperty]
private bool _leyLineResinExhaustionMode = false;
// 地脉花刷取次数取小值(仅耗尽模式生效)
[ObservableProperty]
private bool _leyLineOpenModeCountMin = false;
#region 每周秘境配置
//周一
@@ -227,9 +69,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _mondayDomainName = string.Empty;
[ObservableProperty]
private string _mondaySelectedValue = "0";
//周二
@@ -238,9 +77,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _tuesdayDomainName = string.Empty;
[ObservableProperty]
private string _tuesdaySelectedValue = "0";
//周三
[ObservableProperty]
@@ -248,9 +84,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _wednesdayDomainName = string.Empty;
[ObservableProperty]
private string _wednesdaySelectedValue = "0";
//周四
[ObservableProperty]
@@ -258,9 +91,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _thursdayDomainName = string.Empty;
[ObservableProperty]
private string _thursdaySelectedValue = "0";
//周五
[ObservableProperty]
@@ -268,9 +98,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _fridayDomainName = string.Empty;
[ObservableProperty]
private string _fridaySelectedValue = "0";
//周六
[ObservableProperty]
@@ -278,9 +105,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _saturdayDomainName = string.Empty;
[ObservableProperty]
private string _saturdaySelectedValue = "0";
//周日
[ObservableProperty]
@@ -289,9 +113,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _sundayDomainName = string.Empty;
[ObservableProperty]
private string _sundaySelectedValue = "0";
// 完成后操作
[ObservableProperty]
private string _completionAction = string.Empty;
@@ -305,93 +126,21 @@ public partial class OneDragonFlowConfig : ObservableObject
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => (GetWeeklyPartyName(MondayPartyName), GetWeeklyDomainName(MondayDomainName), GetWeeklySelectedValue(MondaySelectedValue)),
DayOfWeek.Tuesday => (GetWeeklyPartyName(TuesdayPartyName), GetWeeklyDomainName(TuesdayDomainName), GetWeeklySelectedValue(TuesdaySelectedValue)),
DayOfWeek.Wednesday => (GetWeeklyPartyName(WednesdayPartyName), GetWeeklyDomainName(WednesdayDomainName), GetWeeklySelectedValue(WednesdaySelectedValue)),
DayOfWeek.Thursday => (GetWeeklyPartyName(ThursdayPartyName), GetWeeklyDomainName(ThursdayDomainName), GetWeeklySelectedValue(ThursdaySelectedValue)),
DayOfWeek.Friday => (GetWeeklyPartyName(FridayPartyName), GetWeeklyDomainName(FridayDomainName), GetWeeklySelectedValue(FridaySelectedValue)),
DayOfWeek.Saturday => (GetWeeklyPartyName(SaturdayPartyName), GetWeeklyDomainName(SaturdayDomainName), GetWeeklySelectedValue(SaturdaySelectedValue)),
DayOfWeek.Sunday => (GetWeeklyPartyName(SundayPartyName), GetWeeklyDomainName(SundayDomainName), GetWeeklySelectedValue(SundaySelectedValue)),
_ => (PartyName, DomainName, SundayWeeklySelectedValue)
DayOfWeek.Monday => (MondayPartyName, MondayDomainName,SundaySelectedValue),
DayOfWeek.Tuesday => (TuesdayPartyName, TuesdayDomainName,SundaySelectedValue),
DayOfWeek.Wednesday => (WednesdayPartyName, WednesdayDomainName,SundaySelectedValue),
DayOfWeek.Thursday => (ThursdayPartyName, ThursdayDomainName,SundaySelectedValue),
DayOfWeek.Friday => (FridayPartyName, FridayDomainName,SundaySelectedValue),
DayOfWeek.Saturday => (SaturdayPartyName, SaturdayDomainName,SundaySelectedValue),
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName,SundaySelectedValue),
_ => (PartyName, DomainName,SundaySelectedValue)
};
}
else
{
return (PartyName, DomainName, SundayEverySelectedValue);
return (PartyName, DomainName,SundayEverySelectedValue);
}
}
private string GetWeeklyPartyName(string partyName)
{
return string.IsNullOrWhiteSpace(partyName) ? PartyName : partyName;
}
private string GetWeeklyDomainName(string domainName)
{
return string.IsNullOrWhiteSpace(domainName) ? DomainName : domainName;
}
private string GetWeeklySelectedValue(string selectedValue)
{
return string.IsNullOrWhiteSpace(selectedValue) || selectedValue == "0" ? SundayWeeklySelectedValue : selectedValue;
}
public bool ShouldRunLeyLineToday()
{
if (!LeyLineRunMonday
&& !LeyLineRunTuesday
&& !LeyLineRunWednesday
&& !LeyLineRunThursday
&& !LeyLineRunFriday
&& !LeyLineRunSaturday
&& !LeyLineRunSunday)
{
return true;
}
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => LeyLineRunMonday,
DayOfWeek.Tuesday => LeyLineRunTuesday,
DayOfWeek.Wednesday => LeyLineRunWednesday,
DayOfWeek.Thursday => LeyLineRunThursday,
DayOfWeek.Friday => LeyLineRunFriday,
DayOfWeek.Saturday => LeyLineRunSaturday,
DayOfWeek.Sunday => LeyLineRunSunday,
_ => true
};
}
public (string type, string country) GetLeyLineConfigForToday(AutoLeyLineOutcropConfig fallback)
{
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
var (type, country) = dayOfWeek switch
{
DayOfWeek.Monday => (LeyLineMondayType, LeyLineMondayCountry),
DayOfWeek.Tuesday => (LeyLineTuesdayType, LeyLineTuesdayCountry),
DayOfWeek.Wednesday => (LeyLineWednesdayType, LeyLineWednesdayCountry),
DayOfWeek.Thursday => (LeyLineThursdayType, LeyLineThursdayCountry),
DayOfWeek.Friday => (LeyLineFridayType, LeyLineFridayCountry),
DayOfWeek.Saturday => (LeyLineSaturdayType, LeyLineSaturdayCountry),
DayOfWeek.Sunday => (LeyLineSundayType, LeyLineSundayCountry),
_ => (string.Empty, string.Empty)
};
if (string.IsNullOrWhiteSpace(type))
{
type = fallback.LeyLineOutcropType;
}
if (string.IsNullOrWhiteSpace(country))
{
country = fallback.Country;
}
return (type, country);
}
#endregion
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -121,4 +121,4 @@ public partial class OtherConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _uiCultureInfoName = "zh-Hans";
}
}
@@ -1,94 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
public enum OverlayMetricItem
{
GameFps,
ProcessingCost,
PeakProcessingCost,
CaptureCost,
TriggerCost,
SkippedTicks,
CpuUsage,
GpuUsage,
MemoryUsage,
BgiMemoryUsage,
BgiCpuUsage
}
public static class OverlayMetricItemDefaults
{
// 显式顺序同时决定遮罩三行三列显示顺序和设置页复选框顺序,不要随手改回 Enum.GetValues。
public static IReadOnlyList<OverlayMetricItem> AllItems { get; } =
[
OverlayMetricItem.GameFps,
OverlayMetricItem.ProcessingCost,
OverlayMetricItem.PeakProcessingCost,
OverlayMetricItem.CaptureCost,
OverlayMetricItem.TriggerCost,
OverlayMetricItem.SkippedTicks,
OverlayMetricItem.GpuUsage,
OverlayMetricItem.CpuUsage,
OverlayMetricItem.MemoryUsage,
OverlayMetricItem.BgiMemoryUsage,
OverlayMetricItem.BgiCpuUsage
];
public static Dictionary<string, bool> CreateDefaultItems()
{
return AllItems.ToDictionary(item => item.ToString(), IsEnabledByDefault);
}
public static bool IsEnabledByDefault(OverlayMetricItem item)
{
// 默认只开启低风险的常用实时指标;硬件传感器项由用户按需开启,读不到时也不会占位显示。
return item is OverlayMetricItem.GameFps
or OverlayMetricItem.ProcessingCost
or OverlayMetricItem.PeakProcessingCost
or OverlayMetricItem.CaptureCost
or OverlayMetricItem.SkippedTicks
or OverlayMetricItem.BgiMemoryUsage
or OverlayMetricItem.MemoryUsage;
}
public static string GetDisplayName(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏帧率",
OverlayMetricItem.ProcessingCost => "处理耗时",
OverlayMetricItem.PeakProcessingCost => "峰值耗时",
OverlayMetricItem.CaptureCost => "截图耗时",
OverlayMetricItem.TriggerCost => "触发器耗时",
OverlayMetricItem.SkippedTicks => "跳过次数",
OverlayMetricItem.CpuUsage => "CPU占用",
OverlayMetricItem.GpuUsage => "显卡占用",
OverlayMetricItem.MemoryUsage => "内存占用",
OverlayMetricItem.BgiMemoryUsage => "BGI内存",
OverlayMetricItem.BgiCpuUsage => "BGI CPU",
_ => item.ToString()
};
}
public static string GetToolTipText(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏当前渲染帧率。",
OverlayMetricItem.ProcessingCost => "BetterGI 每轮截图、识别和触发器处理的总耗时。",
OverlayMetricItem.PeakProcessingCost => "最近 5 秒内 BetterGI 单轮处理耗时的峰值。",
OverlayMetricItem.CaptureCost => "单次获取游戏画面的耗时。",
OverlayMetricItem.TriggerCost => "本轮实际执行触发器的总耗时。",
OverlayMetricItem.SkippedTicks => "上一轮未结束导致本秒跳过的调度次数。",
OverlayMetricItem.CpuUsage => "CPU 总占用率,读取不到时自动隐藏。",
OverlayMetricItem.GpuUsage => "原神当前使用显卡的整体占用率,按最繁忙 GPU 引擎计算;不可用时自动隐藏。",
OverlayMetricItem.MemoryUsage => "系统内存占用率,读取不到时自动隐藏。",
OverlayMetricItem.BgiMemoryUsage => "BetterGI 进程自身占用的私有内存。",
OverlayMetricItem.BgiCpuUsage => "BetterGI 进程自身占用的 CPU 使用率。",
_ => string.Empty
};
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -29,24 +29,7 @@ public partial class PathingConditionConfig : ObservableObject
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 低血量回复时机
private RecoverTiming? _recoverTiming;
public RecoverTiming RecoverTiming
{
get
{
if (_recoverTiming is null)
{
// 首次读取时从旧字段自动迁移
_recoverTiming = RecoverTimingMigration.Migrate(_onlyInTeleportRecover);
}
return _recoverTiming.Value;
}
set => SetProperty(ref _recoverTiming, value);
}
// 使用小道具的间隔时间(ms)
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
@@ -8,28 +8,12 @@ using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Core.Config;
public enum RecoverTiming
{
AnyWaypoint,
OnlyTeleport,
Never
}
/// <summary>
/// 从旧字段 OnlyInTeleportRecover 迁移到 RecoverTiming 枚举的共享方法
/// </summary>
internal static class RecoverTimingMigration
{
public static RecoverTiming Migrate(bool onlyInTeleportRecover)
=> onlyInTeleportRecover ? RecoverTiming.OnlyTeleport : RecoverTiming.AnyWaypoint;
}
[Serializable]
public partial class PathingPartyConfig : ObservableObject
{
// 配置是否启用,不启用会使用地图追踪内的条件配置
[ObservableProperty]
private bool _enabled = true;
private bool _enabled = false;
// 是否启用自动拾取
[ObservableProperty]
@@ -37,9 +21,6 @@ public partial class PathingPartyConfig : ObservableObject
// 切换到队伍的名称
[ObservableProperty]
private string _partyName = string.Empty;
[JsonIgnore]
public bool SkipPartySwitch { get; set; }
// 切换队伍前是否前往须弥七天神像
[ObservableProperty]
@@ -87,24 +68,7 @@ public partial class PathingPartyConfig : ObservableObject
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 低血量回复时机
private RecoverTiming? _recoverTiming;
public RecoverTiming RecoverTiming
{
get
{
if (_recoverTiming is null)
{
// 首次读取时从旧字段自动迁移
_recoverTiming = RecoverTimingMigration.Migrate(_onlyInTeleportRecover);
}
return _recoverTiming.Value;
}
set => SetProperty(ref _recoverTiming, value);
}
//允许在jsScript脚本中使用此地图追踪配置
[ObservableProperty]
private bool _jsScriptUseEnabled = true;
@@ -157,69 +121,10 @@ public partial class PathingPartyConfig : ObservableObject
//启用自动战斗配置
[ObservableProperty]
private bool _autoFightEnabled = true;
private bool _autoFightEnabled = false;
[ObservableProperty]
private AutoFightConfig _autoFightConfig = new();
// 赶路通用临界距离(米),节点小于此距离时触发接近/切换模式
[ObservableProperty]
private int _distance = 45;
/// <summary>
/// 接近停止距离(米),强制小于等于 <see cref="Distance"/>,越界时自动使用 Distance 的值。
/// </summary>
[ObservableProperty]
private int _approachStopDistance = 25;
partial void OnDistanceChanged(int value)
{
if (ApproachStopDistance > value)
{
ApproachStopDistance = value;
}
}
partial void OnApproachStopDistanceChanged(int value)
{
if (value > Distance)
{
_approachStopDistance = Distance;
}
}
[JsonIgnore]
public List<string> HurryOnAvatarList { get; } = ["","自动","玛薇卡","闲云","桑多涅","恰斯卡","流浪者","伊法","希诺宁"];
[JsonIgnore]
public List<string> TravelModeList { get; } = ["精准靠近","连续赶路"];
[ObservableProperty]
private string _hurryOnAvatar = "";
[ObservableProperty]
private string _travelMode = "精准靠近";
/// <summary>
/// 接近节点时切人步行
/// </summary>
[ObservableProperty]
private bool _switchToWalkEnabled = false;
[ObservableProperty]
private bool _mwkFlyEnabled = true;
/// <summary>
/// 玛薇卡跳飞开关
/// </summary>
[ObservableProperty]
private bool _mwkJumpFlyEnabled = true;
/// <summary>
/// 跳飞间隔(秒),闲云使用其1/2值
/// </summary>
[ObservableProperty]
private double _mwkJumpFlyIntervalSeconds = 1;
public static PathingPartyConfig BuildDefault()
{
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
@@ -227,7 +132,6 @@ public partial class PathingPartyConfig : ObservableObject
return new PathingPartyConfig
{
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
RecoverTiming = pathingConditionConfig.RecoverTiming,
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs,
AutoEatEnabled = pathingConditionConfig.AutoEatEnabled
};
@@ -50,10 +50,4 @@ public partial class ScriptConfig : ObservableObject
// 仓库新手教程是否已阅读
[ObservableProperty] private bool _guideStatus = false;
// 是否在启动时自动更新已订阅的脚本
[ObservableProperty] private bool _autoUpdateSubscribedScripts = false;
// 命令行启动时是否先自动更新已订阅脚本再执行命令
[ObservableProperty] private bool _autoUpdateBeforeCommandLineRun = false;
}
@@ -1,130 +1,55 @@
using Microsoft.Extensions.Logging;
using BetterGenshinImpact.Core.Recorder;
using SharpDX.DirectInput;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Monitor;
public sealed class DirectInputMonitor(ILogger<DirectInputMonitor> logger) : RelativeMouseInputMonitorBase(logger)
public class DirectInputMonitor : IDisposable
{
private const int Interval = 5;
private readonly object _captureLock = new();
private CaptureContext? _captureContext;
private bool _isRunning = true;
protected override void StartCore()
private readonly Mouse _mouse;
public static int Interval = 5;
public DirectInputMonitor()
{
var directInput = new DirectInput();
Mouse? mouse = null;
try
{
mouse = new Mouse(directInput);
mouse.SetCooperativeLevel(
IntPtr.Zero,
CooperativeLevel.Background | CooperativeLevel.NonExclusive);
mouse.Acquire();
var context = new CaptureContext(directInput, mouse);
lock (_captureLock)
{
context.CaptureTask = Task.Run(() => Capture(context));
_captureContext = context;
}
}
catch
{
mouse?.Dispose();
directInput.Dispose();
throw;
}
_mouse = new Mouse(directInput);
_mouse.SetCooperativeLevel(IntPtr.Zero, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
}
protected override void StopCore()
public MouseState GetMouseState()
{
CaptureContext? context;
lock (_captureLock)
{
context = _captureContext;
_captureContext = null;
context?.CancellationTokenSource.Cancel();
}
if (context == null)
{
return;
}
var captureTask = context.CaptureTask;
if (captureTask != null &&
Environment.CurrentManagedThreadId != context.CaptureThreadId)
{
try
{
captureTask.Wait();
}
catch (AggregateException ex) when (ex.InnerExceptions.All(x => x is OperationCanceledException))
{
// 正常取消
}
}
_mouse.Acquire();
return _mouse.GetCurrentState();
}
private void Capture(CaptureContext context)
public void Start()
{
context.CaptureThreadId = Environment.CurrentManagedThreadId;
try
Task.Run(() =>
{
while (!context.CancellationTokenSource.IsCancellationRequested)
while (_isRunning)
{
context.Mouse.Acquire();
MouseState state = context.Mouse.GetCurrentState();
_mouse.Acquire();
MouseState state = _mouse.GetCurrentState();
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
if (state is not { X: 0, Y: 0 })
{
var timestamp = DateTime.UtcNow.AddMilliseconds(-Interval);
Publish(new RelativeMouseMoveEventArgs(state.X, state.Y, timestamp));
}
if (context.CancellationTokenSource.Token.WaitHandle.WaitOne(Interval))
{
break;
}
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state, Kernel32.GetTickCount());
Thread.Sleep(Interval); // 10ms, equivalent to CLOCKS_PER_SEC/100
}
}
catch (Exception ex)
{
if (!context.CancellationTokenSource.IsCancellationRequested)
{
Logger.LogError(ex, "DirectInput 相对鼠标捕获异常终止");
}
}
finally
{
lock (_captureLock)
{
if (ReferenceEquals(_captureContext, context))
{
_captureContext = null;
}
}
context.Mouse.Dispose();
context.DirectInput.Dispose();
context.CancellationTokenSource.Dispose();
}
});
}
private sealed class CaptureContext(DirectInput directInput, Mouse mouse)
public void Stop()
{
public DirectInput DirectInput { get; } = directInput;
_isRunning = false;
}
public Mouse Mouse { get; } = mouse;
public CancellationTokenSource CancellationTokenSource { get; } = new();
public Task? CaptureTask { get; set; }
public int CaptureThreadId { get; set; }
public void Dispose()
{
_mouse.Dispose();
}
}
@@ -1,233 +0,0 @@
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Core.Monitor;
/// <summary>
/// 在本地会话中约束并隐藏鼠标。所有调用应来自同一个 UI 线程,
/// 以便成对恢复 ShowCursor 的显示计数。
/// </summary>
internal sealed class LocalCursorCapture(ILogger logger) : IDisposable
{
private const int MaxCursorHideAttempts = 64;
private const int SmXVirtualScreen = 76;
private const int SmYVirtualScreen = 77;
private const int SmCxVirtualScreen = 78;
private const int SmCyVirtualScreen = 79;
private NativeRect _previousClipRect;
private Rectangle _appliedBounds;
private bool _hasPreviousClipRect;
private bool _isCaptureSessionActive;
private bool _isRestrictionApplied;
private bool _isDisposed;
private int _cursorHideCallCount;
internal void Capture(Rectangle bounds)
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
if (bounds.Width <= 0 || bounds.Height <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(bounds),
bounds,
"鼠标限制区域必须具有有效宽度和高度。");
}
if (!_isCaptureSessionActive)
{
var clipRectRead = NativeMethods.GetClipCursor(out _previousClipRect);
if (!clipRectRead)
{
logger.LogWarning(
"读取现有鼠标限制区域失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
_hasPreviousClipRect =
clipRectRead && !IsVirtualDesktopBounds(_previousClipRect);
_isCaptureSessionActive = true;
}
if (_isRestrictionApplied && _appliedBounds == bounds)
{
return;
}
var clipRect = NativeRect.FromRectangle(bounds);
if (!NativeMethods.ClipCursor(ref clipRect))
{
var exception = new Win32Exception(
Marshal.GetLastWin32Error(),
"限制本地鼠标到桌面分身窗口失败");
if (!_isRestrictionApplied)
{
Release();
}
throw exception;
}
_appliedBounds = bounds;
if (!_isRestrictionApplied)
{
HideCursor();
_isRestrictionApplied = true;
}
}
internal void ReleaseTemporarily()
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
if (!_isCaptureSessionActive || !_isRestrictionApplied)
{
return;
}
if (!NativeMethods.ReleaseClipCursor(IntPtr.Zero))
{
throw new Win32Exception(
Marshal.GetLastWin32Error(),
"临时解除本地鼠标限制失败");
}
var centerX = _appliedBounds.Left + _appliedBounds.Width / 2;
var centerY = _appliedBounds.Top + _appliedBounds.Height / 2;
if (!NativeMethods.SetCursorPos(centerX, centerY))
{
logger.LogWarning(
"将本地鼠标移动到桌面分身控件中心失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
RestoreCursorVisibility();
_isRestrictionApplied = false;
_appliedBounds = Rectangle.Empty;
}
internal void Release()
{
if (!_isCaptureSessionActive)
{
return;
}
var restored = _hasPreviousClipRect
? NativeMethods.ClipCursor(ref _previousClipRect)
: NativeMethods.ReleaseClipCursor(IntPtr.Zero);
if (!restored)
{
logger.LogWarning(
"恢复本地鼠标限制区域失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
RestoreCursorVisibility();
_hasPreviousClipRect = false;
_isCaptureSessionActive = false;
_isRestrictionApplied = false;
_appliedBounds = Rectangle.Empty;
}
public void Dispose()
{
if (_isDisposed)
{
return;
}
Release();
_isDisposed = true;
GC.SuppressFinalize(this);
}
private void HideCursor()
{
var displayCount = 0;
do
{
displayCount = NativeMethods.ShowCursor(false);
_cursorHideCallCount++;
}
while (displayCount >= 0 && _cursorHideCallCount < MaxCursorHideAttempts);
if (displayCount >= 0)
{
logger.LogWarning(
"隐藏本地鼠标时 ShowCursor 显示计数仍为 {DisplayCount}",
displayCount);
}
}
private void RestoreCursorVisibility()
{
while (_cursorHideCallCount > 0)
{
_ = NativeMethods.ShowCursor(true);
_cursorHideCallCount--;
}
}
private static bool IsVirtualDesktopBounds(NativeRect rect)
{
var left = NativeMethods.GetSystemMetrics(SmXVirtualScreen);
var top = NativeMethods.GetSystemMetrics(SmYVirtualScreen);
var width = NativeMethods.GetSystemMetrics(SmCxVirtualScreen);
var height = NativeMethods.GetSystemMetrics(SmCyVirtualScreen);
return rect.Left == left
&& rect.Top == top
&& rect.Right == left + width
&& rect.Bottom == top + height;
}
[StructLayout(LayoutKind.Sequential)]
private struct NativeRect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
internal static NativeRect FromRectangle(Rectangle rectangle)
{
return new NativeRect
{
Left = rectangle.Left,
Top = rectangle.Top,
Right = rectangle.Right,
Bottom = rectangle.Bottom
};
}
}
private static class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClipCursor(out NativeRect rect);
[DllImport("user32.dll", EntryPoint = "ClipCursor", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ClipCursor(ref NativeRect rect);
[DllImport("user32.dll", EntryPoint = "ClipCursor", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseClipCursor(nint rect);
[DllImport("user32.dll")]
internal static extern int ShowCursor(
[MarshalAs(UnmanagedType.Bool)] bool show);
[DllImport("user32.dll")]
internal static extern int GetSystemMetrics(int index);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetCursorPos(int x, int y);
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
@@ -100,12 +100,7 @@ public partial class MouseKeyMonitor
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, DateTime.UtcNow);
if (SystemControl.IsGenshinImpactActive())
{
ChatUiHotkeyGuard.PrimeFromChatKey(e.KeyCode);
}
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
// 热键按下事件
HotKeyDown(sender, e);
@@ -143,7 +138,7 @@ public partial class MouseKeyMonitor
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, DateTime.UtcNow);
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, Kernel32.GetTickCount());
// 热键松开事件
HotKeyUp(sender, e);
@@ -188,7 +183,7 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseDownExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseDown: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e, DateTime.UtcNow);
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e);
if (e.Button != MouseButtons.Left)
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
@@ -198,7 +193,7 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseUpExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseUp: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e, DateTime.UtcNow);
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e);
if (e.Button != MouseButtons.Left)
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
@@ -208,13 +203,13 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseMoveExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e, DateTime.UtcNow);
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e);
}
private void GlobalHookMouseWheelExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e, DateTime.UtcNow);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e);
}
public void Unsubscribe()
@@ -1,497 +0,0 @@
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Threading;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Monitor;
public sealed class RawInputMonitor(ILogger<RawInputMonitor> logger)
: RelativeMouseInputMonitorBase(logger)
{
private static readonly TimeSpan InitializationTimeout = TimeSpan.FromSeconds(10);
private const ushort GenericDesktopUsagePage = 0x01;
private const ushort MouseUsage = 0x02;
private const ushort KeyBreakFlag = 0x01;
private const ushort InvalidVirtualKey = 0x00FF;
private static readonly nint HwndMessage = new(-3);
// 键盘输入不再复用相对鼠标监听器的采集生命周期,避免覆盖 RDP ActiveX 的进程级注册。
private readonly object _sourceLock = new();
private RawInputThreadContext? _context;
private long _lifecycleVersion;
protected override void StartCore()
{
RawInputThreadContext context;
lock (_sourceLock)
{
_lifecycleVersion++;
if (_context != null)
{
return;
}
context = new RawInputThreadContext();
context.Thread = new Thread(() => RunMessageLoop(context))
{
IsBackground = true,
Name = "BetterGI RawInput Monitor"
};
context.Thread.SetApartmentState(ApartmentState.STA);
_context = context;
}
try
{
context.Thread.Start();
}
catch
{
ClearContext(context);
context.Initialized.Dispose();
throw;
}
if (!context.Initialized.Wait(InitializationTimeout))
{
ClearContext(context);
RequestStop(context);
throw new TimeoutException(
$"Raw Input 采集线程初始化超过 {InitializationTimeout.TotalSeconds:0} 秒。");
}
context.Initialized.Dispose();
if (context.InitializationException == null)
{
return;
}
ClearContext(context);
throw new InvalidOperationException("Raw Input 初始化失败", context.InitializationException);
}
protected override void StopCore()
{
RawInputThreadContext? context;
long stopVersion;
lock (_sourceLock)
{
stopVersion = ++_lifecycleVersion;
context = _context;
}
if (context?.Dispatcher == null || context.Thread == null)
{
return;
}
if (Thread.CurrentThread == context.Thread)
{
_ = context.Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new Action(() => StopOnMessageThread(context, stopVersion)));
return;
}
bool stopped;
try
{
stopped = context.Dispatcher.Invoke(
() => StopOnMessageThread(context, stopVersion),
DispatcherPriority.Send);
}
catch (TaskCanceledException)
{
return;
}
catch (InvalidOperationException)
{
return;
}
if (stopped)
{
context.Thread.Join();
}
}
internal static bool TryGetRelativeMovement(
in User32.RAWINPUT rawInput,
out int deltaX,
out int deltaY)
{
deltaX = 0;
deltaY = 0;
if (rawInput.header.dwType != User32.RIM_TYPE.RIM_TYPEMOUSE)
{
return false;
}
var mouse = rawInput.data.mouse;
if ((mouse.usFlags & User32.MouseState.MOUSE_MOVE_ABSOLUTE) != 0)
{
return false;
}
deltaX = mouse.lLastX;
deltaY = mouse.lLastY;
return deltaX != 0 || deltaY != 0;
}
internal static bool TryGetRelativeMovementFromBuffer(
nint rawInputBuffer,
uint rawInputSize,
out int deltaX,
out int deltaY)
{
deltaX = 0;
deltaY = 0;
var headerSize = Marshal.SizeOf<User32.RAWINPUTHEADER>();
var mouseSize = Marshal.SizeOf<RawMouseData>();
if (rawInputSize < headerSize + mouseSize)
{
return false;
}
var header = Marshal.PtrToStructure<User32.RAWINPUTHEADER>(rawInputBuffer);
if (header.dwType != User32.RIM_TYPE.RIM_TYPEMOUSE)
{
return false;
}
var mouse = Marshal.PtrToStructure<RawMouseData>(IntPtr.Add(rawInputBuffer, headerSize));
if ((mouse.Flags & (ushort)User32.MouseState.MOUSE_MOVE_ABSOLUTE) != 0)
{
return false;
}
deltaX = mouse.LastX;
deltaY = mouse.LastY;
return deltaX != 0 || deltaY != 0;
}
internal static bool TryGetKeyboardInputFromBuffer(
nint rawInputBuffer,
uint rawInputSize,
out ushort virtualKey,
out ushort scanCode,
out ushort flags,
out bool isKeyDown)
{
virtualKey = 0;
scanCode = 0;
flags = 0;
isKeyDown = false;
var headerSize = Marshal.SizeOf<User32.RAWINPUTHEADER>();
var keyboardSize = Marshal.SizeOf<RawKeyboardData>();
if (rawInputSize < headerSize + keyboardSize)
{
return false;
}
var header = Marshal.PtrToStructure<User32.RAWINPUTHEADER>(rawInputBuffer);
if (header.dwType != User32.RIM_TYPE.RIM_TYPEKEYBOARD)
{
return false;
}
var keyboard = Marshal.PtrToStructure<RawKeyboardData>(
IntPtr.Add(rawInputBuffer, headerSize));
if (keyboard.VirtualKey == InvalidVirtualKey)
{
return false;
}
virtualKey = keyboard.VirtualKey;
scanCode = keyboard.MakeCode;
flags = keyboard.Flags;
isKeyDown = (keyboard.Flags & KeyBreakFlag) == 0;
return true;
}
private void RunMessageLoop(RawInputThreadContext context)
{
try
{
context.Dispatcher = Dispatcher.CurrentDispatcher;
context.HwndSource = new HwndSource(new HwndSourceParameters("BetterGI RawInput Monitor")
{
ParentWindow = HwndMessage,
WindowStyle = 0
});
context.HwndSource.AddHook(WindowProc);
RegisterRawInput(context);
context.Registered = true;
if (Volatile.Read(ref context.StopRequested) != 0)
{
throw new OperationCanceledException("Raw Input 初始化已取消。");
}
context.InitializationSucceeded = true;
context.Initialized.Set();
Dispatcher.Run();
}
catch (Exception ex)
{
if (!context.InitializationSucceeded)
{
context.InitializationException = ex;
context.Initialized.Set();
}
Logger.LogError(ex, "Raw Input 消息窗口异常终止");
}
finally
{
CleanupContext(context);
lock (_sourceLock)
{
if (ReferenceEquals(_context, context))
{
_context = null;
_lifecycleVersion++;
}
}
}
}
private bool StopOnMessageThread(RawInputThreadContext context, long stopVersion)
{
lock (_sourceLock)
{
if (stopVersion != _lifecycleVersion || !ReferenceEquals(_context, context))
{
return false;
}
CleanupContext(context);
_context = null;
context.Dispatcher?.BeginInvokeShutdown(DispatcherPriority.Send);
return true;
}
}
private void ClearContext(RawInputThreadContext context)
{
lock (_sourceLock)
{
if (ReferenceEquals(_context, context))
{
_context = null;
_lifecycleVersion++;
}
}
}
private static void RequestStop(RawInputThreadContext context)
{
Interlocked.Exchange(ref context.StopRequested, 1);
try
{
context.Dispatcher?.BeginInvokeShutdown(DispatcherPriority.Send);
}
catch (InvalidOperationException)
{
// Dispatcher 已关闭,无需再次请求退出。
}
}
private void RegisterRawInput(RawInputThreadContext context)
{
var devices = new[]
{
new User32.RAWINPUTDEVICE
{
usUsagePage = GenericDesktopUsagePage,
usUsage = MouseUsage,
dwFlags = User32.RIDEV.RIDEV_INPUTSINK,
hwndTarget = context.HwndSource!.Handle
}
};
if (!User32.RegisterRawInputDevices(
devices,
(uint)devices.Length,
(uint)Marshal.SizeOf<User32.RAWINPUTDEVICE>()))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "注册 Raw Input 鼠标设备失败");
}
}
private void CleanupContext(RawInputThreadContext context)
{
if (context.Registered)
{
var devices = new[]
{
new User32.RAWINPUTDEVICE
{
usUsagePage = GenericDesktopUsagePage,
usUsage = MouseUsage,
dwFlags = User32.RIDEV.RIDEV_REMOVE,
hwndTarget = HWND.NULL
}
};
if (!User32.RegisterRawInputDevices(
devices,
(uint)devices.Length,
(uint)Marshal.SizeOf<User32.RAWINPUTDEVICE>()))
{
Logger.LogWarning(
"注销 Raw Input 鼠标设备失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
context.Registered = false;
}
if (context.HwndSource != null)
{
context.HwndSource.RemoveHook(WindowProc);
context.HwndSource.Dispose();
context.HwndSource = null;
}
}
private nint WindowProc(
nint hwnd,
int message,
nint wParam,
nint lParam,
ref bool handled)
{
if (message != (int)User32.WindowMessage.WM_INPUT)
{
return IntPtr.Zero;
}
try
{
ProcessRawInput(lParam);
}
catch (Exception ex)
{
Logger.LogError(ex, "读取 Raw Input 鼠标数据失败");
}
// 保持 handled = false,让默认窗口过程完成 WM_INPUT 的必要清理。
handled = false;
return IntPtr.Zero;
}
private void ProcessRawInput(nint rawInputHandle)
{
uint size = 0;
uint headerSize = (uint)Marshal.SizeOf<User32.RAWINPUTHEADER>();
var handle = new User32.HRAWINPUT(rawInputHandle);
if (User32.GetRawInputData(
handle,
User32.RID.RID_INPUT,
IntPtr.Zero,
ref size,
headerSize) == uint.MaxValue)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (size == 0)
{
return;
}
var buffer = Marshal.AllocHGlobal(checked((int)size));
try
{
var readSize = size;
uint result = User32.GetRawInputData(
handle,
User32.RID.RID_INPUT,
buffer,
ref readSize,
headerSize);
if (result == uint.MaxValue)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var timestamp = DateTime.UtcNow;
if (TryGetRelativeMovementFromBuffer(buffer, readSize, out int deltaX, out int deltaY))
{
Publish(new RelativeMouseMoveEventArgs(deltaX, deltaY, timestamp));
return;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
private sealed class RawInputThreadContext
{
public Thread? Thread { get; set; }
public Dispatcher? Dispatcher { get; set; }
public HwndSource? HwndSource { get; set; }
public ManualResetEventSlim Initialized { get; } = new();
public Exception? InitializationException { get; set; }
public bool InitializationSucceeded { get; set; }
public bool Registered { get; set; }
public int StopRequested;
}
[StructLayout(LayoutKind.Sequential)]
private readonly struct RawMouseData
{
public ushort Flags { get; init; }
public ushort Reserved { get; init; }
public ushort ButtonFlags { get; init; }
public short ButtonData { get; init; }
public uint RawButtons { get; init; }
public int LastX { get; init; }
public int LastY { get; init; }
public uint ExtraInformation { get; init; }
}
[StructLayout(LayoutKind.Sequential)]
private readonly struct RawKeyboardData
{
public ushort MakeCode { get; init; }
public ushort Flags { get; init; }
public ushort Reserved { get; init; }
public ushort VirtualKey { get; init; }
public uint Message { get; init; }
public uint ExtraInformation { get; init; }
}
}
@@ -1,60 +0,0 @@
using System;
namespace BetterGenshinImpact.Core.Monitor;
public enum RelativeMouseInputType
{
DirectInput,
RawInput
}
public sealed class RelativeMouseMoveEventArgs(int deltaX, int deltaY, DateTime timestamp) : EventArgs
{
public int DeltaX { get; } = deltaX;
public int DeltaY { get; } = deltaY;
public DateTime Timestamp { get; } = timestamp;
}
public interface IRelativeMouseInputMonitor
{
/// <summary>
/// 订阅相对鼠标移动事件。首个订阅会启动采集,最后一个订阅释放后停止采集。
/// 回调在采集线程执行,需要操作 UI 时由订阅方自行切换到 UI 线程。
/// </summary>
IDisposable Subscribe(EventHandler<RelativeMouseMoveEventArgs> handler);
}
public interface IRelativeMouseInputMonitorFactory
{
IRelativeMouseInputMonitor Get(RelativeMouseInputType type);
}
public sealed class RawKeyboardInputEventArgs(
ushort virtualKey,
ushort scanCode,
ushort flags,
bool isKeyDown,
DateTime timestamp) : EventArgs
{
public ushort VirtualKey { get; } = virtualKey;
public ushort ScanCode { get; } = scanCode;
public ushort Flags { get; } = flags;
public bool IsKeyDown { get; } = isKeyDown;
public DateTime Timestamp { get; } = timestamp;
}
public interface IRawKeyboardInputMonitor
{
/// <summary>
/// 订阅 Raw Input 键盘事件。首个鼠标或键盘订阅会启动采集,
/// 最后一个订阅释放后停止采集。回调在采集线程执行。
/// 包含 RDP ActiveX 的进程不应直接实现此接口,否则会覆盖 RDP 的键盘 Raw Input 注册。
/// </summary>
IDisposable SubscribeKeyboard(EventHandler<RawKeyboardInputEventArgs> handler);
}
@@ -1,171 +0,0 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace BetterGenshinImpact.Core.Monitor;
public abstract class RelativeMouseInputMonitorBase(ILogger logger) : IRelativeMouseInputMonitor, IDisposable
{
private readonly object _subscriptionLock = new();
private readonly Dictionary<long, EventHandler<RelativeMouseMoveEventArgs>> _handlers = [];
private long _nextSubscriptionId;
private bool _isStarted;
private bool _isStopping;
private bool _isDisposed;
protected ILogger Logger { get; } = logger;
public IDisposable Subscribe(EventHandler<RelativeMouseMoveEventArgs> handler)
{
ArgumentNullException.ThrowIfNull(handler);
long subscriptionId;
lock (_subscriptionLock)
{
while (_isStopping)
{
System.Threading.Monitor.Wait(_subscriptionLock);
}
ObjectDisposedException.ThrowIf(_isDisposed, this);
subscriptionId = ++_nextSubscriptionId;
_handlers.Add(subscriptionId, handler);
if (!_isStarted)
{
try
{
StartCore();
_isStarted = true;
}
catch
{
_handlers.Remove(subscriptionId);
throw;
}
}
}
return new Subscription(this, subscriptionId);
}
protected void Publish(RelativeMouseMoveEventArgs eventArgs)
{
EventHandler<RelativeMouseMoveEventArgs>[] handlers;
lock (_subscriptionLock)
{
if (_isDisposed || _handlers.Count == 0)
{
return;
}
handlers = _handlers.Values.ToArray();
}
foreach (var handler in handlers)
{
try
{
handler(this, eventArgs);
}
catch (Exception ex)
{
Logger.LogError(ex, "相对鼠标移动事件订阅方执行失败");
}
}
}
protected abstract void StartCore();
protected abstract void StopCore();
public virtual void Dispose()
{
bool shouldStop;
lock (_subscriptionLock)
{
while (_isStopping)
{
System.Threading.Monitor.Wait(_subscriptionLock);
}
if (_isDisposed)
{
return;
}
_isDisposed = true;
_handlers.Clear();
shouldStop = _isStarted;
_isStarted = false;
_isStopping = shouldStop;
}
if (shouldStop)
{
try
{
StopCore();
}
finally
{
CompleteStop();
}
}
GC.SuppressFinalize(this);
}
private void Unsubscribe(long subscriptionId)
{
bool shouldStop;
lock (_subscriptionLock)
{
if (_isDisposed || !_handlers.Remove(subscriptionId))
{
return;
}
shouldStop = _handlers.Count == 0 && _isStarted;
if (shouldStop)
{
_isStarted = false;
_isStopping = true;
}
}
if (shouldStop)
{
try
{
StopCore();
}
finally
{
CompleteStop();
}
}
}
private void CompleteStop()
{
lock (_subscriptionLock)
{
_isStopping = false;
System.Threading.Monitor.PulseAll(_subscriptionLock);
}
}
private sealed class Subscription(RelativeMouseInputMonitorBase owner, long subscriptionId) : IDisposable
{
private RelativeMouseInputMonitorBase? _owner = owner;
public void Dispose()
{
Interlocked.Exchange(ref _owner, null)?.Unsubscribe(subscriptionId);
}
}
}
@@ -1,18 +0,0 @@
using System;
namespace BetterGenshinImpact.Core.Monitor;
public sealed class RelativeMouseInputMonitorFactory(
DirectInputMonitor directInputMonitor,
RawInputMonitor rawInputMonitor) : IRelativeMouseInputMonitorFactory
{
public IRelativeMouseInputMonitor Get(RelativeMouseInputType type)
{
return type switch
{
RelativeMouseInputType.DirectInput => directInputMonitor,
RelativeMouseInputType.RawInput => rawInputMonitor,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, "不支持的相对鼠标输入类型")
};
}
}
@@ -44,14 +44,4 @@ public readonly record struct OcrVersionConfig(
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
public static OcrVersionConfig PpOcrV6 = new(
"PP-OCRv6",
OcrImgMode.BGR,
false,
new OcrNormalizeImage(
1.0f / 255.0f,
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Globalization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
@@ -100,9 +100,6 @@ public class OcrFactory : IDisposable
PaddleOcrModelConfig.V5 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5),
PaddleOcrModelConfig.V6 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V6),
PaddleOcrModelConfig.V4 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V4),
@@ -123,6 +120,7 @@ public class OcrFactory : IDisposable
};
}
public Task Unload()
{
if (_paddleOcrService is not IDisposable disposable)
@@ -13,17 +13,8 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
{
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
/// <summary>Gets or sets the detection side length limit used by the Python det preprocess.</summary>
public int LimitSideLen { get; set; } = 960;
/// <summary>Gets or sets the maximum size limit after resizing.</summary>
public int MaxSideLimit { get; set; } = 4000;
/// <summary>Gets or sets the side length limit type. Supports max/min/resize_long.</summary>
public string LimitType { get; set; } = "max";
/// <summary>Gets or sets the shortest side threshold used for tiny-image upscaling.</summary>
public int SmallImageLimitSideLen { get; set; } = 64;
/// <summary>Gets or sets the maximum size for resizing the input image.</summary>
public int? MaxSize { get; set; } = 960;
/// <summary>Gets or sets the size for dilation during preprocessing.</summary>
public int? DilatedSize { get; set; } = 2;
@@ -80,24 +71,20 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
var contours = dilated.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);
// PaddleOCR Python keeps ratio_h/ratio_w separately. Because we align det resize to that behavior,
// map contour points back with independent X/Y scales before building rotated rects.
var scaleX = 1.0 * src.Width / resizedSize.Width;
var scaleY = 1.0 * src.Height / resizedSize.Height;
// var size = src.Size();
var scaleRate = 1.0 * src.Width / resizedSize.Width;
var rects = contours
.Where(x => BoxScoreThreshold == null || GetScore(x, pred) > BoxScoreThreshold)
.Select(contour =>
contour.Select(point => new Point2f((float)(point.X * scaleX), (float)(point.Y * scaleY))).ToArray())
.Select(Cv2.MinAreaRect)
.Where(x => x.Size.Width > MinSize && x.Size.Height > MinSize)
.Select(rect =>
{
var minEdge = Math.Min(rect.Size.Width, rect.Size.Height);
Size2f newSize = new(
rect.Size.Width + UnclipRatio * minEdge,
rect.Size.Height + UnclipRatio * minEdge);
RotatedRect largerRect = new(rect.Center, newSize, rect.Angle);
(rect.Size.Width + UnclipRatio * minEdge) * scaleRate,
(rect.Size.Height + UnclipRatio * minEdge) * scaleRate);
RotatedRect largerRect = new(rect.Center * scaleRate, newSize, rect.Angle);
return largerRect;
})
.OrderBy(v => v.Center.Y)
@@ -120,14 +107,11 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
// Align with PaddleOCR Python DetResizeForTest:
// 1. tiny image padding when h + w < 64
// 2. keep current max/960 behavior for normal images
// 3. switch to limit_type=min for very small crops so det can see the text
using (var resized = MatResizeForDetection(padded))
// DetResizeForTest resize_long
using (var resized = MatResize(padded, MaxSize))
{
resizedSize = new Size(resized.Width, resized.Height);
padded = resized.Clone();
padded = MatPadding32(resized);
}
using (var _ = padded)
@@ -166,80 +150,19 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
/// <summary>
/// 按 PaddleOCR Python 的 DetResizeForTest 思路缩放图像:
/// 小图先补边,再按 max/min/resize_long 规则缩放,并对齐到 32 的倍数。
/// 按比例缩放图像,保持长边不超过 maxSize。
/// </summary>
/// <param name="src"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
private Mat MatResizeForDetection(Mat src)
private static Mat MatResize(Mat src, int? maxSize)
{
using var preprocessed = PrepareTinyImage(src);
if (maxSize == null) return src.Clone();
var size = preprocessed.Size();
var height = size.Height;
var width = size.Width;
var limitSideLen = LimitSideLen;
var limitType = LimitType;
if (Math.Min(height, width) < SmallImageLimitSideLen)
{
limitSideLen = SmallImageLimitSideLen;
limitType = "min";
}
var ratio = CalculateResizeRatio(width, height, limitSideLen, limitType);
var resizeHeight = (int)(height * ratio);
var resizeWidth = (int)(width * ratio);
if (Math.Max(resizeHeight, resizeWidth) > MaxSideLimit)
{
var maxSideRatio = 1.0 * MaxSideLimit / Math.Max(resizeHeight, resizeWidth);
resizeHeight = (int)(resizeHeight * maxSideRatio);
resizeWidth = (int)(resizeWidth * maxSideRatio);
}
resizeHeight = Math.Max((int)Math.Round(resizeHeight / 32.0) * 32, 32);
resizeWidth = Math.Max((int)Math.Round(resizeWidth / 32.0) * 32, 32);
if (resizeWidth <= 0 || resizeHeight <= 0)
{
throw new InvalidOperationException(
$"Invalid det resize target size: {resizeWidth}x{resizeHeight}, src={width}x{height}");
}
using var resized = preprocessed.Resize(new Size(resizeWidth, resizeHeight));
return MatPadding32(resized);
}
private static Mat PrepareTinyImage(Mat src)
{
if (src.Width + src.Height >= 64)
{
return src.Clone();
}
var newHeight = Math.Max(32, src.Height);
var newWidth = Math.Max(32, src.Width);
var padded = new Mat(newHeight, newWidth, src.Type(), Scalar.Black);
src.CopyTo(padded[new Rect(0, 0, src.Width, src.Height)]);
return padded;
}
private static double CalculateResizeRatio(int width, int height, int limitSideLen, string limitType)
{
return limitType switch
{
"max" => Math.Max(height, width) > limitSideLen
? 1.0 * limitSideLen / Math.Max(height, width)
: 1.0,
"min" => Math.Min(height, width) < limitSideLen
? 1.0 * limitSideLen / Math.Min(height, width)
: 1.0,
"resize_long" => 1.0 * limitSideLen / Math.Max(height, width),
_ => throw new ArgumentOutOfRangeException(nameof(limitType), limitType,
"limitType only supports max/min/resize_long")
};
var size = src.Size();
var longEdge = Math.Max(size.Width, size.Height);
var scaleRate = 1.0 * maxSize.Value / longEdge;
return scaleRate < 1.0 ? src.Resize(default, scaleRate, scaleRate) : src.Clone();
}
private static float GetScore(Point[] contour, Mat pred)
@@ -274,4 +197,4 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
public string GetConfigName => config.Name;
}
}
@@ -7,7 +7,6 @@ using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using YamlDotNet.Core;
@@ -101,7 +100,7 @@ public class PaddleOcrService : IOcrService, IDisposable
recognitionModel,
recognitionVersion,
recLabel ?? (() => DefaultRecLabelFunc(recognitionModel)),
preHeatImagePath ?? TestImagePath);
TestImagePath);
}
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
@@ -130,12 +129,6 @@ public class PaddleOcrService : IOcrService, IDisposable
BgiOnnxModel.PaddleOcrRecV5,
OcrVersionConfig.PpOcrV5);
public static readonly PaddleOcrModelType V6 = Create(
BgiOnnxModel.PaddleOcrDetV6,
OcrVersionConfig.PpOcrV6,
BgiOnnxModel.PaddleOcrRecV6,
OcrVersionConfig.PpOcrV6);
public static readonly PaddleOcrModelType V5Latin = Create(
BgiOnnxModel.PaddleOcrDetV5,
OcrVersionConfig.PpOcrV5,
@@ -253,7 +246,7 @@ public class PaddleOcrService : IOcrService, IDisposable
_localRecModel = modelsRec;
// 预热模型
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
// Debug输出结果
var preHeatResult = RunAll(preHeatImageMat, 1);
@@ -291,7 +284,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var str = _localRecModel.Run(mat).Text;
var time = Stopwatch.GetElapsedTime(startTime);
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
return str;
}
@@ -300,7 +293,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var result = RunAll(mat);
var time = Stopwatch.GetElapsedTime(startTime);
// Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
return result;
}
@@ -2,6 +2,7 @@ using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
@@ -94,33 +95,21 @@ public class Rec(
// .AsParallel()
.Select(src =>
{
Mat? channel3 = default;
try
using var channel3 = src.Channels() switch
{
channel3 = src.Channels() switch
{
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
return result;
}
finally
{
// Only dispose Mats created in this scope
if (channel3 != null && !ReferenceEquals(channel3, src))
{
channel3.Dispose();
}
}
return result;
})
.Select(inputTensor =>
{
@@ -152,46 +141,46 @@ public class Rec(
{
var resultArray = resultTensor.Item2;
var resultShape = resultTensor.Item1;
var labelCount = resultShape[2];
var charCount = resultShape[1];
GCHandle dataHandle = default;
try
{
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
var dataPtr = dataHandle.AddrOfPinnedObject();
var labelCount = resultShape[2];
var charCount = resultShape[1];
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
var batchOffset = i * charCount * labelCount;
for (var n = 0; n < charCount; ++n)
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
var rowOffset = batchOffset + n * labelCount;
var maxVal = float.MinValue;
var maxIndex = 0;
for (var c = 0; c < labelCount; c++)
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
for (var n = 0; n < charCount; ++n)
{
var value = resultArray[rowOffset + c];
if (value > maxVal)
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
var maxIdx = new int[2];
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
{
maxVal = value;
maxIndex = c;
score += (float)maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
}
lastIndex = maxIdx[1];
}
if (maxIndex > 0 && !(n > 0 && maxIndex == lastIndex))
{
score += maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIndex, labels));
}
lastIndex = maxIndex;
}
var text = sb.ToString();
return new OcrRecognizerResult(text, text.Length > 0 ? score / text.Length : 0);
})
.ToArray();
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
})
.ToArray();
}
finally
{
dataHandle.Free();
}
}).ToArray();
}
public string GetConfigName => config.Name;
}
}
@@ -407,11 +407,11 @@ public class BgiOnnxFactory
break;
case ProviderType.Cpu:
sessionOptions.AppendExecutionProvider_CPU();
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
// {
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
// }
if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
{
sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
}
break;
case ProviderType.Dnnl:
sessionOptions.AppendExecutionProvider_Dnnl();
@@ -44,35 +44,12 @@ public class BgiOnnxModel
/// </summary>
public static readonly BgiOnnxModel BgiWorld = Register("BgiTree", @"Assets\Model\World\bgi_world.onnx");
/// <summary>
/// 矿物识别模型
/// </summary>
public static readonly BgiOnnxModel BgiMine = Register("BgiMine", @"Assets\Model\Mine\bgi_mine.onnx");
/// <summary>
/// 角色识别
/// </summary>
public static readonly BgiOnnxModel BgiAvatarSide =
Register("BgiAvatarSide", @"Assets\Model\Common\avatar_side_classify_sim.onnx");
/// <summary>
/// Q技能冷却分类模型
/// </summary>
public static readonly BgiOnnxModel BgiQClassify =
Register("BgiQClassify", @"Assets\Model\Common\q_classify_sim.onnx");
/// <summary>
/// 队伍配置角色头像识别模型
/// </summary>
public static readonly BgiOnnxModel AvatarGridIcon =
Register("AvatarGridIcon", @"Assets\Model\AvatarGridIcon\avatar.onnx");
/// <summary>
/// Silero 人声检测模型
/// </summary>
public static readonly BgiOnnxModel SileroVad =
Register("SileroVad", @"Assets\Model\Vad\silero_vad.onnx");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -85,12 +62,6 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrDetV5 =
Register("PpOcrDetV5", @"Assets\Model\PaddleOCR\Det\V5\PP-OCRv5_mobile_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 检测模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrDetV6 =
Register("PpOcrDetV6", @"Assets\Model\PaddleOCR\Det\V6\PP-OCRv6_small_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V4 识别模型
/// </summary>
@@ -109,12 +80,6 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrRecV5 =
Register("PpOcrRecV5", @"Assets\Model\PaddleOCR\Rec\V5\PP-OCRv5_mobile_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 识别模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrRecV6 =
Register("PpOcrRecV6", @"Assets\Model\PaddleOCR\Rec\V6\PP-OCRv6_small_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V5 拉丁文 识别模型
/// </summary>
@@ -174,4 +139,4 @@ public class BgiOnnxModel
RegisteredModels.Add(model);
return model;
}
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
@@ -8,9 +8,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
@@ -31,7 +31,7 @@ public class PickTextInference : ITextInference
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
_wordDictionary = JsonConvert.DeserializeObject<Dictionary<int, string>>(json) ??
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ??
throw new Exception("index_2_word.json deserialize failed");
}
@@ -116,4 +116,4 @@ public class PickTextInference : ITextInference
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
}
}
}
@@ -6,7 +6,7 @@ namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
public class TextInferenceFactory
{
public static readonly Lazy<ITextInference> Pick = new(() => Create(OcrEngineTypes.YapModel));
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
public static ITextInference Create(OcrEngineTypes type)
{
@@ -87,24 +87,4 @@ public static class CommonExtension
{
return list.ConvertAll(ToPoint2d);
}
/// <summary>
/// 将矩形钳位到指定尺寸范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, int maxWidth, int maxHeight)
{
int x1 = Math.Clamp(rect.X, 0, maxWidth);
int y1 = Math.Clamp(rect.Y, 0, maxHeight);
int x2 = Math.Clamp(rect.X + rect.Width, 0, maxWidth);
int y2 = Math.Clamp(rect.Y + rect.Height, 0, maxHeight);
return new Rect(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// 将矩形钳位到 Mat 范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, Mat mat)
{
return rect.ClampTo(mat.Cols, mat.Rows);
}
}
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
@@ -26,7 +24,7 @@ public static class Feature2DExtensions
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
{
Mat trainDescriptors = new();
var img = Bv.ImRead(trainImagePath, ImreadModes.Grayscale);
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
@@ -193,53 +191,6 @@ public static class Feature2DExtensions
return transformedCenter[0];
}
public static Point2f KnnMatchLocal(
this Feature2D feature2D,
KeyPointFeatureBlock[][] splitBlocks,
Mat trainDescriptors,
Size trainImageSize,
Rect searchRect,
Mat queryMat,
Mat? queryMatMask = null,
int expandCells = 2)
{
if (splitBlocks.Length == 0 || splitBlocks[0].Length == 0)
{
return default;
}
try
{
var (rowStart, rowEnd, colStart, colEnd) = KeyPointFeatureBlockHelper.GetCellRange(
trainImageSize,
splitBlocks.Length,
splitBlocks[0].Length,
searchRect);
var mergedBlock = KeyPointFeatureBlockHelper.MergeFeaturesInRange(
splitBlocks,
trainDescriptors,
rowStart - expandCells,
rowEnd + expandCells,
colStart - expandCells,
colEnd + expandCells);
var descriptors = mergedBlock.Descriptor;
if (mergedBlock.KeyPointArray.Length == 0 || descriptors == null || descriptors.Empty())
{
descriptors?.Dispose();
return default;
}
using (descriptors)
{
return feature2D.KnnMatch(mergedBlock.KeyPointArray, descriptors, queryMat, queryMatMask);
}
}
catch
{
return default;
}
}
public static Point2f[] KnnMatchCorners(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
@@ -308,4 +259,4 @@ public static class Feature2DExtensions
}
#endregion Knn匹配
}
}
@@ -1,4 +1,4 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections.Generic;
@@ -6,7 +6,8 @@ using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
/// <summary>
/// 模板匹配辅助方法
/// 多目标模板匹配demo
/// https://github.com/shimat/opencvsharp/issues/182
/// </summary>
public class MatchTemplateHelper
{
@@ -23,12 +24,46 @@ public class MatchTemplateHelper
/// <returns>左上角的标点,由于(0,0)点作为未匹配的结果,所以不能做完全相同的模板匹配</returns>
public static Point MatchTemplate(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat = null, double threshold = 0.8)
{
return FindBestMatch(srcMat, dstMat, matchMode, maskMat, threshold)?.Location ?? default;
try
{
using var result = new Mat();
Cv2.MatchTemplate(srcMat, dstMat, result, matchMode, maskMat!);
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.CCoeff or TemplateMatchModes.CCorr)
{
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax);
}
Cv2.MinMaxLoc(result, out var minValue, out var maxValue, out var minLoc, out var maxLoc);
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.SqDiffNormed)
{
if (minValue <= 1 - threshold)
{
return minLoc;
}
}
else
{
if (maxValue >= threshold)
{
return maxLoc;
}
}
return default;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogDebug(ex, ex.Message);
return default;
}
}
/// <summary>
/// 模板匹配多个结果
/// 从一次匹配的结果矩阵中提取候选,并在当前模板内执行 NMS
/// 不好用
/// </summary>
/// <param name="srcMat"></param>
/// <param name="dstMat"></param>
@@ -39,14 +74,34 @@ public class MatchTemplateHelper
[Obsolete]
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8, int maxCount = 8)
{
var matches = FindMatches(srcMat, dstMat, TemplateMatchModes.CCoeffNormed, maskMat, threshold, maxCount);
var points = new List<Point>(matches.Count);
foreach (var match in matches)
var points = new List<Point>();
try
{
points.Add(match.Location);
}
using var result = new Mat();
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed, maskMat!);
return points;
var mask = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.White);
var maskSub = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.Black);
while (true)
{
Cv2.MinMaxLoc(result, out _, out var maxValue, out _, out var maxLoc, mask);
var maskRect = new Rect(maxLoc.X, maxLoc.Y, dstMat.Width, dstMat.Height);
maskSub.Rectangle(maskRect, Scalar.White, -1);
mask -= maskSub;
if (maxValue >= threshold)
points.Add(maxLoc);
else
break;
}
return points;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogDebug(ex, ex.Message);
return points;
}
}
public static List<Point> MatchTemplateMulti(Mat srcMat, Mat dstMat, double threshold)
@@ -56,6 +111,7 @@ public class MatchTemplateHelper
/// <summary>
/// 在一张图中查找多个模板
/// 查到一个遮盖一个的笨方法,效率很低,但是很准确
/// </summary>
/// <param name="srcMat"></param>
/// <param name="imgSubDictionary"></param>
@@ -66,11 +122,21 @@ public class MatchTemplateHelper
var dictionary = new Dictionary<string, List<Point>>();
foreach (var kvp in imgSubDictionary)
{
var matches = FindMatches(srcMat, kvp.Value, TemplateMatchModes.CCoeffNormed, null, threshold, -1);
var list = new List<Point>(matches.Count);
foreach (var match in matches)
var list = new List<Point>();
while (true)
{
list.Add(match.Location);
var point = MatchTemplate(srcMat, kvp.Value, TemplateMatchModes.CCoeffNormed, null, threshold);
if (point != new Point())
{
// 把结果给遮掩掉,避免重复识别
Cv2.Rectangle(srcMat, point, new Point(point.X + kvp.Value.Width, point.Y + kvp.Value.Height), Scalar.Black, -1);
list.Add(point);
}
else
{
break;
}
}
dictionary.Add(kvp.Key, list);
@@ -81,22 +147,30 @@ public class MatchTemplateHelper
/// <summary>
/// 在一张图中查找多个模板
/// 查到一个遮盖一个的笨方法,效率很低,但是很准确
/// </summary>
/// <param name="srcMat"></param>
/// <param name="imgSubList"></param>
/// <param name="threshold"></param>
/// <returns></returns>
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, IReadOnlyList<Mat> imgSubList, double threshold = 0.8)
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, List<Mat> imgSubList, double threshold = 0.8)
{
List<Rect> list = [];
foreach (var sub in imgSubList)
{
var matches = FindMatches(srcMat, sub, TemplateMatchModes.CCoeffNormed, null, threshold, -1);
foreach (var match in matches)
while (true)
{
list.Add(new Rect(match.Location.X, match.Location.Y, sub.Width, sub.Height));
var point = MatchTemplate(srcMat, sub, TemplateMatchModes.CCoeffNormed, null, threshold);
if (point != new Point())
{
// 把结果给遮掩掉,避免重复识别
Cv2.Rectangle(srcMat, point, new Point(point.X + sub.Width, point.Y + sub.Height), Scalar.Black, -1);
list.Add(new Rect(point.X, point.Y, sub.Width, sub.Height));
}
else
{
break;
}
}
}
return list;
}
@@ -111,7 +185,24 @@ public class MatchTemplateHelper
/// <returns></returns>
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, Mat? maskMat = null, double threshold = 0.8)
{
return MatchOnePicForOnePic(srcMat, dstMat, TemplateMatchModes.CCoeffNormed, maskMat, threshold);
List<Rect> list = [];
while (true)
{
var point = MatchTemplate(srcMat, dstMat, TemplateMatchModes.CCoeffNormed, maskMat, threshold);
if (point != new Point())
{
// 把结果给遮掩掉,避免重复识别
Cv2.Rectangle(srcMat, point, new Point(point.X + dstMat.Width, point.Y + dstMat.Height), Scalar.Black, -1);
list.Add(new Rect(point.X, point.Y, dstMat.Width, dstMat.Height));
}
else
{
break;
}
}
return list;
}
/// <summary>
@@ -126,194 +217,28 @@ public class MatchTemplateHelper
/// <returns></returns>
public static List<Rect> MatchOnePicForOnePic(Mat srcMat, Mat dstMat, TemplateMatchModes matchMode, Mat? maskMat, double threshold, int maxCount = -1)
{
var matches = FindMatches(srcMat, dstMat, matchMode, maskMat, threshold, maxCount);
var list = new List<Rect>(matches.Count);
foreach (var match in matches)
List<Rect> list = [];
if (maxCount < 0)
{
list.Add(new Rect(match.Location.X, match.Location.Y, dstMat.Width, dstMat.Height));
maxCount = srcMat.Width * srcMat.Height / dstMat.Width / dstMat.Height;
}
for (int i = 0; i < maxCount; i++)
{
var point = MatchTemplate(srcMat, dstMat, matchMode, maskMat, threshold);
if (point != new Point())
{
// 把结果给遮掩掉,避免重复识别
Cv2.Rectangle(srcMat, point, new Point(point.X + dstMat.Width, point.Y + dstMat.Height), Scalar.Black, -1);
list.Add(new Rect(point.X, point.Y, dstMat.Width, dstMat.Height));
}
else
{
break;
}
}
return list;
}
internal readonly record struct TemplateMatchResult(Point Location, double Score);
/// <summary>
/// 返回源图中的最佳模板匹配,并保留匹配得分。
/// </summary>
internal static TemplateMatchResult? FindBestMatch(
Mat srcMat,
Mat template,
TemplateMatchModes matchMode,
Mat? mask,
double threshold)
{
var matches = FindMatches(srcMat, template, matchMode, mask, threshold, 1);
return matches.Count == 0 ? null : matches[0];
}
/// <summary>
/// 在源图中匹配指定模板,从响应矩阵中按分数顺序提取候选,并通过 NMS 去除重复结果。
/// </summary>
/// <param name="srcMat">待搜索的源图。</param>
/// <param name="template">需要匹配的模板图。</param>
/// <param name="matchMode">OpenCV 模板匹配模式。</param>
/// <param name="mask">模板掩码;为 <see langword="null"/> 时模板全部区域参与匹配。</param>
/// <param name="threshold">匹配阈值,值越大筛选越严格。</param>
/// <param name="maxCount">最大结果数;小于 0 时根据源图与模板面积自动估算。</param>
/// <returns>按匹配质量从优到劣排列的模板左上角坐标及分数。</returns>
internal static List<TemplateMatchResult> FindMatches(
Mat srcMat,
Mat template,
TemplateMatchModes matchMode,
Mat? mask,
double threshold,
int maxCount)
{
var matches = new List<TemplateMatchResult>();
try
{
// 模板必须能够完整地在源图中滑动,否则 OpenCV 无法生成有效的匹配结果矩阵。
if (srcMat.Empty() || template.Empty()
|| srcMat.Width < template.Width || srcMat.Height < template.Height)
{
return matches;
}
// 负数表示不限制明确数量,这里以源图最多能容纳的模板数量作为循环安全上限。
if (maxCount < 0)
{
maxCount = srcMat.Width * srcMat.Height / template.Width / template.Height;
}
if (maxCount <= 0)
{
return matches;
}
// result 的每个坐标代表模板左上角放置在源图对应坐标时的匹配分数。
using var result = new Mat();
Cv2.MatchTemplate(srcMat, template, result, matchMode, mask);
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.CCoeff or TemplateMatchModes.CCorr)
{
// 非 Normed 模式的分数没有固定范围,统一归一化到 [0, 1] 以便应用阈值。
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax);
}
// 平方差模式分数越小越好;其余模式分数越大越好。
// 对平方差使用 1 - threshold,使调用方始终可以按“阈值越大越严格”理解 threshold。
var isLowerBetter = matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.SqDiffNormed;
var scoreThreshold = isLowerBetter ? 1 - threshold : threshold;
// 将通过阈值的位置标记为候选点;后续 NMS 只修改该掩码,不修改原始匹配分数。
using var candidateMask = new Mat();
Cv2.Compare(result, new Scalar(scoreThreshold), candidateMask,
isLowerBetter ? CmpType.LE : CmpType.GE);
while (matches.Count < maxCount)
{
// 仅在候选掩码非零的位置中,提取当前分数最优的匹配点。
Cv2.MinMaxLoc(result, out var minScore, out var maxScore, out var minLocation, out var maxLocation, candidateMask);
var location = isLowerBetter ? minLocation : maxLocation;
// 没有有效候选点时 MinMaxLoc 的位置不可再使用,结束提取。
if (location.X < 0 || location.X >= candidateMask.Width
|| location.Y < 0 || location.Y >= candidateMask.Height
|| candidateMask.At<byte>(location.Y, location.X) == 0)
{
break;
}
var rawScore = isLowerBetter ? minScore : maxScore;
if (double.IsNaN(rawScore))
{
// 忽略异常分数并移除该候选,避免下一轮重复选中。
candidateMask.Set(location.Y, location.X, (byte)0);
continue;
}
// 对外统一为分数越高匹配越好,平方差模式需反转原始分数方向。
var score = isLowerBetter ? 1 - rawScore : rawScore;
matches.Add(new TemplateMatchResult(location, score));
// 抑制与当前结果 IoU 过高的邻近候选,避免同一目标被重复返回。
SuppressOverlappingCandidates(candidateMask, location, template.Width, template.Height);
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogDebug(ex, ex.Message);
}
return matches;
}
/// <summary>
/// 在候选掩码中清除与已选结果的 IoU 达到阈值的候选点,避免重复返回同一目标。
/// </summary>
/// <param name="candidateMask">候选点掩码,非零像素表示该坐标仍可参与匹配。</param>
/// <param name="selected">已选模板在源图中的左上角坐标。</param>
/// <param name="templateWidth">模板宽度。</param>
/// <param name="templateHeight">模板高度。</param>
private static void SuppressOverlappingCandidates(
Mat candidateMask,
Point selected,
int templateWidth,
int templateHeight)
{
// 根据 IoU 阈值推导可能触发抑制的最大坐标偏移,只遍历已选点附近区域。
var maxDeltaX = (int)Math.Floor(templateWidth * (1 - 0.5) / (1 + 0.5)) + 1;
var maxDeltaY = (int)Math.Floor(templateHeight * (1 - 0.5) / (1 + 0.5)) + 1;
// 将搜索区域裁剪到候选掩码边界内,防止访问越界。
var minX = Math.Max(0, selected.X - maxDeltaX);
var maxX = Math.Min(candidateMask.Width - 1, selected.X + maxDeltaX);
var minY = Math.Max(0, selected.Y - maxDeltaY);
var maxY = Math.Min(candidateMask.Height - 1, selected.Y + maxDeltaY);
for (var y = minY; y <= maxY; y++)
{
for (var x = minX; x <= maxX; x++)
{
if (HasSuppressingOverlap(selected, new Point(x, y), templateWidth, templateHeight)
&& candidateMask.At<byte>(y, x) != 0)
{
// 清零后,该坐标不会再被后续 MinMaxLoc 选中。
candidateMask.Set(y, x, (byte)0);
}
}
}
}
/// <summary>
/// 判断两个相同尺寸的模板矩形是否达到 NMS 抑制所需的重叠比例。
/// </summary>
/// <param name="first">第一个模板矩形的左上角坐标。</param>
/// <param name="second">第二个模板矩形的左上角坐标。</param>
/// <param name="templateWidth">模板矩形宽度。</param>
/// <param name="templateHeight">模板矩形高度。</param>
/// <returns>两个矩形的 IoU 大于或等于 0.5 时返回 <see langword="true"/>。</returns>
private static bool HasSuppressingOverlap(
Point first,
Point second,
int templateWidth,
int templateHeight)
{
var templateArea = (double)templateWidth * templateHeight;
// 两个矩形尺寸相同,因此重叠边长等于模板边长减去对应方向的坐标偏移。
var overlapWidth = templateWidth - Math.Abs(first.X - second.X);
var overlapHeight = templateHeight - Math.Abs(first.Y - second.Y);
if (overlapWidth <= 0 || overlapHeight <= 0)
{
return false;
}
// IoU = 交集面积 / 并集面积;并集为两个模板面积之和减去交集面积。
var intersection = (double)overlapWidth * overlapHeight;
var union = templateArea * 2 - intersection;
return intersection / union >= 0.5;
}
}
@@ -10,5 +10,4 @@ public enum PaddleOcrModelConfig
V5Latin = 4,
V5Eslav = 5,
V5Korean = 6,
V6 = 8,
}
}
@@ -1,109 +0,0 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Area;
using OpenCvSharp;
using System;
using System.Collections.Concurrent;
using System.IO;
namespace BetterGenshinImpact.Core.Recognition;
public static class RecognitionAssets
{
private static readonly ConcurrentDictionary<RecognitionAssetCacheKey, RecognitionObject> Cache = new();
public static RecognitionObject Get(string taskName, string objectName, Region region)
{
ArgumentNullException.ThrowIfNull(region);
return Get(taskName, objectName, region.Width, region.Height);
}
public static RecognitionObject Get(string taskName, string objectName)
{
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
return Get(taskName, objectName, captureRect.Width, captureRect.Height);
}
public static RecognitionObject Get(string taskName, string objectName, int captureWidth, int captureHeight)
{
var key = new RecognitionAssetCacheKey(taskName, objectName, captureWidth, captureHeight);
var recognitionObject = Cache.GetOrAdd(key, static cacheKey => Load(cacheKey));
return recognitionObject;
}
public static void Clear(string taskName, string objectName)
{
foreach (var key in Cache.Keys)
{
if (string.Equals(key.TaskName, taskName, StringComparison.Ordinal)
&& string.Equals(key.ObjectName, objectName, StringComparison.Ordinal))
{
Cache.TryRemove(key, out _);
}
}
}
public static void ClearTask(string taskName)
{
foreach (var key in Cache.Keys)
{
if (string.Equals(key.TaskName, taskName, StringComparison.Ordinal))
{
Cache.TryRemove(key, out _);
}
}
}
public static void ClearAll()
{
Cache.Clear();
}
private static RecognitionObject Load(RecognitionAssetCacheKey key)
{
return RecognitionObjectJsonLoader.LoadFromFile(
Global.Absolute($@"GameTask\{key.TaskName}\Assets\Recognition.json"),
key.ObjectName,
new RecognitionObjectJsonLoadContext
{
CaptureHeight = key.CaptureHeight,
CaptureWidth = key.CaptureWidth,
TemplateLoader = (template, mode) => LoadTemplateImage(key.TaskName, template, key.CaptureWidth, key.CaptureHeight, mode),
});
}
private static Mat LoadTemplateImage(string taskName, string assetName, int captureWidth, int captureHeight, ImreadModes flags)
{
var assetsFolder = Global.Absolute($@"GameTask\{taskName}\Assets\{captureWidth}x{captureHeight}");
if (!Directory.Exists(assetsFolder))
{
assetsFolder = Global.Absolute($@"GameTask\{taskName}\Assets\1920x1080");
}
if (!Directory.Exists(assetsFolder))
{
throw new FileNotFoundException($"未找到{taskName}的素材文件夹");
}
var filePath = Path.Combine(assetsFolder, assetName);
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"未找到{taskName}中的{assetName}文件");
}
using var stream = File.OpenRead(filePath);
var mat = Mat.FromStream(stream, flags);
if (captureWidth < 1920)
{
using (mat)
{
return ResizeHelper.Resize(mat, captureWidth / 1920d);
}
}
return mat;
}
private readonly record struct RecognitionAssetCacheKey(string TaskName, string ObjectName, int CaptureWidth, int CaptureHeight);
}
@@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Size = OpenCvSharp.Size;
namespace BetterGenshinImpact.Core.Recognition;
@@ -19,7 +18,6 @@ public class RecognitionObject
/// <summary>
/// 感兴趣的区域
/// 直接指定区域进行搜索,当这个值存在时
/// </summary>
public Rect RegionOfInterest { get; set; }
@@ -28,24 +26,6 @@ public class RecognitionObject
/// </summary>
public string? Name { get; set; }
/// <summary>
/// 模板图或者识别区域所在捕获区域的画布大小,比如 1920 x 1080、3840 x 2160 等。对应模板图的截取来源图像大小
/// </summary>
public Size? ReferenceImageSize { get; set; }
/// <summary>
/// 模板图或者识别区域在截取来源图像的位置和大小信息。
/// 在识别时,输入图大于 SourceRect
/// 模板匹配时 ReferenceBoundingBox.Width = TemplateImageMat.Width && ReferenceBoundingBox.Height = TemplateImageMat.Height,类似于bbox
/// </summary>
public Rect? ReferenceBoundingBox { get; set; }
/// <summary>
/// 查找位置的时候,相关参数,不指定会用默认的机制进行查找
/// </summary>
public SearchOptions? SearchOptions { get; set; }
#region 模板匹配
/// <summary>
@@ -113,7 +93,7 @@ public class RecognitionObject
/// 二值化阈值,默认 128
/// </summary>
public int BinaryThreshold { get; set; } = 128;
public RecognitionObject InitTemplate()
{
if (TemplateImageMat != null && TemplateImageGreyMat == null)
@@ -269,15 +249,6 @@ public class RecognitionObject
RecognitionType = this.RecognitionType,
RegionOfInterest = this.RegionOfInterest,
Name = this.Name,
ReferenceImageSize = this.ReferenceImageSize,
ReferenceBoundingBox = this.ReferenceBoundingBox,
SearchOptions = this.SearchOptions == null
? null
: new SearchOptions
{
AnchorMode = this.SearchOptions.AnchorMode,
ExpandSize = this.SearchOptions.ExpandSize
},
// 模板匹配相关属性
TemplateImageMat = this.TemplateImageMat, // 注意:Mat 是引用类型,克隆后仍然指向同一内存
@@ -1,285 +0,0 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Recognition;
/// <summary>
/// `Recognition.json` 文件根对象。
/// </summary>
public sealed class RecognitionObjectJsonFile
{
/// <summary>
/// 配置文件版本号。
/// 当前实现固定使用 `1`。
/// </summary>
[JsonProperty("version")]
public int Version { get; set; } = 1;
/// <summary>
/// 公共变量表。
/// 值为表达式字符串,可在 `roi`、`reference.bbox` 等表达式中复用。
/// 常用内置变量有 `cw`、`ch`、`cx`、`cy`、`s`。
/// </summary>
[JsonProperty("vars")]
public Dictionary<string, string> Vars { get; set; } = [];
/// <summary>
/// 公共区域表达式表。
/// 值为返回 `Rect` 的表达式字符串,其他字段可通过 `@别名` 引用。
/// 常用于复用 ROI 定义。
/// </summary>
[JsonProperty("regions")]
public Dictionary<string, string> Regions { get; set; } = [];
/// <summary>
/// 公共模板别名表。
/// 值为模板图片文件名或路径,`template` 可通过 `@别名` 引用。
/// </summary>
[JsonProperty("templates")]
public Dictionary<string, string> Templates { get; set; } = [];
/// <summary>
/// 识别对象集合。
/// Key 为对象名,也就是调用 `RecognitionAssets.Get(taskName, objectName, ...)` 时的 `objectName`。
/// </summary>
[JsonProperty("objects")]
public Dictionary<string, RecognitionObjectJsonConfig> Objects { get; set; } = [];
}
/// <summary>
/// 单个识别对象的 JSON 配置。
/// </summary>
public sealed class RecognitionObjectJsonConfig
{
/// <summary>
/// 可选的运行时名称。
/// 不填时:
/// 模板匹配默认取模板文件名(不含扩展名);
/// 其他类型默认取 objects 下的对象名。
/// </summary>
[JsonProperty("name")]
public string? Name { get; set; }
/// <summary>
/// 识别类型。
/// 文本必须与 `RecognitionTypes` 枚举名一致,例如 `TemplateMatch`、`OcrMatch`、`ColorMatch`。
/// </summary>
[JsonProperty("type")]
public string? Type { get; set; }
/// <summary>
/// 模板图片文件名、相对路径或模板别名。
/// 仅 `TemplateMatch` 使用;支持写成 `@模板别名`。
/// </summary>
[JsonProperty("template")]
public string? Template { get; set; }
/// <summary>
/// 模板图片加载模式。
/// 文本必须与 OpenCV `ImreadModes` 枚举名一致;不填默认 `Color`。
/// </summary>
[JsonProperty("templateMode")]
public string? TemplateMode { get; set; }
/// <summary>
/// 感兴趣区域(ROI)。
/// 值为返回 `Rect` 的表达式字符串,也可写成 `@区域别名`。
/// </summary>
[JsonProperty("roi")]
public string? Roi { get; set; }
/// <summary>
/// 模板匹配阈值。
/// 仅模板匹配常用;不填时沿用 `RecognitionObject` 默认值。
/// </summary>
[JsonProperty("threshold")]
public double? Threshold { get; set; }
/// <summary>
/// 是否启用三通道模板匹配。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("use3Channels")]
public bool? Use3Channels { get; set; }
/// <summary>
/// 模板匹配算法。
/// 文本必须与 OpenCV `TemplateMatchModes` 枚举名一致,例如 `CCoeffNormed`、`CCorrNormed`。
/// </summary>
[JsonProperty("templateMatchMode")]
public string? TemplateMatchMode { get; set; }
/// <summary>
/// 是否启用模板遮罩。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("useMask")]
public bool? UseMask { get; set; }
/// <summary>
/// 遮罩颜色,使用 HTML 颜色格式,例如 `#00FF00`。
/// 当 `useMask=true` 时用于生成遮罩。
/// </summary>
[JsonProperty("maskColor")]
public string? MaskColor { get; set; }
/// <summary>
/// 识别成功时是否绘制调试框。
/// </summary>
[JsonProperty("draw")]
public bool? Draw { get; set; }
/// <summary>
/// 调试框颜色,使用 HTML 颜色格式,例如 `#FF0000`。
/// </summary>
[JsonProperty("drawColor")]
public string? DrawColor { get; set; }
/// <summary>
/// 调试框线宽。
/// </summary>
[JsonProperty("drawWidth")]
public float? DrawWidth { get; set; }
/// <summary>
/// 单次模板匹配最多返回多少个结果。
/// 仅 `TemplateMatch` 使用;`-1` 表示不限制。
/// </summary>
[JsonProperty("maxMatchCount")]
public int? MaxMatchCount { get; set; }
/// <summary>
/// 是否先做二值化再进行模板匹配。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("useBinaryMatch")]
public bool? UseBinaryMatch { get; set; }
/// <summary>
/// 二值化阈值。
/// 当 `useBinaryMatch=true` 时使用。
/// </summary>
[JsonProperty("binaryThreshold")]
public int? BinaryThreshold { get; set; }
/// <summary>
/// 颜色转换方式。
/// 文本必须与 OpenCV `ColorConversionCodes` 枚举名一致,例如 `BGR2RGB`、`BGR2HSV`、`BGR2GRAY`。
/// </summary>
[JsonProperty("colorCode")]
public string? ColorCode { get; set; }
/// <summary>
/// 颜色下界。
/// 用于 `ColorMatch` / `ColorRangeAndOcr` 等颜色范围识别,长度支持 1 到 4 个数字。
/// </summary>
[JsonProperty("lowerColor")]
public List<double>? LowerColor { get; set; }
/// <summary>
/// 颜色上界。
/// 用于 `ColorMatch` / `ColorRangeAndOcr` 等颜色范围识别,长度支持 1 到 4 个数字。
/// </summary>
[JsonProperty("upperColor")]
public List<double>? UpperColor { get; set; }
/// <summary>
/// 颜色匹配要求的最小命中点数。
/// 主要用于 `ColorMatch`。
/// </summary>
[JsonProperty("matchCount")]
public int? MatchCount { get; set; }
/// <summary>
/// OCR 引擎。
/// 文本必须与 `OcrEngineTypes` 枚举名一致;当前通常写 `Paddle`。
/// </summary>
[JsonProperty("ocrEngine")]
public string? OcrEngine { get; set; }
/// <summary>
/// OCR 结果替换表。
/// Key 为期望文本,Value 为会被替换到该文本的一组误识别写法。
/// </summary>
[JsonProperty("replace")]
public Dictionary<string, List<string>> Replace { get; set; } = [];
/// <summary>
/// OCR 全包含匹配。
/// 列表中的所有文本都命中时才算成功。
/// </summary>
[JsonProperty("allContains")]
public List<string> AllContains { get; set; } = [];
/// <summary>
/// OCR 任一包含匹配。
/// 列表中任意一个文本命中就算成功。
/// </summary>
[JsonProperty("oneContains")]
public List<string> OneContains { get; set; } = [];
/// <summary>
/// OCR 正则匹配列表。
/// 列表中的所有正则都命中时才算成功。
/// </summary>
[JsonProperty("regex")]
public List<string> Regex { get; set; } = [];
/// <summary>
/// OCR 目标文本。
/// 常用于多 OCR 结果筛选,或与其他 OCR 匹配配置配合使用。
/// </summary>
[JsonProperty("text")]
public string? Text { get; set; }
/// <summary>
/// 模板参考信息。
/// 用于描述模板来源截图尺寸和原始包围盒,方便后续定位或搜索扩展。
/// </summary>
[JsonProperty("reference")]
public RecognitionReferenceJsonConfig? Reference { get; set; }
/// <summary>
/// 搜索扩展配置。
/// 用于指定锚点和扩展范围。
/// </summary>
[JsonProperty("search")]
public RecognitionSearchJsonConfig? Search { get; set; }
}
/// <summary>
/// 模板参考信息配置。
/// </summary>
public sealed class RecognitionReferenceJsonConfig
{
/// <summary>
/// 模板来源截图尺寸,格式为 `[width, height]`。
/// </summary>
[JsonProperty("size")]
public List<int>? Size { get; set; }
/// <summary>
/// 模板在来源截图中的包围盒,值为返回 `Rect` 的表达式字符串。
/// </summary>
[JsonProperty("bbox")]
public string? Bbox { get; set; }
}
/// <summary>
/// 搜索扩展配置。
/// </summary>
public sealed class RecognitionSearchJsonConfig
{
/// <summary>
/// 搜索锚点。
/// 文本必须与 `SearchAnchorMode` 枚举名一致。
/// </summary>
[JsonProperty("anchor")]
public string? Anchor { get; set; }
/// <summary>
/// 在锚点附近额外扩展的搜索尺寸,格式为 `[width, height]`。
/// </summary>
[JsonProperty("expand")]
public List<int>? Expand { get; set; }
}
@@ -1,530 +0,0 @@
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using NCalc;
using Newtonsoft.Json;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace BetterGenshinImpact.Core.Recognition;
public sealed class RecognitionObjectJsonLoadContext
{
public required int CaptureWidth { get; init; }
public required int CaptureHeight { get; init; }
public required Func<string, ImreadModes, Mat> TemplateLoader { get; init; }
public IReadOnlyDictionary<string, object>? ExtraParameters { get; init; }
}
public static class RecognitionObjectJsonLoader
{
private sealed class LoggerTag;
private static readonly ILogger Logger = App.GetLogger<LoggerTag>();
public static RecognitionObject LoadFromFile(string filePath, string objectName, RecognitionObjectJsonLoadContext context)
{
ArgumentNullException.ThrowIfNull(filePath);
ArgumentNullException.ThrowIfNull(objectName);
ArgumentNullException.ThrowIfNull(context);
try
{
var json = File.ReadAllText(filePath, Encoding.UTF8);
var config = JsonConvert.DeserializeObject<RecognitionObjectJsonFile>(json)
?? throw new InvalidOperationException($"无法解析 RecognitionObject 配置文件: {filePath}");
return Load(config, objectName, context);
}
catch (Exception ex)
{
Logger.LogError(ex,
"Recognition 加载失败: {ObjectName} @ {CaptureWidth}x{CaptureHeight}, file={FilePath}",
objectName,
context.CaptureWidth,
context.CaptureHeight,
filePath);
throw;
}
}
public static RecognitionObject Load(RecognitionObjectJsonFile config, string objectName, RecognitionObjectJsonLoadContext context)
{
ArgumentNullException.ThrowIfNull(config);
ArgumentNullException.ThrowIfNull(objectName);
ArgumentNullException.ThrowIfNull(context);
try
{
if (!config.Objects.TryGetValue(objectName, out var objectConfig))
{
throw new KeyNotFoundException($"未找到名称为 {objectName} 的 RecognitionObject 配置");
}
return new Loader(config, context).BuildRecognitionObject(objectName, objectConfig);
}
catch (Exception ex)
{
Logger.LogError(ex,
"Recognition 构建失败: {ObjectName} @ {CaptureWidth}x{CaptureHeight}",
objectName,
context.CaptureWidth,
context.CaptureHeight);
throw;
}
}
private sealed class Loader
{
private static readonly string[] RectFunctionNames =
[
"rect",
"cutLeft",
"cutRight",
"cutTop",
"cutBottom",
"cutLeftTop",
"cutRightTop",
"cutLeftBottom",
"cutRightBottom",
];
private readonly RecognitionObjectJsonFile _config;
private readonly RecognitionObjectJsonLoadContext _context;
private readonly Rect _captureRect;
private readonly double _assetScale;
private readonly Dictionary<string, double> _resolvedVars = new(StringComparer.Ordinal);
private readonly HashSet<string> _resolvingVars = new(StringComparer.Ordinal);
private readonly HashSet<string> _functionNames = new(RectFunctionNames, StringComparer.Ordinal);
public Loader(RecognitionObjectJsonFile config, RecognitionObjectJsonLoadContext context)
{
_config = config;
_context = context;
_captureRect = new Rect(0, 0, context.CaptureWidth, context.CaptureHeight);
_assetScale = context.CaptureWidth < 1920 ? context.CaptureWidth / 1920d : 1d;
}
public RecognitionObject BuildRecognitionObject(string objectName, RecognitionObjectJsonConfig config)
{
var recognitionType = ParseEnumExact<RecognitionTypes>(config.Type, nameof(config.Type));
string? templateName = null;
if (recognitionType == RecognitionTypes.TemplateMatch)
{
templateName = ResolveTemplate(config.Template, objectName);
}
var recognitionObject = new RecognitionObject
{
Name = ResolveName(objectName, config, recognitionType, templateName),
RecognitionType = recognitionType,
};
if (!string.IsNullOrWhiteSpace(config.Roi))
{
recognitionObject.RegionOfInterest = EvaluateRect(config.Roi);
}
if (config.Threshold.HasValue)
{
recognitionObject.Threshold = config.Threshold.Value;
}
if (config.Use3Channels.HasValue)
{
recognitionObject.Use3Channels = config.Use3Channels.Value;
}
if (!string.IsNullOrWhiteSpace(config.TemplateMatchMode))
{
recognitionObject.TemplateMatchMode = ParseEnumExact<TemplateMatchModes>(config.TemplateMatchMode, nameof(config.TemplateMatchMode));
}
if (config.UseMask.HasValue)
{
recognitionObject.UseMask = config.UseMask.Value;
}
if (!string.IsNullOrWhiteSpace(config.MaskColor))
{
recognitionObject.MaskColor = ParseColor(config.MaskColor);
}
if (config.Draw.HasValue)
{
recognitionObject.DrawOnWindow = config.Draw.Value;
}
if (!string.IsNullOrWhiteSpace(config.DrawColor) || config.DrawWidth.HasValue)
{
var drawColor = !string.IsNullOrWhiteSpace(config.DrawColor)
? ParseColor(config.DrawColor)
: recognitionObject.DrawOnWindowPen.Color;
var drawWidth = config.DrawWidth ?? recognitionObject.DrawOnWindowPen.Width;
recognitionObject.DrawOnWindowPen = new Pen(drawColor, drawWidth);
}
if (config.MaxMatchCount.HasValue)
{
recognitionObject.MaxMatchCount = config.MaxMatchCount.Value;
}
if (config.UseBinaryMatch.HasValue)
{
recognitionObject.UseBinaryMatch = config.UseBinaryMatch.Value;
}
if (config.BinaryThreshold.HasValue)
{
recognitionObject.BinaryThreshold = config.BinaryThreshold.Value;
}
if (!string.IsNullOrWhiteSpace(config.ColorCode))
{
recognitionObject.ColorConversionCode = ParseEnumExact<ColorConversionCodes>(config.ColorCode, nameof(config.ColorCode));
}
if (config.LowerColor is { Count: > 0 })
{
recognitionObject.LowerColor = BuildScalar(config.LowerColor, nameof(config.LowerColor));
}
if (config.UpperColor is { Count: > 0 })
{
recognitionObject.UpperColor = BuildScalar(config.UpperColor, nameof(config.UpperColor));
}
if (config.MatchCount.HasValue)
{
recognitionObject.MatchCount = config.MatchCount.Value;
}
if (!string.IsNullOrWhiteSpace(config.OcrEngine))
{
recognitionObject.OcrEngine = ParseEnumExact<OcrEngineTypes>(config.OcrEngine, nameof(config.OcrEngine));
}
if (config.Replace.Count > 0)
{
recognitionObject.ReplaceDictionary = config.Replace.ToDictionary(
pair => pair.Key,
pair => pair.Value.ToArray(),
StringComparer.Ordinal);
}
if (config.AllContains.Count > 0)
{
recognitionObject.AllContainMatchText = [.. config.AllContains];
}
if (config.OneContains.Count > 0)
{
recognitionObject.OneContainMatchText = [.. config.OneContains];
}
if (config.Regex.Count > 0)
{
recognitionObject.RegexMatchText = [.. config.Regex];
}
if (!string.IsNullOrWhiteSpace(config.Text))
{
recognitionObject.Text = config.Text;
}
if (config.Reference?.Size is { Count: 2 })
{
recognitionObject.ReferenceImageSize = new OpenCvSharp.Size(config.Reference.Size[0], config.Reference.Size[1]);
}
if (!string.IsNullOrWhiteSpace(config.Reference?.Bbox))
{
recognitionObject.ReferenceBoundingBox = EvaluateRect(config.Reference.Bbox);
}
if (config.Search != null)
{
recognitionObject.SearchOptions = new SearchOptions();
if (!string.IsNullOrWhiteSpace(config.Search.Anchor))
{
recognitionObject.SearchOptions.AnchorMode = ParseEnumExact<SearchAnchorMode>(config.Search.Anchor, nameof(config.Search.Anchor));
}
if (config.Search.Expand is { Count: 2 })
{
recognitionObject.SearchOptions.ExpandSize = new OpenCvSharp.Size(config.Search.Expand[0], config.Search.Expand[1]);
}
}
if (recognitionType == RecognitionTypes.TemplateMatch)
{
var loadMode = ParseTemplateMode(config.TemplateMode);
recognitionObject.TemplateImageMat = _context.TemplateLoader(templateName!, loadMode);
}
return recognitionObject.InitTemplate();
}
private string ResolveName(string objectName, RecognitionObjectJsonConfig config, RecognitionTypes recognitionType, string? templateName)
{
if (!string.IsNullOrWhiteSpace(config.Name))
{
return config.Name;
}
if (recognitionType == RecognitionTypes.TemplateMatch && !string.IsNullOrWhiteSpace(templateName))
{
return Path.GetFileNameWithoutExtension(templateName);
}
return objectName;
}
private ImreadModes ParseTemplateMode(string? templateMode)
{
return string.IsNullOrWhiteSpace(templateMode)
? ImreadModes.Color
: ParseEnumExact<ImreadModes>(templateMode, nameof(templateMode));
}
private string ResolveTemplate(string? template, string objectName)
{
if (string.IsNullOrWhiteSpace(template))
{
throw new InvalidOperationException($"对象 {objectName} 缺少 template 配置");
}
var resolved = template.Trim();
while (resolved.StartsWith('@'))
{
var alias = resolved[1..];
if (!_config.Templates.TryGetValue(alias, out resolved))
{
throw new KeyNotFoundException($"未找到模板别名 {alias}");
}
}
return resolved;
}
private Rect EvaluateRect(string expression)
{
var resolved = ResolveRegionExpression(expression);
var value = EvaluateValue(resolved);
return value switch
{
Rect rect => rect,
_ => throw new InvalidOperationException($"表达式 {expression} 未返回 Rect")
};
}
private string ResolveRegionExpression(string expression)
{
var resolved = expression.Trim();
while (resolved.StartsWith('@'))
{
var alias = resolved[1..];
if (!_config.Regions.TryGetValue(alias, out resolved))
{
throw new KeyNotFoundException($"未找到区域别名 {alias}");
}
}
return resolved;
}
private object EvaluateValue(string expression, string? skipVarName = null)
{
var normalizedExpression = NormalizeExpression(expression);
var ncalcExpression = new Expression(normalizedExpression);
foreach (var (name, value) in BuildParameters(skipVarName))
{
ncalcExpression.Parameters[name] = value;
}
ncalcExpression.Functions["rect"] = args => BuildRect(args.Evaluate(0), args.Evaluate(1), args.Evaluate(2), args.Evaluate(3));
ncalcExpression.Functions["cutLeft"] = args => _captureRect.CutLeft(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutRight"] = args => _captureRect.CutRight(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutTop"] = args => _captureRect.CutTop(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutBottom"] = args => _captureRect.CutBottom(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutLeftTop"] = args => _captureRect.CutLeftTop(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutRightTop"] = args => _captureRect.CutRightTop(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutLeftBottom"] = args => _captureRect.CutLeftBottom(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutRightBottom"] = args => _captureRect.CutRightBottom(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
return ncalcExpression.Evaluate();
}
private Dictionary<string, object> BuildParameters(string? skipVarName = null)
{
var parameters = new Dictionary<string, object>(StringComparer.Ordinal)
{
["cw"] = _captureRect.Width,
["ch"] = _captureRect.Height,
["cx"] = _captureRect.X,
["cy"] = _captureRect.Y,
["s"] = _assetScale,
};
if (_context.ExtraParameters != null)
{
foreach (var (name, value) in _context.ExtraParameters)
{
parameters[name] = value;
}
}
foreach (var varName in _config.Vars.Keys)
{
if (string.Equals(varName, skipVarName, StringComparison.Ordinal))
{
continue;
}
parameters[varName] = ResolveVariable(varName);
}
return parameters;
}
private double ResolveVariable(string name)
{
if (_resolvedVars.TryGetValue(name, out var resolvedValue))
{
return resolvedValue;
}
if (!_config.Vars.TryGetValue(name, out var expression))
{
throw new KeyNotFoundException($"未找到变量 {name}");
}
if (!_resolvingVars.Add(name))
{
throw new InvalidOperationException($"变量 {name} 存在循环引用");
}
try
{
var value = ToDouble(EvaluateValue(expression, name));
_resolvedVars[name] = value;
return value;
}
finally
{
_resolvingVars.Remove(name);
}
}
private string NormalizeExpression(string expression)
{
var normalized = expression;
var parameterNames = GetParameterNames()
.OrderByDescending(name => name.Length)
.ToList();
foreach (var parameterName in parameterNames)
{
if (_functionNames.Contains(parameterName))
{
continue;
}
var pattern = $@"(?<![\w\]]){Regex.Escape(parameterName)}(?![\w\(])";
normalized = Regex.Replace(normalized, pattern, $"[{parameterName}]");
}
return normalized;
}
private IEnumerable<string> GetParameterNames()
{
yield return "cw";
yield return "ch";
yield return "cx";
yield return "cy";
yield return "s";
if (_context.ExtraParameters != null)
{
foreach (var name in _context.ExtraParameters.Keys)
{
yield return name;
}
}
foreach (var name in _config.Vars.Keys)
{
yield return name;
}
}
private static Rect BuildRect(object? x, object? y, object? width, object? height)
{
return new Rect(
(int)Math.Round(ToDouble(x)),
(int)Math.Round(ToDouble(y)),
(int)Math.Round(ToDouble(width)),
(int)Math.Round(ToDouble(height)));
}
private static Scalar BuildScalar(IReadOnlyList<double> values, string fieldName)
{
return values.Count switch
{
1 => new Scalar(values[0]),
2 => new Scalar(values[0], values[1]),
3 => new Scalar(values[0], values[1], values[2]),
4 => new Scalar(values[0], values[1], values[2], values[3]),
_ => throw new InvalidOperationException($"{fieldName} 必须是 1 到 4 个数字"),
};
}
private static TEnum ParseEnumExact<TEnum>(string? value, string fieldName) where TEnum : struct, Enum
{
if (string.IsNullOrWhiteSpace(value))
{
throw new InvalidOperationException($"{fieldName} 不能为空");
}
if (Enum.TryParse<TEnum>(value, false, out var parsed))
{
return parsed;
}
throw new InvalidOperationException($"{fieldName} 的值 {value} 不是有效的 {typeof(TEnum).Name}");
}
private static Color ParseColor(string value)
{
return ColorTranslator.FromHtml(value);
}
private static double ToDouble(object? value)
{
return value switch
{
null => 0d,
byte byteValue => byteValue,
short shortValue => shortValue,
int intValue => intValue,
long longValue => longValue,
float floatValue => floatValue,
double doubleValue => doubleValue,
decimal decimalValue => (double)decimalValue,
_ => Convert.ToDouble(value, CultureInfo.InvariantCulture),
};
}
}
}
@@ -1,32 +0,0 @@
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition;
public class SearchOptions
{
/// <summary>
/// 搜索锚定点。当输入图与参考图宽高比不一致时,决定缩放后的参考画布贴向哪一侧。
/// 这个缩放规则需要和待匹配 UI 在不同分辨率下的布局缩放规则保持一致。
/// </summary>
public SearchAnchorMode AnchorMode { get; set; } = SearchAnchorMode.Auto;
/// <summary>
/// 在预测框外额外扩展的像素大小。未指定时默认四周各扩展 10px。
/// </summary>
public Size? ExpandSize { get; set; }
}
/// <summary>
/// 参考搜索的锚定方式。
/// 元素在画布右/下侧时通常使用右/下锚定,元素在左/上侧时通常使用左/上锚定;
/// 居中元素使用中心锚定,按画布中心加偏移进行缩放。
/// </summary>
public enum SearchAnchorMode
{
Auto,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
Center
}
@@ -1,11 +1,11 @@
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Windows;
using Gma.System.MouseKeyHook;
using Microsoft.Extensions.Logging;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -23,7 +23,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
private readonly Dictionary<Keys, bool> _keyDownState = [];
private IDisposable? _relativeMouseSubscription;
private DirectInputMonitor? _directInputMonitor;
private readonly System.Timers.Timer _timer = new();
@@ -37,78 +37,44 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_timer.Interval = 50; // ms
}
public async Task<bool> StartRecord(
RelativeMouseInputType inputType = RelativeMouseInputType.DirectInput)
public async Task StartRecord()
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return false;
return;
}
if (Status != KeyMouseRecorderStatus.Stop)
{
Toast.Warning("已经在录制状态,请不要重复启动录制功能");
return false;
return;
}
Status = KeyMouseRecorderStatus.Start;
var taskTriggerStopped = false;
try
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
for (var i = 3; i >= 1; i--)
{
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
for (var i = 3; i >= 1; i--)
{
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
}
TaskTriggerDispatcher.Instance().StopTimer();
taskTriggerStopped = true;
_recorder = new KeyMouseRecorder();
var monitorFactory = App.GetService<IRelativeMouseInputMonitorFactory>()
?? throw new InvalidOperationException("相对鼠标捕获工厂未注册");
_relativeMouseSubscription = monitorFactory
.Get(inputType)
.Subscribe(RelativeMouseMoved);
_timer.Start();
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:已启动,相对鼠标捕获方式:{InputType}", inputType);
return true;
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
}
catch (Exception ex)
{
_timer.Stop();
try
{
_relativeMouseSubscription?.Dispose();
}
catch (Exception disposeException)
{
_logger.LogWarning(disposeException, "清理相对鼠标捕获订阅失败");
}
_relativeMouseSubscription = null;
_recorder = null;
if (taskTriggerStopped)
{
TaskTriggerDispatcher.Instance().StartTimer();
}
TaskTriggerDispatcher.Instance().StopTimer();
Status = KeyMouseRecorderStatus.Stop;
_logger.LogError(ex, "启动键鼠录制失败,相对鼠标捕获方式:{InputType}", inputType);
await ThemedMessageBox.ErrorAsync(
$"启动键鼠录制失败:{ex.Message}",
"键鼠录制启动失败");
return false;
}
_timer.Start();
_recorder = new KeyMouseRecorder();
_directInputMonitor = new DirectInputMonitor();
_directInputMonitor.Start();
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:{Text}", "已启动");
}
public string StopRecord()
@@ -118,30 +84,27 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
throw new InvalidOperationException("未处于录制中状态,无法停止");
}
var macro = _recorder?.ToJsonMacro() ?? string.Empty;
_recorder = null;
_directInputMonitor?.Stop();
_directInputMonitor?.Dispose();
_directInputMonitor = null;
_timer.Stop();
var recorder = _recorder;
_recorder = null;
var relativeMouseSubscription = _relativeMouseSubscription;
_relativeMouseSubscription = null;
_logger.LogInformation("录制:{Text}", "结束录制");
try
{
relativeMouseSubscription?.Dispose();
return recorder?.ToJsonMacro() ?? string.Empty;
}
finally
{
_logger.LogInformation("录制:{Text}", "结束录制");
TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
}
TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
return macro;
}
public void Tick(object? sender, EventArgs e)
{
var ra = TaskControl.CaptureToRectArea();
var iconRa = ra.Find(ElementRecognition.Get("FriendChat", ra));
var iconRa = ra.Find(ElementAssets.Instance.FriendChat);
var exist = iconRa.IsExist();
if (exist != _isInMainUi)
{
@@ -152,7 +115,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
ra.Dispose();
}
public void GlobalHookKeyDown(KeyEventArgs e, DateTime time)
public void GlobalHookKeyDown(KeyEventArgs e, uint time)
{
// 排除热键
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.KeyMouseMacroRecordHotkey)
@@ -179,7 +142,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_recorder?.KeyDown(e, time);
}
public void GlobalHookKeyUp(KeyEventArgs e, DateTime time)
public void GlobalHookKeyUp(KeyEventArgs e, uint time)
{
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.Test1Hotkey)
{
@@ -194,42 +157,42 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
}
}
public void GlobalHookMouseDown(MouseEventExtArgs e, DateTime time)
public void GlobalHookMouseDown(MouseEventExtArgs e)
{
// Debug.WriteLine($"MouseDown: {e.Button}");
_recorder?.MouseDown(e, time);
_recorder?.MouseDown(e);
}
public void GlobalHookMouseUp(MouseEventExtArgs e, DateTime time)
public void GlobalHookMouseUp(MouseEventExtArgs e)
{
// Debug.WriteLine($"MouseUp: {e.Button}");
_recorder?.MouseUp(e, time);
_recorder?.MouseUp(e);
}
public void GlobalHookMouseMoveTo(MouseEventExtArgs e, DateTime time)
public void GlobalHookMouseMoveTo(MouseEventExtArgs e)
{
if (_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMove: {e.X}, {e.Y}");
_recorder?.MouseMoveTo(e, time);
_recorder?.MouseMoveTo(e);
}
public void GlobalHookMouseWheel(MouseEventExtArgs e, DateTime time)
public void GlobalHookMouseWheel(MouseEventExtArgs e)
{
// Debug.WriteLine($"MouseWheel: {e.Delta}");
_recorder?.MouseWheel(e, time);
_recorder?.MouseWheel(e);
}
private void RelativeMouseMoved(object? sender, RelativeMouseMoveEventArgs e)
public void GlobalHookMouseMoveBy(MouseState state, uint time)
{
if (e is { DeltaX: 0, DeltaY: 0 } || !_isInMainUi)
if (state is { X: 0, Y: 0 } || !_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMoveBy: {e.DeltaX}, {e.DeltaY}");
_recorder?.MouseMoveBy(e);
// Debug.WriteLine($"MouseMoveBy: {state.X}, {state.Y}");
_recorder?.MouseMoveBy(state, time);
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
@@ -49,7 +49,7 @@ public class KeyMouseMacroPlayer
public static async Task PlayMacro(List<MacroEvent> macroEvents, CancellationToken ct)
{
WorkingArea = PrimaryScreen.WorkingArea;
var startTime = DateTime.UtcNow;
var startTime = Kernel32.GetTickCount();
foreach (var e in macroEvents)
{
if (ct.IsCancellationRequested)
@@ -57,14 +57,14 @@ public class KeyMouseMacroPlayer
return;
}
var timeToWait = e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds;
var timeToWait = e.Time - (Kernel32.GetTickCount() - startTime);
if (timeToWait < 0)
{
TaskControl.Logger.LogDebug("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), (-timeToWait).ToString("F0"));
}
else
{
await Task.Delay(TimeSpan.FromMilliseconds(timeToWait), ct);
await Task.Delay((int)timeToWait, ct);
}
switch (e.Type)
@@ -209,4 +209,4 @@ public class KeyMouseMacroPlayer
{
return y * 65535 * 1d / WorkingArea.Height;
}
}
}
@@ -1,14 +1,15 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using Gma.System.MouseKeyHook;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Recorder;
@@ -16,7 +17,7 @@ public class KeyMouseRecorder
{
public List<MacroEvent> MacroEvents { get; } = [];
public DateTime StartTime { get; set; } = DateTime.UtcNow;
public uint StartTime { get; set; } = Kernel32.GetTickCount();
public DateTime LastOrientationDetection { get; set; } = DateTime.UtcNow;
@@ -113,27 +114,27 @@ public class KeyMouseRecorder
return JsonSerializer.Serialize(keyMouseScript, JsonOptions);
}
public void KeyDown(KeyEventArgs e, DateTime time)
public void KeyDown(KeyEventArgs e, uint time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = (time - StartTime).TotalMilliseconds
Time = time - StartTime
});
}
public void KeyUp(KeyEventArgs e, DateTime time)
public void KeyUp(KeyEventArgs e, uint time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = (time - StartTime).TotalMilliseconds
Time = time - StartTime
});
}
public void MouseDown(MouseEventExtArgs e, DateTime time)
public void MouseDown(MouseEventExtArgs e)
{
MacroEvents.Add(new MacroEvent
{
@@ -141,11 +142,11 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (time - StartTime).TotalMilliseconds
Time = e.Timestamp - StartTime
});
}
public void MouseUp(MouseEventExtArgs e, DateTime time)
public void MouseUp(MouseEventExtArgs e)
{
MacroEvents.Add(new MacroEvent
{
@@ -153,32 +154,32 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (time - StartTime).TotalMilliseconds
Time = e.Timestamp - StartTime
});
}
public void MouseMoveTo(MouseEventExtArgs e, DateTime time)
public void MouseMoveTo(MouseEventExtArgs e)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = (time - StartTime).TotalMilliseconds
Time = e.Timestamp - StartTime
});
}
public void MouseWheel(MouseEventExtArgs e, DateTime time)
public void MouseWheel(MouseEventExtArgs e)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseWheel,
MouseY = e.Delta, // 120 的倍率
Time = (time - StartTime).TotalMilliseconds
Time = e.Timestamp - StartTime
});
}
public void MouseMoveBy(RelativeMouseMoveEventArgs e)
public void MouseMoveBy(MouseState state, uint time)
{
int? cao = null;
@@ -195,9 +196,9 @@ public class KeyMouseRecorder
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = e.DeltaX,
MouseY = e.DeltaY,
Time = (e.Timestamp - StartTime).TotalMilliseconds,
MouseX = state.X,
MouseY = state.Y,
Time = time - 5 - StartTime,
CameraOrientation = cao,
});
}
@@ -1,99 +1,42 @@
using System;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using System.Threading;
namespace BetterGenshinImpact.Core.Script;
public class CancellationContext : Singleton<CancellationContext>
{
private readonly object _sync = new();
public CancellationTokenSource Cts { get; private set; } = new();
public CancellationTokenSource Cts { get; set; } = new();
public bool IsManualStop { get; private set; }
public bool IsCancellationRequested
{
get
{
lock (_sync)
{
return !disposed && Cts.IsCancellationRequested;
}
}
}
private bool disposed;
public void Set()
{
lock (_sync)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
public void ManualCancel()
{
CancellationTokenSource cts;
lock (_sync)
if (!disposed)
{
if (disposed)
{
return;
}
IsManualStop = true;
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
Cts.Cancel();
}
}
public void Cancel()
{
CancellationTokenSource cts;
lock (_sync)
if (!disposed)
{
if (disposed)
{
return;
}
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
Cts.Cancel();
}
}
public void Clear()
{
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
cts = Cts;
disposed = true;
}
cts.Dispose();
Cts.Dispose();
disposed = true;
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
@@ -12,13 +12,11 @@ public class AutoPathingScript
{
private object? _config = null;
private string _rootPath;
private readonly LimitedFile _autoPathingFile;
public AutoPathingScript(string rootPath, object? config)
{
_config = config;
_rootPath = rootPath;
_autoPathingFile = new LimitedFile(Global.Absolute(@"User\AutoPathing"));
}
public async Task Run(string json)
@@ -61,48 +59,7 @@ public class AutoPathingScript
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
public async Task RunFileFromUser(string path)
{
var json = await AutoPathingFile.ReadText(path);
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
await Run(json);
}
/// <summary>
/// 判断 AutoPathing 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => AutoPathingFile.IsExists(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => AutoPathingFile.IsFile(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => AutoPathingFile.IsFolder(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => AutoPathingFile.ReadPathSync(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件的文本内容
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的文件路径</param>
/// <returns>文件文本内容,读取失败时返回空字符串</returns>
public string ReadTextSync(string subPath) => AutoPathingFile.ReadTextSync(subPath);
/// <summary>
/// LimitedFile 实例,用于操作 AutoPathing 目录
/// </summary>
private LimitedFile AutoPathingFile => _autoPathingFile;
}
@@ -1,34 +0,0 @@
using Microsoft.ClearScript;
using System;
using System.Reflection;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class CustomHostFunctions : HostFunctions
{
/// <summary>
/// 创建指定维度的交错数组变量
/// </summary>
/// <typeparam name="T">数组元素类型</typeparam>
/// <param name="dimensions">数组维度</param>
/// <returns>交错数组变量</returns>
public object NewVarOfArr<T>(int dimensions)
{
try
{
Type arrayType = typeof(T);
for (int i = 0; i < dimensions; i++)
{
arrayType = arrayType.MakeArrayType();
}
MethodInfo newVarMethod = typeof(HostFunctions).GetMethod(nameof(newVar))!;
MethodInfo genericMethod = newVarMethod.MakeGenericMethod(arrayType);
return genericMethod.Invoke(this, new object?[] { null })!;
}
catch (Exception ex)
{
throw new InvalidOperationException($"创建维度为 {dimensions} 的数组失败: {ex.Message}", ex);
}
}
}
@@ -1,11 +1,9 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoWood;
@@ -18,14 +16,9 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.Common;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -193,24 +186,13 @@ public class Dispatcher
return null;
}
return await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
case "AutoBoss":
var autoBossConfig = TaskContext.Instance().Config.AutoBossConfig;
if (taskSettingsPageViewModel.GetFightStrategy(autoBossConfig.StrategyName, out var autoBossPath))
{
return null;
}
return await new AutoBossTask(new AutoBossParam(autoBossPath)).Start(cancellationToken);
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
return null;
case "AutoFishing":
await new AutoFishingTask(AutoFishingTaskParam.BuildFromSoloTaskConfig(soloTask.Config)).Start(
cancellationToken);
return null;
case "AutoCook":
await new AutoCookTask().Start(cancellationToken);
return null;
case "AutoEat":
{
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodName", (string?)null);
@@ -283,15 +265,16 @@ public class Dispatcher
GridScreenName gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null) ?? throw new Exception("gridScreenName为空或错误");
string? itemName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "itemName", (string?)null);
IEnumerable<string>? itemNames = ScriptObjectConverter.GetValue<string>((ScriptObject)soloTask.Config, "itemNames");
CountInventoryItemParam param = new()
if (itemName != null && itemNames != null)
{
GridScreenName = gridScreenName,
ItemName = itemName,
ItemNames = itemNames?.ToList() ?? []
};
var result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时使用");
}
if (itemName == null && itemNames == null)
{
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时为空");
}
var result = await new CountInventoryItem(gridScreenName, itemName, itemNames).Start(cancellationToken);
if (itemName != null)
{
return result;
}
@@ -329,7 +312,7 @@ public class Dispatcher
/// <param name="param">秘境任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task<Dictionary<string, int>> RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
public async Task RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
{
if (param == null)
{
@@ -337,26 +320,9 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
return await new AutoDomainTask(param).Start(cancellationToken);
await new AutoDomainTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动首领讨伐任务
/// </summary>
/// <param name="param">自动首领讨伐任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task<Dictionary<string, int>> RunAutoBossTask(AutoBossParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动首领讨伐任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
return await new AutoBossTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动战斗任务
/// </summary>
@@ -371,101 +337,6 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
var factory = GameTask.AutoFight.Factory.CombatTaskFactoryProvider.GetFactory(param.CombatStrategyPath);
var fightTask = factory.CreateTask(param);
await fightTask.Start(cancellationToken);
}
/// <summary>
/// 运行简易战斗策略脚本。
/// 使用策略语言直接控制角色执行动作(如 e、q、attack 等),适合快速操作。
/// </summary>
/// <param name="script">策略字符串,支持逗号/换行/分号分隔指令,可选角色名前缀</param>
/// <param name="avatarName">指定操作的角色名(可选,不指定则操作当前角色)</param>
/// <param name="customCt">自定义取消令牌</param>
public async Task RunCombatScript(string script, string? avatarName = null, CancellationToken? customCt = null)
{
if (string.IsNullOrWhiteSpace(script))
{
throw new ArgumentException("策略字符串不能为空", nameof(script));
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
// 1. 解析策略字符串(ParseContext 已处理全角符号、注释、分号/逗号分隔)
var combatScript = CombatScriptParser.ParseContext(script, validate: false, defaultAvatarName: avatarName);
if (combatScript.CombatCommands.Count == 0) return;
_logger.LogInformation("执行 {Text}", "简易策略脚本");
await CombatScriptExecutor.ExecuteAsync(combatScript, cancellationToken, _logger);
}
/// <summary>
/// 运行自动地脉花任务
/// </summary>
/// <param name="param">自动地脉花任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoLeyLineOutcropTask(AutoLeyLineOutcropParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动地脉花任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoLeyLineOutcropTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动幽境危战任务
/// </summary>
/// <param name="param">自动幽境危战任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoStygianOnslaughtTask(AutoStygianOnslaughtParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动幽境危战任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoStygianOnslaughtTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行背包物品计数任务。
/// </summary>
/// <param name="param">背包物品计数参数。</param>
/// <param name="customCt">自定义取消令牌。</param>
/// <returns>单物品返回数量;多物品返回名称到数量的脚本对象。</returns>
public async Task<object?> RunCountInventoryItemTask(CountInventoryItemParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "背包物品计数参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
object result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
{
return result;
}
else
{
dynamic expando = new ExpandoObject();
var expandoDict = (IDictionary<string, object>)expando;
foreach (var kvp in (Dictionary<string, int>)result)
{
expandoDict[kvp.Key] = kvp.Value;
}
return expandoDict;
}
await new AutoFightTask(param).Start(cancellationToken);
}
}
@@ -16,14 +16,12 @@ using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
{
private RECT captureAreaRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
private readonly ILogger<Genshin> _logger = App.GetLogger<Genshin>();
/// <summary>
/// 游戏宽度
@@ -45,15 +43,6 @@ public class Genshin
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 通过 OCR 识别当前角色的 UID
/// </summary>
/// <returns>UID 数字,如果识别失败则返回 0</returns>
public Task<int> Uid()
{
return Task.FromResult(Bv.Uid());
}
public Lazy<NavigationInstance> LazyNavigationInstance { get; } = new(() =>
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
@@ -77,6 +66,7 @@ public class Genshin
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, mapName, force);
}
public async Task Tp(double x, double y, bool force)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, MapTypes.Teyvat.ToString(), force);
@@ -123,23 +113,6 @@ public class Genshin
await tpTask.MoveMapTo(x, y, MapTypes.Teyvat.ToString());
}
/// <summary>
/// 点击大地图上的指定坐标。
/// </summary>
/// <remarks>
/// 该方法会先把目标移动到大地图的可点击安全区域,再执行一次点击。
/// </remarks>
/// <param name="x">目标X坐标。</param>
/// <param name="y">目标Y坐标。</param>
/// <param name="forceCountry">强制指定移动大地图时先切换的国家,默认为null。</param>
public async Task ClickMapPoint(double x, double y, string? forceCountry = null)
{
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
await tpTask.CheckInBigMapUi();
await tpTask.SwitchRecentlyCountryMap(x, y, forceCountry);
await tpTask.ClickMapPoint(x, y, MapTypes.Teyvat.ToString());
}
/// <summary>
/// 移动大地图到指定坐标
/// </summary>
@@ -234,11 +207,6 @@ public class Genshin
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
public Point2f? GetPositionFromMapWithMatchingMethod(string matchingMethod)
{
return GetPositionFromMapWithMatchingMethod(nameof(MapTypes.Teyvat), matchingMethod);
}
public float GetCameraOrientation()
{
@@ -253,18 +221,14 @@ public class Genshin
/// <param name="cacheTimeMs">缓存时间,单位毫秒,默认900ms</param>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f? GetPositionFromMap(string mapName, int cacheTimeMs = 900)
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return GetPositionFromMapWithMatchingMethod(mapName,matchingMethod, cacheTimeMs);
}
public Point2f? GetPositionFromMapWithMatchingMethod(string mapName, string matchingMethod, int cacheTimeMs = 900)
{
var imageRegion = CaptureToRectArea();
if (!Bv.IsInMainUi(imageRegion))
{
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
}
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return MapManager.GetMap(mapName, matchingMethod)
.ConvertImageCoordinatesToGenshinMapCoordinates(LazyNavigationInstance.Value
.GetPositionStableByCache(imageRegion, mapName, matchingMethod, cacheTimeMs));
@@ -305,37 +269,12 @@ public class Genshin
{
return await new SwitchPartyTask().Start(partyName, CancellationContext.Instance.Cts.Token);
}
catch (PartySetupFailedException)
catch (PartySetupFailedException ex)
{
return false;//释放失败状态给调用方,否则失败后会退出任务。
return false;//释放失败状态到JS,否则失败后会退出任务。
}
}
/// <summary>
/// 按槽位重组当前队伍角色。
/// </summary>
/// <param name="slot1">1 号位角色名。</param>
/// <param name="slot2">2 号位角色名。</param>
/// <param name="slot3">3 号位角色名。</param>
/// <param name="slot4">4 号位角色名。</param>
/// <returns>完成保存并返回主界面返回 true;参数无效、目标角色未找到或流程失败返回 false。</returns>
/// <remarks>
/// 未传入的槽位默认跳过;空字符串表示跳过对应槽位。
/// 调用示例:<c>await genshin.SwitchCharacter("胡桃", "夜兰", "", "钟离");</c>
/// 该方法表示重组队伍槽位角色,不是按数字键切换当前出战角色。
/// </remarks>
public async Task<bool> SwitchCharacter(string slot1 = "", string slot2 = "", string slot3 = "", string slot4 = "")
{
try
{
return await new SwitchCharacterStateMachineTask().Start(slot1, slot2, slot3, slot4, CancellationContext.Instance.Cts.Token);
}
catch (PartySetupFailedException)
{
return false;
}
}
/// <summary>
/// 清除当前调度器的队伍缓存
/// </summary>
@@ -401,29 +340,7 @@ public class Genshin
/// <returns></returns>
public async Task GoToCraftingBench(string country)
{
await new GoToCraftingBenchTask().GoToCraftingBench(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 前往合成台合成浓缩树脂
/// </summary>
/// <param name="country">国家名称</param>
/// <returns></returns>
public async Task GoCraftResin(string country)
{
await new GoToCraftingBenchTask().GoCraftResin(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 在当前已打开的合成界面中合成指定材料。
/// </summary>
/// <param name="materialName">目标成品材料名。</param>
/// <param name="quantity">目标合成个数,必须大于 0。</param>
/// <param name="materialType">材料筛选类型;为空时从物品模型 CSV 中读取。</param>
/// <returns>合成执行结果。</returns>
public async Task<CraftMaterialResult> CraftMaterial(string materialName, int quantity, string? materialType = null)
{
return await new CraftMaterialTask(materialName, quantity, materialType).Start(CancellationContext.Instance.Cts.Token);
await new GoToCraftingBenchTask().Start(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
@@ -501,17 +418,4 @@ public class Genshin
throw new ArgumentException($"无效的分钟值: {minute},必须是 0-59 之间的整数字符", nameof(minute));
await new SetTimeTask().Start(h, m, CancellationContext.Instance.Cts.Token, skip);
}
// /// <summary>
// /// 莉奈娅挖矿,调试使用,暂时注释
// /// </summary>
// /// <param name="mineCount">射箭次数,默认1</param>
// /// <param name="scanRounds">大循环寻矿次数。不传则默认5;传单个数字时与射箭次数相同</param>
// public async Task StartMining(int? mineCount = null, int? scanRounds = null)
// {
// var actualMine = mineCount ?? 1;
// var actualScan = scanRounds ?? (mineCount ?? 5);
// if (actualScan < actualMine) actualScan = actualMine;
// await new LinneaMiningTask(actualScan, actualMine).Start(CancellationContext.Instance.Cts.Token);
// }
}
}
@@ -1,410 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// HTML遮罩层 - JS脚本依赖类
/// 提供窗口管理与消息通信功能
/// </summary>
public class HtmlMask : IDisposable
{
private static readonly JsonSerializerOptions _jsonOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false
};
/// <summary>
/// 通信消息结构
/// </summary>
public class Message
{
public string Url { get; set; } = "";
public JsonElement? Data { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? RequestId { get; set; }
}
/// <summary>
/// 脚本到HTML的待推送队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _toHtmlQueues = new();
/// <summary>
/// HTML到脚本的消息队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _fromHtmlQueues = new();
/// <summary>
/// JS到HTML请求的等待句柄,用于request-response匹配
/// </summary>
private static readonly ConcurrentDictionary<string, TaskCompletionSource<string>> _jsPendingRequests = new();
/// <summary>
/// requestId到windowId的映射,用于窗口关闭时取消对应的pending请求
/// </summary>
private static readonly ConcurrentDictionary<string, string> _requestWindowMap = new();
private readonly string _workDir;
private readonly List<string> _openedWindows = [];
private readonly object _openedWindowsLock = new();
private bool _disposed;
public HtmlMask(string workDir)
{
_workDir = workDir;
}
#region 窗口管理
/// <summary>
/// 显示HTML遮罩窗口
/// </summary>
public string Show(string url, string? id = null)
{
try
{
if (string.IsNullOrWhiteSpace(url))
throw new ArgumentException("URL不能为空");
string finalUrl;
if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
finalUrl = url;
}
else
{
// 禁止 file:// 绝对路径,仅允许脚本目录下的相对路径
string absPath = ScriptUtils.NormalizePath(_workDir, url);
finalUrl = new Uri(absPath).AbsoluteUri;
}
string windowId = HtmlMaskWindow.Show(finalUrl, id, _workDir);
_toHtmlQueues[windowId] = new ConcurrentQueue<Message>();
_fromHtmlQueues[windowId] = new ConcurrentQueue<Message>();
lock (_openedWindowsLock) { _openedWindows.Add(windowId); }
return windowId;
}
catch (Exception ex)
{
TaskControl.Logger.LogError(ex, "打开HTML遮罩失败: {Url}", url);
throw;
}
}
/// <summary>
/// 关闭指定窗口
/// </summary>
public bool Close(string id)
{
lock (_openedWindowsLock) { _openedWindows.Remove(id); }
CleanupQueues(id);
return HtmlMaskWindow.Close(id);
}
/// <summary>
/// 关闭所有由本实例打开的窗口
/// </summary>
public void CloseAll()
{
List<string> windows;
lock (_openedWindowsLock)
{
windows = [.. _openedWindows];
_openedWindows.Clear();
}
foreach (var windowId in windows)
{
CleanupQueues(windowId);
HtmlMaskWindow.Close(windowId);
}
}
/// <summary>
/// 获取所有窗口ID
/// </summary>
public string[] GetWindowIds() => HtmlMaskWindow.GetWindowIds();
/// <summary>
/// 窗口是否存在
/// </summary>
public bool Exists(string id) => HtmlMaskWindow.Exists(id);
/// <summary>
/// 设置窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThrough(string windowId, bool enabled)
{
HtmlMaskWindow.SetClickThrough(windowId, enabled);
}
/// <summary>
/// 获取窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>true=点击穿透,false=可交互</returns>
public bool GetClickThrough(string windowId)
{
return HtmlMaskWindow.GetClickThrough(windowId);
}
/// <summary>
/// 切换窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public void ToggleClickThrough(string windowId)
{
HtmlMaskWindow.ToggleClickThrough(windowId);
}
#endregion
#region 消息通信
/// <summary>
/// 发送消息到HTML(单向推送)
/// </summary>
public void Send(string windowId, string url, string jsonData)
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData)
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 响应 HTML 页面通过 window.htmlMask.request(...) 发起的请求。
/// </summary>
/// <param name="windowId">HTML 遮罩窗口 ID。</param>
/// <param name="requestId">从 Receive/Poll/PollAll 返回消息的 requestId 字段取得,不能由脚本自行生成。</param>
/// <param name="jsonData">响应数据,必须是合法 JSON 字符串。</param>
public void Respond(string windowId, string requestId, string jsonData)
{
if (string.IsNullOrWhiteSpace(requestId))
throw new ArgumentException("requestId cannot be empty", nameof(requestId));
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = "/__response__",
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 发送请求到HTML并等待响应
/// </summary>
/// <param name="windowId">目标窗口ID</param>
/// <param name="url">接口路径</param>
/// <param name="jsonData">JSON数据</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Request(string windowId, string url, string jsonData, int timeoutMs = 0)
{
var requestId = Guid.NewGuid().ToString("N");
var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
_jsPendingRequests[requestId] = tcs;
_requestWindowMap[requestId] = windowId;
try
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
if (timeoutMs > 0)
{
using var cts = new System.Threading.CancellationTokenSource(timeoutMs);
await using var registration = cts.Token.Register(() =>
{
if (_jsPendingRequests.TryRemove(requestId, out var pending))
pending.TrySetResult(null!);
});
return await tcs.Task;
}
return await tcs.Task;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
_jsPendingRequests.TryRemove(requestId, out _);
_requestWindowMap.TryRemove(requestId, out _);
}
}
/// <summary>
/// 等待接收来自HTML的一条消息
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Receive(string windowId, int timeoutMs = 0)
{
if (!_fromHtmlQueues.TryGetValue(windowId, out var queue))
return null;
var sw = System.Diagnostics.Stopwatch.StartNew();
while (true)
{
if (queue.TryDequeue(out var message))
return JsonSerializer.Serialize(message, _jsonOptions);
if (_disposed || !_fromHtmlQueues.ContainsKey(windowId) || !HtmlMaskWindow.Exists(windowId))
return null;
if (timeoutMs > 0 && sw.ElapsedMilliseconds > timeoutMs)
return null;
await Task.Delay(50);
}
}
/// <summary>
/// 轮询来自HTML的消息(非阻塞)
/// </summary>
public string? Poll(string windowId)
{
if (_fromHtmlQueues.TryGetValue(windowId, out var queue) &&
queue.TryDequeue(out var message))
{
return JsonSerializer.Serialize(message, _jsonOptions);
}
return null;
}
/// <summary>
/// 批量获取来自HTML的所有消息
/// </summary>
public string PollAll(string windowId)
{
var messages = new List<Message>();
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var message))
{
messages.Add(message);
}
}
return JsonSerializer.Serialize(messages, _jsonOptions);
}
#endregion
#region 内部方法
/// <summary>
/// 将待推送队列中的消息通过回调逐一发出
/// </summary>
internal static void FlushPendingMessages(string windowId, Action<string> postAction)
{
if (_toHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var msg))
{
postAction(JsonSerializer.Serialize(msg, _jsonOptions));
}
}
}
/// <summary>
/// HTML端发来的消息入队,如果是JS请求的响应则直接resolve
/// </summary>
internal static void SendFromHtml(string windowId, string url, string data, string? requestId = null)
{
// 匹配JS端pending的request
if (requestId != null && _jsPendingRequests.TryRemove(requestId, out var tcs))
{
var parsed = ParseData(data);
tcs.TrySetResult(parsed != null ? parsed.Value.GetRawText() : "null");
return;
}
// 普通消息入队
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(data),
RequestId = requestId
});
}
}
private static JsonElement? ParseData(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.Clone();
}
catch
{
// 不是合法JSON,作为纯文本包装
return JsonSerializer.SerializeToElement(json, _jsonOptions);
}
}
private static void CleanupQueues(string windowId)
{
_toHtmlQueues.TryRemove(windowId, out _);
_fromHtmlQueues.TryRemove(windowId, out _);
// 取消该窗口关联的待响应请求
foreach (var kvp in _requestWindowMap)
{
if (kvp.Value == windowId && _jsPendingRequests.TryRemove(kvp.Key, out var tcs))
{
tcs.TrySetCanceled();
}
}
}
#endregion
public void Dispose()
{
if (_disposed) return;
_disposed = true;
CloseAll();
}
}
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
@@ -42,9 +40,6 @@ public class KeyMouseHook: IDisposable
private EventHandler<MouseEventExtArgs>? _mouseMoveExtHandler;
private EventHandler<MouseEventExtArgs>? _mouseWheelExtHandler;
private readonly object _mouseMoveLock = new();
private DateTime _lastProcessMouseMoveTime = DateTime.MinValue;
private readonly ILogger<KeyMouseHook> _logger = App.GetLogger<KeyMouseHook>();
/// <summary>
@@ -115,259 +110,182 @@ public class KeyMouseHook: IDisposable
}
}
private readonly System.Threading.Channels.Channel<Action> _eventChannel =
System.Threading.Channels.Channel.CreateBounded<Action>(
new System.Threading.Channels.BoundedChannelOptions(2048)
{
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
private readonly CancellationTokenSource _cts = new();
public KeyMouseHook()
{
// 启动后台事件处理器,确保不阻塞钩子线程
_ = Task.Run(async () =>
{
try
{
var reader = _eventChannel.Reader;
while (await reader.WaitToReadAsync(_cts.Token))
{
while (reader.TryRead(out var action))
{
try
{
action();
}
catch (Exception ex)
{
// 内部错误已在 action 闭包中通过 HandleCallbackException 处理
}
}
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex, "键鼠钩子后台处理器发生异常");
}
});
// 初始化事件处理程序
_keyDownHandler = (_, args) =>
{
if (_keyDownDataCallbacks.Count == 0 && _keyDownCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyDownDataCallbacksCopy = new List<ScriptObject>(_keyDownDataCallbacks);
var keyDownCodeCallbacksCopy = new List<ScriptObject>(_keyDownCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘按下回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
};
_keyUpHandler = (_, args) =>
{
if (_keyUpDataCallbacks.Count == 0 && _keyUpCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyUpDataCallbacksCopy = new List<ScriptObject>(_keyUpDataCallbacks);
var keyUpCodeCallbacksCopy = new List<ScriptObject>(_keyUpCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘释放回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
};
_mouseDownExtHandler = (_, args) =>
{
if (_mouseDownCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseDownCallbacksCopy = new List<ScriptObject>(_mouseDownCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标按下回调");
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
};
_mouseUpExtHandler = (_, args) =>
{
if (_mouseUpCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseUpCallbacksCopy = new List<ScriptObject>(_mouseUpCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseUpCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
}))
foreach (var callback in mouseUpCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标释放回调");
try
{
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
};
_mouseMoveExtHandler = (_, args) =>
{
if (_mouseMoveCallbacks.Count == 0) return;
var now = DateTime.Now;
if ((now - _lastProcessMouseMoveTime).TotalMilliseconds < 10) return;
_lastProcessMouseMoveTime = now;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseMoveCallbacksCopy = new List<ScriptObject>(_mouseMoveCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseMoveCallbacksCopy)
{
try
{
foreach (var callback in mouseMoveCallbacksCopy)
// 获取回调的间隔时间
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval))
{
try
// 获取上次调用时间
if (_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
lock (_mouseMoveLock)
// 计算时间差
var timeSpan = now - lastTime;
// 如果时间差大于等于间隔时间,则执行回调
if (timeSpan.TotalMilliseconds >= interval)
{
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval) &&
_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
var timeSpan = now - lastTime;
if (timeSpan.TotalMilliseconds >= interval)
{
callback.InvokeAsFunction(localX, localY);
_lastMouseMoveCallbackTimes[callback] = now;
}
}
callback.InvokeAsFunction(localX, localY);
// 更新上次调用时间
_lastMouseMoveCallbackTimes[callback] = now;
}
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标移动回调");
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
};
_mouseWheelExtHandler = (_, args) =>
{
if (_mouseWheelCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseWheelCallbacksCopy = new List<ScriptObject>(_mouseWheelCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var delta = args.Delta;
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseWheelCallbacksCopy)
{
try
{
callback.InvokeAsFunction(delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
}))
foreach (var callback in mouseWheelCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标滚轮回调");
try
{
callback.InvokeAsFunction(args.Delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
};
@@ -458,8 +376,6 @@ public class KeyMouseHook: IDisposable
{
if (disposing)
{
_cts.Cancel();
_eventChannel.Writer.TryComplete();
// 移除所有事件监听器
if (_keyDownHandler != null)
{
@@ -1,7 +1,5 @@
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.Core.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenCvSharp;
@@ -15,7 +13,6 @@ public class LimitedFile(string rootPath)
{
/// <summary>
/// 读取指定文件夹内所有文件和文件夹的路径(非递归方式)。
/// 目录不存在时返回空数组
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
@@ -24,19 +21,19 @@ public class LimitedFile(string rootPath)
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
string normalizedFolderPath = NormalizePath(folderPath);
if (!Directory.Exists(fullPath))
// 确保目录存在
if (!Directory.Exists(normalizedFolderPath))
{
TaskControl.Logger.LogError("ReadPathSync 目录不存在: {Path}", fullPath);
return Array.Empty<string>();
Directory.CreateDirectory(normalizedFolderPath);
}
// 获取指定文件夹下的所有文件(非递归)
string[] files = Directory.GetFiles(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 获取指定文件夹下的所有子文件夹(非递归)
string[] directories = Directory.GetDirectories(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 合并文件和文件夹路径
string[] combined = files.Concat(directories).ToArray();
@@ -46,33 +43,12 @@ public class LimitedFile(string rootPath)
}
catch (Exception ex)
{
// 记录异常并返回空数组
TaskControl.Logger.LogError("ReadPathSync 异常: {Message}", ex.Message);
return Array.Empty<string>();
}
}
/// <summary>
/// 创建指定路径的目录,如果已存在则跳过
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>是否创建成功或目录已存在</returns>
public bool CreateDirectory(string folderPath)
{
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
// 如果目录不存在,自动创建
if (!Directory.Exists(fullPath)){Directory.CreateDirectory(fullPath);}
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("CreateDir 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定路径是否为文件夹。
/// </summary>
@@ -96,44 +72,6 @@ public class LimitedFile(string rootPath)
}
}
/// <summary>
/// 判断指定路径是否为文件
/// </summary>
/// <param name="path">文件路径(相对于根目录)</param>
/// <returns>如果是文件则返回 true,否则返回 false</returns>
public bool IsFile(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsFile 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定的文件或目录是否存在
/// </summary>
/// <param name="path">文件或目录路径(相对于根目录)</param>
/// <returns>如果存在返回 true,否则返回 false</returns>
public bool IsExists(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath) || Directory.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsExists 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// Normalize and validate a path.
/// </summary>
@@ -509,51 +447,4 @@ public class LimitedFile(string rootPath)
return true;
}
/// <summary>
/// 重命名文件或文件夹(相对于根目录)
/// </summary>
/// <param name="oldPath">原路径</param>
/// <param name="newPath">新路径</param>
/// <returns>是否重命名成功</returns>
public bool RenamePathSync(string oldPath, string newPath)
{
try
{
// 标准化路径
oldPath = NormalizePath(oldPath);
newPath = NormalizePath(newPath);
// 检查原路径是否存在
if (!File.Exists(oldPath) && !Directory.Exists(oldPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 原路径不存在 {Path}", oldPath);
return false;
}
//验证扩展名合法性
if (File.Exists(oldPath) && !IsValid(newPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 新文件路径不合法 {Path}", newPath);
return false;
}
// 确保目标目录存在
string? directoryPath = Path.GetDirectoryName(newPath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// 执行重命名
Directory.Move(oldPath, newPath);
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("RenamePathSync 异常: {Message}", ex.Message);
return false;
}
}
}
@@ -1,43 +0,0 @@
using System;
using System.Linq;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// 战斗策略文件访问类
/// 提供JS脚本环境访问 User\AutoFight 目录下战斗策略文件的方法
/// </summary>
public class StrategyFile
{
private readonly LimitedFile _strategyFile = new(Global.Absolute(@"User\AutoFight"));
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => _strategyFile.IsFolder(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => _strategyFile.IsFile(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => _strategyFile.IsExists(subPath);
/// <summary>
/// 读取 User\AutoFight 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的子目录路径,默认为根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => _strategyFile.ReadPathSync(subPath);
}
@@ -1,27 +1,18 @@
using System;
using System;
using System.Collections.Generic;
using System.Drawing;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.BgiVision;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.CharacterDevelopment;
using BetterGenshinImpact.GameTask.Model.GameUI;
using Region = BetterGenshinImpact.GameTask.Model.Area.Region;
namespace BetterGenshinImpact.Core.Script;
@@ -41,7 +32,6 @@ public class EngineExtend
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir, config));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("characterDevelopmentTask", new CharacterDevelopmentTask());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
engine.AddHostObject("http", new Http()); // 限制文件访问
@@ -72,9 +62,6 @@ public class EngineExtend
engine.AddHostType("ImageRegion", typeof(ImageRegion));
engine.AddHostType("Region", typeof(Region));
engine.AddHostType("Pen", typeof(Pen));
engine.AddHostType("Color", typeof(Color));
engine.AddHostType("CombatScenes", typeof(CombatScenes));
engine.AddHostType("Avatar", typeof(Avatar));
@@ -84,33 +71,16 @@ public class EngineExtend
engine.AddHostType("ServerTime", typeof(ServerTime));
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
engine.AddHostType("AutoBossParam", typeof(AutoBossParam));
engine.AddHostType("CountInventoryItemParam", typeof(CountInventoryItemParam));
engine.AddHostType("GridScreenName", typeof(GridScreenName));
engine.AddHostType("ItemIconRecognitionMode", typeof(ItemIconRecognitionMode));
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
engine.AddHostType("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
engine.AddHostObject("strategyFile", new StrategyFile());
//鼠标回调
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
// 添加C#的类型
engine.AddHostType(typeof(Task));
// 新的BvPage类
engine.AddHostType("BvPage", typeof(BvPage));
engine.AddHostType("BvLocator", typeof(BvLocator));
engine.AddHostType("BvImage", typeof(BvImage));
engine.AddHostObject("host", new CustomHostFunctions());
// HTML 遮罩
engine.AddHostObject("htmlMask", new HtmlMask(workDir));
// 导入 JavaScript 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.AllowCategoryMismatch;
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
if (searchPaths != null)
{
var normalizedPaths = new List<string>();
@@ -172,4 +142,4 @@ public class EngineExtend
engine.AddHostObject("inputText", GlobalMethod.InputText);
#pragma warning restore CS8974 // Converting method group to non-delegate type
}
}
}
@@ -216,9 +216,6 @@ public partial class ScriptGroupProject : ObservableObject
}
JsScriptSettingsObject ??= new ExpandoObject();
// 清理配置中的无效值
CleanInvalidSettingsValues();
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
await Project.ExecuteAsync(JsScriptSettingsObject, pathingPartyConfig);
}
@@ -339,67 +336,6 @@ public partial class ScriptGroupProject : ObservableObject
{
OnPropertyChanged(nameof(ScheduleDesc));
}
/// <summary>
/// 清理 JsScriptSettingsObject 中不在 settings.json 定义的 Options 列表中的无效值
/// </summary>
private void CleanInvalidSettingsValues()
{
if (Project == null || JsScriptSettingsObject == null)
{
return;
}
try
{
// 加载 settings.json 中定义的配置项
var settingItems = Project.Manifest.LoadSettingItems(Project.ProjectPath);
if (settingItems.Count == 0)
{
return;
}
var settingsDict = JsScriptSettingsObject as IDictionary<string, object?>;
if (settingsDict == null)
{
return;
}
// 遍历所有 multi-checkbox 类型的配置项
foreach (var item in settingItems.Where(i => i.Type == "multi-checkbox"))
{
if (!settingsDict.ContainsKey(item.Name))
{
continue;
}
// 获取当前保存的值
var savedValue = settingsDict[item.Name];
List<string>? checkedValues = null;
if (savedValue is List<string> stringList)
{
checkedValues = stringList;
}
else if (savedValue is List<object> objectList)
{
checkedValues = objectList.Select(i => (string)i).ToList();
settingsDict[item.Name] = checkedValues;
}
// 清理不在 Options 列表中的无效值
if (checkedValues != null && item.Options != null)
{
checkedValues.RemoveAll(value => !item.Options.Contains(value));
}
}
}
catch (Exception ex)
{
// 清理失败不影响脚本执行,只记录日志
TaskControl.Logger.LogDebug(ex, "清理JS脚本配置中的无效值时发生异常");
}
}
}
public class ScriptGroupProjectExtensions
@@ -1,189 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DefaultDocumentLoader
{
private readonly string _scriptRootPath;
public PackageDocumentLoader(string scriptRootPath)
{
_scriptRootPath = Path.GetFullPath(scriptRootPath);
}
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
// ResolvePhysicalPath 可能因 sourceInfo 为空而失败,直接从脚本根目录兜底
if (targetPath == null || !File.Exists(targetPath))
{
var stripped = Regex.Replace(specifier, @"^(?:\.\.?/)+", "");
if (!Path.IsPathRooted(stripped))
{
var fullPath = Path.GetFullPath(Path.Combine(_scriptRootPath, stripped));
if (fullPath.StartsWith(_scriptRootPath, StringComparison.OrdinalIgnoreCase)
&& File.Exists(fullPath))
{
targetPath = fullPath;
}
}
}
if (targetPath == null || !File.Exists(targetPath))
{
throw new FileNotFoundException($"无法解析模块导入路径: '{specifier}'", specifier);
}
// 处理 JS 文件的重写
if (Path.GetExtension(targetPath).ToLower() == ".js")
{
var uri = new Uri(targetPath);
// 检查缓存
var cached = GetCachedDocument(uri);
if (cached != null) return cached;
string content = await File.ReadAllTextAsync(targetPath);
string processedCode = RewriteScriptCode(content, targetPath);
var documentInfo = new DocumentInfo(uri) { Category = ModuleCategory.Standard };
return CacheDocument(new StringDocument(documentInfo, processedCode), false);
}
throw new FileNotFoundException($"不支持的模块导入类型: '{specifier}' (仅支持 .js 文件)", specifier);
}
/// <summary>
/// js重写
/// </summary>
public string RewriteScriptCode(string code, string currentFilePath)
{
if (string.IsNullOrEmpty(code)) return code;
string result = code.Replace("../../../packages", "packages");
// 拦截资源导入
var resourceRegex = new Regex(@"import\s+([\w\d_*$]+|[\s\S]*?)\s+from\s+(['""])([^'""\n]+)(['""])");
result = resourceRegex.Replace(result, match =>
{
string importPart = match.Groups[1].Value.Trim();
string quote = match.Groups[2].Value;
string path = match.Groups[3].Value.Replace("../../../packages", "packages");
string? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
if (resourceFullPath != null && File.Exists(resourceFullPath))
{
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
bool isJs = resourceFullPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase);
bool isImage = IsImageFile(resourceFullPath);
// 图片 -> Mat
if (isImage)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadImageMatSync({quote}{normalizedPath}{quote});";
}
// 非 JS 资源 -> 文本内容
if (!isJs)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadTextSync({quote}{normalizedPath}{quote});";
}
}
return match.Value;
});
return result;
}
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
string? referrer = null;
if (sourceInfo.HasValue)
{
var sourceUri = sourceInfo.Value.Uri;
if (sourceUri != null && sourceUri.IsAbsoluteUri && sourceUri.IsFile)
{
referrer = sourceUri.LocalPath;
}
else if (!string.IsNullOrEmpty(sourceInfo.Value.Name))
{
if (Uri.TryCreate(sourceInfo.Value.Name, UriKind.Absolute, out var nameUri) && nameUri.IsFile)
{
referrer = nameUri.LocalPath;
}
}
}
return ResolvePathInternal(settings.SearchPath, referrer, specifier);
}
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
{
if (specifier.StartsWith("packages/", StringComparison.OrdinalIgnoreCase))
{
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
var packagesMatch = Regex.Match(specifier, @"^(?:\.\.\/)+(packages/.*)$");
if (packagesMatch.Success)
{
return ProbeFile(Path.Combine(_scriptRootPath, packagesMatch.Groups[1].Value));
}
if (specifier.StartsWith("."))
{
if (!string.IsNullOrEmpty(referrer))
{
string? dir = Path.GetDirectoryName(referrer);
if (dir != null)
{
return ProbeFile(Path.GetFullPath(Path.Combine(dir, specifier)));
}
}
}
if (!string.IsNullOrEmpty(searchPath))
{
var paths = searchPath.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var p in paths)
{
string combined = Path.Combine(p, specifier);
string? found = ProbeFile(combined);
if (found != null) return found;
}
}
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
private string? ProbeFile(string path)
{
try
{
var normalized = Path.GetFullPath(path);
if (File.Exists(normalized)) return normalized;
if (File.Exists(normalized + ".js")) return normalized + ".js";
}
catch { }
return null;
}
private static bool IsImageFile(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string ext = Path.GetExtension(path).ToLower();
string[] imageExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp" };
return imageExtensions.Contains(ext);
}
}
}
@@ -2,18 +2,13 @@ using BetterGenshinImpact.Core.Config;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.ClearScript.JavaScript;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Project;
@@ -34,7 +29,6 @@ public class ScriptProject
{
throw new DirectoryNotFoundException("脚本文件夹不存在:" + ProjectPath);
}
ManifestFile = Path.GetFullPath(Path.Combine(ProjectPath, "manifest.json"));
if (!File.Exists(ManifestFile))
{
@@ -52,7 +46,6 @@ public class ScriptProject
{
return null;
}
var stackPanel = new StackPanel
{
Margin = new Thickness(0, 0, 20, 0) // 给右侧滚动条留出位置
@@ -76,60 +69,33 @@ public class ScriptProject
return scrollViewer;
}
private IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig)
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
{
V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
// packages 依赖和资源重载
var loader = new PackageDocumentLoader(ProjectPath);
engine.DocumentSettings.Loader = loader;
// 添加 packages 到搜索路径
var libraries = new HashSet<string>(Manifest.Library ?? Array.Empty<string>())
{
".",
"./packages"
};
var libraryList = libraries.ToList();
EngineExtend.InitHost(engine, ProjectPath, libraryList.ToArray(), partyConfig);
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
return engine;
}
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig = null)
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig=null)
{
// 默认值
GlobalMethod.SetGameMetrics(1920, 1080);
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine(partyConfig);
// 使用自定义加载器解析脚本文件
var loader = (PackageDocumentLoader)engine.DocumentSettings.Loader;
if (context != null)
{
// 写入配置的内容
engine.AddHostObject("settings", context);
}
try
{
bool useModule = Manifest.Library.Length != 0 ||
code.Contains("import ", StringComparison.Ordinal) ||
code.Contains("export ", StringComparison.Ordinal);
if (useModule)
if (Manifest.Library.Length != 0)
{
// 清除Document缓存
DocumentLoader.Default.DiscardCachedDocuments();
string mainScriptPath = Path.Combine(ProjectPath, Manifest.Main);
string runtimeCode = loader.RewriteScriptCode(code, mainScriptPath);
var documentInfo = new DocumentInfo(new Uri(mainScriptPath)) { Category = ModuleCategory.Standard };
var evaluation = engine.Evaluate(documentInfo, runtimeCode);
var evaluation = engine.Evaluate(new DocumentInfo { Category = ModuleCategory.Standard }, code);
if (evaluation is Task task) await task;
}
else
@@ -145,16 +111,6 @@ public class ScriptProject
}
finally
{
// 终止代码执行
try
{
engine.Interrupt();
}
catch (Exception e)
{
TaskControl.Logger.LogError(e, "中断脚本执行异常:" + e.Message);
}
engine.Dispose();
}
}
@@ -169,4 +125,4 @@ public class ScriptProject
return code;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -84,7 +84,7 @@ public class FileAccessBridge
// if (!string.IsNullOrEmpty(directory))
// Directory.CreateDirectory(directory);
File.WriteAllText(fullPath, content, new UTF8Encoding(false));
File.WriteAllText(fullPath, content, Encoding.UTF8);
}
catch (Exception ex)
{
@@ -1,11 +1,13 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.Service;
using Serilog.Core;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script.WebView;
@@ -21,17 +23,4 @@ public class MapEditorWebBridge
{
TaskContext.Instance().Config.DevConfig.RecordMapName = mapName;
}
public async Task RunPathing(string json)
{
await ScriptService.StartGameTask();
SystemControl.ActivateWindow();
await new TaskRunner().RunThreadAsync(async () =>
{
var task = PathingTask.BuildFromJson(json);
var pathExecutor = new PathExecutor(CancellationContext.Instance.Cts.Token);
pathExecutor.PartyConfig = new PathingPartyConfig { AutoFightEnabled = false };
await pathExecutor.Pathing(task);
});
}
}
}
@@ -78,28 +78,6 @@ public sealed class RepoWebBridge
return await File.ReadAllTextAsync(userConfigPath);
}
/// <summary>
/// 获取当前仓库的已订阅脚本路径列表(JSON 数组)。
/// 相比 GetUserConfigJson() 更轻量,仅返回当前仓库的订阅路径。
/// </summary>
public string GetSubscribedScriptPaths()
{
try
{
var paths = ScriptRepoUpdater.GetSubscribedPathsForCurrentRepo();
if (paths.Count > 0)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(paths);
}
return "[]";
}
catch
{
return "[]";
}
}
public Task<string> GetFile(string relPath)
{
try
@@ -205,7 +183,7 @@ public sealed class RepoWebBridge
throw new FileNotFoundException("找不到原始 repo.json 文件");
}
string targetPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string targetPath = Path.Combine(ScriptRepoUpdater.ReposPath, "repo_updated.json");
File.Copy(repoJsonPath, targetPath, overwrite: true);
@@ -250,7 +228,10 @@ public sealed class RepoWebBridge
private static string GetRepoJsonPath()
{
string updatedRepoJsonPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string updatedRepoJsonPath = Path.Combine(
Path.GetDirectoryName(Path.Combine(ScriptRepoUpdater.ReposPath, "bettergi-scripts-list-git"))!,
"repo_updated.json"
);
if (File.Exists(updatedRepoJsonPath))
{
@@ -264,7 +245,7 @@ public sealed class RepoWebBridge
return repoJson ?? throw new FileNotFoundException("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
}
internal static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
private static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
{
foreach (JObject item in array.OfType<JObject>())
{
@@ -282,7 +263,7 @@ public sealed class RepoWebBridge
}
}
internal static void ResetHasUpdateFlag(JObject node)
private static void ResetHasUpdateFlag(JObject node)
{
if (node["hasUpdate"] is { Type: JTokenType.Boolean } hasUpdate &&
(bool)hasUpdate)
@@ -28,9 +28,6 @@ public class Simulation
SendInput.Keyboard.KeyUp(key);
}
}
SendInput.Mouse.LeftButtonUp();
SendInput.Mouse.RightButtonUp();
SendInput.Mouse.MiddleButtonUp();
}
public static bool IsKeyDown(User32.VK key)
@@ -1,167 +0,0 @@
# BetterGI 多实例命名管道协议
## 设计目标
协议不再使用 InstanceId,也不要求根实例保存“由谁启动了谁”的进程树。实例关系只由
当前 Windows 用户、Windows Session、进程用途和进程 ID 决定。
当前协议版本为 `v2`,规则如下:
- 每个 Windows 用户最多有一个根 BetterGI;
- 根 BetterGI 是该用户固定根管道的持有者,通常运行在主桌面 Session;
- 与根不在同一个 Session 的 BetterGI 是桌面分身 BetterGI;
- WebView 无论在哪个 Session 启动,都是根 BetterGI 的直接客户端;
- 桌面分身 BetterGI 只能查询和访问相同 Session 中的 WebView;
- 同一个 Session 只允许一个 BetterGI,WebView 则允许多个并通过进程 ID 精确寻址。
独立任务的选择面板、任务下发和状态回传不在当前实现范围内。
## 管道和 Windows 用户隔离
每个 Windows 用户只有一个固定根管道:
```text
BetterGI.v2.user-<Windows用户SID>.root
```
命名管道名称在整台计算机上可见,而不是按 Windows Session 隔离。因此根 BetterGI、
桌面分身 BetterGI 和 WebView 即使运行在不同 Session,也能连接同一个固定端点。
管道 ACL 只允许当前 Windows 用户 SID 完全控制,并显式拒绝 `Network` SID,所以
不同 Windows 用户分别拥有自己的根 BetterGI,彼此不会注册到对方的实例组中。
协议内容不敏感,不使用密钥、令牌、InstanceId 或父实例 ID。根端从已连接的命名管道
句柄调用 Windows API 获取客户端真实进程 ID,再由进程 ID取得真实 Windows Session;
客户端提交的用途只用于区分 BetterGI 与 WebView,不能伪造进程或 Session 身份。
## 启动参数
客户端用途仅使用:
```text
--instance <childSession|webview>
```
- `--instance childSession` 表示该进程只能作为桌面分身客户端,根暂时不存在时也不会
自行成为根;
- `--instance webview` 表示该进程只能作为 WebView 客户端;
- 不带 `--instance` 的 BetterGI 会先竞争固定根管道。竞争成功即成为根;竞争失败则
连接已有根,由根根据真实 Session 决定是转发重复启动还是注册为桌面分身。
应用自身重启时额外传递:
```text
--restart-from-pid <旧进程ID>
```
新进程会等待旧进程退出,再竞争根管道或替换同 Session 中的旧客户端连接。该参数只用于
消除重启交接期间的竞态,不作为长期身份。
## 连接拓扑和访问规则
```text
某个 Windows 用户的根 BetterGI
├─ Session 2 的桌面分身 BetterGI(最多一个)
├─ Session 3 的桌面分身 BetterGI(最多一个)
├─ Session 1 的 WebView(可多个,以进程 ID 区分)
├─ Session 2 的 WebView(可多个,以进程 ID 区分)
└─ Session 3 的 WebView(可多个,以进程 ID 区分)
```
所有客户端都直接连接根管道,不在桌面分身下面建立二级管道。这样根重启后只需恢复一个
固定端点,客户端也只需重连一个固定名称。
WebView 访问规则:
- 根 BetterGI 可以查询和访问全部 WebView;
- 桌面分身 BetterGI 只能查询与自己 Windows Session 相同的 WebView;
- 单播通过 WebView 进程 ID 精确定位;
- 组播由调用方先查询可见 WebView,再逐个发送,不在协议中维护易失的实例组。
## 连接建立和重复启动
客户端连接固定根管道后,首先发送 `connection.open`。根根据管道连接的真实进程 ID 和
Session 处理:
1. `webview`:按进程 ID 注册,可在断线后替换旧连接。
2. BetterGI 与根位于相同 Session:视为重复启动,把业务启动参数转发给根窗口,然后
新进程退出。
3. BetterGI 与根位于不同 Session:注册为桌面分身。
4. 同一 Session 已有桌面分身:把业务启动参数转发给已有进程,然后新进程退出。
5. 旧连接已经失效,或 `--restart-from-pid` 指向该 Session 中被替换的进程:接受新连接。
## 断线、闪退和退出语义
桌面分身 BetterGI 与 WebView 在根管道断开后,每秒尝试重新连接固定根管道,且没有总
超时时间。因此根 BetterGI 闪退、被结束进程或隔很久后才重新启动,都不改变客户端的
发现地址;新根取得固定管道后,仍存活的客户端会自动重新注册。
正常关闭根 BetterGI 时,现有 `ChildSessionService.Dispose` 流程继续主动断开 RDP 并
注销桌面分身 Session。只有未执行正常释放流程的闪退场景,桌面分身才会留存并等待根
恢复。
连接断开即移除对应运行时记录,不把客户端清单持久化。根重启后的关系由仍存活的客户端
重新连接重建,避免把已经退出的 PID 当作在线实例。
## 帧格式
同一条连接同时承载 JSON 控制消息和二进制相对鼠标批次。整数使用小端序。
```text
uint32 payloadLength
byte payloadType
byte[] payload
```
`payloadLength` 最大为 1 MiB。
| payloadType | 内容 |
| --- | --- |
| `1` | UTF-8 JSON 控制消息 |
| `2` | 相对鼠标二进制批次 |
JSON 信封的主要字段:
```json
{
"version": 2,
"requestId": "00000000-0000-0000-0000-000000000000",
"operation": "ping",
"success": true,
"errorCode": null,
"errorMessage": null,
"data": {}
}
```
响应使用相同 `requestId`,并将 `operation` 设为 `response`。信封中不再传输
`sourceInstanceId`。
当前控制操作:
| 操作 | 用途 |
| --- | --- |
| `ping` | 检查连接并读取端点描述 |
| `connection.open` | 客户端声明用途,根按真实 PID/Session 注册或转发激活 |
| `activation.dispatch` | 根向已有 BetterGI 转发二次启动参数 |
| `input.relativeMouse.subscribe` | 桌面分身请求根开始转发相对鼠标 |
| `input.relativeMouse.unsubscribe` | 桌面分身停止转发相对鼠标 |
| `input.relativeMouse.state` | 预留的相对鼠标状态通知名称 |
| `webview.list` | 查询当前调用方可见的 WebView |
| `webview.send` | 根按目标进程 ID 向 WebView 单播 |
| `webview.message` | 根向目标 WebView 下发消息 |
相对鼠标批次结构:
```text
uint16 sampleCount // 1..64
uint64 firstSequence
int64 baseUtcTicks
repeat sampleCount:
int32 deltaX
int32 deltaY
int32 timestampOffsetUs
```
发送端最多等待 5 ms 或累计 64 个样本后发送。队列拥塞时将后续位移合并,避免阻塞
Raw Input 采集线程。根 BetterGI 仅在游戏鼠标模式已启用、桌面分身窗口可见、RDP 已连接且
`Input Capture Window` 具有键盘焦点时转发。
@@ -1,469 +0,0 @@
# Recognition.json 编写说明
本文档说明各任务目录下 `Assets\Recognition.json` 的写法,用于将普通静态 `RecognitionObject` 配置化,并通过 `RecognitionAssets.Get(...)` 动态加载。
## 1. 文件位置
每个任务自己的识别配置文件放在:
```text
BetterGenshinImpact\GameTask\<任务名>\Assets\Recognition.json
```
例如:
```text
BetterGenshinImpact\GameTask\AutoSkip\Assets\Recognition.json
BetterGenshinImpact\GameTask\Common\Element\Assets\Recognition.json
```
调用方式通常是:
```csharp
RecognitionAssets.Get("AutoSkip", "Collect", region);
RecognitionAssets.Get("AutoFight", "Confirm", width, height);
ElementRecognition.Get("PaimonMenu", region);
```
其中第二个参数就是 `objects` 下的对象名。
## 2. 基本结构
```json
{
"version": 1,
"vars": {},
"regions": {},
"templates": {},
"objects": {}
}
```
各字段含义:
- `version`:配置版本号,目前固定写 `1`
- `vars`:公共变量,供表达式复用
- `regions`:公共区域表达式,供 `roi` / `reference.bbox` 通过 `@别名` 引用
- `templates`:公共模板别名,供 `template` 通过 `@别名` 引用
- `objects`:识别对象定义集合
## 3. 一个最小示例
```json
{
"version": 1,
"regions": {
"topLeftQuarter": "rect(0, 0, cw / 4, ch / 4)"
},
"objects": {
"PaimonMenu": {
"type": "TemplateMatch",
"template": "paimon_menu.png",
"roi": "@topLeftQuarter",
"draw": false
}
}
}
```
说明:
- `PaimonMenu` 是对象名,也是调用时的 `objectName`
- `type` 必须与 `RecognitionTypes` 枚举文本完全一致
- `template` 是模板文件名
- `roi` 可以直接写表达式,也可以引用 `regions` 中的别名
- 模板匹配场景下如果不写 `name`,运行时名称默认使用模板名,因此通常可以省略
## 4. 表达式系统
`roi`、`reference.bbox`、`vars` 中的值都支持表达式,底层由 NCalc 解析。
### 4.1 内置变量
- `cw`:当前截图宽度
- `ch`:当前截图高度
- `cx`:当前截图区域左上角 X
- `cy`:当前截图区域左上角 Y
- `s`:资源缩放系数
- 当截图宽度小于 1920 时,`s = cw / 1920`
- 其他情况 `s = 1`
### 4.2 支持的函数
- `rect(x, y, w, h)`:创建矩形
- `cutLeft(percent)`:截取左侧比例区域
- `cutRight(percent)`:截取右侧比例区域
- `cutTop(percent)`:截取上侧比例区域
- `cutBottom(percent)`:截取下侧比例区域
- `cutLeftTop(widthPercent, heightPercent)`:截取左上区域
- `cutRightTop(widthPercent, heightPercent)`:截取右上区域
- `cutLeftBottom(widthPercent, heightPercent)`:截取左下区域
- `cutRightBottom(widthPercent, heightPercent)`:截取右下区域
### 4.3 示例
```json
{
"vars": {
"topBarHeight": "100 * s"
},
"regions": {
"inventoryTopRight": "rect(cw * 3 / 4, 0, cw / 4, topBarHeight)",
"pageCloseWhite": "rect(cw - cw / 8, 0, cw / 8, ch / 8)",
"leftBottom": "cutLeftBottom(0.2, 0.2)"
}
}
```
## 5. 模板别名和区域别名
### 5.1 区域别名
在 `regions` 中先定义:
```json
"regions": {
"option": "rect(cw / 2, ch / 12, cw - cw / 2 - cw / 6, ch - ch / 12 - 10)"
}
```
再在对象里引用:
```json
"roi": "@option"
```
### 5.2 模板别名
在 `templates` 中先定义:
```json
"templates": {
"pageClose": "page_close.png"
}
```
再在对象里引用:
```json
"template": "@pageClose"
```
适合多个对象共用同一模板,或者模板文件名比较长的时候。
## 6. objects 常用字段
下面只列常用和当前加载器支持的字段。
### 6.1 通用字段
- `name`
- 可选
- 运行时名称
- 模板匹配通常可以省略
- `type`
- 必填
- 必须与 `RecognitionTypes` 一致
- 常见值:
- `TemplateMatch`
- `ColorMatch`
- `OcrMatch`
- `Ocr`
- `ColorRangeAndOcr`
- `roi`
- 可选
- 返回 `Rect` 的表达式,或 `@区域别名`
- `draw`
- 可选
- 是否绘制调试框
- `drawColor`
- 可选
- 调试框颜色,HTML 颜色格式,例如 `#FF0000`
- `drawWidth`
- 可选
- 调试框线宽
## 7. TemplateMatch 字段
适用于 `type = "TemplateMatch"`。
- `template`
- 必填
- 模板文件名、相对路径或 `@模板别名`
- `templateMode`
- 可选
- 对应 OpenCV `ImreadModes`
- 默认 `Color`
- `threshold`
- 可选
- 匹配阈值
- 默认通常为 `0.8`
- `use3Channels`
- 可选
- 是否使用三通道匹配
- `templateMatchMode`
- 可选
- 对应 OpenCV `TemplateMatchModes`
- 常见值:
- `CCoeffNormed`
- `CCorrNormed`
- `SqDiff`
- `useMask`
- 可选
- 是否启用遮罩
- `maskColor`
- 可选
- 遮罩颜色,HTML 颜色格式
- `maxMatchCount`
- 可选
- 最大匹配数量
- 不限制时可不填
- `useBinaryMatch`
- 可选
- 是否先二值化再匹配
- `binaryThreshold`
- 可选
- 二值化阈值
示例:
```json
"SubmitGoods": {
"type": "TemplateMatch",
"template": "submit_goods.png",
"roi": "rect(0, 0, cw / 2, ch / 3)",
"threshold": 0.9,
"use3Channels": true,
"templateMatchMode": "CCorrNormed",
"draw": true
}
```
## 8. ColorMatch / ColorRangeAndOcr 字段
适用于颜色范围识别相关场景。
- `colorCode`
- 可选
- 对应 OpenCV `ColorConversionCodes`
- 常见值:
- `BGR2RGB`
- `BGR2HSV`
- `BGR2GRAY`
- `lowerColor`
- 可选
- 颜色下界
- 支持 1 到 4 个数字
- `upperColor`
- 可选
- 颜色上界
- 支持 1 到 4 个数字
- `matchCount`
- 可选
- 至少命中的像素点数量
示例:
```json
"SomeColorMark": {
"type": "ColorMatch",
"roi": "rect(0, 0, cw / 4, ch / 4)",
"colorCode": "BGR2HSV",
"lowerColor": [90, 80, 80],
"upperColor": [130, 255, 255],
"matchCount": 10
}
```
## 9. OCR / OcrMatch 字段
适用于 `type = "Ocr"` 或 `type = "OcrMatch"`。
- `ocrEngine`
- 可选
- 对应 `OcrEngineTypes`
- 当前通常写 `Paddle`
- `text`
- 可选
- 用于 OCR 结果筛选的目标文本
- `replace`
- 可选
- OCR 误识别替换表
- `allContains`
- 可选
- 所有文本都包含才算成功
- `oneContains`
- 可选
- 任一文本包含即成功
- `regex`
- 可选
- 正则表达式列表
- 当前实现要求列表中的所有正则都命中
示例:
```json
"PlayingText": {
"type": "OcrMatch",
"roi": "rect(100 * s, 35 * s, 85 * s, 35 * s)",
"oneContains": [
"播放",
"暂停",
"继续"
],
"draw": true
}
```
`replace` 示例:
```json
"replace": {
"播放": ["播故", "搰放"],
"继续": ["绫续"]
}
```
## 10. reference 字段
`reference` 用于记录模板截图来源信息,便于后续按参考尺寸或原始包围盒做定位扩展。
字段:
- `size`
- 格式 `[width, height]`
- 表示模板来源截图尺寸
- `bbox`
- 返回 `Rect` 的表达式
- 表示模板在来源截图中的包围盒
示例:
```json
"reference": {
"size": [1920, 1080],
"bbox": "rect(1680, 32, 180, 72)"
}
```
## 11. search 字段
`search` 用于描述锚点和额外扩展区域。
字段:
- `anchor`
- 对应 `SearchAnchorMode` 枚举名
- `expand`
- 格式 `[width, height]`
- 表示搜索时向外扩展的尺寸
示例:
```json
"search": {
"anchor": "Center",
"expand": [120, 80]
}
```
## 12. 推荐写法
- 普通模板匹配对象优先只写 `type`、`template`、`roi`、`threshold`
- 重复使用的区域优先抽到 `regions`
- 重复使用的模板优先抽到 `templates`
- 可通过表达式描述的 ROI 尽量写进 JSON,不再写死在 C# 里
- 普通静态对象不要再回退到 `XXXAssets` 字段里缓存,直接调用 `RecognitionAssets.Get(...)`
- 模板匹配对象通常不需要手写 `name`
## 13. 不建议放进 JSON 的场景
下面这些仍然更适合保留在 C# 里:
- 需要运行时变量替换,而且变量来源复杂
- 需要动态拼接多份 Mat / 模板列表
- 需要依赖特殊 OpenCV 预处理逻辑
- 需要依赖外部配置、业务状态或复杂流程控制
- ROI 不是单纯表达式,而是与多个运行时对象联动
这类对象可以继续保留在对应任务类或专用 helper 中。
## 14. 排错建议
如果加载失败,当前日志会输出类似:
```text
Recognition 加载失败: Collect @ 1920x1080, file=...
Recognition 构建失败: Collect @ 1920x1080
```
建议优先检查:
1. `type` 是否和枚举名完全一致
2. `templateMatchMode`、`templateMode`、`colorCode`、`ocrEngine`、`anchor` 是否和对应枚举名完全一致
3. `template` 引用的模板文件或模板别名是否存在
4. `roi` / `bbox` 表达式是否能返回 `Rect`
5. `@区域别名`、`@模板别名`、`vars` 引用的名字是否存在
6. `lowerColor` / `upperColor` 数组长度是否在 1 到 4 之间
## 15. 一个较完整示例
```json
{
"version": 1,
"vars": {
"topBarHeight": "100 * s"
},
"regions": {
"topLeftQuarter": "rect(0, 0, cw / 4, ch / 4)",
"inventoryTopRight": "rect(cw * 3 / 4, 0, cw / 4, topBarHeight)"
},
"templates": {
"menu": "paimon_menu.png"
},
"objects": {
"PaimonMenu": {
"type": "TemplateMatch",
"template": "@menu",
"roi": "@topLeftQuarter",
"threshold": 0.8,
"draw": false
},
"Inventory": {
"type": "TemplateMatch",
"template": "inventory.png",
"roi": "@inventoryTopRight",
"draw": false
},
"ConfirmText": {
"type": "OcrMatch",
"roi": "rect(cw / 2, ch / 2, 200 * s, 80 * s)",
"oneContains": ["确认", "确定"]
}
}
}
```
@@ -96,40 +96,40 @@ public class AutoArtifactSalvageTask : ISoloTask
switch (gridScreenName)
{
case GridScreenName.Weapons:
recognitionObjectChecked = ElementRecognition.Get("BagWeaponChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagWeaponUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagWeaponChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagWeaponUnchecked;
break;
case GridScreenName.Artifacts:
recognitionObjectChecked = ElementRecognition.Get("BagArtifactChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagArtifactUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagArtifactChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagArtifactUnchecked;
break;
case GridScreenName.CharacterDevelopmentItems:
recognitionObjectChecked = ElementRecognition.Get("BagCharacterDevelopmentItemChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagCharacterDevelopmentItemUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagCharacterDevelopmentItemChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagCharacterDevelopmentItemUnchecked;
break;
case GridScreenName.Food:
recognitionObjectChecked = ElementRecognition.Get("BagFoodChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagFoodUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagFoodChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagFoodUnchecked;
break;
case GridScreenName.Materials:
recognitionObjectChecked = ElementRecognition.Get("BagMaterialChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagMaterialUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagMaterialChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagMaterialUnchecked;
break;
case GridScreenName.Gadget:
recognitionObjectChecked = ElementRecognition.Get("BagGadgetChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagGadgetUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagGadgetChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagGadgetUnchecked;
break;
case GridScreenName.Quest:
recognitionObjectChecked = ElementRecognition.Get("BagQuestChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagQuestUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagQuestChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagQuestUnchecked;
break;
case GridScreenName.PreciousItems:
recognitionObjectChecked = ElementRecognition.Get("BagPreciousItemChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagPreciousItemUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagPreciousItemChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagPreciousItemUnchecked;
break;
case GridScreenName.Furnishings:
recognitionObjectChecked = ElementRecognition.Get("BagFurnishingChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagFurnishingUnchecked");
recognitionObjectChecked = ElementAssets.Instance.BagFurnishingChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagFurnishingUnchecked;
break;
default:
throw new NotSupportedException($"背包不支持的界面:{gridScreenName.GetDescription()}");
@@ -147,7 +147,7 @@ public class AutoArtifactSalvageTask : ISoloTask
if (Bv.IsInPromptDialog(ra))
{
// 如果存在物品过期提示,则点击确认按钮
Bv.ClickWhiteConfirmButton(ra, new Rect(0, 0, ra.Width, (int)Math.Round(ra.Height - ra.Height * 0.2)));
Bv.ClickWhiteConfirmButton(ra.DeriveCrop(0, 0, ra.Width, ra.Height - ra.Height * 0.2));
Sleep(300, ct);
return false;
}
@@ -199,7 +199,7 @@ public class AutoArtifactSalvageTask : ISoloTask
// 点击分解按钮打开分解界面
using var ra2 = CaptureToRectArea();
using var salvageBtn = ra2.Find(ElementRecognition.Get("BtnArtifactSalvage", ra2));
using var salvageBtn = ra2.Find(ElementAssets.Instance.BtnArtifactSalvage);
if (salvageBtn.IsExist())
{
salvageBtn.Click();
@@ -258,7 +258,7 @@ public class AutoArtifactSalvageTask : ISoloTask
}
}
using var quickSelectConfirmBtn = ra4.Find(ElementRecognition.Get("BtnWhiteConfirm", ra4));
using var quickSelectConfirmBtn = ra4.Find(ElementAssets.Instance.BtnWhiteConfirm);
if (quickSelectConfirmBtn.IsExist())
{
quickSelectConfirmBtn.Click();
@@ -268,7 +268,7 @@ public class AutoArtifactSalvageTask : ISoloTask
// 点击分解
using var ra5 = CaptureToRectArea();
var salvageBtnConfirm = ra5.Find(ElementRecognition.Get("BtnArtifactSalvageConfirm", ra5));
var salvageBtnConfirm = ra5.Find(ElementAssets.Instance.BtnArtifactSalvageConfirm);
if (salvageBtnConfirm.IsExist())
{
salvageBtnConfirm.Click();
@@ -812,4 +812,4 @@ public class AutoArtifactSalvageTask : ISoloTask
/// </summary>
Selected
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1018 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

@@ -1,107 +0,0 @@
{
"info": {
"authors": [],
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1755828864835,
"map_name": "Teyvat",
"name": "未命名路径",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "walk",
"type": "teleport",
"x": 2289.0078125,
"y": -1197.31640625
},
{
"action": "combat_script",
"action_params": "wait(1.5)",
"id": 2,
"move_mode": "walk",
"type": "target",
"x": 2270.921875,
"y": -1181.94580078125
},
{
"action": "",
"action_params": "",
"id": 3,
"move_mode": "walk",
"type": "target",
"x": 2266.435546875,
"y": -1173.31787109375
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "walk",
"type": "path",
"x": 2238.7578125,
"y": -1184.73046875
},
{
"action": "",
"action_params": "",
"id": 5,
"move_mode": "fly",
"type": "path",
"x": 2215.11328125,
"y": -1197.294921875
},
{
"action": "",
"action_params": "",
"id": 6,
"move_mode": "walk",
"type": "path",
"x": 2191.3359375,
"y": -1214.46533203125
},
{
"action": "",
"action_params": "",
"id": 7,
"move_mode": "walk",
"type": "path",
"x": 2119.0048828125,
"y": -1231.728515625
},
{
"action": "",
"action_params": "",
"id": 8,
"move_mode": "walk",
"type": "path",
"x": 2117.5,
"y": -1254.09521484375
},
{
"action": "stop_flying",
"action_params": "",
"id": 9,
"move_mode": "fly",
"type": "path",
"x": 2114.4345703125,
"y": -1308.1357421875
},
{
"action": "",
"action_params": "",
"id": 10,
"move_mode": "run",
"type": "path",
"x": 2110.509765625,
"y": -1331.59130859375
}
]
}
Loaded 100 of 1226 files, more files were not shown because too many files have changed in this diff. Show more