Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c8210c3b5 | ||
|
|
ad4125510b | ||
|
|
ffd87f2b11 | ||
|
|
dca422de8e | ||
|
|
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 | ||
|
|
f614695a3a | ||
|
|
77306168f9 | ||
|
|
dee418cbe5 | ||
|
|
226785e8a4 | ||
|
|
5a5b77266e | ||
|
|
864efb42a3 | ||
|
|
32582e39a9 | ||
|
|
6bcb63e996 | ||
|
|
65b5032e6e | ||
|
|
b9e1c37b67 | ||
|
|
a5829ed6bb | ||
|
|
8b7d2353e5 | ||
|
|
c3b8c9e78f | ||
|
|
b49910873e | ||
|
|
ea6a9a4af2 | ||
|
|
a51213dceb | ||
|
|
e3c451cd92 | ||
|
|
e69283c3f2 | ||
|
|
23de87d1a6 | ||
|
|
dad2e8ef7d | ||
|
|
7e944e18fb | ||
|
|
f1154e6ef7 | ||
|
|
b2d5988d24 | ||
|
|
c2b68cfee9 | ||
|
|
6668a89fa7 | ||
|
|
01f1beba0b | ||
|
|
9e3c8920ba | ||
|
|
ce31169f66 | ||
|
|
53854e6d28 | ||
|
|
01c506fa13 | ||
|
|
95e0f01753 | ||
|
|
4aaca366f0 | ||
|
|
cac0dfc754 | ||
|
|
847bc8970e | ||
|
|
d4d99d34bc | ||
|
|
f86abe3ceb | ||
|
|
b1c6e9e4e3 | ||
|
|
d632bdd9fc | ||
|
|
fe61549c95 | ||
|
|
6832d0f8d8 | ||
|
|
a872dde7c8 | ||
|
|
12423edd6e | ||
|
|
9fe0209122 | ||
|
|
6e49368f0a | ||
|
|
f80939dad4 | ||
|
|
f7976b0bbd | ||
|
|
e9d11f7267 | ||
|
|
20fe152630 | ||
|
|
3c883fcf05 | ||
|
|
a4684ee6f7 | ||
|
|
edf0c695c6 | ||
|
|
12db6280b2 | ||
|
|
ffec4aadbe | ||
|
|
368ca18d9f | ||
|
|
891c695383 | ||
|
|
53051eff11 | ||
|
|
0797f20f26 | ||
|
|
77f8013bb0 | ||
|
|
df8e7288c1 | ||
|
|
e565f4b438 | ||
|
|
a8de2fb41a | ||
|
|
a0584f6fdc | ||
|
|
44459cbca7 | ||
|
|
c37ebae3bc | ||
|
|
2f7e64ac57 | ||
|
|
87c21f85bf | ||
|
|
7b7efdce80 | ||
|
|
536ed10dbf | ||
|
|
67ced40b6b | ||
|
|
b242d98208 | ||
|
|
28c50211a7 | ||
|
|
9f67726781 | ||
|
|
a2bd48a56f | ||
|
|
b9b251aa13 | ||
|
|
8ab64a70b5 | ||
|
|
c24329eca6 | ||
|
|
57421b9a45 | ||
|
|
efc66e6062 | ||
|
|
e8c067f7c0 | ||
|
|
292dc8fb4f | ||
|
|
0d466e5022 | ||
|
|
908294e2fe | ||
|
|
b3e2a08a6d | ||
|
|
c28aba2bab | ||
|
|
08583c776f | ||
|
|
e15a1d7276 | ||
|
|
f80afc0244 | ||
|
|
2caa6ee9f3 | ||
|
|
2f2311aa68 | ||
|
|
4f7afb6a34 | ||
|
|
2f3ca34704 | ||
|
|
ea1a30a685 | ||
|
|
b61ceae5ea | ||
|
|
bf3957d4e8 | ||
|
|
7c026fcf5f | ||
|
|
50055c3f26 | ||
|
|
6b2f2543c4 | ||
|
|
a24dd1c778 | ||
|
|
2ced2862b3 | ||
|
|
73422860af | ||
|
|
b5787aa9d3 | ||
|
|
f38e3e05ae | ||
|
|
db67429350 | ||
|
|
5484aea335 | ||
|
|
a948c70baf | ||
|
|
688bdcd8ae | ||
|
|
3f2f45e3b1 | ||
|
|
ff3e89aa1c | ||
|
|
ddf1c72ba3 | ||
|
|
a651bbfbe5 | ||
|
|
a9cf0dcfb3 | ||
|
|
e3caf32b94 | ||
|
|
0761652e31 | ||
|
|
abc2b5dd19 | ||
|
|
200f904a64 | ||
|
|
ab498fa731 | ||
|
|
42ef97b1cd | ||
|
|
3beb762223 | ||
|
|
fc942bd8cd | ||
|
|
da80dd02c4 | ||
|
|
0c4f7f30c8 | ||
|
|
62481baba9 | ||
|
|
3d6a24d11c | ||
|
|
1d9e05dc2c | ||
|
|
b612e70592 | ||
|
|
2854e14f97 | ||
|
|
af2028c2b5 | ||
|
|
99784c4263 | ||
|
|
e1545a3508 | ||
|
|
e9611d9e22 | ||
|
|
de79d8a61c | ||
|
|
ad4525c36f | ||
|
|
a169489ac0 | ||
|
|
1bc51be511 | ||
|
|
2a413c5dfc | ||
|
|
ea3f653d95 | ||
|
|
6e9da06f08 | ||
|
|
a90da14842 | ||
|
|
6efee18f69 | ||
|
|
98ceba2315 | ||
|
|
1d3e44c113 | ||
|
|
e25194e29a | ||
|
|
61eb5f4fe3 | ||
|
|
2d5c7f6e1f | ||
|
|
3b3236d9f9 | ||
|
|
01b52a5d78 | ||
|
|
2f44f74daa | ||
|
|
8a99c2a63b | ||
|
|
1b748f4dc7 | ||
|
|
cbef23b7ba | ||
|
|
9e18dcf018 | ||
|
|
d4b8b09210 | ||
|
|
a7f030711b | ||
|
|
8fd6c64c14 | ||
|
|
4e24701b1d | ||
|
|
3068069e79 | ||
|
|
73c142d33f | ||
|
|
7333020e3a | ||
|
|
5f4185b7f0 | ||
|
|
45a76d03d1 | ||
|
|
9372c007f8 | ||
|
|
53c2751eb0 | ||
|
|
117be11b8f | ||
|
|
655f938fb9 | ||
|
|
62a0611e3d | ||
|
|
7caab0854e | ||
|
|
fde3d79265 | ||
|
|
9697e4ebec | ||
|
|
b08e8485c3 | ||
|
|
b32da6f902 | ||
|
|
81f21e5bc9 | ||
|
|
f2ebea497c | ||
|
|
e0c495fae3 | ||
|
|
358b56fca2 | ||
|
|
9b888a2430 | ||
|
|
36477f9d39 | ||
|
|
ac915a9639 | ||
|
|
018bc35659 | ||
|
|
6eaea38dcf | ||
|
|
ddbf50121a | ||
|
|
843b929841 | ||
|
|
e278ac1bf0 | ||
|
|
158eb97056 | ||
|
|
af90b930bd | ||
|
|
f5d783d473 | ||
|
|
c7c0a1eb4b | ||
|
|
d07b5e8571 | ||
|
|
3167bf6590 | ||
|
|
1c05245b83 | ||
|
|
8eb50fade4 | ||
|
|
c0e1c4c28b | ||
|
|
cd3ace0b62 | ||
|
|
15d6525b14 | ||
|
|
6332905b7b | ||
|
|
16a8142faa | ||
|
|
6db5926dce | ||
|
|
24c134fb11 | ||
|
|
902dbdecd6 | ||
|
|
26d8499419 | ||
|
|
d0bb5be3b1 | ||
|
|
ba222b90a6 | ||
|
|
d2b2c9afb7 | ||
|
|
645b7fd607 | ||
|
|
9c3810a7ef | ||
|
|
f7190a9042 | ||
|
|
7229bf1c05 | ||
|
|
cbf1cf1efc | ||
|
|
6f9044c792 | ||
|
|
2174fc1b04 | ||
|
|
d830dea328 | ||
|
|
cd5b22548c | ||
|
|
71e64fe2a0 | ||
|
|
d46d594f31 | ||
|
|
bda91816d4 | ||
|
|
97486e7222 | ||
|
|
8fc0cc264f | ||
|
|
bcfc3f7c7e | ||
|
|
ed61c9dfe7 | ||
|
|
c3871e0286 | ||
|
|
947752f17b | ||
|
|
6eca5dfc7b | ||
|
|
8cc8d97780 | ||
|
|
cced20e8e4 | ||
|
|
88bcf9b151 | ||
|
|
b4a1e9a2ab | ||
|
|
cf7eab0939 | ||
|
|
f73a546acb | ||
|
|
f1dd7bdd54 | ||
|
|
f66a96f0c0 | ||
|
|
530c7df520 | ||
|
|
39be95f126 | ||
|
|
c1b7a3c1f7 | ||
|
|
a40643e828 | ||
|
|
85829868a1 | ||
|
|
a960ef40e9 | ||
|
|
573f7f13b8 | ||
|
|
3d526c2314 | ||
|
|
47784ca01c | ||
|
|
f618f87326 | ||
|
|
c7c25b104f | ||
|
|
59cf8316b0 | ||
|
|
2c32dafd44 | ||
|
|
048e69e78b | ||
|
|
4d5af17f98 | ||
|
|
9c3a2d738d | ||
|
|
fb272c1756 | ||
|
|
8f432f6a43 | ||
|
|
918aaf3b99 | ||
|
|
c2a7fd3b92 | ||
|
|
b2995e7402 | ||
|
|
72446fe519 | ||
|
|
275b2a5b90 | ||
|
|
08f9312fb3 | ||
|
|
15d688797f | ||
|
|
d282abfd49 | ||
|
|
a0cea560d6 | ||
|
|
9eac844757 | ||
|
|
5b748d6774 | ||
|
|
773b129bde | ||
|
|
c26fde5644 | ||
|
|
10dcf831e8 | ||
|
|
91c370433c | ||
|
|
a9f3f563e1 | ||
|
|
e3a67f309d | ||
|
|
be25f42e47 | ||
|
|
90c6a7d93a | ||
|
|
47f7ac1995 | ||
|
|
63a936afee | ||
|
|
7035bca982 | ||
|
|
f19a16e1d3 | ||
|
|
e62a76d238 | ||
|
|
c4df2324b5 | ||
|
|
a9f5541145 | ||
|
|
f8ec331a65 | ||
|
|
18efc69d0d | ||
|
|
fdd270068d | ||
|
|
38e541137e | ||
|
|
7bfe4ab87a | ||
|
|
ba4ec6f7f6 | ||
|
|
55ed41f878 | ||
|
|
971151eaa1 | ||
|
|
ea40534851 | ||
|
|
56959d356f | ||
|
|
16f4f5c311 | ||
|
|
12efb98edc | ||
|
|
b9707c43af | ||
|
|
eb1a06f4b6 | ||
|
|
89beeeccef | ||
|
|
49b78aafe2 | ||
|
|
dbf489fd04 | ||
|
|
81ac69bde0 | ||
|
|
51116d16d0 | ||
|
|
55bf112d80 | ||
|
|
05247ea5a9 | ||
|
|
fb0cccbf5f | ||
|
|
b55805965d | ||
|
|
461e446c35 | ||
|
|
75835566d9 | ||
|
|
6f657aa1fe | ||
|
|
1e57bfcf18 | ||
|
|
522749385a | ||
|
|
e659fec281 | ||
|
|
08a5729ac6 | ||
|
|
840ba00cdf | ||
|
|
5a62083bd4 | ||
|
|
c32aae6cca | ||
|
|
cca3b36398 | ||
|
|
26947144be | ||
|
|
b43a2b7554 | ||
|
|
be2918ef56 | ||
|
|
00dc48d847 | ||
|
|
3e114d8d60 | ||
|
|
7cef698679 | ||
|
|
300656761d | ||
|
|
67aa0f68c6 | ||
|
|
71eb73c449 | ||
|
|
15fcb7d36c | ||
|
|
e39b34b4af | ||
|
|
86d2db17bf | ||
|
|
c05cd93d42 | ||
|
|
cb0bd2310a | ||
|
|
ee12703d1a | ||
|
|
880d68823b | ||
|
|
58b095663a | ||
|
|
d14de170f2 | ||
|
|
16a5d2d815 | ||
|
|
6b7ee1a545 | ||
|
|
9a6f8c1dc7 | ||
|
|
bc346d1680 | ||
|
|
227f429c0b | ||
|
|
fe0ded705f | ||
|
|
48616b0683 | ||
|
|
ddbc6a9339 | ||
|
|
583546ed2e | ||
|
|
19ea22a651 | ||
|
|
2cd8ff60a1 | ||
|
|
0b9e4ad14e | ||
|
|
4e479496f8 | ||
|
|
9527fb2363 | ||
|
|
9a8c37e513 | ||
|
|
d9f6a01fab | ||
|
|
3b43a7318f | ||
|
|
11c09d3d49 | ||
|
|
3b4c36fc8e | ||
|
|
62a25711e7 | ||
|
|
d308ea70ef | ||
|
|
438fa70d2c | ||
|
|
6afbf06977 | ||
|
|
f1bf269107 | ||
|
|
e00f43b7f3 | ||
|
|
d249eab914 | ||
|
|
627d48145d | ||
|
|
a58e93976c | ||
|
|
53564c3951 | ||
|
|
06ac010962 | ||
|
|
b04a4f9427 | ||
|
|
192d4624d0 | ||
|
|
e90100e6f0 | ||
|
|
c038563c4d | ||
|
|
4d6d337631 | ||
|
|
6d05fd2270 | ||
|
|
34761ef23e | ||
|
|
22663c6383 | ||
|
|
81ab66acfa | ||
|
|
7ab80da472 | ||
|
|
91939cfbea | ||
|
|
910b005461 | ||
|
|
38a5ddc842 | ||
|
|
f5dc391d84 | ||
|
|
e6d1867b26 | ||
|
|
4cd5ab25c5 | ||
|
|
150328a8e6 | ||
|
|
4547c5cd74 | ||
|
|
00adec5709 | ||
|
|
87bbe32592 | ||
|
|
f5e22d20cb | ||
|
|
2bf9eb9495 | ||
|
|
92061261e2 | ||
|
|
8dcf563b31 | ||
|
|
a10cdc32d0 | ||
|
|
5381be1658 | ||
|
|
3100862c04 | ||
|
|
716ceb2b77 | ||
|
|
92c6556316 | ||
|
|
0bbc868039 | ||
|
|
a178996dca | ||
|
|
138663a378 | ||
|
|
b71aa8c266 | ||
|
|
973ff178cb | ||
|
|
24d1bab2d4 | ||
|
|
e60ff723f2 | ||
|
|
4c5cdb0ccf | ||
|
|
8a7440dbbe | ||
|
|
0aef3ec39a | ||
|
|
17790317d9 | ||
|
|
a3492aaabe |
No files matched your search
@@ -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,74 @@
|
||||
name: Bug report / 错误报告
|
||||
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
|
||||
title: "[bug] "
|
||||
labels:
|
||||
- BUG
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提交确认 / Checklist
|
||||
description: Checklist before submitting
|
||||
options:
|
||||
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate
|
||||
required: true
|
||||
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
|
||||
required: true
|
||||
- label: 我愿意为了解决这个问题尽自己所能 / I am willing to do my part to help resolve this issue
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: 系统环境
|
||||
description: System environment,例如操作系统版本、运行时版本、显卡驱动版本
|
||||
placeholder: Windows 11 24H2 (26100.3775) / .NET Desktop Runtime 8.0.15 / NVIDIA 572.83
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: BetterGI 版本号
|
||||
description: BetterGI Version
|
||||
placeholder: e.g. 0.58.0
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: Describe the actual behavior and impact
|
||||
placeholder: 请描述实际出现的问题,以及这个问题对使用造成了什么影响 / Describe the actual behavior and impact
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期望结果
|
||||
description: Expected behavior
|
||||
placeholder: 请描述你期望出现的正确行为或结果 / Describe the expected behavior or result
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
description: Reproduction steps
|
||||
placeholder: |-
|
||||
1. 打开…… / Open ...
|
||||
2. 点击…… / Click ...
|
||||
3. 出现…… / Observe ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 日志与附件
|
||||
description: Logs and attachments,可直接拖拽上传日志文件、压缩包、截图或视频
|
||||
placeholder: |-
|
||||
可在这里补充日志和附件说明 / Add logs and attachment notes here:
|
||||
- 可直接粘贴关键日志片段 / Paste key log snippets directly
|
||||
- 可拖拽上传日志文件或压缩包 / Drag and drop log files or archives
|
||||
- 可拖拽上传截图、录屏或演示视频 / Drag and drop screenshots or videos
|
||||
- 若附件较多,请说明对应的时间点、任务名称或异常现象 / If there are many files, explain the relevant timestamps or symptoms
|
||||
- 提交前请注意移除账号、路径等隐私信息 / Remove private information before submitting
|
||||
validations:
|
||||
required: false
|
||||
@@ -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,52 @@
|
||||
name: I have feature requesting / 我有功能需求
|
||||
description: 提出新的功能想法 / Share a feature request
|
||||
title: "[feature] "
|
||||
labels:
|
||||
- 功能建议
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提交确认 / Checklist
|
||||
description: Please confirm the following before submitting
|
||||
options:
|
||||
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate request
|
||||
required: true
|
||||
- label: 我已确认当前版本中尚未提供该功能,或至少没有等价实现 / I have confirmed this feature, or an equivalent one, is not already available in the current version
|
||||
required: true
|
||||
- label: 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好 / I believe this request provides clear value to a broader group of users, not just my personal preference
|
||||
required: true
|
||||
- label: 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳 / I understand this request may not be accepted due to implementation cost, maintenance cost, or project direction
|
||||
required: true
|
||||
- type: textarea
|
||||
id: request
|
||||
attributes:
|
||||
label: 功能请求
|
||||
description: Feature Request
|
||||
placeholder: 请简要说明你希望新增什么能力 / Briefly describe the capability you want to add
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scenario
|
||||
attributes:
|
||||
label: 使用场景
|
||||
description: Use Case
|
||||
placeholder: 这个功能要解决什么问题?在哪些场景下使用? / What problem does this feature solve, and when would it be used?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: impact
|
||||
attributes:
|
||||
label: 潜在影响
|
||||
description: Potential Impact
|
||||
placeholder: 请说明这个功能是否可能带来新的问题、维护成本、使用门槛或兼容性影响;如果没有,请填写“无” / Describe any potential downsides such as new issues, maintenance cost, usability barriers, or compatibility impact. Write "None" if there are no obvious downsides.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: 补充信息
|
||||
description: Optional
|
||||
placeholder: "可选,补充示意图、交互草图、参考链接或相关背景信息 / Optional: add mockups, interaction sketches, reference links, or other background information"
|
||||
validations:
|
||||
required: false
|
||||
@@ -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,32 @@
|
||||
name: I have a question / 我有疑问
|
||||
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
|
||||
title: "[question] "
|
||||
labels:
|
||||
- 问题咨询
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提交确认 / Checklist
|
||||
description: Please confirm the following before submitting
|
||||
options:
|
||||
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate question
|
||||
required: true
|
||||
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
|
||||
required: true
|
||||
- type: textarea
|
||||
id: question
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: Problem Description
|
||||
placeholder: 请清楚描述你的问题 / Clearly describe your question
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: tried
|
||||
attributes:
|
||||
label: 已尝试内容
|
||||
description: Screenshots / logs / what you already tried
|
||||
placeholder: 可附上截图、日志,以及你已经尝试过的排查过程 / Add screenshots, logs, and what you have already tried
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: I have suggestions / 我有建议
|
||||
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
|
||||
title: "[suggestion] "
|
||||
labels: suggestion
|
||||
---
|
||||
|
||||
- Your suggestions / 你的建议
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
name: I have suggestions / 我有建议
|
||||
description: 分享对项目的改进建议 / Share an improvement suggestion
|
||||
title: "[suggestion] "
|
||||
labels:
|
||||
- 功能建议
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提交确认 / Checklist
|
||||
description: Please confirm the following before submitting
|
||||
options:
|
||||
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate suggestion
|
||||
required: true
|
||||
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的建议 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my suggestion"
|
||||
required: true
|
||||
- type: textarea
|
||||
id: suggestion
|
||||
attributes:
|
||||
label: 建议内容
|
||||
description: Suggestion
|
||||
placeholder: 请描述你的建议内容 / Describe your suggestion
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: benefit
|
||||
attributes:
|
||||
label: 预期收益
|
||||
description: Expected Benefit
|
||||
placeholder: 这个建议会给用户或项目带来什么帮助? / What benefits would this suggestion bring to users or the project?
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,229 @@
|
||||
runtime:
|
||||
languageMode: auto
|
||||
dryRun: false
|
||||
|
||||
providers:
|
||||
openAiCompatible:
|
||||
enabled: true
|
||||
baseUrl: https://api.openai.com/v1
|
||||
model: gpt-5.4
|
||||
apiStyle: responses
|
||||
timeoutMs: 30000
|
||||
|
||||
issues:
|
||||
autoProcessing:
|
||||
skipCreatedBefore: auto
|
||||
validation:
|
||||
enabled: true
|
||||
fallbackTemplateKey: normal
|
||||
commentAnchor: issue-bot:validation
|
||||
templates:
|
||||
- key: bug
|
||||
detect:
|
||||
markers:
|
||||
- bug
|
||||
titlePrefixes:
|
||||
- "[bug]"
|
||||
requiredSections:
|
||||
- id: environment
|
||||
aliases:
|
||||
- 系统环境
|
||||
- System Environment
|
||||
- id: version
|
||||
aliases:
|
||||
- BetterGI 版本号
|
||||
- BetterGI Version
|
||||
- id: description
|
||||
aliases:
|
||||
- 问题描述
|
||||
- Description of the issue
|
||||
- id: steps
|
||||
aliases:
|
||||
- 复现步骤
|
||||
- Reproduction steps
|
||||
labels:
|
||||
whenValid:
|
||||
- BUG
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: feature
|
||||
detect:
|
||||
markers:
|
||||
- feature
|
||||
titlePrefixes:
|
||||
- "[feature]"
|
||||
requiredSections:
|
||||
- id: request
|
||||
aliases:
|
||||
- 功能请求
|
||||
- Feature Request
|
||||
- id: scenario
|
||||
aliases:
|
||||
- 使用场景
|
||||
- Use Case
|
||||
labels:
|
||||
whenValid:
|
||||
- 功能建议
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: suggestion
|
||||
detect:
|
||||
markers:
|
||||
- suggestion
|
||||
titlePrefixes:
|
||||
- "[suggestion]"
|
||||
requiredSections:
|
||||
- id: suggestion
|
||||
aliases:
|
||||
- 建议内容
|
||||
- Suggestion
|
||||
- id: benefit
|
||||
aliases:
|
||||
- 预期收益
|
||||
- Expected Benefit
|
||||
labels:
|
||||
whenValid:
|
||||
- 功能建议
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: question
|
||||
detect:
|
||||
markers:
|
||||
- question
|
||||
titlePrefixes:
|
||||
- "[question]"
|
||||
requiredSections:
|
||||
- id: question
|
||||
aliases:
|
||||
- 问题描述
|
||||
- Problem Description
|
||||
- id: tried
|
||||
aliases:
|
||||
- 已尝试内容
|
||||
- What I Tried
|
||||
labels:
|
||||
whenValid:
|
||||
- 问题咨询
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: normal
|
||||
detect:
|
||||
markers:
|
||||
- normal
|
||||
titlePrefixes:
|
||||
- "[feedback]"
|
||||
- "[normal]"
|
||||
requiredSections:
|
||||
- id: description
|
||||
aliases:
|
||||
- 描述
|
||||
- Description
|
||||
labels:
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
duplicateDetection:
|
||||
enabled: true
|
||||
bypassLabels:
|
||||
- 跳过重复检测
|
||||
duplicateLabel: 重复
|
||||
searchResultLimit: 50
|
||||
candidateLimit: 20
|
||||
aiReviewMaxCandidates: 3
|
||||
thresholds:
|
||||
exact: 0.995
|
||||
highConfidence: 0.93
|
||||
reviewMin: 0.82
|
||||
similarityComment:
|
||||
enabled: true
|
||||
commentAnchor: issue-bot:similar-issues
|
||||
minScore: 0.3
|
||||
maxCandidates: 3
|
||||
labeling:
|
||||
enabled: true
|
||||
autoCreateMissing: true
|
||||
managed:
|
||||
- BUG
|
||||
- 功能建议
|
||||
- 问题咨询
|
||||
- 需要更多信息
|
||||
- 重复
|
||||
definitions:
|
||||
BUG:
|
||||
color: d73a4a
|
||||
description: 程序存在缺陷或异常行为。
|
||||
功能建议:
|
||||
color: a2eeef
|
||||
description: 新功能建议或现有功能改进。
|
||||
问题咨询:
|
||||
color: d876e3
|
||||
description: 使用问题、求助或咨询。
|
||||
# 需要更多信息:
|
||||
# color: fbca04
|
||||
# description: 当前 Issue 缺少必要信息。
|
||||
重复:
|
||||
color: cfd3d7
|
||||
description: 已存在相同或高度相似的问题。
|
||||
keywordRules: []
|
||||
aiClassification:
|
||||
enabled: false
|
||||
maxLabels: 3
|
||||
minConfidence: 0.65
|
||||
include: []
|
||||
exclude:
|
||||
- BUG
|
||||
- 功能请求
|
||||
- 重复
|
||||
- 不会修复
|
||||
- 使用问题
|
||||
- 需要帮助
|
||||
- 已完成
|
||||
- 未解决
|
||||
- 待确认
|
||||
- P0
|
||||
- P1
|
||||
- 需要文档
|
||||
- 优化点
|
||||
- 急急急
|
||||
prompt: 优先给 BetterGI Issue 选择能反映具体功能模块、子系统或使用场景的标签,例如一条龙、调度器、脚本、设置项、地图追踪;避免只选择宽泛的流程或状态标签。
|
||||
sourceRepository:
|
||||
owner: babalae
|
||||
repo: better-genshin-impact
|
||||
aiHelp:
|
||||
enabled: true
|
||||
triggerLabels: []
|
||||
commentAnchor: issue-bot:ai
|
||||
projectContext:
|
||||
enabled: true
|
||||
includeRepositoryMetadata: true
|
||||
includeReadme: true
|
||||
readmeMaxChars: 3000
|
||||
profile:
|
||||
name: BetterGI
|
||||
aliases:
|
||||
- BGI
|
||||
- Better Genshin Impact
|
||||
summary: BetterGI is a desktop automation assistant for Genshin Impact.
|
||||
techStack:
|
||||
- C#
|
||||
- WPF
|
||||
- .NET
|
||||
commands:
|
||||
enabled: true
|
||||
mentions:
|
||||
- "@bot"
|
||||
- "@bettergi-repo-bot"
|
||||
access: collaborators
|
||||
fix:
|
||||
enabled: true
|
||||
commentAnchor: issue-bot:fix
|
||||
refresh:
|
||||
enabled: true
|
||||
|
||||
pullRequests:
|
||||
review:
|
||||
enabled: false
|
||||
labeling:
|
||||
enabled: false
|
||||
summary:
|
||||
enabled: false
|
||||
@@ -7,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
|
||||
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: huiyadanli/bettergi-scripts-web
|
||||
repository: zaodonganqi/bettergi-script-web
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
name: Repo Bot
|
||||
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- reopened
|
||||
- labeled
|
||||
issue_comment:
|
||||
types:
|
||||
- created
|
||||
- edited
|
||||
|
||||
jobs:
|
||||
repo-bot:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
contents: read
|
||||
steps:
|
||||
- name: Detect GitHub App configuration
|
||||
id: auth-mode
|
||||
shell: bash
|
||||
env:
|
||||
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
|
||||
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
|
||||
echo "use_app=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "use_app=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Create GitHub App token
|
||||
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
|
||||
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Run Repo Bot
|
||||
uses: ddaodan/bettergi-github-bot@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
|
||||
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
|
||||
with:
|
||||
config-path: .github/repo-bot.yml
|
||||
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
|
||||
@@ -33,5 +33,6 @@ github_actions_cache/
|
||||
.trae
|
||||
.claude
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
|
||||
__pycache__/
|
||||
@@ -1,7 +1,10 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=chyan/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=enkanomiya/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Kongying/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=mirrorchan/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=onslaugh/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=retcode/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=serenitea/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=steambird/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=steambird/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Teyvat/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
|
||||
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
|
||||
<bgivc:DomainNameToCascadingItemConverter x:Key="DomainNameConverter" />
|
||||
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
|
||||
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
|
||||
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
|
||||
@@ -24,6 +25,9 @@
|
||||
<bgivc:NotNullConverter x:Key="NotNullConverter" />
|
||||
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
|
||||
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
|
||||
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
|
||||
<bgivc:TrConverter x:Key="TrConverter" />
|
||||
<bgivc:AdaptiveUniformGridColumnsConverter x:Key="AdaptiveUniformGridColumnsConverter" />
|
||||
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
|
||||
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
|
||||
</Style>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
@@ -20,6 +21,8 @@ using BetterGenshinImpact.View.Pages;
|
||||
using BetterGenshinImpact.ViewModel;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using BetterGenshinImpact.ViewModel.Pages.View;
|
||||
using LazyCache;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -28,8 +31,13 @@ using Serilog.Events;
|
||||
using Serilog.Sinks.RichTextBox.Abstraction;
|
||||
using Wpf.Ui;
|
||||
using Wpf.Ui.DependencyInjection;
|
||||
using Wpf.Ui.Violeta.Appearance;
|
||||
using Wpf.Ui.Violeta.Controls;
|
||||
|
||||
// Wine 平台适配
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
using BetterGenshinImpact.Service.Tavern;
|
||||
|
||||
namespace BetterGenshinImpact;
|
||||
|
||||
public partial class App : Application
|
||||
@@ -44,8 +52,7 @@ public partial class App : Application
|
||||
.UseElevated()
|
||||
.UseSingleInstance("BetterGI")
|
||||
.ConfigureLogging(builder => { builder.ClearProviders(); })
|
||||
.ConfigureServices(
|
||||
(context, services) =>
|
||||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
// 提前初始化配置
|
||||
var configService = new ConfigService();
|
||||
@@ -66,7 +73,7 @@ public partial class App : Application
|
||||
rollingInterval: RollingInterval.Day,
|
||||
retainedFileCountLimit: 31,
|
||||
retainedFileTimeLimit: TimeSpan.FromDays(21))
|
||||
.WriteTo.Console(outputTemplate:
|
||||
.WriteTo.Console(outputTemplate:
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.MinimumLevel.Debug()
|
||||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||||
@@ -78,16 +85,31 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
Log.Logger = loggerConfiguration.CreateLogger();
|
||||
services.AddSingleton<IMissingTranslationReporter, SupabaseMissingTranslationReporter>();
|
||||
services.AddSingleton<ITranslationService, JsonTranslationService>();
|
||||
|
||||
services.AddLogging(c => c.AddSerilog());
|
||||
// if ("zh-Hans".Equals(all.OtherConfig.UiCultureInfoName, StringComparison.OrdinalIgnoreCase))
|
||||
// {
|
||||
// services.AddLogging(c => c.AddSerilog());
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// services.AddLogging(logging =>
|
||||
// {
|
||||
// logging.ClearProviders();
|
||||
// logging.SetMinimumLevel(LogLevel.Debug);
|
||||
// logging.AddFilter("Microsoft", LogLevel.Warning);
|
||||
// logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);
|
||||
// logging.Services.AddSingleton<ILoggerProvider, TranslatingSerilogLoggerProvider>();
|
||||
// });
|
||||
// }
|
||||
|
||||
services.AddLocalization();
|
||||
|
||||
services.AddNavigationViewPageProvider();
|
||||
// App Host
|
||||
services.AddHostedService<ApplicationHostService>();
|
||||
// HTTP Server Service
|
||||
services.AddHostedService<HttpServerService>();
|
||||
|
||||
// Page resolver service
|
||||
services.AddSingleton<INavigationService, NavigationService>();
|
||||
services.AddSingleton<IUpdateService, UpdateService>();
|
||||
@@ -137,12 +159,21 @@ public partial class App : Application
|
||||
services.AddSingleton<HutaoNamedPipe>();
|
||||
services.AddSingleton<BgiOnnxFactory>();
|
||||
services.AddSingleton<OcrFactory>();
|
||||
|
||||
services.AddMemoryCache();
|
||||
services.AddSingleton<IAppCache, CachingService>();
|
||||
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
|
||||
}
|
||||
)
|
||||
.Build();
|
||||
@@ -179,6 +210,8 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
protected override async void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// Wine 平台适配
|
||||
WinePlatformAddon.ApplyApplicationConfig();
|
||||
base.OnStartup(e);
|
||||
|
||||
try
|
||||
@@ -192,10 +225,19 @@ public partial class App : Application
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// DEBUG only, no overhead
|
||||
Debug.WriteLine(ex);
|
||||
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
|
||||
|
||||
try
|
||||
{
|
||||
HandleException(ex);
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
Debug.WriteLine(ex2);
|
||||
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
|
||||
}
|
||||
|
||||
if (Debugger.IsAttached)
|
||||
{
|
||||
Debugger.Break();
|
||||
@@ -211,12 +253,12 @@ public partial class App : Application
|
||||
base.OnExit(e);
|
||||
|
||||
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
|
||||
|
||||
|
||||
TempManager.CleanUp();
|
||||
|
||||
await _host.StopAsync();
|
||||
_host.Dispose();
|
||||
|
||||
|
||||
// 释放控制台窗口
|
||||
ConsoleHelper.FreeConsoleWindow();
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.51.1-alpha.1</Version>
|
||||
<Version>0.60.2-alpha.1</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
@@ -40,11 +40,12 @@
|
||||
<ItemGroup>
|
||||
<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.11" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.12" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.9" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.18" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.20" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.15" />
|
||||
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="DeviceId" Version="6.9.0" />
|
||||
@@ -52,10 +53,11 @@
|
||||
<PackageReference Include="DeviceId.Windows.Wmi" Version="6.9.0" />
|
||||
<PackageReference Include="Emoji.Wpf" Version="0.3.4" />
|
||||
<PackageReference Include="LibGit2Sharp" Version="0.31.0" />
|
||||
<PackageReference Include="LazyCache" Version="2.4.0" />
|
||||
<PackageReference Include="MailKit" Version="4.14.0" />
|
||||
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.App" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.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" />
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
|
||||
@@ -65,6 +67,7 @@
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.21.0" />
|
||||
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
|
||||
<PackageReference Include="MimeKit" Version="4.15.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
|
||||
@@ -81,16 +84,18 @@
|
||||
<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="System.Drawing.Common" Version="9.0.5" />
|
||||
<!-- <PackageReference Include="supabase-csharp" Version="0.16.2" />-->
|
||||
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
|
||||
<PackageReference Include="TorchSharp" Version="0.105.0" />
|
||||
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
|
||||
<PackageReference Include="WPF-UI" Version="4.0.2" />
|
||||
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.0.2" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="4.0.2" />
|
||||
<PackageReference Include="WPF-UI.Violeta" Version="4.0.2.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.10" />
|
||||
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
@@ -124,6 +129,9 @@
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\LogParse\Assets\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -190,6 +198,12 @@
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\I18n\en.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
@@ -22,6 +21,10 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
|
||||
using BetterGenshinImpact.GameTask.GetGridIcons;
|
||||
using BetterGenshinImpact.GameTask.AutoEat;
|
||||
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask.MapMask;
|
||||
using BetterGenshinImpact.GameTask.SkillCd;
|
||||
using BetterGenshinImpact.GameTask.UseRedeemCode;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -126,11 +129,6 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动烹饪配置
|
||||
/// </summary>
|
||||
public AutoCookConfig AutoCookConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动打牌配置
|
||||
/// </summary>
|
||||
@@ -171,7 +169,24 @@ public partial class AllConfig : ObservableObject
|
||||
/// 自动吃药配置
|
||||
/// </summary>
|
||||
public AutoEatConfig AutoEatConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动地脉花配置
|
||||
/// </summary>
|
||||
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
|
||||
|
||||
public AutoCookConfig AutoCookConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 地图遮罩
|
||||
/// </summary>
|
||||
public MapMaskConfig MapMaskConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 技能 CD 提示
|
||||
/// </summary>
|
||||
public SkillCdConfig SkillCdConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动使用
|
||||
/// </summary>
|
||||
@@ -235,11 +250,6 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public HardwareAccelerationConfig HardwareAccelerationConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 服务器配置
|
||||
/// </summary>
|
||||
public HttpServerConfig HttpServerConfig { get; set; } = new();
|
||||
|
||||
[JsonIgnore]
|
||||
public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
@@ -256,7 +266,6 @@ public partial class AllConfig : ObservableObject
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
@@ -266,13 +275,16 @@ public partial class AllConfig : ObservableObject
|
||||
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
TpConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
DevConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HttpServerConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
@@ -285,4 +297,4 @@ public partial class AllConfig : ObservableObject
|
||||
{
|
||||
NotificationService.Instance().RefreshNotifiers();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -36,7 +36,7 @@ public partial class CommonConfig : ObservableObject
|
||||
/// UID遮盖是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _screenshotUidCoverEnabled;
|
||||
private bool _screenshotUidCoverEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 退出时最小化至托盘
|
||||
@@ -48,7 +48,7 @@ public partial class CommonConfig : ObservableObject
|
||||
/// 当前主题类型(新版主题)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private ThemeType _currentThemeType = OsVersionHelper.IsWindows11_22523_OrGreater? ThemeType.DarkMica : ThemeType.DarkNone;
|
||||
private ThemeType _currentThemeType = OsVersionHelper.IsWindows11_22523_OrGreater ? ThemeType.DarkMica : ThemeType.DarkNone;
|
||||
|
||||
/// <summary>
|
||||
/// 主题(旧版主题,兼容性保留)
|
||||
@@ -73,4 +73,11 @@ public partial class CommonConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private List<string> _onceHadRunDeviceIdList = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 当前看过的兑换码推送版本
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _redeemCodeFeedsUpdateVersion = "20251013";
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -44,4 +44,7 @@ public partial class GenshinStartConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _recordGameTimeEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _startGameWithCmd = false;
|
||||
}
|
||||
@@ -14,10 +14,10 @@ public partial class HardwareAccelerationConfig : ObservableObject
|
||||
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
|
||||
|
||||
/// <summary>
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _cpuOcr = false;
|
||||
private bool _cpuOcr = true;
|
||||
|
||||
#region 一般GPU加速设置
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
@@ -100,6 +100,13 @@ public partial class HotKeyConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 技能CD提示开关
|
||||
[ObservableProperty]
|
||||
private string _skillCdEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _skillCdEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 截图
|
||||
[ObservableProperty]
|
||||
@@ -156,6 +163,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 = "";
|
||||
@@ -237,4 +251,11 @@ public partial class HotKeyConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 地图遮罩开关
|
||||
[ObservableProperty]
|
||||
private string _mapMaskEnabledHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _mapMaskEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 服务器配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class HttpServerConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用 HTTP 服务器
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 服务器端口
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _port = 30648;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用 CORS
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableCors = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用 WebSocket 支持
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableWebSocket = true;
|
||||
|
||||
/// <summary>
|
||||
/// API 访问令牌(可选,用于安全验证)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _accessToken = Guid.NewGuid().ToString("N");
|
||||
|
||||
// /// <summary>
|
||||
// /// 是否启用 Swagger 文档
|
||||
// /// </summary>
|
||||
// [ObservableProperty]
|
||||
// private bool _enableSwagger = true;
|
||||
|
||||
/// <summary>
|
||||
/// 监听地址
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _host = "localhost";
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
|
||||
@@ -64,9 +64,35 @@ public partial class MaskWindowConfig : ObservableObject
|
||||
private bool _showFps = false;
|
||||
|
||||
/// <summary>
|
||||
/// 作为原神子窗体
|
||||
/// 有些bug没解决
|
||||
/// 遮罩文本透明度 (0.0-1.0)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _useSubform = false;
|
||||
private double _textOpacity = 1.0;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _overlayLayoutEditEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxTopRatio = 822.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxWidthRatio = 480.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxHeightRatio = 188.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListTopRatio = 790.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListWidthRatio = 480.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListHeightRatio = 24.0 / 1080;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
@@ -61,6 +62,87 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private List<string> _secretTreasureObjects = new();
|
||||
|
||||
// 地脉花一条龙模式(跳过部分准备流程)
|
||||
[ObservableProperty]
|
||||
private bool _leyLineOneDragonMode = false;
|
||||
|
||||
// 地脉花运行日期设置
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunMonday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunTuesday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunWednesday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunThursday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunFriday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunSaturday = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _leyLineRunSunday = true;
|
||||
|
||||
// 地脉花每日类型与国家配置(为空则使用独立任务配置)
|
||||
[ObservableProperty]
|
||||
private string _leyLineMondayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineMondayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineTuesdayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineTuesdayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineWednesdayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineWednesdayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineThursdayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineThursdayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineFridayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineFridayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineSaturdayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineSaturdayCountry = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineSundayType = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _leyLineSundayCountry = string.Empty;
|
||||
|
||||
// 地脉花刷取次数(0 表示使用独立任务配置)
|
||||
[ObservableProperty]
|
||||
private int _leyLineRunCount = 0;
|
||||
|
||||
// 地脉花树脂耗尽模式
|
||||
[ObservableProperty]
|
||||
private bool _leyLineResinExhaustionMode = false;
|
||||
|
||||
// 地脉花刷取次数取小值(仅耗尽模式生效)
|
||||
[ObservableProperty]
|
||||
private bool _leyLineOpenModeCountMin = false;
|
||||
|
||||
#region 每周秘境配置
|
||||
|
||||
//周一
|
||||
@@ -142,5 +224,62 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
public bool ShouldRunLeyLineToday()
|
||||
{
|
||||
if (!LeyLineRunMonday
|
||||
&& !LeyLineRunTuesday
|
||||
&& !LeyLineRunWednesday
|
||||
&& !LeyLineRunThursday
|
||||
&& !LeyLineRunFriday
|
||||
&& !LeyLineRunSaturday
|
||||
&& !LeyLineRunSunday)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var serverTime = ServerTimeHelper.GetServerTimeNow();
|
||||
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
|
||||
return dayOfWeek switch
|
||||
{
|
||||
DayOfWeek.Monday => LeyLineRunMonday,
|
||||
DayOfWeek.Tuesday => LeyLineRunTuesday,
|
||||
DayOfWeek.Wednesday => LeyLineRunWednesday,
|
||||
DayOfWeek.Thursday => LeyLineRunThursday,
|
||||
DayOfWeek.Friday => LeyLineRunFriday,
|
||||
DayOfWeek.Saturday => LeyLineRunSaturday,
|
||||
DayOfWeek.Sunday => LeyLineRunSunday,
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
public (string type, string country) GetLeyLineConfigForToday(AutoLeyLineOutcropConfig fallback)
|
||||
{
|
||||
var serverTime = ServerTimeHelper.GetServerTimeNow();
|
||||
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
|
||||
var (type, country) = dayOfWeek switch
|
||||
{
|
||||
DayOfWeek.Monday => (LeyLineMondayType, LeyLineMondayCountry),
|
||||
DayOfWeek.Tuesday => (LeyLineTuesdayType, LeyLineTuesdayCountry),
|
||||
DayOfWeek.Wednesday => (LeyLineWednesdayType, LeyLineWednesdayCountry),
|
||||
DayOfWeek.Thursday => (LeyLineThursdayType, LeyLineThursdayCountry),
|
||||
DayOfWeek.Friday => (LeyLineFridayType, LeyLineFridayCountry),
|
||||
DayOfWeek.Saturday => (LeyLineSaturdayType, LeyLineSaturdayCountry),
|
||||
DayOfWeek.Sunday => (LeyLineSundayType, LeyLineSundayCountry),
|
||||
_ => (string.Empty, string.Empty)
|
||||
};
|
||||
|
||||
if (string.IsNullOrWhiteSpace(type))
|
||||
{
|
||||
type = fallback.LeyLineOutcropType;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(country))
|
||||
{
|
||||
country = fallback.Country;
|
||||
}
|
||||
|
||||
return (type, country);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
@@ -121,4 +121,4 @@ public partial class OtherConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _uiCultureInfoName = "zh-Hans";
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ public partial class PathingPartyConfig : ObservableObject
|
||||
// 切换到队伍的名称
|
||||
[ObservableProperty]
|
||||
private string _partyName = string.Empty;
|
||||
|
||||
[JsonIgnore]
|
||||
public bool SkipPartySwitch { get; set; }
|
||||
|
||||
// 切换队伍前是否前往须弥七天神像
|
||||
[ObservableProperty]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
@@ -25,7 +26,34 @@ public partial class ScriptConfig : ObservableObject
|
||||
// 已订阅的脚本路径列表
|
||||
[ObservableProperty]
|
||||
private List<string> _subscribedScriptPaths = [];
|
||||
|
||||
// 选择的更新渠道名称
|
||||
[ObservableProperty] private string _selectedChannelName = "";
|
||||
|
||||
// 自定义渠道的URL
|
||||
[ObservableProperty] private string _customRepoUrl = "";
|
||||
|
||||
// 选择的更新渠道URL
|
||||
[ObservableProperty] private string _selectedRepoUrl = "";
|
||||
// 仓库页面宽度
|
||||
[ObservableProperty] private double _webviewWidth = 0;
|
||||
|
||||
// 仓库页面高度
|
||||
[ObservableProperty] private double _webviewHeight = 0;
|
||||
|
||||
// 仓库页面横向位置
|
||||
[ObservableProperty] private double _webviewLeft = 0;
|
||||
|
||||
// 仓库页面纵向位置
|
||||
[ObservableProperty] private double _webviewTop = 0;
|
||||
|
||||
// 仓库页面是否最大化
|
||||
[ObservableProperty] private WindowState _webviewState = WindowState.Normal;
|
||||
|
||||
// 仓库新手教程是否已阅读
|
||||
[ObservableProperty] private bool _guideStatus = false;
|
||||
|
||||
// 是否在启动时自动更新已订阅的脚本
|
||||
[ObservableProperty] private bool _autoUpdateSubscribedScripts = false;
|
||||
|
||||
// 命令行启动时是否先自动更新已订阅脚本再执行命令
|
||||
[ObservableProperty] private bool _autoUpdateBeforeCommandLineRun = false;
|
||||
}
|
||||
@@ -6,14 +6,18 @@ using BetterGenshinImpact.Model;
|
||||
using Gma.System.MouseKeyHook;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
using Vanara.PInvoke;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
// Wine 平台适配
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
namespace BetterGenshinImpact.Core.Monitor;
|
||||
|
||||
public class MouseKeyMonitor
|
||||
public partial class MouseKeyMonitor
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
@@ -41,21 +45,41 @@ public class MouseKeyMonitor
|
||||
/// </summary>
|
||||
private DateTime _firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
private IKeyboardMouseEvents? _globalHook;
|
||||
private static IKeyboardMouseEvents? _globalHook;
|
||||
private static readonly object GlobalHookLock = new object();
|
||||
public static IKeyboardMouseEvents GlobalHook
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_globalHook == null)
|
||||
{
|
||||
lock (GlobalHookLock)
|
||||
{
|
||||
if (_globalHook == null)
|
||||
{
|
||||
_globalHook = Hook.GlobalEvents();
|
||||
}
|
||||
}
|
||||
}
|
||||
return _globalHook;
|
||||
}
|
||||
}
|
||||
private nint _hWnd;
|
||||
|
||||
public void Subscribe(nint gameHandle)
|
||||
{
|
||||
_hWnd = gameHandle;
|
||||
// Note: for the application hook, use the Hook.AppEvents() instead
|
||||
_globalHook = Hook.GlobalEvents();
|
||||
|
||||
_globalHook.KeyDown += GlobalHookKeyDown;
|
||||
_globalHook.KeyUp += GlobalHookKeyUp;
|
||||
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
_globalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
_globalHook.MouseMoveExt += GlobalHookMouseMoveExt;
|
||||
_globalHook.MouseWheelExt += GlobalHookMouseWheelExt;
|
||||
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;
|
||||
|
||||
_pickUpKey = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToWinFormKeys();
|
||||
@@ -78,6 +102,11 @@ public class MouseKeyMonitor
|
||||
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
|
||||
|
||||
if (SystemControl.IsGenshinImpactActive())
|
||||
{
|
||||
ChatUiHotkeyGuard.PrimeFromChatKey(e.KeyCode);
|
||||
}
|
||||
|
||||
// 热键按下事件
|
||||
HotKeyDown(sender, e);
|
||||
|
||||
@@ -190,7 +219,7 @@ public class MouseKeyMonitor
|
||||
|
||||
public void Unsubscribe()
|
||||
{
|
||||
if (_globalHook != null)
|
||||
if (_globalHook != null && !WinePlatformAddon.IsRunningOnWine)
|
||||
{
|
||||
_globalHook.KeyDown -= GlobalHookKeyDown;
|
||||
_globalHook.KeyUp -= GlobalHookKeyUp;
|
||||
@@ -200,6 +229,10 @@ public class MouseKeyMonitor
|
||||
_globalHook.MouseWheelExt -= GlobalHookMouseWheelExt;
|
||||
//_globalHook.KeyPress -= GlobalHookKeyPress;
|
||||
_globalHook.Dispose();
|
||||
_globalHook = null;
|
||||
}
|
||||
if (WinePlatformAddon.IsRunningOnWine){
|
||||
DisposeWineAddon();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using System.Linq;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Extensions;
|
||||
using YamlDotNet.Core;
|
||||
@@ -246,7 +247,7 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
_localRecModel = modelsRec;
|
||||
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
|
||||
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
@@ -281,8 +282,10 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
/// </summary>
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 结果: {str}");
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -95,21 +94,33 @@ public class Rec(
|
||||
// .AsParallel()
|
||||
.Select(src =>
|
||||
{
|
||||
using var channel3 = src.Channels() switch
|
||||
Mat? channel3 = default;
|
||||
try
|
||||
{
|
||||
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
|
||||
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
|
||||
3 => src,
|
||||
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
|
||||
};
|
||||
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
|
||||
out var owner);
|
||||
lock (owners)
|
||||
{
|
||||
owners.Add(owner);
|
||||
}
|
||||
channel3 = src.Channels() switch
|
||||
{
|
||||
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
|
||||
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
|
||||
3 => src,
|
||||
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
|
||||
};
|
||||
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
|
||||
out var owner);
|
||||
lock (owners)
|
||||
{
|
||||
owners.Add(owner);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only dispose Mats created in this scope
|
||||
if (channel3 != null && !ReferenceEquals(channel3, src))
|
||||
{
|
||||
channel3.Dispose();
|
||||
}
|
||||
}
|
||||
})
|
||||
.Select(inputTensor =>
|
||||
{
|
||||
@@ -141,46 +152,46 @@ public class Rec(
|
||||
{
|
||||
var resultArray = resultTensor.Item2;
|
||||
var resultShape = resultTensor.Item1;
|
||||
GCHandle dataHandle = default;
|
||||
try
|
||||
{
|
||||
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
|
||||
var dataPtr = dataHandle.AddrOfPinnedObject();
|
||||
var labelCount = resultShape[2];
|
||||
var charCount = resultShape[1];
|
||||
var labelCount = resultShape[2];
|
||||
var charCount = resultShape[1];
|
||||
|
||||
return Enumerable.Range(0, resultShape[0])
|
||||
.Select(i =>
|
||||
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)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
var lastIndex = 0;
|
||||
float score = 0;
|
||||
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++)
|
||||
{
|
||||
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
|
||||
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
|
||||
var maxIdx = new int[2];
|
||||
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
|
||||
|
||||
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
|
||||
var value = resultArray[rowOffset + c];
|
||||
if (value > maxVal)
|
||||
{
|
||||
score += (float)maxVal;
|
||||
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
|
||||
maxVal = value;
|
||||
maxIndex = c;
|
||||
}
|
||||
|
||||
lastIndex = maxIdx[1];
|
||||
}
|
||||
|
||||
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dataHandle.Free();
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -311,6 +311,17 @@ public class BgiOnnxFactory
|
||||
: new BgiYoloPredictor(model, cached, CreateSessionOptions(model, false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据模型创建一个 RedNet 分类预测器
|
||||
/// </summary>
|
||||
/// <param name="model">模型</param>
|
||||
/// <param name="labelRelativePath">标签文件相对路径,可选,支持 .txt/.json</param>
|
||||
/// <returns>BgiRedNetPredictor</returns>
|
||||
public BgiRedNetPredictor CreateRedNetPredictor(BgiOnnxModel model, string? labelRelativePath = null)
|
||||
{
|
||||
return new BgiRedNetPredictor(model, CreateInferenceSession(model), labelRelativePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据模型创建一个onnx运行时的InferenceSession
|
||||
/// </summary>
|
||||
@@ -407,6 +418,11 @@ public class BgiOnnxFactory
|
||||
break;
|
||||
case ProviderType.Cpu:
|
||||
sessionOptions.AppendExecutionProvider_CPU();
|
||||
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
|
||||
// {
|
||||
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
|
||||
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
|
||||
// }
|
||||
break;
|
||||
case ProviderType.Dnnl:
|
||||
sessionOptions.AppendExecutionProvider_Dnnl();
|
||||
@@ -577,4 +593,4 @@ public class BgiOnnxFactory
|
||||
result["enable_opencl_throttling"] = "true";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,12 @@ public class BgiOnnxModel
|
||||
public static readonly BgiOnnxModel BgiAvatarSide =
|
||||
Register("BgiAvatarSide", @"Assets\Model\Common\avatar_side_classify_sim.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 角色识别(RedNet-110)
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiPickRedNet110 =
|
||||
Register("BgiPickRedNet110", @"Assets\Model\Common\resnet_pick.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// paddleOCR V4 检测模型
|
||||
/// </summary>
|
||||
@@ -139,4 +145,4 @@ public class BgiOnnxModel
|
||||
RegisteredModels.Add(model);
|
||||
return model;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public sealed class BgiRedNetPredictor : IDisposable
|
||||
{
|
||||
private const int DefaultInputSize = 224;
|
||||
|
||||
private static readonly float[] ImagenetMean = [0.485f, 0.456f, 0.406f];
|
||||
private static readonly float[] ImagenetStd = [0.229f, 0.224f, 0.225f];
|
||||
|
||||
private readonly InferenceSession _session;
|
||||
private readonly string[]? _labels;
|
||||
private readonly string _inputName;
|
||||
private readonly int _inputWidth;
|
||||
private readonly int _inputHeight;
|
||||
|
||||
/// <summary>
|
||||
/// 使用 BgiOnnxFactory 创建这个类的实例
|
||||
/// </summary>
|
||||
internal BgiRedNetPredictor(BgiOnnxModel model, InferenceSession session, string? labelRelativePath = null)
|
||||
{
|
||||
_session = session;
|
||||
|
||||
var input = _session.InputMetadata.FirstOrDefault();
|
||||
if (input.Key is null || input.Value is null)
|
||||
{
|
||||
throw new InvalidDataException("ONNX 模型输入信息为空");
|
||||
}
|
||||
|
||||
_inputName = input.Key;
|
||||
var dimensions = input.Value.Dimensions;
|
||||
if (dimensions.Length < 4)
|
||||
{
|
||||
throw new InvalidDataException($"ONNX 模型输入维度不正确,预期 >=4,实际 {dimensions.Length}");
|
||||
}
|
||||
|
||||
_inputHeight = dimensions[^2] > 0 ? dimensions[^2] : DefaultInputSize;
|
||||
_inputWidth = dimensions[^1] > 0 ? dimensions[^1] : DefaultInputSize;
|
||||
_labels = LoadLabels(labelRelativePath ?? Path.ChangeExtension(model.ModelRelativePath, ".labels.txt"));
|
||||
}
|
||||
|
||||
public RedNetPrediction Predict(Image<Rgb24> image)
|
||||
{
|
||||
using var resized = image.Clone(ctx => ctx.Resize(_inputWidth, _inputHeight));
|
||||
var tensorInput = BuildInputTensor(resized);
|
||||
using var results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_inputName, tensorInput)
|
||||
]);
|
||||
|
||||
var logits = results.First().AsEnumerable<float>().ToArray();
|
||||
if (logits.Length == 0)
|
||||
{
|
||||
throw new InvalidDataException("ONNX 模型输出为空");
|
||||
}
|
||||
|
||||
var probabilities = Softmax(logits);
|
||||
var maxIndex = 0;
|
||||
var maxValue = probabilities[0];
|
||||
for (var i = 1; i < probabilities.Length; i++)
|
||||
{
|
||||
if (probabilities[i] <= maxValue) continue;
|
||||
maxValue = probabilities[i];
|
||||
maxIndex = i;
|
||||
}
|
||||
|
||||
var label = maxIndex >= 0 && _labels is not null && maxIndex < _labels.Length
|
||||
? _labels[maxIndex]
|
||||
: $"Class_{maxIndex}";
|
||||
return new RedNetPrediction(maxIndex, label, maxValue);
|
||||
}
|
||||
|
||||
private DenseTensor<float> BuildInputTensor(Image<Rgb24> image)
|
||||
{
|
||||
var tensor = new DenseTensor<float>([1, 3, _inputHeight, _inputWidth]);
|
||||
for (var y = 0; y < _inputHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < _inputWidth; x++)
|
||||
{
|
||||
var pixel = image[x, y];
|
||||
var r = pixel.R / 255f;
|
||||
var g = pixel.G / 255f;
|
||||
var b = pixel.B / 255f;
|
||||
|
||||
tensor[0, 0, y, x] = (r - ImagenetMean[0]) / ImagenetStd[0];
|
||||
tensor[0, 1, y, x] = (g - ImagenetMean[1]) / ImagenetStd[1];
|
||||
tensor[0, 2, y, x] = (b - ImagenetMean[2]) / ImagenetStd[2];
|
||||
}
|
||||
}
|
||||
|
||||
return tensor;
|
||||
}
|
||||
|
||||
private static float[] Softmax(float[] logits)
|
||||
{
|
||||
var max = logits.Max();
|
||||
var result = new float[logits.Length];
|
||||
var sum = 0d;
|
||||
|
||||
for (var i = 0; i < logits.Length; i++)
|
||||
{
|
||||
var value = Math.Exp(logits[i] - max);
|
||||
result[i] = (float)value;
|
||||
sum += value;
|
||||
}
|
||||
|
||||
if (sum <= 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
for (var i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = (float)(result[i] / sum);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string[]? LoadLabels(string labelRelativePath)
|
||||
{
|
||||
var labelAbsolutePath = Core.Config.Global.Absolute(labelRelativePath);
|
||||
if (!File.Exists(labelAbsolutePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var ext = Path.GetExtension(labelAbsolutePath);
|
||||
if (ext.Equals(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var labels = JsonSerializer.Deserialize<string[]>(File.ReadAllText(labelAbsolutePath));
|
||||
return labels is { Length: > 0 } ? labels : null;
|
||||
}
|
||||
|
||||
var lines = File.ReadAllLines(labelAbsolutePath)
|
||||
.Where(t => !string.IsNullOrWhiteSpace(t))
|
||||
.Select(t => t.Trim())
|
||||
.ToArray();
|
||||
return lines.Length > 0 ? lines : null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public readonly record struct RedNetPrediction(int ClassIndex, string ClassLabel, float Confidence);
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
@@ -8,9 +8,9 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
|
||||
@@ -31,7 +31,7 @@ public class PickTextInference : ITextInference
|
||||
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
|
||||
|
||||
var json = File.ReadAllText(wordJsonPath);
|
||||
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ??
|
||||
_wordDictionary = JsonConvert.DeserializeObject<Dictionary<int, string>>(json) ??
|
||||
throw new Exception("index_2_word.json deserialize failed");
|
||||
}
|
||||
|
||||
@@ -116,4 +116,4 @@ public class PickTextInference : ITextInference
|
||||
|
||||
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
|
||||
public class TextInferenceFactory
|
||||
{
|
||||
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
|
||||
public static readonly Lazy<ITextInference> Pick = new(() => Create(OcrEngineTypes.YapModel));
|
||||
|
||||
public static ITextInference Create(OcrEngineTypes type)
|
||||
{
|
||||
|
||||
@@ -87,4 +87,24 @@ public static class CommonExtension
|
||||
{
|
||||
return list.ConvertAll(ToPoint2d);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将矩形钳位到指定尺寸范围内(交集语义),防止 OpenCV ROI 越界
|
||||
/// </summary>
|
||||
public static Rect ClampTo(this Rect rect, int maxWidth, int maxHeight)
|
||||
{
|
||||
int x1 = Math.Clamp(rect.X, 0, maxWidth);
|
||||
int y1 = Math.Clamp(rect.Y, 0, maxHeight);
|
||||
int x2 = Math.Clamp(rect.X + rect.Width, 0, maxWidth);
|
||||
int y2 = Math.Clamp(rect.Y + rect.Height, 0, maxHeight);
|
||||
return new Rect(x1, y1, x2 - x1, y2 - y1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将矩形钳位到 Mat 范围内(交集语义),防止 OpenCV ROI 越界
|
||||
/// </summary>
|
||||
public static Rect ClampTo(this Rect rect, Mat mat)
|
||||
{
|
||||
return rect.ClampTo(mat.Cols, mat.Rows);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,40 @@ using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
/// <summary>
|
||||
/// 形态学操作参数类
|
||||
/// </summary>
|
||||
public class MorphologyParam
|
||||
{
|
||||
/// <summary>
|
||||
/// 运算核大小
|
||||
/// </summary>
|
||||
public Size KernelSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 运算方法
|
||||
/// </summary>
|
||||
public MorphTypes MorphType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 运算次数
|
||||
/// </summary>
|
||||
public int Iterations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 形态学操作参数构造函数
|
||||
/// </summary>
|
||||
/// <param name="kernelSize">运算核大小</param>
|
||||
/// <param name="morphType">运算方法</param>
|
||||
/// <param name="iterations">运算次数</param>
|
||||
public MorphologyParam(Size kernelSize, MorphTypes morphType, int iterations)
|
||||
{
|
||||
KernelSize = kernelSize;
|
||||
MorphType = morphType;
|
||||
Iterations = iterations;
|
||||
}
|
||||
}
|
||||
|
||||
public class ContoursHelper
|
||||
{
|
||||
/// <summary>
|
||||
@@ -16,14 +50,21 @@ public class ContoursHelper
|
||||
/// <param name="high">RGB色彩高位</param>
|
||||
/// <param name="minWidth">矩形最小宽度</param>
|
||||
/// <param name="minHeight">矩形最小高度</param>
|
||||
/// <param name="morphologyParam">形态学操作参数(可选)</param>
|
||||
/// <returns></returns>
|
||||
public static List<Rect> FindSpecifyColorRects(Mat srcMat, Scalar low, Scalar high, int minWidth = -1, int minHeight = -1)
|
||||
public static List<Rect> FindSpecifyColorRects(Mat srcMat, Scalar low, Scalar high, int minWidth = -1, int minHeight = -1, MorphologyParam? morphologyParam = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var src = srcMat.Clone();
|
||||
Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(src, low, high, src);
|
||||
|
||||
if (morphologyParam != null)
|
||||
{
|
||||
using var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, morphologyParam.KernelSize);
|
||||
Cv2.MorphologyEx(src, src, morphologyParam.MorphType, kernel, iterations: morphologyParam.Iterations);
|
||||
}
|
||||
|
||||
Cv2.FindContours(src, out var contours, out _, RetrievalModes.External,
|
||||
ContourApproximationModes.ApproxSimple);
|
||||
@@ -56,4 +97,9 @@ public class ContoursHelper
|
||||
{
|
||||
return FindSpecifyColorRects(srcMat, color, color, minWidth, minHeight);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Rect> FindSpecifyColorRects(Mat srcMat, Scalar color, int minWidth, int minHeight, MorphologyParam morphologyParam)
|
||||
{
|
||||
return FindSpecifyColorRects(srcMat, color, color, minWidth, minHeight, morphologyParam);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using OpenCvSharp;
|
||||
|
||||
@@ -24,7 +25,7 @@ public static class Feature2DExtensions
|
||||
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
|
||||
{
|
||||
Mat trainDescriptors = new();
|
||||
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
|
||||
var img = Bv.ImRead(trainImagePath, ImreadModes.Grayscale);
|
||||
|
||||
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -81,6 +81,79 @@ public class KeyPointFeatureBlockHelper
|
||||
return (cellRow, cellCol);
|
||||
}
|
||||
|
||||
public static (int RowStart, int RowEnd, int ColStart, int ColEnd) GetCellRange(Size originalImage, int rows, int cols, Rect rect)
|
||||
{
|
||||
int cellWidth = originalImage.Width / cols;
|
||||
int cellHeight = originalImage.Height / rows;
|
||||
|
||||
var rowStart = (int)(rect.Y / cellHeight);
|
||||
var rowEnd = (int)((rect.Y + rect.Height) / cellHeight);
|
||||
var colStart = (int)(rect.X / cellWidth);
|
||||
var colEnd = (int)((rect.X + rect.Width) / cellWidth);
|
||||
|
||||
rowStart = Math.Max(0, Math.Min(rowStart, rows - 1));
|
||||
rowEnd = Math.Max(0, Math.Min(rowEnd, rows - 1));
|
||||
colStart = Math.Max(0, Math.Min(colStart, cols - 1));
|
||||
colEnd = Math.Max(0, Math.Min(colEnd, cols - 1));
|
||||
|
||||
if (rowEnd < rowStart)
|
||||
{
|
||||
rowEnd = rowStart;
|
||||
}
|
||||
|
||||
if (colEnd < colStart)
|
||||
{
|
||||
colEnd = colStart;
|
||||
}
|
||||
|
||||
return (rowStart, rowEnd, colStart, colEnd);
|
||||
}
|
||||
|
||||
public static KeyPointFeatureBlock MergeFeaturesInRange(KeyPointFeatureBlock[][] splitKeyPoints, Mat matches, int rowStart, int rowEnd, int colStart, int colEnd)
|
||||
{
|
||||
var rows = splitKeyPoints.Length;
|
||||
if (rows == 0)
|
||||
{
|
||||
return new KeyPointFeatureBlock();
|
||||
}
|
||||
|
||||
var cols = splitKeyPoints[0].Length;
|
||||
|
||||
rowStart = Math.Max(0, Math.Min(rowStart, rows - 1));
|
||||
rowEnd = Math.Max(0, Math.Min(rowEnd, rows - 1));
|
||||
colStart = Math.Max(0, Math.Min(colStart, cols - 1));
|
||||
colEnd = Math.Max(0, Math.Min(colEnd, cols - 1));
|
||||
|
||||
var matchesCols = matches.Cols;
|
||||
var neighboringKeyPoints = new List<KeyPoint>();
|
||||
var neighboringKeyPointIndices = new List<int>();
|
||||
|
||||
for (int i = rowStart; i <= rowEnd; i++)
|
||||
{
|
||||
for (int j = colStart; j <= colEnd; j++)
|
||||
{
|
||||
if (splitKeyPoints[i][j] != null)
|
||||
{
|
||||
neighboringKeyPoints.AddRange(splitKeyPoints[i][j].KeyPointList);
|
||||
neighboringKeyPointIndices.AddRange(splitKeyPoints[i][j].KeyPointIndexList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var mergedKeyPointBlock = new KeyPointFeatureBlock
|
||||
{
|
||||
MergedCenterCellCol = (colStart + colEnd) / 2,
|
||||
MergedCenterCellRow = (rowStart + rowEnd) / 2,
|
||||
KeyPointList = neighboringKeyPoints,
|
||||
KeyPointIndexList = neighboringKeyPointIndices
|
||||
};
|
||||
|
||||
mergedKeyPointBlock.Descriptor = new Mat(mergedKeyPointBlock.KeyPointIndexList.Count, matchesCols, MatType.CV_32FC1);
|
||||
InitBlockMat(mergedKeyPointBlock.KeyPointIndexList, mergedKeyPointBlock.Descriptor, matches);
|
||||
|
||||
return mergedKeyPointBlock;
|
||||
}
|
||||
|
||||
public static KeyPointFeatureBlock MergeNeighboringFeatures(KeyPointFeatureBlock[][] splitKeyPoints, Mat matches, int cellRow, int cellCol)
|
||||
{
|
||||
var matchesCols = matches.Cols; // SURF 64 SIFT 128
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class ImageDifferenceDetector
|
||||
{
|
||||
/// <summary>
|
||||
/// 找出四张灰度图中与其他三张差异最大的图片
|
||||
/// 投票机制:每张图片投票给与它差异最大的图片,如果某张图片获得3票则返回其索引
|
||||
/// </summary>
|
||||
/// <param name="images">包含4张Mat对象的数组</param>
|
||||
/// <returns>差异最大的图片索引(0-3),如果没有图片获得3票则返回-1</returns>
|
||||
public static int FindMostDifferentImage(Mat[] images)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (images is not { Length: 4 })
|
||||
{
|
||||
throw new ArgumentException("必须提供4张图片");
|
||||
}
|
||||
|
||||
// 验证所有图片尺寸相同
|
||||
Size firstSize = images[0].Size();
|
||||
for (int i = 1; i < 4; i++)
|
||||
{
|
||||
if (images[i].Size() != firstSize)
|
||||
{
|
||||
throw new ArgumentException("所有图片必须具有相同的尺寸");
|
||||
}
|
||||
}
|
||||
|
||||
// 存储每张图片获得的投票数
|
||||
int[] votes = new int[4];
|
||||
|
||||
// 每张图片投票给与它差异最大的图片
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
int maxDiffImageIndex = -1;
|
||||
double maxDifference = 0;
|
||||
|
||||
// 找出与图片i差异最大的图片
|
||||
for (int j = 0; j < 4; j++)
|
||||
{
|
||||
if (i != j)
|
||||
{
|
||||
double difference = CalculateDifference(images[i], images[j]);
|
||||
Debug.WriteLine($"{i} vs {j} 差异像素数量: {difference}");
|
||||
|
||||
if (difference > maxDifference)
|
||||
{
|
||||
maxDifference = difference;
|
||||
maxDiffImageIndex = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 图片i投票给差异最大的图片
|
||||
if (maxDiffImageIndex != -1)
|
||||
{
|
||||
votes[maxDiffImageIndex]++;
|
||||
Debug.WriteLine($"图片 {i} 投票给图片 {maxDiffImageIndex} (差异值: {maxDifference:F2})");
|
||||
}
|
||||
}
|
||||
|
||||
// 输出投票结果
|
||||
Debug.WriteLine("\n投票结果:");
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Debug.WriteLine($"图片 {i}: {votes[i]} 票");
|
||||
}
|
||||
|
||||
// 检查是否有图片获得3票
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
if (votes[i] >= 3)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine($"FindMostDifferentImage 出错: {ex.Message}");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算差值
|
||||
/// </summary>
|
||||
private static double CalculateDifference(Mat img1, Mat img2)
|
||||
{
|
||||
using var diff = new Mat();
|
||||
// 计算差值的绝对值
|
||||
Cv2.Absdiff(img1, img2, diff);
|
||||
// 统计非零像素点(即颜色不同的像素点)
|
||||
return Cv2.CountNonZero(diff);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
public class TemplateMatchStabilityDetector : IDisposable
|
||||
{
|
||||
private Mat previousFrame;
|
||||
private readonly double similarityThreshold = 0.98; // 相似度阈值(0-1)
|
||||
private readonly int stableFrameCount = 2;
|
||||
private int currentStableCount = 0;
|
||||
private double lastSimilarity = 0;
|
||||
|
||||
public bool IsStable(Mat currentFrame)
|
||||
{
|
||||
Mat processed = PreprocessFrame(currentFrame);
|
||||
|
||||
if (previousFrame == null)
|
||||
{
|
||||
previousFrame = processed;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用归一化相关系数进行匹配
|
||||
double similarity = ComputeSimilarity(previousFrame, processed);
|
||||
lastSimilarity = similarity;
|
||||
|
||||
Debug.WriteLine("Similarity: " + similarity);
|
||||
if (similarity >= similarityThreshold)
|
||||
{
|
||||
currentStableCount++;
|
||||
if (currentStableCount >= stableFrameCount)
|
||||
{
|
||||
previousFrame?.Dispose();
|
||||
previousFrame = processed;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
processed.Dispose();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
currentStableCount = 0;
|
||||
previousFrame?.Dispose();
|
||||
previousFrame = processed;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Mat PreprocessFrame(Mat frame)
|
||||
{
|
||||
Mat small = new Mat();
|
||||
|
||||
// 降采样加速
|
||||
Cv2.Resize(frame, small, new Size(320, 180), 0, 0, InterpolationFlags.Area);
|
||||
|
||||
return small;
|
||||
}
|
||||
|
||||
private double ComputeSimilarity(Mat template, Mat image)
|
||||
{
|
||||
// 确保两帧大小相同
|
||||
if (template.Size() != image.Size())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 使用归一化相关系数匹配
|
||||
Mat result = new Mat();
|
||||
Cv2.MatchTemplate(image, template, result, TemplateMatchModes.CCoeffNormed);
|
||||
|
||||
// 获取匹配结果(只有一个值)
|
||||
double minVal, maxVal;
|
||||
Point minLoc, maxLoc;
|
||||
Cv2.MinMaxLoc(result, out minVal, out maxVal, out minLoc, out maxLoc);
|
||||
|
||||
result.Dispose();
|
||||
|
||||
return maxVal; // 返回相关系数(-1 到 1,1 表示完全相同)
|
||||
}
|
||||
|
||||
public double GetLastSimilarity()
|
||||
{
|
||||
return lastSimilarity;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
currentStableCount = 0;
|
||||
previousFrame?.Dispose();
|
||||
previousFrame = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
previousFrame?.Dispose();
|
||||
previousFrame = null;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,16 @@ public class RecognitionObject
|
||||
/// </summary>
|
||||
public int MaxMatchCount { get; set; } = -1;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用二值化后模板匹配
|
||||
/// </summary>
|
||||
public bool UseBinaryMatch { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 二值化阈值,默认 128
|
||||
/// </summary>
|
||||
public int BinaryThreshold { get; set; } = 128;
|
||||
|
||||
public RecognitionObject InitTemplate()
|
||||
{
|
||||
if (TemplateImageMat != null && TemplateImageGreyMat == null)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using System.Threading.Tasks;
|
||||
@@ -12,11 +12,13 @@ public class AutoPathingScript
|
||||
{
|
||||
private object? _config = null;
|
||||
private string _rootPath;
|
||||
private readonly LimitedFile _autoPathingFile;
|
||||
|
||||
public AutoPathingScript(string rootPath, object? config)
|
||||
{
|
||||
_config = config;
|
||||
_rootPath = rootPath;
|
||||
_autoPathingFile = new LimitedFile(Global.Absolute(@"User\AutoPathing"));
|
||||
}
|
||||
|
||||
public async Task Run(string json)
|
||||
@@ -59,7 +61,40 @@ public class AutoPathingScript
|
||||
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
|
||||
public async Task RunFileFromUser(string path)
|
||||
{
|
||||
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
|
||||
var json = await AutoPathingFile.ReadText(path);
|
||||
await Run(json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断 AutoPathing 目录下的路径是否存在
|
||||
/// </summary>
|
||||
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
|
||||
/// <returns>存在返回 true,否则返回 false</returns>
|
||||
public bool IsExists(string subPath) => AutoPathingFile.IsExists(subPath);
|
||||
|
||||
/// <summary>
|
||||
/// 判断 AutoPathing 目录下的路径是否为文件
|
||||
/// </summary>
|
||||
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
|
||||
/// <returns>是文件返回 true,否则返回 false</returns>
|
||||
public bool IsFile(string subPath) => AutoPathingFile.IsFile(subPath);
|
||||
|
||||
/// <summary>
|
||||
/// 判断 AutoPathing 目录下的路径是否为文件夹
|
||||
/// </summary>
|
||||
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
|
||||
/// <returns>是文件夹返回 true,否则返回 false</returns>
|
||||
public bool IsFolder(string subPath) => AutoPathingFile.IsFolder(subPath);
|
||||
|
||||
/// <summary>
|
||||
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
|
||||
/// </summary>
|
||||
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
|
||||
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
|
||||
public string[] ReadPathSync(string subPath = "./") => AutoPathingFile.ReadPathSync(subPath);
|
||||
|
||||
/// <summary>
|
||||
/// LimitedFile 实例,用于操作 AutoPathing 目录
|
||||
/// </summary>
|
||||
private LimitedFile AutoPathingFile => _autoPathingFile;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.ClearScript;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public class CustomHostFunctions : HostFunctions
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建指定维度的交错数组变量
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数组元素类型</typeparam>
|
||||
/// <param name="dimensions">数组维度</param>
|
||||
/// <returns>交错数组变量</returns>
|
||||
public object NewVarOfArr<T>(int dimensions)
|
||||
{
|
||||
try
|
||||
{
|
||||
Type arrayType = typeof(T);
|
||||
for (int i = 0; i < dimensions; i++)
|
||||
{
|
||||
arrayType = arrayType.MakeArrayType();
|
||||
}
|
||||
|
||||
MethodInfo newVarMethod = typeof(HostFunctions).GetMethod(nameof(newVar))!;
|
||||
MethodInfo genericMethod = newVarMethod.MakeGenericMethod(arrayType);
|
||||
return genericMethod.Invoke(this, new object?[] { null })!;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new InvalidOperationException($"创建维度为 {dimensions} 的数组失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoEat;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
using BetterGenshinImpact.GameTask.AutoWood;
|
||||
@@ -14,8 +15,13 @@ using BetterGenshinImpact.ViewModel.Pages;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Dynamic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
|
||||
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
@@ -190,10 +196,13 @@ public class Dispatcher
|
||||
await new AutoFishingTask(AutoFishingTaskParam.BuildFromSoloTaskConfig(soloTask.Config)).Start(
|
||||
cancellationToken);
|
||||
return null;
|
||||
case "AutoCook":
|
||||
await new AutoCookTask().Start(cancellationToken);
|
||||
return null;
|
||||
case "AutoEat":
|
||||
{
|
||||
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue<string?>((ScriptObject)soloTask.Config, "foodName", null);
|
||||
FoodEffectType? foodEffectType = soloTask.Config == null ? null : (FoodEffectType?)ScriptObjectConverter.GetValue<int?>((ScriptObject)soloTask.Config, "foodEffectType", null);
|
||||
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodName", (string?)null);
|
||||
FoodEffectType? foodEffectType = soloTask.Config == null ? null : (FoodEffectType?)ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodEffectType", (int?)null);
|
||||
|
||||
if (foodName != null && foodEffectType != null)
|
||||
{
|
||||
@@ -259,9 +268,32 @@ public class Dispatcher
|
||||
{
|
||||
throw new NullReferenceException($"{nameof(soloTask.Config)}为空");
|
||||
}
|
||||
GridScreenName gridScreenName = ScriptObjectConverter.GetValue<GridScreenName?>((ScriptObject)soloTask.Config, "gridScreenName", null) ?? throw new Exception("gridScreenName为空或错误");
|
||||
string itemName = ScriptObjectConverter.GetValue<string?>((ScriptObject)soloTask.Config, "itemName", null) ?? throw new Exception("itemName为空");
|
||||
return await new CountInventoryItem(gridScreenName, itemName).Start(cancellationToken);
|
||||
GridScreenName gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null) ?? throw new Exception("gridScreenName为空或错误");
|
||||
string? itemName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "itemName", (string?)null);
|
||||
IEnumerable<string>? itemNames = ScriptObjectConverter.GetValue<string>((ScriptObject)soloTask.Config, "itemNames");
|
||||
if (itemName != null && itemNames != null)
|
||||
{
|
||||
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时使用");
|
||||
}
|
||||
if (itemName == null && itemNames == null)
|
||||
{
|
||||
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时为空");
|
||||
}
|
||||
var result = await new CountInventoryItem(gridScreenName, itemName, itemNames).Start(cancellationToken);
|
||||
if (itemName != null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
dynamic expando = new ExpandoObject();
|
||||
var expandoDict = (IDictionary<string, object>)expando;
|
||||
foreach (var kvp in (Dictionary<string, int>)result)
|
||||
{
|
||||
expandoDict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
return expandoDict;
|
||||
}
|
||||
}
|
||||
default:
|
||||
throw new ArgumentException($"未知的任务名称: {soloTask.Name}", nameof(soloTask.Name));
|
||||
@@ -279,4 +311,73 @@ public class Dispatcher
|
||||
{
|
||||
return GetLinkedCancellationTokenSource().Token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运行自动秘境任务
|
||||
/// </summary>
|
||||
/// <param name="param">秘境任务参数</param>
|
||||
/// <param name="customCt">自定义取消令牌</param>
|
||||
/// <returns></returns>
|
||||
public async Task RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
|
||||
{
|
||||
if (param == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(param), "秘境任务参数不能为空");
|
||||
}
|
||||
|
||||
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
|
||||
await new AutoDomainTask(param).Start(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运行自动战斗任务
|
||||
/// </summary>
|
||||
/// <param name="param">战斗任务参数</param>
|
||||
/// <param name="customCt">自定义取消令牌</param>
|
||||
/// <returns></returns>
|
||||
public async Task RunAutoFightTask(AutoFightParam param, CancellationToken? customCt = null)
|
||||
{
|
||||
if (param == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(param), "战斗任务参数不能为空");
|
||||
}
|
||||
|
||||
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
|
||||
await new AutoFightTask(param).Start(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运行自动地脉花任务
|
||||
/// </summary>
|
||||
/// <param name="param">自动地脉花任务参数</param>
|
||||
/// <param name="customCt">自定义取消令牌</param>
|
||||
/// <returns></returns>
|
||||
public async Task RunAutoLeyLineOutcropTask(AutoLeyLineOutcropParam param, CancellationToken? customCt = null)
|
||||
{
|
||||
if (param == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(param), "自动地脉花任务参数不能为空");
|
||||
}
|
||||
|
||||
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
|
||||
await new AutoLeyLineOutcropTask(param).Start(cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 运行自动幽境危战任务
|
||||
/// </summary>
|
||||
/// <param name="param">自动幽境危战任务参数</param>
|
||||
/// <param name="customCt">自定义取消令牌</param>
|
||||
/// <returns></returns>
|
||||
public async Task RunAutoStygianOnslaughtTask(AutoStygianOnslaughtParam param, CancellationToken? customCt = null)
|
||||
{
|
||||
if (param == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(param), "自动幽境危战任务参数不能为空");
|
||||
}
|
||||
|
||||
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
|
||||
await new AutoStygianOnslaughtTask(param).Start(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,8 @@ public class Genshin
|
||||
|
||||
public Lazy<NavigationInstance> LazyNavigationInstance { get; } = new(() =>
|
||||
{
|
||||
Navigation.WarmUp();
|
||||
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
Navigation.WarmUp(matchingMethod);
|
||||
return new NavigationInstance();
|
||||
});
|
||||
|
||||
@@ -181,7 +182,7 @@ public class Genshin
|
||||
/// 获取当前在大地图上的位置坐标
|
||||
/// </summary>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromBigMap()
|
||||
public Point2f? GetPositionFromBigMap()
|
||||
{
|
||||
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
|
||||
return tpTask.GetPositionFromBigMap(MapTypes.Teyvat.ToString());
|
||||
@@ -192,7 +193,7 @@ public class Genshin
|
||||
/// </summary>
|
||||
/// <param name="mapName">大地图名称</param>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromBigMap(string mapName)
|
||||
public Point2f? GetPositionFromBigMap(string mapName)
|
||||
{
|
||||
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
|
||||
return tpTask.GetPositionFromBigMap(mapName);
|
||||
@@ -202,7 +203,7 @@ public class Genshin
|
||||
/// 获取当前在小地图上的位置坐标
|
||||
/// </summary>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromMap()
|
||||
public Point2f? GetPositionFromMap()
|
||||
{
|
||||
return GetPositionFromMap(MapTypes.Teyvat.ToString());
|
||||
}
|
||||
@@ -219,7 +220,7 @@ public class Genshin
|
||||
/// <param name="mapName">大地图名称</param>
|
||||
/// <param name="cacheTimeMs">缓存时间,单位毫秒,默认900ms</param>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromMap(string mapName, int cacheTimeMs = 900)
|
||||
public Point2f? GetPositionFromMap(string mapName, int cacheTimeMs = 900)
|
||||
{
|
||||
var imageRegion = CaptureToRectArea();
|
||||
if (!Bv.IsInMainUi(imageRegion))
|
||||
@@ -227,7 +228,10 @@ public class Genshin
|
||||
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
|
||||
}
|
||||
|
||||
return MapManager.GetMap(mapName).ConvertImageCoordinatesToGenshinMapCoordinates(LazyNavigationInstance.Value.GetPositionStableByCache(imageRegion, mapName, cacheTimeMs));
|
||||
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
return MapManager.GetMap(mapName, matchingMethod)
|
||||
.ConvertImageCoordinatesToGenshinMapCoordinates(LazyNavigationInstance.Value
|
||||
.GetPositionStableByCache(imageRegion, mapName, matchingMethod, cacheTimeMs));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -237,18 +241,19 @@ public class Genshin
|
||||
/// <param name="x">世界坐标x</param>
|
||||
/// <param name="y">世界坐标y</param>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromMap(string mapName, float x, float y)
|
||||
public Point2f? GetPositionFromMap(string mapName, float x, float y)
|
||||
{
|
||||
var imageRegion = CaptureToRectArea();
|
||||
if (!Bv.IsInMainUi(imageRegion))
|
||||
{
|
||||
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
|
||||
}
|
||||
var sceneMap = MapManager.GetMap(mapName);
|
||||
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
var sceneMap = MapManager.GetMap(mapName, matchingMethod);
|
||||
var navigationInstance = LazyNavigationInstance.Value;
|
||||
var pos = sceneMap.ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f(x, y));
|
||||
navigationInstance.SetPrevPosition(pos.X, pos.Y);
|
||||
return sceneMap.ConvertImageCoordinatesToGenshinMapCoordinates(navigationInstance.GetPosition(imageRegion, mapName));
|
||||
return sceneMap.ConvertImageCoordinatesToGenshinMapCoordinates(navigationInstance.GetPosition(imageRegion, mapName, matchingMethod));
|
||||
}
|
||||
|
||||
#endregion 大地图操作
|
||||
@@ -372,4 +377,45 @@ public class Genshin
|
||||
{
|
||||
await new ExitAndReloginJob().Start(CancellationContext.Instance.Cts.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进出千星奇域
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task WonderlandCycle()
|
||||
{
|
||||
await new EnterAndExitWonderlandJob().Start(CancellationContext.Instance.Cts.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 调整时间
|
||||
/// </summary>
|
||||
/// <param name="hour">目标小时(0-24)</param>
|
||||
/// <param name="minute">目标分钟(0-59)</param>
|
||||
/// <param name="skip">是否跳过动画(默认为否)</param>
|
||||
/// <returns></returns>
|
||||
public async Task SetTime(int hour, int minute, bool skip = false)
|
||||
{
|
||||
if ( hour < 0 || hour > 24)
|
||||
throw new ArgumentException($"无效的小时值: {hour},必须是 0-24 之间的整数字符", nameof(hour));
|
||||
if (minute < 0 || minute > 59)
|
||||
throw new ArgumentException($"无效的分钟值: {minute},必须是 0-59 之间的整数字符", nameof(minute));
|
||||
await new SetTimeTask().Start(hour, minute, CancellationContext.Instance.Cts.Token, skip);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 调整时间
|
||||
/// </summary>
|
||||
/// <param name="hour">目标小时(0-24的字符类型)</param>
|
||||
/// <param name="minute">目标分钟(0-59的字符类型)</param>
|
||||
/// <param name="skip">是否跳过动画(默认为否)</param>
|
||||
/// <returns></returns>
|
||||
public async Task SetTime(string hour, string minute, bool skip = false)
|
||||
{
|
||||
if (!int.TryParse(hour, out var h) || h < 0 || h > 24)
|
||||
throw new ArgumentException($"无效的小时值: {hour},必须是 0-24 之间的整数字符", nameof(hour));
|
||||
if (!int.TryParse(minute, out var m) || m < 0 || m > 59)
|
||||
throw new ArgumentException($"无效的分钟值: {minute},必须是 0-59 之间的整数字符", nameof(minute));
|
||||
await new SetTimeTask().Start(h, m, CancellationContext.Instance.Cts.Token, skip);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
@@ -23,6 +24,11 @@ public class GlobalMethod
|
||||
{
|
||||
await Task.Delay(millisecondsTimeout, CancellationContext.Instance.Cts.Token);
|
||||
}
|
||||
|
||||
public static string GetVersion()
|
||||
{
|
||||
return Global.Version;
|
||||
}
|
||||
|
||||
#region 键盘操作
|
||||
|
||||
@@ -161,6 +167,11 @@ public class GlobalMethod
|
||||
_dpi = dpi;
|
||||
}
|
||||
|
||||
public static double[] GetGameMetrics()
|
||||
{
|
||||
return [_gameWidth, _gameHeight, _dpi];
|
||||
}
|
||||
|
||||
public static void MoveMouseBy(int x, int y)
|
||||
{
|
||||
var realDpi = TaskContext.Instance().DpiScale;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using BetterGenshinImpact.Core.Script.Utils;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public class Http
|
||||
{
|
||||
private readonly ILogger<Http> _logger = App.GetLogger<Http>();
|
||||
|
||||
private void CheckHttpPermission(string url)
|
||||
{
|
||||
var currentProject = TaskContext.Instance().CurrentScriptProject;
|
||||
if (!currentProject?.AllowJsHTTP ?? false)
|
||||
{
|
||||
throw new UnauthorizedAccessException("当前JS脚本不允许使用HTTP请求,请在调度器通用设置中启用“JS HTTP权限”");
|
||||
}
|
||||
var allowedUrls = currentProject?.Project?.Manifest.HttpAllowedUrls ?? [];
|
||||
if (allowedUrls.Length == 0)
|
||||
{
|
||||
throw new UnauthorizedAccessException("当前JS脚本没有配置允许请求的URL,请在脚本的manifest.json中配置http_allowed_urls");
|
||||
}
|
||||
if (allowedUrls.Any(allowedUrl =>
|
||||
{
|
||||
// fuzzy match
|
||||
var pattern = "^" + System.Text.RegularExpressions.Regex.Escape(allowedUrl).Replace("\\*", ".*") + "$";
|
||||
_logger.LogDebug($"[HTTP] 检查URL {url} 是否符合: {pattern}");
|
||||
var regex = new System.Text.RegularExpressions.Regex(pattern);
|
||||
return regex.IsMatch(url);
|
||||
}))
|
||||
{
|
||||
return;
|
||||
}
|
||||
throw new UnauthorizedAccessException($"当前JS脚本不允许请求此URL: {url},请在脚本的manifest.json中配置http_allowed_urls,当前允许的URL列表: [{string.Join(", ", allowedUrls)}]");
|
||||
}
|
||||
|
||||
public class HttpReponse
|
||||
{
|
||||
public int status_code { get; set; }
|
||||
public Dictionary<string, string> headers { get; set; } = new();
|
||||
public string body { get; set; } = "";
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 执行HTTP请求
|
||||
/// </summary>
|
||||
/// <param name="method">HTTP方法</param>
|
||||
/// <param name="url">请求URL</param>
|
||||
/// <param name="body">请求体</param>
|
||||
/// <param name="headersJson">请求头,JSON格式</param>
|
||||
/// <returns></returns>
|
||||
public async Task<HttpReponse> Request(string method, string url, string? body = null, string? headersJson = null)
|
||||
{
|
||||
_logger.LogDebug($"[HTTP] 发送HTTP请求: {method} {url} Body: {(body != null ? body : "null")} Headers: {(headersJson != null ? headersJson : "null")}");
|
||||
CheckHttpPermission(url);
|
||||
|
||||
var dictHeaders = new Dictionary<string, string>();
|
||||
if (!string.IsNullOrWhiteSpace(headersJson))
|
||||
{
|
||||
try
|
||||
{
|
||||
var headers = JsonSerializer.Deserialize<Dictionary<string, string>>(headersJson);
|
||||
if (headers != null)
|
||||
{
|
||||
dictHeaders = headers;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new ArgumentException("Headers JSON格式错误");
|
||||
}
|
||||
}
|
||||
|
||||
// header全部小写
|
||||
dictHeaders = dictHeaders.ToDictionary(kvp => kvp.Key.ToLowerInvariant(), kvp => kvp.Value);
|
||||
|
||||
// 提前取出来Content-Type,防止被覆盖
|
||||
string contentType = "application/json";
|
||||
if (dictHeaders.TryGetValue("content-type", out var ct))
|
||||
{
|
||||
contentType = ct;
|
||||
dictHeaders.Remove("content-type");
|
||||
}
|
||||
|
||||
// 使用HttpClient发送请求
|
||||
using var httpClient = new HttpClient();
|
||||
httpClient.DefaultRequestHeaders.Clear();
|
||||
foreach (var header in dictHeaders)
|
||||
{
|
||||
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
|
||||
var content = body == null ? null : new StringContent(body, Encoding.UTF8, contentType);
|
||||
var response = await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(method), url) { Content = content });
|
||||
|
||||
var responseCode = (int)response.StatusCode;
|
||||
var responseHeaders = response.Headers.ToDictionary(h => h.Key, h => h.Value.First()); // 只取第一个值
|
||||
var responseBody = await response.Content.ReadAsStringAsync();
|
||||
return new HttpReponse
|
||||
{
|
||||
status_code = responseCode,
|
||||
headers = responseHeaders,
|
||||
body = responseBody,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using BetterGenshinImpact.Core.Monitor;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Gma.System.MouseKeyHook;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public class KeyMouseHook: IDisposable
|
||||
{
|
||||
private IKeyboardMouseEvents? _appEvents;
|
||||
private IKeyboardMouseEvents AppHook => _appEvents ??= MouseKeyMonitor.GlobalHook;
|
||||
|
||||
private readonly List<ScriptObject> _keyDownDataCallbacks = new();
|
||||
private readonly List<ScriptObject> _keyUpDataCallbacks = new();
|
||||
private readonly List<ScriptObject> _keyDownCodeCallbacks = new();
|
||||
private readonly List<ScriptObject> _keyUpCodeCallbacks = new();
|
||||
private readonly List<ScriptObject> _mouseDownCallbacks = new();
|
||||
private readonly List<ScriptObject> _mouseUpCallbacks = new();
|
||||
private readonly List<ScriptObject> _mouseMoveCallbacks = new();
|
||||
private readonly List<ScriptObject> _mouseWheelCallbacks = new();
|
||||
|
||||
/// <summary>
|
||||
/// 存储每个鼠标移动回调的间隔时间(毫秒)
|
||||
/// </summary>
|
||||
private readonly Dictionary<ScriptObject, int> _mouseMoveCallbackIntervals = new();
|
||||
|
||||
/// <summary>
|
||||
/// 存储每个鼠标移动回调的上次调用时间
|
||||
/// </summary>
|
||||
private readonly Dictionary<ScriptObject, DateTime> _lastMouseMoveCallbackTimes = new();
|
||||
|
||||
private KeyEventHandler? _keyDownHandler;
|
||||
private KeyEventHandler? _keyUpHandler;
|
||||
private EventHandler<MouseEventExtArgs>? _mouseDownExtHandler;
|
||||
private EventHandler<MouseEventExtArgs>? _mouseUpExtHandler;
|
||||
private EventHandler<MouseEventExtArgs>? _mouseMoveExtHandler;
|
||||
private EventHandler<MouseEventExtArgs>? _mouseWheelExtHandler;
|
||||
|
||||
private readonly object _mouseMoveLock = new();
|
||||
private DateTime _lastProcessMouseMoveTime = DateTime.MinValue;
|
||||
|
||||
private readonly ILogger<KeyMouseHook> _logger = App.GetLogger<KeyMouseHook>();
|
||||
|
||||
/// <summary>
|
||||
/// 统一处理回调函数执行过程中的异常
|
||||
/// </summary>
|
||||
/// <param name="ex">捕获到的异常</param>
|
||||
/// <param name="eventType">事件类型描述</param>
|
||||
private void HandleCallbackException(Exception ex, string eventType)
|
||||
{
|
||||
if (ex is ScriptEngineException scriptEx)
|
||||
{
|
||||
_logger.LogError("执行{eventType}JS回调时发生错误:{scriptEx.Message},清除所有回调",eventType, scriptEx.Message);
|
||||
_logger.LogDebug("{scriptEx}",scriptEx);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("执行{eventType}回调时发生错误:{ex.Message},清除所有回调,如果此异常出现在JS脚本结束时,请在JS脚本结束前手动调用Dispose()方法",eventType,ex.Message);
|
||||
_logger.LogDebug("{ex}",ex);
|
||||
}
|
||||
|
||||
Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将全局屏幕坐标转换为游戏窗口局部坐标
|
||||
/// </summary>
|
||||
/// <param name="globalX">全局X坐标</param>
|
||||
/// <param name="globalY">全局Y坐标</param>
|
||||
/// <returns>游戏窗口局部坐标(X, Y),转换失败时返回(-1, -1)</returns>
|
||||
private (int X, int Y) ConvertToLocalCoordinates(int globalX, int globalY)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 检查TaskContext是否已初始化
|
||||
if (!TaskContext.Instance().IsInitialized)
|
||||
{
|
||||
_logger.LogError("TaskContext未初始化,无法获取游戏窗口信息");
|
||||
return (-1, -1);
|
||||
}
|
||||
|
||||
var gameHandle = TaskContext.Instance().GameHandle;
|
||||
if (gameHandle == IntPtr.Zero)
|
||||
{
|
||||
_logger.LogError("游戏窗口句柄无效,无法获取游戏窗口位置");
|
||||
return (-1, -1);
|
||||
}
|
||||
|
||||
// 获取游戏窗口捕获区域
|
||||
var captureRect = SystemControl.GetCaptureRect(gameHandle);
|
||||
|
||||
// 检查捕获区域是否有效
|
||||
if (captureRect.Width <= 0 || captureRect.Height <= 0)
|
||||
{
|
||||
_logger.LogError("获取的游戏窗口捕获区域无效,宽度或高度为0");
|
||||
return (-1, -1);
|
||||
}
|
||||
|
||||
// 计算局部坐标
|
||||
int localX = globalX - captureRect.Left;
|
||||
int localY = globalY - captureRect.Top;
|
||||
|
||||
return (localX, localY);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "转换鼠标坐标时发生错误");
|
||||
return (-1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly System.Threading.Channels.Channel<Action> _eventChannel =
|
||||
System.Threading.Channels.Channel.CreateBounded<Action>(
|
||||
new System.Threading.Channels.BoundedChannelOptions(2048)
|
||||
{
|
||||
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait,
|
||||
SingleReader = true,
|
||||
SingleWriter = false
|
||||
});
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
|
||||
public KeyMouseHook()
|
||||
{
|
||||
// 启动后台事件处理器,确保不阻塞钩子线程
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var reader = _eventChannel.Reader;
|
||||
while (await reader.WaitToReadAsync(_cts.Token))
|
||||
{
|
||||
while (reader.TryRead(out var action))
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 内部错误已在 action 闭包中通过 HandleCallbackException 处理
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "键鼠钩子后台处理器发生异常");
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化事件处理程序
|
||||
_keyDownHandler = (_, args) =>
|
||||
{
|
||||
if (_keyDownDataCallbacks.Count == 0 && _keyDownCodeCallbacks.Count == 0) return;
|
||||
|
||||
var keyDownDataCallbacksCopy = new List<ScriptObject>(_keyDownDataCallbacks);
|
||||
var keyDownCodeCallbacksCopy = new List<ScriptObject>(_keyDownCodeCallbacks);
|
||||
var keyDataStr = args.KeyData.ToString();
|
||||
var keyCodeStr = args.KeyCode.ToString();
|
||||
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
// 调用KeyData回调
|
||||
foreach (var callback in keyDownDataCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(keyDataStr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "键盘按下事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 调用KeyCode回调
|
||||
foreach (var callback in keyDownCodeCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(keyCodeStr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "键盘按下事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略键盘按下回调");
|
||||
}
|
||||
};
|
||||
|
||||
_keyUpHandler = (_, args) =>
|
||||
{
|
||||
if (_keyUpDataCallbacks.Count == 0 && _keyUpCodeCallbacks.Count == 0) return;
|
||||
|
||||
var keyUpDataCallbacksCopy = new List<ScriptObject>(_keyUpDataCallbacks);
|
||||
var keyUpCodeCallbacksCopy = new List<ScriptObject>(_keyUpCodeCallbacks);
|
||||
var keyDataStr = args.KeyData.ToString();
|
||||
var keyCodeStr = args.KeyCode.ToString();
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
// 调用KeyData回调
|
||||
foreach (var callback in keyUpDataCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(keyDataStr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "键盘释放事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 调用KeyCode回调
|
||||
foreach (var callback in keyUpCodeCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(keyCodeStr);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "键盘释放事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略键盘释放回调");
|
||||
}
|
||||
};
|
||||
|
||||
_mouseDownExtHandler = (_, args) =>
|
||||
{
|
||||
if (_mouseDownCallbacks.Count == 0) return;
|
||||
|
||||
var mouseDownCallbacksCopy = new List<ScriptObject>(_mouseDownCallbacks);
|
||||
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
|
||||
var buttonStr = args.Button.ToString();
|
||||
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
foreach (var callback in mouseDownCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(buttonStr, localX, localY);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "鼠标按下事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标按下回调");
|
||||
}
|
||||
};
|
||||
|
||||
_mouseUpExtHandler = (_, args) =>
|
||||
{
|
||||
if (_mouseUpCallbacks.Count == 0) return;
|
||||
|
||||
var mouseUpCallbacksCopy = new List<ScriptObject>(_mouseUpCallbacks);
|
||||
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
|
||||
var buttonStr = args.Button.ToString();
|
||||
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
foreach (var callback in mouseUpCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(buttonStr, localX, localY);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "鼠标释放事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标释放回调");
|
||||
}
|
||||
};
|
||||
|
||||
_mouseMoveExtHandler = (_, args) =>
|
||||
{
|
||||
if (_mouseMoveCallbacks.Count == 0) return;
|
||||
|
||||
var now = DateTime.Now;
|
||||
if ((now - _lastProcessMouseMoveTime).TotalMilliseconds < 10) return;
|
||||
_lastProcessMouseMoveTime = now;
|
||||
|
||||
var mouseMoveCallbacksCopy = new List<ScriptObject>(_mouseMoveCallbacks);
|
||||
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
|
||||
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
foreach (var callback in mouseMoveCallbacksCopy)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
lock (_mouseMoveLock)
|
||||
{
|
||||
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval) &&
|
||||
_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
|
||||
{
|
||||
var timeSpan = now - lastTime;
|
||||
if (timeSpan.TotalMilliseconds >= interval)
|
||||
{
|
||||
callback.InvokeAsFunction(localX, localY);
|
||||
_lastMouseMoveCallbackTimes[callback] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "鼠标移动事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标移动回调");
|
||||
}
|
||||
};
|
||||
|
||||
_mouseWheelExtHandler = (_, args) =>
|
||||
{
|
||||
if (_mouseWheelCallbacks.Count == 0) return;
|
||||
|
||||
var mouseWheelCallbacksCopy = new List<ScriptObject>(_mouseWheelCallbacks);
|
||||
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
|
||||
var delta = args.Delta;
|
||||
|
||||
if (!_eventChannel.Writer.TryWrite(() =>
|
||||
{
|
||||
foreach (var callback in mouseWheelCallbacksCopy)
|
||||
{
|
||||
try
|
||||
{
|
||||
callback.InvokeAsFunction(delta, localX, localY);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleCallbackException(ex, "鼠标滚轮事件");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}))
|
||||
{
|
||||
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标滚轮回调");
|
||||
}
|
||||
};
|
||||
|
||||
// 添加事件监听器
|
||||
AppHook.KeyDown += _keyDownHandler;
|
||||
AppHook.KeyUp += _keyUpHandler;
|
||||
AppHook.MouseDownExt += _mouseDownExtHandler;
|
||||
AppHook.MouseUpExt += _mouseUpExtHandler;
|
||||
AppHook.MouseMoveExt += _mouseMoveExtHandler;
|
||||
AppHook.MouseWheelExt += _mouseWheelExtHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册键盘按下事件回调
|
||||
/// </summary>
|
||||
/// <param name="callback">回调函数</param>
|
||||
/// <param name="useCodeOnly">是否仅返回KeyCode,默认为true(仅返回KeyCode)</param>
|
||||
public void OnKeyDown(ScriptObject callback, bool useCodeOnly = true)
|
||||
{
|
||||
if (useCodeOnly)
|
||||
_keyDownCodeCallbacks.Add(callback);
|
||||
else
|
||||
_keyDownDataCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册键盘释放事件回调
|
||||
/// </summary>
|
||||
/// <param name="callback">回调函数</param>
|
||||
/// <param name="useCodeOnly">是否仅返回KeyCode,默认为true(仅返回KeyCode)</param>
|
||||
public void OnKeyUp(ScriptObject callback, bool useCodeOnly = true)
|
||||
{
|
||||
if (useCodeOnly)
|
||||
_keyUpCodeCallbacks.Add(callback);
|
||||
else
|
||||
_keyUpDataCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
public void OnMouseDown(ScriptObject callback)
|
||||
{
|
||||
_mouseDownCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
public void OnMouseUp(ScriptObject callback)
|
||||
{
|
||||
_mouseUpCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册鼠标移动事件回调
|
||||
/// </summary>
|
||||
/// <param name="callback">回调函数</param>
|
||||
/// <param name="interval">回调间隔时间(毫秒),默认200ms</param>
|
||||
public void OnMouseMove(ScriptObject callback, int interval = 200)
|
||||
{
|
||||
_mouseMoveCallbacks.Add(callback);
|
||||
_mouseMoveCallbackIntervals[callback] = interval;
|
||||
_lastMouseMoveCallbackTimes[callback] = DateTime.MinValue;
|
||||
}
|
||||
|
||||
public void OnMouseWheel(ScriptObject callback)
|
||||
{
|
||||
_mouseWheelCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
public void RemoveAllListeners()
|
||||
{
|
||||
_keyDownDataCallbacks.Clear();
|
||||
_keyUpDataCallbacks.Clear();
|
||||
_keyDownCodeCallbacks.Clear();
|
||||
_keyUpCodeCallbacks.Clear();
|
||||
_mouseDownCallbacks.Clear();
|
||||
_mouseUpCallbacks.Clear();
|
||||
_mouseMoveCallbacks.Clear();
|
||||
_mouseWheelCallbacks.Clear();
|
||||
|
||||
_mouseMoveCallbackIntervals.Clear();
|
||||
_lastMouseMoveCallbackTimes.Clear();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_cts.Cancel();
|
||||
_eventChannel.Writer.TryComplete();
|
||||
// 移除所有事件监听器
|
||||
if (_keyDownHandler != null)
|
||||
{
|
||||
AppHook.KeyDown -= _keyDownHandler;
|
||||
_keyDownHandler = null;
|
||||
}
|
||||
|
||||
if (_keyUpHandler != null)
|
||||
{
|
||||
AppHook.KeyUp -= _keyUpHandler;
|
||||
_keyUpHandler = null;
|
||||
}
|
||||
|
||||
if (_mouseDownExtHandler != null)
|
||||
{
|
||||
AppHook.MouseDownExt -= _mouseDownExtHandler;
|
||||
_mouseDownExtHandler = null;
|
||||
}
|
||||
|
||||
if (_mouseUpExtHandler != null)
|
||||
{
|
||||
AppHook.MouseUpExt -= _mouseUpExtHandler;
|
||||
_mouseUpExtHandler = null;
|
||||
}
|
||||
|
||||
if (_mouseMoveExtHandler != null)
|
||||
{
|
||||
AppHook.MouseMoveExt -= _mouseMoveExtHandler;
|
||||
_mouseMoveExtHandler = null;
|
||||
}
|
||||
|
||||
if (_mouseWheelExtHandler != null)
|
||||
{
|
||||
AppHook.MouseWheelExt -= _mouseWheelExtHandler;
|
||||
_mouseWheelExtHandler = null;
|
||||
}
|
||||
|
||||
// 清空回调列表
|
||||
RemoveAllListeners();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
using BetterGenshinImpact.Core.Script.Utils;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
@@ -16,26 +20,35 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
|
||||
public string[] ReadPathSync(string folderPath)
|
||||
{
|
||||
// 对传入的文件夹路径进行标准化
|
||||
string normalizedFolderPath = NormalizePath(folderPath);
|
||||
|
||||
// 确保目录存在
|
||||
if (!Directory.Exists(normalizedFolderPath))
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(normalizedFolderPath);
|
||||
// 对传入的文件夹路径进行标准化
|
||||
string normalizedFolderPath = NormalizePath(folderPath);
|
||||
|
||||
// 确保目录存在
|
||||
if (!Directory.Exists(normalizedFolderPath))
|
||||
{
|
||||
Directory.CreateDirectory(normalizedFolderPath);
|
||||
}
|
||||
|
||||
// 获取指定文件夹下的所有文件(非递归)
|
||||
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
|
||||
|
||||
// 获取指定文件夹下的所有子文件夹(非递归)
|
||||
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
|
||||
|
||||
// 合并文件和文件夹路径
|
||||
string[] combined = files.Concat(directories).ToArray();
|
||||
|
||||
// 将绝对路径转换为相对于 rootPath 的相对路径
|
||||
return combined.Select(path => Path.GetRelativePath(rootPath, path)).ToArray();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回空数组
|
||||
TaskControl.Logger.LogError("ReadPathSync 异常: {Message}", ex.Message);
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
|
||||
// 获取指定文件夹下的所有文件(非递归)
|
||||
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
|
||||
|
||||
// 获取指定文件夹下的所有子文件夹(非递归)
|
||||
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
|
||||
|
||||
// 合并文件和文件夹路径
|
||||
string[] combined = files.Concat(directories).ToArray();
|
||||
|
||||
// 将绝对路径转换为相对于 rootPath 的相对路径
|
||||
return combined.Select(path => Path.GetRelativePath(rootPath, path)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -45,11 +58,58 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns>如果该路径是文件夹则返回 true,否则返回 false。</returns>
|
||||
public bool IsFolder(string path)
|
||||
{
|
||||
// 对传入的路径进行标准化处理
|
||||
string normalizedPath = NormalizePath(path);
|
||||
try
|
||||
{
|
||||
// 对传入的路径进行标准化处理
|
||||
string normalizedPath = NormalizePath(path);
|
||||
|
||||
// 使用 Directory.Exists 判断标准化路径是否为文件夹
|
||||
return Directory.Exists(normalizedPath);
|
||||
// 使用 Directory.Exists 判断标准化路径是否为文件夹
|
||||
return Directory.Exists(normalizedPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回 false
|
||||
TaskControl.Logger.LogError("IsFolder 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定路径是否为文件
|
||||
/// </summary>
|
||||
/// <param name="path">文件路径(相对于根目录)</param>
|
||||
/// <returns>如果是文件则返回 true,否则返回 false</returns>
|
||||
public bool IsFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string normalizedPath = NormalizePath(path);
|
||||
return File.Exists(normalizedPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskControl.Logger.LogError("IsFile 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定的文件或目录是否存在
|
||||
/// </summary>
|
||||
/// <param name="path">文件或目录路径(相对于根目录)</param>
|
||||
/// <returns>如果存在返回 true,否则返回 false</returns>
|
||||
public bool IsExists(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string normalizedPath = NormalizePath(path);
|
||||
return File.Exists(normalizedPath) || Directory.Exists(normalizedPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskControl.Logger.LogError("IsExists 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,8 +127,17 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns>Text read from file.</returns>
|
||||
public string ReadTextSync(string path)
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
return File.ReadAllText(path);
|
||||
try
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
return File.ReadAllText(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回空字符串
|
||||
TaskControl.Logger.LogError("ReadTextSync 异常: {Message}", ex.Message);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -78,9 +147,18 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns>Text read from file.</returns>
|
||||
public async Task<string> ReadText(string path)
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
var ret = await File.ReadAllTextAsync(path);
|
||||
return ret;
|
||||
try
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
var ret = await File.ReadAllTextAsync(path);
|
||||
return ret;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回空字符串
|
||||
TaskControl.Logger.LogError("ReadText 异常: {Message}", ex.Message);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,11 +190,70 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns></returns>
|
||||
public Mat ReadImageMatSync(string path)
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
var mat = Mat.FromStream(File.OpenRead(path), ImreadModes.Color);
|
||||
return mat;
|
||||
try
|
||||
{
|
||||
path = NormalizePath(path);
|
||||
using var stream = File.OpenRead(path);
|
||||
var mat = Mat.FromStream(stream, ImreadModes.Color);
|
||||
return mat;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回空的Mat
|
||||
TaskControl.Logger.LogError("ReadImageMatSync 异常: {Message}", ex.Message);
|
||||
return new Mat();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取图像文件为Mat对象,并调整到指定尺寸
|
||||
/// </summary>
|
||||
/// <param name="path">图像文件路径</param>
|
||||
/// <param name="width">调整后的宽度</param>
|
||||
/// <param name="height">调整后的高度</param>
|
||||
/// <param name="interpolation">插值算法,默认为双线性插值(1)</param>
|
||||
/// <returns>调整尺寸后的Mat图像对象</returns>
|
||||
/// <remarks>
|
||||
/// 支持的插值算法:
|
||||
/// <list type="bullet">
|
||||
/// <item><description>最近邻插值 (0)</description></item>
|
||||
/// <item><description>双线性插值 (1) - 默认</description></item>
|
||||
/// <item><description>双三次插值 (2)</description></item>
|
||||
/// <item><description>像素区域关系重采样 (3)</description></item>
|
||||
/// <item><description>Lanczos插值 (4)</description></item>
|
||||
/// <item><description>精确双线性插值 (5)</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public Mat ReadImageMatWithResizeSync(string path, double width, double height, int interpolation = 1)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (width <= 0 || height <= 0)
|
||||
{
|
||||
throw new Exception("ReadImageMatWithResizeSync: 宽度和高度必须为正数");
|
||||
}
|
||||
|
||||
if (interpolation is < 0 or > 5)
|
||||
{
|
||||
throw new Exception($"ReadImageMatWithResizeSync: 不支持的插值算法 {interpolation}");
|
||||
}
|
||||
|
||||
path = NormalizePath(path);
|
||||
using var stream = File.OpenRead(path);
|
||||
using var mat = Mat.FromStream(stream, ImreadModes.Color);
|
||||
var rsz = new Mat();
|
||||
Cv2.Resize(mat, rsz, new Size(width, height), 0, 0, (InterpolationFlags)interpolation);
|
||||
return rsz;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回空的Mat
|
||||
TaskControl.Logger.LogError("ReadImageMatWithResizeSync 异常: {Message}", ex.Message);
|
||||
return new Mat();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 允许的文件扩展名白名单
|
||||
/// </summary>
|
||||
@@ -135,32 +272,41 @@ public class LimitedFile(string rootPath)
|
||||
/// <returns>是否合法</returns>
|
||||
private bool IsValid(string path, string? content = null)
|
||||
{
|
||||
// 验证文件扩展名
|
||||
string extension = Path.GetExtension(path).ToLower();
|
||||
if (!Array.Exists(_allowedExtensions, ext => ext == extension))
|
||||
try
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
var normalizedPath = NormalizePath(path);
|
||||
string? directoryPath = Path.GetDirectoryName(normalizedPath);
|
||||
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
// 如果提供了内容,验证内容是否合法
|
||||
if (content != null)
|
||||
{
|
||||
// 检查文件大小
|
||||
if (content.Length > MaxFileSize)
|
||||
// 验证文件扩展名
|
||||
string extension = Path.GetExtension(path).ToLower();
|
||||
if (!Array.Exists(_allowedExtensions, ext => ext == extension))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
var normalizedPath = NormalizePath(path);
|
||||
string? directoryPath = Path.GetDirectoryName(normalizedPath);
|
||||
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
// 如果提供了内容,验证内容是否合法
|
||||
if (content != null)
|
||||
{
|
||||
// 检查文件大小
|
||||
if (content.Length > MaxFileSize)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回 false
|
||||
TaskControl.Logger.LogError("IsValid 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -295,8 +441,10 @@ public class LimitedFile(string rootPath)
|
||||
Cv2.ImWrite(path, mat);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 记录异常并返回 false
|
||||
TaskControl.Logger.LogError("WriteImageSync 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -339,4 +487,51 @@ public class LimitedFile(string rootPath)
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重命名文件或文件夹(相对于根目录)
|
||||
/// </summary>
|
||||
/// <param name="oldPath">原路径</param>
|
||||
/// <param name="newPath">新路径</param>
|
||||
/// <returns>是否重命名成功</returns>
|
||||
public bool RenamePathSync(string oldPath, string newPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 标准化路径
|
||||
oldPath = NormalizePath(oldPath);
|
||||
newPath = NormalizePath(newPath);
|
||||
|
||||
// 检查原路径是否存在
|
||||
if (!File.Exists(oldPath) && !Directory.Exists(oldPath))
|
||||
{
|
||||
TaskControl.Logger.LogError("RenamePathSync 异常: 原路径不存在 {Path}", oldPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
//验证扩展名合法性
|
||||
if (File.Exists(oldPath) && !IsValid(newPath))
|
||||
{
|
||||
TaskControl.Logger.LogError("RenamePathSync 异常: 新文件路径不合法 {Path}", newPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确保目标目录存在
|
||||
string? directoryPath = Path.GetDirectoryName(newPath);
|
||||
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
// 执行重命名
|
||||
Directory.Move(oldPath, newPath);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskControl.Logger.LogError("RenamePathSync 异常: {Message}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
|
||||
@@ -40,5 +42,16 @@ public class RealtimeTimer
|
||||
{
|
||||
Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
|
||||
}
|
||||
else if (Name == "AutoSkip")
|
||||
{
|
||||
if (config is AutoSkipConfig)
|
||||
{
|
||||
Config = config;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("AutoSkip的配置参数需要为AutoSkipConfig类型");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,21 @@
|
||||
using BetterGenshinImpact.Core.Script.Dependence;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.Core.Script.Dependence;
|
||||
using BetterGenshinImpact.Core.Script.Dependence.Model;
|
||||
using Microsoft.ClearScript;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.BgiVision;
|
||||
using OpenCvSharp;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Script.Utils;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip;
|
||||
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script;
|
||||
|
||||
@@ -30,12 +37,14 @@ public class EngineExtend
|
||||
engine.AddHostObject("genshin", new Dependence.Genshin());
|
||||
engine.AddHostObject("log", new Log());
|
||||
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
|
||||
engine.AddHostObject("http", new Http()); // 限制文件访问
|
||||
engine.AddHostObject("notification", new Notification());
|
||||
|
||||
|
||||
// 任务调度器
|
||||
engine.AddHostObject("dispatcher", new Dispatcher(config));
|
||||
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
|
||||
engine.AddHostType("SoloTask", typeof(SoloTask));
|
||||
engine.AddHostType("AutoSkipConfig", typeof(AutoSkipConfig));
|
||||
|
||||
// 添加取消令牌相关类型
|
||||
engine.AddHostType("CancellationTokenSource", typeof(CancellationTokenSource));
|
||||
@@ -64,18 +73,46 @@ public class EngineExtend
|
||||
|
||||
engine.AddHostType("ServerTime", typeof(ServerTime));
|
||||
|
||||
|
||||
|
||||
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
|
||||
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
|
||||
engine.AddHostType("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
|
||||
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
|
||||
//鼠标回调
|
||||
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
|
||||
// 添加C#的类型
|
||||
engine.AddHostType(typeof(Task));
|
||||
|
||||
// 新的BvPage类
|
||||
engine.AddHostType("BvPage", typeof(BvPage));
|
||||
engine.AddHostType("BvLocator", typeof(BvLocator));
|
||||
engine.AddHostType("BvImage", typeof(BvImage));
|
||||
|
||||
// 导入 CommonJS 模块
|
||||
engine.AddHostObject("host", new CustomHostFunctions());
|
||||
|
||||
// 导入 JavaScript 模块
|
||||
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
|
||||
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
|
||||
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
|
||||
if (searchPaths != null)
|
||||
{
|
||||
engine.DocumentSettings.SearchPath = string.Join(';', searchPaths);
|
||||
var normalizedPaths = new List<string>();
|
||||
foreach (var path in searchPaths)
|
||||
{
|
||||
try
|
||||
{
|
||||
var normalizedPath = ScriptUtils.NormalizePath(workDir, path);
|
||||
normalizedPaths.Add(normalizedPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"从 library 字段读取路径 '{path}' 失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedPaths.Count > 0)
|
||||
{
|
||||
engine.DocumentSettings.SearchPath = string.Join(';', normalizedPaths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,10 +130,12 @@ public class EngineExtend
|
||||
|
||||
#pragma warning disable CS8974 // Converting method group to non-delegate type
|
||||
engine.AddHostObject("sleep", GlobalMethod.Sleep);
|
||||
engine.AddHostObject("getVersion", GlobalMethod.GetVersion);
|
||||
engine.AddHostObject("keyDown", GlobalMethod.KeyDown);
|
||||
engine.AddHostObject("keyUp", GlobalMethod.KeyUp);
|
||||
engine.AddHostObject("keyPress", GlobalMethod.KeyPress);
|
||||
engine.AddHostObject("setGameMetrics", GlobalMethod.SetGameMetrics);
|
||||
engine.AddHostObject("getGameMetrics", GlobalMethod.GetGameMetrics);
|
||||
engine.AddHostObject("moveMouseBy", GlobalMethod.MoveMouseBy);
|
||||
engine.AddHostObject("moveMouseTo", GlobalMethod.MoveMouseTo);
|
||||
engine.AddHostObject("click", GlobalMethod.Click);
|
||||
@@ -115,4 +154,4 @@ public class EngineExtend
|
||||
engine.AddHostObject("inputText", GlobalMethod.InputText);
|
||||
#pragma warning restore CS8974 // Converting method group to non-delegate type
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,22 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool? _allowJsNotification = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _allowJsHTTPHash = "";
|
||||
|
||||
/// <summary>
|
||||
/// 是否允许JS脚本发送HTTP请求,通过验证Hash来控制
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public bool AllowJsHTTP
|
||||
{
|
||||
get
|
||||
{
|
||||
return GetHttpAllowedUrlsHash() == AllowJsHTTPHash;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public ScriptGroupProject()
|
||||
{
|
||||
}
|
||||
@@ -163,6 +179,19 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
Project = new ScriptProject(FolderName);
|
||||
}
|
||||
|
||||
public string GetHttpAllowedUrlsHash()
|
||||
{
|
||||
if (Project == null)
|
||||
{
|
||||
BuildScriptProjectRelation();
|
||||
}
|
||||
if (Project == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return string.Join("|", Project.Manifest.HttpAllowedUrls);
|
||||
}
|
||||
|
||||
public async Task Run()
|
||||
{
|
||||
//执行记录
|
||||
@@ -187,6 +216,9 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
}
|
||||
JsScriptSettingsObject ??= new ExpandoObject();
|
||||
|
||||
// 清理配置中的无效值
|
||||
CleanInvalidSettingsValues();
|
||||
|
||||
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
|
||||
await Project.ExecuteAsync(JsScriptSettingsObject, pathingPartyConfig);
|
||||
}
|
||||
@@ -307,6 +339,67 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
{
|
||||
OnPropertyChanged(nameof(ScheduleDesc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理 JsScriptSettingsObject 中不在 settings.json 定义的 Options 列表中的无效值
|
||||
/// </summary>
|
||||
private void CleanInvalidSettingsValues()
|
||||
{
|
||||
if (Project == null || JsScriptSettingsObject == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 加载 settings.json 中定义的配置项
|
||||
var settingItems = Project.Manifest.LoadSettingItems(Project.ProjectPath);
|
||||
if (settingItems.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var settingsDict = JsScriptSettingsObject as IDictionary<string, object?>;
|
||||
if (settingsDict == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 遍历所有 multi-checkbox 类型的配置项
|
||||
foreach (var item in settingItems.Where(i => i.Type == "multi-checkbox"))
|
||||
{
|
||||
if (!settingsDict.ContainsKey(item.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// 获取当前保存的值
|
||||
var savedValue = settingsDict[item.Name];
|
||||
List<string>? checkedValues = null;
|
||||
|
||||
if (savedValue is List<string> stringList)
|
||||
{
|
||||
checkedValues = stringList;
|
||||
}
|
||||
else if (savedValue is List<object> objectList)
|
||||
{
|
||||
checkedValues = objectList.Select(i => (string)i).ToList();
|
||||
settingsDict[item.Name] = checkedValues;
|
||||
}
|
||||
|
||||
// 清理不在 Options 列表中的无效值
|
||||
if (checkedValues != null && item.Options != null)
|
||||
{
|
||||
checkedValues.RemoveAll(value => !item.Options.Contains(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 清理失败不影响脚本执行,只记录日志
|
||||
TaskControl.Logger.LogDebug(ex, "清理JS脚本配置中的无效值时发生异常");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ScriptGroupProjectExtensions
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.ClearScript.JavaScript;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script
|
||||
{
|
||||
public class PackageDocumentLoader : DocumentLoader
|
||||
{
|
||||
private readonly string _scriptRootPath;
|
||||
|
||||
public PackageDocumentLoader(string scriptRootPath)
|
||||
{
|
||||
_scriptRootPath = Path.GetFullPath(scriptRootPath);
|
||||
}
|
||||
|
||||
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
|
||||
{
|
||||
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
|
||||
|
||||
if (targetPath == null || !File.Exists(targetPath))
|
||||
{
|
||||
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
|
||||
}
|
||||
|
||||
// 处理 JS 文件的重写
|
||||
if (Path.GetExtension(targetPath).ToLower() == ".js")
|
||||
{
|
||||
string content = await File.ReadAllTextAsync(targetPath);
|
||||
string processedCode = RewriteScriptCode(content, targetPath);
|
||||
return new StringDocument(new DocumentInfo(targetPath) { Category = ModuleCategory.Standard }, processedCode);
|
||||
}
|
||||
|
||||
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// js重写
|
||||
/// </summary>
|
||||
public string RewriteScriptCode(string code, string currentFilePath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(code)) return code;
|
||||
|
||||
string result = code.Replace("../../../packages", "packages");
|
||||
|
||||
// 拦截资源导入
|
||||
var resourceRegex = new Regex(@"import\s+([\w\d_*$]+|[\s\S]*?)\s+from\s+(['""])([^'""\n]+)(['""])");
|
||||
result = resourceRegex.Replace(result, match =>
|
||||
{
|
||||
string importPart = match.Groups[1].Value.Trim();
|
||||
string quote = match.Groups[2].Value;
|
||||
string rawPath = match.Groups[3].Value;
|
||||
|
||||
string path = rawPath.Replace("../../../packages", "packages");
|
||||
string? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
|
||||
|
||||
if (resourceFullPath != null && File.Exists(resourceFullPath))
|
||||
{
|
||||
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
|
||||
bool isJs = resourceFullPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase);
|
||||
bool isImage = IsImageFile(resourceFullPath);
|
||||
|
||||
// 图片 -> Mat
|
||||
if (isImage)
|
||||
{
|
||||
if (importPart.StartsWith("{")) return match.Value;
|
||||
return $"const {importPart} = file.ReadImageMatSync({quote}{normalizedPath}{quote});";
|
||||
}
|
||||
|
||||
// 非 JS 资源 -> 文本内容
|
||||
if (!isJs)
|
||||
{
|
||||
if (importPart.StartsWith("{")) return match.Value;
|
||||
return $"const {importPart} = file.ReadTextSync({quote}{normalizedPath}{quote});";
|
||||
}
|
||||
}
|
||||
|
||||
return match.Value;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
|
||||
{
|
||||
return ResolvePathInternal(settings.SearchPath, sourceInfo?.Name, specifier);
|
||||
}
|
||||
|
||||
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
|
||||
{
|
||||
if (specifier.StartsWith("packages/", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
|
||||
}
|
||||
|
||||
if (specifier.StartsWith("."))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(referrer))
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(referrer);
|
||||
if (dir != null)
|
||||
{
|
||||
return ProbeFile(Path.GetFullPath(Path.Combine(dir, specifier)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(searchPath))
|
||||
{
|
||||
var paths = searchPath.Split(';', StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (var p in paths)
|
||||
{
|
||||
string combined = Path.Combine(p, specifier);
|
||||
string? found = ProbeFile(combined);
|
||||
if (found != null) return found;
|
||||
}
|
||||
}
|
||||
|
||||
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
|
||||
}
|
||||
|
||||
private string? ProbeFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) return path;
|
||||
if (File.Exists(path + ".js")) return path + ".js";
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsImageFile(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path)) return false;
|
||||
string ext = Path.GetExtension(path).ToLower();
|
||||
string[] imageExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp" };
|
||||
return imageExtensions.Contains(ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ public class Manifest
|
||||
public string[] Scripts { get; set; } = [];
|
||||
public string[] Library { get; set; } = [];
|
||||
public string[] SavedFiles { get; set; } = [];
|
||||
public string[] HttpAllowedUrls { get; set; } = [];
|
||||
|
||||
public static Manifest FromJson(string json)
|
||||
{
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.ClearScript.V8;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using BetterGenshinImpact.Core.Script.Dependence;
|
||||
using Microsoft.ClearScript.JavaScript;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Project;
|
||||
|
||||
@@ -68,10 +71,24 @@ public class ScriptProject
|
||||
return scrollViewer;
|
||||
}
|
||||
|
||||
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
|
||||
private IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig)
|
||||
{
|
||||
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
|
||||
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
|
||||
V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
|
||||
|
||||
// packages 依赖和资源重载
|
||||
var loader = new PackageDocumentLoader(ProjectPath);
|
||||
engine.DocumentSettings.Loader = loader;
|
||||
|
||||
// 添加 packages 到搜索路径
|
||||
var libraries = new HashSet<string>(Manifest.Library ?? Array.Empty<string>())
|
||||
{
|
||||
".",
|
||||
"./packages"
|
||||
};
|
||||
|
||||
var libraryList = libraries.ToList();
|
||||
|
||||
EngineExtend.InitHost(engine, ProjectPath, libraryList.ToArray(), partyConfig);
|
||||
return engine;
|
||||
}
|
||||
|
||||
@@ -82,6 +99,10 @@ public class ScriptProject
|
||||
// 加载代码
|
||||
var code = await LoadCode();
|
||||
var engine = BuildScriptEngine(partyConfig);
|
||||
|
||||
// 使用自定义加载器解析脚本文件
|
||||
var loader = (PackageDocumentLoader)engine.DocumentSettings.Loader;
|
||||
|
||||
if (context != null)
|
||||
{
|
||||
// 写入配置的内容
|
||||
@@ -89,7 +110,26 @@ public class ScriptProject
|
||||
}
|
||||
try
|
||||
{
|
||||
await (Task)engine.Evaluate(code);
|
||||
bool useModule = Manifest.Library.Length != 0 ||
|
||||
code.Contains("import ", StringComparison.Ordinal) ||
|
||||
code.Contains("export ", StringComparison.Ordinal);
|
||||
|
||||
if (useModule)
|
||||
{
|
||||
// 清除Document缓存
|
||||
DocumentLoader.Default.DiscardCachedDocuments();
|
||||
|
||||
string mainScriptPath = Path.Combine(ProjectPath, Manifest.Main);
|
||||
string runtimeCode = loader.RewriteScriptCode(code, mainScriptPath);
|
||||
|
||||
var evaluation = engine.Evaluate(new DocumentInfo(mainScriptPath) { Category = ModuleCategory.Standard }, runtimeCode);
|
||||
if (evaluation is Task task) await task;
|
||||
}
|
||||
else
|
||||
{
|
||||
var evaluation = engine.Evaluate(code);
|
||||
if (evaluation is Task task) await task;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Utils;
|
||||
|
||||
@@ -10,17 +11,30 @@ public class ScriptUtils
|
||||
/// </summary>
|
||||
public static string NormalizePath(string root, string path)
|
||||
{
|
||||
// convert to full path relative to root
|
||||
path = path.Replace('\\', '/');
|
||||
var fullPath = Path.GetFullPath(Path.Combine(root, path));
|
||||
// 校验空字符串
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
throw new ArgumentException("文件路径不能为空");
|
||||
|
||||
// if root is locked, make sure didn't attempt to exit it
|
||||
if (!fullPath.StartsWith(root))
|
||||
// 检查是否含有非法文件名字符
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
string fileName = Path.GetFileName(path);
|
||||
if (fileName.Any(c => invalidChars.Contains(c)))
|
||||
{
|
||||
throw new ArgumentException($"Path '{path}' is not allowed, because its outside the caged root folder!");
|
||||
throw new ArgumentException($"文件路径 '{path}' 包含非法字符");
|
||||
}
|
||||
|
||||
// 替换分隔符
|
||||
path = path.Replace('\\', '/');
|
||||
|
||||
// 组合并获取绝对路径
|
||||
var fullPath = Path.GetFullPath(Path.Combine(root, path));
|
||||
|
||||
// 防止越界访问
|
||||
if (!fullPath.StartsWith(root, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException($"文件路径 '{path}' 越界访问!");
|
||||
}
|
||||
|
||||
// return full path
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,12 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.View.Windows;
|
||||
using BetterGenshinImpact.ViewModel.Message;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Net;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.WebView;
|
||||
|
||||
@@ -24,7 +27,12 @@ public sealed class RepoWebBridge
|
||||
".vue", ".css", ".html", ".csv", ".xml",
|
||||
".yaml", ".yml", ".ini", ".config"
|
||||
};
|
||||
|
||||
|
||||
private static readonly HashSet<string> AllowedImageExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico"
|
||||
};
|
||||
|
||||
public async Task<string> GetRepoJson()
|
||||
{
|
||||
try
|
||||
@@ -39,7 +47,7 @@ public sealed class RepoWebBridge
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await MessageBox.ShowAsync(ex.Message, "获取仓库信息失败");
|
||||
await ThemedMessageBox.ErrorAsync(ex.Message, "获取仓库信息失败");
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -53,7 +61,7 @@ public sealed class RepoWebBridge
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
await MessageBox.ShowAsync(e.Message, "订阅脚本链接失败!");
|
||||
await ThemedMessageBox.ErrorAsync(e.Message, "订阅脚本链接失败!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,36 +71,97 @@ public sealed class RepoWebBridge
|
||||
|
||||
if (!File.Exists(userConfigPath))
|
||||
{
|
||||
await MessageBox.ShowAsync($"用户配置文件不存在: {userConfigPath}", "获取用户配置失败");
|
||||
await ThemedMessageBox.ErrorAsync($"用户配置文件不存在: {userConfigPath}", "获取用户配置失败");
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return await File.ReadAllTextAsync(userConfigPath);
|
||||
}
|
||||
|
||||
public async Task<string> GetFile(string relPath)
|
||||
/// <summary>
|
||||
/// 获取当前仓库的已订阅脚本路径列表(JSON 数组)。
|
||||
/// 相比 GetUserConfigJson() 更轻量,仅返回当前仓库的订阅路径。
|
||||
/// </summary>
|
||||
public string GetSubscribedScriptPaths()
|
||||
{
|
||||
try
|
||||
{
|
||||
string filePath = Path.Combine(ScriptRepoUpdater.CenterRepoPath, "repo", relPath)
|
||||
.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
var paths = ScriptRepoUpdater.GetSubscribedPathsForCurrentRepo();
|
||||
if (paths.Count > 0)
|
||||
{
|
||||
return "404";
|
||||
return Newtonsoft.Json.JsonConvert.SerializeObject(paths);
|
||||
}
|
||||
|
||||
string extension = Path.GetExtension(filePath);
|
||||
return AllowedTextExtensions.Contains(extension)
|
||||
? await File.ReadAllTextAsync(filePath)
|
||||
: "404";
|
||||
return "[]";
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "404";
|
||||
return "[]";
|
||||
}
|
||||
}
|
||||
|
||||
public Task<string> GetFile(string relPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
// URL 解码路径(处理中文文件名)
|
||||
relPath = WebUtility.UrlDecode(relPath);
|
||||
|
||||
string filePath = Path.Combine(ScriptRepoUpdater.CenterRepoPath, "repo", relPath)
|
||||
.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
|
||||
|
||||
// 验证解析后的路径在允许的目录范围内
|
||||
string normalizedBasePath = Path.GetFullPath(Path.Combine(ScriptRepoUpdater.CenterRepoPath, "repo"));
|
||||
string normalizedFilePath = Path.GetFullPath(filePath);
|
||||
if (!normalizedFilePath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Task.FromResult("404");
|
||||
}
|
||||
|
||||
string extension = Path.GetExtension(filePath).ToLower();
|
||||
|
||||
if (AllowedTextExtensions.Contains(extension))
|
||||
{
|
||||
// 读取文本文件
|
||||
string? content = ScriptRepoUpdater.Instance.ReadFileFromCenterRepo(relPath);
|
||||
return Task.FromResult(string.IsNullOrEmpty(content) ? "404" : content);
|
||||
}
|
||||
else if (AllowedImageExtensions.Contains(extension))
|
||||
{
|
||||
// 读取图片文件,返回 Base64 编码
|
||||
byte[]? bytes = ScriptRepoUpdater.Instance.ReadBinaryFileFromCenterRepo(relPath);
|
||||
if (bytes == null || bytes.Length == 0)
|
||||
{
|
||||
return Task.FromResult("404");
|
||||
}
|
||||
|
||||
string base64 = Convert.ToBase64String(bytes);
|
||||
return Task.FromResult(base64);
|
||||
}
|
||||
|
||||
return Task.FromResult("404");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Task.FromResult("404");
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetMimeType(string extension)
|
||||
{
|
||||
return extension.ToLower() switch
|
||||
{
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".gif" => "image/gif",
|
||||
".bmp" => "image/bmp",
|
||||
".webp" => "image/webp",
|
||||
".svg" => "image/svg+xml",
|
||||
".ico" => "image/x-icon",
|
||||
_ => "application/octet-stream"
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateSubscribed(string path)
|
||||
{
|
||||
try
|
||||
@@ -118,7 +187,7 @@ public sealed class RepoWebBridge
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await MessageBox.ShowAsync(ex.Message, "信息更新失败");
|
||||
await ThemedMessageBox.ErrorAsync(ex.Message, "信息更新失败");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -136,7 +205,7 @@ public sealed class RepoWebBridge
|
||||
throw new FileNotFoundException("找不到原始 repo.json 文件");
|
||||
}
|
||||
|
||||
string targetPath = Path.Combine(ScriptRepoUpdater.ReposPath, "repo_updated.json");
|
||||
string targetPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
|
||||
|
||||
File.Copy(repoJsonPath, targetPath, overwrite: true);
|
||||
|
||||
@@ -144,17 +213,44 @@ public sealed class RepoWebBridge
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await MessageBox.ShowAsync($"清空更新标记失败: {ex.Message}", "操作失败");
|
||||
await ThemedMessageBox.ErrorAsync($"清空更新标记失败: {ex.Message}", "操作失败");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新手引导标志位
|
||||
public bool SetGuideStatus(bool status)
|
||||
{
|
||||
try
|
||||
{
|
||||
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
|
||||
scriptConfig.GuideStatus = status;
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取新手引导标志位
|
||||
public bool GetGuideStatus()
|
||||
{
|
||||
try
|
||||
{
|
||||
return TaskContext.Instance().Config.ScriptConfig.GuideStatus;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetRepoJsonPath()
|
||||
{
|
||||
string updatedRepoJsonPath = Path.Combine(
|
||||
Path.GetDirectoryName(Path.Combine(ScriptRepoUpdater.ReposPath, "bettergi-scripts-list-git"))!,
|
||||
"repo_updated.json"
|
||||
);
|
||||
string updatedRepoJsonPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
|
||||
|
||||
if (File.Exists(updatedRepoJsonPath))
|
||||
{
|
||||
@@ -168,7 +264,7 @@ public sealed class RepoWebBridge
|
||||
return repoJson ?? throw new FileNotFoundException("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
|
||||
}
|
||||
|
||||
private static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
|
||||
internal static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
|
||||
{
|
||||
foreach (JObject item in array.OfType<JObject>())
|
||||
{
|
||||
@@ -186,7 +282,7 @@ public sealed class RepoWebBridge
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResetHasUpdateFlag(JObject node)
|
||||
internal static void ResetHasUpdateFlag(JObject node)
|
||||
{
|
||||
if (node["hasUpdate"] is { Type: JTokenType.Boolean } hasUpdate &&
|
||||
(bool)hasUpdate)
|
||||
|
||||
@@ -6,16 +6,16 @@ namespace BetterGenshinImpact.GameTask.AutoArtifactSalvage
|
||||
/// <summary>
|
||||
/// 圣遗物词条
|
||||
/// </summary>
|
||||
public class ArtifactAffix
|
||||
public class ArtifactAffix(ArtifactAffixType type, float value, bool isUnactivated)
|
||||
{
|
||||
public ArtifactAffix(ArtifactAffixType type, float value)
|
||||
public ArtifactAffix(ArtifactAffixType type, float value) : this(type, value, false)
|
||||
{
|
||||
Type = type;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public ArtifactAffixType Type { get; private set; }
|
||||
public float Value { get; private set; }
|
||||
public ArtifactAffixType Type { get; private set; } = type;
|
||||
public float Value { get; private set; } = value;
|
||||
public bool IsUnactivated { get; private set; } = isUnactivated;
|
||||
|
||||
public static FrozenDictionary<ArtifactAffixType, string> DefaultStrDic { get; } = new Dictionary<ArtifactAffixType, string>() {
|
||||
{ ArtifactAffixType.ATK, "攻击力" },
|
||||
{ ArtifactAffixType.ATKPercent, "攻击力" },
|
||||
|
||||
@@ -50,7 +50,11 @@ namespace BetterGenshinImpact.GameTask.AutoArtifactSalvage
|
||||
sb.Append("├─").Append("MinorAffixes: ").Append('\n');
|
||||
for (int i = 0; i < this.MinorAffixes.Length; i++)
|
||||
{
|
||||
sb.Append('│').Append('\t').Append(i == this.MinorAffixes.Length - 1 ? "└─" : "├─").Append($"[{i}]: ").Append(this.MinorAffixes[i].Type).Append(", ").Append(this.MinorAffixes[i].Value).Append('\n');
|
||||
sb.Append('│').Append('\t').Append(i == this.MinorAffixes.Length - 1 ? "└─" : "├─").Append($"[{i}]: ").Append(this.MinorAffixes[i].Type).Append(", ").Append(this.MinorAffixes[i].Value);
|
||||
if (this.MinorAffixes[i].IsUnactivated) {
|
||||
sb.Append(", Unactivated");
|
||||
}
|
||||
sb.Append('\n');
|
||||
}
|
||||
sb.Append("└─").Append("Level: ").Append(this.Level);
|
||||
return sb.ToString();
|
||||
|
||||
@@ -8,11 +8,10 @@ public partial class AutoArtifactSalvageConfig : ObservableObject
|
||||
{
|
||||
// JavaScript
|
||||
[ObservableProperty]
|
||||
private string _javaScript = @"(async function (artifact) {
|
||||
var hasATK = Array.from(artifact.MinorAffixes).some(affix => affix.Type == 'ATK');
|
||||
var hasDEF = Array.from(artifact.MinorAffixes).some(affix => affix.Type == 'DEF');
|
||||
Output = hasATK && hasDEF;
|
||||
})(ArtifactStat);";
|
||||
private string _javaScript = @"var hasATK = Array.from(ArtifactStat.MinorAffixes).some(affix => affix.Type == 'ATK');
|
||||
var hasDEF = Array.from(ArtifactStat.MinorAffixes).some(affix => affix.Type == 'DEF');
|
||||
var hasHP = Array.from(ArtifactStat.MinorAffixes).some(affix => affix.Type == 'HP');
|
||||
Output = (hasATK && hasDEF) || (hasHP && hasDEF);";
|
||||
|
||||
// JavaScript
|
||||
[ObservableProperty]
|
||||
@@ -32,7 +31,7 @@ public partial class AutoArtifactSalvageConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _maxNumToCheck = 100;
|
||||
|
||||
// 单次识别失败政策
|
||||
// 单次识别失败策略
|
||||
[ObservableProperty]
|
||||
private RecognitionFailurePolicy _recognitionFailurePolicy = RecognitionFailurePolicy.Skip;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.GameTask.Model.GameUI;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.ClearScript.V8;
|
||||
@@ -303,21 +304,49 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
quickSelectConfirmBtn.Click();
|
||||
await Delay(400, ct);
|
||||
// 点击所属套装
|
||||
ra5.ClickTo(315, 205);
|
||||
ra5.ClickTo(315, 190);
|
||||
await Delay(1000, ct);
|
||||
// 遍历套装Grid勾选套装
|
||||
using InferenceSession session = GridIconsAccuracyTestTask.LoadModel(out Dictionary<string, float[]> prototypes);
|
||||
ArtifactSetFilterScreen gridScreen = new ArtifactSetFilterScreen(new GridParams(new Rect(40, 100, 1300, 852), 2, 3, 40, 40, 0.024), this.logger, this.ct);
|
||||
await foreach (ImageRegion itemRegion in gridScreen)
|
||||
string drawKey = "ArtifactSetFilter";
|
||||
var drawRectList = new List<RectDrawable>();
|
||||
var drawTextList = new List<TextDrawable>();
|
||||
gridScreen.OnBeforeScroll += () => { VisionContext.Instance().DrawContent.RemoveRect(drawKey); drawRectList.Clear(); drawTextList.Clear(); };
|
||||
try
|
||||
{
|
||||
using Mat img125 = GetGridIconsTask.CropResizeArtifactSetFilterGridIcon(itemRegion);
|
||||
(string predName, _) = GridIconsAccuracyTestTask.Infer(img125, session, prototypes);
|
||||
if (this.artifactSetFilter.Contains(predName))
|
||||
await foreach ((ImageRegion pageRegion, Rect itemRect) in gridScreen)
|
||||
{
|
||||
itemRegion.Click();
|
||||
await Delay(100, ct);
|
||||
using ImageRegion itemRegion = pageRegion.DeriveCrop(itemRect);
|
||||
using Mat img125 = GetGridIconsTask.CropResizeArtifactSetFilterGridIcon(itemRegion);
|
||||
(string? predName, _) = GridIconsAccuracyTestTask.Infer(img125, session, prototypes);
|
||||
if (predName == null)
|
||||
{
|
||||
var rectDrawable = itemRegion.SelfToRectDrawable(drawKey);
|
||||
drawRectList.Add(rectDrawable);
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(drawKey, drawRectList);
|
||||
drawTextList.Add(new TextDrawable("识别失败", new System.Windows.Point(rectDrawable.Rect.X + rectDrawable.Rect.Width / 3, rectDrawable.Rect.Y)));
|
||||
VisionContext.Instance().DrawContent.TextList.GetOrAdd(drawKey, drawTextList);
|
||||
}
|
||||
else
|
||||
{
|
||||
var rectDrawable = itemRegion.SelfToRectDrawable(drawKey, System.Drawing.Pens.Lime);
|
||||
drawRectList.Add(rectDrawable);
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(drawKey, drawRectList);
|
||||
drawTextList.Add(new TextDrawable(predName, new System.Windows.Point(rectDrawable.Rect.X + rectDrawable.Rect.Width / 3, rectDrawable.Rect.Y)));
|
||||
VisionContext.Instance().DrawContent.TextList.GetOrAdd(drawKey, drawTextList);
|
||||
if (this.artifactSetFilter.Contains(predName))
|
||||
{
|
||||
itemRegion.Click();
|
||||
await Delay(100, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
}
|
||||
// 点击确认筛选
|
||||
using var confirmFilterBtnRegion = CaptureToRectArea();
|
||||
Bv.ClickWhiteConfirmButton(confirmFilterBtnRegion);
|
||||
@@ -351,60 +380,70 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
|
||||
GridParams gridParams = GridParams.Templates[GridScreenName.ArtifactSalvage];
|
||||
GridScreen gridScreen = new GridScreen(gridParams, this.logger, this.ct); // 圣遗物分解Grid有4行9列
|
||||
await foreach (ImageRegion itemRegion in gridScreen)
|
||||
gridScreen.OnAfterTurnToNewPage += GridScreen.DrawItemsAfterTurnToNewPage;
|
||||
gridScreen.OnBeforeScroll += () => VisionContext.Instance().DrawContent.ClearAll();
|
||||
try
|
||||
{
|
||||
Rect gridRect = itemRegion.ToRect();
|
||||
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
|
||||
await foreach ((ImageRegion pageRegion, Rect itemRect) in gridScreen)
|
||||
{
|
||||
itemRegion.Click();
|
||||
await Delay(300, ct);
|
||||
|
||||
using var ra1 = CaptureToRectArea();
|
||||
using ImageRegion itemRegion1 = ra1.DeriveCrop(gridRect + new Point(gridParams.Roi.X, gridParams.Roi.Y));
|
||||
if (GetArtifactStatus(itemRegion1.SrcMat) == ArtifactStatus.Selected)
|
||||
using ImageRegion itemRegion = pageRegion.DeriveCrop(itemRect);
|
||||
Rect gridRect = itemRegion.ToRect();
|
||||
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
|
||||
{
|
||||
using ImageRegion card = ra1.DeriveCrop(new Rect((int)(ra1.Width * 0.70), (int)(ra1.Height * 0.112), (int)(ra1.Width * 0.275), (int)(ra1.Height * 0.50)));
|
||||
itemRegion.Click();
|
||||
await Delay(300, ct);
|
||||
|
||||
ArtifactStat artifact;
|
||||
try
|
||||
using var ra1 = CaptureToRectArea();
|
||||
using ImageRegion itemRegion1 = ra1.DeriveCrop(gridRect + new Point(gridParams.Roi.X, gridParams.Roi.Y));
|
||||
if (GetArtifactStatus(itemRegion1.SrcMat) == ArtifactStatus.Selected)
|
||||
{
|
||||
artifact = GetArtifactStat(card.SrcMat, OcrFactory.Paddle, out string allText);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (recognitionFailurePolicy == RecognitionFailurePolicy.Skip)
|
||||
using ImageRegion card = ra1.DeriveCrop(new Rect((int)(ra1.Width * 0.70), (int)(ra1.Height * 0.112), (int)(ra1.Width * 0.275), (int)(ra1.Height * 0.50)));
|
||||
|
||||
ArtifactStat artifact;
|
||||
try
|
||||
{
|
||||
logger.LogError("识别失败,跳过当前圣遗物:{msg}", e.Message);
|
||||
artifact = GetArtifactStat(card.SrcMat, OcrFactory.Paddle, out string allText);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (recognitionFailurePolicy == RecognitionFailurePolicy.Skip)
|
||||
{
|
||||
logger.LogError("识别失败,跳过当前圣遗物:{msg}", e.Message);
|
||||
|
||||
itemRegion.Click(); // 反选取消
|
||||
await Delay(100, ct);
|
||||
continue;
|
||||
itemRegion.Click(); // 反选取消
|
||||
await Delay(100, ct);
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (await IsMatchJavaScript(artifact, javaScript))
|
||||
{
|
||||
// logger.LogInformation(message: msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
itemRegion.Click(); // 反选取消
|
||||
await Delay(100, ct);
|
||||
}
|
||||
}
|
||||
|
||||
if (IsMatchJavaScript(artifact, javaScript))
|
||||
count--;
|
||||
if (count <= 0)
|
||||
{
|
||||
// logger.LogInformation(message: msg);
|
||||
logger.LogInformation("检查次数已耗尽");
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
itemRegion.Click(); // 反选取消
|
||||
await Delay(100, ct);
|
||||
}
|
||||
}
|
||||
|
||||
count--;
|
||||
if (count <= 0)
|
||||
{
|
||||
logger.LogInformation("检查次数已耗尽");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -412,20 +451,33 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
/// </summary>
|
||||
/// <param name="artifact">作为JS入参,JS使用“ArtifactStat”获取</param>
|
||||
/// <param name="javaScript"></param>
|
||||
/// <param name="engine">由调用者控制生命周期</param>
|
||||
/// <param name="cts">为空则默认创建一个3秒延迟的cts</param>
|
||||
/// <returns>是否匹配。取JS的“Output”作为出参</returns>
|
||||
/// <exception cref="InvalidOperationException"></exception>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public static bool IsMatchJavaScript(ArtifactStat artifact, string javaScript)
|
||||
public async static Task<bool> IsMatchJavaScript(ArtifactStat artifact, string javaScript, ILogger? logger = null, TimeProvider? timeProvider = null)
|
||||
{
|
||||
logger = logger ?? App.GetLogger<AutoArtifactSalvageTask>();
|
||||
using V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.DisableGlobalMembers);
|
||||
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3), timeProvider ?? TimeProvider.System); // 这里只是用JS写一个自定义判断方法,由于每个圣遗物都会执行一次,这个方法不应执行太久
|
||||
cts.Token.Register(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
engine.Interrupt();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"中断失败: {ex.Message}");
|
||||
}
|
||||
});
|
||||
try
|
||||
{
|
||||
// 传入输入参数
|
||||
engine.Script.ArtifactStat = artifact;
|
||||
|
||||
// 执行JavaScript代码
|
||||
engine.Execute(javaScript);
|
||||
await Task.Run(() => engine.Execute(javaScript));
|
||||
|
||||
// 检查是否有输出
|
||||
if (!engine.Script.propertyIsEnumerable("Output"))
|
||||
@@ -440,6 +492,11 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
|
||||
return (bool)engine.Script.Output;
|
||||
}
|
||||
catch (ScriptInterruptedException)
|
||||
{
|
||||
logger.LogWarning("脚本执行超出3秒限制,请使用正确的JS代码(JavaScript execution timeout!)");
|
||||
throw;
|
||||
}
|
||||
catch (ScriptEngineException ex)
|
||||
{
|
||||
throw new Exception($"JavaScript execution error: {ex.Message}", ex);
|
||||
@@ -471,25 +528,25 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
public ArtifactStat GetArtifactStat(Mat src, IOcrService ocrService, out string allText)
|
||||
{
|
||||
using Mat gray = src.CvtColor(ColorConversionCodes.BGR2GRAY);
|
||||
Mat hatKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(15, 15)/*需根据实际文本大小调整*/); // 顶帽运算核
|
||||
using Mat hatKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(15, 15)/*需根据实际文本大小调整*/); // 顶帽运算核
|
||||
|
||||
Mat nameRoi = gray.SubMat(new Rect(0, 0, src.Width, (int)(src.Height * 0.106)));
|
||||
using Mat nameRoi = gray.SubMat(new Rect(0, 0, src.Width, (int)(src.Height * 0.106)));
|
||||
//Cv2.ImShow("name", nameRoi);
|
||||
Mat typeRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.106), src.Width, (int)(src.Height * 0.106)));
|
||||
using Mat typeRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.106), src.Width, (int)(src.Height * 0.106)));
|
||||
#region 主词条预处理 去除背景干扰
|
||||
Mat mainAffixRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.22), (int)(src.Width * 0.55), (int)(src.Height * 0.30)));
|
||||
using Mat mainAffixRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.22), (int)(src.Width * 0.55), (int)(src.Height * 0.30)));
|
||||
using Mat mainAffixRoiBottomHat = mainAffixRoi.MorphologyEx(MorphTypes.TopHat, hatKernel);
|
||||
using Mat mainAffixRoiThreshold = mainAffixRoiBottomHat.Threshold(30, 255, ThresholdTypes.Binary);
|
||||
//Cv2.ImShow("mainAffix", mainAffixRoiThreshold);
|
||||
#endregion
|
||||
#region 副词条预处理 还是不处理效果最好……
|
||||
Mat levelAndMinorAffixRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.52), src.Width, (int)(src.Height * 0.48)));
|
||||
//using Mat levelAndMinorAffixRoiThreshold = new Mat();
|
||||
using Mat levelAndMinorAffixRoi = gray.SubMat(new Rect(0, (int)(src.Height * 0.52), src.Width, (int)(src.Height * 0.48)));
|
||||
//using Mat levelAndMinorAffixRoiThreshold = new Mat(); // otsu确定阈值大概在170
|
||||
//double otsu = Cv2.Threshold(levelAndMinorAffixRoi, levelAndMinorAffixRoiThreshold, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
|
||||
// //using Mat levelAndMinorAffixRoiThreshold = levelAndMinorAffixRoi.Threshold(170, 255, ThresholdTypes.Binary);
|
||||
//Cv2.ImShow($"levelAndMinorAffixRoi = {otsu}", levelAndMinorAffixRoiThreshold);
|
||||
#endregion
|
||||
//Cv2.WaitKey();
|
||||
//using Mat levelAndMinorAffixRoiThreshold = levelAndMinorAffixRoi.Threshold(170, 255, ThresholdTypes.Binary);
|
||||
#endregion
|
||||
|
||||
var nameOcrResult = ocrService.OcrResult(nameRoi);
|
||||
var typeOcrResult = ocrService.OcrResult(typeRoi);
|
||||
@@ -497,12 +554,16 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
string mainAffixText = string.Join("\n", mainAffixOcrResult.Regions.Where(r => r.Score > 0.5).OrderBy(r => r.Rect.Center.Y).ThenBy(r => r.Rect.Center.X).Select(r => r.Text));
|
||||
var mainAffixLines = mainAffixText.Split('\n');
|
||||
var levelAndMinorAffixOcrResult = ocrService.OcrResult(levelAndMinorAffixRoi);
|
||||
string levelAndMinorAffixText = string.Join("\n", levelAndMinorAffixOcrResult.Regions.Where(r => r.Score > 0.5)
|
||||
(string Text, Rect Rect)[] levelAndMinorAffixResult = levelAndMinorAffixOcrResult.Regions.Where(r => r.Score > 0.5)
|
||||
.Where(r => r.Rect.BoundingRect().Left < levelAndMinorAffixRoi.Width * 0.1) // 一定是贴着左边的,排除套装效果文字也存在类似+15%的情况
|
||||
.OrderBy(r => r.Rect.Center.Y).ThenBy(r => r.Rect.Center.X).Select(r => r.Text));
|
||||
var levelAndMinorAffixLines = levelAndMinorAffixText.Split('\n');
|
||||
|
||||
allText = String.Join('\n', nameOcrResult.Text, typeOcrResult.Text, mainAffixText, levelAndMinorAffixText);
|
||||
.OrderBy(r => r.Rect.Center.Y).ThenBy(r => r.Rect.Center.X).Select(r => (r.Text, r.Rect.BoundingRect())).ToArray();
|
||||
var levelAndMinorAffixLines = levelAndMinorAffixResult.Select(r => r.Text).ToArray();
|
||||
allText = string.Join('\n', new[]
|
||||
{
|
||||
nameOcrResult.Text,
|
||||
typeOcrResult.Text,
|
||||
mainAffixText
|
||||
}.Concat(levelAndMinorAffixLines));
|
||||
|
||||
string percentStr = "%";
|
||||
|
||||
@@ -547,81 +608,112 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
#endregion
|
||||
|
||||
#region 副词条
|
||||
ArtifactAffix[] minorAffixes = levelAndMinorAffixLines.Select(l =>
|
||||
var minorAffixes = new List<ArtifactAffix>();
|
||||
string pattern = @"^([^+::]+)\+([\d., 。]*)(%?).*$";
|
||||
pattern = pattern.Replace("%", percentStr);
|
||||
foreach (var r in levelAndMinorAffixResult)
|
||||
{
|
||||
string pattern = @"^([^+::]+)\+([\d., ]*)(%?).*$";
|
||||
pattern = pattern.Replace("%", percentStr);
|
||||
Match match = Regex.Match(l, pattern);
|
||||
if (match.Success)
|
||||
Match match = Regex.Match(r.Text, pattern);
|
||||
if (!match.Success)
|
||||
{
|
||||
ArtifactAffixType artifactAffixType;
|
||||
var dic = this.artifactAffixStrDic;
|
||||
|
||||
if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.ATK]))
|
||||
continue;
|
||||
}
|
||||
ArtifactAffixType artifactAffixType;
|
||||
var dic = this.artifactAffixStrDic;
|
||||
if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.ATK]))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.ATK;
|
||||
}
|
||||
else
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.ATKPercent;
|
||||
}
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.DEF]))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.DEF;
|
||||
}
|
||||
else
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.DEFPercent;
|
||||
}
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.HP]))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.HP;
|
||||
}
|
||||
else
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.HPPercent;
|
||||
}
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.CRITRate]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.CRITRate;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.CRITDMG]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.CRITDMG;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.ElementalMastery]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.ElementalMastery;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.EnergyRecharge]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.EnergyRecharge;
|
||||
artifactAffixType = ArtifactAffixType.ATK;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"未识别的副词条:{match.Groups[1].Value}");
|
||||
artifactAffixType = ArtifactAffixType.ATKPercent;
|
||||
}
|
||||
|
||||
if (!float.TryParse(match.Groups[2].Value, NumberStyles.Any, cultureInfo, out float value))
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.DEF]))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
throw new Exception($"未识别的副词条数值:{match.Groups[2].Value}");
|
||||
artifactAffixType = ArtifactAffixType.DEF;
|
||||
}
|
||||
return new ArtifactAffix(artifactAffixType, value);
|
||||
else
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.DEFPercent;
|
||||
}
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.HP]))
|
||||
{
|
||||
if (String.IsNullOrEmpty(match.Groups[3].Value))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.HP;
|
||||
}
|
||||
else
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.HPPercent;
|
||||
}
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.CRITRate]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.CRITRate;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.CRITDMG]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.CRITDMG;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.ElementalMastery]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.ElementalMastery;
|
||||
}
|
||||
else if (match.Groups[1].Value.Contains(dic[ArtifactAffixType.EnergyRecharge]))
|
||||
{
|
||||
artifactAffixType = ArtifactAffixType.EnergyRecharge;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
throw new Exception($"未识别的副词条:{match.Groups[1].Value}");
|
||||
}
|
||||
}).Where(a => a != null).Cast<ArtifactAffix>().ToArray();
|
||||
|
||||
if (!float.TryParse(match.Groups[2].Value.Replace("。", "."), NumberStyles.Any, cultureInfo, out float affixValue))
|
||||
{
|
||||
throw new Exception($"未识别的副词条数值:{match.Groups[2].Value}");
|
||||
}
|
||||
|
||||
bool isUnactivated = false;
|
||||
// 只有在已经成功识别至少 3 个词条后才执行额外的直方图分析。
|
||||
if (minorAffixes.Count >= 3)
|
||||
{
|
||||
using var lineRoi = levelAndMinorAffixRoi.SubMat(r.Rect);
|
||||
using var lineHistogram = new Mat();
|
||||
Cv2.CalcHist(
|
||||
images: [lineRoi],
|
||||
channels: [0],
|
||||
mask: null,
|
||||
hist: lineHistogram,
|
||||
dims: 1,
|
||||
histSize: [256],
|
||||
ranges: [new Rangef(0, 256)]
|
||||
);
|
||||
lineHistogram.GetArray(out float[] histogramFrequencies);
|
||||
// 检查背景和前景像素是否符合未激活的特征。
|
||||
const int backgroundIntensity = 222;
|
||||
const int foregroundIntensity = 152;
|
||||
var backgroundFrequency = histogramFrequencies[backgroundIntensity];
|
||||
var foregroundFrequency = histogramFrequencies[foregroundIntensity];
|
||||
var noiseFrequencyUpperBound = Math.Min(backgroundFrequency, foregroundFrequency);
|
||||
// 检查这两个强度是否比所有其他强度更常见
|
||||
isUnactivated = backgroundFrequency > 0 &&
|
||||
foregroundFrequency > 0 &&
|
||||
backgroundFrequency > foregroundFrequency &&
|
||||
!histogramFrequencies
|
||||
.Where((frequency, intensity) =>
|
||||
intensity != backgroundIntensity &&
|
||||
intensity != foregroundIntensity &&
|
||||
frequency > noiseFrequencyUpperBound)
|
||||
.Any();
|
||||
}
|
||||
minorAffixes.Add(new ArtifactAffix(artifactAffixType, affixValue, isUnactivated));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 等级
|
||||
@@ -637,14 +729,14 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}).Where(l => l != null).Cast<string>().SingleOrDefault() ?? throw new Exception($"未找到等级对应的行:\n{levelAndMinorAffixText}");
|
||||
}).Where(l => l != null).Cast<string>().SingleOrDefault() ?? throw new Exception($"未找到等级对应的行:\n{levelAndMinorAffixLines}");
|
||||
if (!int.TryParse(levelLine, out int level) || level < 0 || level > 20)
|
||||
{
|
||||
throw new Exception($"未识别的等级:{levelLine}");
|
||||
}
|
||||
#endregion
|
||||
|
||||
return new ArtifactStat(name, mainAffix, minorAffixes, level);
|
||||
return new ArtifactStat(name, mainAffix, minorAffixes.ToArray(), level);
|
||||
}
|
||||
|
||||
public static ArtifactStatus GetArtifactStatus(Mat src)
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
/// <summary>
|
||||
///自动烹饪配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class AutoCookConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 触发器是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
private int _checkIntervalMs = 10;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _stopTaskWhenRecoverButtonDetected = true;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using Vanara.PInvoke;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
public class AutoCookTask : ISoloTask
|
||||
{
|
||||
private readonly ILogger<AutoCookTask> _logger = App.GetLogger<AutoCookTask>();
|
||||
private const int UiCheckIntervalMs = 400;
|
||||
private const int PeakMinCount = 600; // 最小仙跳墙 700 多
|
||||
private const int PeakTolerance = 20;
|
||||
private const int PeakStableFrameCount = 3;
|
||||
private const int TriggerDropCount = 300; // 正常是 400多
|
||||
private static readonly Rect CookColorRect1080P = new(600, 660, 730, 190);
|
||||
private static readonly Scalar TargetCookColor = new(255, 192, 64);
|
||||
|
||||
public string Name => "自动烹饪";
|
||||
|
||||
public async Task Start(CancellationToken ct)
|
||||
{
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
var autoCookConfig = TaskContext.Instance().Config.AutoCookConfig;
|
||||
var checkIntervalMs = Math.Max(1, autoCookConfig.CheckIntervalMs);
|
||||
var stopTaskWhenRecoverButtonDetected = autoCookConfig.StopTaskWhenRecoverButtonDetected;
|
||||
var peakMinCount = (int)(PeakMinCount * assetScale);
|
||||
var triggerDropCount = (int)(TriggerDropCount * assetScale);
|
||||
var cookColorRect = ScaleRect(CookColorRect1080P, assetScale);
|
||||
_logger.LogInformation("自动烹饪任务启动");
|
||||
var lastUiCheckTime = DateTime.MinValue;
|
||||
var inCookUi = false;
|
||||
int? peakColorCount = null;
|
||||
int? peakCandidate = null;
|
||||
var peakCandidateStableFrames = 0;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
using var captureRegion = CaptureToRectArea();
|
||||
var now = DateTime.UtcNow;
|
||||
if (!inCookUi || (now - lastUiCheckTime).TotalMilliseconds >= UiCheckIntervalMs)
|
||||
{
|
||||
var currentInCookUi = IsInCookUi(captureRegion);
|
||||
if (currentInCookUi != inCookUi)
|
||||
{
|
||||
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
|
||||
}
|
||||
|
||||
inCookUi = currentInCookUi;
|
||||
lastUiCheckTime = now;
|
||||
if (!inCookUi)
|
||||
{
|
||||
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (stopTaskWhenRecoverButtonDetected)
|
||||
{
|
||||
var e = captureRegion.Find(ElementAssets.Instance.BtnWhiteRecover);
|
||||
if (e.IsExist())
|
||||
{
|
||||
_logger.LogInformation("自动烹饪:{Text}", "检测到自动烹饪按钮,结束任务");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (Bv.ClickWhiteConfirmButton(captureRegion))
|
||||
{
|
||||
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
|
||||
_logger.LogInformation("自动烹饪:{Text}", "自动点击确认");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (inCookUi)
|
||||
{
|
||||
var currentColorCount = CountTargetColor(captureRegion, cookColorRect);
|
||||
if (peakColorCount.HasValue)
|
||||
{
|
||||
if (currentColorCount <= peakColorCount.Value - triggerDropCount)
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
|
||||
_logger.LogInformation("自动烹饪:{Text}", $"烹饪条像素数量较峰值下降超过{triggerDropCount},按下空格。峰值:{peakColorCount.Value} 当前:{currentColorCount}");
|
||||
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
|
||||
}
|
||||
}
|
||||
else if (TryBuildPeak(currentColorCount, peakMinCount, ref peakCandidate, ref peakCandidateStableFrames, out var builtPeak))
|
||||
{
|
||||
peakColorCount = builtPeak;
|
||||
_logger.LogInformation("自动烹饪:{Text}", $"识别到完美烹饪条峰值像素数:{builtPeak}");
|
||||
}
|
||||
}
|
||||
|
||||
await Delay(checkIntervalMs, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResetPeakState(ref int? peakColorCount, ref int? peakCandidate, ref int peakCandidateStableFrames)
|
||||
{
|
||||
peakColorCount = null;
|
||||
peakCandidate = null;
|
||||
peakCandidateStableFrames = 0;
|
||||
}
|
||||
|
||||
private static bool TryBuildPeak(int currentColorCount, int peakMinCount, ref int? peakCandidate, ref int peakCandidateStableFrames, out int builtPeak)
|
||||
{
|
||||
builtPeak = 0;
|
||||
if (currentColorCount <= peakMinCount)
|
||||
{
|
||||
peakCandidate = null;
|
||||
peakCandidateStableFrames = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!peakCandidate.HasValue)
|
||||
{
|
||||
peakCandidate = currentColorCount;
|
||||
peakCandidateStableFrames = 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Math.Abs(currentColorCount - peakCandidate.Value) <= PeakTolerance)
|
||||
{
|
||||
peakCandidate = Math.Max(peakCandidate.Value, currentColorCount);
|
||||
peakCandidateStableFrames++;
|
||||
if (peakCandidateStableFrames >= PeakStableFrameCount && peakCandidate.Value > peakMinCount)
|
||||
{
|
||||
builtPeak = peakCandidate.Value;
|
||||
peakCandidate = null;
|
||||
peakCandidateStableFrames = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
peakCandidate = currentColorCount;
|
||||
peakCandidateStableFrames = 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Rect ScaleRect(Rect rect, double scale)
|
||||
{
|
||||
return new Rect(
|
||||
(int)(rect.X * scale),
|
||||
(int)(rect.Y * scale),
|
||||
(int)(rect.Width * scale),
|
||||
(int)(rect.Height * scale));
|
||||
}
|
||||
|
||||
private bool IsInCookUi(ImageRegion captureRegion)
|
||||
{
|
||||
using var cookIcon = captureRegion.Find(ElementAssets.Instance.UiLeftTopCookIcon);
|
||||
return cookIcon.IsExist();
|
||||
}
|
||||
|
||||
private int CountTargetColor(ImageRegion captureRegion, Rect cookColorRect)
|
||||
{
|
||||
using var crop = captureRegion.DeriveCrop(cookColorRect);
|
||||
using var rgb = new Mat();
|
||||
using var mask = new Mat();
|
||||
Cv2.CvtColor(crop.SrcMat, rgb, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(rgb, TargetCookColor, TargetCookColor, mask);
|
||||
return Cv2.CountNonZero(mask);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
public class AutoCookTrigger : ITaskTrigger
|
||||
{
|
||||
private readonly ILogger<AutoCookTrigger> _logger = App.GetLogger<AutoCookTrigger>();
|
||||
|
||||
public string Name => "自动烹饪";
|
||||
public bool IsEnabled { get; set; }
|
||||
public int Priority => 50;
|
||||
public bool IsExclusive { get; set; }
|
||||
|
||||
public void Init()
|
||||
{
|
||||
IsEnabled = TaskContext.Instance().Config.AutoCookConfig.Enabled;
|
||||
IsExclusive = false;
|
||||
}
|
||||
|
||||
public void OnCapture(CaptureContent content)
|
||||
{
|
||||
// 判断是否处于烹饪界面
|
||||
IsExclusive = false;
|
||||
content.CaptureRectArea.Find(ElementAssets.Instance.UiLeftTopCookIcon, _ =>
|
||||
{
|
||||
IsExclusive = true;
|
||||
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
using var region = content.CaptureRectArea.DeriveCrop(0, captureRect.Height / 2, captureRect.Width, captureRect.Height / 2);
|
||||
var perfectBarRects = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 192, 64), 0, 8);
|
||||
if (perfectBarRects.Count >= 2)
|
||||
{
|
||||
// 点击烹饪按钮
|
||||
var btnList = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 255, 192), 12, 12);
|
||||
if (btnList.Count >= 1)
|
||||
{
|
||||
if (btnList.Count > 1)
|
||||
{
|
||||
_logger.LogWarning("自动烹饪:{Text}", "识别到多个结束烹饪按钮");
|
||||
btnList = [.. btnList.OrderByDescending(r => r.Width)];
|
||||
}
|
||||
var btn = btnList[0];
|
||||
var x = btn.X + btn.Width / 2;
|
||||
var y = btn.Y + btn.Height / 2;
|
||||
region.ClickTo(x, y);
|
||||
_logger.LogInformation("自动烹饪:{Text}", "点击结束按钮");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
@@ -0,0 +1,49 @@
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain.Assets;
|
||||
|
||||
public class AutoDomainAssets : BaseAssets<AutoDomainAssets>
|
||||
{
|
||||
public RecognitionObject ResinSwitchBtnRo;
|
||||
public RecognitionObject ResinSwitchBtnNoActiveRo;
|
||||
|
||||
|
||||
private AutoDomainAssets() : base()
|
||||
{
|
||||
Initialization(this.systemInfo);
|
||||
}
|
||||
|
||||
protected AutoDomainAssets(ISystemInfo systemInfo) : base(systemInfo)
|
||||
{
|
||||
Initialization(systemInfo);
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void Initialization(ISystemInfo systemInfo)
|
||||
{
|
||||
// 可点击状态的树脂切换按钮
|
||||
ResinSwitchBtnRo = new RecognitionObject
|
||||
{
|
||||
Name = "ResinSwitchBtn",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoDomain", "resin_switch_btn.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect((int)(960 * AssetScale), (int)(430 * AssetScale), (int)(400 * AssetScale), (int)(130 * AssetScale)),
|
||||
Threshold = 0.8,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
// 不可点击状态的树脂切换按钮
|
||||
ResinSwitchBtnNoActiveRo = new RecognitionObject
|
||||
{
|
||||
Name = "ResinSwitchBtnNoActive",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoDomain", "resin_switch_btn_no_active.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect((int)(960 * AssetScale), (int)(430 * AssetScale), (int)(400 * AssetScale), (int)(130 * AssetScale)),
|
||||
Threshold = 0.8,
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,13 @@ public partial class AutoDomainConfig : ObservableObject
|
||||
// 使用原粹树脂刷取副本次数
|
||||
[ObservableProperty]
|
||||
private int _originalResinUseCount = 0;
|
||||
// 使用原粹树脂(20)刷取副本次数
|
||||
[ObservableProperty]
|
||||
private int _originalResin20UseCount = 0;
|
||||
|
||||
// 使用原粹树脂(40)刷取副本次数
|
||||
[ObservableProperty]
|
||||
private int _originalResin40UseCount = 0;
|
||||
|
||||
//使用浓缩树脂刷取副本次数
|
||||
[ObservableProperty]
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using System.Threading;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
|
||||
public class AutoDomainParam : BaseTaskParam<AutoDomainParam>
|
||||
public class AutoDomainParam : BaseTaskParam<AutoDomainTask>
|
||||
{
|
||||
public int DomainRoundNum { get; set; }
|
||||
|
||||
@@ -34,9 +34,13 @@ public class AutoDomainParam : BaseTaskParam<AutoDomainParam>
|
||||
"浓缩树脂",
|
||||
"原粹树脂"
|
||||
];
|
||||
|
||||
// 使用原粹树脂刷取副本次数
|
||||
public int OriginalResinUseCount { get; set; } = 0;
|
||||
// 使用原粹树脂(20)刷取副本次数
|
||||
public int OriginalResin20UseCount { get; set; } = 0;
|
||||
|
||||
// 使用原粹树脂(40)刷取副本次数
|
||||
public int OriginalResin40UseCount { get; set; } = 0;
|
||||
|
||||
// 使用浓缩树脂刷取副本次数
|
||||
public int CondensedResinUseCount { get; set; } = 0;
|
||||
@@ -73,5 +77,44 @@ public class AutoDomainParam : BaseTaskParam<AutoDomainParam>
|
||||
TransientResinUseCount = config.TransientResinUseCount;
|
||||
FragileResinUseCount = config.FragileResinUseCount;
|
||||
SpecifyResinUse = config.SpecifyResinUse;
|
||||
OriginalResin20UseCount = config.OriginalResin20UseCount;
|
||||
OriginalResin40UseCount = config.OriginalResin40UseCount;
|
||||
}
|
||||
|
||||
public AutoDomainParam(int domainRoundNum = 0) : base(null, null)
|
||||
{
|
||||
DomainRoundNum = domainRoundNum;
|
||||
if (domainRoundNum == 0)
|
||||
{
|
||||
DomainRoundNum = 9999;
|
||||
}
|
||||
|
||||
CombatStrategyPath = SetCombatStrategyPath();
|
||||
SetDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置战斗策略路径
|
||||
/// </summary>
|
||||
/// <param name="strategyName">策略名称</param>
|
||||
public string SetCombatStrategyPath(string? strategyName = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(strategyName))
|
||||
{
|
||||
strategyName = TaskContext.Instance().Config.AutoFightConfig.StrategyName;
|
||||
}
|
||||
|
||||
if ("根据队伍自动选择".Equals(strategyName))
|
||||
{
|
||||
return Global.Absolute(@"User\AutoFight\");
|
||||
}
|
||||
|
||||
return Global.Absolute(@"User\AutoFight\" + strategyName + ".txt");
|
||||
}
|
||||
|
||||
public void SetResinPriorityList(params string[] priorities)
|
||||
{
|
||||
ResinPriorityList.Clear();
|
||||
ResinPriorityList.AddRange(priorities);
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ using BetterGenshinImpact.GameTask.Common;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain.Assets;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
|
||||
@@ -94,7 +95,7 @@ public class AutoDomainTask : ISoloTask
|
||||
this.clickanywheretocloseLocalizedString = stringLocalizer.WithCultureGet(cultureInfo, "点击任意位置关闭");
|
||||
this.matchingChallengeString = stringLocalizer.WithCultureGet(cultureInfo, "匹配挑战");
|
||||
this.rapidformationString = stringLocalizer.WithCultureGet(cultureInfo, "快速编队");
|
||||
this.limitedFullyString = stringLocalizer.WithCultureGet(cultureInfo, "限时全开");
|
||||
this.limitedFullyString = stringLocalizer.WithCultureGet(cultureInfo, "限时全部开放");
|
||||
this.limitedFullyAllString = stringLocalizer.WithCultureGet(cultureInfo, "限时开放");
|
||||
}
|
||||
|
||||
@@ -176,7 +177,8 @@ public class AutoDomainTask : ISoloTask
|
||||
{
|
||||
combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
|
||||
}
|
||||
RetryTeamInit(combatScenes);// 队伍没初始化成功则重试
|
||||
|
||||
RetryTeamInit(combatScenes); // 队伍没初始化成功则重试
|
||||
|
||||
// 0. 切换到第一个角色
|
||||
var combatCommands = FindCombatScriptAndSwitchAvatar(combatScenes);
|
||||
@@ -206,8 +208,6 @@ public class AutoDomainTask : ISoloTask
|
||||
Logger.LogInformation("体力耗尽或者设置轮次已达标,结束自动秘境");
|
||||
break;
|
||||
}
|
||||
|
||||
Notify.Event(NotificationEvent.DomainReward).Success("自动秘境奖励领取");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,12 +274,12 @@ public class AutoDomainTask : ISoloTask
|
||||
if ("芬德尼尔之顶".Equals(_taskParam.DomainName))
|
||||
{
|
||||
menuFound = await NewRetry.WaitForElementAppear(
|
||||
AutoPickAssets.Instance.PickRo,
|
||||
() => Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyDown),
|
||||
_ct,
|
||||
20,
|
||||
500
|
||||
);
|
||||
AutoPickAssets.Instance.PickRo,
|
||||
() => Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyDown),
|
||||
_ct,
|
||||
20,
|
||||
500
|
||||
);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyUp);
|
||||
}
|
||||
else if ("无妄引咎密宫".Equals(_taskParam.DomainName))
|
||||
@@ -296,14 +296,13 @@ public class AutoDomainTask : ISoloTask
|
||||
500
|
||||
);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
|
||||
}
|
||||
else if ("太山府".Equals(_taskParam.DomainName))
|
||||
{
|
||||
menuFound = await NewRetry.WaitForElementAppear(
|
||||
AutoPickAssets.Instance.PickRo,
|
||||
() => { },
|
||||
_ct,
|
||||
_ct,
|
||||
20,
|
||||
500
|
||||
);
|
||||
@@ -311,11 +310,11 @@ public class AutoDomainTask : ISoloTask
|
||||
else
|
||||
{
|
||||
menuFound = await NewRetry.WaitForElementAppear(
|
||||
AutoPickAssets.Instance.PickRo,
|
||||
() => Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown),
|
||||
_ct,
|
||||
20,
|
||||
500
|
||||
AutoPickAssets.Instance.PickRo,
|
||||
() => Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown),
|
||||
_ct,
|
||||
20,
|
||||
500
|
||||
);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
}
|
||||
@@ -336,7 +335,6 @@ public class AutoDomainTask : ISoloTask
|
||||
{
|
||||
throw new Exception("请检查是否已进入秘境页面");
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -382,7 +380,7 @@ public class AutoDomainTask : ISoloTask
|
||||
using var limitedFullyStringRa = CaptureToRectArea();
|
||||
var limitedFullyStringRaocrList =
|
||||
limitedFullyStringRa.FindMulti(RecognitionObject.Ocr(0, 0, limitedFullyStringRa.Width * 0.5,
|
||||
limitedFullyStringRa.Height));
|
||||
limitedFullyStringRa.Height * 0.5));
|
||||
var limitedFullyStringRaocrListdone = limitedFullyStringRaocrList.LastOrDefault(t =>
|
||||
Regex.IsMatch(t.Text, this.limitedFullyString) || Regex.IsMatch(t.Text, this.limitedFullyAllString));
|
||||
// 检测是否为限时全开秘境
|
||||
@@ -457,7 +455,7 @@ public class AutoDomainTask : ISoloTask
|
||||
// 点击单人挑战确认并等待队伍界面--使用图像模版匹配的方法,也可以使用文字OCR的方法识别“单人挑战”直到消失
|
||||
await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PartyBtnChooseView,
|
||||
async void () =>
|
||||
() =>
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
var ra2 = ra.Find(fightAssets.ConfirmRa);
|
||||
@@ -467,6 +465,7 @@ public class AutoDomainTask : ISoloTask
|
||||
ra2.Dispose();
|
||||
Logger.LogInformation("自动秘境:点击 {Text}", "单人挑战");
|
||||
}
|
||||
|
||||
using var confirmRectArea2 = ra.Find(RecognitionObject.Ocr(ra.Width * 0.263, ra.Height * 0.32,
|
||||
ra.Width - ra.Width * 0.263 * 2, ra.Height - ra.Height * 0.32 - ra.Height * 0.353));
|
||||
if (confirmRectArea2.IsExist() && confirmRectArea2.Text.Contains("是否仍要挑战该秘境"))
|
||||
@@ -483,10 +482,7 @@ public class AutoDomainTask : ISoloTask
|
||||
// 等待队伍选择界面出现
|
||||
var teamUiFound = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PartyBtnChooseView,
|
||||
() =>
|
||||
{
|
||||
Logger.LogInformation("自动秘境:进入 {Text}", "队伍选择界面");
|
||||
},
|
||||
() => { Logger.LogInformation("自动秘境:进入 {Text}", "队伍选择界面"); },
|
||||
_ct,
|
||||
10,
|
||||
1000
|
||||
@@ -520,6 +516,7 @@ public class AutoDomainTask : ISoloTask
|
||||
{
|
||||
Logger.LogWarning("开始挑战按钮未出现或未能点击。");
|
||||
}
|
||||
|
||||
// 载入
|
||||
await Delay(1000, _ct);
|
||||
}
|
||||
@@ -535,7 +532,7 @@ public class AutoDomainTask : ISoloTask
|
||||
var ocrListLeft = ra.Find(AutoFightAssets.Instance.AbnormalIconRa);
|
||||
return (ocrList.Any(t => t.Text.Contains(leyLineDisorderLocalizedString) ||
|
||||
t.Text.Contains(clickanywheretocloseLocalizedString))) || ocrListLeft.IsExist();
|
||||
}, _ct, 20, 500);
|
||||
}, _ct, 40, 500);
|
||||
if (!domainTipFound)
|
||||
{
|
||||
Logger.LogWarning("秘境提示未出现或未能点击。");
|
||||
@@ -556,6 +553,7 @@ public class AutoDomainTask : ISoloTask
|
||||
done.Dispose();
|
||||
Logger.LogInformation("自动秘境:点击 {Text}", done.Text);
|
||||
}
|
||||
|
||||
// 检查左下角区域是否还存在目标文字,消失则继续,存在则结束
|
||||
using var leftBottom = CaptureToRectArea();
|
||||
var leftBottomOcr = leftBottom.Find(AutoFightAssets.Instance.AbnormalIconRa);
|
||||
@@ -1120,13 +1118,13 @@ public class AutoDomainTask : ISoloTask
|
||||
bool resinUsed = false;
|
||||
if (resinStatus.CondensedResinCount > 0)
|
||||
{
|
||||
resinUsed = PressUseResin(ra3, "浓缩树脂");
|
||||
(resinUsed, _) = PressUseResin(ra3, "浓缩树脂");
|
||||
resinStatus.CondensedResinCount -= 1;
|
||||
}
|
||||
else if (resinStatus.OriginalResinCount >= 20)
|
||||
{
|
||||
resinUsed = PressUseResin(ra3, "原粹树脂");
|
||||
resinStatus.OriginalResinCount -= 20;
|
||||
(resinUsed, var num) = PressUseResin(ra3, "原粹树脂");
|
||||
resinStatus.OriginalResinCount -= num;
|
||||
}
|
||||
|
||||
if (!resinUsed)
|
||||
@@ -1147,18 +1145,39 @@ public class AutoDomainTask : ISoloTask
|
||||
// 指定使用树脂
|
||||
var textListInPrompt2 = ra3.FindMulti(RecognitionObject.Ocr(ra3.Width * 0.25, ra3.Height * 0.2, ra3.Width * 0.5, ra3.Height * 0.6));
|
||||
// 按优先级使用
|
||||
var failCount = 0;
|
||||
int successCount = 0;
|
||||
foreach (var record in _resinPriorityListWhenSpecifyUse)
|
||||
{
|
||||
if (record.RemainCount > 0 && PressUseResin(textListInPrompt2, record.Name))
|
||||
if (record.RemainCount > 0)
|
||||
{
|
||||
record.RemainCount -= 1;
|
||||
Logger.LogInformation("自动秘境:{Name} 刷取 {Re}/{Max}", record.Name, record.MaxCount - record.RemainCount, record.MaxCount);
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
failCount++;
|
||||
if (record.Name == "原粹树脂20" || record.Name == "原粹树脂40")
|
||||
{
|
||||
int expectedNum = record.Name == "原粹树脂20" ? 20 : 40;
|
||||
bool switched;
|
||||
try
|
||||
{
|
||||
switched = SwitchOriginalResinType(expectedNum, _ct);
|
||||
}
|
||||
catch (RetryException)
|
||||
{
|
||||
Logger.LogWarning("自动秘境:切换原粹树脂类型重试超时,跳过 {Name}", record.Name);
|
||||
switched = false;
|
||||
}
|
||||
|
||||
if (!switched)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
var (success, _) = PressUseResin(textListInPrompt2, record.Name);
|
||||
if (success)
|
||||
{
|
||||
record.RemainCount -= 1;
|
||||
Logger.LogInformation("自动秘境:{Name} 刷取 {Re}/{Max}", record.Name, record.MaxCount - record.RemainCount, record.MaxCount);
|
||||
successCount++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1168,7 +1187,7 @@ public class AutoDomainTask : ISoloTask
|
||||
isLastTurn = true;
|
||||
}
|
||||
|
||||
if (failCount == _resinPriorityListWhenSpecifyUse.Count)
|
||||
if (successCount == 0)
|
||||
{
|
||||
// 没有找到对应的树脂
|
||||
Logger.LogWarning("自动秘境:指定树脂领取次数时,当前可用树脂选项无法满足配置。你可能设置的刷取次数过多!退出秘境。");
|
||||
@@ -1183,6 +1202,8 @@ public class AutoDomainTask : ISoloTask
|
||||
// 如果没有选择树脂的提示,说明只有原粹树脂
|
||||
// 继续向下执行
|
||||
}
|
||||
|
||||
Notify.Event(NotificationEvent.DomainReward).Success("自动秘境奖励领取");
|
||||
|
||||
Sleep(1000, _ct);
|
||||
|
||||
@@ -1230,6 +1251,7 @@ public class AutoDomainTask : ISoloTask
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1249,14 +1271,19 @@ public class AutoDomainTask : ISoloTask
|
||||
Bv.ClickBlackConfirmButton(CaptureToRectArea());
|
||||
}
|
||||
|
||||
private bool PressUseResin(ImageRegion ra, string resinName)
|
||||
public static (bool, int) PressUseResin(ImageRegion ra, string resinName)
|
||||
{
|
||||
var regionList = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.25, ra.Height * 0.2, ra.Width * 0.5, ra.Height * 0.6));
|
||||
return PressUseResin(regionList, resinName);
|
||||
}
|
||||
|
||||
private bool PressUseResin(List<Region> regionList, string resinName)
|
||||
public static (bool, int) PressUseResin(List<Region> regionList, string resinName)
|
||||
{
|
||||
if (resinName == "原粹树脂20" || resinName == "原粹树脂40")
|
||||
{
|
||||
resinName = "原粹树脂";
|
||||
}
|
||||
|
||||
var resinKey = regionList.FirstOrDefault(t => t.Text.Contains(resinName));
|
||||
if (resinKey != null)
|
||||
{
|
||||
@@ -1272,10 +1299,11 @@ public class AutoDomainTask : ISoloTask
|
||||
// 点击使用
|
||||
useKey.Click();
|
||||
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了。使用双击
|
||||
Sleep(60, _ct);
|
||||
Sleep(60);
|
||||
useKey.Click();
|
||||
Logger.LogInformation("自动秘境:使用 {ResinName}", resinName);
|
||||
return true;
|
||||
var num = GetResinNum(resinKey, resinName);
|
||||
Logger.LogInformation("自动秘境:使用 {ResinName}, 数量:{Num}", resinName, num);
|
||||
return (true, num);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1288,13 +1316,81 @@ public class AutoDomainTask : ISoloTask
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
private bool SwitchOriginalResinType(int expectedNum, CancellationToken ct)
|
||||
{
|
||||
return NewRetry.Do(() =>
|
||||
{
|
||||
using var ra0 = CaptureToRectArea();
|
||||
var regionList = ra0.FindMulti(RecognitionObject.Ocr(ra0.Width * 0.25, ra0.Height * 0.2, ra0.Width * 0.5, ra0.Height * 0.6));
|
||||
var has20 = regionList.Any(t => t.Text.Contains("20"));
|
||||
var has40 = regionList.Any(t => t.Text.Contains("40"));
|
||||
if (expectedNum == 20 && has20)
|
||||
{
|
||||
Logger.LogInformation("自动秘境:已切换到使用20原粹树脂");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (expectedNum == 40 && has40)
|
||||
{
|
||||
Logger.LogInformation("自动秘境:已切换到使用40原粹树脂");
|
||||
return true;
|
||||
}
|
||||
|
||||
//切换20/40原粹树脂的按钮是亮的
|
||||
var clickable = ra0.Find(AutoDomainAssets.Instance.ResinSwitchBtnRo);
|
||||
if (clickable.IsExist())
|
||||
{
|
||||
Logger.LogDebug("自动秘境:切换原粹树脂使用数量");
|
||||
clickable.Click();
|
||||
}
|
||||
|
||||
//切换20/40原粹树脂的按钮是暗的
|
||||
var disabled = ra0.Find(AutoDomainAssets.Instance.ResinSwitchBtnNoActiveRo);
|
||||
if (disabled.IsExist())
|
||||
{
|
||||
Logger.LogWarning("自动秘境:切换原粹树脂的使用数量失败,可能是体力不足,当前目标:{Num}", expectedNum);
|
||||
return false; // 不可点击
|
||||
}
|
||||
|
||||
throw new RetryException("未检测到按钮"); // 继续重试
|
||||
}, TimeSpan.FromMilliseconds(500), 10);
|
||||
}
|
||||
|
||||
private static int GetResinNum(Region region, string resinName)
|
||||
{
|
||||
if (resinName == "原粹树脂")
|
||||
{
|
||||
if (region.Text.Contains("20"))
|
||||
{
|
||||
return 20;
|
||||
}
|
||||
else if (region.Text.Contains("40"))
|
||||
{
|
||||
return 40;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("自动秘境:未识别到原粹树脂消耗体力数量,默认按20计算");
|
||||
return 20;
|
||||
}
|
||||
}
|
||||
else if (resinName == "浓缩树脂" || resinName == "脆弱树脂" || resinName == "须臾树脂")
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("未知的树脂名称");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断两个区域在垂直方向上是否有重叠
|
||||
/// </summary>
|
||||
private bool IsHeightOverlap(Region region1, Region region2)
|
||||
private static bool IsHeightOverlap(Region region1, Region region2)
|
||||
{
|
||||
int region1Top = region1.Y;
|
||||
int region1Bottom = region1.Y + region1.Height;
|
||||
@@ -1319,4 +1415,4 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
await new AutoArtifactSalvageTask(new AutoArtifactSalvageTaskParam(star, javaScript: null, artifactSetFilter: null, maxNumToCheck: null, recognitionFailurePolicy: null)).Start(_ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,14 @@ public class ResinUseRecord
|
||||
{
|
||||
list.Add(new ResinUseRecord("浓缩树脂", taskParam.CondensedResinUseCount));
|
||||
}
|
||||
if (taskParam.OriginalResin40UseCount > 0)
|
||||
{
|
||||
list.Add(new ResinUseRecord("原粹树脂40", taskParam.OriginalResin40UseCount));
|
||||
}
|
||||
if (taskParam.OriginalResin20UseCount > 0)
|
||||
{
|
||||
list.Add(new ResinUseRecord("原粹树脂20", taskParam.OriginalResin20UseCount));
|
||||
}
|
||||
if (taskParam.OriginalResinUseCount > 0)
|
||||
{
|
||||
list.Add(new ResinUseRecord("原粹树脂", taskParam.OriginalResinUseCount));
|
||||
@@ -54,7 +62,7 @@ public class ResinUseRecord
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<ResinUseRecord> BuildFromDomainParam(AutoStygianOnslaughtConfig taskParam)
|
||||
public static List<ResinUseRecord> BuildFromDomainParam(AutoStygianOnslaughtParam taskParam)
|
||||
{
|
||||
List<ResinUseRecord> list = [];
|
||||
if (taskParam.SpecifyResinUse)
|
||||
|
||||
@@ -9,6 +9,8 @@ using BetterGenshinImpact.GameTask.GetGridIcons;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.GameTask.Model.GameUI;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
@@ -86,42 +88,53 @@ public class AutoEatTask : BaseIndependentTask, ISoloTask<int?>
|
||||
using InferenceSession session = GridIconsAccuracyTestTask.LoadModel(out Dictionary<string, float[]> prototypes);
|
||||
|
||||
GridScreen gridScreen = new GridScreen(GridParams.Templates[GridScreenName.Food], _logger, _ct);
|
||||
gridScreen.OnAfterTurnToNewPage += GridScreen.DrawItemsAfterTurnToNewPage;
|
||||
gridScreen.OnBeforeScroll += () => VisionContext.Instance().DrawContent.ClearAll();
|
||||
int? count = null;
|
||||
await foreach (ImageRegion itemRegion in gridScreen)
|
||||
try
|
||||
{
|
||||
using Mat icon = itemRegion.SrcMat.GetGridIcon();
|
||||
var result = GridIconsAccuracyTestTask.Infer(icon, session, prototypes);
|
||||
string predName = result.Item1;
|
||||
if (predName == _taskParam.FoodName)
|
||||
await foreach ((ImageRegion pageRegion, Rect itemRect) in gridScreen)
|
||||
{
|
||||
// 点击item
|
||||
itemRegion.Click();
|
||||
using ImageRegion itemRegion = pageRegion.DeriveCrop(itemRect);
|
||||
using Mat icon = itemRegion.SrcMat.GetGridIcon();
|
||||
var result = GridIconsAccuracyTestTask.Infer(icon, session, prototypes);
|
||||
string predName = result.Item1;
|
||||
if (predName == _taskParam.FoodName)
|
||||
{
|
||||
// 点击item
|
||||
itemRegion.Click();
|
||||
|
||||
#region 识别数量
|
||||
string numStr = itemRegion.SrcMat.GetGridItemIconText(OcrFactory.Paddle);
|
||||
if (int.TryParse(numStr, out int num))
|
||||
{
|
||||
count = num - 1; // 算上吃掉的1个
|
||||
}
|
||||
else
|
||||
{
|
||||
count = -2;
|
||||
_logger.LogWarning("无法识别食物数量:{text},依然尝试使用", numStr);
|
||||
}
|
||||
#endregion
|
||||
#region 识别数量
|
||||
string ocrText = itemRegion.SrcMat.GetGridItemIconText(OcrFactory.Paddle);
|
||||
string numStr = StringUtils.ConvertFullWidthNumToHalfWidth(ocrText);
|
||||
if (int.TryParse(numStr, out int num))
|
||||
{
|
||||
count = num - 1; // 算上吃掉的1个
|
||||
}
|
||||
else
|
||||
{
|
||||
count = -2;
|
||||
_logger.LogWarning("无法识别食物数量:{text},依然尝试使用", numStr);
|
||||
}
|
||||
#endregion
|
||||
|
||||
await Delay(300, ct);
|
||||
// 点击确定
|
||||
using var ra0 = CaptureToRectArea();
|
||||
using var ra = ra0.Find(ElementAssets.Instance.BtnWhiteConfirm);
|
||||
if (ra.IsExist())
|
||||
{
|
||||
ra.Click();
|
||||
await Delay(300, ct);
|
||||
// 点击确定
|
||||
using var ra0 = CaptureToRectArea();
|
||||
using var ra = ra0.Find(ElementAssets.Instance.BtnWhiteConfirm);
|
||||
if (ra.IsExist())
|
||||
{
|
||||
ra.Click();
|
||||
}
|
||||
_logger.LogInformation("吃了一份{name},真香!", predName);
|
||||
break;
|
||||
}
|
||||
_logger.LogInformation("吃了一份{name},真香!", predName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
}
|
||||
if (count == null)
|
||||
{
|
||||
count = -1;
|
||||
|
||||
@@ -9,13 +9,12 @@ using BetterGenshinImpact.Service.Notification.Model.Enum;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using static Vanara.PInvoke.User32;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoEat;
|
||||
|
||||
/// <summary>
|
||||
/// 自动吃药触发器
|
||||
/// 检测红血状态时自动使用Recovery.png,检测到Resurrection.png时按z复活
|
||||
/// 检测红血状态时自动使用Recovery.png,检测到Resurrection.png时按快捷使用小道具键复活
|
||||
/// </summary>
|
||||
public class AutoEatTrigger : ITaskTrigger
|
||||
{
|
||||
@@ -94,8 +93,8 @@ public class AutoEatTrigger : ITaskTrigger
|
||||
// 检查复活CD(2秒)
|
||||
if ((now - _lastResurrectionTime).TotalSeconds >= 2)
|
||||
{
|
||||
// 按z键复活
|
||||
Simulation.SendInput.Keyboard.KeyPress(VK.VK_Z);
|
||||
// 走原神动作映射,跟随“快捷使用小道具”键位配置
|
||||
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
|
||||
_lastResurrectionTime = now;
|
||||
_logger.LogInformation("检测到复活图标,自动复活");
|
||||
}
|
||||
@@ -140,4 +139,4 @@ public class AutoEatTrigger : ITaskTrigger
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 607 B After Width: | Height: | Size: 1.8 KiB |
@@ -1,7 +1,13 @@
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
|
||||
@@ -11,6 +17,8 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
public Rect TeamRect;
|
||||
public List<Rect> AvatarSideIconRectList; // 侧边栏角色头像 非联机状态下
|
||||
public List<Rect> AvatarIndexRectList; // 侧边栏角色头像对应的白色块 非联机状态下
|
||||
public List<Rect> AvatarQRectListMap; // 角色头像对应的Q技能图标
|
||||
|
||||
public Rect ERect;
|
||||
public Rect ECooldownRect;
|
||||
public Rect QRect;
|
||||
@@ -41,7 +49,24 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
|
||||
public RecognitionObject AbnormalIconRa;
|
||||
|
||||
private AutoFightAssets()
|
||||
/// <summary>
|
||||
/// 经验值模板识别对象列表,用于检测怪物死亡时掉落的经验值数字图标
|
||||
/// </summary>
|
||||
public IReadOnlyList<RecognitionObject> ExperienceRecognitionObjects { get; private set; } = Array.Empty<RecognitionObject>();
|
||||
|
||||
#pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 "required" 修饰符或声明为可为 null。
|
||||
private AutoFightAssets() : base()
|
||||
{
|
||||
Initialization(this.systemInfo);
|
||||
}
|
||||
|
||||
protected AutoFightAssets(ISystemInfo systemInfo) : base(systemInfo)
|
||||
{
|
||||
Initialization(systemInfo);
|
||||
}
|
||||
#pragma warning restore CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 "required" 修饰符或声明为可为 null。
|
||||
|
||||
private void Initialization(ISystemInfo systemInfo)
|
||||
{
|
||||
TeamRectNoIndex = new Rect(CaptureRect.Width - (int)(355 * AssetScale), (int)(220 * AssetScale),
|
||||
(int)((355 - 85) * AssetScale), (int)(465 * AssetScale));
|
||||
@@ -72,6 +97,14 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
new Rect(CaptureRect.Width - (int)(61 * AssetScale), (int)(544 * AssetScale), (int)(28 * AssetScale), (int)(24 * AssetScale)),
|
||||
];
|
||||
|
||||
AvatarQRectListMap =
|
||||
[
|
||||
new Rect(CaptureRect.Width - (int)(336 * AssetScale), (int)(216 * AssetScale), (int)(64 * AssetScale), (int)(84 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(336 * AssetScale), (int)(316 * AssetScale), (int)(64 * AssetScale), (int)(84 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(336 * AssetScale), (int)(416 * AssetScale), (int)(64 * AssetScale), (int)(84 * AssetScale)),
|
||||
new Rect(CaptureRect.Width - (int)(336 * AssetScale), (int)(516 * AssetScale), (int)(64 * AssetScale), (int)(84 * AssetScale)),
|
||||
];
|
||||
|
||||
AvatarSideIconRectList =
|
||||
[
|
||||
new Rect(CaptureRect.Width - (int)(155 * AssetScale), (int)(225 * AssetScale), (int)(76 * AssetScale), (int)(76 * AssetScale)),
|
||||
@@ -156,7 +189,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "1P",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "1p.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "1p.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(0, 0, CaptureRect.Width / 4, CaptureRect.Height / 7),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -165,7 +198,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "P",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "p.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "p.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width - (int)(CaptureRect.Width / 12.5), CaptureRect.Height / 5, (int)(CaptureRect.Width / 12.5), CaptureRect.Height / 2 - CaptureRect.Width / 7),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -174,14 +207,14 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "WandererIcon",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "wanderer_icon.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "wanderer_icon.png", this.systemInfo),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
WandererIconNoActiveRa = new RecognitionObject
|
||||
{
|
||||
Name = "WandererIconNoActive",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "wanderer_icon_no_active.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "wanderer_icon_no_active.png", this.systemInfo),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
@@ -190,7 +223,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "Confirm",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "confirm.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "confirm.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 2, CaptureRect.Width / 2, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -198,7 +231,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "ArtifactArea",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "artifact_flower_logo.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "artifact_flower_logo.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, 0, CaptureRect.Width / 2, CaptureRect.Height),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -208,7 +241,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "ClickAnyCloseTip",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "click_any_close_tip.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "click_any_close_tip.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(0, CaptureRect.Height / 2, CaptureRect.Width, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -217,7 +250,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "Exit",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "exit.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "exit.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(0, CaptureRect.Height / 2, CaptureRect.Width / 2, CaptureRect.Height / 2),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
@@ -227,7 +260,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
// {
|
||||
// Name = "LockIcon",
|
||||
// RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
// TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "lock_icon.png"),
|
||||
// TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "lock_icon.png", this.systemInfo),
|
||||
// RegionOfInterest = new Rect(CaptureRect.Width - (int)(215 * AssetScale), 0, (int)(215 * AssetScale), (int)(80 * AssetScale)),
|
||||
// DrawOnWindow = false
|
||||
// }.InitTemplate();
|
||||
@@ -236,9 +269,60 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
{
|
||||
Name = "AbnormalIcon",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "abnormal_icon.png"),
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "abnormal_icon.png", this.systemInfo),
|
||||
RegionOfInterest = new Rect(0, (int)(CaptureRect.Height * 0.08), (int)(CaptureRect.Width * 0.04), (int)(CaptureRect.Height * 0.07)),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
// 加载经验值模板图片(用于检测精英怪死亡时的经验值数字图标)
|
||||
try
|
||||
{
|
||||
LoadExperienceRecognitionObjects();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 经验值模板加载失败不应阻止 AutoFightAssets 初始化
|
||||
ExperienceRecognitionObjects = Array.Empty<RecognitionObject>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载经验值模板图片,文件缺失时跳过,不影响其他功能
|
||||
/// </summary>
|
||||
private void LoadExperienceRecognitionObjects()
|
||||
{
|
||||
var experienceValues = new[] { 57, 58, 60 };
|
||||
var threshold = CaptureRect.Width > 1920 ? 0.6 : 0.9;
|
||||
var roi = new Rect(
|
||||
(int)(CaptureRect.Width * 0.145),
|
||||
(int)(CaptureRect.Height * 0.5),
|
||||
(int)(CaptureRect.Width * 0.02),
|
||||
(int)(CaptureRect.Height * 0.22));
|
||||
|
||||
var list = new List<RecognitionObject>();
|
||||
foreach (var exp in experienceValues)
|
||||
{
|
||||
var fileName = $"experience_{exp}.png";
|
||||
try
|
||||
{
|
||||
var ro = new RecognitionObject
|
||||
{
|
||||
Name = $"Experience_{exp}",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", fileName, this.systemInfo),
|
||||
RegionOfInterest = roi,
|
||||
UseMask = true,
|
||||
Threshold = threshold,
|
||||
DrawOnWindow = true,
|
||||
}.InitTemplate();
|
||||
list.Add(ro);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 构造阶段 Logger 可能不可用,静默跳过缺失的模板
|
||||
}
|
||||
}
|
||||
|
||||
ExperienceRecognitionObjects = list.AsReadOnly();
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,26 @@
|
||||
"nameEn": "PlayerBoy",
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"奇偶(男)",
|
||||
"MannequinBoy"
|
||||
],
|
||||
"id": "10000117",
|
||||
"name": "奇偶(男)",
|
||||
"nameEn": "MannequinBoy",
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"奇偶(女)",
|
||||
"MannequinGirl"
|
||||
],
|
||||
"id": "10000118",
|
||||
"name": "奇偶(女)",
|
||||
"nameEn": "MannequinGirl",
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"神里绫华",
|
||||
@@ -1949,5 +1969,111 @@
|
||||
"nameEn": "Aino",
|
||||
"skillCD": 10,
|
||||
"weapon": "11"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"奈芙尔",
|
||||
"Nefer"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000122",
|
||||
"name": "奈芙尔",
|
||||
"nameEn": "Nefer",
|
||||
"skillCD": 9,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"杜林",
|
||||
"Durin"
|
||||
],
|
||||
"burstCD": 18,
|
||||
"id": "10000123",
|
||||
"name": "杜林",
|
||||
"nameEn": "Durin",
|
||||
"skillCD": 12,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"雅珂达",
|
||||
"Jahoda"
|
||||
],
|
||||
"burstCD": 18,
|
||||
"id": "10000124",
|
||||
"name": "雅珂达",
|
||||
"nameEn": "Jahoda",
|
||||
"skillCD": 15,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"哥伦比娅",
|
||||
"Columbina",
|
||||
"少女",
|
||||
"库塔尔",
|
||||
"月神",
|
||||
"月之少女"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000125",
|
||||
"name": "哥伦比娅",
|
||||
"nameEn": "Columbina",
|
||||
"skillCD": 17,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"兹白",
|
||||
"Zibai",
|
||||
"白马仙人",
|
||||
"白马"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000126",
|
||||
"name": "兹白",
|
||||
"nameEn": "Zibai",
|
||||
"skillCD": 18,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"叶洛亚",
|
||||
"Illuga",
|
||||
"少爷",
|
||||
"小少爷"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000127",
|
||||
"name": "叶洛亚",
|
||||
"nameEn": "Illuga",
|
||||
"skillCD": 15,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"法尔伽",
|
||||
"Varka",
|
||||
"团长",
|
||||
"法尔加"
|
||||
],
|
||||
"burstCD": 16,
|
||||
"id": "10000128",
|
||||
"name": "法尔伽",
|
||||
"nameEn": "Varka",
|
||||
"skillCD": 16,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"莉奈娅",
|
||||
"Linnea"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000130",
|
||||
"name": "莉奈娅",
|
||||
"nameEn": "Linnea",
|
||||
"skillCD": 18,
|
||||
"weapon": "10"
|
||||
}
|
||||
]
|
||||
@@ -83,7 +83,24 @@ public partial class AutoFightConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _beforeDetectDelay = "";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 旋转寻找敌人位置的旋转因子,默认为5,越大越快。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _rotaryFactor = 10;
|
||||
|
||||
/// <summary>
|
||||
/// 是否是第一次检查和面敌。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _isFirstCheck = false;
|
||||
|
||||
/// <summary>
|
||||
/// 是有元素爆发前检查战斗结束
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _checkBeforeBurst = false;
|
||||
}
|
||||
/// <summary>
|
||||
/// 战斗结束相关配置
|
||||
@@ -114,7 +131,10 @@ public partial class AutoFightConfig : ObservableObject
|
||||
private bool _kazuhaPickupEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _guardianAvatar = " ";
|
||||
private bool _qinDoublePickUp = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _guardianAvatar = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _guardianCombatSkip = false;
|
||||
@@ -125,12 +145,23 @@ public partial class AutoFightConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool _guardianAvatarHold = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _burstEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 战斗结束后,如果不存在万叶,则切换至存在万叶的队伍(基于开启万叶拾取情况下)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _kazuhaPartyName = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _swimmingEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 基于经验值判断是否执行战后拾取(检测到精英怪经验值图标时才拾取)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _expBasedPickupEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 战斗超时,单位秒
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
@@ -47,8 +48,15 @@ public class AutoFightParam : BaseTaskParam<AutoFightTask>
|
||||
|
||||
GuardianAvatar = autoFightConfig.GuardianAvatar;
|
||||
GuardianCombatSkip = autoFightConfig.GuardianCombatSkip;
|
||||
SkipModel = autoFightConfig.SkipModel;
|
||||
GuardianAvatarHold = autoFightConfig.GuardianAvatarHold;
|
||||
BurstEnabled = autoFightConfig.BurstEnabled;
|
||||
|
||||
CheckBeforeBurst = autoFightConfig.FinishDetectConfig.CheckBeforeBurst;
|
||||
IsFirstCheck = autoFightConfig.FinishDetectConfig.IsFirstCheck;
|
||||
RotaryFactor = autoFightConfig.FinishDetectConfig.RotaryFactor;
|
||||
QinDoublePickUp = autoFightConfig.QinDoublePickUp;
|
||||
SwimmingEnabled = autoFightConfig.SwimmingEnabled;
|
||||
ExpBasedPickupEnabled = autoFightConfig.ExpBasedPickupEnabled;
|
||||
}
|
||||
|
||||
public FightFinishDetectConfig FinishDetectConfig { get; set; } = new();
|
||||
@@ -65,8 +73,79 @@ public class AutoFightParam : BaseTaskParam<AutoFightTask>
|
||||
public string ActionSchedulerByCd = "";
|
||||
public string KazuhaPartyName;
|
||||
public string OnlyPickEliteDropsMode = "";
|
||||
public string GuardianAvatar { get; set; } = " ";
|
||||
public string GuardianAvatar { get; set; } = string.Empty;
|
||||
public bool GuardianCombatSkip { get; set; } = false;
|
||||
public bool SkipModel = false;
|
||||
public bool GuardianAvatarHold = false;
|
||||
|
||||
public bool CheckBeforeBurst { get; set; } = false;
|
||||
public bool IsFirstCheck { get; set; } = true;
|
||||
public int RotaryFactor { get; set; } = 10;
|
||||
public bool BurstEnabled { get; set; } = false;
|
||||
|
||||
public bool QinDoublePickUp { get; set; } = false;
|
||||
public static bool SwimmingEnabled { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 基于经验值判断是否执行战后拾取
|
||||
/// </summary>
|
||||
public bool ExpBasedPickupEnabled { get; set; } = false;
|
||||
|
||||
public AutoFightParam(string? strategyName = null) : base(null, null)
|
||||
{
|
||||
SetCombatStrategyPath(strategyName);
|
||||
SetDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置战斗策略路径
|
||||
/// </summary>
|
||||
/// <param name="strategyName">策略名称</param>
|
||||
public void SetCombatStrategyPath(string? strategyName = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(strategyName))
|
||||
{
|
||||
strategyName = TaskContext.Instance().Config.AutoFightConfig.StrategyName;
|
||||
}
|
||||
|
||||
if ("根据队伍自动选择".Equals(strategyName))
|
||||
{
|
||||
CombatStrategyPath = Global.Absolute(@"User\AutoFight\");
|
||||
}
|
||||
else
|
||||
{
|
||||
CombatStrategyPath = Global.Absolute(@"User\AutoFight\" + strategyName + ".txt");
|
||||
}
|
||||
}
|
||||
|
||||
public void SetDefault()
|
||||
{
|
||||
var autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
|
||||
Timeout = autoFightConfig.Timeout;
|
||||
FightFinishDetectEnabled = autoFightConfig.FightFinishDetectEnabled;
|
||||
PickDropsAfterFightEnabled = autoFightConfig.PickDropsAfterFightEnabled;
|
||||
PickDropsAfterFightSeconds = autoFightConfig.PickDropsAfterFightSeconds;
|
||||
KazuhaPickupEnabled = autoFightConfig.KazuhaPickupEnabled;
|
||||
ActionSchedulerByCd = autoFightConfig.ActionSchedulerByCd;
|
||||
|
||||
FinishDetectConfig.FastCheckEnabled = autoFightConfig.FinishDetectConfig.FastCheckEnabled;
|
||||
FinishDetectConfig.FastCheckParams = autoFightConfig.FinishDetectConfig.FastCheckParams;
|
||||
FinishDetectConfig.CheckEndDelay = autoFightConfig.FinishDetectConfig.CheckEndDelay;
|
||||
FinishDetectConfig.BeforeDetectDelay = autoFightConfig.FinishDetectConfig.BeforeDetectDelay;
|
||||
FinishDetectConfig.RotateFindEnemyEnabled = autoFightConfig.FinishDetectConfig.RotateFindEnemyEnabled;
|
||||
|
||||
|
||||
KazuhaPartyName = autoFightConfig.KazuhaPartyName;
|
||||
OnlyPickEliteDropsMode = autoFightConfig.OnlyPickEliteDropsMode;
|
||||
BattleThresholdForLoot = autoFightConfig.BattleThresholdForLoot ?? BattleThresholdForLoot;
|
||||
//下面参数固定,只取自动战斗里面的
|
||||
FinishDetectConfig.BattleEndProgressBarColor = autoFightConfig.FinishDetectConfig.BattleEndProgressBarColor;
|
||||
FinishDetectConfig.BattleEndProgressBarColorTolerance = autoFightConfig.FinishDetectConfig.BattleEndProgressBarColorTolerance;
|
||||
|
||||
GuardianAvatar = autoFightConfig.GuardianAvatar;
|
||||
GuardianCombatSkip = autoFightConfig.GuardianCombatSkip;
|
||||
GuardianAvatarHold = autoFightConfig.GuardianAvatarHold;
|
||||
SwimmingEnabled = autoFightConfig.SwimmingEnabled;
|
||||
QinDoublePickUp = autoFightConfig.QinDoublePickUp;
|
||||
ExpBasedPickupEnabled = autoFightConfig.ExpBasedPickupEnabled;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,14 @@ using OpenCvSharp;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using OpenCvSharp;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
{
|
||||
@@ -21,20 +29,20 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
|
||||
public static Task<bool?> MoveForwardAsync(Scalar scalarLower, Scalar scalarHigher, ILogger logger, CancellationToken ct)
|
||||
{
|
||||
var image2 = CaptureToRectArea();
|
||||
Mat mask2 = OpenCvCommonHelper.Threshold(
|
||||
using var image2 = CaptureToRectArea();
|
||||
using Mat mask2 = OpenCvCommonHelper.Threshold(
|
||||
image2.DeriveCrop(0, 0, image2.Width * 1570 / 1920, image2.Height * 970 / 1080).SrcMat,
|
||||
scalarLower,
|
||||
scalarHigher
|
||||
);
|
||||
|
||||
Mat labels2 = new Mat();
|
||||
Mat stats2 = new Mat();
|
||||
Mat centroids2 = new Mat();
|
||||
using Mat labels2 = new Mat();
|
||||
using Mat stats2 = new Mat();
|
||||
using Mat centroids2 = new Mat();
|
||||
|
||||
int numLabels2 = Cv2.ConnectedComponentsWithStats(mask2, labels2, stats2, centroids2, connectivity: PixelConnectivity.Connectivity4, ltype: MatType.CV_32S);
|
||||
|
||||
logger.LogInformation("检测数量:{numLabels2}", numLabels2 - 1);
|
||||
// logger.LogInformation("检测数量:{numLabels2}", numLabels2 - 1);
|
||||
|
||||
if (numLabels2 > 1)
|
||||
{
|
||||
@@ -153,10 +161,12 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
// 非上述区域且非中心区域,判断左右
|
||||
if (firstPixel.X < 920 && height > 6)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
logger.LogInformation("敌人在左侧,不移动");
|
||||
}
|
||||
else if (firstPixel.X > 920 && height > 6)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
logger.LogInformation("敌人在右侧,不移动");
|
||||
}
|
||||
}
|
||||
@@ -165,6 +175,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
{
|
||||
if (height > 6)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
logger.LogInformation("敌人在中心且高度大于6,不移动");
|
||||
}
|
||||
else if (firstPixel.X < 1315 && firstPixel.X > 500 && firstPixel.Y < 800 && height > 2)
|
||||
@@ -189,10 +200,12 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
}
|
||||
else if (height < 3)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
logger.LogInformation("敌人血量高度小于3,不移动");
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
logger.LogInformation("不移动");
|
||||
}
|
||||
}
|
||||
@@ -202,9 +215,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
logger.LogError("无法获取统计信息数组");
|
||||
}
|
||||
}
|
||||
|
||||
mask2.Dispose();
|
||||
labels2.Dispose();
|
||||
|
||||
return Task.FromResult<bool?>(null);
|
||||
}
|
||||
}
|
||||
@@ -213,71 +224,116 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
{
|
||||
public static int RotationCount = 0;
|
||||
|
||||
public static async Task<bool?> SeekAndFightAsync(ILogger logger, int detectDelayTime,int delayTime,CancellationToken ct)
|
||||
private static readonly Dictionary<int, int> RotaryFactorMapping = new Dictionary<int, int> //旋转因子映射表
|
||||
{
|
||||
{ 1, 100 }, { 2, 90 }, { 3, 80}, { 4, 70 }, { 5, 60}, { 6,45 },
|
||||
{ 7, 30 }, { 8, 15 }, { 9, 6 }, { 10, 1 }, { 11,-10 }, { 12,-50 }, { 13, -60 }
|
||||
};
|
||||
|
||||
public static async Task<bool?> SeekAndFightAsync(ILogger logger, int detectDelayTime,int delayTime,CancellationToken ct,bool isEndCheck = false,int rotaryFactor = 6)
|
||||
{
|
||||
Scalar bloodLower = new Scalar(255, 90, 90);
|
||||
int retryCount = 0;
|
||||
|
||||
var adjustedX = RotaryFactorMapping[rotaryFactor];
|
||||
var adjustedDivisor = rotaryFactor<=12 ? 2 : 1.3;
|
||||
|
||||
// Logger.LogInformation("开始寻找敌人 {Text} ...",adjustedX);
|
||||
|
||||
int retryCount = isEndCheck? 1 : 0;
|
||||
|
||||
while (retryCount < 27)
|
||||
while (retryCount < 25+(int)(adjustedX / 5))
|
||||
{
|
||||
var image = CaptureToRectArea();
|
||||
Mat mask = OpenCvCommonHelper.Threshold(image.DeriveCrop(0, 0, 1500, 900).SrcMat, bloodLower);
|
||||
|
||||
Mat labels = new Mat();
|
||||
Mat stats = new Mat();
|
||||
Mat centroids = new Mat();
|
||||
|
||||
int numLabels = Cv2.ConnectedComponentsWithStats(mask, labels, stats, centroids,
|
||||
connectivity: PixelConnectivity.Connectivity4, ltype: MatType.CV_32S);
|
||||
if (retryCount == 0) logger.LogInformation("敌人初检数量: {numLabels}", numLabels - 1);
|
||||
// if (retryCount == 0) logger.LogInformation("敌人初检数量: {numLabels}", numLabels - 1);
|
||||
|
||||
if (numLabels > 1)
|
||||
{
|
||||
logger.LogInformation("检测画面内疑似有敌人,继续战斗...");
|
||||
// logger.LogInformation("检测画面内疑似有敌人,继续战斗...");
|
||||
|
||||
Mat firstRow = stats.Row(1);
|
||||
using Mat firstRow = stats.Row(1);
|
||||
int[] statsArray;
|
||||
bool success = firstRow.GetArray(out statsArray);
|
||||
int height = statsArray[3];
|
||||
logger.LogInformation("敌人血量高度:{height}", height);
|
||||
int x = statsArray[0];
|
||||
// Logger.LogInformation("敌人位置: ({x},血量高度: {height}", x, height);
|
||||
|
||||
image.Dispose();
|
||||
mask.Dispose();
|
||||
labels.Dispose();
|
||||
stats.Dispose();
|
||||
centroids.Dispose();
|
||||
|
||||
if (success && height > 2)
|
||||
if (success)
|
||||
{
|
||||
if (height < 7)
|
||||
if (isEndCheck)
|
||||
{
|
||||
logger.LogInformation("敌人血量高度小于7且大于2,向前移动");
|
||||
Task.Run(() =>
|
||||
await Task.Run(() =>
|
||||
{
|
||||
MoveForwardTask.MoveForwardAsync(bloodLower, bloodLower, logger, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
Task.Delay(1000, ct).Wait();
|
||||
Task.Delay(100, ct).Wait();;
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
}, ct);
|
||||
}
|
||||
return false;
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward);
|
||||
}
|
||||
|
||||
if (height > 2 && height < 7)
|
||||
{
|
||||
// logger.LogInformation("画面内有找到敌人,尝试移动...");
|
||||
Task.Run(() => { MoveForwardTask.MoveForwardAsync(bloodLower, bloodLower, logger, ct); }, ct);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (height > 6 && height < 25)
|
||||
{
|
||||
if ((x == 758 || x == 722) && (height ==7 || height == 8))//固定血条的怪物,尝试旋转寻找
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(960, 0);
|
||||
Task.Delay(200, ct).Wait();
|
||||
Simulation.SendInput.Mouse.MiddleButtonClick();
|
||||
}, ct);
|
||||
}
|
||||
// logger.LogInformation("画面内有找到敌人,继续战斗...");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (height < 3 || height > 25)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (height < 3) return null;
|
||||
}
|
||||
|
||||
if (retryCount == 0)
|
||||
{
|
||||
await Delay(delayTime,ct);
|
||||
Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
|
||||
// Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
|
||||
Logger.LogInformation("打开编队界面检查战斗是否结束");
|
||||
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
|
||||
await Delay(detectDelayTime, ct);
|
||||
var ra3 = CaptureToRectArea();
|
||||
var b33 = ra3.SrcMat.At<Vec3b>(50, 790); // 进度条颜色
|
||||
var whiteTile3 = ra3.SrcMat.At<Vec3b>(50, 768); // 白块
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
ra3.Dispose();
|
||||
|
||||
if (IsWhite(whiteTile3.Item2, whiteTile3.Item1, whiteTile3.Item0) &&
|
||||
IsYellow(b33.Item2, b33.Item1, b33.Item0))
|
||||
{
|
||||
logger.LogInformation("识别到战斗结束");
|
||||
logger.LogInformation("识别到战斗结束-s");
|
||||
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
|
||||
return true;
|
||||
}
|
||||
@@ -292,12 +348,13 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
if (retryCount <= 2)
|
||||
{
|
||||
var offsets = new (int x, int y)[] {
|
||||
(image.Width / 6, -image.Height / 5),
|
||||
(image.Width / 6, image.Height / 7),
|
||||
(image.Width / 6, 0),
|
||||
(image.Width / 6, image.Height / 6)
|
||||
(image.Width / 6, -image.Height / 5),
|
||||
(image.Width / 6, -image.Height),
|
||||
};
|
||||
|
||||
var offsetIndex = RotationCount < 3 ? 0 : (RotationCount == 3) ? 1 : 2;
|
||||
var offsetIndex = RotationCount < 2 ? 0 : (RotationCount == 2) ? 1 : (RotationCount >= 3) ? 2 : 3;
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(offsets[offsetIndex].x, offsets[offsetIndex].y);
|
||||
}
|
||||
else
|
||||
@@ -305,7 +362,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(image.Width / 6, 0);
|
||||
}
|
||||
|
||||
await Task.Delay(50,ct);
|
||||
await Task.Delay(50+(int)(adjustedX/adjustedDivisor),ct);
|
||||
|
||||
image = CaptureToRectArea();
|
||||
mask = OpenCvCommonHelper.Threshold(image.DeriveCrop(0, 0, 1500, 900).SrcMat, bloodLower);
|
||||
@@ -318,34 +375,57 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
|
||||
if (numLabels > 1)
|
||||
{
|
||||
logger.LogInformation("检测敌人第 {retryCount} 次: {numLabels}", retryCount + 1, numLabels - 1);
|
||||
// logger.LogInformation("检测敌人第 {retryCount} 次: {numLabels}", retryCount + 1, numLabels - 1);
|
||||
Mat firstRow2 = stats.Row(1); // 获取第1行(标签1)的数据
|
||||
int[] statsArray2;
|
||||
bool success2 = firstRow2.GetArray(out statsArray2); // 使用 out 参数来接收数组数据
|
||||
int height2 = statsArray2[3];
|
||||
logger.LogInformation("敌人血量高度:{height2}", height2);
|
||||
// logger.LogInformation("敌人血量 :{height2}", height2);
|
||||
|
||||
mask.Dispose();
|
||||
labels.Dispose();
|
||||
stats.Dispose();
|
||||
centroids.Dispose();
|
||||
|
||||
if (success2 && height2 > 2)
|
||||
image.Dispose();
|
||||
|
||||
if (success2)
|
||||
{
|
||||
if (height2 < 7)
|
||||
if (isEndCheck) await Task.Run(() =>
|
||||
{
|
||||
logger.LogInformation("画面内有找到敌人,继续战斗...");
|
||||
Task.Run(() => { MoveForwardTask.MoveForwardAsync(bloodLower, bloodLower, logger, ct); }, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
Task.Delay(100, ct).Wait();
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
}, ct);
|
||||
|
||||
if (height2 > 2 && height2 < 7)
|
||||
{
|
||||
// logger.LogInformation("画面内有找到敌人,尝试移动...");
|
||||
Task.Run(() => { MoveForwardTask.MoveForwardAsync(bloodLower, bloodLower, logger, ct); }, ct);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (height2 > 6 && height2 < 25)
|
||||
{
|
||||
// logger.LogInformation("画面内有找到敌人,继续战斗...");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (height2 < 3 || height2 > 25)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (height2 < 3) return null;
|
||||
|
||||
}
|
||||
|
||||
mask.Dispose();
|
||||
labels.Dispose();
|
||||
stats.Dispose();
|
||||
centroids.Dispose();
|
||||
image.Dispose();
|
||||
|
||||
retryCount++;
|
||||
}
|
||||
|
||||
logger.LogInformation("寻找敌人:{Text}", "无");
|
||||
return null;
|
||||
}
|
||||
@@ -371,103 +451,271 @@ namespace BetterGenshinImpact.GameTask.AutoFight
|
||||
|
||||
public class AutoFightSkill
|
||||
{
|
||||
public static async Task EnsureGuardianSkill(Avatar guardianAvatar, CombatCommand command,string lastFightName,
|
||||
string guardianAvatarName,bool guardianAvatarHold,int retryCount,CancellationToken ct)
|
||||
public static async Task EnsureGuardianSkill(Avatar guardianAvatar, CombatCommand command, string lastFightName,
|
||||
string guardianAvatarName, bool guardianAvatarHold, int retryCount, CancellationToken ct,bool guardianCombatSkip = false,
|
||||
bool burstEnabled = false)
|
||||
{
|
||||
int attempt = 0;
|
||||
|
||||
|
||||
if (guardianAvatar.IsSkillReady())
|
||||
{
|
||||
while (attempt < retryCount)
|
||||
{
|
||||
if (guardianAvatar.TrySwitch(15,false))
|
||||
if (guardianAvatar.TrySwitch(10))
|
||||
{
|
||||
Simulation.ReleaseAllKey();
|
||||
|
||||
await Task.Delay(100, ct);
|
||||
|
||||
guardianAvatar.ManualSkillCd = -1;
|
||||
var cd1 = guardianAvatar.AfterUseSkill();
|
||||
if (cd1 > 0 )
|
||||
if (await AvatarSkillAsync(Logger, guardianAvatar, false, 1, ct))
|
||||
{
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 战技Cd检测:{cd} 秒", guardianAvatarName, guardianAvatar.Name, cd1);
|
||||
guardianAvatar.ManualSkillCd = -1;
|
||||
return;
|
||||
var cd1 = guardianAvatar.AfterUseSkill();
|
||||
if (cd1 > 0)
|
||||
{
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 战技Cd检测:{cd} 秒", guardianAvatarName,
|
||||
guardianAvatar.Name, cd1);
|
||||
guardianAvatar.ManualSkillCd = -1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
guardianAvatar.UseSkill(guardianAvatarHold);
|
||||
Simulation.ReleaseAllKey();
|
||||
await Task.Delay(200, ct);
|
||||
var imageAfterUseSkill = CaptureToRectArea();
|
||||
|
||||
var cd2 = guardianAvatar.AfterUseSkill();
|
||||
if ( cd2 > 0 && guardianAvatar.TrySwitch(4,false))
|
||||
var retry = 50;
|
||||
while (!(await AvatarSkillAsync(Logger, guardianAvatar, false, 1, ct,imageAfterUseSkill)) && retry > 0)
|
||||
{
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 释放战技成功,cd:{cd2} 秒", guardianAvatarName, guardianAvatar.Name, cd2);
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
|
||||
//防止在纳塔飞天或爬墙
|
||||
Simulation.ReleaseAllKey();
|
||||
if (retry % 3 == 0)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
}
|
||||
imageAfterUseSkill = CaptureToRectArea();
|
||||
await Task.Delay(30, ct);
|
||||
// Logger.LogInformation("优先第333 {t}", retry);
|
||||
retry -= 1;
|
||||
}
|
||||
imageAfterUseSkill.Dispose();
|
||||
|
||||
if (retry > 0)
|
||||
{
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 释放战技:{t}",
|
||||
guardianAvatarName, guardianAvatar.Name,"成功");
|
||||
guardianAvatar.LastSkillTime = DateTime.UtcNow;
|
||||
guardianAvatar.ManualSkillCd = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
//新方法法:色块识别,带角色切换确认,不管OCR结果。避免OCR技能CD错误
|
||||
// if (await AvatarSkillAsync(Logger, guardianAvatar,false, 5, ct))
|
||||
// {
|
||||
// guardianAvatar.ManualSkillCd = -1;
|
||||
// return;
|
||||
// }
|
||||
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 释放战技:失败重试 {attempt} 次", guardianAvatarName, guardianAvatar.Name , attempt+1);
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 释放战技:失败重试 {attempt} 次",
|
||||
guardianAvatarName, guardianAvatar.Name, attempt + 1);
|
||||
guardianAvatar.ManualSkillCd = 0;
|
||||
guardianAvatar.UseSkill(guardianAvatarHold);
|
||||
//防止在纳塔飞天或
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
}
|
||||
attempt++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (burstEnabled)
|
||||
{
|
||||
using var image = CaptureToRectArea();
|
||||
if (!guardianAvatar.IsActive(image))
|
||||
{
|
||||
var skillArea = AutoFightAssets.Instance.AvatarQRectListMap[guardianAvatar.Index - 1];//Q技能区域
|
||||
// 首先对图像进行预处理,转为灰度图
|
||||
using var grayImage = image.DeriveCrop(skillArea).SrcMat.CvtColor(ColorConversionCodes.BGR2GRAY);
|
||||
|
||||
//调试用
|
||||
// grayImage.SaveImage("D:\\Images\\grayImage.png");
|
||||
// Cv2.ImShow("灰度图像", grayImage);
|
||||
|
||||
// 计算图像的平均亮度
|
||||
var meanBrightness = Cv2.Mean(grayImage);
|
||||
var avgBrightness = meanBrightness.Val0;
|
||||
// 根据平均亮度动态调整Canny边缘检测的阈值
|
||||
var threshold1 = avgBrightness * 0.9;
|
||||
var threshold2 = avgBrightness * 2;
|
||||
|
||||
// Logger.LogInformation("角色{i} 平均亮度 {avgBrightness}", i, avgBrightness);
|
||||
|
||||
Cv2.Canny(grayImage, grayImage, threshold1: (float)threshold1, threshold2: (float)threshold2); // 边缘检测
|
||||
|
||||
// 使用霍夫变换检测圆形
|
||||
var circles = Cv2.HoughCircles(grayImage, HoughModes.Gradient, dp: 1.2, minDist: 20,
|
||||
param1: 70, param2: 30, minRadius: 25, maxRadius: 34);
|
||||
|
||||
if (circles.Length > 0)
|
||||
{
|
||||
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 元素爆发状态:{attempt},尝试释放",
|
||||
guardianAvatarName, guardianAvatar.Name, "就绪");
|
||||
|
||||
if (guardianAvatar.TrySwitch(8))
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
|
||||
Sleep(500, ct);
|
||||
Simulation.ReleaseAllKey();
|
||||
|
||||
//普攻一下,防止在纳塔飞天
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
using (var imageAfterBurst = CaptureToRectArea())
|
||||
{
|
||||
if (AvatarSkillAsync(Logger, guardianAvatar, true, 1, ct).Result
|
||||
|| !Bv.IsInMainUi(imageAfterBurst)) //Q技能CD(冷却检测)或者不在主界面(大招动画播放中)
|
||||
{
|
||||
guardianAvatar.IsBurstReady = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
Sleep(500, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);//普攻一下,防止在纳塔飞天
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);//尝试再放一次,不检查
|
||||
guardianAvatar.IsBurstReady = true;
|
||||
}
|
||||
Logger.LogInformation("优先第 {guardianAvatarName} 盾奶位 {GuardianAvatar} 释放元素爆发:{text}",
|
||||
guardianAvatarName, guardianAvatar.Name, !guardianAvatar.IsBurstReady ? "成功" : "失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//新方法,备用,非OCR识别,判断色块进行,速度更快
|
||||
//检测技能图标中释放含有白色色块,检测前进行角色切换的确认,skills:false为E技能,true为Q技能(未开发)
|
||||
public static async Task<bool> AvatarSkillAsync(ILogger logger, Avatar guardianAvatar, bool skills , int retryCount, CancellationToken ct)
|
||||
//检测技能图标中释放含有白色色块,检测前进行角色切换的确认,skills:false为E技能,true为Q技能
|
||||
/// <summary>
|
||||
/// 检测角色技能冷却状态
|
||||
/// </summary>
|
||||
/// <param name="logger">日志记录器</param>
|
||||
/// <param name="guardianAvatar">角色对象</param>
|
||||
/// <param name="skills">技能类型,false为E技能,true为Q技能</param>
|
||||
/// <param name="retryCount">重试次数</param>
|
||||
/// <param name="ct">取消令牌</param>
|
||||
/// <param name="image">图像对象</param>
|
||||
/// <param name="needLog">是否需要日志输出</param>
|
||||
/// <param name="isResetCd">是否重置技能冷却状态</param>
|
||||
/// <returns>技能是否就绪</returns>
|
||||
public static async Task<bool> AvatarSkillAsync(ILogger logger, Avatar guardianAvatar, bool skills , int retryCount,
|
||||
CancellationToken ct,ImageRegion? image = null,bool needLog = false, bool isResetCd = false)
|
||||
{
|
||||
if (guardianAvatar.TrySwitch())
|
||||
{
|
||||
Scalar bloodLower = new Scalar(255, 255, 255);
|
||||
int attempt = 0;
|
||||
var model = image is null;
|
||||
|
||||
while (attempt < retryCount)
|
||||
{
|
||||
var image2 = CaptureToRectArea();
|
||||
using var image2 = model ? CaptureToRectArea() : image ?? CaptureToRectArea();
|
||||
|
||||
var skillAra = skills
|
||||
? new Rect(image2.Width * 1700 / 1920, image2.Height * 996 / 1080,
|
||||
image2.Width * 12 / 1920, image2.Height * 7 / 1080) //E技能区域
|
||||
// var image2 = CaptureToRectArea();
|
||||
|
||||
var skillAra = !skills
|
||||
? new Rect(image2.Width * 1688 / 1920, image2.Height * 988 / 1080,
|
||||
image2.Width * 22 / 1920, image2.Height * 12 / 1080) //E技能区域
|
||||
|
||||
: new Rect(image2.Width * 1819 / 1920, image2.Height * 977 / 1080,
|
||||
image2.Width * 13 / 1920, image2.Height * 6 / 1080); //Q技能区域
|
||||
: new Rect(image2.Width * 1809 / 1920, image2.Height * 968 / 1080,
|
||||
image2.Width * 30 / 1920, image2.Height * 15 / 1080); //Q技能区域
|
||||
|
||||
var mask2 = OpenCvCommonHelper.Threshold(
|
||||
using var mask2 = OpenCvCommonHelper.Threshold(
|
||||
image2.DeriveCrop(skillAra).SrcMat,
|
||||
bloodLower,
|
||||
bloodLower
|
||||
);
|
||||
|
||||
var labels2 = new Mat();
|
||||
var stats2 = new Mat();
|
||||
var centroids2 = new Mat();
|
||||
using var labels2 = new Mat();
|
||||
using var stats2 = new Mat();
|
||||
using var centroids2 = new Mat();
|
||||
|
||||
int numLabels2 = Cv2.ConnectedComponentsWithStats(mask2, labels2, stats2, centroids2,
|
||||
connectivity: PixelConnectivity.Connectivity4, ltype: MatType.CV_32S);
|
||||
|
||||
logger.LogInformation("盾奶位 {guardianAvatar.Name} 战技状态:{text}", guardianAvatar.Name , numLabels2 > 1 ? "已释放" : "未释放");
|
||||
|
||||
if (numLabels2 > 1)
|
||||
if (model) image2.Dispose();
|
||||
|
||||
if (needLog) Logger.LogInformation("技能状态:{guardianAvatar.Name} - {skills} 状态 {text}",
|
||||
guardianAvatar.Name, skills?"Q技能":"E技能", numLabels2 > 1?"冷却中":"就绪");
|
||||
|
||||
// Logger.LogInformation("技能状态:{numLabels2} 数量", numLabels2);
|
||||
if (numLabels2 > 2)
|
||||
{
|
||||
if (!isResetCd)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (skills)
|
||||
{
|
||||
guardianAvatar.IsBurstReady = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
guardianAvatar.ManualSkillCd = 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
attempt++;
|
||||
await Task.Delay(100, ct);
|
||||
if (retryCount > 1) await Task.Delay(100, ct);
|
||||
}
|
||||
}
|
||||
guardianAvatar.AfterUseSkill();
|
||||
|
||||
if (!isResetCd)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (skills)
|
||||
{
|
||||
guardianAvatar.IsBurstReady = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
guardianAvatar.AfterUseSkill();
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
//全队Q检测函数,备用,后续可用于自动EQ开发
|
||||
public static Task<List<int>> AvatarQSkillAsync(ImageRegion? image = null, List<int>? useEqList = null,int? avatarCurrent = null)
|
||||
{
|
||||
image ??= CaptureToRectArea();
|
||||
image.SrcMat.ConvertTo(image.SrcMat, MatType.CV_8UC3, alpha: 2, beta: -200); // 增加亮度和对比度
|
||||
var useMedicine = new List<int>();
|
||||
var eqList = useEqList ?? new List<int> { 1, 2, 3, 4 };
|
||||
|
||||
foreach (var i in eqList)
|
||||
{
|
||||
var skillArea = i != avatarCurrent ? AutoFightAssets.Instance.AvatarQRectListMap[i - 1]: new Rect(1762, 915, 114, 111);
|
||||
|
||||
using var grayImage = image.DeriveCrop(skillArea).SrcMat.CvtColor(ColorConversionCodes.BGR2GRAY);
|
||||
|
||||
var meanBrightness = Cv2.Mean(grayImage);
|
||||
var avgBrightness = meanBrightness.Val0;
|
||||
var threshold1 = avgBrightness * 0.9;
|
||||
var threshold2 = avgBrightness * 2;
|
||||
|
||||
Cv2.Canny(grayImage, grayImage, threshold1: (float)threshold1, threshold2: (float)threshold2);
|
||||
|
||||
var circles = Cv2.HoughCircles(grayImage, HoughModes.Gradient, dp: 1.2, minDist: 20,
|
||||
param1: 90, param2:i != avatarCurrent ? 25 : 35, minRadius: i != avatarCurrent ? 25 : 50, maxRadius:i != avatarCurrent ? 34 : 60);
|
||||
|
||||
if (circles.Length > 0)
|
||||
{
|
||||
useMedicine.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
image.Dispose();
|
||||
|
||||
if (useMedicine.Count > 0)
|
||||
{
|
||||
Logger.LogInformation("元素爆发 {text} 的角色序号:{useMedicine}", "就绪", useMedicine);
|
||||
return Task.FromResult(useMedicine);
|
||||
}
|
||||
|
||||
return Task.FromResult(new List<int>());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
@@ -13,13 +13,19 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
using OpenCvSharp;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Vanara;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
using BetterGenshinImpact.GameTask.AutoPick.Assets;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
@@ -38,11 +44,18 @@ public class AutoFightTask : ISoloTask
|
||||
private DateTime _lastFightFlagTime = DateTime.Now; // 战斗标志最近一次出现的时间
|
||||
|
||||
private readonly double _dpi = TaskContext.Instance().DpiScale;
|
||||
|
||||
public static OtherConfig Config { get; set; } = TaskContext.Instance().Config.OtherConfig;
|
||||
|
||||
public static bool FightStatusFlag { get; set; } = false;
|
||||
|
||||
private static readonly object PickLock = new object();
|
||||
|
||||
private readonly double _assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
|
||||
private readonly ReturnMainUiTask _returnMainUiTask = new();
|
||||
|
||||
// 战斗点位
|
||||
public static WaypointForTrack? FightWaypoint {get; set;} = null;
|
||||
|
||||
private class TaskFightFinishDetectConfig
|
||||
{
|
||||
public int DelayTime = 1500;
|
||||
@@ -279,11 +292,24 @@ public class AutoFightTask : ISoloTask
|
||||
//所有角色是否都可被跳过
|
||||
var allCanBeSkipped = commandAvatarNames.All(a => canBeSkippedAvatarNames.Contains(a));
|
||||
|
||||
var delayTime = _finishDetectConfig.DelayTime;
|
||||
var detectDelayTime = _finishDetectConfig.DetectDelayTime;
|
||||
|
||||
//盾奶优先功能角色预处理
|
||||
var guardianAvatar = string.IsNullOrWhiteSpace(_taskParam.GuardianAvatar) ? null : combatScenes.SelectAvatar(int.Parse(_taskParam.GuardianAvatar));
|
||||
|
||||
AutoFightSeek.RotationCount= 0; // 重置旋转次数
|
||||
|
||||
// 基于经验值的战后拾取检测:在战斗过程中异步检测精英怪经验值图标
|
||||
// 仅在万叶拾取总开关开启时才启动经验值检测
|
||||
ExperienceDetector? expDetector = null;
|
||||
if (_taskParam.KazuhaPickupEnabled && _taskParam.ExpBasedPickupEnabled)
|
||||
{
|
||||
var expRos = AutoFightAssets.Instance.ExperienceRecognitionObjects;
|
||||
expDetector = new ExperienceDetector(expRos, cts2.Token);
|
||||
expDetector.Start();
|
||||
}
|
||||
|
||||
// 战斗操作
|
||||
var fightTask = Task.Run(async () =>
|
||||
{
|
||||
@@ -322,13 +348,23 @@ public class AutoFightTask : ISoloTask
|
||||
|
||||
#region 盾奶位技能优先功能
|
||||
|
||||
var skipModel = _taskParam.SkipModel? (guardianAvatar != null) : (guardianAvatar != null && lastFightName != command.Name);
|
||||
if (skipModel) await AutoFightSkill.EnsureGuardianSkill(guardianAvatar,lastCommand,lastFightName,_taskParam.GuardianAvatar,_taskParam.GuardianAvatarHold,5,ct);
|
||||
var skipModel = guardianAvatar != null && lastFightName != command.Name;
|
||||
if (skipModel) await AutoFightSkill.EnsureGuardianSkill(guardianAvatar,lastCommand,lastFightName,
|
||||
_taskParam.GuardianAvatar,_taskParam.GuardianAvatarHold,5,ct,_taskParam.GuardianCombatSkip,_taskParam.BurstEnabled);
|
||||
var avatar = combatScenes.SelectAvatar(command.Name);
|
||||
|
||||
#endregion
|
||||
|
||||
if (avatar is null || (avatar.Name == guardianAvatar?.Name && _taskParam.GuardianCombatSkip))
|
||||
#region 初始寻敌处理
|
||||
|
||||
if ( _finishDetectConfig.RotateFindEnemyEnabled && i == 0 && _taskParam.IsFirstCheck)
|
||||
{
|
||||
await AutoFightSeek.SeekAndFightAsync(Logger, detectDelayTime, delayTime, ct,true,_taskParam.RotaryFactor);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
if (avatar is null || (avatar.Name == guardianAvatar?.Name && (_taskParam.GuardianCombatSkip || _taskParam.BurstEnabled)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -386,14 +422,28 @@ public class AutoFightTask : ISoloTask
|
||||
timeOutFlag = true;
|
||||
break;
|
||||
}
|
||||
|
||||
command.Execute(combatScenes);
|
||||
|
||||
#region Q前寻敌处理
|
||||
if (_finishDetectConfig.RotateFindEnemyEnabled && _taskParam.CheckBeforeBurst && (command.Method == Method.Burst || command.Args.Contains("q") || command.Args.Contains("Q")))
|
||||
{
|
||||
fightEndFlag = await CheckFightFinish(delayTime, detectDelayTime);
|
||||
}
|
||||
#endregion
|
||||
|
||||
command.Execute(combatScenes, lastCommand);
|
||||
//统计战斗人次
|
||||
if (i == combatCommands.Count - 1 || command.Name != combatCommands[i + 1].Name)
|
||||
{
|
||||
countFight++;
|
||||
}
|
||||
|
||||
#region check动作触发战斗结束检测
|
||||
if (command.Method == Method.Check)
|
||||
{
|
||||
fightEndFlag = await CheckFightFinish(delayTime, detectDelayTime);
|
||||
}
|
||||
#endregion
|
||||
|
||||
lastFightName = command.Name;
|
||||
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true })
|
||||
{
|
||||
@@ -408,12 +458,11 @@ public class AutoFightTask : ISoloTask
|
||||
))
|
||||
{
|
||||
checkFightFinishStopwatch.Restart();
|
||||
var delayTime = _finishDetectConfig.DelayTime;
|
||||
var detectDelayTime = _finishDetectConfig.DetectDelayTime;
|
||||
|
||||
if (_finishDetectConfig.DelayTimes.TryGetValue(command.Name, out var time))
|
||||
{
|
||||
delayTime = time;
|
||||
Logger.LogInformation($"{command.Name}结束后,延时检查为{delayTime}毫秒");
|
||||
// Logger.LogInformation($"{command.Name}结束后,延时检查为{delayTime}毫秒");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -451,6 +500,50 @@ public class AutoFightTask : ISoloTask
|
||||
}, cts2.Token);
|
||||
|
||||
await fightTask;
|
||||
|
||||
try
|
||||
{
|
||||
// 基于经验值检测结果的拾取判断
|
||||
if (_taskParam.KazuhaPickupEnabled && _taskParam.ExpBasedPickupEnabled && expDetector != null)
|
||||
{
|
||||
// 战斗结束与怪物死亡可能几乎同时发生,检测器可能还没来得及捕获经验值图标
|
||||
// 保持检测器运行,每 100ms 轮询一次结果,最多等待 1.1 秒
|
||||
if (!expDetector.HasDetectedExperience)
|
||||
{
|
||||
Logger.LogInformation("基于经验值判断:等待经验值检测结果");
|
||||
var waitMs = 1100;
|
||||
while (!expDetector.HasDetectedExperience && waitMs > 0)
|
||||
{
|
||||
await Delay(100, ct);
|
||||
waitMs -= 100;
|
||||
}
|
||||
}
|
||||
|
||||
await expDetector.StopAsync();
|
||||
var shouldPickup = expDetector.HasDetectedExperience;
|
||||
Logger.LogInformation("基于经验值判断:{Result} 战后拾取", shouldPickup ? "执行" : "不执行");
|
||||
|
||||
if (!shouldPickup)
|
||||
{
|
||||
// 经验值检测未通过,跳过拾取(但仍执行扫描拾取逻辑)
|
||||
if (_taskParam is { PickDropsAfterFightEnabled: true })
|
||||
{
|
||||
await new ScanPickTask().Start(ct);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 确保检测器在任何路径(异常/取消/正常)都被停止和释放
|
||||
if (expDetector != null)
|
||||
{
|
||||
await expDetector.StopAsync();
|
||||
expDetector.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
if (_taskParam.BattleThresholdForLoot>=2 && countFight < _taskParam.BattleThresholdForLoot)
|
||||
{
|
||||
Logger.LogInformation($"战斗人次({countFight})低于配置人次({_taskParam.BattleThresholdForLoot}),跳过此次拾取!");
|
||||
@@ -460,11 +553,95 @@ public class AutoFightTask : ISoloTask
|
||||
if (_taskParam.KazuhaPickupEnabled)
|
||||
{
|
||||
// 队伍中存在万叶的时候使用一次长E
|
||||
var kazuha = combatScenes.SelectAvatar("枫原万叶");
|
||||
var picker = combatScenes.SelectAvatar("枫原万叶") ?? combatScenes.SelectAvatar("琴");
|
||||
|
||||
var oldPartyName = RunnerContext.Instance.PartyName;
|
||||
string? oldPartyName = null;
|
||||
if (RunnerContext.Instance.PartyName is not null)
|
||||
{
|
||||
oldPartyName = RunnerContext.Instance.PartyName;
|
||||
}
|
||||
else if(picker is null && !string.IsNullOrEmpty(_taskParam.KazuhaPartyName))
|
||||
{
|
||||
Logger.LogWarning("换队拾取:当前队伍名称为空,尝试读取!");
|
||||
await Delay(1000, ct);
|
||||
await _returnMainUiTask.Start(ct);
|
||||
|
||||
for (int attempt = 0; attempt < 6; attempt++)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
|
||||
var enterGameAppear = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PartyBtnChooseView,
|
||||
() => { },
|
||||
ct,
|
||||
15,
|
||||
500
|
||||
);
|
||||
if(attempt == 5 && !enterGameAppear)
|
||||
{
|
||||
Logger.LogWarning("换队拾取:读取队伍名称失败,跳过换队拾取步骤");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(_taskParam.KazuhaPartyName)){
|
||||
await Delay(1000, ct);
|
||||
|
||||
//等待寻找2秒队伍按钮出现
|
||||
var timeWaitStart = 0;
|
||||
while(timeWaitStart < 6000)
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
var partyViewBtn = ra.Find(ElementAssets.Instance.PartyBtnChooseView);
|
||||
if (partyViewBtn.IsExist())
|
||||
{
|
||||
// OCR 当前队伍名称(无法单字,中间禁止空格)
|
||||
// 读取OCR原始识别文本
|
||||
var rawPartyName = ra.Find(new RecognitionObject
|
||||
{
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect(partyViewBtn.Right, partyViewBtn.Top, (int)(350 * _assetScale),
|
||||
partyViewBtn.Height)
|
||||
}).Text;
|
||||
|
||||
// 核心处理逻辑:1.空值兜底 2.去首尾空白 3.移除末尾的“口”字(仅最后一个是口才删)
|
||||
if (string.IsNullOrWhiteSpace(rawPartyName))
|
||||
{
|
||||
oldPartyName = string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
//有概率把编辑图标识别为字符,并且含有空格或换行符,需要过滤
|
||||
var tempName = rawPartyName
|
||||
.Replace("\"", "") // 移除所有双引号(核心新增,解决日志里的""问题)
|
||||
.Replace("\r\n", "") // 清理Windows换行符
|
||||
.Replace("\r", ""); // 先清理所有双引号,避免引号干扰后续处理
|
||||
|
||||
// 核心逻辑:找到第一个换行符(\n)的位置,截断并删除换行+后面所有字符
|
||||
int firstNewLineIndex = tempName.IndexOf('\n');
|
||||
if (firstNewLineIndex != -1) // 存在换行符,截取到换行符前
|
||||
{
|
||||
tempName = tempName.Substring(0, firstNewLineIndex);
|
||||
}
|
||||
|
||||
// 最后统一去首尾所有空白(空格、制表符、回车符\r等),得到纯净队伍名
|
||||
oldPartyName = tempName.Trim();
|
||||
}
|
||||
|
||||
// 后续原有逻辑不变
|
||||
Logger.LogInformation("换队拾取:当前队伍名称读取为:{oldPartyName}", oldPartyName);
|
||||
// 加在rawPartyName赋值后,打印原始文本的“原始形态”(转义符会显示)
|
||||
Logger.LogDebug("OCR原始识别文本(含转义):{rawPartyName}", rawPartyName);
|
||||
RunnerContext.Instance.PartyName = oldPartyName;
|
||||
// await _returnMainUiTask.Start(ct);
|
||||
break;
|
||||
}
|
||||
await Delay(200, ct);
|
||||
timeWaitStart += 200;
|
||||
}
|
||||
}
|
||||
|
||||
var switchPartyFlag = false;
|
||||
if (kazuha == null && !timeOutFlag &&!string.IsNullOrEmpty(_taskParam.KazuhaPartyName) && oldPartyName != _taskParam.KazuhaPartyName)
|
||||
if (picker == null && !timeOutFlag &&!string.IsNullOrEmpty(_taskParam.KazuhaPartyName) && oldPartyName != _taskParam.KazuhaPartyName)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -477,7 +654,7 @@ public class AutoFightTask : ISoloTask
|
||||
RunnerContext.Instance.PartyName = _taskParam.KazuhaPartyName;
|
||||
RunnerContext.Instance.ClearCombatScenes();
|
||||
var cs = await RunnerContext.Instance.GetCombatScenes(ct);
|
||||
kazuha = cs.SelectAvatar("枫原万叶");
|
||||
picker = cs.SelectAvatar("枫原万叶") ?? cs.SelectAvatar("琴");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -486,28 +663,105 @@ public class AutoFightTask : ISoloTask
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (kazuha != null)
|
||||
if (picker != null)
|
||||
{
|
||||
var time = TimeSpan.FromSeconds(kazuha.GetSkillCdSeconds());
|
||||
//当万叶cd大于3时,此时不再触发万叶拾取,
|
||||
if (!(lastFightName == "枫原万叶" && time.TotalSeconds > 3))
|
||||
if (picker.Name == "枫原万叶")
|
||||
{
|
||||
Logger.LogInformation("使用枫原万叶长E拾取掉落物");
|
||||
await Delay(300, ct);
|
||||
if (kazuha.TrySwitch())
|
||||
var time = TimeSpan.FromSeconds(picker.GetSkillCdSeconds());
|
||||
|
||||
// 如果配置了二次拾取,或者不满足跳过条件(上次是万叶且冷却时间>3秒),则执行拾取
|
||||
bool shouldSkip = lastFightName == picker.Name && time.TotalSeconds > 3;
|
||||
bool forcePickup = _taskParam.QinDoublePickUp;
|
||||
|
||||
if (forcePickup || !shouldSkip)
|
||||
{
|
||||
await kazuha.WaitSkillCd(ct);
|
||||
kazuha.UseSkill(true);
|
||||
await Task.Delay(100);
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
await Delay(1500, ct);
|
||||
Logger.LogInformation("使用 枫原万叶-长E 拾取掉落物");
|
||||
await Delay(200, ct);
|
||||
if (picker.TrySwitch(10))
|
||||
{
|
||||
await picker.WaitSkillCd(ct);
|
||||
picker.UseSkill(true);
|
||||
await Delay(50, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
await Delay(1500, ct);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("距最近一次万叶出招,时间过短,跳过此次万叶拾取!");
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (picker.Name == "琴")
|
||||
{
|
||||
Logger.LogInformation("距最近一次万叶出招,时间过短,跳过此次万叶拾取!");
|
||||
Logger.LogInformation("使用 琴-长E 拾取掉落物");
|
||||
|
||||
var actionsToUse = PickUpCollectHandler.PickUpActions
|
||||
.Where(action => action.StartsWith("琴-长E" + " ", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(action => action.Replace("琴-长E","琴", StringComparison.OrdinalIgnoreCase))
|
||||
.ToArray();
|
||||
|
||||
var find = _taskParam.QinDoublePickUp;
|
||||
await Delay(150, ct);
|
||||
if (picker.TrySwitch(10))
|
||||
{
|
||||
foreach (var miningActionStr in actionsToUse)
|
||||
{
|
||||
var pickUpAction = CombatScriptParser.ParseContext(miningActionStr);
|
||||
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
await picker.WaitSkillCd(ct);
|
||||
foreach (var command in pickUpAction.CombatCommands)
|
||||
{
|
||||
command.Execute(combatScenes);
|
||||
//异步执行,防止卡顿
|
||||
Task.Run(() =>
|
||||
{
|
||||
if (Monitor.TryEnter(PickLock))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (find)
|
||||
{
|
||||
using (var imagePick = CaptureToRectArea())
|
||||
{
|
||||
if (imagePick.Find(AutoPickAssets.Instance.PickRo).IsExist())
|
||||
{
|
||||
find = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Monitor.Exit(PickLock);
|
||||
}
|
||||
}
|
||||
// 后面没代码了,不用写return?
|
||||
});
|
||||
}
|
||||
|
||||
if (!find)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (i == 0)
|
||||
{
|
||||
Logger.LogInformation("自动拾取;尝试再次执行 琴-长E 拾取");
|
||||
// picker.LastSkillTime = DateTime.Now;不正确
|
||||
picker.AfterUseSkill();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//切换过队伍的,需要再切回来
|
||||
@@ -537,7 +791,7 @@ public class AutoFightTask : ISoloTask
|
||||
|
||||
if (_taskParam is { PickDropsAfterFightEnabled: true } )
|
||||
{
|
||||
// 执行自动拾取掉落物的功能
|
||||
// 执行扫描掉落物光柱并靠近的功能
|
||||
await new ScanPickTask().Start(ct);
|
||||
}
|
||||
}
|
||||
@@ -581,12 +835,13 @@ public class AutoFightTask : ISoloTask
|
||||
|
||||
if (!_finishDetectConfig.RotateFindEnemyEnabled)await Delay(delayTime, _ct);
|
||||
|
||||
Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
|
||||
// Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
|
||||
Logger.LogInformation("打开编队界面检查战斗是否结束");
|
||||
// 最终方案确认战斗结束
|
||||
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
|
||||
await Delay(detectDelayTime, _ct);
|
||||
|
||||
var ra = CaptureToRectArea();
|
||||
using var ra = CaptureToRectArea();
|
||||
//判断整个界面是否有红色色块,如果有,则战继续,否则战斗结束
|
||||
// 只提取橙色
|
||||
|
||||
@@ -604,8 +859,9 @@ public class AutoFightTask : ISoloTask
|
||||
return true;
|
||||
}
|
||||
|
||||
Logger.LogInformation($"未识别到战斗结束yellow{b3.Item0},{b3.Item1},{b3.Item2}");
|
||||
Logger.LogInformation($"未识别到战斗结束white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
|
||||
// Logger.LogInformation($"未识别到战斗结束yellow{b3.Item0},{b3.Item1},{b3.Item2}");
|
||||
// Logger.LogInformation($"未识别到战斗结束white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
|
||||
Logger.LogInformation($"未识别到战斗结束: yellow{b3.Item0},{b3.Item1},{b3.Item2};white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
|
||||
|
||||
if (_finishDetectConfig.RotateFindEnemyEnabled)
|
||||
{
|
||||
@@ -708,4 +964,4 @@ public class AutoFightTask : ISoloTask
|
||||
// // 要大于 gadgetMat 的 1/2
|
||||
// return list.Any(r => r.Width > gadgetMat.Width / 2 && r.Height > gadgetMat.Height / 2);
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
/// <summary>
|
||||
/// 经验值检测器:在战斗过程中异步检测屏幕上怪物死亡时掉落的经验值数字图标,
|
||||
/// 用于判断是否有精英怪被击杀,从而决定战后是否执行拾取。
|
||||
/// </summary>
|
||||
public sealed class ExperienceDetector : IDisposable
|
||||
{
|
||||
private static readonly ILogger Logger = TaskControl.Logger;
|
||||
|
||||
/// <summary>
|
||||
/// 经验值图标左侧特征像素的水平偏移量(相对于模板匹配位置)
|
||||
/// </summary>
|
||||
private const int ExpIconPixelOffsetX = -147;
|
||||
|
||||
/// <summary>
|
||||
/// 经验值图标特征颜色 BGR 范围(用于二次验证模板匹配结果)
|
||||
/// </summary>
|
||||
private static readonly Vec3b ExpColorMin = new(200, 200, 150);
|
||||
private static readonly Vec3b ExpColorMax = new(255, 255, 200);
|
||||
|
||||
/// <summary>
|
||||
/// 检测循环间隔(毫秒)
|
||||
/// </summary>
|
||||
private const int DetectionIntervalMs = 100;
|
||||
|
||||
private readonly IReadOnlyList<RecognitionObject> _experienceRos;
|
||||
private readonly CancellationTokenSource _linkedCts;
|
||||
private readonly TaskCompletionSource<bool> _resultTcs;
|
||||
private Task? _detectionTask;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// 获取检测结果:是否检测到经验值图标
|
||||
/// </summary>
|
||||
public bool HasDetectedExperience =>
|
||||
_resultTcs.Task.IsCompletedSuccessfully && _resultTcs.Task.Result;
|
||||
|
||||
public ExperienceDetector(
|
||||
IReadOnlyList<RecognitionObject> experienceRos,
|
||||
CancellationToken externalToken)
|
||||
{
|
||||
_experienceRos = experienceRos ?? throw new ArgumentNullException(nameof(experienceRos));
|
||||
_linkedCts = CancellationTokenSource.CreateLinkedTokenSource(externalToken);
|
||||
_resultTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动后台经验值检测循环
|
||||
/// </summary>
|
||||
public void
|
||||
Start()
|
||||
{
|
||||
if (_experienceRos.Count == 0)
|
||||
{
|
||||
Logger.LogWarning("经验值检测:无可用模板,跳过检测");
|
||||
return;
|
||||
}
|
||||
|
||||
_detectionTask = Task.Run(() => DetectionLoop(_linkedCts.Token), _linkedCts.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止检测并等待后台任务结束
|
||||
/// </summary>
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_linkedCts.Cancel();
|
||||
if (_detectionTask != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _detectionTask.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 正常取消,忽略
|
||||
}
|
||||
}
|
||||
|
||||
// 确保结果有值(未检测到时设为 false)
|
||||
_resultTcs.TrySetResult(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 后台检测循环:截屏 → 模板匹配 → 像素颜色验证
|
||||
/// </summary>
|
||||
private void DetectionLoop(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var capture = TaskControl.CaptureToRectArea();
|
||||
|
||||
foreach (var ro in _experienceRos)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var matchResult = capture.Find(ro);
|
||||
if (!matchResult.IsExist())
|
||||
continue;
|
||||
|
||||
// 模板匹配成功,执行像素颜色二次验证
|
||||
if (ValidateExpPixelColor(capture, matchResult))
|
||||
{
|
||||
Logger.LogInformation("基于经验值判断:检测到 {Name} 经验值图标,启用战后拾取", ro.Name.Replace("Experience_", ""));
|
||||
_resultTcs.TrySetResult(true);
|
||||
return; // 检测到后退出循环
|
||||
}
|
||||
}
|
||||
|
||||
// 短暂等待后继续下一轮检测
|
||||
Thread.Sleep(DetectionIntervalMs);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "经验值检测循环中发生异常,继续下一轮");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 像素颜色验证:检查匹配位置左侧偏移处的像素是否符合经验值图标特征色
|
||||
/// </summary>
|
||||
private static bool ValidateExpPixelColor(ImageRegion capture, Region matchResult)
|
||||
{
|
||||
var checkX = matchResult.X + ExpIconPixelOffsetX;
|
||||
var checkY = matchResult.Y;
|
||||
|
||||
// 边界检查
|
||||
if (checkX < 0 || checkX >= capture.SrcMat.Cols || checkY < 0 || checkY >= capture.SrcMat.Rows)
|
||||
return false;
|
||||
|
||||
var pixel = capture.SrcMat.At<Vec3b>(checkY, checkX);
|
||||
return pixel[0] >= ExpColorMin[0] && pixel[0] <= ExpColorMax[0] // B
|
||||
&& pixel[1] >= ExpColorMin[1] && pixel[1] <= ExpColorMax[1] // G
|
||||
&& pixel[2] >= ExpColorMin[2] && pixel[2] <= ExpColorMax[2]; // R
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
_linkedCts.Cancel();
|
||||
_linkedCts.Dispose();
|
||||
_resultTcs.TrySetResult(false);
|
||||
_detectionTask = null;
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
@@ -83,8 +87,19 @@ public class Avatar
|
||||
/// </summary>
|
||||
public CombatScenes CombatScenes { get; set; }
|
||||
|
||||
public static string? LastActiveAvatar { get; internal set; } = null;
|
||||
/// <summary>
|
||||
/// 脱困方向数组(前/后/左/右)
|
||||
/// </summary>
|
||||
private static readonly GIActions[] UnstuckDirections =
|
||||
{
|
||||
GIActions.MoveForward,
|
||||
GIActions.MoveBackward,
|
||||
GIActions.MoveLeft,
|
||||
GIActions.MoveRight
|
||||
};
|
||||
|
||||
private static readonly Random UnstuckRandom = new();
|
||||
|
||||
|
||||
public Avatar(CombatScenes combatScenes, string name, int index, Rect nameRect, double manualSkillCd = -1)
|
||||
{
|
||||
@@ -115,6 +130,75 @@ public class Avatar
|
||||
Sleep(600, ct);
|
||||
TpForRecover(ct, new RetryException("检测到复苏界面,存在角色被击败,前往七天神像复活"));
|
||||
}
|
||||
else if(AutoFightParam.SwimmingEnabled && AutoFightTask.FightStatusFlag && SwimmingConfirm(region))
|
||||
{
|
||||
if (AutoFightTask.FightWaypoint is not null)
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
if (!SwimmingConfirm(ra)) //二次确认
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("游泳检测:尝试回到战斗地点");
|
||||
var cts = new CancellationTokenSource();
|
||||
var pathExecutor = new PathExecutor(cts.Token);
|
||||
|
||||
try
|
||||
{
|
||||
pathExecutor.FaceTo(AutoFightTask.FightWaypoint).Wait(2000,cts.Token);
|
||||
AutoFightTask.FightWaypoint.MoveMode = MoveModeEnum.Fly.Code; // 改为跳飞
|
||||
Simulation.SendInput.Mouse.RightButtonDown();
|
||||
pathExecutor.MoveTo(AutoFightTask.FightWaypoint).Wait(15000,cts.Token);
|
||||
cts.Cancel();
|
||||
AutoFightTask.FightWaypoint = null;
|
||||
Simulation.SendInput.Mouse.RightButtonUp();
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
Logger.LogError("游泳检测:回到战斗地点任务被取消");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "游泳检测:回到战斗地点异常");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
|
||||
using var bitmap2 = CaptureToRectArea();
|
||||
if (!SwimmingConfirm(bitmap2))
|
||||
{
|
||||
Logger.LogInformation("游泳检测:游泳脱困成功");
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogWarning("游泳检测:回到战斗地点失败");
|
||||
}
|
||||
|
||||
Logger.LogWarning("战斗过程检测到游泳,前往七天神像重试");
|
||||
TpForRecover(ct, new RetryException("战斗过程检测到游泳,前往七天神像重试"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 游泳检测(色块连通性检测)
|
||||
/// 游泳时右下角会出现鼠标图标,带有黄色色块,不受改按键影响
|
||||
/// </summary>
|
||||
private static bool SwimmingConfirm(Region region)
|
||||
{
|
||||
using var imageRegion = region.ToImageRegion();
|
||||
using var cropped = imageRegion.DeriveCrop(1819, 1025, 9, 11);
|
||||
using var mask = OpenCvCommonHelper.Threshold(cropped.SrcMat, new Scalar(242, 223, 39), new Scalar(255, 233, 44));
|
||||
using var labels = new Mat();
|
||||
using var stats = new Mat();
|
||||
using var centroids = new Mat();
|
||||
|
||||
var numLabels = Cv2.ConnectedComponentsWithStats(mask, labels, stats, centroids,
|
||||
connectivity: PixelConnectivity.Connectivity4, ltype: MatType.CV_32S);
|
||||
|
||||
return numLabels > 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -138,6 +222,7 @@ public class Avatar
|
||||
/// </summary>
|
||||
public void Switch()
|
||||
{
|
||||
var context = new AvatarActiveCheckContext();
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
if (Ct is { IsCancellationRequested: true })
|
||||
@@ -145,41 +230,25 @@ public class Avatar
|
||||
return;
|
||||
}
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
using var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
|
||||
// 切换成功
|
||||
if (CombatScenes.GetActiveAvatarIndex(region, context) == Index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
switch (Index)
|
||||
{
|
||||
case 1:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
|
||||
break;
|
||||
case 2:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
|
||||
break;
|
||||
case 3:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
|
||||
break;
|
||||
case 4:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
|
||||
break;
|
||||
case 5:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
Offset60Fix(i);
|
||||
|
||||
SimulateSwitchAction(Index);
|
||||
// Debug.WriteLine($"切换到{Index}号位");
|
||||
// Cv2.ImWrite($"log/切换.png", region.SrcMat);
|
||||
|
||||
// 第13次重试时,战斗状态下执行脱困动作
|
||||
if (i == 10 && AutoFightTask.FightStatusFlag)
|
||||
{
|
||||
PerformUnstuckAction(Ct);
|
||||
}
|
||||
|
||||
Sleep(250, Ct);
|
||||
}
|
||||
}
|
||||
@@ -190,8 +259,9 @@ public class Avatar
|
||||
/// <param name="tryTimes"></param>
|
||||
/// <param name="needLog"></param>
|
||||
/// <returns></returns>
|
||||
public bool TrySwitch(int tryTimes = 4, bool needLog = true)
|
||||
public bool TrySwitch(int tryTimes = 4)
|
||||
{
|
||||
var context = new AvatarActiveCheckContext();
|
||||
for (var i = 0; i < tryTimes; i++)
|
||||
{
|
||||
if (Ct is { IsCancellationRequested: true })
|
||||
@@ -199,129 +269,105 @@ public class Avatar
|
||||
return false;
|
||||
}
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
using var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
|
||||
// 切换成功
|
||||
if (CombatScenes.GetActiveAvatarIndex(region, context) == Index)
|
||||
{
|
||||
if (needLog && i > 0)
|
||||
{
|
||||
LastActiveAvatar = Name;
|
||||
Logger.LogInformation("成功切换角色:{Name}", Name);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop); //反正会重试就不等落地了
|
||||
switch (Index)
|
||||
else
|
||||
{
|
||||
case 1:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
|
||||
break;
|
||||
case 2:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
|
||||
break;
|
||||
case 3:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
|
||||
break;
|
||||
case 4:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
|
||||
break;
|
||||
case 5:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
if (i == tryTimes - 1 && tryTimes == 4) //默认状态,没有特意设置重试次数的情况下,最后一次重试失败才输出日志
|
||||
{
|
||||
Logger.LogWarning("切换角色失败,最后一次尝试,当前角色编号:{CurrentIndex},期望角色编号:{ExpectedIndex}", CombatScenes.GetActiveAvatarIndex(region, context), Index);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 特意需要脱困情形下,会设置重试次数激活脱困检测,第10次重试时(2.5秒切换失败,超过角色的大招动画时间),如在盾奶位功能中次数会到第十次。
|
||||
if (i == 9 && AutoFightTask.FightStatusFlag)
|
||||
{
|
||||
PerformUnstuckAction(Ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Offset60Fix(i);
|
||||
|
||||
SimulateSwitchAction(Index);
|
||||
|
||||
Sleep(250, Ct);
|
||||
}
|
||||
|
||||
Logger.LogWarning("切换角色失败:{Name}", Name);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void SimulateSwitchAction(int index)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop); //反正会重试就不等落地了
|
||||
switch (index)
|
||||
{
|
||||
case 1:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
|
||||
break;
|
||||
case 2:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
|
||||
break;
|
||||
case 3:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
|
||||
break;
|
||||
case 4:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
|
||||
break;
|
||||
case 5:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 战斗中切换角色卡住时的脱困动作:跳跃 → 随机方向移动+切换 → 攻击 → 释放按键
|
||||
/// </summary>
|
||||
private void PerformUnstuckAction(CancellationToken ct)
|
||||
{
|
||||
var direction = UnstuckDirections[UnstuckRandom.Next(4)];
|
||||
Logger.LogWarning("切换角色卡住,执行脱困(方向:{Dir})", direction);
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.Jump);
|
||||
Sleep(200, ct);
|
||||
Simulation.SendInput.SimulateAction(direction, KeyType.KeyDown);
|
||||
SimulateSwitchAction(Index);
|
||||
Sleep(1000, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 切换到本角色
|
||||
/// 切换cd是1秒,如果切换失败,会尝试再次切换,最多尝试5次
|
||||
/// </summary>
|
||||
public void SwitchWithoutCts()
|
||||
{
|
||||
var context = new AvatarActiveCheckContext();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var region = CaptureToRectArea();
|
||||
using var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == 3)
|
||||
if (CombatScenes.GetActiveAvatarIndex(region, context) == Index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
switch (Index)
|
||||
{
|
||||
case 1:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
|
||||
break;
|
||||
case 2:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
|
||||
break;
|
||||
case 3:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
|
||||
break;
|
||||
case 4:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
|
||||
break;
|
||||
case 5:
|
||||
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
Offset60Fix(i);
|
||||
SimulateSwitchAction(Index);
|
||||
|
||||
Sleep(250);
|
||||
}
|
||||
}
|
||||
|
||||
private void Offset60Fix(int i)
|
||||
{
|
||||
// 3次失败考虑是否偏移出现问题,修改偏移位置
|
||||
if (i <= 2 || AutoFightTask.FightStatusFlag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (CombatScenes.IndexRectOffset60Fix)
|
||||
{
|
||||
foreach (var avatar in CombatScenes.GetAvatars())
|
||||
{
|
||||
var originalRect = AutoFightAssets.Instance.AvatarIndexRectList[avatar.Index - 1];
|
||||
var rect1 = new Rect(originalRect.X, originalRect.Y, originalRect.Width, originalRect.Height);
|
||||
avatar.IndexRect = rect1;
|
||||
}
|
||||
CombatScenes.IndexRectOffset60Fix = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var avatar in CombatScenes.GetAvatars())
|
||||
{
|
||||
var originalRect = AutoFightAssets.Instance.AvatarIndexRectList[avatar.Index - 1];
|
||||
var rect1 = new Rect(originalRect.X, originalRect.Y, originalRect.Width, originalRect.Height);
|
||||
rect1.Y -= 14;
|
||||
avatar.IndexRect = rect1;
|
||||
}
|
||||
|
||||
CombatScenes.IndexRectOffset60Fix = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否出战状态
|
||||
/// </summary>
|
||||
@@ -338,12 +384,12 @@ public class Avatar
|
||||
return !white;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private bool IsIndexRectWhite(ImageRegion region, Rect rect)
|
||||
{
|
||||
// 剪裁出IndexRect区域
|
||||
var indexRa = region.DeriveCrop(rect);
|
||||
var mat = indexRa.CacheGreyMat;
|
||||
using var indexRa = region.DeriveCrop(rect);
|
||||
using var mat = indexRa.CacheGreyMat;
|
||||
var count = OpenCvCommonHelper.CountGrayMatColor(mat, 251, 255);
|
||||
if (count * 1.0 / (mat.Width * mat.Height) > 0.5)
|
||||
{
|
||||
@@ -470,13 +516,13 @@ public class Avatar
|
||||
|
||||
Sleep(200, Ct);
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
using var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct); // 检测是不是要跑神像
|
||||
var cd = AfterUseSkill(region);
|
||||
if (cd > 0)
|
||||
{
|
||||
Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd} 秒" : "{Name} 点按元素战技,cd:{Cd} 秒", Name,
|
||||
Math.Round(cd, 2));
|
||||
// Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd} 秒" : "{Name} 点按元素战技,cd:{Cd} 秒", Name,
|
||||
// Math.Round(cd, 2));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -495,7 +541,7 @@ public class Avatar
|
||||
return GetSkillCdSeconds();
|
||||
}
|
||||
|
||||
var region = givenRegion ?? CaptureToRectArea();
|
||||
using var region = givenRegion ?? CaptureToRectArea();
|
||||
return GetSkillCurrentCd(region);
|
||||
}
|
||||
|
||||
@@ -506,8 +552,8 @@ public class Avatar
|
||||
/// </summary>
|
||||
private double GetSkillCurrentCd(ImageRegion imageRegion)
|
||||
{
|
||||
var eRa = imageRegion.DeriveCrop(AutoFightAssets.Instance.ECooldownRect);
|
||||
var eRaWhite = OpenCvCommonHelper.InRangeHsv(eRa.SrcMat, new Scalar(0, 0, 235), new Scalar(0, 25, 255));
|
||||
using var eRa = imageRegion.DeriveCrop(AutoFightAssets.Instance.ECooldownRect);
|
||||
using var eRaWhite = OpenCvCommonHelper.InRangeHsv(eRa.SrcMat, new Scalar(0, 0, 235), new Scalar(0, 25, 255));
|
||||
var text = OcrFactory.Paddle.OcrWithoutDetector(eRaWhite);
|
||||
var cd = StringUtils.TryParseDouble(text);
|
||||
if (cd > 0 && cd <= CombatAvatar.SkillCd)
|
||||
@@ -525,7 +571,6 @@ public class Avatar
|
||||
/// </summary>
|
||||
public void UseBurst()
|
||||
{
|
||||
// var isBurstReleased = false;
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
if (Ct is { IsCancellationRequested: true })
|
||||
@@ -536,28 +581,15 @@ public class Avatar
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
|
||||
Sleep(200, Ct);
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
using var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (notActiveCount == 0)
|
||||
|
||||
if (!PartyAvatarSideIndexHelper.HasAnyIndexRect(region))
|
||||
{
|
||||
// isBurstReleased = true;
|
||||
// 找不到角色编号块意味者技能释放成功
|
||||
Sleep(1500, Ct);
|
||||
return;
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// if (!isBurstReleased)
|
||||
// {
|
||||
// var cd = GetBurstCurrentCd(content);
|
||||
// if (cd > 0)
|
||||
// {
|
||||
// Logger.LogInformation("{Name} 释放元素爆发,cd:{Cd}", Name, cd);
|
||||
// // todo 把cd加入执行队列
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -646,6 +678,32 @@ public class Avatar
|
||||
{
|
||||
Sleep(ms); // 由于存在宏操作,等待不应被cts取消
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待完成
|
||||
/// </summary>
|
||||
public void Ready()
|
||||
{
|
||||
Sleep(10, Ct);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (Ct is { IsCancellationRequested: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var region = CaptureToRectArea();
|
||||
// 等待角色编号块出现
|
||||
if (PartyAvatarSideIndexHelper.HasAnyIndexRect(region))
|
||||
{
|
||||
region.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
Sleep(150, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -809,6 +867,7 @@ public class Avatar
|
||||
rateX = lowspeed;
|
||||
rateY = 0;
|
||||
}
|
||||
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)(rateX * 50 * dpi), (int)(rateY * 50 * dpi));
|
||||
|
||||
tick = (tick + 1) % 100;
|
||||
@@ -882,6 +941,11 @@ public class Avatar
|
||||
GlobalMethod.MoveMouseBy(x, y);
|
||||
}
|
||||
|
||||
public void Scroll(int scrollAmountInClicks)
|
||||
{
|
||||
Simulation.SendInput.Mouse.VerticalScroll(scrollAmountInClicks);
|
||||
}
|
||||
|
||||
public void KeyDown(string key)
|
||||
{
|
||||
var vk = KeyBindingsSettingsPageViewModel.MappingKey(User32Helper.ToVk(key));
|
||||
@@ -1014,4 +1078,4 @@ public class Avatar
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 多次识别出战角色结果上下文
|
||||
/// </summary>
|
||||
public class AvatarActiveCheckContext
|
||||
{
|
||||
/// <summary>
|
||||
/// 出战标识识别结果的次数统计
|
||||
/// </summary>
|
||||
public int[] ActiveIndexByArrowCount { get; set; } = new int[4];
|
||||
|
||||
/// <summary>
|
||||
/// 累计识别失败次数
|
||||
/// </summary>
|
||||
public int TotalCheckFailedCount { get; set; } = 0;
|
||||
}
|
||||
@@ -1,25 +1,28 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Config;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Compunet.YoloSharp;
|
||||
using Compunet.YoloSharp.Data;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using Compunet.YoloSharp;
|
||||
using Compunet.YoloSharp.Data;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
@@ -35,17 +38,71 @@ public class CombatScenes : IDisposable
|
||||
|
||||
public int AvatarCount => Avatars.Length;
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次识别出的出战角色编号,从1开始,-1表示未识别
|
||||
/// </summary>
|
||||
public int LastActiveAvatarIndex { get; set; } = -1;
|
||||
|
||||
private readonly BgiYoloPredictor _predictor =
|
||||
App.ServiceProvider.GetRequiredService<BgiOnnxFactory>().CreateYoloPredictor(BgiOnnxModel.BgiAvatarSide);
|
||||
public MultiGameStatus? CurrentMultiGameStatus { set; get; }
|
||||
|
||||
private readonly BgiYoloPredictor _predictor;
|
||||
private readonly bool _ownsPredictor;
|
||||
|
||||
private readonly AutoFightAssets _autoFightAssets;
|
||||
|
||||
private readonly ElementAssets _elementAssets;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly ISystemInfo _systemInfo;
|
||||
|
||||
public CombatScenes(BgiYoloPredictor? predictor = null, AutoFightAssets? autoFightAssets = null, ILogger? logger = null, ElementAssets? elementAssets = null, ISystemInfo? systemInfo = null)
|
||||
{
|
||||
if (predictor == null)
|
||||
{
|
||||
_predictor = App.ServiceProvider.GetRequiredService<BgiOnnxFactory>().CreateYoloPredictor(BgiOnnxModel.BgiAvatarSide);
|
||||
_ownsPredictor = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_predictor = predictor;
|
||||
_ownsPredictor = false;
|
||||
}
|
||||
if (autoFightAssets == null)
|
||||
{
|
||||
_autoFightAssets = AutoFightAssets.Instance; // todo BaseAssets重构后直接由systemInfo构建,省去传入?
|
||||
}
|
||||
else
|
||||
{
|
||||
_autoFightAssets = autoFightAssets;
|
||||
}
|
||||
if (logger == null)
|
||||
{
|
||||
_logger = TaskControl.Logger;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
if (elementAssets == null)
|
||||
{
|
||||
_elementAssets = ElementAssets.Instance;
|
||||
}
|
||||
else
|
||||
{
|
||||
_elementAssets = elementAssets;
|
||||
}
|
||||
if (systemInfo == null)
|
||||
{
|
||||
_systemInfo = TaskContext.Instance().SystemInfo;
|
||||
}
|
||||
else
|
||||
{
|
||||
_systemInfo = systemInfo;
|
||||
}
|
||||
}
|
||||
|
||||
public int ExpectedTeamAvatarNum { get; private set; } = 4;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 6.0 UI偏移标识
|
||||
/// </summary>
|
||||
public bool IndexRectOffset60Fix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个只读的Avatars
|
||||
@@ -61,54 +118,27 @@ public class CombatScenes : IDisposable
|
||||
/// 通过YOLO分类器识别队伍内角色
|
||||
/// </summary>
|
||||
/// <param name="imageRegion">完整游戏画面的捕获截图</param>
|
||||
public CombatScenes InitializeTeam(ImageRegion imageRegion)
|
||||
public CombatScenes InitializeTeam(ImageRegion imageRegion, AutoFightConfig? autoFightConfig = null)
|
||||
{
|
||||
if (autoFightConfig == null)
|
||||
{
|
||||
autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
|
||||
}
|
||||
|
||||
AssertUtils.CheckGameResolution();
|
||||
// 优先取配置
|
||||
if (!string.IsNullOrEmpty(TaskContext.Instance().Config.AutoFightConfig.TeamNames))
|
||||
if (!string.IsNullOrEmpty(autoFightConfig.TeamNames))
|
||||
{
|
||||
InitializeTeamFromConfig(TaskContext.Instance().Config.AutoFightConfig.TeamNames);
|
||||
InitializeTeamFromConfig(autoFightConfig.TeamNames, autoFightConfig);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 判断当前是否处于联机状态
|
||||
List<Rect> avatarSideIconRectList;
|
||||
List<Rect> avatarIndexRectList;
|
||||
var pRaList = imageRegion.FindMulti(AutoFightAssets.Instance.PRa);
|
||||
if (pRaList.Count > 0)
|
||||
{
|
||||
var num = pRaList.Count + 1;
|
||||
if (num > 4)
|
||||
{
|
||||
throw new Exception("当前处于联机状态,但是队伍人数超过4人,无法识别");
|
||||
}
|
||||
|
||||
// 联机状态下判断
|
||||
var onePRa = imageRegion.Find(AutoFightAssets.Instance.OnePRa);
|
||||
var p = "p";
|
||||
if (!onePRa.IsEmpty())
|
||||
{
|
||||
Logger.LogInformation("当前处于联机状态,且当前账号是房主,联机人数{Num}人", num);
|
||||
p = "1p";
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("当前处于联机状态,且在别人世界中,联机人数{Num}人", num);
|
||||
}
|
||||
|
||||
avatarSideIconRectList = new List<Rect>(AutoFightAssets.Instance.AvatarSideIconRectListMap[$"{p}_{num}"]);
|
||||
avatarIndexRectList = new List<Rect>(AutoFightAssets.Instance.AvatarIndexRectListMap[$"{p}_{num}"]);
|
||||
|
||||
ExpectedTeamAvatarNum = avatarSideIconRectList.Count;
|
||||
}
|
||||
else
|
||||
{
|
||||
avatarSideIconRectList = new List<Rect>(AutoFightAssets.Instance.AvatarSideIconRectList);
|
||||
avatarIndexRectList = new List<Rect>(AutoFightAssets.Instance.AvatarIndexRectList);
|
||||
}
|
||||
|
||||
// 6.0 版本 队伍下的 草露 进度条 导致位置偏移
|
||||
IndexRectOffset60Fix = AvatarSideFixOffset(imageRegion, avatarSideIconRectList, avatarIndexRectList);
|
||||
// 判断联机状态
|
||||
CurrentMultiGameStatus = PartyAvatarSideIndexHelper.DetectedMultiGameStatus(imageRegion, _autoFightAssets, _logger);
|
||||
// 队伍角色编号和侧面头像位置
|
||||
var (avatarIndexRectList, avatarSideIconRectList) = PartyAvatarSideIndexHelper.GetAllIndexRects(imageRegion, CurrentMultiGameStatus, _logger, _elementAssets, _systemInfo);
|
||||
ExpectedTeamAvatarNum = avatarIndexRectList.Count;
|
||||
|
||||
// 识别队伍
|
||||
var names = new string[avatarSideIconRectList.Count];
|
||||
@@ -117,13 +147,13 @@ public class CombatScenes : IDisposable
|
||||
{
|
||||
for (var i = 0; i < avatarSideIconRectList.Count; i++)
|
||||
{
|
||||
var ra = imageRegion.DeriveCrop(avatarSideIconRectList[i]);
|
||||
using var ra = imageRegion.DeriveCrop(avatarSideIconRectList[i]);
|
||||
var pair = ClassifyAvatarCnName(ra.CacheImage, i + 1);
|
||||
names[i] = pair.Item1;
|
||||
if (!string.IsNullOrEmpty(pair.Item2))
|
||||
{
|
||||
var costumeName = pair.Item2;
|
||||
if (AutoFightAssets.Instance.AvatarCostumeMap.TryGetValue(costumeName, out string? name))
|
||||
if (_autoFightAssets.AvatarCostumeMap.TryGetValue(costumeName, out string? name))
|
||||
{
|
||||
costumeName = name;
|
||||
}
|
||||
@@ -136,64 +166,106 @@ public class CombatScenes : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
|
||||
Avatars = BuildAvatars([.. names], null, avatarIndexRectList);
|
||||
_logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
|
||||
Avatars = BuildAvatars([.. names], null, avatarIndexRectList, autoFightConfig);
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception e) // todo 此处catch把错误吞了不便排查
|
||||
{
|
||||
Logger.LogWarning(e.Message);
|
||||
_logger.LogWarning(e.Message);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 6.0 版本 队伍下的 草露 进度条 导致位置偏移
|
||||
///
|
||||
/// 静默模式下的队伍识别(用于后台挂件)
|
||||
/// </summary>
|
||||
public CombatScenes InitializeTeamSilent(ImageRegion imageRegion, AutoFightConfig? autoFightConfig = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (autoFightConfig == null)
|
||||
{
|
||||
autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
|
||||
}
|
||||
|
||||
// 优先取配置
|
||||
if (!string.IsNullOrEmpty(autoFightConfig.TeamNames))
|
||||
{
|
||||
InitializeTeamFromConfig(autoFightConfig.TeamNames, autoFightConfig);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 使用 NullLogger 彻底屏蔽底层工具类的日志输出
|
||||
var nullLogger = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
CurrentMultiGameStatus = PartyAvatarSideIndexHelper.DetectedMultiGameStatus(imageRegion, _autoFightAssets, nullLogger);
|
||||
var (avatarIndexRectList, avatarSideIconRectList) = PartyAvatarSideIndexHelper.GetAllIndexRects(imageRegion, CurrentMultiGameStatus, nullLogger, _elementAssets, _systemInfo);
|
||||
ExpectedTeamAvatarNum = avatarIndexRectList.Count;
|
||||
|
||||
var names = new string[avatarSideIconRectList.Count];
|
||||
for (var i = 0; i < avatarSideIconRectList.Count; i++)
|
||||
{
|
||||
using var ra = imageRegion.DeriveCrop(avatarSideIconRectList[i]);
|
||||
var pair = ClassifyAvatarCnName(ra.CacheImage, i + 1);
|
||||
names[i] = pair.Item1;
|
||||
}
|
||||
Avatars = BuildAvatars([.. names], null, avatarIndexRectList, autoFightConfig);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 静默模式下完全不抛出、不记录异常
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 这个个方法主要用于在切人判断有误的情况下,且能够找到预期数量的角色编号框。此时只有两种情况
|
||||
/// 1. A草露进度条导致角色编号框偏移,B退队后偏移不变,C独立地图传送后偏移还原
|
||||
/// 2. 地图边缘环境,导致角色编号框切人判断失效
|
||||
/// 此方法必须在判定一定存在 ExpectedTeamAvatarNum 数量的 IndexRectList 的情况下才能使用
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>
|
||||
/// <param name="avatarSideIconRectList"></param>
|
||||
/// <param name="avatarIndexRectList"></param>
|
||||
public bool AvatarSideFixOffset(ImageRegion imageRegion, List<Rect> avatarSideIconRectList, List<Rect> avatarIndexRectList)
|
||||
/// <returns>false:存在 IndexRectList 的情况下使用此方法,返回false的时候很有可能处于地图边缘环境下</returns>
|
||||
public bool RefreshTeamAvatarIndexRectList(ImageRegion imageRegion)
|
||||
{
|
||||
// 角色序号 左上角 坐标偏移(+2, -5)后存在3个白色点,则认为存在 草露 进度条
|
||||
// 存在 草露 进度条时候整体上移 14 个像素
|
||||
var whitePointCount = 0;
|
||||
foreach (var rectIndex in avatarIndexRectList)
|
||||
// 只用新方法判断
|
||||
try
|
||||
{
|
||||
int x = rectIndex.X + 2;
|
||||
int y = rectIndex.Y - 5;
|
||||
var color = imageRegion.SrcMat.At<Vec3b>(y, x);
|
||||
if (color is { Item0: 255, Item1: 255, Item2: 255 })
|
||||
var (avatarIndexRectList, _) = PartyAvatarSideIndexHelper.GetAllIndexRectsNew(imageRegion, CurrentMultiGameStatus!, _logger, _elementAssets, _systemInfo);
|
||||
if (avatarIndexRectList.Count != ExpectedTeamAvatarNum)
|
||||
{
|
||||
whitePointCount++;
|
||||
_logger.LogWarning("重新识别到的队伍角色数量与之前不一致,之前{Old}个,现在{New}个", ExpectedTeamAvatarNum, avatarIndexRectList.Count);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (whitePointCount < 3)
|
||||
for (var i = 0; i < ExpectedTeamAvatarNum; i++)
|
||||
{
|
||||
Avatars[i].IndexRect = avatarIndexRectList[i];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "使用新方法获取角色编号位置失败");
|
||||
_logger.LogWarning("[重新识别角色编号位置]使用新方法获取角色编号位置失败,原因:" + ex.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
Logger.LogInformation("检测到右侧队伍上偏移,进行位置偏移");
|
||||
|
||||
for (var i = 0; i < avatarSideIconRectList.Count; i++)
|
||||
{
|
||||
var rect = avatarSideIconRectList[i];
|
||||
rect.Y -= 14;
|
||||
avatarSideIconRectList[i] = rect;
|
||||
}
|
||||
|
||||
for (var i = 0; i < avatarIndexRectList.Count; i++)
|
||||
{
|
||||
var rect = avatarIndexRectList[i];
|
||||
rect.Y -= 14;
|
||||
avatarIndexRectList[i] = rect;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// public static List<Rect> FindAvatarIndexRectList(ImageRegion imageRegion)
|
||||
// {
|
||||
// var i1 = imageRegion.Find(ElementAssets.Instance.Index1);
|
||||
// var i2 = imageRegion.Find(ElementAssets.Instance.Index2);
|
||||
// var i3 = imageRegion.Find(ElementAssets.Instance.Index3);
|
||||
// var i4 = imageRegion.Find(ElementAssets.Instance.Index4);
|
||||
// var curr = imageRegion.Find(ElementAssets.Instance.CurrentAvatarThreshold);
|
||||
// // Debug.WriteLine($"i1:{i1.X},{i1.Y},{i1.Width},{i1.Height}; i2:{i2.X},{i2.Y},{i2.Width},{i2.Height}; i3:{i3.X},{i3.Y},{i3.Width},{i3.Height}; i4:{i4.X},{i4.Y},{i4.Width},{i4.Height}; curr:{curr.X},{curr.Y},{curr.Width},{curr.Height}");
|
||||
// return null;
|
||||
// }
|
||||
|
||||
|
||||
public (string, string) ClassifyAvatarCnName(Image<Rgb24> img, int index)
|
||||
{
|
||||
@@ -226,7 +298,7 @@ public class CombatScenes : IDisposable
|
||||
// 降低琴和衣装角色的识别率要求
|
||||
if (topClass.Confidence < 0.51)
|
||||
{
|
||||
img.SaveAsPng(@"log\avatar_side_classify_error.png");
|
||||
img.SaveAsPng(Global.Absolute($@"log\avatar_side_classify_error.png"));
|
||||
throw new Exception(
|
||||
$"无法识别第{index}位角色,置信度{topClass.Confidence:F1},结果:{topClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
}
|
||||
@@ -235,7 +307,7 @@ public class CombatScenes : IDisposable
|
||||
{
|
||||
if (topClass.Confidence < 0.7)
|
||||
{
|
||||
img.SaveAsPng(@"log\avatar_side_classify_error.png");
|
||||
img.SaveAsPng(Global.Absolute($@"log\avatar_side_classify_error.png"));
|
||||
throw new Exception(
|
||||
$"无法识别第{index}位角色,置信度{topClass.Confidence:F1},结果:{topClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
}
|
||||
@@ -244,7 +316,7 @@ public class CombatScenes : IDisposable
|
||||
return topClass.Name.Name;
|
||||
}
|
||||
|
||||
private void InitializeTeamFromConfig(string teamNames)
|
||||
private void InitializeTeamFromConfig(string teamNames, AutoFightConfig autoFightConfig)
|
||||
{
|
||||
var names = teamNames.Split([",", ","], StringSplitOptions.TrimEntries);
|
||||
if (names.Length != 4)
|
||||
@@ -258,9 +330,9 @@ public class CombatScenes : IDisposable
|
||||
names[i] = DefaultAutoFightConfig.AvatarAliasToStandardName(names[i]);
|
||||
}
|
||||
|
||||
Logger.LogInformation("强制指定队伍角色:{Text}", string.Join(",", names));
|
||||
TaskContext.Instance().Config.AutoFightConfig.TeamNames = string.Join(",", names);
|
||||
Avatars = BuildAvatars([.. names]);
|
||||
_logger.LogInformation("强制指定队伍角色:{Text}", string.Join(",", names));
|
||||
autoFightConfig.TeamNames = string.Join(",", names);
|
||||
Avatars = BuildAvatars([.. names], autoFightConfig: autoFightConfig);
|
||||
}
|
||||
|
||||
public bool CheckTeamInitialized()
|
||||
@@ -274,13 +346,16 @@ public class CombatScenes : IDisposable
|
||||
}
|
||||
|
||||
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null,
|
||||
List<Rect>? avatarIndexRectList = null)
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null, List<Rect>? avatarIndexRectList = null, AutoFightConfig? autoFightConfig = null)
|
||||
{
|
||||
var cdConfig = TaskContext.Instance().Config.AutoFightConfig.ActionSchedulerByCd;
|
||||
if (autoFightConfig == null)
|
||||
{
|
||||
autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
|
||||
}
|
||||
var cdConfig = autoFightConfig.ActionSchedulerByCd;
|
||||
if (avatarIndexRectList == null && ExpectedTeamAvatarNum == 4)
|
||||
{
|
||||
avatarIndexRectList = AutoFightAssets.Instance.AvatarIndexRectList;
|
||||
avatarIndexRectList = _autoFightAssets.AvatarIndexRectList;
|
||||
}
|
||||
|
||||
if (avatarIndexRectList == null)
|
||||
@@ -369,7 +444,7 @@ public class CombatScenes : IDisposable
|
||||
{
|
||||
if (avatarIndex < 1 || avatarIndex > AvatarCount)
|
||||
{
|
||||
Logger.LogError("切换角色编号错误,当前角色数量{Count},编号{Index}", AvatarCount, avatarIndex);
|
||||
_logger.LogError("切换角色编号错误,当前角色数量{Count},编号{Index}", AvatarCount, avatarIndex);
|
||||
throw new Exception("不存在的角色编号");
|
||||
}
|
||||
|
||||
@@ -378,6 +453,8 @@ public class CombatScenes : IDisposable
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前出战角色名
|
||||
/// 不考虑重新刷新编号框位置
|
||||
/// 不推荐使用
|
||||
/// </summary>
|
||||
/// <param name="force"></param>
|
||||
/// <param name="region"></param>
|
||||
@@ -386,30 +463,63 @@ public class CombatScenes : IDisposable
|
||||
public string? CurrentAvatar(bool force = false, ImageRegion? region = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (!force && Avatar.LastActiveAvatar is not null)
|
||||
if (!force && LastActiveAvatarIndex > 0)
|
||||
{
|
||||
return Avatar.LastActiveAvatar;
|
||||
return Avatars[LastActiveAvatarIndex - 1].Name;
|
||||
}
|
||||
|
||||
var imageRegion = region ?? CaptureToRectArea();
|
||||
string? avatarName = null;
|
||||
using var imageRegion = region ?? TaskControl.CaptureToRectArea();
|
||||
|
||||
var notActiveCount = 0;
|
||||
foreach (var avatar in GetAvatars())
|
||||
var rectArray = Avatars.Select(t => t.IndexRect).ToArray();
|
||||
int index = PartyAvatarSideIndexHelper.GetAvatarIndexIsActiveWithContext(imageRegion, rectArray, new AvatarActiveCheckContext());
|
||||
|
||||
if (index > 0)
|
||||
{
|
||||
if (avatar.IsActive(imageRegion))
|
||||
LastActiveAvatarIndex = index;
|
||||
}
|
||||
|
||||
return Avatars[LastActiveAvatarIndex - 1].Name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推荐使用
|
||||
/// 失败后自动刷新编号框位置
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>l
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public int GetActiveAvatarIndex(ImageRegion imageRegion, AvatarActiveCheckContext context)
|
||||
{
|
||||
var rectArray = Avatars.Select(t => t.IndexRect).ToArray();
|
||||
int index = PartyAvatarSideIndexHelper.GetAvatarIndexIsActiveWithContext(imageRegion, rectArray, context);
|
||||
|
||||
if (index > 0)
|
||||
{
|
||||
LastActiveAvatarIndex = index;
|
||||
return index;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 多次识别失败则尝试刷新角色编号位置
|
||||
// 应对草露问题
|
||||
if (context.TotalCheckFailedCount % 3 == 0 && context.TotalCheckFailedCount > 0 && context.TotalCheckFailedCount < 10)
|
||||
{
|
||||
avatarName = avatar.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
notActiveCount++;
|
||||
// 失败多次,识别是否存在满足预期的编号框
|
||||
if (PartyAvatarSideIndexHelper.CountIndexRect(imageRegion) == Avatars.Length)
|
||||
{
|
||||
bool res = RefreshTeamAvatarIndexRectList(imageRegion);
|
||||
_logger.LogWarning("多次识别出战角色失败,尝试刷新角色编号位置,刷新结果:{Result}", res ? "成功" : "失败");
|
||||
imageRegion.SrcMat.SaveImage(Global.Absolute("log\\refresh_avatar_index_rect.png"));
|
||||
if (res)
|
||||
{
|
||||
context.TotalCheckFailedCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notActiveCount != ExpectedTeamAvatarNum - 1) return avatarName;
|
||||
Avatar.LastActiveAvatar = avatarName;
|
||||
return Avatar.LastActiveAvatar;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -425,12 +535,12 @@ public class CombatScenes : IDisposable
|
||||
// 优先取配置
|
||||
if (!string.IsNullOrEmpty(TaskContext.Instance().Config.AutoFightConfig.TeamNames))
|
||||
{
|
||||
InitializeTeamFromConfig(TaskContext.Instance().Config.AutoFightConfig.TeamNames);
|
||||
InitializeTeamFromConfig(TaskContext.Instance().Config.AutoFightConfig.TeamNames, TaskContext.Instance().Config.AutoFightConfig);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 剪裁出队伍区域
|
||||
var teamRa = content.CaptureRectArea.DeriveCrop(AutoFightAssets.Instance.TeamRectNoIndex);
|
||||
var teamRa = content.CaptureRectArea.DeriveCrop(_autoFightAssets.TeamRectNoIndex);
|
||||
// 过滤出白色
|
||||
var hsvFilterMat =
|
||||
OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
|
||||
@@ -459,23 +569,23 @@ public class CombatScenes : IDisposable
|
||||
|
||||
if (names.Count != 4)
|
||||
{
|
||||
Logger.LogWarning("识别到的队伍角色数量不正确,当前识别结果:{Text}", string.Join(",", names));
|
||||
_logger.LogWarning("识别到的队伍角色数量不正确,当前识别结果:{Text}", string.Join(",", names));
|
||||
}
|
||||
|
||||
if (names.Count == 3)
|
||||
{
|
||||
// 流浪者特殊处理
|
||||
// 4人以上的队伍,不支持流浪者的识别
|
||||
var wanderer = rectArea.Find(AutoFightAssets.Instance.WandererIconRa);
|
||||
var wanderer = rectArea.Find(_autoFightAssets.WandererIconRa);
|
||||
if (wanderer.IsEmpty())
|
||||
{
|
||||
wanderer = rectArea.Find(AutoFightAssets.Instance.WandererIconNoActiveRa);
|
||||
wanderer = rectArea.Find(_autoFightAssets.WandererIconNoActiveRa);
|
||||
}
|
||||
|
||||
if (wanderer.IsEmpty())
|
||||
{
|
||||
// 补充识别流浪者
|
||||
Logger.LogWarning("二次尝试识别失败,当前识别结果:{Text}", string.Join(",", names));
|
||||
_logger.LogWarning("二次尝试识别失败,当前识别结果:{Text}", string.Join(",", names));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -501,12 +611,12 @@ public class CombatScenes : IDisposable
|
||||
|
||||
if (names.Count != 4)
|
||||
{
|
||||
Logger.LogWarning("图像识别到流浪者,但识别队内位置信息失败");
|
||||
_logger.LogWarning("图像识别到流浪者,但识别队内位置信息失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", names));
|
||||
_logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", names));
|
||||
Avatars = BuildAvatars(names, nameRects);
|
||||
}
|
||||
|
||||
@@ -542,6 +652,9 @@ public class CombatScenes : IDisposable
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_predictor.Dispose();
|
||||
if (_ownsPredictor)
|
||||
{
|
||||
_predictor.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
public class MultiGameStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否在联机状态
|
||||
/// </summary>
|
||||
public bool IsInMultiGame { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 是不是房主
|
||||
/// 我是房主的情况下
|
||||
/// 1人联机:最多控制4名角色
|
||||
/// 2人联机:最多控制2名角色
|
||||
/// 3人联机:最多控制2名角色
|
||||
/// 4人联机:最多控制1名角色
|
||||
/// 我不是房主的情况下
|
||||
/// 2人联机:最多控制2名角色
|
||||
/// 3人联机:最多控制1名角色
|
||||
/// 4人联机:最多控制1名角色
|
||||
/// </summary>
|
||||
public bool IsHost { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 玩家数量,最少1人(我自己)
|
||||
/// </summary>
|
||||
public int PlayerCount { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 我能控制的最大角色数量
|
||||
/// </summary>
|
||||
public int MaxControlAvatarCount
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!IsInMultiGame)
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
if (IsHost)
|
||||
{
|
||||
return PlayerCount switch
|
||||
{
|
||||
1 => 4,
|
||||
2 => 2,
|
||||
3 => 2,
|
||||
4 => 1,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(PlayerCount), "自己为主机时,联机总人数异常")
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
return PlayerCount switch
|
||||
{
|
||||
2 => 2,
|
||||
3 => 1,
|
||||
4 => 1,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(PlayerCount), "进入别人世界时,联机总人数异常")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 用于处理主界面右侧角色编号的一些方法
|
||||
/// </summary>
|
||||
public class PartyAvatarSideIndexHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 角色编号以当前模板匹配结果的情况下的Y轴公差
|
||||
/// </summary>
|
||||
private static readonly int IndexRectDistanceY = 96;
|
||||
|
||||
/// <summary>
|
||||
/// 检查当前联机状态
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public static MultiGameStatus DetectedMultiGameStatus(ImageRegion imageRegion, AutoFightAssets? autoFightAssets = null, ILogger? logger = null)
|
||||
{
|
||||
if (autoFightAssets == null)
|
||||
{
|
||||
autoFightAssets = AutoFightAssets.Instance;
|
||||
}
|
||||
|
||||
if (logger == null)
|
||||
{
|
||||
logger = TaskControl.Logger;
|
||||
}
|
||||
|
||||
var status = new MultiGameStatus();
|
||||
// 判断当前联机人数
|
||||
var pRaList = imageRegion.FindMulti(autoFightAssets.PRa);
|
||||
if (pRaList.Count > 0)
|
||||
{
|
||||
status.IsInMultiGame = true;
|
||||
var num = pRaList.Count + 1;
|
||||
if (num > 4)
|
||||
{
|
||||
throw new Exception("当前处于联机状态,但是队伍人数超过4人,无法识别");
|
||||
}
|
||||
|
||||
status.PlayerCount = num;
|
||||
|
||||
// 联机状态下判断
|
||||
var onePRa = imageRegion.Find(autoFightAssets.OnePRa);
|
||||
if (onePRa.IsExist())
|
||||
{
|
||||
logger.LogInformation("当前处于联机状态,且当前账号是房主,联机人数{Num}人", num);
|
||||
status.IsHost = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation("当前处于联机状态,且在别人世界中,联机人数{Num}人", num);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 没有其他联机玩家的情况下,也有可能是单人房主
|
||||
var onePRa = imageRegion.Find(autoFightAssets.OnePRa);
|
||||
if (onePRa.IsExist())
|
||||
{
|
||||
logger.LogInformation("当前处于联机状态,但是没有其他玩家连入");
|
||||
status.IsInMultiGame = true;
|
||||
status.IsHost = true;
|
||||
status.PlayerCount = 1;
|
||||
}
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据已知的某个角色编号位置,计算其他角色编号的位置
|
||||
/// </summary>
|
||||
/// <param name="knownIndex">已知编号</param>
|
||||
/// <param name="knownRect">已知编号矩形</param>
|
||||
/// <param name="targetIndex">目标编号</param>
|
||||
/// <returns>目标编号矩形</returns>
|
||||
public static Rect GetIndexRectFromKnownIndexRect(int knownIndex, Rect knownRect, int targetIndex)
|
||||
{
|
||||
var s = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
|
||||
// y_k + (n - k) * d
|
||||
int y = knownRect.Y + (targetIndex - knownIndex) * (int)(IndexRectDistanceY * s);
|
||||
|
||||
return new Rect(knownRect.X, y, knownRect.Width, knownRect.Height);
|
||||
}
|
||||
|
||||
public static Rect GetIndexRectFromKnownCurrentAvatarFlag(Rect currRect)
|
||||
{
|
||||
var s = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
return new Rect(currRect.X + (int)(126 * s), currRect.Y - (int)(194 * s), (int)(16 * s), (int)(17 * s));
|
||||
}
|
||||
|
||||
public static (List<Rect>, List<Rect>) GetAllIndexRects(ImageRegion imageRegion, MultiGameStatus multiGameStatus, ILogger logger, ElementAssets elementAssets, ISystemInfo systemInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 新的动态获取角色编号位置逻辑
|
||||
return GetAllIndexRectsNew(imageRegion, multiGameStatus, logger, elementAssets, systemInfo);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug(ex, "使用新方法获取角色编号位置失败");
|
||||
logger.LogWarning("使用新方法获取角色编号位置失败,原因:" + ex.Message);
|
||||
logger.LogWarning("尝试使用旧的写死位置逻辑");
|
||||
// 旧的写死位置逻辑
|
||||
return GetAllIndexRectsOld(imageRegion, multiGameStatus);
|
||||
}
|
||||
}
|
||||
|
||||
private static (List<Rect>, List<Rect>) GetAllIndexRectsOld(ImageRegion imageRegion, MultiGameStatus multiGameStatus)
|
||||
{
|
||||
List<Rect> avatarSideIconRectList;
|
||||
List<Rect> avatarIndexRectList;
|
||||
if (multiGameStatus.IsInMultiGame)
|
||||
{
|
||||
var p = multiGameStatus.IsHost ? "1p" : "p";
|
||||
avatarSideIconRectList = new List<Rect>(AutoFightAssets.Instance.AvatarSideIconRectListMap[$"{p}_{multiGameStatus.PlayerCount}"]);
|
||||
avatarIndexRectList = new List<Rect>(AutoFightAssets.Instance.AvatarIndexRectListMap[$"{p}_{multiGameStatus.PlayerCount}"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
avatarSideIconRectList = new List<Rect>(AutoFightAssets.Instance.AvatarSideIconRectList);
|
||||
avatarIndexRectList = new List<Rect>(AutoFightAssets.Instance.AvatarIndexRectList);
|
||||
}
|
||||
|
||||
// 6.0 版本 队伍下的 草露 进度条 导致位置偏移
|
||||
AvatarSideFixOffset(imageRegion, avatarSideIconRectList, avatarIndexRectList);
|
||||
return (avatarIndexRectList, avatarSideIconRectList);
|
||||
}
|
||||
|
||||
public static bool HasAnyIndexRect(ImageRegion imageRegion)
|
||||
{
|
||||
return ElementAssets.Instance.IndexList.Select(indexRo => imageRegion.Find(indexRo)).Any(indexRes => indexRes.IsExist());
|
||||
}
|
||||
|
||||
public static int CountIndexRect(ImageRegion imageRegion)
|
||||
{
|
||||
return ElementAssets.Instance.IndexList.Select(indexRo => imageRegion.Find(indexRo)).Count(indexRes => indexRes.IsExist());
|
||||
}
|
||||
|
||||
public static bool HasActiveAvatarArrow(ImageRegion imageRegion)
|
||||
{
|
||||
return imageRegion.Find(ElementAssets.Instance.CurrentAvatarThreshold).IsExist();
|
||||
}
|
||||
|
||||
public static (List<Rect>, List<Rect>) GetAllIndexRectsNew(ImageRegion imageRegion, MultiGameStatus multiGameStatus, ILogger logger, ElementAssets elementAssets, ISystemInfo systemInfo)
|
||||
{
|
||||
// 找到编号块
|
||||
var i1 = imageRegion.Find(elementAssets.Index1);
|
||||
var i2 = imageRegion.Find(elementAssets.Index2);
|
||||
var i3 = imageRegion.Find(elementAssets.Index3);
|
||||
var i4 = imageRegion.Find(elementAssets.Index4);
|
||||
List<Rect> indexRectList = [i1.ToRect(), i2.ToRect(), i3.ToRect(), i4.ToRect()];
|
||||
int existNum = indexRectList.Count(indexRect => indexRect != default);
|
||||
if (existNum == multiGameStatus.MaxControlAvatarCount)
|
||||
{
|
||||
// 识别存在个数和当前能控制的最大角色数相等,意味者全部识别,直接返回
|
||||
var notNullIndexRectList = indexRectList.Where(r => r != default).ToList();
|
||||
return (notNullIndexRectList, GetAvatarSideIconRectFromIndexRect(notNullIndexRectList, systemInfo));
|
||||
}
|
||||
else
|
||||
{
|
||||
// 为什么这里要用箭头确认一遍?因为出战角色编号框的识别率不是100%,需要用箭头来辅助确认。这也是为了保证非满队情况下的队伍识别率
|
||||
// 非出战角色编号框识别率100%
|
||||
var curr = imageRegion.Find(elementAssets.CurrentAvatarThreshold); // 当前出战角色标识
|
||||
if (curr.IsExist())
|
||||
{
|
||||
var (knownIndex, knownRect) = GetKnownIndexAndRect(indexRectList);
|
||||
if (knownRect == default)
|
||||
{
|
||||
// 没有已知的编号位置,这种情况下可能是单人队
|
||||
// 直接用出战角色标识来反推
|
||||
var oneIndexRect = GetIndexRectFromKnownCurrentAvatarFlag(curr.ToRect());
|
||||
logger.LogInformation("当前编队中可能只存在一个角色(且角色编号未正确识别)");
|
||||
return ([oneIndexRect], [GetAvatarSideIconRectFromIndexRect(oneIndexRect, systemInfo)]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 有已知的编号位置,通过已知位置来推测其他位置
|
||||
for (int i = 0; i < indexRectList.Count; i++)
|
||||
{
|
||||
if (indexRectList[i] == default)
|
||||
{
|
||||
var rect = GetIndexRectFromKnownIndexRect(knownIndex, knownRect, i + 1);
|
||||
if (IsIntersecting(curr.Y, curr.Height, rect.Y, rect.Height))
|
||||
{
|
||||
// 如果和当前出战角色标识相交,说明这个位置是正确的
|
||||
indexRectList[i] = rect;
|
||||
logger.LogInformation("当前出战角色未正确识别,通过出战标识推测角色编号为{Index}", i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 校验推测结果(编号从 1 开始必定连续)
|
||||
if (AreNullsAtEnd(indexRectList))
|
||||
{
|
||||
var notNullIndexRectList = indexRectList.Where(r => r != default).ToList();
|
||||
return (notNullIndexRectList, GetAvatarSideIconRectFromIndexRect(notNullIndexRectList, systemInfo));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("校验角色列表识别结果失败,角色编号不是连续的!");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 没有出战角色标识的情况下,直接抛出错误走写死逻辑
|
||||
throw new Exception("找不到出战角色编号块与当前出战角色标识!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static (int, Rect) GetKnownIndexAndRect(List<Rect> indexRectList)
|
||||
{
|
||||
for (int i = 0; i < indexRectList.Count; i++)
|
||||
{
|
||||
if (indexRectList[i] != default)
|
||||
{
|
||||
return (i + 1, indexRectList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return (-1, default);
|
||||
}
|
||||
|
||||
public static Rect GetAvatarSideIconRectFromIndexRect(Rect indexRect, ISystemInfo systemInfo)
|
||||
{
|
||||
var s = systemInfo.AssetScale;
|
||||
return new Rect(indexRect.X - (int)(91 * s), indexRect.Y - (int)(47 * s), (int)(82 * s), (int)(82 * s));
|
||||
}
|
||||
|
||||
public static List<Rect> GetAvatarSideIconRectFromIndexRect(List<Rect> indexRect, ISystemInfo systemInfo)
|
||||
{
|
||||
return indexRect.Select(r => GetAvatarSideIconRectFromIndexRect(r, systemInfo)).ToList();
|
||||
}
|
||||
|
||||
public static bool IsIntersecting(double y1, double h1, double y2, double h2)
|
||||
{
|
||||
// 计算第一个区域的结束位置
|
||||
double end1 = y1 + h1;
|
||||
// 计算第二个区域的结束位置
|
||||
double end2 = y2 + h2;
|
||||
return y1 < end2 && y2 < end1;
|
||||
}
|
||||
|
||||
public static bool AreNullsAtEnd(List<Rect> list)
|
||||
{
|
||||
int firstNullIndex = list.FindIndex(x => x == default); // 找到第一个 null 的索引
|
||||
return firstNullIndex == -1 || list.Skip(firstNullIndex).All(x => x == default); // 检查从第一个 null 开始到末尾是否都是 null
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 6.0 版本 队伍下的 草露 进度条 导致位置偏移
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>
|
||||
/// <param name="avatarSideIconRectList"></param>
|
||||
/// <param name="avatarIndexRectList"></param>
|
||||
public static bool AvatarSideFixOffset(ImageRegion imageRegion, List<Rect> avatarSideIconRectList, List<Rect> avatarIndexRectList)
|
||||
{
|
||||
// 角色序号 左上角 坐标偏移(+2, -5)后存在3个白色点,则认为存在 草露 进度条
|
||||
// 存在 草露 进度条时候整体上移 14 个像素
|
||||
var whitePointCount = 0;
|
||||
foreach (var rectIndex in avatarIndexRectList)
|
||||
{
|
||||
int x = rectIndex.X + 2;
|
||||
int y = rectIndex.Y - 5;
|
||||
var color = imageRegion.SrcMat.At<Vec3b>(y, x);
|
||||
if (color is { Item0: 255, Item1: 255, Item2: 255 })
|
||||
{
|
||||
whitePointCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (whitePointCount < 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
TaskControl.Logger.LogInformation("检测到右侧队伍上偏移,进行位置偏移");
|
||||
|
||||
for (var i = 0; i < avatarSideIconRectList.Count; i++)
|
||||
{
|
||||
var rect = avatarSideIconRectList[i];
|
||||
rect.Y -= 14;
|
||||
avatarSideIconRectList[i] = rect;
|
||||
}
|
||||
|
||||
for (var i = 0; i < avatarIndexRectList.Count; i++)
|
||||
{
|
||||
var rect = avatarIndexRectList[i];
|
||||
rect.Y -= 14;
|
||||
avatarIndexRectList[i] = rect;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 识别当前出战角色编号
|
||||
/// 1. 颜色识别只要成功一次就认为成功并返回(优先级最高)
|
||||
/// 2. 出战标识识别成功,颜色识别失败,认为结果不确定,需要重试一次。2次后结果相同认为成功
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>
|
||||
/// <param name="rectArray"></param>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public static int GetAvatarIndexIsActiveWithContext(ImageRegion imageRegion, Rect[] rectArray, AvatarActiveCheckContext context)
|
||||
{
|
||||
var indexByColor = FindActiveIndexRectByColor(imageRegion, rectArray);
|
||||
if (indexByColor > 0)
|
||||
{
|
||||
context.TotalCheckFailedCount = 0;
|
||||
return indexByColor;
|
||||
}
|
||||
|
||||
var indexByArrow = FindActiveIndexRectByArrow(imageRegion, rectArray);
|
||||
if (indexByArrow > 0)
|
||||
{
|
||||
// 累计识别次数
|
||||
context.ActiveIndexByArrowCount[indexByArrow - 1]++;
|
||||
if (context.ActiveIndexByArrowCount[indexByArrow - 1] >= 2)
|
||||
{
|
||||
context.TotalCheckFailedCount = 0;
|
||||
return indexByArrow;
|
||||
}
|
||||
|
||||
return -2; // 重试
|
||||
}
|
||||
|
||||
context.TotalCheckFailedCount++;
|
||||
return -1; // 两种方式都失败
|
||||
}
|
||||
|
||||
// public static int FindDifferentRect(Mat greyMat, Rect[] rectArray)
|
||||
// {
|
||||
// // 取其中一个矩形和另外三个矩形进行比较
|
||||
// var one = new Mat(greyMat, rectArray[0]);
|
||||
// for (int i = 1; i < rectArray.Length; i++)
|
||||
// {
|
||||
// Mat diff = new Mat();
|
||||
// Cv2.Absdiff(one, new Mat(greyMat, rectArray[i]), diff);
|
||||
// Scalar diffSum = Cv2.Sum(diff);
|
||||
// double totalDiff = diffSum.Val0 + diffSum.Val1 + diffSum.Val2;
|
||||
// totalDiff = totalDiff / (one.Width * one.Height);
|
||||
// }
|
||||
//
|
||||
// return 1;
|
||||
// }
|
||||
|
||||
public static int FindActiveIndexRectByColor(ImageRegion imageRegion, Rect[] rectArray)
|
||||
{
|
||||
if (rectArray.Length == 1)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
Mat[] mats = new Mat[rectArray.Length];
|
||||
try
|
||||
{
|
||||
int whiteCount = 0, notWhiteRectNum = 0;
|
||||
var mat = imageRegion.CacheGreyMat;
|
||||
for (int i = 0; i < rectArray.Length; i++)
|
||||
{
|
||||
var indexMat = new Mat(mat, rectArray[i]);
|
||||
mats[i] = indexMat;
|
||||
if (IsWhiteRect(indexMat))
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
notWhiteRectNum = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (whiteCount == rectArray.Length - 1)
|
||||
{
|
||||
return notWhiteRectNum;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 方法2:边缘像素白色比例
|
||||
int m2 = FindActiveIndexRectByEdgeColor(mats);
|
||||
if (m2 > 0)
|
||||
{
|
||||
return m2;
|
||||
}
|
||||
|
||||
// 方法3:使用更加靠谱的差值识别(-1是未识别),但是不支持非满队
|
||||
if (mats.Length == 4)
|
||||
{
|
||||
var result = ImageDifferenceDetector.FindMostDifferentImage(mats);
|
||||
return result >= 0 ? result + 1 : -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var mat in mats)
|
||||
{
|
||||
mat?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsWhiteRect(Mat indexMat)
|
||||
{
|
||||
var count1 = OpenCvCommonHelper.CountGrayMatColor(indexMat, 251, 255); // 白
|
||||
var count2 = OpenCvCommonHelper.CountGrayMatColor(indexMat, 50, 54); // 黑色文字
|
||||
if ((count1 + count2) * 1.0 / (indexMat.Width * indexMat.Height) > 0.35)
|
||||
{
|
||||
// Debug.WriteLine($"白色矩形占比{(count1 + count2) * 1.0 / (indexMat.Width * indexMat.Height)}");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 使用出战标识识别出战
|
||||
/// </summary>
|
||||
/// <param name="imageRegion"></param>
|
||||
/// <param name="rectArray"></param>
|
||||
/// <returns></returns>
|
||||
public static int FindActiveIndexRectByArrow(ImageRegion imageRegion, Rect[] rectArray)
|
||||
{
|
||||
if (rectArray.Length == 1)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var curr = imageRegion.Find(ElementAssets.Instance.CurrentAvatarThreshold); // 当前出战角色标识
|
||||
if (curr.IsEmpty())
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < rectArray.Length; i++)
|
||||
{
|
||||
if (IsIntersecting(curr.Y, curr.Height, rectArray[i].Y, rectArray[i].Height))
|
||||
{
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过边缘像素颜色识别出战角色编号
|
||||
/// </summary>
|
||||
/// <param name="mats"></param>
|
||||
/// <returns></returns>
|
||||
public static int FindActiveIndexRectByEdgeColor(Mat[] mats)
|
||||
{
|
||||
try
|
||||
{
|
||||
int whiteCount = 0, notWhiteRectNum = 0;
|
||||
for (int i = 0; i < mats.Length; i++)
|
||||
{
|
||||
if (CalculateWhiteEdgePixelsRatio(mats[i]) > 0.5)
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
notWhiteRectNum = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (whiteCount == mats.Length - 1)
|
||||
{
|
||||
return notWhiteRectNum;
|
||||
}
|
||||
else if (whiteCount == mats.Length)
|
||||
{
|
||||
// 如果四个都是白色,那就找内部有没有黑色
|
||||
int blackCount = 0, notBlackRectNum = -1;
|
||||
for (int i = 0; i < mats.Length; i++)
|
||||
{
|
||||
var count = OpenCvCommonHelper.CountGrayMatColorC1(mats[i], 50, 50); // 黑字
|
||||
if (count > 0)
|
||||
{
|
||||
blackCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
notBlackRectNum = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (notBlackRectNum >= 1)
|
||||
{
|
||||
TaskControl.Logger.LogDebug("当前所有编号边缘均为白色(背景过白),通过内部黑色像素识别出战编号为{Index},存在黑色数字的角色编号有{C1}个,总角色数量{C2}", notBlackRectNum, blackCount, mats.Length);
|
||||
return notBlackRectNum;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.WriteLine(e);
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算灰度图最边缘一圈中纯白色(255)像素的占比
|
||||
/// </summary>
|
||||
/// <returns>返回纯白像素占比 (0.0 到 1.0)</returns>
|
||||
public static double CalculateWhiteEdgePixelsRatio(Mat image)
|
||||
{
|
||||
int whiteCount = 0;
|
||||
int height = image.Height;
|
||||
int width = image.Width;
|
||||
|
||||
// 如果图片太小,无法获取边缘
|
||||
if (height < 1 || width < 1)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
// 计算总边缘像素数
|
||||
int totalCount = 2 * (width + height - 2);
|
||||
|
||||
// 顶边和底边
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
// 顶边
|
||||
if (image.At<byte>(0, x) == 255)
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
|
||||
// 底边(避免只有一行时重复计数)
|
||||
if (height > 1 && image.At<byte>(height - 1, x) == 255)
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 左边和右边(不包括四个角,因为已经在顶边和底边中计算过)
|
||||
for (int y = 1; y < height - 1; y++)
|
||||
{
|
||||
// 左边
|
||||
if (image.At<byte>(y, 0) == 255)
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
|
||||
// 右边(避免只有一列时重复计数)
|
||||
if (width > 1 && image.At<byte>(y, width - 1) == 255)
|
||||
{
|
||||
whiteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 计算并返回占比
|
||||
return totalCount > 0 ? (double)whiteCount / totalCount : 0.0;
|
||||
}
|
||||
}
|
||||
@@ -167,9 +167,10 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
return new Task(() =>
|
||||
{
|
||||
Logger.LogInformation("→ {Name}执行宏", activeAvatar.Name);
|
||||
var round = 1;
|
||||
while (!ct.IsCancellationRequested && IsEnabled())
|
||||
{
|
||||
Logger.LogInformation("→ {Name}执行宏 (第{Round}轮)", activeAvatar.Name, round);
|
||||
if (IsHoldOnMode() && !_isKeyDown)
|
||||
{
|
||||
break;
|
||||
@@ -178,8 +179,14 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
// 通用化战斗策略
|
||||
foreach (var command in combatCommands)
|
||||
{
|
||||
if (command.ActivatingRound != null && command.ActivatingRound.Count > 0 && !command.ActivatingRound.Contains(round))
|
||||
{
|
||||
// 跳过强制首轮指令
|
||||
continue;
|
||||
}
|
||||
command.Execute(activeAvatar);
|
||||
}
|
||||
round++;
|
||||
}
|
||||
|
||||
Logger.LogInformation("→ {Name}停止宏", activeAvatar.Name);
|
||||
@@ -194,7 +201,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
|
||||
public Dictionary<string, List<CombatCommand>> LoadAvatarMacros()
|
||||
{
|
||||
var jsonPath = Global.Absolute("User/avatar_macro.json");
|
||||
var jsonPath = GetAvatarMacroJsonPath();
|
||||
var json = File.ReadAllText(jsonPath);
|
||||
_lastUpdateTime = File.GetLastWriteTime(jsonPath);
|
||||
var avatarMacros = JsonSerializer.Deserialize<List<AvatarMacro>>(json, ConfigService.JsonOptions);
|
||||
@@ -219,10 +226,20 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
public bool IsAvatarMacrosEdited()
|
||||
{
|
||||
// 通过修改时间判断是否编辑过
|
||||
var jsonPath = Global.Absolute("User/avatar_macro.json");
|
||||
var jsonPath = GetAvatarMacroJsonPath();
|
||||
var lastWriteTime = File.GetLastWriteTime(jsonPath);
|
||||
return lastWriteTime > _lastUpdateTime;
|
||||
}
|
||||
|
||||
public static string GetAvatarMacroJsonPath()
|
||||
{
|
||||
var path = Global.Absolute("User/avatar_macro.json");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
File.Copy(Global.Absolute("User/avatar_macro_default.json"), path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public static bool IsEnabled()
|
||||
{
|
||||
|
||||
@@ -14,6 +14,8 @@ public class CombatCommand
|
||||
|
||||
public List<string>? Args { get; set; }
|
||||
|
||||
public List<int> ActivatingRound { get; set; }
|
||||
|
||||
public CombatCommand(string name, string command)
|
||||
{
|
||||
Name = name.Trim();
|
||||
@@ -62,9 +64,19 @@ public class CombatCommand
|
||||
throw new ArgumentException($"{Method.Alias[0]}方法的入参必须是VirtualKeyCodes枚举中的值,当前入参 {Args[0]} 不合法");
|
||||
}
|
||||
}
|
||||
else if (Method == Method.Scroll)
|
||||
{
|
||||
AssertUtils.IsTrue(Args.Count == 1, "scroll方法必须有一个入参,代表滚动格数。例:scroll(1) 或 scroll(-1)");
|
||||
AssertUtils.IsTrue(int.TryParse(Args[0], out _), "滚动格数必须是整数");
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"<CombatCommand {Name}, {Method}({Args}) (rounds {ActivatingRound})>";
|
||||
}
|
||||
|
||||
public void Execute(CombatScenes combatScenes)
|
||||
public void Execute(CombatScenes combatScenes, CombatCommand? lastCommand = null)
|
||||
{
|
||||
Avatar? avatar;
|
||||
if (Name == CombatScriptParser.CurrentAvatarName)
|
||||
@@ -79,18 +91,29 @@ public class CombatCommand
|
||||
{
|
||||
return;
|
||||
}
|
||||
// 非宏类脚本,等待切换角色成功
|
||||
if (Method != Method.Wait
|
||||
&& Method != Method.MouseDown
|
||||
&& Method != Method.MouseUp
|
||||
&& Method != Method.Click
|
||||
&& Method != Method.MoveBy
|
||||
&& Method != Method.KeyDown
|
||||
&& Method != Method.KeyUp
|
||||
&& Method != Method.KeyPress)
|
||||
|
||||
if (lastCommand != null && lastCommand.Name != Name)
|
||||
{
|
||||
// 上一个命令和当前命令不是同一个角色,直接切换角色
|
||||
avatar.Switch();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 非宏类脚本,等待切换角色成功
|
||||
if (Method != Method.Wait
|
||||
&& Method != Method.MouseDown
|
||||
&& Method != Method.MouseUp
|
||||
&& Method != Method.Click
|
||||
&& Method != Method.MoveBy
|
||||
&& Method != Method.KeyDown
|
||||
&& Method != Method.KeyUp
|
||||
&& Method != Method.KeyPress
|
||||
&& Method != Method.Scroll
|
||||
&& Method != Method.Ready)
|
||||
{
|
||||
avatar.Switch();
|
||||
}
|
||||
}
|
||||
}
|
||||
Execute(avatar);
|
||||
}
|
||||
@@ -176,6 +199,14 @@ public class CombatCommand
|
||||
var s = double.Parse(Args![0]);
|
||||
avatar.Wait((int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.Ready)
|
||||
{
|
||||
avatar.Ready();
|
||||
}
|
||||
else if (Method == Method.Check)
|
||||
{
|
||||
// check动作在AutoFightTask主循环中处理,此处不做任何操作
|
||||
}
|
||||
else if (Method == Method.Aim)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
@@ -255,6 +286,14 @@ public class CombatCommand
|
||||
{
|
||||
avatar.KeyPress(Args![0]);
|
||||
}
|
||||
else if (Method == Method.Scroll)
|
||||
{
|
||||
avatar.Scroll(int.Parse(Args![0]));
|
||||
}
|
||||
else if (Method == Method.Round)
|
||||
{
|
||||
// 作为回合标记使用,不做任何操作
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
|
||||
@@ -28,7 +28,9 @@ public class CombatScriptBag(List<CombatScript> combatScripts)
|
||||
}
|
||||
|
||||
if (matchCount != avatars.Count) continue;
|
||||
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
|
||||
// Logger.LogInformation("匹配到战斗脚本:{Name},共{Cnt}条指令,涉及角色:{Str}",
|
||||
// combatScript.Name, combatScript.CombatCommands.Count, string.Join(",", combatScript.AvatarNames));
|
||||
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
|
||||
return combatScript.CombatCommands;
|
||||
}
|
||||
|
||||
|
||||