Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4118e28f3d | ||
|
|
25e73e500a | ||
|
|
fd1a1a439a | ||
|
|
9a39c769fe | ||
|
|
3ec8048805 | ||
|
|
b3f90e7049 | ||
|
|
bee45ef958 | ||
|
|
4dca07d17f | ||
|
|
c9db8b8291 | ||
|
|
51c1aaea4e | ||
|
|
7a48461d7a | ||
|
|
c4f9e70eeb | ||
|
|
c163bb0cd5 | ||
|
|
704d920d6d | ||
|
|
95a6f9a059 | ||
|
|
67162cd6a2 | ||
|
|
711bbef8a2 | ||
|
|
4893fc6100 | ||
|
|
d533eab029 | ||
|
|
8a4db29436 | ||
|
|
a6ef833f00 | ||
|
|
ae72911f81 | ||
|
|
21a575086d | ||
|
|
d42e6142ad | ||
|
|
2083b11c31 | ||
|
|
a4cb735c32 | ||
|
|
d1967477d2 | ||
|
|
6180194da2 | ||
|
|
50254a6efc | ||
|
|
249a79d7be | ||
|
|
6f713ca719 | ||
|
|
10808edb21 | ||
|
|
902caf462f | ||
|
|
614f6a8abf | ||
|
|
893777b4ad | ||
|
|
6982d3ba74 | ||
|
|
a0bc552a8a | ||
|
|
1dd1e2aa16 | ||
|
|
76353f54d1 | ||
|
|
b808aa696c | ||
|
|
5bd55682d3 | ||
|
|
b9106fd994 | ||
|
|
8323ece56c | ||
|
|
d8335ff097 | ||
|
|
e761c2e01b | ||
|
|
880ac623ff | ||
|
|
86ac610bf0 | ||
|
|
efc90cb63b | ||
|
|
6a8a9a6223 | ||
|
|
810a2797c2 | ||
|
|
ac7348e427 | ||
|
|
537c5d0024 | ||
|
|
5011141a6e | ||
|
|
44510b49ef | ||
|
|
6f0caa4505 | ||
|
|
4951ce7f08 | ||
|
|
24201751c9 | ||
|
|
0af68c28f6 | ||
|
|
e0deb2049f | ||
|
|
29aff3ed75 | ||
|
|
18781460a1 | ||
|
|
92b6dda274 | ||
|
|
fd33d0657a | ||
|
|
e1afc4b552 | ||
|
|
d99d2c2c52 | ||
|
|
7849b675b3 | ||
|
|
6eef898743 | ||
|
|
3b7ea40ba9 | ||
|
|
6efd415290 | ||
|
|
e14b28ddba | ||
|
|
248e1f0e6e | ||
|
|
c5851914df | ||
|
|
bfe5f868ed | ||
|
|
f29966868c | ||
|
|
cbb49b705d | ||
|
|
459920cb3f | ||
|
|
80048ca262 | ||
|
|
5a0edf2bf4 | ||
|
|
cd4459c889 | ||
|
|
477343c6af | ||
|
|
eac0a285ac | ||
|
|
8e24879b33 | ||
|
|
42e1c0e745 | ||
|
|
de5d38a5ba | ||
|
|
f29b0828ab | ||
|
|
491b55bcb5 | ||
|
|
05b074ccd4 | ||
|
|
7519ccb9e4 | ||
|
|
fca9e5cbe7 | ||
|
|
4790db7979 | ||
|
|
6202243c8d | ||
|
|
c2943426dc | ||
|
|
fd760e6b85 | ||
|
|
5913398153 | ||
|
|
4662118f59 | ||
|
|
7eb493bc33 | ||
|
|
4f5ef08c1f | ||
|
|
9424d1f3c3 | ||
|
|
0233a19f39 | ||
|
|
4d1c1847c2 | ||
|
|
8aeb1cd7ef | ||
|
|
07c5ea5849 | ||
|
|
6e51f601f8 | ||
|
|
4e019511e2 | ||
|
|
178ae2dc96 | ||
|
|
97c90aa117 | ||
|
|
63432547cf | ||
|
|
5a584c0143 | ||
|
|
1799103e84 | ||
|
|
7de8a45dce | ||
|
|
8bd43f3918 | ||
|
|
c8dbfeb370 | ||
|
|
e33800e754 | ||
|
|
7cea971b6e | ||
|
|
ad78bf95b0 | ||
|
|
83a86c8bae | ||
|
|
325142390d | ||
|
|
7d838cd644 | ||
|
|
64defc0f02 | ||
|
|
b3e46b3004 | ||
|
|
bbd5a1b806 | ||
|
|
cca51e1f5f | ||
|
|
639ccfb123 | ||
|
|
a0f0983af7 | ||
|
|
05efd0ceef | ||
|
|
412a6c405e | ||
|
|
4f4cfc052d | ||
|
|
27017bbf4e | ||
|
|
29d93a2c6e | ||
|
|
6209e1b498 | ||
|
|
ae131ea5ce | ||
|
|
5c6a2ba9fd | ||
|
|
7d1872bda9 | ||
|
|
c7c8210df6 | ||
|
|
4a289f3f4f | ||
|
|
c97e6055fa | ||
|
|
bf0b442442 | ||
|
|
98ef0b879f | ||
|
|
e97dc4e46b | ||
|
|
2d6182233b | ||
|
|
faf84401bc | ||
|
|
4cc4e123d5 | ||
|
|
8f2bdc76ad | ||
|
|
d24023e7bf | ||
|
|
ac38d39b52 | ||
|
|
f7a2c558c5 | ||
|
|
e7c01cf70c | ||
|
|
fd80f2952a | ||
|
|
fe4e978e6f | ||
|
|
df4325bea3 | ||
|
|
cbb7171cc5 | ||
|
|
68404a63ca | ||
|
|
8abea9801a | ||
|
|
bffa587517 | ||
|
|
cab921384b | ||
|
|
8361479787 | ||
|
|
2bebe865ad | ||
|
|
08f5fe9504 | ||
|
|
1566560f80 | ||
|
|
b2631ed362 | ||
|
|
3f81331e37 | ||
|
|
3ea1c67288 | ||
|
|
41909055c7 | ||
|
|
00305aa5d2 | ||
|
|
a3c2024267 | ||
|
|
f0cd4fe90d | ||
|
|
9541959fdc | ||
|
|
c3c22507c1 | ||
|
|
97e94ace76 | ||
|
|
334e30c695 | ||
|
|
5207fcafb2 | ||
|
|
debc23cc3a | ||
|
|
6de0c9b9ef | ||
|
|
bf13dbd475 | ||
|
|
3fcf205235 | ||
|
|
a96f9e911e | ||
|
|
d026aea00e | ||
|
|
eee20bb99c | ||
|
|
c9650d06a8 | ||
|
|
0b75ad7db8 | ||
|
|
af9b14608a | ||
|
|
6ef0377840 | ||
|
|
885c78a9a5 | ||
|
|
43998fa01b | ||
|
|
dc8267180c | ||
|
|
a9590cce49 | ||
|
|
0ccc5a0cbc | ||
|
|
eddc838ec8 | ||
|
|
d4408763e2 | ||
|
|
0e9facb478 | ||
|
|
d958feb686 | ||
|
|
9c9d2c26b4 | ||
|
|
59c0961b25 | ||
|
|
77c787222f | ||
|
|
44507432ec | ||
|
|
8fe55a13f2 | ||
|
|
0c6e0172dc | ||
|
|
f80af2b672 | ||
|
|
c87a96756f | ||
|
|
0a17d5449b | ||
|
|
42a9ec18a5 | ||
|
|
dee1e5af8d | ||
|
|
23bd3c5ca9 | ||
|
|
c37f8c8ff2 | ||
|
|
5c72096bc9 | ||
|
|
40509150c5 | ||
|
|
d5ffa7758b | ||
|
|
0260a29648 | ||
|
|
8f7cab46f3 | ||
|
|
50614cbdb9 | ||
|
|
bab2191b06 | ||
|
|
4526a1ca8b | ||
|
|
a7cb36712d | ||
|
|
3543e20323 | ||
|
|
bae812d165 | ||
|
|
ec9a149e01 | ||
|
|
35817f24b9 | ||
|
|
12ef97cdfa | ||
|
|
f1b28809eb | ||
|
|
494126996a | ||
|
|
9e62ecdca4 | ||
|
|
90289d8a8c | ||
|
|
98d7cfd401 | ||
|
|
4af9144e67 | ||
|
|
68b870a93c | ||
|
|
98bfb82621 | ||
|
|
7660d03de8 | ||
|
|
92d1f9eac8 | ||
|
|
08fb1a846c | ||
|
|
9e214af3c2 | ||
|
|
5421def4d5 | ||
|
|
a5ea122d96 | ||
|
|
f55760aba5 | ||
|
|
9655e143ab | ||
|
|
c7376ddc03 | ||
|
|
1725a5fb69 | ||
|
|
18c08357ce | ||
|
|
d73b025e04 | ||
|
|
b50ae3e37f | ||
|
|
c22a4c9548 | ||
|
|
95a39ab4cb | ||
|
|
8c9d7ca739 | ||
|
|
83299856bc | ||
|
|
be3920be9c | ||
|
|
00dc692fc9 | ||
|
|
83cd1e4658 | ||
|
|
ed22dff1c5 | ||
|
|
34a373cf41 | ||
|
|
9691964992 | ||
|
|
b19836e49c | ||
|
|
4344efd574 | ||
|
|
9ee83a442c | ||
|
|
e22707da21 | ||
|
|
5b9d882b02 | ||
|
|
b0c8fca195 | ||
|
|
6b22225d05 | ||
|
|
af320489c9 | ||
|
|
507c76a7c7 | ||
|
|
535d6d8e10 | ||
|
|
ad21612cf0 | ||
|
|
ac6ef873fb | ||
|
|
7fcd7cce2e | ||
|
|
8f554e2114 | ||
|
|
0060ae5a85 | ||
|
|
976b74b308 | ||
|
|
5b9aa2eb1e | ||
|
|
6ddc4117ad | ||
|
|
2182ce64dd | ||
|
|
b550fee177 | ||
|
|
08f65dcc60 | ||
|
|
a977d8e60e | ||
|
|
0bb3619067 | ||
|
|
69e039497c | ||
|
|
476f6ff08c | ||
|
|
ff72ca4c4f | ||
|
|
53c48c7aac | ||
|
|
4d8877c7c2 | ||
|
|
87e9e2c7fe | ||
|
|
1db02d06af | ||
|
|
59d01d4f6f | ||
|
|
371550b917 | ||
|
|
1d948c6328 | ||
|
|
f055785429 | ||
|
|
e08aaa8e0f | ||
|
|
fb587f4bb7 | ||
|
|
dc1070ad19 | ||
|
|
5a38fc6aa4 | ||
|
|
80a9c059bf | ||
|
|
9f80a18e7d | ||
|
|
1bb8017e55 | ||
|
|
fd8da28084 | ||
|
|
9099e17b5a | ||
|
|
6f0dbd9c3f | ||
|
|
d1eb06e411 | ||
|
|
603d75f085 | ||
|
|
2a07ea7a5a | ||
|
|
780f566198 | ||
|
|
76d11e16c9 | ||
|
|
d7e25d00cd | ||
|
|
c135f63730 | ||
|
|
df4a058715 | ||
|
|
1040e45da5 | ||
|
|
bd0039f2fb | ||
|
|
ad5a5f8a1b | ||
|
|
761d66b651 | ||
|
|
1678aada02 | ||
|
|
99e97d7180 | ||
|
|
40d424dc71 | ||
|
|
0f951a4249 | ||
|
|
0d9b024ec3 | ||
|
|
6d73496132 | ||
|
|
f63362299c | ||
|
|
132f16cb12 | ||
|
|
5437cb7116 | ||
|
|
c5f1890d97 | ||
|
|
14068e7279 | ||
|
|
7d7ebe1fc2 | ||
|
|
98e50ebf3c | ||
|
|
bbd892c2de | ||
|
|
206eb284d7 | ||
|
|
7e30466378 | ||
|
|
9bf2a41e2e | ||
|
|
5ff61ec5bb | ||
|
|
0eb90304c4 | ||
|
|
903a72525f | ||
|
|
3b028d8939 | ||
|
|
7ec3687c53 | ||
|
|
a962d69ac3 | ||
|
|
ca91b97aee | ||
|
|
10b04f0045 | ||
|
|
075da66bbe | ||
|
|
cb822eb5ed | ||
|
|
1202ad3180 | ||
|
|
8d65f739a5 | ||
|
|
1631729dd8 | ||
|
|
abebd1c9b5 | ||
|
|
da35a91dee | ||
|
|
ff148e9b8c | ||
|
|
cb3dcace85 | ||
|
|
eb1beaadfd | ||
|
|
4f9fa50e99 | ||
|
|
4b14e03274 | ||
|
|
beb0a70f5b | ||
|
|
080bf4196b | ||
|
|
d7e7e40465 | ||
|
|
e2111543a7 | ||
|
|
d50b09ad69 | ||
|
|
92b8beab53 | ||
|
|
4beaa4a3d9 | ||
|
|
beddfe01ba | ||
|
|
bf06ba3ce1 | ||
|
|
85d3da2f02 | ||
|
|
105e4ccd10 | ||
|
|
5992a9d91b | ||
|
|
5f02b26cd2 | ||
|
|
6388c6521c | ||
|
|
db74dec3f6 | ||
|
|
89edfe7945 | ||
|
|
deaa565847 | ||
|
|
90b812f6a9 | ||
|
|
659143aaf6 | ||
|
|
114cad1b47 | ||
|
|
cfe5e745be | ||
|
|
12ee510601 | ||
|
|
b3a6da24f9 | ||
|
|
f95ced446c | ||
|
|
5eb91c4092 | ||
|
|
4bc4516cd8 | ||
|
|
3df57333c2 | ||
|
|
13b85c5904 | ||
|
|
1a3e626af0 | ||
|
|
0c20c74075 | ||
|
|
f91a15515e | ||
|
|
63fe6ec8bb | ||
|
|
2acdb2c1a1 | ||
|
|
740ce67be7 | ||
|
|
f9d04bc62b | ||
|
|
a83ba61d87 | ||
|
|
974a80eb2b | ||
|
|
a33eb1c45f | ||
|
|
b561b8db33 | ||
|
|
8a7c47b17a | ||
|
|
4cb82865d8 | ||
|
|
9479297dcc | ||
|
|
d61f804442 | ||
|
|
4747c39ae1 | ||
|
|
7a6854e7d5 | ||
|
|
6f7c78b474 | ||
|
|
43701b90f0 | ||
|
|
6090cce849 | ||
|
|
96cf2d5261 | ||
|
|
8813235ebf | ||
|
|
bbd9634c07 | ||
|
|
d7b6ab9365 | ||
|
|
13f3951d7f | ||
|
|
c8fba493c1 | ||
|
|
96f523d4b8 | ||
|
|
f8e231c235 | ||
|
|
58bceffe0e | ||
|
|
4c6232fdb3 | ||
|
|
1eb483b639 | ||
|
|
796bda0af3 | ||
|
|
6d8bbc18fc | ||
|
|
753c595625 | ||
|
|
88bd60ab93 | ||
|
|
36669b89ef | ||
|
|
70b3f6dd99 | ||
|
|
6996356251 | ||
|
|
359bdb899e | ||
|
|
ec39fc980e | ||
|
|
8d502d76c1 | ||
|
|
3519008bd2 | ||
|
|
649bc0fc66 | ||
|
|
4fbc74e7e0 | ||
|
|
847e4076d2 | ||
|
|
951a890ded | ||
|
|
ea13091320 | ||
|
|
2e57a3aae9 | ||
|
|
ff4ff78349 | ||
|
|
71ace72d9c | ||
|
|
e54e5e7af7 | ||
|
|
17af6e01f8 | ||
|
|
5e98ff724f | ||
|
|
e2f84f7edd | ||
|
|
de75d02104 | ||
|
|
36c2e25792 | ||
|
|
6b9ac1b5d0 | ||
|
|
6071b4096f | ||
|
|
dc1c25ee00 | ||
|
|
8ca6830c4b | ||
|
|
e5aa33c577 | ||
|
|
a76767499d | ||
|
|
3470c5e30b | ||
|
|
10ee93e8bb | ||
|
|
255bf653e8 | ||
|
|
4a17383f86 | ||
|
|
edc5580267 | ||
|
|
dfef6ddf30 | ||
|
|
0cc48ce6d8 | ||
|
|
6be85a03af | ||
|
|
e78d54ba2a | ||
|
|
1fd45c42b1 | ||
|
|
e06b105365 | ||
|
|
83637172fd | ||
|
|
b0a1bb019c | ||
|
|
304147f965 | ||
|
|
99a17010d2 | ||
|
|
fb527a13c4 | ||
|
|
2ea663b0ff | ||
|
|
bbf1be3de9 | ||
|
|
3586e37c69 | ||
|
|
4896d0344a | ||
|
|
c1d0a53110 | ||
|
|
0eedfb6969 | ||
|
|
d0c02717e8 | ||
|
|
2a53fb9742 | ||
|
|
bd8451a190 | ||
|
|
ee500b2971 | ||
|
|
b0a1715ba3 | ||
|
|
33760242ea | ||
|
|
7d91fba327 | ||
|
|
8956c306c2 | ||
|
|
a7dac95468 | ||
|
|
dea40ce177 | ||
|
|
410c3f2a92 | ||
|
|
30d11bed4c | ||
|
|
cfebcd0b8d | ||
|
|
43f2263cfa | ||
|
|
f9dd661c05 | ||
|
|
24128ee64b | ||
|
|
c8d10614c5 | ||
|
|
5c7e8e8f11 | ||
|
|
907fe5b3c2 | ||
|
|
4c81109f0d | ||
|
|
11102a4be2 | ||
|
|
c1c578d256 | ||
|
|
1690a727fc | ||
|
|
ee928a6847 | ||
|
|
4ad7db06ae | ||
|
|
8a6194f374 | ||
|
|
b1f1fe913a | ||
|
|
c8be442943 | ||
|
|
3d394475e1 | ||
|
|
da068549fe | ||
|
|
ca249206ae | ||
|
|
f80814952b | ||
|
|
38f41ac573 | ||
|
|
399b9d4adb | ||
|
|
091bbb2865 | ||
|
|
ec7b00e35e | ||
|
|
c5f7a68e79 | ||
|
|
e0c56a74ea | ||
|
|
3f1dc374eb | ||
|
|
eaa412d8c9 | ||
|
|
03a4102fe7 | ||
|
|
70c5a84bed | ||
|
|
147f466fb9 | ||
|
|
4cbdaa6ff8 | ||
|
|
8300d9dd7c | ||
|
|
5b2701a68f | ||
|
|
3d84638c55 | ||
|
|
7f6c3c408b | ||
|
|
fc7993afda | ||
|
|
040a5e8417 | ||
|
|
1c33bb9282 | ||
|
|
f923a8a4d2 | ||
|
|
f658bf85ee | ||
|
|
0d8de96e17 | ||
|
|
e9413f4214 | ||
|
|
aef3fa913b | ||
|
|
d55b1d867b | ||
|
|
311c8b2f37 | ||
|
|
1a478affb2 | ||
|
|
da6d956ef1 | ||
|
|
955d7d51d9 | ||
|
|
b4053e9357 | ||
|
|
a0d8133558 | ||
|
|
99f4f54ff7 | ||
|
|
c8a8d6217a | ||
|
|
cd978327fc | ||
|
|
b0b13cb36d | ||
|
|
beb36ff41a | ||
|
|
713589734b | ||
|
|
eedce17a9c | ||
|
|
4572b94122 | ||
|
|
5831e3671c | ||
|
|
e46076eaaa | ||
|
|
c553a49f18 | ||
|
|
53810d34b8 | ||
|
|
875434b492 | ||
|
|
565510ebe6 | ||
|
|
eec4518605 | ||
|
|
201cbf1629 | ||
|
|
33013fd7a5 | ||
|
|
f9b707b1ac | ||
|
|
68ebf2eb4b | ||
|
|
2c28cc2335 | ||
|
|
47a4983c16 | ||
|
|
c5a9427ca7 | ||
|
|
12e6296059 | ||
|
|
cf344b2d39 | ||
|
|
e958e24d4e | ||
|
|
26416b00b5 | ||
|
|
54301e1e02 | ||
|
|
1e9b72e547 | ||
|
|
d660f79b4c | ||
|
|
48bbad9853 | ||
|
|
5dcbd9b577 | ||
|
|
bb1f6d7281 | ||
|
|
d4ef75344e |
No files matched your search
@@ -0,0 +1,274 @@
|
||||
---
|
||||
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,纯本地解析
|
||||
- 如果存在下面箭头左侧的作者信息,请替换为右侧的作者名
|
||||
- mno -> Bedrockx
|
||||
- 秋云 -> physligl
|
||||
- darkflamemaster -> 1004452714
|
||||
|
||||
## 内容提炼规则
|
||||
|
||||
### 强制处理顺序
|
||||
|
||||
必须先完成全部分析,再开始写 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 获取,不依赖网络
|
||||
@@ -0,0 +1,4 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
name: Bug report / 错误报告
|
||||
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
|
||||
title: "[bug] "
|
||||
type: 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
|
||||
@@ -1,9 +1,9 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: 官方文档 / Document
|
||||
url: https://bgi.huiyadan.com/doc.html
|
||||
url: https://www.bettergi.com/doc.html
|
||||
about: 请在提出问题前阅读文档 / Read the document before submit the issue
|
||||
|
||||
- name: 常见问题 / FAQ
|
||||
url: https://bgi.huiyadan.com/faq.html
|
||||
url: https://www.bettergi.com/faq.html
|
||||
about: 常见的用户提出的问题 / Common questions asked by users
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: I have feature requesting / 我有新功能请求
|
||||
about: Your request may come as a surprise. / 你的请求也许成为惊喜
|
||||
title: "[feature] "
|
||||
labels: feature 功能请求
|
||||
---
|
||||
|
||||
- Your feature requesting / 你的新功能请求
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
name: I have feature requesting / 我有功能需求
|
||||
description: 提出新的功能想法 / Share a feature request
|
||||
title: "[feature] "
|
||||
type: Feature
|
||||
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
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
name: Feel free to express / 随便写写
|
||||
about: Record something / 简单写写记录记录
|
||||
---
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
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
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: I have a question / 我有疑问
|
||||
about: Solve your problem / 解决你的疑问
|
||||
title: "[question] "
|
||||
labels: question
|
||||
---
|
||||
|
||||
- Problem Description / 问题描述
|
||||
- 请尽量提供问题相关的截图/日志等内容
|
||||
@@ -0,0 +1,31 @@
|
||||
name: I have a question / 我有疑问
|
||||
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
|
||||
title: "[question] "
|
||||
type: Question
|
||||
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
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: I have suggestions / 我有建议
|
||||
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
|
||||
title: "[suggestion] "
|
||||
labels: suggestion
|
||||
---
|
||||
|
||||
- Your suggestions / 你的建议
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
name: I have suggestions / 我有建议
|
||||
description: 分享对项目的改进建议 / Share an improvement suggestion
|
||||
title: "[suggestion] "
|
||||
type: Suggestions
|
||||
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
|
||||
@@ -0,0 +1,78 @@
|
||||
<!--
|
||||
感谢你的贡献!提交前请先阅读以下说明 / Thanks for contributing! Please read this before submitting:
|
||||
1. 请按模板逐项填写,请勿删除模板中的标题,否则内容无法被正确识别 / Fill in every section and do not delete the headings.
|
||||
2. 未填写关键信息(解决的需求、是否在游戏内实际运行、代码是否纯手工编写)的 PR 可能会被直接关闭 / PRs missing key information may be closed directly.
|
||||
3. 请保持改动聚焦,避免在一次 PR 中混入与需求无关的大规模改动 / Keep the change focused.
|
||||
-->
|
||||
|
||||
## 提交确认 / Checklist
|
||||
|
||||
- [ ] 我已经搜索过现有 Issue 与 PR,确认这不是重复内容 / I have searched existing issues and PRs and confirmed this is not a duplicate
|
||||
- [ ] 我已经阅读过[文档](https://www.bettergi.com/doc.html),确认改动符合项目的使用方式 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed the change matches the project's usage
|
||||
- [ ] 本次改动可以通过 `dotnet build BetterGenshinImpact.sln -c Debug` 编译 / This change compiles with `dotnet build BetterGenshinImpact.sln -c Debug`
|
||||
- [ ] 我理解未经过实际验证的改动,可能被要求补充证据后再合并 / I understand unverified changes may require more evidence before merging
|
||||
|
||||
## 关联 Issue / Related Issue
|
||||
|
||||
<!-- 例:close #1234 / Fixes #1234;没有关联 Issue 可填写“无” / Write "None" if there is no related issue -->
|
||||
|
||||
## 解决的需求 / Problem Solved
|
||||
|
||||
> 请说明这个 PR 要解决什么问题,而不是只描述改了哪些代码 / Explain the problem this PR solves, not just which code was changed.
|
||||
|
||||
**要解决的需求或问题是什么?/ What problem does this PR solve?**
|
||||
|
||||
**在什么场景下会触发或需要它?/ In which scenarios is it needed?**
|
||||
|
||||
**实现方案简述 / Implementation summary**
|
||||
|
||||
## 是否在游戏内实际运行 / Verified In-Game
|
||||
|
||||
> BetterGI 的行为高度依赖真实游戏环境(分辨率、帧率、任务状态、网络延迟等),因此请如实填写本项,以下两项请只勾选一项。/ BetterGI's behavior heavily depends on the real game environment, so please answer this honestly. Check only one of the following.
|
||||
|
||||
- [ ] 已在游戏内实际运行并验证本次改动 / Yes, I actually ran and verified this change in the game
|
||||
- [ ] 未在游戏内实际运行 / No, I have not run it in the game
|
||||
|
||||
**若已在游戏内运行,请补充验证信息 / If yes, please provide details:**
|
||||
|
||||
| 项目 / Item | 内容 / Detail |
|
||||
| --- | --- |
|
||||
| 游戏版本 / Game version | |
|
||||
| 分辨率与窗口模式 / Resolution & window mode | |
|
||||
| 验证的功能或任务 / Verified feature or task | |
|
||||
| 验证次数与运行时长 / Runs & duration | |
|
||||
| 结果 / Result | 符合预期 / 存在问题(请说明) |
|
||||
|
||||
**若未在游戏内运行,请说明原因与替代验证方式(例如仅文档、仅 UI 调整、仅重构、单元测试)/ If not, explain why and what alternative verification was done:**
|
||||
|
||||
## 代码是否纯手工编写 / Hand-Written Code
|
||||
|
||||
> 本项目推荐使用 AI 辅助编写代码,但要求提交者完全理解并验证自己提交的每一行代码,并对最终结果负责。以下三项请只勾选一项。/ AI-assisted coding is recommended, but you must fully understand and verify every line you submit, and you are responsible for the result. Check only one of the following.
|
||||
|
||||
- [ ] 本次代码完全由我手工编写,未使用 AI 生成 / Entirely hand-written, no AI generation
|
||||
- [ ] 部分代码由 AI 辅助生成,我已逐行阅读、理解并验证 / Partly AI-assisted; I have read, understood and verified it line by line
|
||||
- [ ] 本次代码完全由 AI 生成,我已逐行阅读、理解并验证 / Fully AI-generated; I have read, understood and verified it line by line
|
||||
|
||||
**AI 参与的部分及我的验证方式(未使用 AI 请填“无”)/ AI-involved parts and how I verified them (write "None" if no AI was used):**
|
||||
|
||||
**我确认 / I confirm:**
|
||||
|
||||
- [ ] 我理解本次改动的全部逻辑,能够解释每一处修改的原因 / I understand the entire change and can explain every modification
|
||||
- [ ] 提交的代码不包含来源不明、我无法解释的代码片段 / No unexplained code from unknown sources is included
|
||||
|
||||
## 改动类型 / Type of Change
|
||||
|
||||
- [ ] 新功能 / New feature
|
||||
- [ ] 问题修复 / Bug fix
|
||||
- [ ] 重构或性能优化 / Refactor or performance
|
||||
- [ ] 文档或其他杂项 / Docs or chores
|
||||
|
||||
## 影响范围 / Impact
|
||||
|
||||
**涉及的模块或功能 / Affected modules or features:**
|
||||
|
||||
**可能带来的风险、兼容性影响或行为变化 / Potential risks, compatibility impact, or behavior changes:**
|
||||
|
||||
## 补充信息 / Additional Information
|
||||
|
||||
<!-- 截图、录屏、日志、参考链接等,可选 / Screenshots, recordings, logs, references (optional) -->
|
||||
@@ -0,0 +1,252 @@
|
||||
runtime:
|
||||
languageMode: auto
|
||||
dryRun: false
|
||||
|
||||
providers:
|
||||
openAiCompatible:
|
||||
enabled: true
|
||||
baseUrl: https://api.openai.com/v1
|
||||
model: gpt-5.6-luna
|
||||
apiStyle: responses
|
||||
timeoutMs: 30000
|
||||
|
||||
issues:
|
||||
autoProcessing:
|
||||
skipCreatedBefore: auto
|
||||
validation:
|
||||
enabled: true
|
||||
fallbackTemplateKey: normal
|
||||
commentAnchor: issue-bot:validation
|
||||
templates:
|
||||
- key: bug
|
||||
issueType: Bug
|
||||
detect:
|
||||
markers:
|
||||
- bug
|
||||
titlePrefixes:
|
||||
- "[bug]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复问题
|
||||
- 确认文档的内容无法解决我的问题
|
||||
- 我愿意为了解决这个问题尽自己所能
|
||||
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: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: feature
|
||||
issueType: Feature
|
||||
detect:
|
||||
markers:
|
||||
- feature
|
||||
titlePrefixes:
|
||||
- "[feature]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复建议
|
||||
- 我已确认当前版本中尚未提供该功能,或至少没有等价实现
|
||||
- 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好
|
||||
- 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳
|
||||
requiredSections:
|
||||
- id: request
|
||||
aliases:
|
||||
- 功能请求
|
||||
- Feature Request
|
||||
- 需求或建议
|
||||
- id: scenario
|
||||
aliases:
|
||||
- 使用场景
|
||||
- Use Case
|
||||
labels:
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: suggestion
|
||||
issueType: Suggestions
|
||||
detect:
|
||||
markers:
|
||||
- suggestion
|
||||
titlePrefixes:
|
||||
- "[suggestion]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复建议
|
||||
- 确认文档的内容无法解决我的问题或覆盖我的建议
|
||||
requiredSections:
|
||||
- id: suggestion
|
||||
aliases:
|
||||
- 建议内容
|
||||
- Suggestion
|
||||
- id: benefit
|
||||
aliases:
|
||||
- 预期收益
|
||||
- Expected Benefit
|
||||
labels:
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: question
|
||||
issueType: Question
|
||||
detect:
|
||||
markers:
|
||||
- question
|
||||
titlePrefixes:
|
||||
- "[question]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复问题
|
||||
- 确认文档的内容无法解决我的问题
|
||||
requiredSections:
|
||||
- id: question
|
||||
aliases:
|
||||
- 问题描述
|
||||
- Problem Description
|
||||
- id: tried
|
||||
aliases:
|
||||
- 已尝试内容
|
||||
- What I Tried
|
||||
labels:
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: normal
|
||||
detect:
|
||||
markers:
|
||||
- normal
|
||||
titlePrefixes:
|
||||
- "[feedback]"
|
||||
- "[normal]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复反馈
|
||||
- 确认文档的内容无法解决我的问题或覆盖我的反馈
|
||||
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:
|
||||
- 需要更多信息
|
||||
- 重复
|
||||
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
|
||||
issueLink:
|
||||
enabled: true
|
||||
commentAnchor: pull-bot:issue-link
|
||||
appendCloseKeyword: true
|
||||
closeKeywordTemplate: "close #{number}"
|
||||
requireSameRepository: true
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
|
||||
jobs:
|
||||
mirrorchyan_release_note:
|
||||
if: github.repository_owner == 'babalae'
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
|
||||
jobs:
|
||||
mirrorchyan:
|
||||
if: github.repository_owner == 'babalae'
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: 📥 Download release
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
name: Repo Bot
|
||||
run-name: "Repo Bot #${{ github.event.issue.number || github.event.pull_request.number }} - ${{ github.event_name }}/${{ github.event.action }} - @${{ github.actor }}"
|
||||
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- reopened
|
||||
- labeled
|
||||
issue_comment:
|
||||
types:
|
||||
- created
|
||||
- edited
|
||||
# pull_request_target (not pull_request) is required so that pull requests opened from
|
||||
# forks can be labelled/commented. Never check out or execute the pull request head here.
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
|
||||
jobs:
|
||||
repo-bot:
|
||||
if: >-
|
||||
github.event.sender.type != 'Bot' &&
|
||||
(
|
||||
github.event_name != 'issue_comment' ||
|
||||
contains(github.event.comment.body, '/fix') ||
|
||||
contains(github.event.comment.body, '/refresh')
|
||||
)
|
||||
uses: ddaodan/bettergi-github-bot/.github/workflows/repo-bot.yml@v1
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
contents: read
|
||||
secrets:
|
||||
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
|
||||
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
|
||||
with:
|
||||
config-path: .github/repo-bot.yml
|
||||
# pull_request_target: only fetch the configuration from the base branch.
|
||||
# Never check out the pull request head (it would execute untrusted code).
|
||||
checkout-mode: config-only
|
||||
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
|
||||
ai-enabled: ${{ vars.REPO_BOT_AI_ENABLED }}
|
||||
ai-base-url: ${{ vars.REPO_BOT_AI_BASE_URL }}
|
||||
ai-model: ${{ vars.REPO_BOT_AI_MODEL }}
|
||||
ai-api-style: ${{ vars.REPO_BOT_AI_API_STYLE }}
|
||||
ai-timeout-ms: ${{ vars.REPO_BOT_AI_TIMEOUT_MS }}
|
||||
action-ref: v1
|
||||
github-app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
|
||||
+25
-6
@@ -9,6 +9,14 @@
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
Build/
|
||||
!Build/
|
||||
Build/*
|
||||
!Build/BetterGenshinImpact.I18nSync/
|
||||
!Build/BetterGenshinImpact.I18nSync/**
|
||||
!Build/Scripts/
|
||||
Build/Scripts/*
|
||||
!Build/Scripts/i18n-sync.ps1
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
@@ -21,18 +29,29 @@ bld/
|
||||
[Ll]og/
|
||||
|
||||
# Mine
|
||||
Tmp/
|
||||
/Tmp/
|
||||
|
||||
# AI temporary design docs
|
||||
Docs/tmp/*
|
||||
!Docs/tmp/README.md
|
||||
/packages/
|
||||
node_modules/
|
||||
github_actions_cache/
|
||||
|
||||
*.zip
|
||||
|
||||
# IDE & AI tools
|
||||
# Rider
|
||||
.idea
|
||||
.trae
|
||||
.claude
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
|
||||
__pycache__/
|
||||
|
||||
|
||||
# Trae
|
||||
.trae/*
|
||||
!.trae/rules/
|
||||
!.trae/rules/**
|
||||
!.trae/skills/
|
||||
!.trae/skills/**
|
||||
|
||||
# Claude
|
||||
.claude/*
|
||||
@@ -0,0 +1,121 @@
|
||||
本项目使用了 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
|
||||
```
|
||||
|
||||
禁止 新增 BetterGenshinImpact\Assets 目录,这里的资源已经被 BetterGI.Assets.* 的外部资源给占用了。如果要新增资源,需要人工去修改对应 nuget 包的资源。
|
||||
|
||||
## 识别与模拟操作
|
||||
|
||||
在进行键鼠操作后再识图的时候,必须添加适当的延时!因为游戏内对键鼠的响应是有 30~60ms 的延迟的,截图的来源图也是有延迟的。
|
||||
|
||||
键鼠操作本身也不宜过快,在 30 fps 的游戏中,过快的操作可能会丢失。
|
||||
|
||||
## Code Review Rules
|
||||
|
||||
### Output language
|
||||
|
||||
- 必须使用简体中文输出代码审查结果。
|
||||
- 问题标题、问题描述、影响分析和修复建议必须使用中文。
|
||||
- 类名、方法名、变量名、文件路径、代码片段和错误消息保持原文。
|
||||
- 专业术语第一次出现时可以采用“中文(English)”格式。
|
||||
|
||||
### Review priorities
|
||||
|
||||
- 优先检查可能造成崩溃、死锁、资源泄漏和数据竞争的问题。
|
||||
- 重点检查异步任务、CancellationToken、线程切换和 STA UI 线程使用。
|
||||
- 重点检查 Mat、Bitmap、Stream、CancellationTokenSource 等 IDisposable 对象是否正确释放。
|
||||
- 检查游戏输入、截图和多实例场景是否存在共享状态冲突。
|
||||
- 不要只提出风格问题,除非它会影响正确性、可维护性或性能。
|
||||
|
||||
### Finding format
|
||||
|
||||
每个问题按以下结构输出:
|
||||
|
||||
1. 严重程度
|
||||
2. 问题位置
|
||||
3. 问题原因
|
||||
4. 可能造成的影响
|
||||
5. 推荐修复方案
|
||||
@@ -17,6 +17,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{02CEA57F-C
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.UnitTest", "Test\BetterGenshinImpact.UnitTest\BetterGenshinImpact.UnitTest.csproj", "{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{DB7D66B7-B4DA-4A16-8BBF-3DDA83654C53}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.I18nSync", "Build\BetterGenshinImpact.I18nSync\BetterGenshinImpact.I18nSync.csproj", "{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -73,6 +77,14 @@ Global
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.Build.0 = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.ActiveCfg = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.Build.0 = Release|x64
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -80,6 +92,7 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76} = {DB7D66B7-B4DA-4A16-8BBF-3DDA83654C53}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {352D8B78-9DE3-4E58-985F-FADD22594DB4}
|
||||
|
||||
@@ -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,10 +13,20 @@
|
||||
<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" />
|
||||
@@ -25,7 +35,9 @@
|
||||
<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>
|
||||
|
||||
+299
-49
@@ -2,25 +2,38 @@ using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using BetterGenshinImpact.Core.Mask;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Monitor;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Audio;
|
||||
using BetterGenshinImpact.GameTask.Music.Service;
|
||||
using BetterGenshinImpact.GameTask.Runtime;
|
||||
using BetterGenshinImpact.GameTask.Runtime.Win32;
|
||||
using BetterGenshinImpact.GameTask.Runtime.WebPage;
|
||||
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.I18n;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using BetterGenshinImpact.Service.Notifier;
|
||||
using BetterGenshinImpact.View;
|
||||
using BetterGenshinImpact.View.Mask;
|
||||
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;
|
||||
@@ -50,10 +63,9 @@ public partial class App : Application
|
||||
private static readonly IHost _host = Host.CreateDefaultBuilder()
|
||||
.CheckIntegration()
|
||||
.UseElevated()
|
||||
.UseSingleInstance("BetterGI")
|
||||
.UseInstanceIpc()
|
||||
.ConfigureLogging(builder => { builder.ClearProviders(); })
|
||||
.ConfigureServices(
|
||||
(context, services) =>
|
||||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
// 提前初始化配置
|
||||
var configService = new ConfigService();
|
||||
@@ -63,52 +75,90 @@ 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;
|
||||
// 网页版实例带上实例名,例如 WebView(小号A):S1:P1234:T…
|
||||
var instanceTypeLabel = instanceContext.InstanceName is { } instanceName
|
||||
? $"{instanceContext.InstanceType}({instanceName})"
|
||||
: instanceContext.InstanceType.ToString();
|
||||
var instanceIdentity =
|
||||
$"{instanceTypeLabel}:S{instanceContext.WindowsSessionId}:P{instanceContext.ProcessId}:T{instanceContext.StartedAt.ToUnixTimeMilliseconds()}";
|
||||
|
||||
var richTextBox = new RichTextBoxImpl();
|
||||
services.AddSingleton<IRichTextBox>(richTextBox);
|
||||
|
||||
var loggerConfiguration = new LoggerConfiguration()
|
||||
.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:
|
||||
.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:
|
||||
"[{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.MaskEnabled)
|
||||
{
|
||||
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
}
|
||||
// 日志遮罩输出:仅当“遮罩启用且日志框可见”时才真正写入,隐藏时避免不必要的 UI 开销(#3161)。
|
||||
// 条件改为运行时每次写入时动态判断,因此启动后通过快捷键切换 ShowLogBox 也能即时恢复日志(#3357)。
|
||||
loggerConfiguration.WriteTo.Sink(
|
||||
new ConditionalLogEventSink(
|
||||
new LoggerConfiguration()
|
||||
.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.CreateLogger(),
|
||||
() => all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true }),
|
||||
LogEventLevel.Information);
|
||||
|
||||
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>();
|
||||
// });
|
||||
// }
|
||||
|
||||
// 配置和日志已经就绪,在任何推理服务或会话初始化前选定原生运行库。
|
||||
all.HardwareAccelerationConfig ??= new();
|
||||
var inferenceStartupStatus = InferenceRuntimeService.PrepareStartup(all.HardwareAccelerationConfig, InstanceBootstrap.Current.Context.IsRoot);
|
||||
// 只规范配置并绑定运行库;待验证状态在主窗口实际开始验证时才落盘。
|
||||
configService.Save();
|
||||
services.AddSingleton(inferenceStartupStatus);
|
||||
var onnxRuntimeLoader = new OnnxRuntimeLoader(all.HardwareAccelerationConfig, AppContext.BaseDirectory);
|
||||
services.AddSingleton(onnxRuntimeLoader);
|
||||
services.AddSingleton<IOnnxRuntimeSelection>(onnxRuntimeLoader);
|
||||
var onnxRuntimeInstaller = new OnnxRuntimeInstaller(AppContext.BaseDirectory);
|
||||
services.AddSingleton(onnxRuntimeInstaller);
|
||||
services.AddSingleton<IOnnxRuntimeInstaller>(onnxRuntimeInstaller);
|
||||
services.AddSingleton<IInferenceDeviceDiscovery, InferenceDeviceDiscovery>();
|
||||
services.AddSingleton<IInferenceBenchmarkLeaseProvider>(sp => new InferenceBenchmarkCoordinator(
|
||||
BetterGenshinImpact.GameTask.Common.TaskControl.TaskSemaphore,
|
||||
() => sp.GetRequiredService<TaskTriggerDispatcher>().PauseForInference()));
|
||||
services.AddSingleton<InferenceModelDiagnostics>();
|
||||
services.AddSingleton<IInferenceModelDiagnostics>(sp => sp.GetRequiredService<InferenceModelDiagnostics>());
|
||||
services.AddSingleton<InferenceRuntimeService>();
|
||||
services.AddSingleton<HardwareAccelerationViewModelFactory>();
|
||||
services.AddSingleton<IInferenceSettingsInteraction, InferenceSettingsInteraction>();
|
||||
|
||||
services.AddLocalization();
|
||||
var i18nService = I18nService.Instance;
|
||||
var uiLanguage = all.OtherConfig.UiCultureInfoName switch
|
||||
{
|
||||
"zh-CN" => "zh-Hans",
|
||||
"en-US" => "en",
|
||||
"ja-JP" => "ja",
|
||||
_ => all.OtherConfig.UiCultureInfoName,
|
||||
};
|
||||
if (uiLanguage != all.OtherConfig.UiCultureInfoName)
|
||||
{
|
||||
all.OtherConfig.UiCultureInfoName = uiLanguage;
|
||||
configService.Save();
|
||||
}
|
||||
|
||||
i18nService.ChangeLanguage(uiLanguage);
|
||||
services.AddSingleton(i18nService);
|
||||
|
||||
services.AddNavigationViewPageProvider();
|
||||
services.AddSingleton(InstanceBootstrap.Current);
|
||||
services.AddSingleton<InstanceService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<InstanceService>());
|
||||
// App Host
|
||||
services.AddHostedService<ApplicationHostService>();
|
||||
// Page resolver service
|
||||
@@ -122,6 +172,9 @@ 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>();
|
||||
@@ -136,7 +189,10 @@ public partial class App : Application
|
||||
services.AddView<JsListPage, JsListViewModel>();
|
||||
services.AddView<MapPathingPage, MapPathingViewModel>();
|
||||
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
|
||||
services.AddView<MusicPage, MusicPageViewModel>();
|
||||
services.AddSingleton<PathingConfigViewModel>();
|
||||
services.AddSingleton<IBannerImageService, BannerImageService>();
|
||||
services.AddTransient<WebImageInputViewModel>();
|
||||
// services.AddView<PathingConfigView, PathingConfigViewModel>();
|
||||
services.AddView<KeyBindingsSettingsPage, KeyBindingsSettingsPageViewModel>();
|
||||
|
||||
@@ -152,12 +208,53 @@ 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>();
|
||||
|
||||
// 遮罩窗口:业务侧只依赖 IMaskWindowDrawingBoard / IMaskWindowHost / IMaskWindowMapState
|
||||
services.AddSingleton<MaskWindowDrawingBoard>();
|
||||
services.AddSingleton<IMaskWindowDrawingBoard>(sp => sp.GetRequiredService<MaskWindowDrawingBoard>());
|
||||
services.AddSingleton<IMaskWindowSnapshotSource<MaskWindowDrawingSnapshot>>(sp => sp.GetRequiredService<MaskWindowDrawingBoard>());
|
||||
services.AddSingleton<MaskWindowMapState>();
|
||||
services.AddSingleton<IMaskWindowMapState>(sp => sp.GetRequiredService<MaskWindowMapState>());
|
||||
services.AddSingleton<IMaskWindowSnapshotSource<MaskWindowMapSnapshot>>(sp => sp.GetRequiredService<MaskWindowMapState>());
|
||||
services.AddSingleton<MaskWindowViewModel>();
|
||||
services.AddTransient<MaskWindow>();
|
||||
services.AddSingleton<Func<MaskWindow>>(sp => () => sp.GetRequiredService<MaskWindow>());
|
||||
services.AddSingleton<IMaskWindowHost, MaskWindowHost>();
|
||||
services.AddSingleton<DialogueOptionVoiceDiagnosticState>();
|
||||
services.AddSingleton<DialogueOptionVoiceDiagnosticService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DialogueOptionVoiceDiagnosticService>());
|
||||
services.AddSingleton<TaskTriggerDispatcher>();
|
||||
// 游戏运行环境:按实例类型选定 Provider,见 Docs/design/game-runtime.md
|
||||
services.AddSingleton<Win32RuntimeProvider>();
|
||||
services.AddSingleton<IGameRuntimeProvider>(sp => sp.GetRequiredService<Win32RuntimeProvider>());
|
||||
services.AddSingleton<IGameRuntimeProvider, WebPageRuntimeProvider>();
|
||||
services.AddTransient<CloudWebHostWindow>();
|
||||
services.AddSingleton<Func<CloudWebHostWindow>>(sp => () => sp.GetRequiredService<CloudWebHostWindow>());
|
||||
services.AddSingleton<GameRuntimeService>();
|
||||
// 云原神网页版实例:实例名存储与启动器(Primary 首页使用)
|
||||
services.AddSingleton<WebViewInstanceStore>();
|
||||
services.AddSingleton<WebViewInstanceLauncher>();
|
||||
services.AddSingleton<RecognitionTemplateAssetService>();
|
||||
services.AddSingleton<RecognitionTemplateEditorService>();
|
||||
services.AddSingleton<NotificationService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
|
||||
services.AddSingleton<NotifierManager>();
|
||||
services.AddSingleton<IScriptService, ScriptService>();
|
||||
services.AddSingleton<HutaoNamedPipe>();
|
||||
services.AddSingleton<IMusicScoreParser, MusicScoreParser>();
|
||||
services.AddSingleton<IMusicStateStore, MusicStateStore>();
|
||||
services.AddSingleton<IInstrumentProfileService, InstrumentProfileService>();
|
||||
services.AddSingleton<IMusicTimelineBuilder, MusicTimelineBuilder>();
|
||||
services.AddSingleton<IMusicLibraryService, MusicLibraryService>();
|
||||
services.AddSingleton<IMusicCoverService, MusicCoverService>();
|
||||
services.AddSingleton<IMusicInstrumentSwitcher, MusicInstrumentSwitcher>();
|
||||
services.AddSingleton<IKeyInputTransport, PostMessageKeyInputTransport>();
|
||||
services.AddSingleton<IKeyInputTransport, SendInputKeyInputTransport>();
|
||||
services.AddSingleton<IMusicPlaybackService, MusicPlaybackService>();
|
||||
services.AddSingleton<BgiOnnxFactory>();
|
||||
services.AddSingleton<OcrFactory>();
|
||||
services.AddMemoryCache();
|
||||
@@ -165,14 +262,15 @@ 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
|
||||
}
|
||||
)
|
||||
@@ -210,6 +308,7 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
protected override async void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
|
||||
// Wine 平台适配
|
||||
WinePlatformAddon.ApplyApplicationConfig();
|
||||
base.OnStartup(e);
|
||||
@@ -219,21 +318,57 @@ public partial class App : Application
|
||||
// 分配控制台窗口以支持控制台输出
|
||||
ConsoleHelper.AllocateConsole("BetterGI Console");
|
||||
RegisterEvents();
|
||||
var inferenceRuntime = _host.Services.GetRequiredService<InferenceRuntimeService>();
|
||||
// 此处只准备设备配置;模型验证和提示由主实例的 MainWindowViewModel.OnLoaded 执行。
|
||||
await inferenceRuntime.InitializeAsync();
|
||||
await _host.StartAsync();
|
||||
ServerTimeHelper.Initialize(_host.Services.GetRequiredService<IServerTimeProvider>());
|
||||
await UrlProtocolHelper.RegisterAsync();
|
||||
if (InstanceBootstrap.Current.Context.IsRoot)
|
||||
{
|
||||
await UrlProtocolHelper.RegisterAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// DEBUG only, no overhead
|
||||
Debug.WriteLine(ex);
|
||||
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
|
||||
|
||||
if (Debugger.IsAttached)
|
||||
var dialogShown = false;
|
||||
try
|
||||
{
|
||||
Debugger.Break();
|
||||
// 启动失败发生在 MainWindow 创建前,日志遮罩可能不可用;
|
||||
// 视为致命异常,记录日志并尝试弹窗。
|
||||
dialogShown = HandleException(ex, isTerminating: true);
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
Debug.WriteLine(ex2);
|
||||
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
|
||||
}
|
||||
|
||||
// 启动早期 WPF Dispatcher 可能尚未就绪,HandleException 可能因此不弹窗。
|
||||
// 仅在未显示 WPF 弹窗时,用不依赖 WPF 的 WinForms MessageBox 兜底,
|
||||
// 避免用户连续看到两个错误对话框。
|
||||
if (!dialogShown)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Windows.Forms.MessageBox.Show(
|
||||
$"应用程序启动失败:{ex.Message}",
|
||||
"BetterGI 启动失败",
|
||||
System.Windows.Forms.MessageBoxButtons.OK,
|
||||
System.Windows.Forms.MessageBoxIcon.Error);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 弹窗失败不影响退出。
|
||||
}
|
||||
}
|
||||
|
||||
// 启动失败 = 无可用的主界面,直接退出,避免留下无窗口的残留进程。
|
||||
Shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -244,12 +379,26 @@ public partial class App : Application
|
||||
base.OnExit(e);
|
||||
|
||||
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
|
||||
|
||||
|
||||
// 写入防抖窗口内尚未落盘的配置改动
|
||||
try
|
||||
{
|
||||
_host.Services.GetService<IConfigService>()?.Flush();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex);
|
||||
}
|
||||
|
||||
TempManager.CleanUp();
|
||||
|
||||
await _host.Services.GetRequiredService<InferenceRuntimeService>().StopAsync();
|
||||
await _host.Services.GetRequiredService<OnnxRuntimeInstaller>().StopAsync();
|
||||
await _host.Services.GetRequiredService<InferenceModelDiagnostics>().StopAsync();
|
||||
await _host.StopAsync();
|
||||
_host.Dispose();
|
||||
|
||||
Log.CloseAndFlush();
|
||||
|
||||
// 释放控制台窗口
|
||||
ConsoleHelper.FreeConsoleWindow();
|
||||
}
|
||||
@@ -273,6 +422,12 @@ public partial class App : Application
|
||||
{
|
||||
try
|
||||
{
|
||||
// 忽略V8引擎释放后pending的Task回调抛出的异常
|
||||
if (IsV8EngineReleasedException(e.Exception))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
HandleException(e.Exception);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -285,6 +440,21 @@ 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)
|
||||
{
|
||||
@@ -292,12 +462,13 @@ public partial class App : Application
|
||||
{
|
||||
if (e.ExceptionObject is Exception exception)
|
||||
{
|
||||
HandleException(exception);
|
||||
// 用官方的 IsTerminating 判断是否致命:致命异常进程将终止,需同步弹窗确保用户可见。
|
||||
HandleException(exception, isTerminating: e.IsTerminating);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleException(ex);
|
||||
HandleException(ex, isTerminating: e.IsTerminating);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -323,13 +494,95 @@ public partial class App : Application
|
||||
}
|
||||
}
|
||||
|
||||
private static void HandleException(Exception e)
|
||||
/// <summary>
|
||||
/// 处理未处理异常。返回 true 表示已尝试显示弹窗(或已处理),false 表示未弹窗(Dispatcher 不可用)。
|
||||
/// </summary>
|
||||
private static bool HandleException(Exception e, bool isTerminating = false)
|
||||
{
|
||||
if (e.InnerException != null)
|
||||
{
|
||||
e = e.InnerException;
|
||||
}
|
||||
|
||||
// 错误日志最先落盘并推送到日志遮罩(LogError ≥ Information 会进入遮罩 LogTextBox)。
|
||||
// 文件日志:Debug 级别也写盘;遮罩:仅 Information 以上可见。
|
||||
// 致命异常(IsTerminating)在日志末尾加 [FATAL] 标记,便于区分。
|
||||
var logMessage = isTerminating ? "UnHandle Exception [FATAL]" : "UnHandle Exception";
|
||||
GetLogger<App>().LogError(e, logMessage);
|
||||
|
||||
// 可恢复异常(默认):仅日志,不弹模态窗,避免阻塞 UI 线程。
|
||||
// 通过日志遮罩提示用户:非致命异常已记录。
|
||||
if (!isTerminating)
|
||||
{
|
||||
const string nonFatalMessage = "发生非致命异常,已记录日志,请查看日志详情。";
|
||||
GetLogger<App>().LogWarning(nonFatalMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 终止性异常(如线程池未处理异常导致进程即将结束):进程终止前同步弹窗兜底,
|
||||
// 确保用户能看到报告(阻塞无妨,进程反正要终止)。
|
||||
var dispatcher = Application.Current?.Dispatcher;
|
||||
if (dispatcher is null
|
||||
|| dispatcher.HasShutdownStarted
|
||||
|| dispatcher.HasShutdownFinished)
|
||||
{
|
||||
// Dispatcher 不可用(如启动早期或已关闭):仅日志,不弹窗。
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确认 Dispatcher 可用后才记录"正在弹窗",避免与实际行为不一致。
|
||||
const string popupShownMessage = "发生致命异常,正在弹窗提示,同时已记录日志。";
|
||||
GetLogger<App>().LogWarning(popupShownMessage);
|
||||
|
||||
try
|
||||
{
|
||||
if (dispatcher.CheckAccess())
|
||||
{
|
||||
ShowExceptionDialog(e);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 双信号:startedSignal 表示 UI 线程开始执行弹窗(有限超时),
|
||||
// completedSignal 表示弹窗已关闭(无超时等待)。
|
||||
// ShowExceptionDialog 是模态的,用户读完并关闭才返回;
|
||||
// 若只在"开始"后立即返回,进程终止会强杀刚创建的弹窗。
|
||||
using var startedSignal = new System.Threading.ManualResetEventSlim(false);
|
||||
using var completedSignal = new System.Threading.ManualResetEventSlim(false);
|
||||
dispatcher.InvokeAsync(new Action(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
startedSignal.Set();
|
||||
ShowExceptionDialog(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
completedSignal.Set();
|
||||
}
|
||||
}));
|
||||
|
||||
// 只为"UI 是否开始执行"设置超时:UI 线程被阻塞/死锁时避免无限等待。
|
||||
if (!startedSignal.Wait(TimeSpan.FromSeconds(3)))
|
||||
{
|
||||
GetLogger<App>().LogWarning("弹窗调度超时,异常已记录,进程即将退出。");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 一旦确认开始执行,就等待弹窗关闭,确保用户能读完致命异常详情。
|
||||
completedSignal.Wait();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 弹窗失败不影响进程退出。
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ShowExceptionDialog(Exception e)
|
||||
{
|
||||
try
|
||||
{
|
||||
ExceptionReport.Show(e);
|
||||
@@ -347,8 +600,5 @@ public partial class App : Application
|
||||
"""
|
||||
);
|
||||
}
|
||||
|
||||
// log
|
||||
GetLogger<App>().LogDebug(e, "UnHandle Exception");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: DisableDpiAwareness]
|
||||
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
|
||||
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
|
||||
[assembly: InternalsVisibleTo("BetterGenshinImpact.UnitTest")]
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.58.0</Version>
|
||||
<Version>0.66.2-alpha.4</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
@@ -38,24 +38,40 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 云原神网页版输入 SDK,由 WebView2InputBridge.InstallAsync 读取并注入页面 -->
|
||||
<None Remove="Resources\JavaScript\ys-input-inject.js" />
|
||||
<EmbeddedResource Include="Resources\JavaScript\ys-input-inject.js" LogicalName="BetterGenshinImpact.Resources.JavaScript.ys-input-inject.js" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Anthropic 官方 SDK:自动连招在 OpenAI 兼容端点之外可选的原生 Messages API 提供方 -->
|
||||
<PackageReference Include="Anthropic" Version="12.53.0" />
|
||||
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.1.120" />
|
||||
<PackageReference Include="BehaviourTree" Version="1.0.73" />
|
||||
|
||||
|
||||
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.19" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.13" />
|
||||
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.24" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.38" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.27" />
|
||||
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="Clipper2" Version="2.0.0" />
|
||||
<PackageReference Include="CsTrees" Version="1.0.5" />
|
||||
<PackageReference Include="CsTrees.MEAI" Version="1.0.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="MailKit" Version="4.14.0" />
|
||||
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.6" />
|
||||
<PackageReference Include="MailKit" Version="4.16.0" />
|
||||
<PackageReference Include="Markdig" Version="1.3.2" />
|
||||
<PackageReference Include="Melanchall.DryWetMidi" Version="8.0.3" />
|
||||
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
|
||||
@@ -67,9 +83,9 @@
|
||||
<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.14.0" />
|
||||
<PackageReference Include="MimeKit" Version="4.16.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenccNetLib" Version="1.7.0" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||
@@ -77,25 +93,24 @@
|
||||
<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" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.1" />
|
||||
<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.0" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
|
||||
<PackageReference Include="TorchSharp" Version="0.105.0" />
|
||||
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
|
||||
<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.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="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.15" />
|
||||
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
@@ -111,6 +126,9 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="GameTask\**\Recognition.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -126,7 +144,10 @@
|
||||
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
|
||||
<None Update="GameTask\CharacterDevelopment\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
|
||||
@@ -147,7 +168,7 @@
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\hangout.json">
|
||||
<None Update="GameTask\AutoSkip\Assets\*.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoTrackPath\Assets\tp.json">
|
||||
@@ -156,6 +177,9 @@
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Job\SwitchCharacter\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\Json\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -165,6 +189,9 @@
|
||||
<None Update="GameTask\AutoMusicGame\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Music\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\GameLoading\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -180,6 +207,9 @@
|
||||
<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>
|
||||
@@ -201,7 +231,10 @@
|
||||
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\I18n\en.json">
|
||||
<None Update="GameTask\AutoBoss\Assets\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\I18n\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
@@ -242,5 +275,21 @@
|
||||
<ItemGroup>
|
||||
<_DeploymentManifestIconFile Remove="Resources\Images\logo.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<!--
|
||||
Melanchall.DryWetMidi 的 build\Melanchall.DryWetMidi.targets 会无条件把 x86/x64/macOS
|
||||
三份本地库都复制到输出目录(它没有使用 runtimes/{rid}/native 结构,不感知 RID)。
|
||||
本项目只支持 win-x64,这里在 AssignTargetPaths 之前把多余的 Native32.dll(x86)
|
||||
和 Native64.dylib(macOS)从 None 项中移除,避免它们被打进 Release 产物。
|
||||
-->
|
||||
<Target Name="RemoveDryWetMidiUnusedNativeLibs" BeforeTargets="AssignTargetPaths">
|
||||
<ItemGroup>
|
||||
<None Remove="@(None)" Condition="'%(Filename)' == 'Melanchall_DryWetMidi_Native32' Or ('%(Filename)' == 'Melanchall_DryWetMidi_Native64' And '%(Extension)' == '.dylib')" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<!-- 古树测试样例用于推理运行库验证与设置页测速。 -->
|
||||
<ItemGroup>
|
||||
<None Update="Assets\Model\Domain\test_petrified_trees.jpg" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,592 @@
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
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.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 => InputHub.Foreground.Keyboard.KeyPress(key),
|
||||
LeftClick = GameCaptureRegion.GameRegion1080PPosClick,
|
||||
RightClick = (x, y) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(x, y);
|
||||
InputHub.Foreground.Mouse.RightButtonClick();
|
||||
},
|
||||
MiddleClick = (x, y) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(x, y);
|
||||
InputHub.Foreground.Mouse.MiddleButtonClick();
|
||||
},
|
||||
MoveTo = GameCaptureRegion.GameRegion1080PPosMove,
|
||||
Drag = async (fromX, fromY, toX, toY, duration) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(fromX, fromY);
|
||||
InputHub.Foreground.Mouse.LeftButtonDown();
|
||||
try
|
||||
{
|
||||
var firstDelay = duration / 2;
|
||||
await page.Wait(firstDelay);
|
||||
GameCaptureRegion.GameRegion1080PPosMove(toX, toY);
|
||||
await page.Wait(duration - firstDelay);
|
||||
}
|
||||
finally
|
||||
{
|
||||
InputHub.Foreground.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
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,19 +21,38 @@ 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 Action<List<Region>>? RetryAction { get; set; }
|
||||
public Func<List<Region>, Task>? 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>
|
||||
@@ -45,7 +64,11 @@ 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);
|
||||
@@ -59,12 +82,7 @@ public class BvLocator
|
||||
else if (RecognitionObject.RecognitionType == RecognitionTypes.Ocr)
|
||||
{
|
||||
var results = screen.FindMulti(RecognitionObject);
|
||||
if (!string.IsNullOrEmpty(RecognitionObject.Text))
|
||||
{
|
||||
return results.FindAll(r => r.Text.Contains(RecognitionObject.Text));
|
||||
}
|
||||
|
||||
return results;
|
||||
return FilterOcrResults(results, _anyTexts, RecognitionObject.Text);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -72,6 +90,22 @@ 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;
|
||||
@@ -85,7 +119,7 @@ public class BvLocator
|
||||
public async Task<Region> ClickUntilDisappears(int? timeout = null)
|
||||
{
|
||||
var region = (await WaitFor(timeout)).First().Click();
|
||||
await new BvLocator(RecognitionObject, _cancellationToken)
|
||||
await Clone()
|
||||
.WithRetryAction(resList => { resList.First().Click(); }).WaitForDisappear();
|
||||
return region;
|
||||
}
|
||||
@@ -98,17 +132,21 @@ public class BvLocator
|
||||
|
||||
public async Task<List<Region>> WaitFor(int? timeout = null)
|
||||
{
|
||||
var actualTimeout = timeout ?? DefaultTimeout;
|
||||
var retryCount = actualTimeout / DefaultRetryInterval;
|
||||
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
|
||||
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
|
||||
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
|
||||
|
||||
List<Region> results = [];
|
||||
var retryRes = await NewRetry.WaitForAction(() =>
|
||||
var retryRes = await NewRetry.WaitForAction(async () =>
|
||||
{
|
||||
results = FindAll();
|
||||
var b = results.Count > 0;
|
||||
RetryAction?.Invoke(results);
|
||||
if (!b && RetryAction != null)
|
||||
{
|
||||
await RetryAction(results);
|
||||
}
|
||||
return b;
|
||||
}, _cancellationToken, retryCount, DefaultRetryInterval);
|
||||
}, _cancellationToken, retryCount, actualRetryInterval);
|
||||
|
||||
if (retryRes)
|
||||
{
|
||||
@@ -124,6 +162,12 @@ 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)
|
||||
@@ -150,20 +194,21 @@ public class BvLocator
|
||||
|
||||
public async Task WaitForDisappear(int? timeout = null)
|
||||
{
|
||||
var actualTimeout = timeout ?? DefaultTimeout;
|
||||
var retryCount = actualTimeout / DefaultRetryInterval;
|
||||
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
|
||||
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
|
||||
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
|
||||
|
||||
var retryRes = await NewRetry.WaitForAction(() =>
|
||||
var retryRes = await NewRetry.WaitForAction(async () =>
|
||||
{
|
||||
var results = FindAll();
|
||||
var b = results.Count == 0;
|
||||
if (!b)
|
||||
if (!b && RetryAction != null)
|
||||
{
|
||||
RetryAction?.Invoke(results);
|
||||
await RetryAction(results);
|
||||
}
|
||||
|
||||
return b;
|
||||
}, _cancellationToken, retryCount, DefaultRetryInterval);
|
||||
}, _cancellationToken, retryCount, actualRetryInterval);
|
||||
|
||||
if (!retryRes)
|
||||
{
|
||||
@@ -205,7 +250,77 @@ public class BvLocator
|
||||
|
||||
public BvLocator WithRetryAction(Action<List<Region>>? action)
|
||||
{
|
||||
RetryAction = action;
|
||||
if (action == null)
|
||||
{
|
||||
RetryAction = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
RetryAction = (results) =>
|
||||
{
|
||||
action(results);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
}
|
||||
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,13 +1,14 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
@@ -18,9 +19,9 @@ public class BvPage
|
||||
private static readonly ILogger Logger = App.GetLogger<BvPage>();
|
||||
private readonly CancellationToken _cancellationToken;
|
||||
|
||||
public IKeyboardSimulator Keyboard => Simulation.SendInput.Keyboard;
|
||||
public IKeyboardInput Keyboard => InputHub.Foreground.Keyboard;
|
||||
|
||||
public IMouseSimulator Mouse => Simulation.SendInput.Mouse;
|
||||
public IMouseInput Mouse => InputHub.Foreground.Mouse;
|
||||
|
||||
/// <summary>
|
||||
/// Default timeout for operations in milliseconds
|
||||
@@ -37,6 +38,11 @@ public class BvPage
|
||||
_cancellationToken = cancellationToken;
|
||||
}
|
||||
|
||||
public BvFlow Flow()
|
||||
{
|
||||
return new BvFlow(this, DefaultTimeout, DefaultRetryInterval);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 截图
|
||||
/// </summary>
|
||||
@@ -57,6 +63,14 @@ public class BvPage
|
||||
return this;
|
||||
}
|
||||
|
||||
internal void ThrowIfCancellationRequested()
|
||||
{
|
||||
if (_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new NormalEndException("取消自动任务");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定位图片位置
|
||||
/// </summary>
|
||||
@@ -99,6 +113,22 @@ 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);
|
||||
@@ -121,55 +151,30 @@ public class BvPage
|
||||
GameCaptureRegion.GameRegion1080PPosClick(x, y);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用模糊匹配判断截图中是否包含目标文字。
|
||||
/// 通过 <see cref="OcrFactory.PaddleMatch"/> 自动选择最佳实现(DP 模糊匹配或普通 OCR + 字符串比较)。
|
||||
/// </summary>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <param name="rect">感兴趣区域,default 表示全屏</param>
|
||||
/// <param name="threshold">匹配阈值 (0~1),null 使用配置中的默认阈值</param>
|
||||
/// <returns>是否匹配成功</returns>
|
||||
public bool OcrMatch(string target, Rect rect = default, double? threshold = null)
|
||||
internal static List<T> ParseCollection<T>(object values, string paramName)
|
||||
{
|
||||
var matchService = OcrFactory.PaddleMatch;
|
||||
var actualThreshold = threshold
|
||||
?? TaskContext.Instance().Config.OtherConfig.OcrConfig.OcrMatchDefaultThreshold;
|
||||
|
||||
var screen = TaskControl.CaptureToRectArea();
|
||||
try
|
||||
ArgumentNullException.ThrowIfNull(values, paramName);
|
||||
if (values is string || values is not IEnumerable enumerable)
|
||||
{
|
||||
var roi = rect == default ? null : screen.DeriveCrop(rect);
|
||||
try
|
||||
{
|
||||
var score = matchService.OcrMatch((roi ?? screen).SrcMat, target);
|
||||
return score >= actualThreshold;
|
||||
}
|
||||
finally
|
||||
{
|
||||
roi?.Dispose();
|
||||
}
|
||||
throw new ArgumentException($"{paramName} 必须是集合或 JS Array", paramName);
|
||||
}
|
||||
finally
|
||||
|
||||
List<T> result = [];
|
||||
foreach (var value in enumerable)
|
||||
{
|
||||
screen.Dispose();
|
||||
if (value is not T typedValue)
|
||||
{
|
||||
throw new ArgumentException($"{paramName} 中的每个元素都必须是 {typeof(T).Name}", paramName);
|
||||
}
|
||||
|
||||
result.Add(typedValue);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重复截图并使用模糊匹配,等待目标文字出现。
|
||||
/// 超时返回 false 而非抛异常。
|
||||
/// </summary>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <param name="rect">感兴趣区域,default 表示全屏</param>
|
||||
/// <param name="threshold">匹配阈值 (0~1),null 使用配置中的默认阈值</param>
|
||||
/// <param name="timeout">超时时间(毫秒),null 使用 DefaultTimeout</param>
|
||||
/// <returns>是否在超时前匹配成功</returns>
|
||||
public async Task<bool> WaitForOcrMatch(string target, Rect rect = default, double? threshold = null, int? timeout = null)
|
||||
{
|
||||
var actualTimeout = timeout ?? DefaultTimeout;
|
||||
var retryCount = DefaultRetryInterval > 0 ? actualTimeout / DefaultRetryInterval : 1;
|
||||
if (result.Count == 0)
|
||||
{
|
||||
throw new ArgumentException($"{paramName} 不能为空", paramName);
|
||||
}
|
||||
|
||||
return await NewRetry.WaitForAction(() => OcrMatch(target, rect, threshold),
|
||||
_cancellationToken, retryCount, DefaultRetryInterval);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoBoss;
|
||||
using BetterGenshinImpact.GameTask.AutoCombo.ComboBuild;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
@@ -23,6 +24,7 @@ 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;
|
||||
@@ -59,6 +61,20 @@ public partial class AllConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _triggerInterval = 50;
|
||||
|
||||
/// <summary>
|
||||
/// WGC V2 帧率上限(毫秒,即最小更新间隔,限制 DWM 推帧频率以降低 GPU 占用)
|
||||
/// 0 = 不启用限流(默认);仅 Windows 11 24H2 及以上系统生效
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _wgcMinUpdateIntervalMs;
|
||||
|
||||
/// <summary>
|
||||
/// WGC V2 使用 CPU 颜色转换(BGRA→BGR 由 CPU CvtColor 完成)
|
||||
/// 默认关闭 = GPU compute shader 打包 BGR24(回读量更小、CPU 零转换);重启捕获后生效
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _wgcV2UseCpuConvert;
|
||||
|
||||
// /// <summary>
|
||||
// /// WGC使用位图缓存
|
||||
// /// 高帧率情况下,可能会导致卡顿
|
||||
@@ -82,6 +98,12 @@ public partial class AllConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private List<ValueTuple<string, int, string, string>> _nextScheduledTask = [];
|
||||
|
||||
/// <summary>
|
||||
/// 禁用键鼠监听,需重启
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _disableInputMonitor = false;
|
||||
|
||||
/// <summary>
|
||||
/// 连续执行任务时,从此任务开始执行
|
||||
/// </summary>
|
||||
@@ -124,16 +146,16 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public AutoFishingConfig AutoFishingConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动连招配置
|
||||
/// </summary>
|
||||
public AutoComboBuildConfig AutoComboBuildConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 快速传送配置
|
||||
/// </summary>
|
||||
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动烹饪配置
|
||||
/// </summary>
|
||||
public AutoCookConfig AutoCookConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动打牌配置
|
||||
/// </summary>
|
||||
@@ -158,6 +180,11 @@ public partial class AllConfig : ObservableObject
|
||||
/// 自动秘境配置
|
||||
/// </summary>
|
||||
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动首领讨伐配置
|
||||
/// </summary>
|
||||
public AutoBossConfig AutoBossConfig { get; set; } = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -179,6 +206,8 @@ public partial class AllConfig : ObservableObject
|
||||
/// 自动地脉花配置
|
||||
/// </summary>
|
||||
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
|
||||
|
||||
public AutoCookConfig AutoCookConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 地图遮罩
|
||||
@@ -207,6 +236,11 @@ public partial class AllConfig : ObservableObject
|
||||
|
||||
public RecordConfig RecordConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 原琴演奏配置
|
||||
/// </summary>
|
||||
public MusicConfig MusicConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 脚本配置
|
||||
/// </summary>
|
||||
@@ -253,46 +287,43 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public HardwareAccelerationConfig HardwareAccelerationConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身配置
|
||||
/// </summary>
|
||||
public ChildSessionConfig ChildSessionConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 任意配置项变更后的回调(由 ConfigService 设置为防抖保存)
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
private ConfigChangeTracker? _changeTracker;
|
||||
|
||||
/// <summary>
|
||||
/// 开始追踪整个配置对象图的变更(含嵌套对象与集合),重复调用无副作用
|
||||
/// </summary>
|
||||
public void InitEvent()
|
||||
{
|
||||
PropertyChanged += OnAnyPropertyChanged;
|
||||
MaskWindowConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
CommonConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
if (_changeTracker != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
|
||||
KeyBindingsConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoStygianOnslaughtConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
TpConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
DevConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
_changeTracker = new ConfigChangeTracker(OnConfigChanged);
|
||||
_changeTracker.Track(this);
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
/// <param name="sender">触发变更的对象(某个子配置、嵌套对象或集合)</param>
|
||||
private void OnConfigChanged(object sender)
|
||||
{
|
||||
GameTaskManager.RefreshTriggerConfigs();
|
||||
// 实时触发器每帧读取配置,不需要在这里通知;只有切换遮罩显示相关的开关时清掉旧的识别结果
|
||||
if (sender is MaskWindowConfig)
|
||||
{
|
||||
TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.ClearAll();
|
||||
}
|
||||
|
||||
OnAnyChangedAction?.Invoke();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class ChildSessionConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 桌面分身普通窗口模式的位置(物理像素坐标)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private WindowPositionConfig? _normalWindowPosition;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身小窗模式的位置(物理像素坐标)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private WindowPositionConfig? _smallWindowPosition;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身的 RDP 音频是否静音,不影响主桌面的其他程序。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _audioMuted = false;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身是否处于观看模式。开启后键鼠不会在桌面分身内生效,仅显示画面。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _watchModeEnabled = false;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class WindowPositionConfig
|
||||
{
|
||||
public int Left { get; set; }
|
||||
|
||||
public int Top { get; set; }
|
||||
|
||||
public WindowPositionConfig()
|
||||
{
|
||||
}
|
||||
|
||||
public WindowPositionConfig(int left, int top)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Media;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -38,6 +39,12 @@ public partial class CommonConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool _screenshotUidCoverEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否保存奖励识别调试截图
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _rewardRecognitionScreenshotEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 退出时最小化至托盘
|
||||
/// </summary>
|
||||
@@ -56,6 +63,30 @@ public partial class CommonConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private WindowBackdropType _currentBackdropType = WindowBackdropType.Mica;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用主窗口自定义背景图
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _mainBackgroundEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口自定义背景图路径,空字符串表示未设置
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _mainBackgroundImagePath = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口背景图不透明度,数值越小背景越淡,文字越清晰
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _mainBackgroundOpacity = 0.35;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口背景图拉伸模式
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private Stretch _mainBackgroundStretch = Stretch.UniformToFill;
|
||||
|
||||
/// <summary>
|
||||
/// 是否是第一次运行
|
||||
/// </summary>
|
||||
@@ -80,4 +111,22 @@ 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;
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 递归追踪配置对象图中所有 <see cref="INotifyPropertyChanged"/> / <see cref="INotifyCollectionChanged"/> 节点的变更。
|
||||
/// <para>
|
||||
/// 订阅是增量且幂等的:
|
||||
/// 1. 已访问对象记录在 <see cref="ConditionalWeakTable{TKey,TValue}"/> 中,同一对象只订阅一次,也天然防环,且不阻止 GC;
|
||||
/// 2. 属性被整体替换为新对象、集合新增元素时,只补订阅新出现的对象;
|
||||
/// 3. 被替换掉的旧对象不主动退订,它们之后再触发事件也只是多一次无害的变更回调。
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// 不做全量重扫:根节点上的子配置是无通知的自动属性,运行时可能被临时替换(如地脉花任务临时替换 AutoFightConfig),
|
||||
/// 全量重扫会把追踪挂到临时对象上。
|
||||
/// </para>
|
||||
/// 回调在触发事件的线程上同步执行。
|
||||
/// </summary>
|
||||
internal sealed class ConfigChangeTracker
|
||||
{
|
||||
/// <summary>
|
||||
/// 递归深度上限,防御异常的对象图
|
||||
/// </summary>
|
||||
private const int MaxDepth = 32;
|
||||
|
||||
private static readonly object Marker = new();
|
||||
|
||||
/// <summary>
|
||||
/// 每个类型可继续向下追踪的属性(按属性名索引)
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> TrackablePropertyCache = new();
|
||||
|
||||
private readonly ConditionalWeakTable<object, object> _tracked = new();
|
||||
private readonly object _trackedLocker = new();
|
||||
private readonly Action<object> _onChanged;
|
||||
|
||||
/// <param name="onChanged">任意节点变更时回调,参数为触发事件的对象(属性所属对象或集合本身)</param>
|
||||
public ConfigChangeTracker(Action<object> onChanged)
|
||||
{
|
||||
_onChanged = onChanged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从根节点开始追踪
|
||||
/// </summary>
|
||||
public void Track(object root)
|
||||
{
|
||||
Visit(root, 0);
|
||||
}
|
||||
|
||||
private void Visit(object? node, int depth)
|
||||
{
|
||||
if (node == null || depth > MaxDepth || !IsTrackableInstance(node))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_trackedLocker)
|
||||
{
|
||||
if (_tracked.TryGetValue(node, out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_tracked.Add(node, Marker);
|
||||
}
|
||||
|
||||
if (node is INotifyPropertyChanged npc)
|
||||
{
|
||||
npc.PropertyChanged += OnPropertyChanged;
|
||||
}
|
||||
|
||||
if (node is INotifyCollectionChanged ncc)
|
||||
{
|
||||
ncc.CollectionChanged += OnCollectionChanged;
|
||||
}
|
||||
|
||||
VisitChildren(node, depth);
|
||||
}
|
||||
|
||||
private void VisitChildren(object node, int depth)
|
||||
{
|
||||
VisitItems(node, depth);
|
||||
|
||||
if (node is not INotifyPropertyChanged)
|
||||
{
|
||||
// 只沿着可通知对象向下展开属性,普通 POCO(如 GiTpPosition)没有变更通知,且可能存在会抛异常的计算属性
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var property in GetTrackableProperties(node.GetType()).Values)
|
||||
{
|
||||
Visit(TryGetValue(property, node), depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void VisitItems(object node, int depth)
|
||||
{
|
||||
if (node is string)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case IDictionary dictionary:
|
||||
// 先拷贝一份,缩短与其他线程并发修改的冲突窗口
|
||||
foreach (var value in dictionary.Values.Cast<object?>().ToArray())
|
||||
{
|
||||
Visit(value, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case IEnumerable enumerable:
|
||||
foreach (var item in enumerable.Cast<object?>().ToArray())
|
||||
{
|
||||
Visit(item, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ArgumentException)
|
||||
{
|
||||
// 其他线程正在修改集合,尽力而为:新元素会在下一次 CollectionChanged 或属性替换时补订阅
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (sender == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(e.PropertyName))
|
||||
{
|
||||
// 约定:属性名为空表示所有属性都已变化
|
||||
VisitChildren(sender, 0);
|
||||
}
|
||||
else if (GetTrackableProperties(sender.GetType()).TryGetValue(e.PropertyName, out var property))
|
||||
{
|
||||
// 子对象可能被整体替换,补订阅新值
|
||||
Visit(TryGetValue(property, sender), 0);
|
||||
}
|
||||
|
||||
_onChanged(sender);
|
||||
}
|
||||
|
||||
private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (sender == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Action == NotifyCollectionChangedAction.Reset)
|
||||
{
|
||||
VisitItems(sender, 0);
|
||||
}
|
||||
else if (e.NewItems != null)
|
||||
{
|
||||
foreach (var item in e.NewItems)
|
||||
{
|
||||
Visit(item, 0);
|
||||
}
|
||||
}
|
||||
|
||||
_onChanged(sender);
|
||||
}
|
||||
|
||||
private static object? TryGetValue(PropertyInfo property, object owner)
|
||||
{
|
||||
try
|
||||
{
|
||||
return property.GetValue(owner);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 计算属性可能抛异常(如依赖未初始化的数据),跳过即可
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只追踪可能产生变更通知或包含可通知元素的引用类型实例
|
||||
/// </summary>
|
||||
private static bool IsTrackableInstance(object node)
|
||||
{
|
||||
if (node is string or Delegate or MemberInfo || node.GetType().IsValueType)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return node is INotifyPropertyChanged or INotifyCollectionChanged or IEnumerable;
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetTrackableProperties(Type type)
|
||||
{
|
||||
return TrackablePropertyCache.GetOrAdd(type, static t => t
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(IsTrackableProperty)
|
||||
// 派生类用 new 隐藏基类属性时会出现同名属性,取第一个(最派生)即可
|
||||
.GroupBy(p => p.Name, StringComparer.Ordinal)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static bool IsTrackableProperty(PropertyInfo property)
|
||||
{
|
||||
if (property.GetMethod is not { IsPublic: true } || property.GetIndexParameters().Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var propertyType = property.PropertyType;
|
||||
if (propertyType.IsValueType || propertyType == typeof(string) || typeof(Delegate).IsAssignableFrom(propertyType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 不参与序列化的属性不属于配置内容
|
||||
var jsonIgnore = property.GetCustomAttribute<JsonIgnoreAttribute>();
|
||||
return jsonIgnore is not { Condition: JsonIgnoreCondition.Always };
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -13,4 +14,24 @@ public partial class DevConfig : ObservableObject
|
||||
// 录制地图名称
|
||||
[ObservableProperty]
|
||||
private string _recordMapName = MapTypes.Teyvat.ToString();
|
||||
|
||||
// Recognition 模板制作工具最近使用的配置文件
|
||||
[ObservableProperty]
|
||||
private string _recognitionJsonPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// Recognition 模板制作工具最近使用的配置文件历史,按最近使用顺序保存,最多 10 条。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private List<string> _recognitionJsonPathHistory = [];
|
||||
|
||||
// Recognition 模板制作工具最近使用的 Assets 根目录
|
||||
[ObservableProperty]
|
||||
private string _recognitionAssetsRootPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// Recognition 模板制作工具最近使用的输出文件夹历史,按最近使用顺序保存,最多 10 条。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private List<string> _recognitionAssetsRootPathHistory = [];
|
||||
}
|
||||
@@ -47,4 +47,10 @@ public partial class GenshinStartConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _startGameWithCmd = false;
|
||||
|
||||
/// <summary>
|
||||
/// 启动前自动关闭原神 HDR(删除原神 HDR 对应注册表键)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoDisableGenshinHdrEnabled = true;
|
||||
}
|
||||
@@ -1,90 +1,102 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
[JsonConverter(typeof(HardwareAccelerationConfigJsonConverter))]
|
||||
public partial class HardwareAccelerationConfig : ObservableObject
|
||||
{
|
||||
// 缺少新结构标识时不迁移旧参数,由启动准备流程使用 CPU 默认设置。
|
||||
[ObservableProperty] private int _formatVersion;
|
||||
[ObservableProperty] private InferenceEngineSettings _cpu = new() { DeviceId = "CPU" };
|
||||
[ObservableProperty] private PaddleOcrCpuConfig _paddleOcrCpu = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _directML = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _openVINO = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _cuda = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _tensorRT = new();
|
||||
[ObservableProperty] private InferenceValidationState _validationState;
|
||||
[ObservableProperty] private string _verifiedSignature = "";
|
||||
// 历史成功记录仅用于设置页展示,不能代替当前设备和参数的验证签名。
|
||||
[ObservableProperty] private InferenceDeviceType[] _validatedEngines = [];
|
||||
[ObservableProperty] private InferenceDeviceType? _lastFailedEngine;
|
||||
[ObservableProperty] private string _lastValidationError = "";
|
||||
|
||||
public InferenceEngineSettings GetEngineSettings(InferenceDeviceType engine) => engine switch
|
||||
{
|
||||
InferenceDeviceType.Cpu => Cpu,
|
||||
InferenceDeviceType.DirectML => DirectML,
|
||||
InferenceDeviceType.OpenVINO => OpenVINO,
|
||||
InferenceDeviceType.CUDA => Cuda,
|
||||
InferenceDeviceType.TensorRT => TensorRT,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(engine))
|
||||
};
|
||||
|
||||
public void RecordValidatedEngine(InferenceDeviceType engine)
|
||||
{
|
||||
if (engine != InferenceDeviceType.Cpu && !ValidatedEngines.Contains(engine))
|
||||
ValidatedEngines = [.. ValidatedEngines, engine];
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsExpectedConfiguration => FormatVersion == 1 && Enum.IsDefined(InferenceDevice)
|
||||
&& Enum.IsDefined(ValidationState) && Cpu != null && DirectML != null && OpenVINO != null
|
||||
&& Cuda != null && TensorRT != null && Cpu.CpuThreads >= 0
|
||||
&& Cpu.CpuThreads <= Environment.ProcessorCount
|
||||
&& !string.IsNullOrWhiteSpace(GetEngineSettings(InferenceDevice).DeviceId);
|
||||
|
||||
/// <summary>配置结构损坏时恢复完整默认值。运行时回退不得调用此方法。</summary>
|
||||
public void ResetToDefaults()
|
||||
{
|
||||
FormatVersion = 1;
|
||||
Cpu = new() { DeviceId = "CPU" };
|
||||
PaddleOcrCpu = new();
|
||||
DirectML = new(); OpenVINO = new(); Cuda = new(); TensorRT = new();
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
CpuOcr = true;
|
||||
ValidationState = InferenceValidationState.None;
|
||||
VerifiedSignature = "";
|
||||
}
|
||||
|
||||
/// <summary>只把当前生效选择切换为 CPU,保留其他引擎、OCR 和线程设置。</summary>
|
||||
public void SwitchToCpu()
|
||||
{
|
||||
FormatVersion = 1;
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
Cpu.DeviceId = "CPU";
|
||||
ValidationState = InferenceValidationState.None;
|
||||
VerifiedSignature = "";
|
||||
}
|
||||
/// <summary>
|
||||
/// 推理使用的设备。默认CPU
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
|
||||
|
||||
/// <summary>
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _cpuOcr = false;
|
||||
|
||||
#region 一般GPU加速设置
|
||||
partial void OnInferenceDeviceChanged(InferenceDeviceType value)
|
||||
{
|
||||
// 脚本或其他调用方写入历史编号、未知值时,也与配置读取保持一致。
|
||||
if (!Enum.IsDefined(value)) InferenceDevice = InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定gpu设备,默认为0(使用默认设备)
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _gpuDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 附加path,用;分割。默认为空。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _additionalPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// 是否输出优化后的模型文件到缓存。注意:在不支持的执行器上使用会导致异常。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _optimizedModel = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region cuda设置
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定cuda设备,默认为0(使用默认设备)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _cudaDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 自动附加cuda的path。一般情况下用这个就足够了。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoAppendCudaPath = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region TensorRT缓存设置
|
||||
|
||||
/// <summary>
|
||||
/// 启用TensorRT缓存。默认开启。不开的话使用TensorRT每次加载模型会卡爆。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableTensorRtCache = true;
|
||||
|
||||
/// <summary>
|
||||
/// 嵌入式引擎缓存。将引擎缓存嵌入到模型中。默认开启。关闭它可能会提高性能(如果不爆炸的话)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _embedTensorRtCache = true;
|
||||
|
||||
#endregion
|
||||
|
||||
#region OpenVINO设置
|
||||
/// <summary>
|
||||
/// OpenVino 设备参数。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _openVinoDevice = "AUTO:GPU,CPU";
|
||||
|
||||
/// <summary>
|
||||
/// 启用 OpenVINO 缓存。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableOpenVinoCache = false;
|
||||
private bool _cpuOcr = true;
|
||||
|
||||
#region 已移除参数的源注释(不读取、不保存,也不参与新推理设置)
|
||||
// 强制指定gpu设备,默认为0(使用默认设备)
|
||||
// 附加path,用;分割。默认为空。
|
||||
// 是否输出优化后的模型文件到缓存。注意:在不支持的执行器上使用会导致异常。默认关闭。
|
||||
// 强制指定cuda设备,默认为0(使用默认设备)
|
||||
// 自动附加cuda的path。一般情况下用这个就足够了。默认关闭。
|
||||
// 启用TensorRT缓存。默认开启。不开的话使用TensorRT每次加载模型会卡爆。
|
||||
// 嵌入式引擎缓存。将引擎缓存嵌入到模型中。默认开启。关闭它可能会提高性能(如果不爆炸的话)。
|
||||
// OpenVino 设备参数。
|
||||
// 启用 OpenVINO 缓存。默认关闭。
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>把无效推理字段隔离在硬件设置内,不能因为单个字段错误重置整份用户配置。</summary>
|
||||
public sealed class HardwareAccelerationConfigJsonConverter : JsonConverter<HardwareAccelerationConfig>
|
||||
{
|
||||
public override HardwareAccelerationConfig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
using var document = JsonDocument.ParseValue(ref reader);
|
||||
try
|
||||
{
|
||||
var data = document.RootElement.Deserialize<SerializedConfiguration>(options);
|
||||
if (data == null) return new();
|
||||
return new()
|
||||
{
|
||||
FormatVersion = data.FormatVersion, InferenceDevice = data.InferenceDevice, CpuOcr = data.CpuOcr,
|
||||
Cpu = data.Cpu!, DirectML = data.DirectML!, OpenVINO = data.OpenVINO!, Cuda = data.Cuda!, TensorRT = data.TensorRT!,
|
||||
PaddleOcrCpu = data.PaddleOcrCpu ?? new(),
|
||||
ValidationState = data.ValidationState, VerifiedSignature = data.VerifiedSignature ?? "",
|
||||
ValidatedEngines = data.ValidatedEngines ?? [],
|
||||
LastFailedEngine = data.LastFailedEngine, LastValidationError = data.LastValidationError ?? ""
|
||||
};
|
||||
}
|
||||
catch (JsonException) { return new(); }
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, HardwareAccelerationConfig value, JsonSerializerOptions options)
|
||||
=> JsonSerializer.Serialize(writer, new SerializedConfiguration
|
||||
{
|
||||
FormatVersion = value.FormatVersion, InferenceDevice = value.InferenceDevice, CpuOcr = value.CpuOcr,
|
||||
Cpu = value.Cpu, DirectML = value.DirectML, OpenVINO = value.OpenVINO, Cuda = value.Cuda, TensorRT = value.TensorRT,
|
||||
PaddleOcrCpu = value.PaddleOcrCpu,
|
||||
ValidationState = value.ValidationState, VerifiedSignature = value.VerifiedSignature,
|
||||
ValidatedEngines = value.ValidatedEngines,
|
||||
LastFailedEngine = value.LastFailedEngine, LastValidationError = value.LastValidationError
|
||||
}, options);
|
||||
|
||||
private sealed class SerializedConfiguration
|
||||
{
|
||||
public SerializedConfiguration() { }
|
||||
public int FormatVersion { get; set; }
|
||||
public InferenceDeviceType InferenceDevice { get; set; }
|
||||
public bool CpuOcr { get; set; } = true;
|
||||
public InferenceEngineSettings? Cpu { get; set; }
|
||||
public PaddleOcrCpuConfig? PaddleOcrCpu { get; set; }
|
||||
public InferenceEngineSettings? DirectML { get; set; }
|
||||
public InferenceEngineSettings? OpenVINO { get; set; }
|
||||
public InferenceEngineSettings? Cuda { get; set; }
|
||||
public InferenceEngineSettings? TensorRT { get; set; }
|
||||
public InferenceValidationState ValidationState { get; set; }
|
||||
public string? VerifiedSignature { get; set; }
|
||||
public InferenceDeviceType[]? ValidatedEngines { get; set; }
|
||||
public InferenceDeviceType? LastFailedEngine { get; set; }
|
||||
public string? LastValidationError { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,12 @@ 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 = "";
|
||||
|
||||
@@ -115,6 +121,13 @@ public partial class HotKeyConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private string _takeScreenshotHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// Recognition 模板素材制作
|
||||
[ObservableProperty]
|
||||
private string _recognitionTemplateEditorHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _recognitionTemplateEditorHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _turnAroundHotkey = "";
|
||||
|
||||
@@ -163,6 +176,13 @@ 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 = "";
|
||||
@@ -219,6 +239,13 @@ 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 = "";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.QuickClaimReward;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
@@ -67,4 +68,22 @@ 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,6 +1,8 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
@@ -10,6 +12,44 @@ 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>
|
||||
@@ -57,18 +97,339 @@ 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>
|
||||
[ObservableProperty]
|
||||
private bool _showFps = false;
|
||||
|
||||
/// <summary>
|
||||
/// 显示遮罩指标栏
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _showOverlayMetrics = false;
|
||||
|
||||
// 配置文件里使用 string key 便于兼容旧版本,读取后由 EnsureOverlayMetricItems 约束回固定枚举集合。
|
||||
public Dictionary<string, bool> OverlayMetricItems { get; set; } = OverlayMetricItemDefaults.CreateDefaultItems();
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩文本透明度 (0.0-1.0)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _textOpacity = 1.0;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用遮罩 UI 缩放。关闭后直接使用各遮罩元素的基础尺寸。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _overlayScalingEnabled = false;
|
||||
|
||||
/// <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;
|
||||
|
||||
@@ -95,4 +456,175 @@ public partial class MaskWindowConfig : ObservableObject
|
||||
|
||||
[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
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class MusicConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 曲谱扫描根目录
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _musicFolder = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 默认使用后台 PostMessage 演奏
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _inputMode = "BackgroundPostMessage";
|
||||
|
||||
/// <summary>
|
||||
/// 播放模式
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _playbackMode = "Sequential";
|
||||
|
||||
/// <summary>
|
||||
/// 播放速度
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _speed = 1.0;
|
||||
|
||||
/// <summary>
|
||||
/// 是否使用自定义 BPM 覆盖曲谱的基准速度
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _useCustomBpm;
|
||||
|
||||
/// <summary>
|
||||
/// 自定义 BPM
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _customBpm = 120;
|
||||
|
||||
/// <summary>
|
||||
/// 演奏前是否自动切换到当前曲目的输出乐器
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoSwitchInstrument;
|
||||
|
||||
/// <summary>
|
||||
/// 默认输出乐器档案
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _selectedInstrumentProfile = "风物之诗琴";
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
|
||||
@@ -14,11 +14,24 @@ 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 = "枫丹";
|
||||
@@ -37,6 +50,91 @@ 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 int _autoBossTotalRunCountLimit = 0;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _autoBossCompletedRunCount = 0;
|
||||
|
||||
[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 OnAutoBossTotalRunCountLimitChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
AutoBossTotalRunCountLimit = 0;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnAutoBossCompletedRunCountChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
AutoBossCompletedRunCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnAutoBossReviveRetryCountChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
AutoBossReviveRetryCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
// 领取每日奖励的好感队伍名称
|
||||
[ObservableProperty]
|
||||
@@ -46,13 +144,13 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _minResinToKeep = 0;
|
||||
|
||||
// 领取每日奖励的好感数量
|
||||
// 普通周日或限时奖励选项
|
||||
[ObservableProperty]
|
||||
private string _sundayEverySelectedValue = "0";
|
||||
|
||||
// 领取每日奖励的好感数量
|
||||
|
||||
// 每周秘境的全局限时奖励选项,单日留空时使用
|
||||
[ObservableProperty]
|
||||
private string _sundaySelectedValue = "0";
|
||||
private string _sundayWeeklySelectedValue = "0";
|
||||
|
||||
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
|
||||
[ObservableProperty]
|
||||
@@ -151,6 +249,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _mondayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _mondaySelectedValue = "0";
|
||||
|
||||
|
||||
//周二
|
||||
@@ -159,6 +260,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _tuesdayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _tuesdaySelectedValue = "0";
|
||||
|
||||
//周三
|
||||
[ObservableProperty]
|
||||
@@ -166,6 +270,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _wednesdayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _wednesdaySelectedValue = "0";
|
||||
|
||||
//周四
|
||||
[ObservableProperty]
|
||||
@@ -173,6 +280,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _thursdayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _thursdaySelectedValue = "0";
|
||||
|
||||
//周五
|
||||
[ObservableProperty]
|
||||
@@ -180,6 +290,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _fridayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _fridaySelectedValue = "0";
|
||||
|
||||
//周六
|
||||
[ObservableProperty]
|
||||
@@ -187,6 +300,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _saturdayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _saturdaySelectedValue = "0";
|
||||
|
||||
//周日
|
||||
[ObservableProperty]
|
||||
@@ -195,6 +311,9 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private string _sundayDomainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _sundaySelectedValue = "0";
|
||||
|
||||
// 完成后操作
|
||||
[ObservableProperty]
|
||||
private string _completionAction = string.Empty;
|
||||
@@ -208,22 +327,37 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
|
||||
return dayOfWeek switch
|
||||
{
|
||||
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)
|
||||
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)
|
||||
};
|
||||
}
|
||||
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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -12,12 +13,18 @@ public partial class OtherConfig : ObservableObject
|
||||
//调度器任务和部分独立任务,失去焦点,自动激活游戏窗口
|
||||
[ObservableProperty]
|
||||
private bool _restoreFocusOnLostEnabled = false;
|
||||
//窗口类名优先检测:原版仅靠进程名+MainWindowHandle 查找游戏窗口,该句柄为 0 或指向错误窗口时会找不到。开启后优先按窗口类名枚举检测,未命中再按进程枚举取客户区最大的可见窗口,仍不命中才回退原版方式。即时生效(每次查找窗口时读取),默认关闭,关闭时行为与旧版完全一致
|
||||
[ObservableProperty]
|
||||
private bool _windowClassDetectPreferred = false;
|
||||
//自动领取派遣任务城市
|
||||
[ObservableProperty]
|
||||
private string _autoFetchDispatchAdventurersGuildCountry = "无";
|
||||
//服务器时区偏移量
|
||||
[ObservableProperty]
|
||||
private TimeSpan _serverTimeZoneOffset = TimeSpan.FromHours(8);
|
||||
//物品图标识别模型
|
||||
[ObservableProperty]
|
||||
private ItemIconRecognitionMode _itemIconRecognitionMode = ItemIconRecognitionMode.Item;
|
||||
[ObservableProperty]
|
||||
private AutoRestart _autoRestartConfig = new();
|
||||
//锄地规划
|
||||
@@ -106,46 +113,6 @@ public partial class OtherConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private PaddleOcrModelConfig _paddleOcrModelConfig = PaddleOcrModelConfig.V4Auto;
|
||||
|
||||
/// <summary>
|
||||
/// 允许OCR结果中出现连续重复字符(关闭CTC重复字符折叠)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _allowDuplicateChar;
|
||||
|
||||
/// <summary>
|
||||
/// 切换队伍时使用 OcrMatch 模糊匹配代替正则表达式匹配
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _useOcrMatchForPartySwitch = true;
|
||||
|
||||
/// <summary>
|
||||
/// OcrMatch 模糊匹配的默认阈值 (0~1),分数 ≥ 阈值视为匹配成功
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _ocrMatchDefaultThreshold = 0.8;
|
||||
|
||||
partial void OnOcrMatchDefaultThresholdChanged(double value)
|
||||
{
|
||||
if (value is <= 0 or > 1)
|
||||
{
|
||||
OcrMatchDefaultThreshold = Math.Clamp(value, 0.01, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PaddleOCR 识别置信度阈值 (0~1),低于此阈值的字符将被过滤
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _paddleOcrThreshold = 0.5;
|
||||
|
||||
partial void OnPaddleOcrThresholdChanged(double value)
|
||||
{
|
||||
if (value is < 0 or >= 1)
|
||||
{
|
||||
PaddleOcrThreshold = Math.Clamp(value, 0, 0.99);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//public partial class OtherConfig : ObservableObject
|
||||
@@ -161,4 +128,5 @@ public partial class OtherConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _uiCultureInfoName = "zh-Hans";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>OCR 纯 CPU 推理的独立线程设置,默认跟随全局 CPU 线程数。</summary>
|
||||
public partial class PaddleOcrCpuConfig : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private PaddleOcrCpuMode _mode;
|
||||
[ObservableProperty] private int _detectionThreads = Math.Min(2, Environment.ProcessorCount);
|
||||
[ObservableProperty] private int _recognitionThreads = Math.Min(2, Environment.ProcessorCount);
|
||||
[ObservableProperty] private int _interOpThreads = 1;
|
||||
[ObservableProperty] private bool _parallelExecution;
|
||||
[ObservableProperty] private bool _allowSpinning = true;
|
||||
|
||||
public PaddleOcrCpuOptions ToOptions() => new()
|
||||
{
|
||||
Mode = Mode, DetectionThreads = DetectionThreads, RecognitionThreads = RecognitionThreads,
|
||||
InterOpThreads = InterOpThreads, ParallelExecution = ParallelExecution, AllowSpinning = AllowSpinning
|
||||
};
|
||||
|
||||
public static PaddleOcrCpuConfig FromOptions(PaddleOcrCpuOptions options) => new()
|
||||
{
|
||||
Mode = options.Mode, DetectionThreads = options.DetectionThreads, RecognitionThreads = options.RecognitionThreads,
|
||||
InterOpThreads = options.InterOpThreads, ParallelExecution = options.ParallelExecution, AllowSpinning = options.AllowSpinning
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
@@ -29,7 +29,24 @@ 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,12 +8,28 @@ 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 = false;
|
||||
private bool _enabled = true;
|
||||
|
||||
// 是否启用自动拾取
|
||||
[ObservableProperty]
|
||||
@@ -21,6 +37,9 @@ public partial class PathingPartyConfig : ObservableObject
|
||||
// 切换到队伍的名称
|
||||
[ObservableProperty]
|
||||
private string _partyName = string.Empty;
|
||||
|
||||
[JsonIgnore]
|
||||
public bool SkipPartySwitch { get; set; }
|
||||
|
||||
// 切换队伍前是否前往须弥七天神像
|
||||
[ObservableProperty]
|
||||
@@ -68,7 +87,24 @@ 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;
|
||||
@@ -121,17 +157,120 @@ public partial class PathingPartyConfig : ObservableObject
|
||||
|
||||
//启用自动战斗配置
|
||||
[ObservableProperty]
|
||||
private bool _autoFightEnabled = false;
|
||||
private bool _autoFightEnabled = true;
|
||||
|
||||
[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;
|
||||
}
|
||||
if (MwkJumpFlyDistance <= value)
|
||||
{
|
||||
MwkJumpFlyDistance = value + 1;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnApproachStopDistanceChanged(int value)
|
||||
{
|
||||
if (value > Distance)
|
||||
{
|
||||
_approachStopDistance = Distance;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnMwkJumpFlyDistanceChanged(int value)
|
||||
{
|
||||
if (value <= Distance)
|
||||
{
|
||||
MwkJumpFlyDistance = Distance + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 赶路角色选择说明:
|
||||
/// - 空选(""):不进行赶路动作,仅普通跑图
|
||||
/// - 选择具体角色:仅使用该角色的赶路逻辑
|
||||
/// - 选择"自动":优先使用行走位(MainAvatarIndex)角色跑图,行走位不支持赶路时,按支持列表顺序尝试使用队伍中其他角色
|
||||
/// 支持的角色列表:玛薇卡、闲云、桑多涅、恰斯卡、流浪者、伊法、希诺宁、法尔伽、夜兰
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public List<string> HurryOnAvatarList { get; } = ["","自动","玛薇卡","闲云","桑多涅","恰斯卡","流浪者","伊法","希诺宁","法尔伽","夜兰"];
|
||||
|
||||
[JsonIgnore]
|
||||
public List<string> TravelModeList { get; } = ["精准靠近","连续赶路"];
|
||||
|
||||
[ObservableProperty]
|
||||
private string _hurryOnAvatar = "";
|
||||
|
||||
/// <summary>
|
||||
/// 覆写赶路帧间隔(ms),默认 100。存在有效赶路角色时生效,有效范围 1-150,超出自动钳制。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _hurryOnFrameInterval = 100;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _travelMode = "精准靠近";
|
||||
|
||||
/// <summary>
|
||||
/// 接近节点时切人步行
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _switchToWalkEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 玛薇卡跳飞开关
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _mwkJumpFlyEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 玛薇卡跳飞启用距离(米),必须大于 <see cref="Distance"/>,越界时自动使用 Distance+1 的值。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _mwkJumpFlyDistance = 75;
|
||||
|
||||
/// <summary>
|
||||
/// 跳飞间隔(秒),闲云使用其1/2值
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _mwkJumpFlyIntervalSeconds = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 玛薇卡在车上禁用冲刺。0命玛薇卡酌情勾选,节约夜魂值。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _mwkDisableSprintEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 跳飞前额外冲刺次数。6命玛薇卡可选,每次上车后前若干次跳飞改为冲刺跳飞,速度更快,夜魂值消耗更高,推荐3次。
|
||||
/// 0 表示不使用冲刺跳飞。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _mwkJumpFlySprintCount = 0;
|
||||
|
||||
public static PathingPartyConfig BuildDefault()
|
||||
{
|
||||
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
|
||||
// 运行时回退配置保持禁用标记,确保继续使用地图追踪条件和独立战斗配置
|
||||
var pathingConditionConfig = TaskContext.Instance().Config.PathingConditionConfig;
|
||||
return new PathingPartyConfig
|
||||
{
|
||||
Enabled = false,
|
||||
AutoFightEnabled = false,
|
||||
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
|
||||
RecoverTiming = pathingConditionConfig.RecoverTiming,
|
||||
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs,
|
||||
AutoEatEnabled = pathingConditionConfig.AutoEatEnabled
|
||||
};
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Gamepad;
|
||||
|
||||
/// <summary>
|
||||
/// 手柄后端(预留,未实现)。前后台返回同一个通道,所有操作都 warn 后忽略。
|
||||
/// </summary>
|
||||
public sealed class GamepadInputBackend : IInputBackend
|
||||
{
|
||||
private readonly GamepadChannel _channel = new();
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.Gamepad;
|
||||
|
||||
public IInputChannel Foreground => _channel;
|
||||
|
||||
public IInputChannel Background => _channel;
|
||||
|
||||
public void ReleaseAll() => _channel.ReleaseAll();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 手柄通道(预留,未实现)。
|
||||
/// <para>实现时的约定:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item>覆写 SimulateAction,把 GIActions 直接映射成手柄输入;</item>
|
||||
/// <item>键盘按键按键位配置反查成 GIActions 再映射;</item>
|
||||
/// <item>MoveMouseBy 映射到右摇杆,是阻塞调用;</item>
|
||||
/// <item>原始鼠标按键和 MoveMouseTo 都 warn 后忽略。坐标点击由“移动 + 左键”两步组成,只忽略移动的话,左键会被映射成普攻。</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal sealed class GamepadChannel : InputChannelBase
|
||||
{
|
||||
private const string NotImplemented = "手柄后端未实现";
|
||||
|
||||
protected override void OnKeyDown(User32.VK key) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMoveTo(double absX, double absY) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnScroll(int clicks) => WarnUnsupported(NotImplemented);
|
||||
|
||||
/// <summary>
|
||||
/// 未实现时没有真正按下的键
|
||||
/// </summary>
|
||||
public override bool IsKeyDown(User32.VK key) => false;
|
||||
|
||||
public override void ReleaseAll() => TakePressedKeys();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版 JS SDK(Resources/JavaScript/ys-input-inject.js,编译为嵌入资源)的通用调用接口
|
||||
/// </summary>
|
||||
public interface IWebInputBridge
|
||||
{
|
||||
/// <summary>
|
||||
/// 调用页面 SDK <c>window.__ysInputInject[method](...args)</c>。
|
||||
/// 不等待执行结果,页面侧按到达顺序串行执行;失败由实现类记录日志。
|
||||
/// 可选参数请直接省略,不要传 null:JSON 的 null 不会触发 JS 的参数默认值。
|
||||
/// </summary>
|
||||
void Invoke(string method, params object[] args);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// VK 到 KeyboardEvent.code 的映射,SDK 的 keyDown / keyUp / tapKey 接收 code 字符串。
|
||||
/// 泛指的 Shift / Ctrl / Alt 映射为左侧键
|
||||
/// </summary>
|
||||
public static class WebKeyCodes
|
||||
{
|
||||
public static bool TryGetCode(User32.VK vk, out string code)
|
||||
{
|
||||
var value = (int)vk;
|
||||
code = value switch
|
||||
{
|
||||
>= 0x41 and <= 0x5A => $"Key{(char)value}",
|
||||
>= 0x30 and <= 0x39 => $"Digit{(char)value}",
|
||||
>= 0x70 and <= 0x7B => $"F{value - 0x6F}",
|
||||
>= 0x60 and <= 0x69 => $"Numpad{value - 0x60}",
|
||||
0x08 => "Backspace",
|
||||
0x09 => "Tab",
|
||||
0x0D => "Enter",
|
||||
0x10 or 0xA0 => "ShiftLeft",
|
||||
0xA1 => "ShiftRight",
|
||||
0x11 or 0xA2 => "ControlLeft",
|
||||
0xA3 => "ControlRight",
|
||||
0x12 or 0xA4 => "AltLeft",
|
||||
0xA5 => "AltRight",
|
||||
0x13 => "Pause",
|
||||
0x14 => "CapsLock",
|
||||
0x1B => "Escape",
|
||||
0x20 => "Space",
|
||||
0x21 => "PageUp",
|
||||
0x22 => "PageDown",
|
||||
0x23 => "End",
|
||||
0x24 => "Home",
|
||||
0x25 => "ArrowLeft",
|
||||
0x26 => "ArrowUp",
|
||||
0x27 => "ArrowRight",
|
||||
0x28 => "ArrowDown",
|
||||
0x2C => "PrintScreen",
|
||||
0x2D => "Insert",
|
||||
0x2E => "Delete",
|
||||
0x5B => "MetaLeft",
|
||||
0x5C => "MetaRight",
|
||||
0x6A => "NumpadMultiply",
|
||||
0x6B => "NumpadAdd",
|
||||
0x6D => "NumpadSubtract",
|
||||
0x6E => "NumpadDecimal",
|
||||
0x6F => "NumpadDivide",
|
||||
0x90 => "NumLock",
|
||||
0x91 => "ScrollLock",
|
||||
0xBA => "Semicolon",
|
||||
0xBB => "Equal",
|
||||
0xBC => "Comma",
|
||||
0xBD => "Minus",
|
||||
0xBE => "Period",
|
||||
0xBF => "Slash",
|
||||
0xC0 => "Backquote",
|
||||
0xDB => "BracketLeft",
|
||||
0xDC => "Backslash",
|
||||
0xDD => "BracketRight",
|
||||
0xDE => "Quote",
|
||||
_ => string.Empty,
|
||||
};
|
||||
return code.Length > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版后端:把通道操作翻译成页面 SDK(ys-input-inject.js)的函数调用。
|
||||
/// 网页版没有前后台之分,后端自身就是唯一的通道,<see cref="Foreground"/> 与 <see cref="Background"/> 都返回自己。
|
||||
/// <para>
|
||||
/// 指针位置由 SDK 保存(setAbsPosition),按键和相对移动默认使用它;按住时长使用 SDK 的默认值
|
||||
/// (keyHoldMs 60 ms、clickHoldMs 35 ms),需要调整时通过 <c>Sdk.Invoke("setDefaults", …)</c>。
|
||||
/// </para>
|
||||
/// 由 WebPageRuntimeProvider 创建,GameRuntimeService 负责 InputHub.Attach。
|
||||
/// </summary>
|
||||
public sealed class WebSdkInputBackend : InputChannelBase, IInputBackend
|
||||
{
|
||||
// TODO(云原神网页版):鼠标相对移动的偏差值尚未实测,暂按 1:1 透传。
|
||||
// dx/dy 原样作为 ClientCore.mouseMove 的 rel 参数发送,与桌面端 SendInput 的相对位移是否等价尚未验证。
|
||||
// 调用方传入前通常已乘过 TaskContext.DpiScale,标定时需要一并考虑。
|
||||
// 实测后只调整这两个系数,不要在业务代码里补偿。
|
||||
private const double RelativeMoveScaleX = 1.0;
|
||||
private const double RelativeMoveScaleY = 1.0;
|
||||
|
||||
// TODO(云原神网页版):滚轮的方向和步长尚未实测,暂按 Windows 的 120/格 透传。
|
||||
private const int WheelDeltaPerClick = 120;
|
||||
|
||||
private readonly Func<RECT> _canvasRect;
|
||||
|
||||
/// <param name="sdk">SDK 调用桥,由宿主持有并释放</param>
|
||||
/// <param name="canvasRect">游戏画面在屏幕上的物理像素矩形,应与截图区域一致</param>
|
||||
public WebSdkInputBackend(IWebInputBridge sdk, Func<RECT> canvasRect)
|
||||
{
|
||||
Sdk = sdk ?? throw new ArgumentNullException(nameof(sdk));
|
||||
_canvasRect = canvasRect ?? throw new ArgumentNullException(nameof(canvasRect));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展口:直接调用 SDK 的其他函数,用于键鼠接口表达不了的需求,例如 sendIme、sendClipboard、setDefaults、look
|
||||
/// </summary>
|
||||
public IWebInputBridge Sdk { get; }
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.WebSdk;
|
||||
|
||||
public IInputChannel Foreground => this;
|
||||
|
||||
public IInputChannel Background => this;
|
||||
|
||||
#region 原子操作
|
||||
|
||||
protected override void OnKeyDown(User32.VK key) => InvokeKey("keyDown", key);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => InvokeKey("keyUp", key);
|
||||
|
||||
protected override void OnKeyPress(User32.VK key) => InvokeKey("tapKey", key);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
if (TryGetButtonName(button, out var name))
|
||||
{
|
||||
Sdk.Invoke(down ? "mouseDown" : "mouseUp", name);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
if (TryGetButtonName(button, out var name))
|
||||
{
|
||||
Sdk.Invoke("click", name);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) =>
|
||||
Sdk.Invoke("mouseMove", dx * RelativeMoveScaleX, dy * RelativeMoveScaleY);
|
||||
|
||||
/// <summary>
|
||||
/// 桌面 0~65535 坐标 -> 屏幕物理像素 -> 相对游戏画面归一化到 0~1
|
||||
/// </summary>
|
||||
protected override void OnMoveTo(double absX, double absY)
|
||||
{
|
||||
var rect = _canvasRect();
|
||||
if (rect.Width <= 0 || rect.Height <= 0)
|
||||
{
|
||||
WarnUnsupported("游戏画面区域为空时的鼠标定位");
|
||||
return;
|
||||
}
|
||||
|
||||
var screen = PrimaryScreen.WorkingArea;
|
||||
var x = Math.Clamp((absX * screen.Width / 65535d - rect.Left) / rect.Width, 0d, 1d);
|
||||
var y = Math.Clamp((absY * screen.Height / 65535d - rect.Top) / rect.Height, 0d, 1d);
|
||||
|
||||
// 位置由 SDK 保存,后续按键和相对移动都使用它
|
||||
Sdk.Invoke("setAbsPosition", x, y);
|
||||
Sdk.Invoke("mouseMove", 0, 0);
|
||||
}
|
||||
|
||||
protected override void OnScroll(int clicks) => Sdk.Invoke("scroll", clicks * WheelDeltaPerClick);
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// SDK 的 releaseAll 会释放页面侧记录的全部按键,本地记录同步清空。
|
||||
/// 同时满足 <see cref="IInputChannel.ReleaseAll"/> 与 <see cref="IInputBackend.ReleaseAll"/>
|
||||
/// </summary>
|
||||
public override void ReleaseAll()
|
||||
{
|
||||
TakePressedKeys();
|
||||
try
|
||||
{
|
||||
Sdk.Invoke("releaseAll");
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
// 页面或桥接已关闭时无法再发送释放指令。ReleaseAll 常在 finally 中调用,不能让它抛出并掩盖原异常
|
||||
Logger.LogDebug(e, "云原神页面已关闭,跳过释放按键");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 桥接由宿主持有并释放,这里不释放
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private void InvokeKey(string method, User32.VK key)
|
||||
{
|
||||
if (WebKeyCodes.TryGetCode(key, out var code))
|
||||
{
|
||||
Sdk.Invoke(method, code);
|
||||
}
|
||||
else
|
||||
{
|
||||
WarnUnsupported($"按键 {key}");
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryGetButtonName(InputMouseButton button, out string name)
|
||||
{
|
||||
name = button switch
|
||||
{
|
||||
InputMouseButton.Left => "left",
|
||||
InputMouseButton.Right => "right",
|
||||
InputMouseButton.Middle => "middle",
|
||||
_ => string.Empty,
|
||||
};
|
||||
if (name.Length > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
WarnUnsupported($"鼠标键 {button}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 基于 WebView2 的 SDK 调用桥:负责把 SDK 注入页面、把调用投递到页面、查询 SDK 状态。
|
||||
/// <para>
|
||||
/// 宿主只需调用 <see cref="InstallAsync"/>。本类不持有 WebView2 的生命周期,由宿主创建和释放。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class WebView2InputBridge : IWebInputBridge, IDisposable
|
||||
{
|
||||
private const string RequestChannel = "bgi.input";
|
||||
private const string ErrorChannel = "bgi.input.error";
|
||||
private const string SdkResourceName = "BetterGenshinImpact.Resources.JavaScript.ys-input-inject.js";
|
||||
|
||||
/// <summary>
|
||||
/// 同类 warn 的最小间隔,避免每次按键都刷日志
|
||||
/// </summary>
|
||||
private const long WarnIntervalMs = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// 页面侧分发脚本:按到达顺序串行调用 window.__ysInputInject 上的函数,只在失败时回报。
|
||||
/// 只在顶层文档生效:注入脚本也会在子 frame 中执行,而子 frame 没有 chrome.webview
|
||||
/// </summary>
|
||||
private const string BootstrapScript = """
|
||||
(() => {
|
||||
if (window.top !== window || !window.chrome?.webview || window.__bgiInputBridge) return;
|
||||
window.__bgiInputBridge = true;
|
||||
let queue = Promise.resolve();
|
||||
window.chrome.webview.addEventListener("message", ({ data }) => {
|
||||
if (!data || data.channel !== "bgi.input") return;
|
||||
const { method, args = [] } = data;
|
||||
// 串行执行:tapKey、click 等是异步函数,并发执行会打乱按键顺序
|
||||
queue = queue
|
||||
.then(() => {
|
||||
const sdk = window.__ysInputInject;
|
||||
if (!sdk || !Object.hasOwn(sdk, method) || typeof sdk[method] !== "function") {
|
||||
throw new Error(`unknown sdk method: ${method}`);
|
||||
}
|
||||
return sdk[method](...args);
|
||||
})
|
||||
.catch(e => window.chrome.webview.postMessage({
|
||||
channel: "bgi.input.error", method, error: String(e?.message ?? e)
|
||||
}));
|
||||
});
|
||||
})();
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// 状态查询脚本:SDK 未注入或页面尚未加载到游戏时 status() 会抛错,统一转成 error 字段
|
||||
/// </summary>
|
||||
private const string StatusScript = """
|
||||
(() => {
|
||||
try {
|
||||
const s = window.__ysInputInject?.status();
|
||||
if (!s) return { error: "sdk not installed" };
|
||||
return { rtcDataChannelState: s.rtcDataChannelState ?? null, gameDataStarted: s.gameDataStarted ?? null };
|
||||
} catch (e) {
|
||||
return { error: String(e?.message ?? e) };
|
||||
}
|
||||
})()
|
||||
""";
|
||||
|
||||
private static ILogger? _logger;
|
||||
private static string? _sdkScript;
|
||||
|
||||
private readonly CoreWebView2 _core;
|
||||
private readonly Dispatcher _dispatcher;
|
||||
private long _lastPostWarnTicks = long.MinValue;
|
||||
private long _lastErrorWarnTicks = long.MinValue;
|
||||
private volatile bool _disposed;
|
||||
|
||||
private WebView2InputBridge(CoreWebView2 core, Dispatcher dispatcher)
|
||||
{
|
||||
_core = core;
|
||||
_dispatcher = dispatcher;
|
||||
_core.WebMessageReceived += OnWebMessageReceived;
|
||||
}
|
||||
|
||||
private static ILogger Logger => _logger ??= App.GetLogger<WebView2InputBridge>();
|
||||
|
||||
/// <summary>
|
||||
/// 注入 SDK 与分发脚本(对之后的每次导航生效),然后返回桥。
|
||||
/// 必须在 CoreWebView2 所在的 UI 线程上、首次导航之前调用
|
||||
/// </summary>
|
||||
public static async Task<WebView2InputBridge> InstallAsync(CoreWebView2 core)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(core);
|
||||
var dispatcher = Dispatcher.CurrentDispatcher;
|
||||
|
||||
// SDK 本身不改动,外面包一层只在顶层文档执行
|
||||
await core.AddScriptToExecuteOnDocumentCreatedAsync($"if (window.top === window) {{\n{GetSdkScript()}\n}}");
|
||||
await core.AddScriptToExecuteOnDocumentCreatedAsync(BootstrapScript);
|
||||
return new WebView2InputBridge(core, dispatcher);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 投递一次 SDK 调用,不等待页面执行。可在任意线程调用:
|
||||
/// 其他线程经 Dispatcher.BeginInvoke 投递到 UI 线程,同优先级按先后顺序执行,任务线程不阻塞,也不会与等待任务的 UI 线程互相死锁;
|
||||
/// UI 线程上直接投递。桥已释放时抛出 <see cref="InvalidOperationException"/>
|
||||
/// </summary>
|
||||
public void Invoke(string method, params object[] args)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(method);
|
||||
if (_disposed)
|
||||
{
|
||||
throw new InvalidOperationException("云原神 WebView2 输入桥已释放");
|
||||
}
|
||||
|
||||
var json = JsonConvert.SerializeObject(new { channel = RequestChannel, method, args });
|
||||
if (_dispatcher.CheckAccess())
|
||||
{
|
||||
// UI 线程直接投递:保证宿主关闭前(Closing 中)发出的 releaseAll 能在页面销毁前送达
|
||||
Post(method, json);
|
||||
}
|
||||
else
|
||||
{
|
||||
_dispatcher.BeginInvoke(() => Post(method, json));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询 SDK 状态。在 UI 线程上调用(宿主的 DispatcherTimer),其他线程会被切到 UI 线程执行
|
||||
/// </summary>
|
||||
public async Task<WebSdkStatus> GetStatusAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return new WebSdkStatus(null, null, "bridge disposed");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = _dispatcher.CheckAccess()
|
||||
? await _core.ExecuteScriptAsync(StatusScript)
|
||||
: await _dispatcher.InvokeAsync(() => _core.ExecuteScriptAsync(StatusScript)).Task.Unwrap();
|
||||
var result = JToken.Parse(json) as JObject;
|
||||
return new WebSdkStatus(
|
||||
result?.Value<string>("rtcDataChannelState"),
|
||||
result?.Value<bool?>("gameDataStarted"),
|
||||
result?.Value<string>("error"));
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ObjectDisposedException or JsonException
|
||||
or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
// 页面正在导航或 WebView2 已关闭
|
||||
return new WebSdkStatus(null, null, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_core.WebMessageReceived -= OnWebMessageReceived;
|
||||
}
|
||||
|
||||
private void Post(string method, string json)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_core.PostWebMessageAsJson(json);
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ObjectDisposedException
|
||||
or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
// 页面已关闭或正在导航。调用方已经返回,只能记录
|
||||
if (ShouldWarn(ref _lastPostWarnTicks))
|
||||
{
|
||||
Logger.LogWarning("云原神 SDK 调用投递失败:{Method},{Error}", method, e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
|
||||
{
|
||||
JObject message;
|
||||
try
|
||||
{
|
||||
message = JObject.Parse(e.WebMessageAsJson);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// 不是 JSON 对象的消息与本桥无关
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(message.Value<string>("channel"), ErrorChannel, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 页面断开由宿主的状态轮询发现,这里只记录调用错误
|
||||
if (ShouldWarn(ref _lastErrorWarnTicks))
|
||||
{
|
||||
Logger.LogWarning("云原神 SDK 调用失败:{Method},{Error}",
|
||||
message.Value<string>("method") ?? string.Empty,
|
||||
message.Value<string>("error") ?? "未知错误");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ShouldWarn(ref long lastTicks)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var last = Interlocked.Read(ref lastTicks);
|
||||
if (last != long.MinValue && now - last < WarnIntervalMs)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Interlocked.Exchange(ref lastTicks, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string GetSdkScript()
|
||||
{
|
||||
if (_sdkScript != null)
|
||||
{
|
||||
return _sdkScript;
|
||||
}
|
||||
|
||||
using var stream = typeof(WebView2InputBridge).Assembly.GetManifestResourceStream(SdkResourceName)
|
||||
?? throw new InvalidOperationException($"找不到嵌入资源 {SdkResourceName}");
|
||||
using var reader = new StreamReader(stream);
|
||||
return _sdkScript = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 页面 SDK 的状态快照
|
||||
/// </summary>
|
||||
/// <param name="RtcDataChannelState">RTC 数据通道状态,open 时输入才能发往云端</param>
|
||||
/// <param name="GameDataStarted">游戏数据通道是否已开始,即已进入游戏画面</param>
|
||||
/// <param name="Error">SDK 未注入、页面未加载到游戏或查询失败时的原因</param>
|
||||
public sealed record WebSdkStatus(string? RtcDataChannelState, bool? GameDataStarted, string? Error)
|
||||
{
|
||||
public bool IsReady => RtcDataChannelState == "open" && GameDataStarted == true;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道:包装 PostMessageSimulator,向游戏窗口投递消息。
|
||||
/// 游戏不在前台时,每次操作前先补发 WM_ACTIVATE。
|
||||
/// 不支持相对移动、中键、侧键、滚轮(warn 后忽略)
|
||||
/// </summary>
|
||||
internal sealed class PostMessageChannel : InputChannelBase
|
||||
{
|
||||
private readonly IntPtr _hWnd;
|
||||
private readonly PostMessageSimulator? _simulator;
|
||||
|
||||
/// <summary>
|
||||
/// 后续点击使用的客户区坐标。未调用过 MoveMouseTo 时沿用原实现的 (16,16)
|
||||
/// </summary>
|
||||
private Point _pointer = new(16, 16);
|
||||
|
||||
public PostMessageChannel(IntPtr hWnd)
|
||||
{
|
||||
_hWnd = hWnd;
|
||||
_simulator = hWnd == IntPtr.Zero ? null : new PostMessageSimulator(hWnd);
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyDown(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnKeyUp(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyUp(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnKeyPress(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyPress(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
if (!IsSupported(button) || !TryPrepare("鼠标"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var (x, y) = (_pointer.X, _pointer.Y);
|
||||
_ = (button, down) switch
|
||||
{
|
||||
(InputMouseButton.Left, true) => _simulator!.LeftButtonDown(x, y),
|
||||
(InputMouseButton.Left, false) => _simulator!.LeftButtonUp(x, y),
|
||||
(InputMouseButton.Right, true) => _simulator!.RightButtonDown(x, y),
|
||||
_ => _simulator!.RightButtonUp(x, y),
|
||||
};
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
if (!IsSupported(button) || !TryPrepare("鼠标"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = button == InputMouseButton.Left
|
||||
? _simulator!.LeftButtonClick(_pointer.X, _pointer.Y)
|
||||
: _simulator!.RightButtonClick(_pointer.X, _pointer.Y);
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => WarnUnsupported("后台相对移动 MoveMouseBy");
|
||||
|
||||
/// <summary>
|
||||
/// 换算成客户区坐标,记为后续点击的位置,不移动真实光标
|
||||
/// </summary>
|
||||
protected override void OnMoveTo(double absX, double absY)
|
||||
{
|
||||
if (_simulator is null)
|
||||
{
|
||||
WarnUnsupported("未绑定游戏窗口时的后台鼠标");
|
||||
return;
|
||||
}
|
||||
|
||||
var screen = PrimaryScreen.WorkingArea;
|
||||
var point = new POINT(
|
||||
(int)Math.Round(absX * screen.Width / 65535d),
|
||||
(int)Math.Round(absY * screen.Height / 65535d));
|
||||
if (!User32.ScreenToClient(_hWnd, ref point))
|
||||
{
|
||||
WarnUnsupported("后台鼠标坐标换算");
|
||||
return;
|
||||
}
|
||||
|
||||
_pointer = new Point(point.X, point.Y);
|
||||
}
|
||||
|
||||
protected override void OnScroll(int clicks) => WarnUnsupported("后台滚轮 VerticalScroll");
|
||||
|
||||
private bool IsSupported(InputMouseButton button)
|
||||
{
|
||||
if (button is InputMouseButton.Left or InputMouseButton.Right)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
WarnUnsupported($"后台鼠标键 {button}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否绑定了窗口,游戏不在前台时补发 WM_ACTIVATE
|
||||
/// </summary>
|
||||
private bool TryPrepare(string operation)
|
||||
{
|
||||
if (_simulator is null)
|
||||
{
|
||||
WarnUnsupported($"未绑定游戏窗口时的后台{operation}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (User32.GetForegroundWindow() != _hWnd)
|
||||
{
|
||||
_simulator.Activate();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using Fischless.WindowsInput;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// 前台通道:包装 Simulation.SendInput(Fischless.WindowsInput)
|
||||
/// </summary>
|
||||
internal sealed class SendInputChannel : InputChannelBase
|
||||
{
|
||||
private static InputSimulator Input => Simulation.SendInput;
|
||||
|
||||
// 扩展标志按真实键盘判断(见 ExtendedKeys):左 Alt 等不带,避免被识别成右 Alt;方向键等带,避免被识别成小键盘按键。
|
||||
// 不使用 Fischless 的自动判断,它把左 Alt 与泛指的 Alt / Ctrl 也算作扩展键
|
||||
protected override void OnKeyDown(User32.VK key) => Input.Keyboard.KeyDown(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => Input.Keyboard.KeyUp(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnKeyPress(User32.VK key) => Input.Keyboard.KeyPress(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
var mouse = Input.Mouse;
|
||||
switch (button)
|
||||
{
|
||||
case InputMouseButton.Left:
|
||||
_ = down ? mouse.LeftButtonDown() : mouse.LeftButtonUp();
|
||||
break;
|
||||
case InputMouseButton.Right:
|
||||
_ = down ? mouse.RightButtonDown() : mouse.RightButtonUp();
|
||||
break;
|
||||
case InputMouseButton.Middle:
|
||||
_ = down ? mouse.MiddleButtonDown() : mouse.MiddleButtonUp();
|
||||
break;
|
||||
case InputMouseButton.X1:
|
||||
_ = down ? mouse.XButtonDown(0x0001) : mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
case InputMouseButton.X2:
|
||||
_ = down ? mouse.XButtonDown(0x0002) : mouse.XButtonUp(0x0002);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
var mouse = Input.Mouse;
|
||||
switch (button)
|
||||
{
|
||||
case InputMouseButton.Left:
|
||||
mouse.LeftButtonClick();
|
||||
break;
|
||||
case InputMouseButton.Right:
|
||||
mouse.RightButtonClick();
|
||||
break;
|
||||
case InputMouseButton.Middle:
|
||||
mouse.MiddleButtonClick();
|
||||
break;
|
||||
case InputMouseButton.X1:
|
||||
mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
case InputMouseButton.X2:
|
||||
mouse.XButtonClick(0x0002);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => Input.Mouse.MoveMouseBy(dx, dy);
|
||||
|
||||
protected override void OnMoveTo(double absX, double absY) => Input.Mouse.MoveMouseTo(absX, absY);
|
||||
|
||||
protected override void OnScroll(int clicks) => Input.Mouse.VerticalScroll(clicks);
|
||||
|
||||
/// <summary>
|
||||
/// 与原 Simulation.IsKeyDown 一致,查询系统的实际按键状态
|
||||
/// </summary>
|
||||
public override bool IsKeyDown(User32.VK key) => Simulation.IsKeyDown(key);
|
||||
|
||||
/// <summary>
|
||||
/// 按记录抬起,再用 Simulation.ReleaseAllKey 兜底(与原 Simulation.ReleaseAllKey 行为一致)
|
||||
/// </summary>
|
||||
public override void ReleaseAll()
|
||||
{
|
||||
base.ReleaseAll();
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// Windows 键鼠后端:前台 SendInput,后台 PostMessage。两路总是同时可用
|
||||
/// </summary>
|
||||
public sealed class Win32InputBackend : IInputBackend
|
||||
{
|
||||
/// <param name="hWnd">游戏窗口句柄。为 IntPtr.Zero 时后台通道的所有操作都 warn</param>
|
||||
public Win32InputBackend(IntPtr hWnd)
|
||||
{
|
||||
Foreground = new SendInputChannel();
|
||||
Background = new PostMessageChannel(hWnd);
|
||||
}
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.Win32;
|
||||
|
||||
public IInputChannel Foreground { get; }
|
||||
|
||||
public IInputChannel Background { get; }
|
||||
|
||||
public void ReleaseAll()
|
||||
{
|
||||
Background.ReleaseAll();
|
||||
Foreground.ReleaseAll();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 一组可以整体切换的输入输出:Win32 (SendInput + PostMessage)、WebSdk、Gamepad
|
||||
/// </summary>
|
||||
public interface IInputBackend : IDisposable
|
||||
{
|
||||
InputBackendKind Kind { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 前台通道
|
||||
/// </summary>
|
||||
IInputChannel Foreground { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道。WebSdk / Gamepad 没有前后台之分,与 <see cref="Foreground"/> 是同一实例
|
||||
/// </summary>
|
||||
IInputChannel Background { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 释放所有通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
void ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 输入通道:后端内部的一路输出(前台或后台)
|
||||
/// </summary>
|
||||
public interface IInputChannel
|
||||
{
|
||||
IKeyboardInput Keyboard { get; }
|
||||
|
||||
IMouseInput Mouse { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 模拟游戏动作,按键由用户的键位配置决定
|
||||
/// </summary>
|
||||
IInputChannel SimulateAction(GIActions action, KeyType type = KeyType.KeyPress);
|
||||
|
||||
/// <summary>
|
||||
/// 按键是否处于按下状态,含鼠标键 VK_LBUTTON 等
|
||||
/// </summary>
|
||||
bool IsKeyDown(User32.VK key);
|
||||
|
||||
IInputChannel Sleep(int ms);
|
||||
|
||||
/// <summary>
|
||||
/// 释放本通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
void ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 键盘输入。传入鼠标键 VK(VK_LBUTTON、VK_RBUTTON、VK_MBUTTON、VK_XBUTTON1、VK_XBUTTON2)时按对应鼠标键处理
|
||||
/// </summary>
|
||||
public interface IKeyboardInput
|
||||
{
|
||||
IKeyboardInput KeyDown(User32.VK key);
|
||||
|
||||
IKeyboardInput KeyUp(User32.VK key);
|
||||
|
||||
IKeyboardInput KeyPress(User32.VK key);
|
||||
|
||||
IKeyboardInput Sleep(int ms);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 鼠标输入。方法名与 Fischless.WindowsInput.IMouseSimulator 保持一致
|
||||
/// </summary>
|
||||
public interface IMouseInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 相对移动(视角控制)
|
||||
/// </summary>
|
||||
IMouseInput MoveMouseBy(int dx, int dy);
|
||||
|
||||
/// <summary>
|
||||
/// 绝对定位。与 Fischless 相同:桌面绝对坐标,按主屏幕归一化到 0~65535。
|
||||
/// 是否是 1080P 坐标由调用方(Region 体系)换算,输入层不感知游戏分辨率
|
||||
/// </summary>
|
||||
IMouseInput MoveMouseTo(double absX, double absY);
|
||||
|
||||
IMouseInput LeftButtonDown();
|
||||
|
||||
IMouseInput LeftButtonUp();
|
||||
|
||||
IMouseInput LeftButtonClick();
|
||||
|
||||
IMouseInput RightButtonDown();
|
||||
|
||||
IMouseInput RightButtonUp();
|
||||
|
||||
IMouseInput RightButtonClick();
|
||||
|
||||
IMouseInput MiddleButtonDown();
|
||||
|
||||
IMouseInput MiddleButtonUp();
|
||||
|
||||
IMouseInput MiddleButtonClick();
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonDown(int buttonId);
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonUp(int buttonId);
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonClick(int buttonId);
|
||||
|
||||
IMouseInput VerticalScroll(int scrollAmountInClicks);
|
||||
|
||||
IMouseInput Sleep(int ms);
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 输入通道基类。
|
||||
/// 一个实例同时实现通道、键盘、鼠标三个接口,<see cref="Keyboard"/> 与 <see cref="Mouse"/> 都返回自身。
|
||||
/// 负责:按下状态记录、GIActions 默认映射、鼠标键 VK 转发、不支持操作的限频 warn。
|
||||
/// 子类只需实现 On* 原子操作。
|
||||
/// </summary>
|
||||
public abstract class InputChannelBase : IInputChannel, IKeyboardInput, IMouseInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 同一种不支持的操作在此时间内只打一次 warn
|
||||
/// </summary>
|
||||
private const long WarnIntervalMs = 10_000;
|
||||
|
||||
private static ILogger? _logger;
|
||||
|
||||
private readonly object _pressedLock = new();
|
||||
private readonly HashSet<User32.VK> _pressed = [];
|
||||
private readonly ConcurrentDictionary<string, long> _lastWarnTicks = new();
|
||||
|
||||
protected static ILogger Logger => _logger ??= App.GetLogger<InputChannelBase>();
|
||||
|
||||
public IKeyboardInput Keyboard => this;
|
||||
|
||||
public IMouseInput Mouse => this;
|
||||
|
||||
#region 子类实现的原子操作
|
||||
|
||||
protected abstract void OnKeyDown(User32.VK key);
|
||||
|
||||
protected abstract void OnKeyUp(User32.VK key);
|
||||
|
||||
/// <summary>
|
||||
/// 默认为按下 + 抬起,子类可覆写以保持各自的时序
|
||||
/// </summary>
|
||||
protected virtual void OnKeyPress(User32.VK key)
|
||||
{
|
||||
OnKeyDown(key);
|
||||
OnKeyUp(key);
|
||||
}
|
||||
|
||||
protected abstract void OnMouseButton(InputMouseButton button, bool down);
|
||||
|
||||
/// <summary>
|
||||
/// 默认为按下 + 抬起,子类可覆写以保持各自的时序
|
||||
/// </summary>
|
||||
protected virtual void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
OnMouseButton(button, true);
|
||||
OnMouseButton(button, false);
|
||||
}
|
||||
|
||||
protected abstract void OnMoveBy(int dx, int dy);
|
||||
|
||||
protected abstract void OnMoveTo(double absX, double absY);
|
||||
|
||||
protected abstract void OnScroll(int clicks);
|
||||
|
||||
#endregion
|
||||
|
||||
#region IInputChannel
|
||||
|
||||
public virtual IInputChannel SimulateAction(GIActions action, KeyType type = KeyType.KeyPress)
|
||||
{
|
||||
var key = action.ToActionKey();
|
||||
if (key is KeyId.None or KeyId.Unknown)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
// KeyId 的鼠标键取值与 VK 一致,鼠标键由 Keyboard 接口转发到鼠标
|
||||
var vk = key.ToVK();
|
||||
switch (type)
|
||||
{
|
||||
case KeyType.KeyPress:
|
||||
KeyPress(vk);
|
||||
break;
|
||||
case KeyType.KeyDown:
|
||||
KeyDown(vk);
|
||||
break;
|
||||
case KeyType.KeyUp:
|
||||
KeyUp(vk);
|
||||
break;
|
||||
case KeyType.Hold:
|
||||
KeyDown(vk);
|
||||
Thread.Sleep(1000);
|
||||
KeyUp(vk);
|
||||
break;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public virtual bool IsKeyDown(User32.VK key)
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
return _pressed.Contains(key);
|
||||
}
|
||||
}
|
||||
|
||||
IInputChannel IInputChannel.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按记录逐个抬起。单个按键失败不影响其余按键
|
||||
/// </summary>
|
||||
public virtual void ReleaseAll()
|
||||
{
|
||||
foreach (var key in TakePressedKeys())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
OnMouseButton(button, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
OnKeyUp(key);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogDebug(e, "释放按键 {Key} 失败", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IKeyboardInput
|
||||
|
||||
public IKeyboardInput KeyDown(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonDown(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
OnKeyDown(key);
|
||||
SetPressed(key, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IKeyboardInput KeyUp(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonUp(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
SetPressed(key, false);
|
||||
OnKeyUp(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IKeyboardInput KeyPress(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonClick(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
SetPressed(key, false);
|
||||
OnKeyPress(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
IKeyboardInput IKeyboardInput.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IMouseInput
|
||||
|
||||
public IMouseInput MoveMouseBy(int dx, int dy)
|
||||
{
|
||||
OnMoveBy(dx, dy);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMouseInput MoveMouseTo(double absX, double absY)
|
||||
{
|
||||
OnMoveTo(absX, absY);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMouseInput LeftButtonDown() => ButtonDown(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput LeftButtonUp() => ButtonUp(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput LeftButtonClick() => ButtonClick(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput RightButtonDown() => ButtonDown(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput RightButtonUp() => ButtonUp(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput RightButtonClick() => ButtonClick(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput MiddleButtonDown() => ButtonDown(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput MiddleButtonUp() => ButtonUp(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput MiddleButtonClick() => ButtonClick(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput XButtonDown(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonDown(b) : this;
|
||||
|
||||
public IMouseInput XButtonUp(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonUp(b) : this;
|
||||
|
||||
public IMouseInput XButtonClick(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonClick(b) : this;
|
||||
|
||||
public IMouseInput VerticalScroll(int scrollAmountInClicks)
|
||||
{
|
||||
OnScroll(scrollAmountInClicks);
|
||||
return this;
|
||||
}
|
||||
|
||||
IMouseInput IMouseInput.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 辅助
|
||||
|
||||
/// <summary>
|
||||
/// 不支持的操作:限频打 warn 后直接忽略
|
||||
/// </summary>
|
||||
protected void WarnUnsupported(string operation)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var last = _lastWarnTicks.GetOrAdd(operation, long.MinValue);
|
||||
if (last != long.MinValue && now - last < WarnIntervalMs)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_lastWarnTicks[operation] = now;
|
||||
Logger.LogWarning("[{Channel}] 不支持的输入操作已忽略:{Operation}", GetType().Name, operation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取出并清空按下记录
|
||||
/// </summary>
|
||||
protected IReadOnlyList<User32.VK> TakePressedKeys()
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
var keys = _pressed.ToList();
|
||||
_pressed.Clear();
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
|
||||
protected static bool TryGetMouseButton(User32.VK key, out InputMouseButton button)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case User32.VK.VK_LBUTTON:
|
||||
button = InputMouseButton.Left;
|
||||
return true;
|
||||
case User32.VK.VK_RBUTTON:
|
||||
button = InputMouseButton.Right;
|
||||
return true;
|
||||
case User32.VK.VK_MBUTTON:
|
||||
button = InputMouseButton.Middle;
|
||||
return true;
|
||||
case User32.VK.VK_XBUTTON1:
|
||||
button = InputMouseButton.X1;
|
||||
return true;
|
||||
case User32.VK.VK_XBUTTON2:
|
||||
button = InputMouseButton.X2;
|
||||
return true;
|
||||
default:
|
||||
button = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected static User32.VK ToVirtualKey(InputMouseButton button) => button switch
|
||||
{
|
||||
InputMouseButton.Left => User32.VK.VK_LBUTTON,
|
||||
InputMouseButton.Right => User32.VK.VK_RBUTTON,
|
||||
InputMouseButton.Middle => User32.VK.VK_MBUTTON,
|
||||
InputMouseButton.X1 => User32.VK.VK_XBUTTON1,
|
||||
InputMouseButton.X2 => User32.VK.VK_XBUTTON2,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(button), button, null),
|
||||
};
|
||||
|
||||
private bool TryGetXButton(int buttonId, out InputMouseButton button)
|
||||
{
|
||||
switch (buttonId)
|
||||
{
|
||||
case 1:
|
||||
button = InputMouseButton.X1;
|
||||
return true;
|
||||
case 2:
|
||||
button = InputMouseButton.X2;
|
||||
return true;
|
||||
default:
|
||||
button = default;
|
||||
WarnUnsupported($"侧键编号 {buttonId}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonDown(InputMouseButton button)
|
||||
{
|
||||
OnMouseButton(button, true);
|
||||
SetPressed(ToVirtualKey(button), true);
|
||||
return this;
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonUp(InputMouseButton button)
|
||||
{
|
||||
SetPressed(ToVirtualKey(button), false);
|
||||
OnMouseButton(button, false);
|
||||
return this;
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonClick(InputMouseButton button)
|
||||
{
|
||||
SetPressed(ToVirtualKey(button), false);
|
||||
OnMouseClick(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
private void SetPressed(User32.VK key, bool pressed)
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
if (pressed)
|
||||
{
|
||||
_pressed.Add(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
_pressed.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 可整体切换的输入后端
|
||||
/// </summary>
|
||||
public enum InputBackendKind
|
||||
{
|
||||
/// <summary>
|
||||
/// Windows 键鼠:前台 SendInput + 后台 PostMessage
|
||||
/// </summary>
|
||||
Win32,
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版 JS SDK
|
||||
/// </summary>
|
||||
WebSdk,
|
||||
|
||||
/// <summary>
|
||||
/// 手柄(预留)
|
||||
/// </summary>
|
||||
Gamepad,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 输入层内部使用的鼠标按键。
|
||||
/// 不复用 WPF 的 System.Windows.Input.MouseButton 与 Fischless 的 MouseButton,避免重名
|
||||
/// </summary>
|
||||
public enum InputMouseButton
|
||||
{
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
X1,
|
||||
X2,
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 模拟输入的统一入口。
|
||||
/// 业务代码只通过这里取通道,不直接使用 Simulation / PostMessageSimulator 等原始实现。
|
||||
/// <para>
|
||||
/// 通道引用只能在单个任务内持有;跨任务存活的对象(静态字段、DI 单例、Trigger 等)必须每次从这里取,
|
||||
/// 否则后端切换后引用会过期。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static class InputHub
|
||||
{
|
||||
private static readonly object AttachLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 未 Attach 时:未绑定窗口的 Win32 后端,前台可用,后台 warn
|
||||
/// </summary>
|
||||
private static IInputBackend _backend = new Win32InputBackend(IntPtr.Zero);
|
||||
|
||||
public static IInputBackend Backend => Volatile.Read(ref _backend);
|
||||
|
||||
public static IInputChannel Foreground => Backend.Foreground;
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道。WebSdk / Gamepad 后端下与 <see cref="Foreground"/> 相同
|
||||
/// </summary>
|
||||
public static IInputChannel Background => Backend.Background;
|
||||
|
||||
/// <summary>
|
||||
/// 替换当前后端并释放旧后端。按键释放由停止流程显式处理,避免绑定新后端时释放全局按键。
|
||||
/// 只在没有任务运行时调用。
|
||||
/// (a,b)、c、d 之间的切换都通过它完成
|
||||
/// </summary>
|
||||
public static void Attach(IInputBackend backend)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(backend);
|
||||
lock (AttachLock)
|
||||
{
|
||||
var old = Backend;
|
||||
if (ReferenceEquals(old, backend))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _backend, backend);
|
||||
old.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放当前后端所有通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
public static void ReleaseAll() => Backend.ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制入口(业务侧)。
|
||||
/// 线程安全,所有方法只写数据并立即返回,不等待 UI;何时重绘由遮罩窗口自行决定。
|
||||
/// </summary>
|
||||
public interface IMaskWindowDrawingBoard
|
||||
{
|
||||
/// <summary>
|
||||
/// 整组替换。shapes 为 null 或空时等价于 <see cref="Clear"/>;内容与当前相同则不做任何事
|
||||
/// </summary>
|
||||
void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes);
|
||||
|
||||
void Clear(MaskWindowDrawingGroup group);
|
||||
|
||||
void ClearAll();
|
||||
}
|
||||
|
||||
public static class MaskWindowDrawingBoardExtensions
|
||||
{
|
||||
public static void Set(this IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group, MaskWindowDrawingShape shape)
|
||||
{
|
||||
board.Set(group, new[] { shape });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回一个作用域,Dispose 时清除该分组。用于"任务期间显示、结束即清"
|
||||
/// </summary>
|
||||
public static IDisposable Scope(this IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group)
|
||||
{
|
||||
return new MaskWindowDrawingScope(board, group);
|
||||
}
|
||||
|
||||
private sealed class MaskWindowDrawingScope(IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
board.Clear(group);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口宿主:唯一负责遮罩窗口的创建、显隐、置顶和跟随游戏窗口。
|
||||
/// View 层以外的代码只能通过它接触遮罩窗口。
|
||||
/// </summary>
|
||||
public interface IMaskWindowHost
|
||||
{
|
||||
/// <summary>
|
||||
/// UI 线程调用。首次调用时创建窗口,绑定游戏窗口并显示
|
||||
/// </summary>
|
||||
void Attach(nint gameHandle);
|
||||
|
||||
/// <summary>
|
||||
/// UI 线程调用。隐藏窗口并解除绑定,窗口实例保留复用
|
||||
/// </summary>
|
||||
void Detach();
|
||||
|
||||
/// <summary>
|
||||
/// UI 线程调用。关闭并释放窗口(程序退出时)
|
||||
/// </summary>
|
||||
void Close();
|
||||
|
||||
/// <summary>
|
||||
/// 任意线程调用,每帧可调,立即返回。宿主去重后决定显隐、置顶、跟随
|
||||
/// </summary>
|
||||
void ReportGameWindow(GameWindowState state);
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次应用到窗口上的状态,任意线程可读
|
||||
/// </summary>
|
||||
MaskWindowState State { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 可见性或位置变化后在 UI 线程触发,附属遮罩(HtmlMask 等)订阅
|
||||
/// </summary>
|
||||
event EventHandler<MaskWindowState>? StateChanged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 游戏窗口的状态。描述的是游戏窗口,不是遮罩窗口,所以不加 MaskWindow 前缀
|
||||
/// </summary>
|
||||
/// <param name="IsCapturing">截图器是否在运行</param>
|
||||
/// <param name="IsActive">游戏窗口是否在前台</param>
|
||||
/// <param name="IsMinimized">游戏窗口是否最小化</param>
|
||||
/// <param name="IsForegroundOwnedByBetterGiOrGame">前台窗口属于 BetterGI 自身或游戏进程(或者没有前台窗口)。按进程 ID 判断</param>
|
||||
/// <param name="Bounds">游戏捕获区域(屏幕物理像素),为空表示本次不更新位置</param>
|
||||
public readonly record struct GameWindowState(
|
||||
bool IsCapturing,
|
||||
bool IsActive,
|
||||
bool IsMinimized,
|
||||
bool IsForegroundOwnedByBetterGiOrGame,
|
||||
RECT Bounds);
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口的状态
|
||||
/// </summary>
|
||||
/// <param name="IsVisible">是否可见</param>
|
||||
/// <param name="Bounds">窗口位置(DIP)</param>
|
||||
public readonly record struct MaskWindowState(bool IsVisible, Rect Bounds);
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口地图点位区域的状态入口(业务侧)。线程安全,立即返回
|
||||
/// </summary>
|
||||
public interface IMaskWindowMapState
|
||||
{
|
||||
/// <summary>
|
||||
/// 字段为 null 表示不修改;多次调用合并为一个快照
|
||||
/// </summary>
|
||||
void Update(bool? isInBigMap = null, Rect? bigMapViewport = null, Rect? miniMapViewport = null);
|
||||
|
||||
/// <summary>
|
||||
/// 退出大地图并清空两个视口。在任务开始、地图遮罩关闭时调用
|
||||
/// </summary>
|
||||
void Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 地图点位区域的不可变快照
|
||||
/// </summary>
|
||||
/// <param name="IsInBigMap">是否在大地图界面</param>
|
||||
/// <param name="BigMapViewport">大地图视口(2048 级地图坐标),空矩形表示不显示</param>
|
||||
/// <param name="MiniMapViewport">小地图视口,空矩形表示不显示</param>
|
||||
public sealed record MaskWindowMapSnapshot(bool IsInBigMap, Rect BigMapViewport, Rect MiniMapViewport)
|
||||
{
|
||||
public static MaskWindowMapSnapshot Empty { get; } = new(false, default, default);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口渲染侧的读取接口,仅 MaskWindowViewModel 使用
|
||||
/// </summary>
|
||||
public interface IMaskWindowSnapshotSource<out T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 不可变快照,UI 线程直接读取,无需加锁
|
||||
/// </summary>
|
||||
T Current { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 可在任意线程触发,只表示"有新版本",由订阅方自行合并。回调里只能做 O(1) 的操作
|
||||
/// </summary>
|
||||
event Action? Changed;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制内容的存储。
|
||||
/// 业务线程写入不可变快照,UI 侧订阅 <see cref="Changed"/> 后合并拉取。
|
||||
/// </summary>
|
||||
public sealed class MaskWindowDrawingBoard : IMaskWindowDrawingBoard, IMaskWindowSnapshotSource<MaskWindowDrawingSnapshot>
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
|
||||
private ImmutableDictionary<string, MaskWindowDrawingEntry> _entries =
|
||||
ImmutableDictionary.Create<string, MaskWindowDrawingEntry>(StringComparer.Ordinal);
|
||||
|
||||
private MaskWindowDrawingSnapshot _current = MaskWindowDrawingSnapshot.Empty;
|
||||
|
||||
public MaskWindowDrawingSnapshot Current => Volatile.Read(ref _current);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes)
|
||||
{
|
||||
if (shapes == null || shapes.Count == 0)
|
||||
{
|
||||
Clear(group);
|
||||
return;
|
||||
}
|
||||
|
||||
// 拷贝一份,调用方之后再修改原列表也不会影响已存的内容
|
||||
var copy = shapes.ToArray();
|
||||
lock (_lock)
|
||||
{
|
||||
if (_entries.TryGetValue(group.Name, out var existing)
|
||||
&& existing.Group == group
|
||||
&& existing.Shapes.SequenceEqual(copy))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.SetItem(group.Name, new MaskWindowDrawingEntry(group, copy));
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Clear(MaskWindowDrawingGroup group)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_entries.ContainsKey(group.Name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.Remove(group.Name);
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_entries.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.Clear();
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private void PublishLocked()
|
||||
{
|
||||
var entries = _entries.IsEmpty ? Array.Empty<MaskWindowDrawingEntry>() : _entries.Values.ToArray();
|
||||
Volatile.Write(ref _current, new MaskWindowDrawingSnapshot(_current.Version + 1, entries));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
public static class MaskWindowDrawingConversions
|
||||
{
|
||||
/// <summary>
|
||||
/// 捕获像素坐标系下的 OpenCV 矩形转换为遮罩窗口绘制矩形。
|
||||
/// 只能用于坐标已经是整个游戏捕获区域的矩形;子区域内的坐标请用 Region.ToMaskWindowDrawingRect
|
||||
/// </summary>
|
||||
public static MaskWindowDrawingRect ToMaskWindowDrawingRect(this OpenCvSharp.Rect rect, System.Drawing.Pen? pen = null)
|
||||
{
|
||||
return new MaskWindowDrawingRect(
|
||||
new System.Windows.Rect(rect.X, rect.Y, rect.Width, rect.Height),
|
||||
MaskWindowDrawingStroke.FromPen(pen));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 绘制分组的类型,决定分组在遮罩窗口上的显示规则
|
||||
/// </summary>
|
||||
public enum MaskWindowDrawingKind
|
||||
{
|
||||
/// <summary>
|
||||
/// 识别结果(调试可视化):受「在遮罩上显示识别结果」开关和统一样式控制
|
||||
/// </summary>
|
||||
Recognition,
|
||||
|
||||
/// <summary>
|
||||
/// 功能提示(技能 CD、地脉 OCR 区域等):遮罩可见就显示,使用图形自带样式
|
||||
/// </summary>
|
||||
Feature,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 绘制分组。一组图形按 Name 整体替换,Kind 决定显示规则
|
||||
/// </summary>
|
||||
public readonly record struct MaskWindowDrawingGroup(string Name, MaskWindowDrawingKind Kind = MaskWindowDrawingKind.Recognition)
|
||||
{
|
||||
public static implicit operator MaskWindowDrawingGroup(string name) => new(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口上的图形。坐标统一使用游戏捕获区域的物理像素(与截图 Mat 相同)
|
||||
/// </summary>
|
||||
public abstract record MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingRect(Rect Bounds, MaskWindowDrawingStroke? Stroke = null) : MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingLine(Point From, Point To, MaskWindowDrawingStroke? Stroke = null) : MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingText(string Text, Point Origin, MaskWindowDrawingTextStyle? Style = null) : MaskWindowDrawingShape;
|
||||
|
||||
/// <summary>
|
||||
/// 线条样式。Thickness 为 DIP
|
||||
/// </summary>
|
||||
public readonly record struct MaskWindowDrawingStroke(Color Color, double Thickness = 2)
|
||||
{
|
||||
/// <summary>
|
||||
/// 兼容业务代码里现有的 System.Drawing.Pen(如 Pens.Lime、识别对象的 DrawOnWindowPen)
|
||||
/// </summary>
|
||||
public static MaskWindowDrawingStroke? FromPen(System.Drawing.Pen? pen)
|
||||
{
|
||||
if (pen == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var c = pen.Color;
|
||||
return new MaskWindowDrawingStroke(Color.FromArgb(c.A, c.R, c.G, c.B), pen.Width);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字样式。为 null 的字段使用 MaskWindowConfig 中的识别结果样式
|
||||
/// </summary>
|
||||
/// <param name="Foreground">文字颜色</param>
|
||||
/// <param name="FontSize">字号,单位为捕获像素</param>
|
||||
/// <param name="Background">不为空时在文字下方绘制圆角底色</param>
|
||||
/// <param name="Numeric">是否使用数字字体(Fgi)</param>
|
||||
public sealed record MaskWindowDrawingTextStyle(
|
||||
Color? Foreground = null,
|
||||
double? FontSize = null,
|
||||
Color? Background = null,
|
||||
bool Numeric = false);
|
||||
|
||||
/// <summary>
|
||||
/// 绘制快照中的一个分组
|
||||
/// </summary>
|
||||
public sealed record MaskWindowDrawingEntry(MaskWindowDrawingGroup Group, IReadOnlyList<MaskWindowDrawingShape> Shapes);
|
||||
|
||||
/// <summary>
|
||||
/// 绘制内容的不可变快照,UI 线程直接读取
|
||||
/// </summary>
|
||||
public sealed record MaskWindowDrawingSnapshot(long Version, IReadOnlyList<MaskWindowDrawingEntry> Entries)
|
||||
{
|
||||
public static MaskWindowDrawingSnapshot Empty { get; } = new(0, Array.Empty<MaskWindowDrawingEntry>());
|
||||
|
||||
public bool IsEmpty => Entries.Count == 0;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制层的全局样式,由 MaskWindowViewModel 从 MaskWindowConfig 的 Recognition* 配置合成
|
||||
/// </summary>
|
||||
/// <param name="OverrideRecognitionStroke">为 true 时 Recognition 分组忽略图形自带的线条样式,统一使用下面的线条样式</param>
|
||||
/// <param name="RectStroke">识别框的统一线条样式</param>
|
||||
/// <param name="LineStroke">识别线的统一线条样式</param>
|
||||
/// <param name="TextColor">文字未指定颜色时使用的颜色</param>
|
||||
/// <param name="TextFontSize">文字未指定字号时使用的字号,单位为捕获像素</param>
|
||||
public sealed record MaskWindowDrawingStyle(
|
||||
bool OverrideRecognitionStroke,
|
||||
MaskWindowDrawingStroke RectStroke,
|
||||
MaskWindowDrawingStroke LineStroke,
|
||||
Color TextColor,
|
||||
double TextFontSize)
|
||||
{
|
||||
public static MaskWindowDrawingStroke DefaultStroke { get; } = new(Colors.Red, 2);
|
||||
|
||||
public static MaskWindowDrawingStyle Default { get; } =
|
||||
new(false, DefaultStroke, DefaultStroke, Colors.Black, 36);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 地图点位区域状态的存储。写入时按字段合并,内容不变则不通知
|
||||
/// </summary>
|
||||
public sealed class MaskWindowMapState : IMaskWindowMapState, IMaskWindowSnapshotSource<MaskWindowMapSnapshot>
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private MaskWindowMapSnapshot _current = MaskWindowMapSnapshot.Empty;
|
||||
|
||||
public MaskWindowMapSnapshot Current => Volatile.Read(ref _current);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Update(bool? isInBigMap = null, Rect? bigMapViewport = null, Rect? miniMapViewport = null)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var next = new MaskWindowMapSnapshot(
|
||||
isInBigMap ?? _current.IsInBigMap,
|
||||
bigMapViewport ?? _current.BigMapViewport,
|
||||
miniMapViewport ?? _current.MiniMapViewport);
|
||||
if (next == _current)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _current, next);
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_current == MaskWindowMapSnapshot.Empty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _current, MaskWindowMapSnapshot.Empty);
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 空实现,用于单测以及不挂在截图区域下的 Region
|
||||
/// </summary>
|
||||
public sealed class NullMaskWindowDrawingBoard : IMaskWindowDrawingBoard
|
||||
{
|
||||
public static NullMaskWindowDrawingBoard Instance { get; } = new();
|
||||
|
||||
private NullMaskWindowDrawingBoard()
|
||||
{
|
||||
}
|
||||
|
||||
public void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes)
|
||||
{
|
||||
}
|
||||
|
||||
public void Clear(MaskWindowDrawingGroup group)
|
||||
{
|
||||
}
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,130 @@
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SharpDX.DirectInput;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Monitor;
|
||||
|
||||
public class DirectInputMonitor : IDisposable
|
||||
public sealed class DirectInputMonitor(ILogger<DirectInputMonitor> logger) : RelativeMouseInputMonitorBase(logger)
|
||||
{
|
||||
private bool _isRunning = true;
|
||||
private const int Interval = 5;
|
||||
private readonly object _captureLock = new();
|
||||
private CaptureContext? _captureContext;
|
||||
|
||||
private readonly Mouse _mouse;
|
||||
|
||||
public static int Interval = 5;
|
||||
|
||||
public DirectInputMonitor()
|
||||
protected override void StartCore()
|
||||
{
|
||||
var directInput = new DirectInput();
|
||||
_mouse = new Mouse(directInput);
|
||||
_mouse.SetCooperativeLevel(IntPtr.Zero, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
|
||||
}
|
||||
|
||||
public MouseState GetMouseState()
|
||||
{
|
||||
_mouse.Acquire();
|
||||
return _mouse.GetCurrentState();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
Task.Run(() =>
|
||||
Mouse? mouse = null;
|
||||
try
|
||||
{
|
||||
while (_isRunning)
|
||||
mouse = new Mouse(directInput);
|
||||
mouse.SetCooperativeLevel(
|
||||
IntPtr.Zero,
|
||||
CooperativeLevel.Background | CooperativeLevel.NonExclusive);
|
||||
mouse.Acquire();
|
||||
|
||||
var context = new CaptureContext(directInput, mouse);
|
||||
lock (_captureLock)
|
||||
{
|
||||
_mouse.Acquire();
|
||||
MouseState state = _mouse.GetCurrentState();
|
||||
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state, Kernel32.GetTickCount());
|
||||
Thread.Sleep(Interval); // 10ms, equivalent to CLOCKS_PER_SEC/100
|
||||
context.CaptureTask = Task.Run(() => Capture(context));
|
||||
_captureContext = context;
|
||||
}
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
mouse?.Dispose();
|
||||
directInput.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
protected override void StopCore()
|
||||
{
|
||||
_isRunning = false;
|
||||
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))
|
||||
{
|
||||
// 正常取消
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
private void Capture(CaptureContext context)
|
||||
{
|
||||
_mouse.Dispose();
|
||||
context.CaptureThreadId = Environment.CurrentManagedThreadId;
|
||||
try
|
||||
{
|
||||
while (!context.CancellationTokenSource.IsCancellationRequested)
|
||||
{
|
||||
context.Mouse.Acquire();
|
||||
MouseState state = context.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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 DirectInput DirectInput { get; } = directInput;
|
||||
|
||||
public Mouse Mouse { get; } = mouse;
|
||||
|
||||
public CancellationTokenSource CancellationTokenSource { get; } = new();
|
||||
|
||||
public Task? CaptureTask { get; set; }
|
||||
|
||||
public int CaptureThreadId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
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,6 +1,6 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Gma.System.MouseKeyHook;
|
||||
@@ -15,8 +15,10 @@ using Timer = System.Timers.Timer;
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
namespace BetterGenshinImpact.Core.Monitor;
|
||||
|
||||
public partial class MouseKeyMonitor
|
||||
public partial class MouseKeyMonitor : IDisposable
|
||||
{
|
||||
private bool _isSubscribed;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
@@ -64,23 +66,16 @@ public partial class MouseKeyMonitor
|
||||
return _globalHook;
|
||||
}
|
||||
}
|
||||
private nint _hWnd;
|
||||
public MouseKeyMonitor()
|
||||
{
|
||||
_spaceTimer.Elapsed += OnSpaceTimerElapsed;
|
||||
_fTimer.Elapsed += OnFTimerElapsed;
|
||||
}
|
||||
|
||||
public void Subscribe(nint gameHandle)
|
||||
{
|
||||
_hWnd = gameHandle;
|
||||
// Note: for the application hook, use the Hook.AppEvents() instead
|
||||
|
||||
if (!WinePlatformAddon.IsRunningOnWine) {
|
||||
GlobalHook.KeyDown += GlobalHookKeyDown;
|
||||
GlobalHook.KeyUp += GlobalHookKeyUp;
|
||||
GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
GlobalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
GlobalHook.MouseMoveExt += GlobalHookMouseMoveExt;
|
||||
GlobalHook.MouseWheelExt += GlobalHookMouseWheelExt;
|
||||
}
|
||||
TrySubscribeWinePolling();
|
||||
//_globalHook.KeyPress += GlobalHookKeyPress;
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
// 按键经 InputHub.Background 发往 TaskContext.Init 绑定的游戏窗口,gameHandle 与其相同
|
||||
|
||||
_pickUpKey = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToWinFormKeys();
|
||||
_pickUpKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToVK();
|
||||
@@ -90,17 +85,56 @@ public partial class MouseKeyMonitor
|
||||
_firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
var si = TaskContext.Instance().Config.MacroConfig.SpaceFireInterval;
|
||||
_spaceTimer.Interval = si;
|
||||
_spaceTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_releaseControlKeyCode); };
|
||||
|
||||
var fi = TaskContext.Instance().Config.MacroConfig.FFireInterval;
|
||||
_fTimer.Interval = fi;
|
||||
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_pickUpKeyCode); };
|
||||
|
||||
// 开关禁用时不装键鼠监听
|
||||
if (TaskContext.Instance().Config.DisableInputMonitor)
|
||||
{
|
||||
if (_isSubscribed) Unsubscribe();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_isSubscribed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Note: for the application hook, use the Hook.AppEvents() instead
|
||||
if (!WinePlatformAddon.IsRunningOnWine)
|
||||
{
|
||||
GlobalHook.KeyDown += GlobalHookKeyDown;
|
||||
GlobalHook.KeyUp += GlobalHookKeyUp;
|
||||
GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
GlobalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
GlobalHook.MouseMoveExt += GlobalHookMouseMoveExt;
|
||||
GlobalHook.MouseWheelExt += GlobalHookMouseWheelExt;
|
||||
}
|
||||
TrySubscribeWinePolling();
|
||||
//_globalHook.KeyPress += GlobalHookKeyPress;
|
||||
_isSubscribed = true;
|
||||
}
|
||||
|
||||
private void OnSpaceTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
InputHub.Background.Keyboard.KeyPress(_releaseControlKeyCode);
|
||||
}
|
||||
|
||||
private void OnFTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
InputHub.Background.Keyboard.KeyPress(_pickUpKeyCode);
|
||||
}
|
||||
|
||||
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, DateTime.UtcNow);
|
||||
|
||||
if (SystemControl.IsGenshinImpactActive())
|
||||
{
|
||||
ChatUiHotkeyGuard.PrimeFromChatKey(e.KeyCode);
|
||||
}
|
||||
|
||||
// 热键按下事件
|
||||
HotKeyDown(sender, e);
|
||||
@@ -138,7 +172,7 @@ public partial class MouseKeyMonitor
|
||||
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
|
||||
{
|
||||
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, Kernel32.GetTickCount());
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, DateTime.UtcNow);
|
||||
|
||||
// 热键松开事件
|
||||
HotKeyUp(sender, e);
|
||||
@@ -183,7 +217,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);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e, DateTime.UtcNow);
|
||||
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
@@ -193,7 +227,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);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e, DateTime.UtcNow);
|
||||
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
@@ -203,17 +237,27 @@ 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);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
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);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
public void Unsubscribe()
|
||||
{
|
||||
_spaceTimer.Stop();
|
||||
_fTimer.Stop();
|
||||
_firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
_firstFKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
if (!_isSubscribed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_globalHook != null && !WinePlatformAddon.IsRunningOnWine)
|
||||
{
|
||||
_globalHook.KeyDown -= GlobalHookKeyDown;
|
||||
@@ -229,5 +273,22 @@ public partial class MouseKeyMonitor
|
||||
if (WinePlatformAddon.IsRunningOnWine){
|
||||
DisposeWineAddon();
|
||||
}
|
||||
_isSubscribed = false;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Unsubscribe();
|
||||
_disposed = true;
|
||||
_spaceTimer.Elapsed -= OnSpaceTimerElapsed;
|
||||
_fTimer.Elapsed -= OnFTimerElapsed;
|
||||
_spaceTimer.Dispose();
|
||||
_fTimer.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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, "不支持的相对鼠标输入类型")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,9 @@ public static class OcrUtils
|
||||
/// 预处理速度比unsafe快5倍以上,且吃的资源还少
|
||||
/// </summary>
|
||||
/// <param name="inputImage">输入图像,若不是灰度图会转换</param>
|
||||
/// <param name="tensorMemoryOwner">tensor的Memory,用完需要释放</param>
|
||||
/// <param name="tensorMemoryOwnser">tensor的Memory,用完需要释放</param>
|
||||
/// <returns></returns>
|
||||
public static Tensor<float> ToTensorYapDnn(Mat inputImage, out IMemoryOwner<float> tensorMemoryOwner)
|
||||
public static Tensor<float> ToTensorYapDnn(Mat inputImage, out IMemoryOwner<float> tensorMemoryOwnser)
|
||||
{
|
||||
using var rt = new ResourcesTracker();
|
||||
Mat dst;
|
||||
@@ -40,10 +40,10 @@ public static class OcrUtils
|
||||
// 使用向量运算代替循环
|
||||
var blob = rt.T(CvDnn.BlobFromImage(padded, 1.0 / 255.0, default, default, false, false));
|
||||
var nCols = padded.Cols * padded.Rows;
|
||||
tensorMemoryOwner = MemoryPool<float>.Shared.Rent(nCols);
|
||||
tensorMemoryOwnser = MemoryPool<float>.Shared.Rent(nCols);
|
||||
// 内存复制,如果直接传指针构建的话速度还不如多复制一份
|
||||
blob.AsSpan<float>().CopyTo(tensorMemoryOwner.Memory.Span);
|
||||
return new DenseTensor<float>(tensorMemoryOwner.Memory[..nCols], [1, 1, 32, 384]);
|
||||
blob.AsSpan<float>().CopyTo(tensorMemoryOwnser.Memory.Span);
|
||||
return new DenseTensor<float>(tensorMemoryOwnser.Memory[..nCols], [1, 1, 32, 384]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -180,119 +180,6 @@ public static class OcrUtils
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从标签列表构建字符串→索引字典,供 Rec 模糊匹配使用。
|
||||
/// 索引从1开始(0为CTC空白符),空格字符为 labels.Count+1。
|
||||
/// </summary>
|
||||
/// <param name="labels">识别模型的标签列表</param>
|
||||
/// <param name="labelLengths">各标签的字符长度集合(降序排列,用于从长到短贪心匹配)</param>
|
||||
public static IReadOnlyDictionary<string, int> CreateLabelDict(
|
||||
IReadOnlyList<string> labels, out int[] labelLengths)
|
||||
{
|
||||
var dict = new Dictionary<string, int>();
|
||||
var lengths = new HashSet<int>();
|
||||
for (var i = 0; i < labels.Count; i++)
|
||||
{
|
||||
if (labels[i] == " ") continue;
|
||||
var len = labels[i].Length;
|
||||
if (len > 0) lengths.Add(len);
|
||||
dict[labels[i]] = i + 1;
|
||||
}
|
||||
// 空格字符对应索引 labels.Count + 1
|
||||
dict[" "] = labels.Count + 1;
|
||||
lengths.Add(1);
|
||||
// 降序:先尝试更长的标签
|
||||
labelLengths = lengths.OrderByDescending(x => x).ToArray();
|
||||
return dict;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据额外权重字典,创建与标签列表等长的权重数组(用于加权推理分数)。
|
||||
/// 未指定权重的标签默认为 1.0。
|
||||
/// </summary>
|
||||
public static float[] CreateWeights(
|
||||
Dictionary<string, float> extraWeights, IReadOnlyDictionary<string, int> labelDict, int labelCount)
|
||||
{
|
||||
var result = new float[labelCount + 2];
|
||||
Array.Fill(result, 1.0f);
|
||||
foreach (var (key, value) in extraWeights)
|
||||
{
|
||||
if (!labelDict.TryGetValue(key, out var index)) continue;
|
||||
if (index >= 0 && index < result.Length)
|
||||
{
|
||||
result[index] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将目标字符串映射为标签索引序列。
|
||||
/// 使用贪心从长到短匹配,无法映射的字符会被跳过。
|
||||
/// </summary>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <param name="labelDict">标签→索引字典(由 CreateLabelDict 生成)</param>
|
||||
/// <param name="labelLengths">标签长度集合,降序排列(由 CreateLabelDict 生成)</param>
|
||||
public static int[] MapStringToLabelIndices(
|
||||
string target,
|
||||
IReadOnlyDictionary<string, int> labelDict,
|
||||
int[] labelLengths)
|
||||
{
|
||||
var chars = target.ToCharArray();
|
||||
var targetIndices = new int[chars.Length];
|
||||
Array.Fill(targetIndices, -1);
|
||||
var index = 0;
|
||||
while (index < chars.Length)
|
||||
{
|
||||
var found = false;
|
||||
foreach (var labelLength in labelLengths)
|
||||
{
|
||||
if (index + labelLength > chars.Length) continue;
|
||||
var subStr = new string(chars, index, labelLength);
|
||||
if (!labelDict.TryGetValue(subStr, out var labelIndex)) continue;
|
||||
targetIndices[index] = labelIndex;
|
||||
index += labelLength;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if (!found) index++;
|
||||
}
|
||||
|
||||
return targetIndices.Where(x => x != -1).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态规划最大子序列匹配。
|
||||
/// 在 result 序列中找到 target 的最大置信度子序列匹配,返回归一化分数 (0~1)。
|
||||
/// </summary>
|
||||
/// <param name="result">OCR 输出的 (labelIndex, confidence) 序列</param>
|
||||
/// <param name="target">目标标签索引序列</param>
|
||||
/// <param name="availableCount">归一化分母(通常为 target.Length,得到每个目标字符的平均置信度)</param>
|
||||
public static double GetMaxScoreDp((int, float)[] result, int[] target, int availableCount)
|
||||
{
|
||||
if (target.Length == 0 || availableCount <= 0) return 0;
|
||||
|
||||
var dp = new double[target.Length + 1];
|
||||
dp[0] = 0;
|
||||
for (var j = 1; j <= target.Length; j++)
|
||||
dp[j] = -255d; // 不可达
|
||||
|
||||
foreach (var (index, confidence) in result)
|
||||
{
|
||||
// 逆序更新,避免同一 result 元素被多次使用
|
||||
for (var j = target.Length; j >= 1; j--)
|
||||
{
|
||||
if (index != target[j - 1]) continue;
|
||||
if (!(dp[j - 1] > -200)) continue; // 前序不可达
|
||||
var newSum = dp[j - 1] + confidence;
|
||||
if (newSum > dp[j]) dp[j] = newSum;
|
||||
}
|
||||
}
|
||||
|
||||
if (dp[target.Length] <= -200) return 0; // 无法完整匹配
|
||||
return dp[target.Length] / availableCount;
|
||||
}
|
||||
|
||||
public static Mat Tensor2Mat(Tensor<float> tensor)
|
||||
{
|
||||
var dimensions = tensor.Dimensions;
|
||||
|
||||
@@ -44,4 +44,14 @@ 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,26 +0,0 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
/// <summary>
|
||||
/// 基于 DP 模糊匹配的 OCR 服务接口,返回匹配置信度分数 (0~1)。
|
||||
/// 独立于 IOcrService,仅由支持模糊匹配的引擎实现。
|
||||
/// </summary>
|
||||
public interface IOcrMatchService
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用检测器定位文字区域后,对每个区域进行模糊匹配,返回最高置信度 (0~1)。
|
||||
/// </summary>
|
||||
/// <param name="mat">输入图像(推荐三通道 BGR)</param>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <returns>匹配置信度,0 表示完全不匹配,1 表示完全匹配</returns>
|
||||
double OcrMatch(Mat mat, string target);
|
||||
|
||||
/// <summary>
|
||||
/// 不使用检测器,直接对整张图像进行模糊匹配,返回置信度 (0~1)。
|
||||
/// </summary>
|
||||
/// <param name="mat">输入图像(推荐三通道 BGR)</param>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <returns>匹配置信度,0 表示完全不匹配,1 表示完全匹配</returns>
|
||||
double OcrMatchDirect(Mat mat, string target);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
@@ -17,29 +16,26 @@ public class OcrFactory : IDisposable
|
||||
|
||||
|
||||
public static IOcrService Paddle => App.ServiceProvider.GetRequiredService<OcrFactory>().PaddleOcr;
|
||||
private IOcrService PaddleOcr => _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
|
||||
|
||||
/// <summary>
|
||||
/// 获取支持模糊匹配的 OCR 服务。
|
||||
/// 若引擎原生支持 IOcrMatchService 则直接返回,否则回退到普通 OCR + 字符串相似度。
|
||||
/// 访问此属性会触发 Paddle 引擎的懒加载。
|
||||
/// </summary>
|
||||
public static IOcrMatchService PaddleMatch
|
||||
public IOcrService PaddleOcr
|
||||
{
|
||||
get
|
||||
{
|
||||
var factory = App.ServiceProvider.GetRequiredService<OcrFactory>();
|
||||
var service = factory.PaddleOcr;
|
||||
if (service is IOcrMatchService matchService)
|
||||
return matchService;
|
||||
var fallback = new OcrMatchFallbackService(service);
|
||||
return Interlocked.CompareExchange(ref factory._paddleOcrMatchFallback, fallback, null)
|
||||
?? fallback;
|
||||
lock (_serviceLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
return _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
|
||||
}
|
||||
}
|
||||
}
|
||||
private readonly object _serviceLock = new();
|
||||
private bool _disposed;
|
||||
private PaddleOcrService.PaddleOcrModelType? _activeModelType;
|
||||
public PaddleOcrService.PaddleOcrModelType ActiveModelType
|
||||
{
|
||||
get { lock (_serviceLock) return _activeModelType ?? ResolveModelType(); }
|
||||
}
|
||||
|
||||
private IOcrService? _paddleOcrService;
|
||||
private IOcrMatchService? _paddleOcrMatchFallback;
|
||||
private readonly ILogger<BgiOnnxFactory> _logger;
|
||||
private readonly OtherConfig.Ocr _config;
|
||||
|
||||
@@ -108,63 +104,58 @@ public class OcrFactory : IDisposable
|
||||
|
||||
private PaddleOcrService CreatePaddleOcrInstance()
|
||||
{
|
||||
var allowDuplicateChar = _config.AllowDuplicateChar;
|
||||
var threshold = (float)_config.PaddleOcrThreshold;
|
||||
var factory = App.ServiceProvider.GetRequiredService<BgiOnnxFactory>();
|
||||
_activeModelType = ResolveModelType();
|
||||
return new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(), _activeModelType);
|
||||
}
|
||||
|
||||
private PaddleOcrService.PaddleOcrModelType ResolveModelType()
|
||||
{
|
||||
return _config.PaddleOcrModelConfig switch
|
||||
{
|
||||
PaddleOcrModelConfig.V4Auto =>
|
||||
new PaddleOcrService(factory,
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V4,
|
||||
allowDuplicateChar, threshold),
|
||||
PaddleOcrModelConfig.V5Auto =>
|
||||
new PaddleOcrService(factory,
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V5,
|
||||
allowDuplicateChar, threshold),
|
||||
PaddleOcrModelConfig.V5 =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V5,
|
||||
PaddleOcrModelConfig.V6 =>
|
||||
PaddleOcrService.PaddleOcrModelType.V6,
|
||||
PaddleOcrModelConfig.V4 =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V4, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V4,
|
||||
PaddleOcrModelConfig.V4En =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V4En, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V4En,
|
||||
PaddleOcrModelConfig.V5Korean =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Korean, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Korean,
|
||||
PaddleOcrModelConfig.V5Latin =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Latin, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Latin,
|
||||
PaddleOcrModelConfig.V5Eslav =>
|
||||
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Eslav, allowDuplicateChar, threshold),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Eslav,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(_config.PaddleOcrModelConfig),
|
||||
_config.PaddleOcrModelConfig, "不支持的 Paddle OCR 模型配置")
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public Task Unload()
|
||||
{
|
||||
_paddleOcrMatchFallback = null;
|
||||
if (_paddleOcrService is not IDisposable disposable)
|
||||
lock (_serviceLock)
|
||||
{
|
||||
if (_paddleOcrService is IDisposable disposable) disposable.Dispose();
|
||||
_paddleOcrService = null;
|
||||
return Task.CompletedTask;
|
||||
_activeModelType = null;
|
||||
}
|
||||
try
|
||||
{
|
||||
disposable.Dispose();
|
||||
_paddleOcrService = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "卸载 OCR 服务时发生错误");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Unload().GetAwaiter().GetResult();
|
||||
lock (_serviceLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Unload().GetAwaiter().GetResult();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
/// <summary>
|
||||
/// 当 OCR 引擎不支持 IOcrMatchService 时的回退实现。
|
||||
/// 使用普通 OCR 识别文字后,通过字符串相似度进行匹配。
|
||||
/// </summary>
|
||||
public class OcrMatchFallbackService : IOcrMatchService
|
||||
{
|
||||
private readonly IOcrService _ocrService;
|
||||
|
||||
public OcrMatchFallbackService(IOcrService ocrService)
|
||||
{
|
||||
_ocrService = ocrService;
|
||||
}
|
||||
|
||||
public double OcrMatch(Mat mat, string target)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var ocrResult = _ocrService.OcrResult(mat);
|
||||
var score = ComputeBestTextSimilarity(ocrResult, target);
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"OcrMatchFallback 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
|
||||
return score;
|
||||
}
|
||||
|
||||
public double OcrMatchDirect(Mat mat, string target)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var text = _ocrService.OcrWithoutDetector(mat);
|
||||
var score = ComputeTextSimilarity(text, target);
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"OcrMatchDirectFallback 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
|
||||
return score;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在 OCR 结果的所有区域中找到与目标字符串最相似的分数。
|
||||
/// </summary>
|
||||
private static double ComputeBestTextSimilarity(OcrResult ocrResult, string target)
|
||||
{
|
||||
double bestScore = 0;
|
||||
foreach (var region in ocrResult.Regions)
|
||||
{
|
||||
var score = ComputeTextSimilarity(region.Text, target);
|
||||
if (score > bestScore) bestScore = score;
|
||||
if (score >= 1.0) break;
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算两个字符串的相似度 (0~1)。
|
||||
/// 优先检查子串包含关系,否则使用编辑距离计算。
|
||||
/// </summary>
|
||||
public static double ComputeTextSimilarity(string text, string target)
|
||||
{
|
||||
if (string.IsNullOrEmpty(target)) return 1.0;
|
||||
if (string.IsNullOrEmpty(text)) return 0.0;
|
||||
if (text.Contains(target, StringComparison.OrdinalIgnoreCase)) return 1.0;
|
||||
if (target.Contains(text, StringComparison.OrdinalIgnoreCase)) return (double)text.Length / target.Length;
|
||||
|
||||
var distance = LevenshteinDistance(text, target);
|
||||
var maxLen = Math.Max(text.Length, target.Length);
|
||||
return 1.0 - (double)distance / maxLen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算两个字符串之间的编辑距离(Levenshtein Distance)。
|
||||
/// </summary>
|
||||
public static int LevenshteinDistance(string s, string t)
|
||||
{
|
||||
var sLen = s.Length;
|
||||
var tLen = t.Length;
|
||||
var prev = new int[tLen + 1];
|
||||
var curr = new int[tLen + 1];
|
||||
|
||||
for (var j = 0; j <= tLen; j++)
|
||||
prev[j] = j;
|
||||
|
||||
for (var i = 1; i <= sLen; i++)
|
||||
{
|
||||
curr[0] = i;
|
||||
for (var j = 1; j <= tLen; j++)
|
||||
{
|
||||
var cost = s[i - 1] == t[j - 1] ? 0 : 1;
|
||||
curr[j] = Math.Min(Math.Min(curr[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);
|
||||
}
|
||||
|
||||
(prev, curr) = (curr, prev);
|
||||
}
|
||||
|
||||
return prev[tLen];
|
||||
}
|
||||
}
|
||||
@@ -65,4 +65,4 @@ public record OcrResult
|
||||
.OrderBy(x => x.Rect.Center.Y)
|
||||
.ThenBy(x => x.Rect.Center.X)
|
||||
.Select(x => x.Text));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
@@ -37,17 +33,6 @@ public static class OcrResultExtension
|
||||
return default;
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableList(this OcrResult result, Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(pen)).ToList();
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this OcrResult result, int offsetX, int offsetY,
|
||||
Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(offsetX, offsetY, pen)).ToList();
|
||||
}
|
||||
|
||||
public static PaddleOcrResultRect ToOcrResultRect(this OcrResultRegion region)
|
||||
{
|
||||
return new PaddleOcrResultRect(region.Rect.BoundingRect(), region.Text, region.Score);
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Clipper2Lib;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
internal readonly record struct PaddleOcrDetectionBox(Point2f[] Points, float Score)
|
||||
{
|
||||
public RotatedRect Rect => Cv2.MinAreaRect(Points);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PaddleOCR DBPostProcess 的 C# 实现。
|
||||
/// </summary>
|
||||
internal sealed class DbPostProcessor(
|
||||
float threshold,
|
||||
float boxThreshold,
|
||||
int maxCandidates,
|
||||
float unclipRatio,
|
||||
int minSize,
|
||||
bool useDilation)
|
||||
{
|
||||
public PaddleOcrDetectionBox[] Run(Mat pred, Size sourceSize)
|
||||
{
|
||||
using var bitmap = new Mat();
|
||||
Cv2.Compare(pred, threshold, bitmap, CmpType.GT);
|
||||
|
||||
using var contourSource = new Mat();
|
||||
if (useDilation)
|
||||
{
|
||||
using var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(2, 2));
|
||||
Cv2.Dilate(bitmap, contourSource, kernel);
|
||||
}
|
||||
else
|
||||
{
|
||||
bitmap.CopyTo(contourSource);
|
||||
}
|
||||
|
||||
var contours = contourSource.FindContoursAsArray(RetrievalModes.List,
|
||||
ContourApproximationModes.ApproxSimple);
|
||||
var boxes = new List<PaddleOcrDetectionBox>(Math.Min(contours.Length, maxCandidates));
|
||||
|
||||
foreach (var contour in contours.Take(maxCandidates))
|
||||
{
|
||||
var (points, shortSide) = GetMiniBox(contour.Select(point => new Point2f(point.X, point.Y)).ToArray());
|
||||
if (shortSide < minSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var score = GetScore(points, pred);
|
||||
if (score < boxThreshold)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var expandedPaths = Unclip(points, unclipRatio);
|
||||
if (expandedPaths.Count != 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var expandedPoints = expandedPaths[0]
|
||||
.Select(point => new Point2f(point.X, point.Y))
|
||||
.ToArray();
|
||||
var (expandedBox, expandedShortSide) = GetMiniBox(expandedPoints);
|
||||
if (expandedShortSide < minSize + 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var mappedBox = MapToSource(expandedBox, pred.Size(), sourceSize);
|
||||
if (!IsValidSourceBox(mappedBox, minSize))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
boxes.Add(new PaddleOcrDetectionBox(mappedBox, score));
|
||||
}
|
||||
|
||||
// Debug
|
||||
//{
|
||||
// using Mat demo = contourSource.CvtColor(ColorConversionCodes.GRAY2RGB);
|
||||
// demo.DrawContours(contours, -1, Scalar.Red);
|
||||
// Image(demo).Dump();
|
||||
//}
|
||||
return boxes.ToArray();
|
||||
}
|
||||
|
||||
private static (Point2f[] Points, float ShortSide) GetMiniBox(Point2f[] contour)
|
||||
{
|
||||
var rect = Cv2.MinAreaRect(contour);
|
||||
var points = rect.Points().OrderBy(point => point.X).ToArray();
|
||||
|
||||
var index1 = points[1].Y > points[0].Y ? 0 : 1;
|
||||
var index4 = points[1].Y > points[0].Y ? 1 : 0;
|
||||
var index2 = points[3].Y > points[2].Y ? 2 : 3;
|
||||
var index3 = points[3].Y > points[2].Y ? 3 : 2;
|
||||
|
||||
return ([points[index1], points[index2], points[index3], points[index4]],
|
||||
Math.Min(rect.Size.Width, rect.Size.Height));
|
||||
}
|
||||
|
||||
private static float GetScore(Point2f[] box, Mat pred)
|
||||
{
|
||||
var xmin = Math.Clamp((int)Math.Floor(box.Min(point => point.X)), 0, pred.Width - 1);
|
||||
var xmax = Math.Clamp((int)Math.Ceiling(box.Max(point => point.X)), 0, pred.Width - 1);
|
||||
var ymin = Math.Clamp((int)Math.Floor(box.Min(point => point.Y)), 0, pred.Height - 1);
|
||||
var ymax = Math.Clamp((int)Math.Ceiling(box.Max(point => point.Y)), 0, pred.Height - 1);
|
||||
|
||||
var localBox = box
|
||||
.Select(point => new Point((int)(point.X - xmin), (int)(point.Y - ymin)))
|
||||
.ToArray();
|
||||
using var mask = new Mat(ymax - ymin + 1, xmax - xmin + 1, MatType.CV_8UC1, Scalar.Black);
|
||||
mask.FillPoly([localBox], Scalar.White);
|
||||
using var cropped = pred[ymin, ymax + 1, xmin, xmax + 1];
|
||||
var score = (float)cropped.Mean(mask).Val0;
|
||||
|
||||
// Debug
|
||||
//{
|
||||
// using Mat cu = new Mat();
|
||||
// cropped.ConvertTo(cu, MatType.CV_8UC1, 255);
|
||||
// Util.HorizontalRun(true, Image(cu), Image(mask), score).Dump();
|
||||
//}
|
||||
return score;
|
||||
}
|
||||
|
||||
private static Paths64 Unclip(Point2f[] box, float ratio)
|
||||
{
|
||||
var area = Math.Abs(GetSignedArea(box));
|
||||
var perimeter = GetPerimeter(box);
|
||||
if (area <= 0 || perimeter <= 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var distance = area * ratio / perimeter;
|
||||
Path64 path = new(box
|
||||
.Select(point => new Point64((long)point.X, (long)point.Y)));
|
||||
return Clipper.InflatePaths([path], distance, JoinType.Round, EndType.Polygon, 2.0, 0.25);
|
||||
}
|
||||
|
||||
private static double GetSignedArea(Point2f[] points)
|
||||
{
|
||||
double area = 0;
|
||||
for (var i = 0; i < points.Length; i++)
|
||||
{
|
||||
var next = points[(i + 1) % points.Length];
|
||||
area += points[i].X * next.Y - next.X * points[i].Y;
|
||||
}
|
||||
|
||||
return area / 2.0;
|
||||
}
|
||||
|
||||
private static double GetPerimeter(Point2f[] points)
|
||||
{
|
||||
double perimeter = 0;
|
||||
for (var i = 0; i < points.Length; i++)
|
||||
{
|
||||
var next = points[(i + 1) % points.Length];
|
||||
var deltaX = points[i].X - next.X;
|
||||
var deltaY = points[i].Y - next.Y;
|
||||
perimeter += Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
}
|
||||
|
||||
return perimeter;
|
||||
}
|
||||
|
||||
private static Point2f[] MapToSource(Point2f[] box, Size predictionSize, Size sourceSize)
|
||||
{
|
||||
var scaleX = 1.0 * sourceSize.Width / predictionSize.Width;
|
||||
var scaleY = 1.0 * sourceSize.Height / predictionSize.Height;
|
||||
return box.Select(point => new Point2f(
|
||||
Math.Clamp((float)Math.Round(point.X * scaleX), 0, sourceSize.Width - 1),
|
||||
Math.Clamp((float)Math.Round(point.Y * scaleY), 0, sourceSize.Height - 1)))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static bool IsValidSourceBox(Point2f[] box, int minimumSize)
|
||||
{
|
||||
var width = (int)Math.Sqrt(
|
||||
Math.Pow(box[0].X - box[1].X, 2) + Math.Pow(box[0].Y - box[1].Y, 2));
|
||||
var height = (int)Math.Sqrt(
|
||||
Math.Pow(box[0].X - box[3].X, 2) + Math.Pow(box[0].Y - box[3].Y, 2));
|
||||
return width > minimumSize && height > minimumSize;
|
||||
}
|
||||
}
|
||||
@@ -8,112 +8,94 @@ using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgiOnnxFactory)
|
||||
public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxSessionFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly object _sessionLock = new();
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Gets or sets the maximum size for resizing the input image.</summary>
|
||||
public int? MaxSize { get; set; } = 960;
|
||||
/// <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 size for dilation during preprocessing.</summary>
|
||||
public int? DilatedSize { get; set; } = 2;
|
||||
/// <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 whether the official 2x2 dilation is enabled during post-processing.</summary>
|
||||
public bool UseDilation { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the score threshold for filtering out possible text boxes.</summary>
|
||||
public float? BoxScoreThreshold { get; set; } = 0.7f;
|
||||
public float BoxScoreThreshold { get; set; } = 0.6f;
|
||||
|
||||
/// <summary>Gets or sets the threshold to binarize the text region.</summary>
|
||||
public float? BoxThreshold { get; set; } = 0.3f;
|
||||
public float BoxThreshold { get; set; } = 0.3f;
|
||||
|
||||
/// <summary>Gets or sets the maximum number of contours processed by DBPostProcess.</summary>
|
||||
public int MaxCandidates { get; set; } = 1000;
|
||||
|
||||
/// <summary>Gets or sets the minimum size of the text boxes to be considered as valid.</summary>
|
||||
public int MinSize { get; set; } = 3;
|
||||
|
||||
/// <summary>Gets or sets the ratio for enlarging text boxes during post-processing.</summary>
|
||||
public float UnclipRatio { get; set; } = 2.0f;
|
||||
|
||||
public float UnclipRatio { get; set; } = 1.5f;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public RotatedRect[] Run(Mat src)
|
||||
{
|
||||
return RunBoxes(src).Select(box => box.Rect).ToArray();
|
||||
}
|
||||
|
||||
internal PaddleOcrDetectionBox[] RunBoxes(Mat src)
|
||||
{
|
||||
using var pred = RunRaw(src, out var resizedSize);
|
||||
using Mat cbuf = new();
|
||||
//OpenCvSharp.OpenCVException: 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols
|
||||
using var roi = pred[0, resizedSize.Height, 0, resizedSize.Width];
|
||||
roi.ConvertTo(cbuf, MatType.CV_8UC1, 255);
|
||||
using Mat dilated = new();
|
||||
using var binary = BoxThreshold != null
|
||||
? cbuf.Threshold((int)(BoxThreshold * 255), 255, ThresholdTypes.Binary)
|
||||
: cbuf;
|
||||
if (DilatedSize != null)
|
||||
{
|
||||
using var ones =
|
||||
Cv2.GetStructuringElement(MorphShapes.Rect, new Size(DilatedSize.Value, DilatedSize.Value));
|
||||
Cv2.Dilate(binary, dilated, ones);
|
||||
}
|
||||
else
|
||||
{
|
||||
Cv2.CopyTo(binary, dilated);
|
||||
}
|
||||
|
||||
var contours = dilated.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);
|
||||
// var size = src.Size();
|
||||
var scaleRate = 1.0 * src.Width / resizedSize.Width;
|
||||
|
||||
var rects = contours
|
||||
.Where(x => BoxScoreThreshold == null || GetScore(x, pred) > BoxScoreThreshold)
|
||||
.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) * scaleRate,
|
||||
(rect.Size.Height + UnclipRatio * minEdge) * scaleRate);
|
||||
RotatedRect largerRect = new(rect.Center * scaleRate, newSize, rect.Angle);
|
||||
return largerRect;
|
||||
})
|
||||
.OrderBy(v => v.Center.Y)
|
||||
.ThenBy(v => v.Center.X)
|
||||
.ToArray();
|
||||
//{
|
||||
// using Mat demo = dilated.CvtColor(ColorConversionCodes.GRAY2RGB);
|
||||
// demo.DrawContours(contours, -1, Scalar.Red);
|
||||
// Image(demo).Dump();
|
||||
//}
|
||||
return rects;
|
||||
var postProcessor = new DbPostProcessor(
|
||||
BoxThreshold,
|
||||
BoxScoreThreshold,
|
||||
MaxCandidates,
|
||||
UnclipRatio,
|
||||
MinSize,
|
||||
UseDilation);
|
||||
return postProcessor.Run(roi, src.Size());
|
||||
}
|
||||
|
||||
public Mat RunRaw(Mat src, out Size resizedSize)
|
||||
{
|
||||
var padded = src.Channels() switch
|
||||
Mat? converted = null;
|
||||
var input = src.Channels() switch
|
||||
{
|
||||
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
|
||||
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
|
||||
4 => converted = src.CvtColor(ColorConversionCodes.BGRA2BGR),
|
||||
1 => converted = src.CvtColor(ColorConversionCodes.GRAY2BGR),
|
||||
3 => src,
|
||||
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
|
||||
};
|
||||
// DetResizeForTest resize_long
|
||||
using (var resized = MatResize(padded, MaxSize))
|
||||
try
|
||||
{
|
||||
// 与 PaddleOCR Python DetResizeForTest 保持一致:
|
||||
// 1. h + w < 64 时先将图像补全到至少 32x32
|
||||
// 2. 按 limit_type 规则缩放,并将宽高分别对齐到 32 的倍数
|
||||
using var resized = MatResizeForDetection(input);
|
||||
resizedSize = new Size(resized.Width, resized.Height);
|
||||
padded = MatPadding32(resized);
|
||||
}
|
||||
|
||||
using (var _ = padded)
|
||||
{
|
||||
var inputTensor = OcrUtils.NormalizeToTensorDnn(padded, config.NormalizeImage.Scale,
|
||||
var inputTensor = OcrUtils.NormalizeToTensorDnn(resized, config.NormalizeImage.Scale,
|
||||
config.NormalizeImage.Mean, config.NormalizeImage.Std, out var owner);
|
||||
using (owner)
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
@@ -129,64 +111,79 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Mat MatPadding32(Mat src)
|
||||
{
|
||||
var size = src.Size();
|
||||
Size newSize = new(
|
||||
32 * Math.Ceiling(1.0 * size.Width / 32),
|
||||
32 * Math.Ceiling(1.0 * size.Height / 32));
|
||||
return src.CopyMakeBorder(0, newSize.Height - size.Height, 0, newSize.Width - size.Width, BorderTypes.Constant,
|
||||
Scalar.Black);
|
||||
finally
|
||||
{
|
||||
converted?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按比例缩放图像,保持长边不超过 maxSize。
|
||||
/// 按 PaddleOCR Python 的 DetResizeForTest 缩放图像:
|
||||
/// 超小图先补边,再按 max/min/resize_long 规则缩放,并对齐到 32 的倍数。
|
||||
/// </summary>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="maxSize"></param>
|
||||
/// <returns></returns>
|
||||
private static Mat MatResize(Mat src, int? maxSize)
|
||||
private Mat MatResizeForDetection(Mat src)
|
||||
{
|
||||
if (maxSize == null) return src.Clone();
|
||||
using var preprocessed = PrepareTinyImage(src);
|
||||
|
||||
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();
|
||||
var size = preprocessed.Size();
|
||||
var height = size.Height;
|
||||
var width = size.Width;
|
||||
|
||||
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}");
|
||||
}
|
||||
|
||||
return preprocessed.Resize(new Size(resizeWidth, resizeHeight));
|
||||
}
|
||||
|
||||
private static float GetScore(Point[] contour, Mat pred)
|
||||
private static Mat PrepareTinyImage(Mat src)
|
||||
{
|
||||
var width = pred.Width;
|
||||
var height = pred.Height;
|
||||
var boxX = contour.Select(v => v.X).ToArray();
|
||||
var boxY = contour.Select(v => v.Y).ToArray();
|
||||
if (src.Width + src.Height >= 64)
|
||||
{
|
||||
return src.Clone();
|
||||
}
|
||||
|
||||
var xmin = Math.Clamp(boxX.Min(), 0, width - 1);
|
||||
var xmax = Math.Clamp(boxX.Max(), 0, width - 1);
|
||||
var ymin = Math.Clamp(boxY.Min(), 0, height - 1);
|
||||
var ymax = Math.Clamp(boxY.Max(), 0, height - 1);
|
||||
var newHeight = Math.Max(32, src.Height);
|
||||
var newWidth = Math.Max(32, src.Width);
|
||||
var padded = new Mat(newHeight, newWidth, src.Type(), Scalar.Black);
|
||||
using var roi = padded[new Rect(0, 0, src.Width, src.Height)];
|
||||
src.CopyTo(roi);
|
||||
return padded;
|
||||
}
|
||||
|
||||
var rootPoints = contour
|
||||
.Select(v => new Point(v.X - xmin, v.Y - ymin))
|
||||
.ToArray();
|
||||
using Mat mask = new(ymax - ymin + 1, xmax - xmin + 1, MatType.CV_8UC1, Scalar.Black);
|
||||
mask.FillPoly(new[] { rootPoints }, new Scalar(1));
|
||||
|
||||
using var croppedMat = pred[ymin, ymax + 1, xmin, xmax + 1];
|
||||
var score = (float)croppedMat.Mean(mask).Val0;
|
||||
|
||||
// Debug
|
||||
//{
|
||||
// using Mat cu = new Mat();
|
||||
// croppedMat.ConvertTo(cu, MatType.CV_8UC1, 255);
|
||||
// Util.HorizontalRun(true, Image(cu), Image(mask), score).Dump();
|
||||
//}
|
||||
|
||||
return score;
|
||||
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")
|
||||
};
|
||||
}
|
||||
|
||||
public string GetConfigName => config.Name;
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ using Size = OpenCvSharp.Size;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
public class PaddleOcrService : IOcrService, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Usage:
|
||||
@@ -27,6 +27,11 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
private readonly Det _localDetModel;
|
||||
|
||||
private readonly Rec _localRecModel;
|
||||
private readonly object _inferenceLock = new();
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Gets or sets the official recognition score threshold used to discard low-confidence results.</summary>
|
||||
public float DropScore { get; set; } = 0.5f;
|
||||
|
||||
public record PaddleOcrModelType(
|
||||
BgiOnnxModel DetectionModel,
|
||||
@@ -101,14 +106,14 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
recognitionModel,
|
||||
recognitionVersion,
|
||||
recLabel ?? (() => DefaultRecLabelFunc(recognitionModel)),
|
||||
TestImagePath);
|
||||
preHeatImagePath ?? TestImagePath);
|
||||
}
|
||||
|
||||
public (Det, Rec) Build(BgiOnnxFactory onnxFactory, bool allowDuplicateChar = false, float threshold = 0.5f)
|
||||
public (Det, Rec) Build(BgiOnnxSessionFactory onnxFactory)
|
||||
{
|
||||
return (
|
||||
new Det(DetectionModel, DetectionVersion, onnxFactory),
|
||||
new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory, allowDuplicateChar, threshold: threshold));
|
||||
var detection = new Det(DetectionModel, DetectionVersion, onnxFactory);
|
||||
try { return (detection, new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory)); }
|
||||
catch { detection.Dispose(); throw; }
|
||||
}
|
||||
|
||||
public static readonly PaddleOcrModelType V4 = Create(
|
||||
@@ -130,6 +135,12 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, 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,
|
||||
@@ -240,20 +251,33 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType,
|
||||
bool allowDuplicateChar = false, float threshold = 0.5f)
|
||||
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType)
|
||||
: this(bgiOnnxFactory.ForCurrentRuntime(), modelType)
|
||||
{
|
||||
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory, allowDuplicateChar, threshold);
|
||||
}
|
||||
|
||||
internal PaddleOcrService(BgiOnnxSessionFactory bgiOnnxFactory, PaddleOcrModelType modelType)
|
||||
{
|
||||
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory);
|
||||
_localDetModel = modelsDet;
|
||||
_localRecModel = modelsRec;
|
||||
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
Debug.WriteLine(
|
||||
$"PaddleOcrService 预热完成,使用模型: {modelType.DetectionModel.Name} 和 {modelType.RecognitionModel.Name},结果: {preHeatResult.Text}");
|
||||
try
|
||||
{
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
Debug.WriteLine(
|
||||
$"PaddleOcrService 预热完成,使用模型: {modelType.DetectionModel.Name} 和 {modelType.RecognitionModel.Name},结果: {preHeatResult.Text}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
_localDetModel.Dispose();
|
||||
_localRecModel.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -269,8 +293,17 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
/// </summary>
|
||||
public OcrResult OcrResult(Mat mat)
|
||||
{
|
||||
using var converted = ConvertBgrIfNeeded(mat);
|
||||
return _OcrResult(converted ?? mat);
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (mat.Channels() == 4)
|
||||
{
|
||||
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
|
||||
return _OcrResult(mat3);
|
||||
}
|
||||
|
||||
return _OcrResult(mat);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -278,11 +311,15 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
/// </summary>
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
private OcrResult _OcrResult(Mat mat)
|
||||
@@ -290,7 +327,7 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, 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;
|
||||
}
|
||||
|
||||
@@ -299,18 +336,18 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
/// </summary>
|
||||
private OcrResult RunAll(Mat src, int recognizeBatchSize = 0)
|
||||
{
|
||||
var rects = _localDetModel.Run(src);
|
||||
Mat[] mats =
|
||||
rects.Select(rect =>
|
||||
{
|
||||
var roi = src[GetCropedRect(rect.BoundingRect(), src.Size())];
|
||||
return roi;
|
||||
})
|
||||
.ToArray();
|
||||
var boxes = SortBoxes(_localDetModel.RunBoxes(src));
|
||||
List<Mat> mats = new(boxes.Length);
|
||||
try
|
||||
{
|
||||
return new OcrResult(_localRecModel.Run(mats, recognizeBatchSize)
|
||||
.Select((result, i) => new OcrResultRegion(rects[i], result.Text, result.Score))
|
||||
foreach (var box in boxes)
|
||||
{
|
||||
mats.Add(GetRotateCropImage(src, box.Points));
|
||||
}
|
||||
|
||||
return new OcrResult(_localRecModel.Run(mats.ToArray(), recognizeBatchSize)
|
||||
.Select((result, i) => new OcrResultRegion(boxes[i].Rect, result.Text, result.Score))
|
||||
.Where(region => region.Score >= DropScore)
|
||||
.ToArray());
|
||||
}
|
||||
finally
|
||||
@@ -320,80 +357,95 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cropped region of the source image specified by the given rectangle, clamping the rectangle coordinates to
|
||||
/// the image bounds.
|
||||
/// 按 PaddleOCR 官方 get_rotate_crop_image 的方式对检测框执行透视裁剪。
|
||||
/// </summary>
|
||||
/// <param name="rect">The rectangle to crop.</param>
|
||||
/// <param name="size">The size of the source image.</param>
|
||||
/// <returns>The cropped rectangle.</returns>
|
||||
private static Rect GetCropedRect(Rect rect, Size size)
|
||||
/// <param name="src">原始图像。</param>
|
||||
/// <param name="points">按左上、右上、右下、左下排列的四个顶点。</param>
|
||||
/// <returns>透视变换后的文字图像。</returns>
|
||||
private static Mat GetRotateCropImage(Mat src, Point2f[] points)
|
||||
{
|
||||
return Rect.FromLTRB(
|
||||
Math.Clamp(rect.Left, 0, size.Width),
|
||||
Math.Clamp(rect.Top, 0, size.Height),
|
||||
Math.Clamp(rect.Right, 0, size.Width),
|
||||
Math.Clamp(rect.Bottom, 0, size.Height));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 若输入为 BGRA 则转换为 BGR,否则返回 null。
|
||||
/// 调用方需在使用后 Dispose 返回的 Mat(若非 null)。
|
||||
/// </summary>
|
||||
private static Mat? ConvertBgrIfNeeded(Mat mat)
|
||||
{
|
||||
return mat.Channels() == 4 ? mat.CvtColor(ColorConversionCodes.BGRA2BGR) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用检测器定位文字区域后,对每个区域进行 DP 模糊匹配,返回最高置信度 (0~1)。
|
||||
/// </summary>
|
||||
public double OcrMatch(Mat mat, string target)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
|
||||
using var src = ConvertBgrIfNeeded(mat);
|
||||
var bgr = src ?? mat;
|
||||
|
||||
var rects = _localDetModel.Run(bgr);
|
||||
Mat[] mats = rects.Select(rect =>
|
||||
if (points.Length != 4)
|
||||
{
|
||||
var roi = bgr[GetCropedRect(rect.BoundingRect(), bgr.Size())];
|
||||
return roi;
|
||||
}).ToArray();
|
||||
throw new ArgumentException("OCR detection box must contain exactly four points.", nameof(points));
|
||||
}
|
||||
|
||||
var cropWidth = (int)Math.Max(GetDistance(points[0], points[1]), GetDistance(points[2], points[3]));
|
||||
var cropHeight = (int)Math.Max(GetDistance(points[0], points[3]), GetDistance(points[1], points[2]));
|
||||
if (cropWidth <= 0 || cropHeight <= 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Invalid OCR crop size: {cropWidth}x{cropHeight}");
|
||||
}
|
||||
|
||||
Point2f[] destinationPoints =
|
||||
[
|
||||
new(0, 0),
|
||||
new(cropWidth, 0),
|
||||
new(cropWidth, cropHeight),
|
||||
new(0, cropHeight)
|
||||
];
|
||||
using var transform = Cv2.GetPerspectiveTransform(points, destinationPoints);
|
||||
var cropped = new Mat();
|
||||
try
|
||||
{
|
||||
var score = _localRecModel.RunMatch(mats, target);
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcrMatch 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
|
||||
return score;
|
||||
Cv2.WarpPerspective(src, cropped, transform, new Size(cropWidth, cropHeight),
|
||||
InterpolationFlags.Cubic, BorderTypes.Replicate);
|
||||
|
||||
if (cropped.Height * 1.0 / cropped.Width >= 1.5)
|
||||
{
|
||||
Cv2.Rotate(cropped, cropped, RotateFlags.Rotate90Counterclockwise);
|
||||
}
|
||||
|
||||
return cropped;
|
||||
}
|
||||
finally
|
||||
catch
|
||||
{
|
||||
foreach (var m in mats) m.Dispose();
|
||||
cropped.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不使用检测器,直接对整张图像进行 DP 模糊匹配,返回置信度 (0~1)。
|
||||
/// </summary>
|
||||
public double OcrMatchDirect(Mat mat, string target)
|
||||
private static double GetDistance(Point2f first, Point2f second)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var deltaX = first.X - second.X;
|
||||
var deltaY = first.Y - second.Y;
|
||||
return Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
}
|
||||
|
||||
using var src = ConvertBgrIfNeeded(mat);
|
||||
var bgr = src ?? mat;
|
||||
private static PaddleOcrDetectionBox[] SortBoxes(PaddleOcrDetectionBox[] source)
|
||||
{
|
||||
var boxes = source
|
||||
.OrderBy(box => box.Points[0].Y)
|
||||
.ThenBy(box => box.Points[0].X)
|
||||
.ToArray();
|
||||
|
||||
var score = _localRecModel.RunMatch([bgr], target);
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcrMatchDirect 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
|
||||
return score;
|
||||
for (var i = 0; i < boxes.Length - 1; i++)
|
||||
{
|
||||
for (var j = i; j >= 0; j--)
|
||||
{
|
||||
if (Math.Abs(boxes[j + 1].Points[0].Y - boxes[j].Points[0].Y) < 10
|
||||
&& boxes[j + 1].Points[0].X < boxes[j].Points[0].X)
|
||||
{
|
||||
(boxes[j], boxes[j + 1]) = (boxes[j + 1], boxes[j]);
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return boxes;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_localDetModel.Dispose();
|
||||
_localRecModel.Dispose();
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
try { _localDetModel.Dispose(); }
|
||||
finally { _localRecModel.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -406,4 +458,4 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
|
||||
return (this._localDetModel.GetConfigName, this._localRecModel.GetConfigName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,89 +2,66 @@ 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;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
/// <summary>
|
||||
/// OCR 识别器,支持标准文字识别和基于动态规划的模糊匹配。
|
||||
/// 模糊匹配将目标字符串与模型原始输出序列做子序列匹配,返回 0~1 的置信度分数,
|
||||
/// 比先识别再字符串匹配更能容忍 OCR 噪声。
|
||||
/// </summary>
|
||||
public class Rec : IDisposable
|
||||
public class Rec(
|
||||
BgiOnnxModel model,
|
||||
IReadOnlyList<string> labels,
|
||||
OcrVersionConfig config,
|
||||
BgiOnnxSessionFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly InferenceSession _session;
|
||||
private readonly IReadOnlyList<string> _labels;
|
||||
private readonly OcrVersionConfig _config;
|
||||
private readonly bool _allowDuplicateChar;
|
||||
private readonly float _threshold;
|
||||
private readonly object _sessionLock = new();
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
private bool _disposed;
|
||||
|
||||
// 模糊匹配相关字段
|
||||
|
||||
/// <summary>标签长度集合(降序),用于从长到短贪心匹配目标字符串</summary>
|
||||
private readonly int[] _labelLengths;
|
||||
|
||||
/// <summary>标签字符串→索引字典,索引从1开始(0为CTC空白符)</summary>
|
||||
private readonly IReadOnlyDictionary<string, int> _labelDict;
|
||||
|
||||
/// <summary>按标签索引的权重数组,用于加权推理分数;为 null 时不加权</summary>
|
||||
private readonly float[]? _weights;
|
||||
|
||||
/// <summary>目标字符串→标签索引序列的 LRU 缓存,加速重复查询</summary>
|
||||
private readonly CacheHelper.LruCache<string, int[]> _targetCache = new(128);
|
||||
|
||||
/// <summary>
|
||||
/// ONNX 推理输出的命名张量结构,替代匿名元组 (int[], float[])。
|
||||
/// </summary>
|
||||
private readonly record struct TensorResult(int Batch, int TimeSteps, int LabelCount, float[] Data);
|
||||
|
||||
public Rec(
|
||||
BgiOnnxModel model,
|
||||
IReadOnlyList<string> labels,
|
||||
OcrVersionConfig config,
|
||||
BgiOnnxFactory bgiOnnxFactory,
|
||||
bool allowDuplicateChar = false,
|
||||
Dictionary<string, float>? extraWeights = null,
|
||||
float threshold = 0.5f)
|
||||
{
|
||||
_session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
_labels = labels;
|
||||
_config = config;
|
||||
_allowDuplicateChar = allowDuplicateChar;
|
||||
_threshold = threshold;
|
||||
|
||||
_labelDict = OcrUtils.CreateLabelDict(labels, out var labelLengths);
|
||||
_labelLengths = labelLengths;
|
||||
_weights = extraWeights is { Count: > 0 }
|
||||
? OcrUtils.CreateWeights(extraWeights, _labelDict, labels.Count)
|
||||
: null;
|
||||
}
|
||||
// _labels = File.ReadAllLines(labelFilePath);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对多张图像按批次执行 OCR 识别。
|
||||
/// Run OCR recognition on multiple images in batches.
|
||||
/// </summary>
|
||||
/// <param name="srcs">Array of images for OCR recognition.</param>
|
||||
/// <param name="batchSize">Size of the batch to run OCR recognition on.</param>
|
||||
/// <returns>Array of <see cref="OcrRecognizerResult" /> instances corresponding to OCR recognition results of the images.</returns>
|
||||
public OcrRecognizerResult[] Run(Mat[] srcs, int batchSize = 0)
|
||||
=> RunBatch(srcs, RunMulti, batchSize);
|
||||
{
|
||||
if (srcs.Length == 0) return [];
|
||||
|
||||
var chooseBatchSize = batchSize != 0 ? batchSize : Math.Min(8, Environment.ProcessorCount);
|
||||
|
||||
return srcs
|
||||
.Select((x, i) => (mat: x, i))
|
||||
.OrderBy(x => x.mat.Width)
|
||||
.Chunk(chooseBatchSize)
|
||||
.Select(x => (result: RunMulti(x.Select(x1 => x1.mat).ToArray()), ids: x.Select(x1 => x1.i).ToArray()))
|
||||
.SelectMany(x => x.result.Zip(x.ids, (result, i) => (result, i)))
|
||||
.OrderBy(x => x.i)
|
||||
.Select(x => x.result)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public OcrRecognizerResult Run(Mat src)
|
||||
=> RunMulti([src]).Single();
|
||||
{
|
||||
return RunMulti([src]).Single();
|
||||
}
|
||||
|
||||
private OcrRecognizerResult[] RunMulti(Mat[] srcs)
|
||||
{
|
||||
@@ -97,173 +74,17 @@ public class Rec : IDisposable
|
||||
throw new ArgumentException($"src[{i}] size should not be 0, wrong input picture provided?");
|
||||
}
|
||||
|
||||
var resultTensors = RunInference(srcs);
|
||||
|
||||
return resultTensors.SelectMany(tensor =>
|
||||
{
|
||||
GCHandle dataHandle = default;
|
||||
try
|
||||
{
|
||||
dataHandle = GCHandle.Alloc(tensor.Data, GCHandleType.Pinned);
|
||||
var dataPtr = dataHandle.AddrOfPinnedObject();
|
||||
|
||||
return Enumerable.Range(0, tensor.Batch)
|
||||
.Select(i =>
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
var lastIndex = 0;
|
||||
float score = 0;
|
||||
var maxIdx = new int[2];
|
||||
using var fullMat = Mat.FromPixelData(tensor.TimeSteps, tensor.LabelCount,
|
||||
MatType.CV_32FC1,
|
||||
dataPtr + i * tensor.TimeSteps * tensor.LabelCount * sizeof(float));
|
||||
for (var n = 0; n < tensor.TimeSteps; ++n)
|
||||
{
|
||||
using var row = fullMat.Row(n);
|
||||
row.MinMaxIdx(out _, out var maxVal, [], maxIdx);
|
||||
|
||||
if (maxIdx[1] > 0 && maxVal >= _threshold && (_allowDuplicateChar || !(n > 0 && maxIdx[1] == lastIndex)))
|
||||
{
|
||||
score += (float)maxVal;
|
||||
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], _labels));
|
||||
}
|
||||
|
||||
lastIndex = maxIdx[1];
|
||||
}
|
||||
|
||||
var text = sb.ToString();
|
||||
return new OcrRecognizerResult(text, text.Length > 0 ? score / text.Length : 0);
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (dataHandle.IsAllocated) dataHandle.Free();
|
||||
}
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将目标字符串转换为标签索引序列,利用 LRU 缓存加速重复查询。
|
||||
/// 无法映射到标签的字符会被跳过。
|
||||
/// </summary>
|
||||
public int[] GetTarget(string target)
|
||||
{
|
||||
if (_targetCache.TryGet(target, out var cached) && cached is not null)
|
||||
return cached;
|
||||
|
||||
var result = OcrUtils.MapStringToLabelIndices(target, _labelDict, _labelLengths);
|
||||
_targetCache.Set(target, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对一批图像执行模糊匹配,返回与目标字符串的最大平均置信度 (0~1)。
|
||||
/// </summary>
|
||||
/// <param name="srcs">待匹配图像数组</param>
|
||||
/// <param name="target">目标字符串</param>
|
||||
/// <param name="batchSize">每批推理图像数,0表示自动</param>
|
||||
public double RunMatch(Mat[] srcs, string target, int batchSize = 0)
|
||||
{
|
||||
if (srcs.Length == 0) return 0;
|
||||
var targetIndexes = GetTarget(target);
|
||||
if (targetIndexes.Length == 0) return 0;
|
||||
|
||||
var charLevelResults = RunBatch(srcs,
|
||||
mats => ProcessForMatch(RunInference(mats), targetIndexes), batchSize);
|
||||
|
||||
return GetMaxScoreFlat(charLevelResults, targetIndexes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 ONNX 原始输出张量中提取目标字符在每个时间步的置信度。
|
||||
/// <para>
|
||||
/// 与 RunMulti(标准 OCR)不同,此方法不做 argmax(MinMaxIdx),
|
||||
/// 而是按目标字符的 label 索引直接查找对应位置的原始置信度。
|
||||
/// 这样即使目标字符不是某个时间步的最高置信度候选,DP 仍然能拿到其实际分数进行匹配。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="resultTensors">RunInference 返回的 (shape, data) 张量数组</param>
|
||||
/// <param name="targetIndexes">目标字符串映射后的 label 索引序列</param>
|
||||
/// <returns>每张图像对应一个 (labelIndex, confidence) 数组,供 DP 匹配使用</returns>
|
||||
private (int, float)[][] ProcessForMatch(TensorResult[] resultTensors, int[] targetIndexes)
|
||||
{
|
||||
// 目标字符去重(排除 CTC 空白符 index=0)
|
||||
var targetSet = new HashSet<int>(targetIndexes);
|
||||
targetSet.Remove(0);
|
||||
|
||||
return resultTensors.Select(tensor =>
|
||||
{
|
||||
var chars = new List<(int, float)>();
|
||||
for (var n = 0; n < tensor.TimeSteps * tensor.Batch; n++)
|
||||
{
|
||||
// 直接按索引查找目标字符的置信度,而非对整行取 argmax
|
||||
var rowOffset = n * tensor.LabelCount;
|
||||
foreach (var labelIdx in targetSet)
|
||||
{
|
||||
if (labelIdx >= tensor.LabelCount) continue;
|
||||
var raw = tensor.Data[rowOffset + labelIdx];
|
||||
var confidence = _weights is not null
|
||||
? raw * _weights[labelIdx]
|
||||
: raw;
|
||||
if (confidence > _threshold)
|
||||
chars.Add((labelIdx, confidence));
|
||||
}
|
||||
}
|
||||
return chars.ToArray();
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将多张图像的字符级别结果展平后,计算与 target 的最大匹配分数。
|
||||
/// 分母使用 target.Length,得到的是每个目标字符的平均置信度 (0~1)。
|
||||
/// </summary>
|
||||
private static double GetMaxScoreFlat((int, float)[][] result, int[] target)
|
||||
{
|
||||
var flatResult = result.SelectMany(x => x).ToArray();
|
||||
return OcrUtils.GetMaxScoreDp(flatResult, target, target.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通用批处理:按宽度排序、分批推理、恢复原始顺序
|
||||
/// </summary>
|
||||
private T[] RunBatch<T>(Mat[] srcs, Func<Mat[], T[]> process, int batchSize = 0)
|
||||
{
|
||||
if (srcs.Length == 0) return [];
|
||||
|
||||
var chooseBatchSize = batchSize != 0 ? batchSize : Math.Min(8, Environment.ProcessorCount);
|
||||
|
||||
return srcs
|
||||
.Select((x, i) => (mat: x, i))
|
||||
.OrderBy(x => x.mat.Width)
|
||||
.Chunk(chooseBatchSize)
|
||||
.Select(chunk =>
|
||||
{
|
||||
var mats = chunk.Select(x => x.mat).ToArray();
|
||||
var result = process(mats);
|
||||
return (result, ids: chunk.Select(x => x.i).ToArray());
|
||||
})
|
||||
.SelectMany(x => x.result.Zip(x.ids, (r, i) => (r, i)))
|
||||
.OrderBy(x => x.i)
|
||||
.Select(x => x.r)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行 ONNX 推理,返回每张图像的原始 (shape, data) 张量
|
||||
/// </summary>
|
||||
private TensorResult[] RunInference(Mat[] srcs)
|
||||
{
|
||||
var modelHeight = _config.Shape.Height;
|
||||
var modelHeight = config.Shape.Height;
|
||||
var maxWidth = (int)Math.Ceiling(srcs.Max(src =>
|
||||
{
|
||||
var size = src.Size();
|
||||
return 1.0 * size.Width / size.Height * modelHeight;
|
||||
}));
|
||||
List<IMemoryOwner<float>> owners = [];
|
||||
(int[], float[])[] resultTensors;
|
||||
try
|
||||
{
|
||||
return srcs
|
||||
resultTensors = srcs
|
||||
// .AsParallel()
|
||||
.Select(src =>
|
||||
{
|
||||
@@ -283,10 +104,12 @@ public class Rec : IDisposable
|
||||
{
|
||||
owners.Add(owner);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only dispose Mats created in this scope
|
||||
if (channel3 != null && !ReferenceEquals(channel3, src))
|
||||
{
|
||||
channel3.Dispose();
|
||||
@@ -294,31 +117,76 @@ public class Rec : IDisposable
|
||||
}
|
||||
})
|
||||
.Select(inputTensor =>
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
// 多线程推理会出现问题,加锁解决。
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
var output = results[0];
|
||||
if (output.ElementType is not TensorElementType.Float)
|
||||
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
|
||||
lock (_sessionLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
// 多线程推理会出现问题,加锁解决。
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
var output = results[0];
|
||||
if (output.ElementType is not TensorElementType.Float)
|
||||
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
|
||||
|
||||
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
|
||||
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
|
||||
var tensor = output.AsTensor<float>();
|
||||
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
|
||||
var dims = tensor.Dimensions;
|
||||
return new TensorResult(dims[0], dims[1], dims[2], tensor.ToArray());
|
||||
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
|
||||
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
|
||||
var tensor = output.AsTensor<float>();
|
||||
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
|
||||
return (tensor.Dimensions.ToArray(), tensor.ToArray());
|
||||
}
|
||||
}
|
||||
}).ToArray();
|
||||
).ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
owners.ForEach(x => { x.Dispose(); });
|
||||
}
|
||||
|
||||
return resultTensors.SelectMany(resultTensor =>
|
||||
{
|
||||
var resultArray = resultTensor.Item2;
|
||||
var resultShape = resultTensor.Item1;
|
||||
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)
|
||||
{
|
||||
var rowOffset = batchOffset + n * labelCount;
|
||||
var maxVal = float.MinValue;
|
||||
var maxIndex = 0;
|
||||
for (var c = 0; c < labelCount; c++)
|
||||
{
|
||||
var value = resultArray[rowOffset + c];
|
||||
if (value > maxVal)
|
||||
{
|
||||
maxVal = value;
|
||||
maxIndex = c;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
public string GetConfigName => _config.Name;
|
||||
public string GetConfigName => config.Name;
|
||||
}
|
||||
@@ -4,93 +4,72 @@ using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.Win32;
|
||||
using Vanara;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public class BgiOnnxFactory
|
||||
/// <summary>从当前已解析运行时创建会话。每次调用只读取一次 Current,已有会话不会受后续回退影响。</summary>
|
||||
public sealed class BgiOnnxFactory(ILogger<BgiOnnxFactory> logger, InferenceRuntimeService runtime)
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
internal BgiOnnxSessionFactory ForCurrentRuntime() => new(logger, runtime.Current);
|
||||
|
||||
internal BgiOnnxSessionFactory ForRuntime(ResolvedInferenceRuntime resolvedRuntime) => new(logger, resolvedRuntime);
|
||||
|
||||
public BgiYoloPredictor CreateYoloPredictor(BgiOnnxModel model)
|
||||
=> ForCurrentRuntime().CreateYoloPredictor(model);
|
||||
|
||||
public InferenceSession CreateInferenceSession(BgiOnnxModel model, bool ocr = false)
|
||||
=> ForCurrentRuntime().CreateInferenceSession(model, ocr);
|
||||
|
||||
/// <summary>为明确不参与硬件加速选择的模型创建纯 CPU 会话。</summary>
|
||||
public static InferenceSession CreateCpuOnlyInferenceSession(BgiOnnxModel model,
|
||||
Action<SessionOptions>? configure = null)
|
||||
{
|
||||
using var options = new SessionOptions();
|
||||
configure?.Invoke(options);
|
||||
options.AppendExecutionProvider_CPU();
|
||||
return new InferenceSession(model.ModalPath, options);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>绑定单个已解析运行时的会话工厂。</summary>
|
||||
public sealed class BgiOnnxSessionFactory
|
||||
{
|
||||
private readonly ILogger<BgiOnnxFactory> _logger;
|
||||
private readonly ProviderType[] _providerTypes;
|
||||
private readonly ResolvedInferenceRuntime _runtime;
|
||||
|
||||
/// <summary>
|
||||
/// 缓存模型路径。如果一开始使用缓存就一直使用缓存文件,如果没有使用缓存就一直使用原始模型路径。
|
||||
/// 缓存模型路径对应的目录;会话始终加载原始模型,不再使用嵌入缓存文件。
|
||||
/// <br />
|
||||
/// 这样能避免并发加载模型问题。比如使用了未完全构建好的缓存文件,导致模型加载失败。
|
||||
/// 这样能避免并发加载模型问题。普通缓存目录按模型内容、设备与设置隔离。
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<BgiOnnxModel, string?> _cachedModelPaths = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 请勿直接实例化此类
|
||||
/// </summary>
|
||||
/// <param name="logger"></param>
|
||||
public BgiOnnxFactory(ILogger<BgiOnnxFactory> logger)
|
||||
internal BgiOnnxSessionFactory(ILogger<BgiOnnxFactory> logger, ResolvedInferenceRuntime runtime)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
var config = GetConfig();
|
||||
if (config.AutoAppendCudaPath) AppendCudaPath();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(config.AdditionalPath))
|
||||
AppendPath(config.AdditionalPath.Split(Path.PathSeparator));
|
||||
|
||||
|
||||
OptimizedModel = config.OptimizedModel;
|
||||
CudaDeviceId = config.CudaDevice;
|
||||
DmlDeviceId = config.GpuDevice;
|
||||
TrtUseEmbedMode = config.EmbedTensorRtCache;
|
||||
EnableCache = config.EnableTensorRtCache;
|
||||
CpuOcr = config.CpuOcr;
|
||||
OpenVinoDevice = config.OpenVinoDevice;
|
||||
OpenVinoCache = config.EnableOpenVinoCache;
|
||||
ProviderTypes = GetProviderType(config.InferenceDevice);
|
||||
_logger.LogDebug(
|
||||
"[ONNX]启用的provider:{Device},初始化参数: InferenceDevice={InferenceDevice}, OptimizedModel={OptimizedModel}, CudaDeviceId={CudaDeviceId}, DmlDeviceId={DmlDeviceId}, EmbedTensorRtCache={EmbedTensorRtCache}, EnableTensorRtCache={EnableTensorRtCache}, CpuOcr={CpuOcr}",
|
||||
string.Join(",", ProviderTypes.Select<ProviderType, string>(Enum.GetName!)),
|
||||
config.InferenceDevice,
|
||||
OptimizedModel,
|
||||
CudaDeviceId,
|
||||
DmlDeviceId,
|
||||
TrtUseEmbedMode,
|
||||
EnableCache,
|
||||
CpuOcr);
|
||||
_runtime = runtime;
|
||||
_providerTypes = GetProviderType(runtime.Engine);
|
||||
_logger.LogInformation("[ONNX]当前引擎 {Engine},设备 {Device},OCR 强制 CPU:{CpuOcr}",
|
||||
runtime.Engine, runtime.Device.Name, runtime.CpuOcr);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 硬件加速配置
|
||||
/// 为了单元测试
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private HardwareAccelerationConfig GetConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 直接使用配置
|
||||
return TaskContext.Instance().Config.HardwareAccelerationConfig;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 如果配置获取失败,使用默认配置
|
||||
_logger.LogWarning(e, "获取硬件加速配置失败,使用默认配置");
|
||||
return new HardwareAccelerationConfig();
|
||||
}
|
||||
}
|
||||
public ResolvedInferenceRuntime Runtime => _runtime;
|
||||
|
||||
public ProviderType[] ProviderTypes { get; }
|
||||
public int DmlDeviceId { get; }
|
||||
public int CudaDeviceId { get; }
|
||||
public bool OptimizedModel { get; }
|
||||
public bool TrtUseEmbedMode { get; }
|
||||
public string OpenVinoDevice { get; }
|
||||
public bool EnableCache { get; }
|
||||
public bool CpuOcr { get; }
|
||||
public bool OpenVinoCache { get; }
|
||||
// OCR 验证使用独立会话,必须实际加载所选 provider;不改变业务 OCR 的 CPU 设置。
|
||||
internal BgiOnnxSessionFactory ForOcrValidation()
|
||||
=> new(_logger, Runtime with { CpuOcr = false });
|
||||
|
||||
public ProviderType[] ProviderTypes => (ProviderType[])_providerTypes.Clone();
|
||||
public int DmlDeviceId => Runtime.Device.Index;
|
||||
public int CudaDeviceId => Runtime.Device.Index;
|
||||
public string OpenVinoDevice => Runtime.Device.ProviderDevice;
|
||||
public bool EnableCache => Runtime.EnableModelCache;
|
||||
public bool CpuOcr => Runtime.CpuOcr;
|
||||
public bool OpenVinoCache => Runtime.EnableModelCache;
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -98,203 +77,36 @@ public class BgiOnnxFactory
|
||||
/// </summary>
|
||||
/// <param name="inferenceDeviceType">InferenceDeviceType</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="InvalidEnumArgumentException"></exception>
|
||||
/// <remarks>历史上的自动 GPU 选项已移除,无法识别的设置回退到 CPU。</remarks>
|
||||
private ProviderType[] GetProviderType(InferenceDeviceType inferenceDeviceType)
|
||||
{
|
||||
// 无论如何都要加入 CPU,一些计算在纯 GPU 上不被支持或性能很差。
|
||||
switch (inferenceDeviceType)
|
||||
{
|
||||
case InferenceDeviceType.Cpu:
|
||||
return [ProviderType.Cpu];
|
||||
case InferenceDeviceType.GpuDirectMl:
|
||||
case InferenceDeviceType.DirectML:
|
||||
//只用dml不加cpu的话在很多场景下性能很差。
|
||||
// DirectML 的性能和稳定性取决于模型与设备,现在由用户独立选择,不与 TensorRT、CUDA 自动比较。
|
||||
return [ProviderType.Dml, ProviderType.Cpu];
|
||||
case InferenceDeviceType.Gpu:
|
||||
{
|
||||
List<ProviderType> list = [];
|
||||
SessionOptions? testSession = null;
|
||||
var hasGpu = false;
|
||||
if (!hasGpu && CudaDeviceId >= 0)
|
||||
// tensorrt本身包含cuda,设备id也是cuda的id,且比纯cuda效果好很多。
|
||||
try
|
||||
{
|
||||
testSession = SessionOptions.MakeSessionOptionWithTensorrtProvider(CudaDeviceId);
|
||||
list.Add(ProviderType.TensorRt);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载TensorRt。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu && DmlDeviceId >= 0)
|
||||
// dml效果不如tensorrt,但是比纯cuda稳定性强
|
||||
try
|
||||
{
|
||||
testSession = new SessionOptions();
|
||||
testSession.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
list.Add(ProviderType.Dml);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载DML。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu && CudaDeviceId >= 0)
|
||||
// cuda优先级比较低,因为跑起来并不太理想。
|
||||
try
|
||||
{
|
||||
testSession = SessionOptions.MakeSessionOptionWithCudaProvider(CudaDeviceId);
|
||||
list.Add(ProviderType.Cuda);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载Cuda。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu) _logger.LogWarning("[init]GPU自动选择失败,回退到CPU处理");
|
||||
|
||||
//无论如何都要加入cpu,一些计算在纯gpu上不被支持或性能很烂
|
||||
list.Add(ProviderType.Cpu);
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
case InferenceDeviceType.OpenVino:
|
||||
{
|
||||
List<ProviderType> list = [];
|
||||
SessionOptions? testSession = null;
|
||||
case InferenceDeviceType.OpenVINO:
|
||||
// OpenVino是英特尔的OpenVINO执行提供程序
|
||||
// 目前来看比Dml强
|
||||
try
|
||||
{
|
||||
testSession = new SessionOptions();
|
||||
testSession.AppendExecutionProvider("OpenVINO", GetOpenVinoProviderConfig(null));
|
||||
testSession.GraphOptimizationLevel = GraphOptimizationLevel.ORT_DISABLE_ALL;
|
||||
list.Add(ProviderType.OpenVino);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载OpenVino。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
list.Add(ProviderType.Cpu);
|
||||
return list.ToArray();
|
||||
}
|
||||
// provider 注册统一在 CreateSessionOptions 中完成,避免重复创建原生选项探测。
|
||||
return [ProviderType.OpenVino, ProviderType.Cpu];
|
||||
case InferenceDeviceType.CUDA:
|
||||
// CUDA 的效果依赖具体模型,不再受旧自动选择策略中的低优先级限制。
|
||||
return [ProviderType.Cuda, ProviderType.Cpu];
|
||||
case InferenceDeviceType.TensorRT:
|
||||
// TensorRT 使用配置的设备编号,性能收益需要按模型和设备判断。
|
||||
// TensorRT 独立注册,未接管的算子由 CPU 兜底。
|
||||
return [ProviderType.TensorRt, ProviderType.Cpu];
|
||||
default:
|
||||
throw new InvalidEnumArgumentException("无效的推理设备");
|
||||
_logger.LogWarning("[ONNX]无法识别推理设备设置 {Device},回退到 CPU", inferenceDeviceType);
|
||||
return [ProviderType.Cpu];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动嗅探并修改path以加载cuda
|
||||
/// </summary>
|
||||
private void AppendCudaPath()
|
||||
{
|
||||
var cudaVersion =
|
||||
Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\NVIDIA Corporation\GPU Computing Toolkit\CUDA",
|
||||
"FirstVersionInstalled", null)?.ToString() ?? "v12.8";
|
||||
string[] filePrefix = ["cudnn", "nvrtc", "cudart", "nvinfer", "cublas", "onnx"];
|
||||
string[] environmentVariableNames = ["PATH", "CUDA_PATH", "CUDNN_PATH", "LD_LIBRARY_PATH"];
|
||||
|
||||
// 例如: CUDNN\v9.8\lib\12.8\x64
|
||||
var validPaths = environmentVariableNames.SelectMany(s => Environment
|
||||
// 获取所有可能包含CUDA/cuDNN路径的环境变量
|
||||
.GetEnvironmentVariable(s, EnvironmentVariableTarget.Process)?
|
||||
.Split(Path.PathSeparator) ?? []).Distinct()
|
||||
// 环境变量下层文件夹
|
||||
.SelectMany<string, string>(s =>
|
||||
// lib路径
|
||||
[s, Path.Combine(s, cudaVersion), Path.Combine(s, "bin"), Path.Combine(s, "lib")])
|
||||
.SelectMany<string, string>(
|
||||
// cuda的版本
|
||||
s => cudaVersion.StartsWith("v", StringComparison.InvariantCultureIgnoreCase)
|
||||
? [s, Path.Combine(s, cudaVersion), Path.Combine(s, cudaVersion[1..])]
|
||||
: [s, Path.Combine(s, cudaVersion)])
|
||||
.SelectMany<string, string>(s =>
|
||||
{
|
||||
// 体系架构
|
||||
var architecture = Enum.GetName(RuntimeInformation.ProcessArchitecture);
|
||||
if (architecture is null) return [s];
|
||||
|
||||
return
|
||||
[
|
||||
s, Path.Combine(s, architecture), Path.Combine(s, architecture.ToLowerInvariant()),
|
||||
Path.Combine(s, architecture.ToUpperInvariant())
|
||||
];
|
||||
})
|
||||
.Where(basePath => !string.IsNullOrWhiteSpace(basePath))
|
||||
//构建完了需要搜索的路径,去重。
|
||||
.Distinct()
|
||||
|
||||
//确定路径是否真的存在
|
||||
.Where(d =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.Exists(d);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.SelectMany(s =>
|
||||
//确定需要的文件是否存在
|
||||
filePrefix.SelectMany(se =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.GetFiles(s, $"{se}*.dll").Select(Path.GetDirectoryName).WhereNotNull();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}))
|
||||
//去重
|
||||
.Distinct();
|
||||
AppendPath(validPaths.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将附加的path应用进来
|
||||
/// </summary>
|
||||
/// <param name="extraPath">附加的path字符串</param>
|
||||
private void AppendPath(string[] extraPath)
|
||||
{
|
||||
if (extraPath.Length <= 0) return;
|
||||
|
||||
var pathVariables = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process)
|
||||
?.Split(Path.PathSeparator).ToList() ?? new List<string>();
|
||||
pathVariables.AddRange(extraPath);
|
||||
if (pathVariables.Count <= 0)
|
||||
{
|
||||
_logger.LogWarning("[GpuAuto]SetCudaPath:No valid paths found.");
|
||||
return;
|
||||
}
|
||||
|
||||
var updatedPath = string.Join(Path.PathSeparator, pathVariables.Distinct());
|
||||
_logger.LogDebug("[GpuAuto]修改进程PATH为:{UpdatedPath}", updatedPath);
|
||||
Environment.SetEnvironmentVariable("PATH", updatedPath, EnvironmentVariableTarget.Process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据模型创建一个YoloPredictor
|
||||
/// </summary>
|
||||
@@ -302,13 +114,19 @@ public class BgiOnnxFactory
|
||||
/// <returns>BgiYoloPredictor</returns>
|
||||
public BgiYoloPredictor CreateYoloPredictor(BgiOnnxModel model)
|
||||
{
|
||||
// 延后验证只影响后续新建会话,不修改或释放已经运行中的会话。
|
||||
// logger.LogDebug("[Yolo]创建yolo预测器,模型: {ModelName}", model.Name);
|
||||
if (!EnableCache) return new BgiYoloPredictor(model, model.ModalPath, CreateSessionOptions(model, false));
|
||||
|
||||
var cached = GetCached(model);
|
||||
return cached == null
|
||||
? new BgiYoloPredictor(model, model.ModalPath, CreateSessionOptions(model, true))
|
||||
: new BgiYoloPredictor(model, cached, CreateSessionOptions(model, false));
|
||||
var options = CreateSessionOptions(model, EnableCache);
|
||||
try
|
||||
{
|
||||
// 延迟创建会话,配置的所有权转交给预测器。
|
||||
return new BgiYoloPredictor(model, model.ModalPath, options);
|
||||
}
|
||||
catch
|
||||
{
|
||||
options.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -323,69 +141,30 @@ public class BgiOnnxFactory
|
||||
ProviderType[]? providerTypes = null;
|
||||
if (CpuOcr && ocr) providerTypes = [ProviderType.Cpu];
|
||||
|
||||
if (!EnableCache)
|
||||
return new InferenceSession(model.ModalPath, CreateSessionOptions(model, false, providerTypes));
|
||||
|
||||
var cached = GetCached(model, providerTypes);
|
||||
return cached == null
|
||||
? new InferenceSession(model.ModalPath, CreateSessionOptions(model, true, providerTypes))
|
||||
: new InferenceSession(cached, CreateSessionOptions(model, false, providerTypes));
|
||||
using var options = CreateSessionOptions(model, EnableCache, providerTypes);
|
||||
return new InferenceSession(model.ModalPath, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取带有缓存的模型(目前只支持TensorRT)
|
||||
/// 获取普通缓存目录(TensorRT / OpenVINO)
|
||||
/// </summary>
|
||||
/// <param name="model">模型</param>
|
||||
/// <param name="forcedProvider">强制使用的 providerTypes</param>
|
||||
/// <returns>带有缓存的模型绝对路径,null表示尚未创建缓存</returns>
|
||||
/// <returns>缓存目录绝对路径,null 表示当前 provider 不需要缓存</returns>
|
||||
private string? GetCached(BgiOnnxModel model, ProviderType[]? forcedProvider = null)
|
||||
{
|
||||
var providerTypes = forcedProvider ?? ProviderTypes;
|
||||
// 目前只支持TensorRT
|
||||
if (!providerTypes.Contains(ProviderType.TensorRt)) return null;
|
||||
var result = _cachedModelPaths.GetOrAdd(model, _GetCached);
|
||||
if (result is null) return result;
|
||||
|
||||
// 判断文件是否存在
|
||||
if (File.Exists(result)) return result;
|
||||
|
||||
_logger.LogWarning("[ONNX]模型 {Model} 的缓存文件可能已被删除,使用原始模型文件。", model.Name);
|
||||
return null;
|
||||
var providers = forcedProvider ?? ProviderTypes;
|
||||
if (!providers.Contains(ProviderType.TensorRt) && !providers.Contains(ProviderType.OpenVino)) return null;
|
||||
// 判断文件是否存在:这里只缓存目录,原始模型始终保持不变,不加载旧 _ctx.onnx。
|
||||
return _cachedModelPaths.GetOrAdd(model, _ => Runtime.GetCachePath(model));
|
||||
}
|
||||
|
||||
private string? _GetCached(BgiOnnxModel model)
|
||||
{
|
||||
if (model.ModelRelativePath.StartsWith(BgiOnnxModel.ModelCacheRelativePath) &&
|
||||
model.ModelRelativePath.EndsWith("_ctx.onnx"))
|
||||
// 这已经是带有缓存的文件路径了
|
||||
return model.ModalPath;
|
||||
|
||||
var ctxA = Path.Combine(model.CachePath, "trt", "_ctx.onnx");
|
||||
if (File.Exists(ctxA))
|
||||
{
|
||||
_logger.LogDebug("[ONNX]模型 {Model} 命中TRT匿名缓存文件: {Path}", model.Name, ctxA);
|
||||
return ctxA;
|
||||
}
|
||||
|
||||
var ctxB = Path.Combine(model.CachePath, "trt",
|
||||
Path.GetFileNameWithoutExtension(model.ModalPath) + "_ctx.onnx");
|
||||
if (File.Exists(ctxB))
|
||||
{
|
||||
_logger.LogDebug("[ONNX]模型 {Model} 命中TRT命名缓存文件: {Path}", model.Name, ctxB);
|
||||
return ctxB;
|
||||
}
|
||||
|
||||
_logger.LogDebug("[ONNX]没有找到模型 {Model} 的模型缓存文件。", model.Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 通过模型路径生成SessionOptions <br />
|
||||
/// 如果加载的模型文件已经是带有缓存的模型,请将cacheFolder设为null避免重复生成。
|
||||
/// 会话始终加载原始模型,缓存只用于加速原生 provider 的初始化。
|
||||
/// </summary>
|
||||
/// <param name="model">模型路径</param>
|
||||
/// <param name="genCache">是否生成缓存。有几种情况下不生成缓存:1为用户主动关闭,即enableCache为false。2为即将加载的模型文件已经是带有缓存的模型文件。</param>
|
||||
/// <param name="genCache">是否启用当前引擎的普通缓存。</param>
|
||||
/// <param name="forcedProvider">强制使用的Provider,为空或null则不强制</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="InvalidEnumArgumentException"></exception>
|
||||
@@ -393,68 +172,92 @@ public class BgiOnnxFactory
|
||||
ProviderType[]? forcedProvider = null)
|
||||
{
|
||||
var sessionOptions = new SessionOptions();
|
||||
foreach (var type in
|
||||
forcedProvider is null || forcedProvider.Length == 0 ? ProviderTypes : forcedProvider)
|
||||
try
|
||||
try
|
||||
{
|
||||
var cache = genCache ? GetCached(model, forcedProvider) : null;
|
||||
var providers = forcedProvider is { Length: > 0 } ? forcedProvider : ProviderTypes;
|
||||
foreach (var type in providers)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case ProviderType.Dml:
|
||||
// DirectML 执行提供程序不支持在 onnxruntime 中使用内存模式优化或并行执行。在创建 InferenceSession 期间提供会话选项时,必须禁用这些选项,否则将返回错误。
|
||||
sessionOptions.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
sessionOptions.EnableMemoryPattern = false;
|
||||
sessionOptions.ExecutionMode = ExecutionMode.ORT_SEQUENTIAL;
|
||||
sessionOptions.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
break;
|
||||
case ProviderType.Cpu:
|
||||
ConfigureCpuSessionOptions(sessionOptions, model, providers.Length == 1);
|
||||
sessionOptions.AppendExecutionProvider_CPU();
|
||||
if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
|
||||
{
|
||||
sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
|
||||
sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
|
||||
}
|
||||
break;
|
||||
case ProviderType.Dnnl:
|
||||
sessionOptions.AppendExecutionProvider_Dnnl();
|
||||
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
|
||||
// {
|
||||
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
|
||||
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
|
||||
// }
|
||||
break;
|
||||
case ProviderType.OpenVino:
|
||||
sessionOptions.AppendExecutionProvider("OpenVINO",
|
||||
GetOpenVinoProviderConfig(OpenVinoCache ? model.CachePath : null));
|
||||
sessionOptions.AppendExecutionProvider("OpenVINO", GetOpenVinoProviderConfig(cache));
|
||||
sessionOptions.GraphOptimizationLevel = GraphOptimizationLevel.ORT_DISABLE_ALL;
|
||||
break;
|
||||
case ProviderType.TensorRt:
|
||||
using (var options = new OrtTensorRTProviderOptions())
|
||||
{
|
||||
options.UpdateOptions(GetTrtProviderConfig(genCache ? model.CachePath : null));
|
||||
options.UpdateOptions(GetTrtProviderConfig(cache));
|
||||
sessionOptions.AppendExecutionProvider_Tensorrt(options);
|
||||
}
|
||||
|
||||
break;
|
||||
case ProviderType.Cuda:
|
||||
using (var options = new OrtCUDAProviderOptions())
|
||||
{
|
||||
options.UpdateOptions(GetCudaProviderConfig());
|
||||
sessionOptions.AppendExecutionProvider_CUDA();
|
||||
sessionOptions.AppendExecutionProvider_CUDA(options);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new InvalidEnumArgumentException("无效的推理设备");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法加载指定的 ONNX provider {Provider},跳过。请检查推理设备配置是否正确。({Err})", Enum.GetName(type),
|
||||
e.Message);
|
||||
}
|
||||
|
||||
if (!OptimizedModel) return sessionOptions;
|
||||
if (!genCache) return sessionOptions;
|
||||
var optPath = Path.Combine(model.CachePath, "optimized");
|
||||
if (!Directory.Exists(optPath)) Directory.CreateDirectory(optPath);
|
||||
sessionOptions.OptimizedModelFilePath = Path.Combine(optPath, Path.GetFileName(model.ModalPath));
|
||||
return sessionOptions;
|
||||
return sessionOptions;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 目标 provider 初始化失败必须向上报告,不能跳过后用 CPU 假装验证成功。
|
||||
sessionOptions.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal void ConfigureCpuSessionOptions(SessionOptions sessionOptions, BgiOnnxModel model, bool cpuOnly)
|
||||
{
|
||||
var isPaddleOcr = model.Name.StartsWith("PpOcrDet", StringComparison.Ordinal)
|
||||
|| model.Name.StartsWith("PpOcrRec", StringComparison.Ordinal);
|
||||
// “ONNX Runtime 自动调度”需要跳过通用 CPU 线程数;新建 SessionOptions 的 0 即 ORT 原生默认值。
|
||||
if (!cpuOnly || !isPaddleOcr || Runtime.PaddleOcrCpu.Mode != PaddleOcrCpuMode.RuntimeAuto)
|
||||
sessionOptions.IntraOpNumThreads = Runtime.CpuThreads;
|
||||
ConfigurePaddleOcrCpu(sessionOptions, model, cpuOnly);
|
||||
}
|
||||
|
||||
/// <summary>只覆盖 PPOCR 纯 CPU 会话;GPU 会话的 CPU 兜底与其他模型仍使用全局设置。</summary>
|
||||
internal void ConfigurePaddleOcrCpu(SessionOptions sessionOptions, BgiOnnxModel model, bool cpuOnly)
|
||||
{
|
||||
if (!cpuOnly) return;
|
||||
var detection = model.Name.StartsWith("PpOcrDet", StringComparison.Ordinal);
|
||||
if (!detection && !model.Name.StartsWith("PpOcrRec", StringComparison.Ordinal)) return;
|
||||
if (Runtime.PaddleOcrCpu.Mode == PaddleOcrCpuMode.RuntimeAuto)
|
||||
{
|
||||
_logger.LogInformation("[ONNX]OCR CPU 线程策略,模型 {Model},使用 ONNX Runtime 自动调度", model.Name);
|
||||
return;
|
||||
}
|
||||
var options = Runtime.PaddleOcrCpu.Resolve(detection);
|
||||
if (options == null) return;
|
||||
sessionOptions.IntraOpNumThreads = options.IntraOpThreads;
|
||||
sessionOptions.InterOpNumThreads = options.InterOpThreads;
|
||||
sessionOptions.ExecutionMode = options.ParallelExecution ? ExecutionMode.ORT_PARALLEL : ExecutionMode.ORT_SEQUENTIAL;
|
||||
sessionOptions.AddSessionConfigEntry("session.intra_op.allow_spinning", options.AllowSpinning ? "1" : "0");
|
||||
sessionOptions.AddSessionConfigEntry("session.inter_op.allow_spinning", options.AllowSpinning ? "1" : "0");
|
||||
_logger.LogInformation("[ONNX]OCR CPU 线程策略,模型 {Model},算子内线程 {IntraOp},算子间线程 {InterOp},并行 {Parallel},自旋 {Spinning}",
|
||||
model.Name, options.IntraOpThreads, options.InterOpThreads, options.ParallelExecution, options.AllowSpinning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取TensorRT的配置
|
||||
@@ -463,73 +266,22 @@ public class BgiOnnxFactory
|
||||
/// <returns>trt配置</returns>
|
||||
private Dictionary<string, string> GetTrtProviderConfig(string? cacheFolder)
|
||||
{
|
||||
var result = new Dictionary<string, string> { ["device_id"] = CudaDeviceId.ToString() };
|
||||
if (cacheFolder is null)
|
||||
{
|
||||
// 不使用缓存目录
|
||||
var r = new Dictionary<string, string>
|
||||
{
|
||||
["device_id"] = CudaDeviceId.ToString()
|
||||
};
|
||||
return r;
|
||||
return result;
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, string>
|
||||
{
|
||||
["trt_engine_cache_enable"] = "1",
|
||||
["trt_dump_ep_context_model"] = "1",
|
||||
["trt_ep_context_file_path"] = Path.Combine(cacheFolder, "trt"),
|
||||
// ["trt_ep_context_embed_mode"] = "1", // 因为yoloSharp是把模型转为嵌入式运行,不这样会爆炸
|
||||
// ["trt_engine_cache_path"] = ".\\" // 没必要了
|
||||
["trt_timing_cache_enable"] = "1",
|
||||
["trt_timing_cache_path"] =
|
||||
Global.Absolute(Path.Combine(BgiOnnxModel.ModelCacheRelativePath, "trt_timing")),
|
||||
// ["trt_force_timing_cache"] = "1",
|
||||
["device_id"] = CudaDeviceId.ToString()
|
||||
};
|
||||
if (TrtUseEmbedMode)
|
||||
{
|
||||
result["trt_ep_context_embed_mode"] = "1";
|
||||
}
|
||||
else
|
||||
{
|
||||
result["trt_ep_context_embed_mode"] = "0";
|
||||
result["trt_engine_cache_path"] = ".\\";
|
||||
}
|
||||
|
||||
if (!Directory.Exists(result["trt_ep_context_file_path"]))
|
||||
{
|
||||
// 如果不存在就创建目录
|
||||
_logger.LogDebug("[ONNX]TensorRT上下文文件路径不存在,创建目录: {Path}", result["trt_ep_context_file_path"]);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(result["trt_ep_context_file_path"]);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法创建TensorRT上下文文件路径: {Path},请检查权限。({Err})",
|
||||
result["trt_ep_context_file_path"], e.Message);
|
||||
// 如果无法创建目录,就不使用缓存
|
||||
result.Remove("trt_ep_context_file_path");
|
||||
}
|
||||
}
|
||||
|
||||
if (!Directory.Exists(result["trt_timing_cache_path"]))
|
||||
{
|
||||
// 如果不存在就创建目录
|
||||
_logger.LogDebug("[ONNX]TensorRT计时缓存路径不存在,创建目录: {Path}", result["trt_timing_cache_path"]);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(result["trt_timing_cache_path"]);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法创建TensorRT计时缓存路径: {Path},请检查权限。({Err})",
|
||||
result["trt_timing_cache_path"], e.Message);
|
||||
// 如果无法创建目录,就不使用缓存
|
||||
result.Remove("trt_timing_cache_path");
|
||||
}
|
||||
}
|
||||
|
||||
// 如果不存在就创建目录。使用普通 engine/timing 缓存,不导出或嵌入优化模型。
|
||||
var engine = Path.Combine(cacheFolder, "trt");
|
||||
var timing = Path.Combine(cacheFolder, "trt_timing");
|
||||
Directory.CreateDirectory(engine);
|
||||
Directory.CreateDirectory(timing);
|
||||
result["trt_engine_cache_enable"] = "1";
|
||||
result["trt_engine_cache_path"] = engine;
|
||||
result["trt_timing_cache_enable"] = "1";
|
||||
result["trt_timing_cache_path"] = timing;
|
||||
// ["trt_force_timing_cache"] = "1", // 不跨设备强制复用 timing cache。
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -556,7 +308,7 @@ public class BgiOnnxFactory
|
||||
var result = new Dictionary<string, string>();
|
||||
if (!string.IsNullOrWhiteSpace(OpenVinoDevice))
|
||||
{
|
||||
result["deice_type"] = OpenVinoDevice;
|
||||
result["device_type"] = OpenVinoDevice;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(cacheFolder))
|
||||
@@ -579,7 +331,26 @@ public class BgiOnnxFactory
|
||||
}
|
||||
}
|
||||
|
||||
result["enable_opencl_throttling"] = "true";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
#region 历史路径探测说明(仅保留注释,依赖由独立安装目录管理)
|
||||
// 获取 硬件加速配置
|
||||
// 为了单元测试
|
||||
// 直接使用配置
|
||||
// 如果配置获取失败,使用默认配置
|
||||
// 自动嗅探并修改path以加载cuda
|
||||
// 例如: CUDNN\v9.8\lib\12.8\x64
|
||||
// 获取所有可能包含CUDA/cuDNN路径的环境变量
|
||||
// 环境变量下层文件夹
|
||||
// lib路径
|
||||
// cuda的版本
|
||||
// 体系架构
|
||||
//构建完了需要搜索的路径,去重。
|
||||
//确定路径是否真的存在
|
||||
//确定需要的文件是否存在
|
||||
//去重
|
||||
// 将附加的path应用进来
|
||||
// <param name="extraPath">附加的path字符串</param>
|
||||
#endregion
|
||||
}
|
||||
@@ -42,7 +42,12 @@ public class BgiOnnxModel
|
||||
/// <summary>
|
||||
/// 用于捡东西等的大世界模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiWorld = Register("BgiTree", @"Assets\Model\World\bgi_world.onnx");
|
||||
public static readonly BgiOnnxModel BgiWorld = Register("BgiWorld", @"Assets\Model\World\bgi_world.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 矿物识别模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiMine = Register("BgiMine", @"Assets\Model\Mine\bgi_mine.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 角色识别
|
||||
@@ -50,6 +55,42 @@ public class BgiOnnxModel
|
||||
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>
|
||||
/// E技能就绪分类模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiEClassify =
|
||||
Register("BgiEClassify", @"Assets\Model\Common\e_classify_sim.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 队伍配置角色头像识别模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel AvatarGridIcon =
|
||||
Register("AvatarGridIcon", @"Assets\Model\AvatarGridIcon\avatar.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 物品网格图标识别模型,固定使用 CPU。
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel GridIcon =
|
||||
Register("GridIcon", @"Assets\Model\Item\gridIcon.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 物品图标识别模型,固定使用 CPU。
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel ItemIcon =
|
||||
Register("ItemIcon", @"Assets\Model\ItemV2\item.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// Silero 人声检测模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel SileroVad =
|
||||
Register("SileroVad", @"Assets\Model\Vad\silero_vad.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// paddleOCR V4 检测模型
|
||||
/// </summary>
|
||||
@@ -62,6 +103,12 @@ 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>
|
||||
@@ -80,6 +127,12 @@ 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>
|
||||
@@ -100,7 +153,7 @@ public class BgiOnnxModel
|
||||
|
||||
#endregion
|
||||
|
||||
private BgiOnnxModel(string name, string modelRelativePath, string cacheRelativePath)
|
||||
public BgiOnnxModel(string name, string modelRelativePath, string cacheRelativePath)
|
||||
{
|
||||
Name = name;
|
||||
ModelRelativePath = modelRelativePath;
|
||||
@@ -139,4 +192,4 @@ public class BgiOnnxModel
|
||||
RegisteredModels.Add(model);
|
||||
return model;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using OpenCvSharp;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
|
||||
@@ -17,6 +16,9 @@ public class BgiYoloPredictor : IDisposable
|
||||
|
||||
|
||||
private readonly Lazy<YoloPredictor> _lazyPredictor;
|
||||
private readonly SessionOptions _sessionOptions;
|
||||
private readonly object _syncRoot = new();
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// 使用 BgiOnnxFactory 创建这个类的实例
|
||||
@@ -27,14 +29,36 @@ public class BgiYoloPredictor : IDisposable
|
||||
protected internal BgiYoloPredictor(BgiOnnxModel onnxModel, string modelPath, SessionOptions sessionOptions)
|
||||
{
|
||||
_model = onnxModel;
|
||||
_lazyPredictor = new Lazy<YoloPredictor>(() => new YoloPredictor(modelPath,
|
||||
new YoloPredictorOptions
|
||||
_sessionOptions = sessionOptions;
|
||||
_lazyPredictor = new Lazy<YoloPredictor>(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
SessionOptions = sessionOptions
|
||||
}));
|
||||
return new YoloPredictor(modelPath, new YoloPredictorOptions
|
||||
{
|
||||
SessionOptions = _sessionOptions
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 会话创建完成(含失败)后不再需要配置;未初始化时由 Dispose 释放。
|
||||
_sessionOptions.Dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public YoloPredictor Predictor => _lazyPredictor.Value;
|
||||
public YoloPredictor Predictor
|
||||
{
|
||||
get
|
||||
{
|
||||
// 串行化延迟初始化与释放,避免创建会话时配置被提前释放。
|
||||
lock (_syncRoot)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
return _lazyPredictor.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测
|
||||
@@ -63,18 +87,31 @@ public class BgiYoloPredictor : IDisposable
|
||||
|
||||
var list = result
|
||||
.Select(box => new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height))
|
||||
.Select(rect => region.ToRectDrawable(rect, _model.Name)).ToList();
|
||||
.Select(rect => region.ToMaskWindowDrawingRect(rect)).ToList();
|
||||
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(_model.Name, list);
|
||||
region.DrawingBoard.Set(_model.Name, list);
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_lazyPredictor.IsValueCreated)
|
||||
lock (_syncRoot)
|
||||
{
|
||||
Predictor.Dispose();
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
try
|
||||
{
|
||||
if (_lazyPredictor.IsValueCreated)
|
||||
{
|
||||
_lazyPredictor.Value.Dispose();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sessionOptions.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public interface IInferenceBenchmarkLeaseProvider
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
IDisposable Acquire();
|
||||
}
|
||||
|
||||
/// <summary>与独立任务使用同一把锁,暂停并等待正在执行的自动识别帧完成。</summary>
|
||||
public sealed class InferenceBenchmarkCoordinator(SemaphoreSlim taskSemaphore, Func<IDisposable> suspend) : IInferenceBenchmarkLeaseProvider
|
||||
{
|
||||
public bool IsAvailable => taskSemaphore.CurrentCount > 0;
|
||||
public IDisposable Acquire()
|
||||
{
|
||||
if (!taskSemaphore.Wait(0)) throw new InvalidOperationException("请先停止正在运行的任务,再进行推理测速。");
|
||||
try { return new Lease(taskSemaphore, suspend()); }
|
||||
catch { taskSemaphore.Release(); throw; }
|
||||
}
|
||||
|
||||
private sealed class Lease(SemaphoreSlim semaphore, IDisposable suspension) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
try { suspension.Dispose(); }
|
||||
finally { semaphore.Release(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public interface IInferenceDeviceDiscovery
|
||||
{
|
||||
IReadOnlyList<InferenceDeviceInfo> GetDevices(InferenceDeviceType engine, string runtimeDirectory);
|
||||
}
|
||||
|
||||
/// <summary>只探测硬件 API,不加载、替换其他引擎的 onnxruntime.dll。</summary>
|
||||
public sealed class InferenceDeviceDiscovery : IInferenceDeviceDiscovery
|
||||
{
|
||||
public IReadOnlyList<InferenceDeviceInfo> GetDevices(InferenceDeviceType engine, string runtimeDirectory) => engine switch
|
||||
{
|
||||
InferenceDeviceType.Cpu => [ResolvedInferenceRuntime.CpuDevice],
|
||||
InferenceDeviceType.DirectML => GetDirectMlDevices(),
|
||||
InferenceDeviceType.CUDA or InferenceDeviceType.TensorRT => GetNvidiaDevices(engine),
|
||||
InferenceDeviceType.OpenVINO => GetOpenVinoDevices(runtimeDirectory),
|
||||
_ => []
|
||||
};
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetDirectMlDevices()
|
||||
{
|
||||
if (!BetterGenshinImpact.Helpers.OsVersionHelper.IsWindows10_1903_OrGreater) return [];
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
using var factory = new Factory1();
|
||||
for (var index = 0; ; index++)
|
||||
{
|
||||
Adapter1 adapter;
|
||||
try { adapter = factory.GetAdapter1(index); }
|
||||
catch (SharpDX.SharpDXException) { break; }
|
||||
using (adapter)
|
||||
{
|
||||
var description = adapter.Description1;
|
||||
if ((description.Flags & AdapterFlags.Software) != 0) continue;
|
||||
var iid = new Guid("189819f1-1db6-4b57-be54-1821339b85f7");
|
||||
var result = D3D12CreateDevice(adapter.NativePointer, 0xb000, ref iid, out var device);
|
||||
if (device != IntPtr.Zero) Marshal.Release(device);
|
||||
if (result < 0) continue;
|
||||
var id = GetDirectMlIdentity(description);
|
||||
devices.Add(new(id, description.Description.Trim(), index, index.ToString()));
|
||||
}
|
||||
}
|
||||
return NormalizeDirectMlDevices(devices);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<InferenceDeviceInfo> NormalizeDirectMlDevices(IReadOnlyList<InferenceDeviceInfo> devices)
|
||||
{
|
||||
// DXGI 可能暴露同一物理显卡的多个适配器入口。保留原始序号,不重新编号。
|
||||
var unique = devices.DistinctBy(device => device.Id).ToArray();
|
||||
return unique.Select(device => unique.Count(other => other.Name == device.Name) > 1
|
||||
? device with { Name = $"{device.Name}(设备 {device.Index + 1})" } : device).ToArray();
|
||||
}
|
||||
|
||||
private static string GetDirectMlIdentity(AdapterDescription1 description)
|
||||
{
|
||||
// LUID 只在一次 Windows 启动期间稳定,持久化时改用显卡的 PCI 位置和型号。
|
||||
var adapter = new KernelAdapter { Luid = description.Luid };
|
||||
if (D3DKMTOpenAdapterFromLuid(ref adapter) >= 0)
|
||||
{
|
||||
var buffer = Marshal.AllocHGlobal(Marshal.SizeOf<AdapterAddress>());
|
||||
try
|
||||
{
|
||||
var query = new AdapterQuery { Handle = adapter.Handle, Type = 6, Data = buffer, Size = (uint)Marshal.SizeOf<AdapterAddress>() };
|
||||
if (D3DKMTQueryAdapterInfo(ref query) >= 0)
|
||||
{
|
||||
var address = Marshal.PtrToStructure<AdapterAddress>(buffer);
|
||||
return $"DXGI:{description.VendorId:X4}:{description.DeviceId:X4}:{address.Bus}:{address.Device}:{address.Function}";
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
var handle = adapter.Handle;
|
||||
D3DKMTCloseAdapter(ref handle);
|
||||
}
|
||||
}
|
||||
// 非 PCI 适配器保留型号与 LUID,避免误合并多张同型号显卡。跨启动标识失效时重新选设备。
|
||||
return $"DXGI:{description.VendorId:X4}:{description.DeviceId:X4}:{description.SubsystemId:X8}:{description.Luid:X16}";
|
||||
}
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetNvidiaDevices(InferenceDeviceType engine)
|
||||
{
|
||||
if (!NativeLibrary.TryLoad(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "nvcuda.dll"), out var library)) return [];
|
||||
try
|
||||
{
|
||||
var init = Get<CudaInit>(library, "cuInit");
|
||||
var count = Get<CudaCount>(library, "cuDeviceGetCount");
|
||||
var get = Get<CudaDevice>(library, "cuDeviceGet");
|
||||
var name = Get<CudaName>(library, "cuDeviceGetName");
|
||||
var uuid = Get<CudaUuid>(library, "cuDeviceGetUuid");
|
||||
var attribute = Get<CudaAttribute>(library, "cuDeviceGetAttribute");
|
||||
var driverVersion = Get<CudaCount>(library, "cuDriverGetVersion");
|
||||
if (init(0) != 0 || driverVersion(out var version) != 0 || version < 12000 || count(out var size) != 0) return [];
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
var compatible = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var ordinal = 0; ordinal < size; ordinal++)
|
||||
{
|
||||
if (get(out var device, ordinal) != 0) continue;
|
||||
var text = new StringBuilder(256);
|
||||
if (name(text, text.Capacity, device) != 0 || uuid(out var id, device) != 0) continue;
|
||||
if (attribute(out var major, 75, device) != 0 || attribute(out var minor, 76, device) != 0) continue;
|
||||
// TensorRT 10.8 的硬件下限为 Turing (SM 7.5),不把旧显卡作为可选设备。
|
||||
var bytes = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref id, 1));
|
||||
var hex = Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
var key = $"GPU-{hex[..8]}-{hex[8..12]}-{hex[12..16]}-{hex[16..20]}-{hex[20..]}";
|
||||
devices.Add(new(key, text.ToString(), ordinal, ordinal.ToString()));
|
||||
if ((engine != InferenceDeviceType.TensorRT && major >= 5) || (engine == InferenceDeviceType.TensorRT && major * 10 + minor >= 75))
|
||||
compatible.Add(key);
|
||||
}
|
||||
// cuInit 已按 CUDA_VISIBLE_DEVICES 过滤并重排设备,ordinal 就是 ORT 需要的 device_id,不能再次映射。
|
||||
return devices.Where(device => compatible.Contains(device.Id)).ToArray();
|
||||
}
|
||||
finally { NativeLibrary.Free(library); }
|
||||
}
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetOpenVinoDevices(string directory)
|
||||
{
|
||||
var path = Path.Combine(directory, "openvino_c.dll");
|
||||
if (!File.Exists(path)) return [];
|
||||
var library = LoadLibraryEx(path, IntPtr.Zero, 0x00001100);
|
||||
if (library == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "OpenVINO 设备探测库加载失败");
|
||||
IntPtr core = IntPtr.Zero;
|
||||
var available = new OpenVinoDevices();
|
||||
try
|
||||
{
|
||||
var create = Get<OvCreate>(library, "ov_core_create");
|
||||
var get = Get<OvDevices>(library, "ov_core_get_available_devices");
|
||||
var property = Get<OvProperty>(library, "ov_core_get_property");
|
||||
var free = Get<OvFree>(library, "ov_free");
|
||||
if (create(out core) != 0 || get(core, ref available) != 0)
|
||||
throw new InvalidOperationException("无法枚举 OpenVINO 设备,请检查设备驱动。");
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
for (var i = 0; i < checked((int)available.Size); i++)
|
||||
{
|
||||
var id = Marshal.PtrToStringUTF8(Marshal.ReadIntPtr(available.Devices, i * IntPtr.Size));
|
||||
if (id == null || !(id == "CPU" || id.StartsWith("GPU", StringComparison.Ordinal) || id.StartsWith("NPU", StringComparison.Ordinal))) continue;
|
||||
string display = id;
|
||||
if (property(core, id, "FULL_DEVICE_NAME", out var value) == 0 && value != IntPtr.Zero)
|
||||
{
|
||||
try { display = $"{id} · {Marshal.PtrToStringUTF8(value)}"; }
|
||||
finally { free(value); }
|
||||
}
|
||||
devices.Add(new(id, display, i, id));
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (available.Devices != IntPtr.Zero) Get<OvDevicesFree>(library, "ov_available_devices_free")(ref available);
|
||||
if (core != IntPtr.Zero) Get<OvFree>(library, "ov_core_free")(core);
|
||||
NativeLibrary.Free(library);
|
||||
}
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr library, string name) where T : Delegate => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library, name));
|
||||
[StructLayout(LayoutKind.Sequential)] private struct DeviceUuid { public uint A, B, C, D; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct KernelAdapter { public long Luid; public uint Handle; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct AdapterAddress { public uint Bus, Device, Function; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct AdapterQuery { public uint Handle; public int Type; public IntPtr Data; public uint Size; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct OpenVinoDevices { public IntPtr Devices; public nuint Size; }
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaInit(uint flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaCount(out int count);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaDevice(out int device, int ordinal);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet = CharSet.Ansi)] private delegate int CudaName(StringBuilder name, int length, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaUuid(out DeviceUuid uuid, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaAttribute(out int value, int attribute, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvCreate(out IntPtr core);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvDevices(IntPtr core, ref OpenVinoDevices devices);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void OvDevicesFree(ref OpenVinoDevices devices);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvProperty(IntPtr core, [MarshalAs(UnmanagedType.LPUTF8Str)] string device, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, out IntPtr value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void OvFree(IntPtr value);
|
||||
[DllImport("d3d12.dll")] private static extern int D3D12CreateDevice(IntPtr adapter, int level, ref Guid iid, out IntPtr device);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTOpenAdapterFromLuid(ref KernelAdapter adapter);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTQueryAdapterInfo(ref AdapterQuery query);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTCloseAdapter(ref uint handle);
|
||||
[DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr LoadLibraryEx(string path, IntPtr file, uint flags);
|
||||
}
|
||||
@@ -1,9 +1,32 @@
|
||||
// ReSharper disable InconsistentNaming
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
[JsonConverter(typeof(InferenceDeviceTypeJsonConverter))]
|
||||
public enum InferenceDeviceType
|
||||
{
|
||||
Cpu,
|
||||
GpuDirectMl,
|
||||
Gpu,
|
||||
OpenVino
|
||||
}
|
||||
// 保持已有后端的配置编号,旧 Gpu 的编号 2 不再复用,读取时回退 CPU。
|
||||
Cpu = 0,
|
||||
DirectML = 1,
|
||||
OpenVINO = 3,
|
||||
CUDA = 4,
|
||||
// TensorRT 推理速度特别慢(首次还要构建引擎,等待时间更长),已从设置页与首页下线:
|
||||
// 界面不再提供该选项,历史配置在启动准备阶段自动回退 CPU。枚举编号、运行库与 provider 代码保留,便于日后恢复。
|
||||
TensorRT = 5
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推理引擎在界面上的可用范围。TensorRT 首次构建引擎耗时过长,已从设置页与首页下线;
|
||||
/// 枚举编号、运行库与 provider 代码保留,便于日后恢复。
|
||||
/// </summary>
|
||||
public static class InferenceDeviceTypeExtensions
|
||||
{
|
||||
/// <summary>设置页与首页可供用户选择的推理引擎,顺序即界面顺序。</summary>
|
||||
public static readonly InferenceDeviceType[] Selectable =
|
||||
[InferenceDeviceType.Cpu, InferenceDeviceType.DirectML, InferenceDeviceType.OpenVINO, InferenceDeviceType.CUDA];
|
||||
|
||||
public static bool IsSelectable(this InferenceDeviceType engine) => Selectable.Contains(engine);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>
|
||||
/// 保留现有数字配置格式;旧 Gpu、未知枚举值和无法识别的设置只回退推理类型,
|
||||
/// 不让单个字段的兼容问题导致整份配置读取失败。
|
||||
/// </summary>
|
||||
public sealed class InferenceDeviceTypeJsonConverter : JsonConverter<InferenceDeviceType>
|
||||
{
|
||||
public override bool HandleNull => true;
|
||||
|
||||
public override InferenceDeviceType Read(ref Utf8JsonReader reader, Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out var number))
|
||||
{
|
||||
var value = (InferenceDeviceType)number;
|
||||
return Enum.IsDefined(value) ? value : InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
var name = reader.GetString();
|
||||
// 未标记 Flags 的枚举也能解析逗号组合,推理类型只接受一个明确的选项。
|
||||
if (name is not null && !name.Contains(',') &&
|
||||
Enum.TryParse<InferenceDeviceType>(name, true, out var value) && Enum.IsDefined(value))
|
||||
return value;
|
||||
}
|
||||
|
||||
// 对错误的对象或数组值消费整个节点,继续读取同一配置中的其他字段。
|
||||
reader.Skip();
|
||||
return InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, InferenceDeviceType value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteNumberValue(Enum.IsDefined(value) ? (int)value : (int)InferenceDeviceType.Cpu);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>每个引擎独立保存的用户设置,原生 provider 的参数由工厂统一生成。</summary>
|
||||
public partial class InferenceEngineSettings : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string _deviceId = "";
|
||||
[ObservableProperty] private int _cpuThreads;
|
||||
[ObservableProperty] private bool _enableModelCache = true;
|
||||
|
||||
public InferenceEngineSettings Copy() => new()
|
||||
{
|
||||
DeviceId = DeviceId, CpuThreads = CpuThreads, EnableModelCache = EnableModelCache
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Image = SixLabors.ImageSharp.Image;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public sealed record InferenceBenchmarkProgress(string Scene, int Completed, int Total);
|
||||
public sealed record InferenceBenchmarkResult(string Scene, string Execution, IReadOnlyList<double> Milliseconds)
|
||||
{
|
||||
public double Average => Milliseconds.Average();
|
||||
public double Minimum => Milliseconds.Min();
|
||||
public double Maximum => Milliseconds.Max();
|
||||
public string SamplesText => "每次耗时(ms):" + string.Join(" / ", Milliseconds.Select(t => t.ToString("F1")));
|
||||
}
|
||||
|
||||
/// <summary>将面向用户的失败原因与供日志排查的原始技术信息分开。</summary>
|
||||
internal sealed class InferenceValidationException(
|
||||
string scene, string userReason, string technicalDetails, Exception? innerException = null)
|
||||
: InvalidOperationException(technicalDetails, innerException)
|
||||
{
|
||||
public string Scene { get; } = scene;
|
||||
public string UserReason { get; } = userReason;
|
||||
}
|
||||
|
||||
public interface IInferenceModelDiagnostics
|
||||
{
|
||||
bool HasDomainTreeImage { get; }
|
||||
Task ValidateTreeAsync(BgiOnnxSessionFactory factory, CancellationToken token);
|
||||
Task ValidateOcrAsync(BgiOnnxSessionFactory factory, CancellationToken token);
|
||||
Task PreheatOcrAsync();
|
||||
Task<InferenceBenchmarkResult> BenchmarkAsync(InferenceBenchmarkScene scene, BgiOnnxSessionFactory factory,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token);
|
||||
}
|
||||
|
||||
public sealed class InferenceModelDiagnostics(
|
||||
OcrFactory ocr, IInferenceBenchmarkLeaseProvider leases, ILogger<InferenceModelDiagnostics> logger)
|
||||
: IInferenceModelDiagnostics, IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly object _warmupLock = new();
|
||||
private Task? _warmupTask;
|
||||
public bool HasDomainTreeImage => InferenceTestImages.HasDomainTreeImage;
|
||||
|
||||
public Task PreheatOcrAsync()
|
||||
{
|
||||
lock (_warmupLock)
|
||||
return _warmupTask ??= Task.Run(async () =>
|
||||
{
|
||||
await _gate.WaitAsync(_lifetime.Token);
|
||||
try
|
||||
{
|
||||
_lifetime.Token.ThrowIfCancellationRequested();
|
||||
var service = ocr.PaddleOcr;
|
||||
using var image = new Mat(ocr.ActiveModelType.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 预热图片无法读取。");
|
||||
Debug.WriteLine("PaddleOcr预热结果:" + service.Ocr(image));
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}, _lifetime.Token);
|
||||
}
|
||||
|
||||
public async Task ValidateTreeAsync(BgiOnnxSessionFactory factory, CancellationToken token)
|
||||
{
|
||||
if (!HasDomainTreeImage) throw new FileNotFoundException("古树测试图片待提供。", InferenceTestImages.DomainTreePath);
|
||||
await ValidateAsync(factory, "古树检测", validationToken =>
|
||||
{
|
||||
using var image = Image.Load<Rgb24>(InferenceTestImages.DomainTreePath);
|
||||
using var predictor = factory.CreateYoloPredictor(BgiOnnxModel.BgiTree);
|
||||
_ = predictor.Predictor.Detect(image);
|
||||
logger.LogInformation("[ONNX]古树检测完整推理已执行");
|
||||
}, token);
|
||||
}
|
||||
|
||||
public Task ValidateOcrAsync(BgiOnnxSessionFactory factory, CancellationToken token)
|
||||
=> ValidateAsync(factory, "OCR", validationToken =>
|
||||
{
|
||||
var model = ocr.ActiveModelType;
|
||||
using var image = new Mat(model.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 验证图片无法读取。");
|
||||
using var service = new PaddleOcrService(factory.ForOcrValidation(), model);
|
||||
validationToken.ThrowIfCancellationRequested();
|
||||
_ = service.Ocr(image);
|
||||
logger.LogInformation("[ONNX]OCR 验证完整推理已执行");
|
||||
}, token);
|
||||
|
||||
/// <summary>验证所选 provider 能创建会话并完成一次真实推理;不再解析性能记录判断单个算子的执行位置。</summary>
|
||||
private async Task ValidateAsync(BgiOnnxSessionFactory factory, string scene,
|
||||
Action<CancellationToken> inference, CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
await _gate.WaitAsync(linked.Token);
|
||||
try
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
inference(linked.Token);
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (InferenceValidationException) { throw; }
|
||||
catch (Exception e)
|
||||
{
|
||||
throw CreateRuntimeFailure(scene, factory.Runtime, e);
|
||||
}
|
||||
}, linked.Token);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
internal static InferenceValidationException CreateRuntimeFailure(string scene, ResolvedInferenceRuntime runtime,
|
||||
Exception exception)
|
||||
{
|
||||
var cause = exception.GetBaseException();
|
||||
var message = cause.Message;
|
||||
var missingDependencies = OnnxRuntimePackageCatalog.MissingDependencyFiles(runtime.Engine, runtime.RuntimeDirectory);
|
||||
string reason;
|
||||
if (missingDependencies.Length > 0 &&
|
||||
(cause is DllNotFoundException || message.Contains("LoadLibrary", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("找不到指定的模块", StringComparison.OrdinalIgnoreCase)))
|
||||
reason = OnnxRuntimePackageCatalog.DescribeMissingDependencies(runtime.Engine, missingDependencies);
|
||||
else if (cause is DllNotFoundException || message.Contains("LoadLibrary", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("找不到指定的模块", StringComparison.OrdinalIgnoreCase))
|
||||
reason = "运行库或配套依赖无法加载,请在硬件加速设置中重新检测并补齐依赖。";
|
||||
else if (cause is BadImageFormatException)
|
||||
reason = "运行库文件与当前系统不兼容,请重新下载该推理引擎。";
|
||||
else if (cause is FileNotFoundException fileNotFound)
|
||||
reason = $"验证需要的文件“{Path.GetFileName(fileNotFound.FileName) ?? "未知文件"}”不存在。";
|
||||
else if (cause is OutOfMemoryException || message.Contains("out of memory", StringComparison.OrdinalIgnoreCase))
|
||||
reason = "运行模型时内存或显存不足。";
|
||||
else if (message.Contains("device", StringComparison.OrdinalIgnoreCase)
|
||||
&& (message.Contains("not found", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("unavailable", StringComparison.OrdinalIgnoreCase)))
|
||||
reason = "保存的推理设备当前不可用,请重新选择设备。";
|
||||
else
|
||||
reason = $"加载或运行{scene}模型时发生错误,详细错误已记录到硬件加速设置和日志中。";
|
||||
|
||||
var technicalDetails = $"{scene}验证异常:{message}";
|
||||
if (missingDependencies.Length > 0)
|
||||
technicalDetails += $"\r\n运行库目录:{runtime.RuntimeDirectory}\r\n缺少依赖:{string.Join("、", missingDependencies)}";
|
||||
return new InferenceValidationException(scene, reason, technicalDetails, exception);
|
||||
}
|
||||
|
||||
public async Task<InferenceBenchmarkResult> BenchmarkAsync(InferenceBenchmarkScene scene, BgiOnnxSessionFactory factory,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
if (scene == InferenceBenchmarkScene.DomainTree && !HasDomainTreeImage) throw new FileNotFoundException("古树测试图片待提供。");
|
||||
using var lease = await Task.Run(leases.Acquire, linked.Token);
|
||||
await _gate.WaitAsync(linked.Token);
|
||||
try
|
||||
{
|
||||
// 在主程序后台测量,结束单次原生调用之后才能响应取消并释放会话。
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
if (scene == InferenceBenchmarkScene.Ocr)
|
||||
{
|
||||
var type = ocr.ActiveModelType;
|
||||
using var service = new PaddleOcrService(factory, type);
|
||||
using var image = new Mat(ocr.ActiveModelType.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 测试图片无法读取。");
|
||||
return Measure("OCR", $"{factory.Runtime.OcrDescription} · {type.DetectionModel.Name}/{type.RecognitionModel.Name}",
|
||||
() => _ = service.Ocr(image), progress, linked.Token);
|
||||
}
|
||||
using var treeImage = Image.Load<Rgb24>(InferenceTestImages.DomainTreePath);
|
||||
using var predictor = factory.CreateYoloPredictor(BgiOnnxModel.BgiTree);
|
||||
return Measure("古树检测", factory.Runtime.Description,
|
||||
() => _ = predictor.Predictor.Detect(treeImage), progress, linked.Token);
|
||||
}, linked.Token);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public static InferenceBenchmarkResult Measure(string scene, string execution, Action inference,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
progress?.Report(new(scene + "预热", 0, 10));
|
||||
inference();
|
||||
var times = new double[10];
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var start = Stopwatch.GetTimestamp();
|
||||
inference();
|
||||
times[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
|
||||
progress?.Report(new(scene, i + 1, times.Length));
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
return new(scene, execution, times);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
Task? warmup;
|
||||
lock (_warmupLock) warmup = _warmupTask;
|
||||
if (warmup != null)
|
||||
{
|
||||
try { await warmup; }
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception) { /* 预热错误已经由调用方报告;退出仍须等待资源释放。 */ }
|
||||
}
|
||||
await _gate.WaitAsync();
|
||||
_gate.Release();
|
||||
}
|
||||
|
||||
public void Dispose() { _lifetime.Dispose(); _gate.Dispose(); }
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>仅属于本次启动的提示,不从持久化的历史验证错误恢复。</summary>
|
||||
public sealed record InferenceStartupStatus(string FallbackMessage, bool IsMainInstance = true);
|
||||
|
||||
/// <summary>设备配置先发布;主窗口加载后的友好验证不作为业务初始化的前置条件。</summary>
|
||||
public sealed class InferenceRuntimeService(
|
||||
IConfigService configService, IOnnxRuntimeSelection loader, IInferenceDeviceDiscovery devices,
|
||||
IInferenceModelDiagnostics diagnostics, ILogger<BgiOnnxFactory> logger, InferenceStartupStatus? startupStatus = null) : IDisposable
|
||||
{
|
||||
private sealed record PublishedRuntime(ResolvedInferenceRuntime Runtime, bool IsValidated);
|
||||
|
||||
private PublishedRuntime? _published;
|
||||
private readonly object _initializationLock = new();
|
||||
private readonly object _settingsLock = new();
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private Task? _initializationTask;
|
||||
private Task? _validationTask;
|
||||
private long _settingsRevision;
|
||||
private long _startupRevision;
|
||||
private PublishedRuntime Published => Volatile.Read(ref _published)
|
||||
?? throw new InvalidOperationException("推理初始化尚未完成。");
|
||||
public ResolvedInferenceRuntime Current => Published.Runtime;
|
||||
public bool IsReady => Volatile.Read(ref _published) != null;
|
||||
public bool IsStopping => _lifetime.IsCancellationRequested;
|
||||
public bool IsCurrentValidated => Volatile.Read(ref _published)?.IsValidated ?? false;
|
||||
public bool HasPendingRestart => Interlocked.Read(ref _settingsRevision) != Interlocked.Read(ref _startupRevision);
|
||||
public string StartupMessage { get; private set; } = startupStatus?.FallbackMessage ?? "";
|
||||
public event EventHandler? SettingsChanged;
|
||||
private bool IsMainInstance => startupStatus?.IsMainInstance ?? true;
|
||||
private HardwareAccelerationConfig Config => configService.Get().HardwareAccelerationConfig;
|
||||
|
||||
public static InferenceStartupStatus PrepareStartup(HardwareAccelerationConfig config, bool isMainInstance = true)
|
||||
{
|
||||
var fallbackMessage = "";
|
||||
config.LastValidationError ??= "";
|
||||
config.VerifiedSignature ??= "";
|
||||
config.ValidatedEngines ??= [];
|
||||
// 新增 OCR 参数单独修正,避免无效比例或换用核心数较少的处理器时丢失其他引擎设置。
|
||||
config.PaddleOcrCpu = PaddleOcrCpuConfig.FromOptions((config.PaddleOcrCpu ?? new()).ToOptions().Normalize());
|
||||
if (config.IsExpectedConfiguration && !string.IsNullOrWhiteSpace(config.VerifiedSignature))
|
||||
{
|
||||
// 兼容已有的单份验证签名:只恢复能与保存参数匹配的历史成功记录。
|
||||
foreach (var engine in Enum.GetValues<InferenceDeviceType>().Where(engine => engine != InferenceDeviceType.Cpu))
|
||||
{
|
||||
var settings = config.GetEngineSettings(engine);
|
||||
if (string.IsNullOrWhiteSpace(settings.DeviceId)) continue;
|
||||
if (InferenceRuntimeFingerprint.Compute(config, engine) == config.VerifiedSignature)
|
||||
config.RecordValidatedEngine(engine);
|
||||
}
|
||||
}
|
||||
if (!config.IsExpectedConfiguration)
|
||||
{
|
||||
config.ResetToDefaults();
|
||||
config.LastFailedEngine = null;
|
||||
config.LastValidationError = "";
|
||||
}
|
||||
else if (!config.InferenceDevice.IsSelectable())
|
||||
{
|
||||
// TensorRT 已下线:只把生效引擎改回 CPU,其他引擎已保存的设备参数保持不变。
|
||||
var retiredEngine = config.InferenceDevice;
|
||||
config.SwitchToCpu();
|
||||
config.LastFailedEngine = null;
|
||||
config.LastValidationError = "";
|
||||
fallbackMessage = $"{retiredEngine} 推理引擎已停止提供(首次构建引擎耗时过长),本次已使用 CPU。\r\n\r\n" +
|
||||
"请在首页的“硬件加速设置”中选择其他引擎后重试。";
|
||||
}
|
||||
else if (isMainInstance && config.ValidationState == InferenceValidationState.Validating)
|
||||
{
|
||||
var failedEngine = config.InferenceDevice;
|
||||
config.SwitchToCpu();
|
||||
config.LastFailedEngine = failedEngine;
|
||||
config.LastValidationError = "上一次推理验证未正常完成,已回退 CPU。";
|
||||
fallbackMessage = $"{failedEngine} 上一次推理验证未正常完成,本次已使用 CPU。";
|
||||
}
|
||||
// PendingRestart 在窗口加载前保持原样,真正开始验证时才记录 Validating。
|
||||
return new(fallbackMessage, isMainInstance);
|
||||
}
|
||||
|
||||
/// <summary>只准备设备与生效配置,不创建模型、运行推理或弹出提示。</summary>
|
||||
public Task InitializeAsync(CancellationToken token = default)
|
||||
{
|
||||
lock (_initializationLock) return _initializationTask ??= InitializeCoreAsync(token);
|
||||
}
|
||||
|
||||
private async Task InitializeCoreAsync(CancellationToken token)
|
||||
{
|
||||
if (IsReady) return;
|
||||
var config = Config;
|
||||
// LastValidationError 只用于设置页的历史详情,不能冒充本次启动的失败重新弹窗。
|
||||
if (loader.InferenceDevice != config.InferenceDevice)
|
||||
{
|
||||
FallBack(config.InferenceDevice, "运行库加载",
|
||||
string.IsNullOrWhiteSpace(loader.FailureReason)
|
||||
? "所选运行库无法加载或依赖不完整,请在硬件加速设置中重新检测并补齐依赖。"
|
||||
: loader.FailureReason,
|
||||
loader.StatusText);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var selected = config.GetEngineSettings(config.InferenceDevice);
|
||||
var found = await Task.Run(() => devices.GetDevices(config.InferenceDevice, loader.RuntimeDirectory), token);
|
||||
var device = found.FirstOrDefault(d => d.Id == selected.DeviceId)
|
||||
?? throw new InvalidOperationException("保存的推理设备不可用,请重新选择设备。");
|
||||
var runtime = ResolvedInferenceRuntime.Resolve(config, device, loader.RuntimeDirectory);
|
||||
var isValidated = runtime.Engine == InferenceDeviceType.Cpu
|
||||
|| (config.ValidationState == InferenceValidationState.None && config.VerifiedSignature == runtime.Fingerprint);
|
||||
_startupRevision = Interlocked.Read(ref _settingsRevision);
|
||||
Volatile.Write(ref _published, new(runtime, isValidated));
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogWarning(e, "[ONNX]推理设备初始化失败,回退 CPU");
|
||||
var reason = e.Message.Contains("设备不可用", StringComparison.Ordinal)
|
||||
? e.Message
|
||||
: "无法初始化保存的推理设备,请在硬件加速设置中重新选择设备。";
|
||||
FallBack(config.InferenceDevice, "设备初始化", reason, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>仅由主实例的 MainWindowViewModel.OnLoaded 调用;重复调用共用同一任务。</summary>
|
||||
public Task ValidatePendingAsync(CancellationToken token = default)
|
||||
{
|
||||
if (!IsMainInstance) return Task.CompletedTask;
|
||||
lock (_initializationLock) return _validationTask ??= ValidatePendingCoreAsync(token);
|
||||
}
|
||||
|
||||
private async Task ValidatePendingCoreAsync(CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
await InitializeAsync(linked.Token);
|
||||
var published = Published;
|
||||
if (published.IsValidated)
|
||||
{
|
||||
if (!HasPendingRestart && Config.ValidationState == InferenceValidationState.PendingRestart)
|
||||
{
|
||||
Config.ValidationState = InferenceValidationState.None;
|
||||
configService.Save();
|
||||
SettingsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var runtime = published.Runtime;
|
||||
bool ownsSavedSettings;
|
||||
lock (_settingsLock)
|
||||
{
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
if (ownsSavedSettings) Config.ValidationState = InferenceValidationState.Validating;
|
||||
}
|
||||
// 验证中的状态必须先落盘,原生调用异常中断后下一次启动才能安全回退。
|
||||
if (ownsSavedSettings) configService.Save();
|
||||
try
|
||||
{
|
||||
// 缺图不是引擎故障:古树场景仍待接入,先通过独立 OCR 会话验证引擎。
|
||||
var factory = new BgiOnnxSessionFactory(logger, runtime);
|
||||
if (diagnostics.HasDomainTreeImage)
|
||||
await diagnostics.ValidateTreeAsync(factory, linked.Token).ConfigureAwait(false);
|
||||
else
|
||||
await diagnostics.ValidateOcrAsync(factory, linked.Token).ConfigureAwait(false);
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
lock (_settingsLock)
|
||||
{
|
||||
Volatile.Write(ref _published, published with { IsValidated = true });
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
// 即使验证期间保存了其他引擎,也保留本次成功记录;不覆盖新的待重启设置。
|
||||
Config.RecordValidatedEngine(runtime.Engine);
|
||||
if (ownsSavedSettings)
|
||||
{
|
||||
Config.VerifiedSignature = runtime.Fingerprint;
|
||||
Config.ValidationState = InferenceValidationState.None;
|
||||
Config.LastFailedEngine = null;
|
||||
Config.LastValidationError = "";
|
||||
}
|
||||
}
|
||||
configService.Save();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 正常退出取消友好验证并不说明引擎不可用,保留待验证设置供下次主实例加载。
|
||||
lock (_settingsLock)
|
||||
{
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
if (ownsSavedSettings) Config.ValidationState = InferenceValidationState.PendingRestart;
|
||||
}
|
||||
if (ownsSavedSettings) configService.Save();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogWarning(e, "[ONNX]主窗口推理验证失败,回退 CPU");
|
||||
var validationError = e as InferenceValidationException;
|
||||
FallBack(runtime.Engine,
|
||||
validationError?.Scene ?? "模型验证",
|
||||
validationError?.UserReason ?? "加载或运行验证模型时发生错误,详细错误已记录到硬件加速设置和日志中。",
|
||||
e.ToString(),
|
||||
_startupRevision);
|
||||
}
|
||||
finally { SettingsChanged?.Invoke(this, EventArgs.Empty); }
|
||||
}
|
||||
|
||||
private void FallBack(InferenceDeviceType engine, string stage, string userReason, string technicalDetails,
|
||||
long? validationRevision = null)
|
||||
{
|
||||
lock (_settingsLock)
|
||||
{
|
||||
// 非主实例只能回退本进程的运行时快照,不能改写主实例共享的持久化设置。
|
||||
if (IsMainInstance)
|
||||
{
|
||||
// 验证期间用户可能已保存新的设置,旧验证结果不能覆盖下一次启动的选择。
|
||||
if (validationRevision == null || _settingsRevision == validationRevision)
|
||||
{
|
||||
Config.SwitchToCpu();
|
||||
}
|
||||
Config.LastFailedEngine = engine;
|
||||
}
|
||||
if (IsMainInstance)
|
||||
Config.LastValidationError = $"失败环节:{stage}\r\n失败原因:{userReason}\r\n\r\n技术详情:{technicalDetails}";
|
||||
StartupMessage = $"{engine} 加速验证失败,已自动切换为 CPU。\r\n\r\n" +
|
||||
$"失败环节:{stage}\r\n失败原因:{userReason}\r\n\r\n" +
|
||||
"软件仍可正常使用。你可以继续使用 CPU,或在首页的“硬件加速设置”中选择其他设备后重试。";
|
||||
var cpu = ResolvedInferenceRuntime.Cpu(Config.Cpu.CpuThreads, Config.PaddleOcrCpu.ToOptions(),
|
||||
loader.RuntimeDirectory);
|
||||
Volatile.Write(ref _published, new(cpu, true));
|
||||
}
|
||||
if (IsMainInstance) configService.Save();
|
||||
}
|
||||
|
||||
public void Apply(InferenceDeviceType engine, InferenceEngineSettings settings, bool cpuOcr, int cpuThreads,
|
||||
PaddleOcrCpuOptions? paddleOcrCpu = null)
|
||||
{
|
||||
if (!Enum.IsDefined(engine) || string.IsNullOrWhiteSpace(settings.DeviceId) || cpuThreads < 0 || cpuThreads > Environment.ProcessorCount)
|
||||
throw new ArgumentException("推理设置不符合预期。");
|
||||
if (paddleOcrCpu is { IsValid: false }) throw new ArgumentException("OCR CPU 线程策略参数不符合预期。");
|
||||
// TensorRT 已下线:任何调用方都不能再把生效引擎切回该引擎。
|
||||
if (!engine.IsSelectable()) throw new ArgumentException($"{engine} 推理引擎已停止提供,请选择其他引擎。");
|
||||
lock (_settingsLock)
|
||||
{
|
||||
_settingsRevision++;
|
||||
var config = Config;
|
||||
var target = config.GetEngineSettings(engine);
|
||||
target.DeviceId = settings.DeviceId;
|
||||
target.EnableModelCache = settings.EnableModelCache;
|
||||
config.Cpu.CpuThreads = cpuThreads;
|
||||
if (paddleOcrCpu != null) config.PaddleOcrCpu = PaddleOcrCpuConfig.FromOptions(paddleOcrCpu);
|
||||
config.CpuOcr = cpuOcr;
|
||||
config.InferenceDevice = engine;
|
||||
config.FormatVersion = 1;
|
||||
config.ValidationState = InferenceValidationState.PendingRestart;
|
||||
}
|
||||
configService.Save();
|
||||
SettingsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
Task? validation;
|
||||
lock (_initializationLock) validation = _validationTask;
|
||||
if (validation != null) await validation;
|
||||
}
|
||||
|
||||
public void Dispose() => _lifetime.Dispose();
|
||||
}
|
||||
Loaded 100 of 974 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user