Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfb83c957e | ||
|
|
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 |
No files matched your search
@@ -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>
|
||||
@@ -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,10 +31,12 @@ 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;
|
||||
|
||||
@@ -137,12 +142,20 @@ 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<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();
|
||||
@@ -320,4 +333,4 @@ public partial class App : Application
|
||||
// log
|
||||
GetLogger<App>().LogDebug(e, "UnHandle Exception");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.55.0</Version>
|
||||
<Version>0.55.2-alpha.1</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
@@ -53,9 +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.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" />
|
||||
@@ -82,16 +84,17 @@
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.5" />
|
||||
<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.1" />
|
||||
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
@@ -22,6 +22,7 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
|
||||
using BetterGenshinImpact.GameTask.GetGridIcons;
|
||||
using BetterGenshinImpact.GameTask.AutoEat;
|
||||
using BetterGenshinImpact.GameTask.MapMask;
|
||||
using BetterGenshinImpact.GameTask.UseRedeemCode;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -172,6 +173,11 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public AutoEatConfig AutoEatConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 地图遮罩
|
||||
/// </summary>
|
||||
public MapMaskConfig MapMaskConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动使用
|
||||
/// </summary>
|
||||
@@ -261,6 +267,7 @@ public partial class AllConfig : ObservableObject
|
||||
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
TpConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
|
||||
@@ -75,4 +75,31 @@ public partial class MaskWindowConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _textOpacity = 1.0;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _overlayLayoutEditEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxTopRatio = 832.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxWidthRatio = 477.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxHeightRatio = 188.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListTopRatio = 807.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListWidthRatio = 477.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListHeightRatio = 24.0 / 1080;
|
||||
}
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
@@ -182,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());
|
||||
@@ -193,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);
|
||||
@@ -203,7 +203,7 @@ public class Genshin
|
||||
/// 获取当前在小地图上的位置坐标
|
||||
/// </summary>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromMap()
|
||||
public Point2f? GetPositionFromMap()
|
||||
{
|
||||
return GetPositionFromMap(MapTypes.Teyvat.ToString());
|
||||
}
|
||||
@@ -220,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))
|
||||
@@ -241,7 +241,7 @@ 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))
|
||||
@@ -377,6 +377,15 @@ 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>
|
||||
/// 调整时间
|
||||
|
||||
@@ -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 键盘操作
|
||||
|
||||
|
||||
@@ -118,6 +118,7 @@ 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);
|
||||
|
||||
@@ -22,6 +22,9 @@ 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;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
@@ -44,6 +47,10 @@ public class AutoFightTask : ISoloTask
|
||||
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;
|
||||
@@ -486,7 +493,58 @@ public class AutoFightTask : ISoloTask
|
||||
// 队伍中存在万叶的时候使用一次长E
|
||||
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)
|
||||
{
|
||||
Logger.LogWarning("换队拾取:当前队伍名称为空,尝试读取!");
|
||||
await Delay(1000, ct);
|
||||
await _returnMainUiTask.Start(ct);
|
||||
|
||||
for (int attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
|
||||
var enterGameAppear = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PartyBtnChooseView,
|
||||
() => { },
|
||||
ct,
|
||||
15,
|
||||
500
|
||||
);
|
||||
if (attempt == 2)
|
||||
{
|
||||
Logger.LogWarning("换队拾取:读取队伍名称失败!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//等待寻找2秒队伍按钮出现
|
||||
var timeWaitStart = 0;
|
||||
while(timeWaitStart < 6000)
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
var partyViewBtn = ra.Find(ElementAssets.Instance.PartyBtnChooseView);
|
||||
if (partyViewBtn.IsExist())
|
||||
{
|
||||
// OCR 当前队伍名称(无法单字,中间禁止空格)
|
||||
oldPartyName = ra.Find(new RecognitionObject
|
||||
{
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect(partyViewBtn.Right, partyViewBtn.Top, (int)(350 * _assetScale),
|
||||
partyViewBtn.Height)
|
||||
}).Text;
|
||||
Logger.LogInformation("换队拾取:当前队伍名称读取为:{oldPartyName}",oldPartyName);
|
||||
RunnerContext.Instance.PartyName = oldPartyName;
|
||||
// await _returnMainUiTask.Start(ct);
|
||||
break;
|
||||
}
|
||||
await Delay(200, ct);
|
||||
timeWaitStart += 200;
|
||||
}
|
||||
|
||||
var switchPartyFlag = false;
|
||||
if (picker == null && !timeOutFlag &&!string.IsNullOrEmpty(_taskParam.KazuhaPartyName) && oldPartyName != _taskParam.KazuhaPartyName)
|
||||
{
|
||||
|
||||
@@ -892,6 +892,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));
|
||||
|
||||
@@ -64,6 +64,11 @@ 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()
|
||||
@@ -102,7 +107,8 @@ public class CombatCommand
|
||||
&& Method != Method.MoveBy
|
||||
&& Method != Method.KeyDown
|
||||
&& Method != Method.KeyUp
|
||||
&& Method != Method.KeyPress)
|
||||
&& Method != Method.KeyPress
|
||||
&& Method != Method.Scroll)
|
||||
{
|
||||
avatar.Switch();
|
||||
}
|
||||
@@ -275,6 +281,10 @@ public class CombatCommand
|
||||
{
|
||||
avatar.KeyPress(Args![0]);
|
||||
}
|
||||
else if (Method == Method.Scroll)
|
||||
{
|
||||
avatar.Scroll(int.Parse(Args![0]));
|
||||
}
|
||||
else if (Method == Method.Round)
|
||||
{
|
||||
// 作为回合标记使用,不做任何操作
|
||||
|
||||
@@ -28,7 +28,8 @@ 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));
|
||||
return combatScript.CombatCommands;
|
||||
}
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ public class CombatScriptParser
|
||||
}
|
||||
|
||||
var names = string.Join(",", combatAvatarNames);
|
||||
Logger.LogDebug("战斗脚本解析完成,共{Cnt}条指令,涉及角色:{Str}", combatCommands.Count, names);
|
||||
// Logger.LogDebug("战斗脚本解析完成,共{Cnt}条指令,涉及角色:{Str}", combatCommands.Count, names);
|
||||
|
||||
return new CombatScript(combatAvatarNames, combatCommands);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ public class Method
|
||||
public static readonly Method KeyDown = new(["keydown"]);
|
||||
public static readonly Method KeyUp = new(["keyup"]);
|
||||
public static readonly Method KeyPress = new(["keypress"]);
|
||||
public static readonly Method Scroll = new(["scroll", "verticalscroll"]);
|
||||
public static readonly Method Round = new(["round"]);
|
||||
|
||||
public static IEnumerable<Method> Values
|
||||
@@ -63,6 +64,7 @@ public class Method
|
||||
yield return KeyDown;
|
||||
yield return KeyUp;
|
||||
yield return KeyPress;
|
||||
yield return Scroll;
|
||||
yield return Round;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,13 +715,6 @@ public class GeniusInvokationControl
|
||||
Sleep(500);
|
||||
}
|
||||
}
|
||||
|
||||
// 存在吞星之鲸的情况下,烧牌后等待加血动画
|
||||
if (duel.Characters.Any(c => c is { Name: "吞星之鲸" }))
|
||||
{
|
||||
Debug.WriteLine("存在吞星之鲸的情况下,烧牌后等待动画");
|
||||
Sleep(5000);
|
||||
}
|
||||
}
|
||||
|
||||
return ActionPhaseUseSkill(skillIndex);
|
||||
@@ -1255,4 +1248,4 @@ public class GeniusInvokationControl
|
||||
return -10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
|
||||
@@ -27,6 +28,7 @@ public class ActionFactory
|
||||
"mining" => new MiningHandler(),
|
||||
"fishing" => new FishingHandler(),
|
||||
"exit_and_relogin" => new ExitAndReloginHandler(),
|
||||
"wonderland_cycle" => new EnterAndExitWonderlandHandler(),
|
||||
"set_time" => new SetTimeHandler(),
|
||||
"use_gadget" => new UseGadgetHandler(),
|
||||
"pick_up_collect" => new PickUpCollectHandler(),
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
|
||||
public class EnterAndExitWonderlandHandler : IActionHandler
|
||||
{
|
||||
private readonly EnterAndExitWonderlandJob _enterAndExitWonderlandJob = new();
|
||||
|
||||
public async Task RunAsync(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
|
||||
{
|
||||
await _enterAndExitWonderlandJob.Start(ct);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,9 @@ public class ActionEnum(string code, string msg, ActionUseWaypointTypeEnum useWa
|
||||
|
||||
public static readonly ActionEnum Fishing = new("fishing", "钓鱼", ActionUseWaypointTypeEnum.Custom);
|
||||
public static readonly ActionEnum ExitAndRelogin = new("exit_and_relogin", "退出重新登录", ActionUseWaypointTypeEnum.Custom);
|
||||
|
||||
public static readonly ActionEnum EnterAndExitWonderland =
|
||||
new("wonderland_cycle", "进出千星奇域", ActionUseWaypointTypeEnum.Custom);
|
||||
public static readonly ActionEnum SetTime = new("set_time", "设置时间", ActionUseWaypointTypeEnum.Custom);
|
||||
public static readonly ActionEnum UseGadget = new("use_gadget", "使用小道具", ActionUseWaypointTypeEnum.Custom);
|
||||
public static readonly ActionEnum PickUpCollect = new("pick_up_collect", "聚集材料", ActionUseWaypointTypeEnum.Custom);
|
||||
|
||||
@@ -53,7 +53,9 @@ public class WaypointForTrack : Waypoint
|
||||
// 坐标系转换
|
||||
mapMatchMethod ??= TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
MapMatchMethod = mapMatchMethod;
|
||||
(MatX, MatY) = MapManager.GetMap(mapName, MapMatchMethod).ConvertGenshinMapCoordinatesToImageCoordinates((float)waypoint.X, (float)waypoint.Y);
|
||||
var MatP = MapManager.GetMap(mapName, MapMatchMethod).ConvertGenshinMapCoordinatesToImageCoordinates(new OpenCvSharp.Point2f((float)waypoint.X, (float)waypoint.Y));
|
||||
MatX = MatP.X;
|
||||
MatY = MatP.Y;
|
||||
X = MatX;
|
||||
Y = MatY;
|
||||
if (waypoint.Action == ActionEnum.CombatScript.Code)
|
||||
|
||||
@@ -20,7 +20,7 @@ public class Navigation
|
||||
{
|
||||
if (!_isWarmUp)
|
||||
{
|
||||
MapManager.GetMap(MapTypes.Teyvat, mapMatchMethod);
|
||||
MapManager.GetMap(MapTypes.Teyvat, mapMatchMethod).WarmUp();
|
||||
}
|
||||
|
||||
_isWarmUp = true;
|
||||
|
||||
@@ -693,7 +693,7 @@ public class PathExecutor
|
||||
await TryGetExpeditionRewardsDispatch(tpTask);
|
||||
var (tpX, tpY) = await tpTask.Tp(waypoint.GameX, waypoint.GameY, waypoint.MapName, forceTp);
|
||||
var (tprX, tprY) = MapManager.GetMap(waypoint.MapName, waypoint.MapMatchMethod)
|
||||
.ConvertGenshinMapCoordinatesToImageCoordinates((float)tpX, (float)tpY);
|
||||
.ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f((float)tpX, (float)tpY));
|
||||
Navigation.SetPrevPosition(tprX, tprY); // 通过上一个位置直接进行局部特征匹配
|
||||
await Delay(500, ct); // 多等一会
|
||||
}
|
||||
@@ -1091,6 +1091,7 @@ public class PathExecutor
|
||||
|| waypoint.Action == ActionEnum.Mining.Code
|
||||
|| waypoint.Action == ActionEnum.Fishing.Code
|
||||
|| waypoint.Action == ActionEnum.ExitAndRelogin.Code
|
||||
|| waypoint.Action == ActionEnum.EnterAndExitWonderland.Code
|
||||
|| waypoint.Action == ActionEnum.SetTime.Code
|
||||
|| waypoint.Action == ActionEnum.UseGadget.Code
|
||||
|| waypoint.Action == ActionEnum.PickUpCollect.Code)
|
||||
@@ -1349,6 +1350,7 @@ public class PathExecutor
|
||||
if (disabledUiButtonRa.IsExist())
|
||||
{
|
||||
_autoSkipTrigger.OnCapture(new CaptureContent(ra));
|
||||
noDisabledUiButtonTimes = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -62,13 +62,16 @@ public class PathRecorder : Singleton<PathRecorder>
|
||||
var waypoint = new Waypoint();
|
||||
var screen = TaskControl.CaptureToRectArea();
|
||||
var position = Navigation.GetPositionStable(screen, GetMapName(), matchingMethod);
|
||||
if (position == default)
|
||||
var nullablePosition = MapManager.GetMap(GetMapName(), matchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(position);
|
||||
if (nullablePosition == null)
|
||||
{
|
||||
TaskControl.Logger.LogWarning("未识别到当前位置!");
|
||||
return;
|
||||
}
|
||||
|
||||
position = MapManager.GetMap(GetMapName(), matchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(position);
|
||||
else
|
||||
{
|
||||
position = nullablePosition.Value;
|
||||
}
|
||||
waypoint.X = position.X;
|
||||
waypoint.Y = position.Y;
|
||||
waypoint.Type = WaypointType.Teleport.Code;
|
||||
@@ -91,12 +94,16 @@ public class PathRecorder : Singleton<PathRecorder>
|
||||
var screen = TaskControl.CaptureToRectArea();
|
||||
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
var position = Navigation.GetPositionStable(screen, GetMapName(), matchingMethod);
|
||||
position = MapManager.GetMap(GetMapName(), matchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(position);
|
||||
if (position == default)
|
||||
var nullablePosition = MapManager.GetMap(GetMapName(), matchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(position);
|
||||
if (nullablePosition == null)
|
||||
{
|
||||
TaskControl.Logger.LogWarning("未识别到当前位置!");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
position = nullablePosition.Value;
|
||||
}
|
||||
|
||||
waypoint.X = position.X;
|
||||
waypoint.Y = position.Y;
|
||||
|
||||
@@ -54,6 +54,47 @@ public partial class AutoPickTrigger : ITaskTrigger
|
||||
// 外部配置
|
||||
private AutoPickExternalConfig? _externalConfig;
|
||||
|
||||
/// <summary>
|
||||
/// 上一帧 OCR 结果
|
||||
/// </summary>
|
||||
private string? _lastOcrText;
|
||||
|
||||
/// <summary>
|
||||
/// 连续相同 OCR 结果的帧数
|
||||
/// </summary>
|
||||
private int _sameOcrFrameCount;
|
||||
|
||||
/// <summary>
|
||||
/// 判定为稳定所需的最小连续帧数
|
||||
/// </summary>
|
||||
private const int OcrStableFrameThreshold = 2;
|
||||
|
||||
/// <summary>
|
||||
/// OCR 帧稳定确认
|
||||
/// </summary>
|
||||
private bool IsOcrTextStable(string text)
|
||||
{
|
||||
if (text == _lastOcrText)
|
||||
{
|
||||
_sameOcrFrameCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lastOcrText = text;
|
||||
_sameOcrFrameCount = 1;
|
||||
}
|
||||
|
||||
if (_sameOcrFrameCount >= OcrStableFrameThreshold)
|
||||
{
|
||||
// 重置
|
||||
_lastOcrText = null;
|
||||
_sameOcrFrameCount = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public AutoPickTrigger()
|
||||
{
|
||||
_autoPickAssets = AutoPickAssets.Instance;
|
||||
@@ -315,44 +356,43 @@ public partial class AutoPickTrigger : ITaskTrigger
|
||||
}
|
||||
|
||||
speedTimer.Record("文字识别");
|
||||
|
||||
if (!string.IsNullOrEmpty(text))
|
||||
{
|
||||
// 处理OCR识别结果,清理无效字符并确保引号配对
|
||||
text = ProcessOcrText(text);
|
||||
|
||||
if (DoNotPick(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 单个字符不拾取
|
||||
if (text.Length <= 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 连续多帧识别结果一致,进行下一步
|
||||
if (!IsOcrTextStable(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (config.WhiteListEnabled && _whiteList.Contains(text))
|
||||
{
|
||||
LogPick(content, text);
|
||||
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
|
||||
return;
|
||||
}
|
||||
|
||||
speedTimer.Record("白名单判断");
|
||||
|
||||
if (isExcludeIcon)
|
||||
{
|
||||
//Debug.WriteLine("AutoPickTrigger: 物品图标是聊天气泡,一般是NPC对话,不拾取");
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.BlackListEnabled)
|
||||
{
|
||||
if (_blackList.Contains(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_fuzzyBlackList.Count > 0)
|
||||
{
|
||||
if (_fuzzyBlackList.Any(item => text.Contains(item)))
|
||||
@@ -361,9 +401,7 @@ public partial class AutoPickTrigger : ITaskTrigger
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speedTimer.Record("黑名单判断");
|
||||
|
||||
LogPick(content, text);
|
||||
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
|
||||
}
|
||||
|
||||
@@ -69,6 +69,12 @@ public partial class AutoSkipConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private string _clickChatOption = "优先选择第一个选项";
|
||||
|
||||
/// <summary>
|
||||
/// 自定义优先选项启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _customPriorityOptionsEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 自定义优先选项文本,每行一个或用分号分隔
|
||||
/// </summary>
|
||||
@@ -108,10 +114,6 @@ public partial class AutoSkipConfig : ObservableObject
|
||||
{
|
||||
return ClickChatOption == "随机选择选项";
|
||||
}
|
||||
public bool IsClickCustomPriorityOption()
|
||||
{
|
||||
return ClickChatOption == "自定义优先选项";
|
||||
}
|
||||
public bool IsClickNoneChatOption()
|
||||
{
|
||||
return ClickChatOption == "不选择选项";
|
||||
@@ -149,6 +151,12 @@ public partial class AutoSkipConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool _closePopupPagedEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// JS调用时跳过内置默认点击选项
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _skipBuiltInClickOptions = false;
|
||||
|
||||
// /// <summary>
|
||||
// /// 使用交互键
|
||||
// /// 使用鼠标
|
||||
|
||||
@@ -40,6 +40,9 @@ public partial class AutoSkipTrigger : ITaskTrigger
|
||||
public bool IsEnabled { get; set; }
|
||||
public int Priority => 20;
|
||||
public bool IsExclusive => false;
|
||||
|
||||
public GameUiCategory SupportedGameUiCategory => GameUiCategory.Talk;
|
||||
|
||||
|
||||
public bool IsBackgroundRunning { get; private set; }
|
||||
|
||||
@@ -170,9 +173,9 @@ public partial class AutoSkipTrigger : ITaskTrigger
|
||||
GetDailyRewardsEsc(_config, content);
|
||||
|
||||
// 找左上角剧情自动的按钮
|
||||
using var foundRectArea = content.CaptureRectArea.Find(_autoSkipAssets.DisabledUiButtonRo);
|
||||
|
||||
var isPlaying = !foundRectArea.IsEmpty(); // 播放中
|
||||
var isPlaying = content.CurrentGameUiCategory == GameUiCategory.Talk
|
||||
|| Bv.IsInTalkUi(content.CaptureRectArea); // 播放中
|
||||
|
||||
if (!isPlaying && (DateTime.Now - _prevPlayingTime).TotalSeconds <= 5)
|
||||
{
|
||||
@@ -486,21 +489,18 @@ public partial class AutoSkipTrigger : ITaskTrigger
|
||||
/// </summary>
|
||||
private bool ChatOptionChoose(ImageRegion region)
|
||||
{
|
||||
if (_config.IsClickNoneChatOption())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
|
||||
// 感叹号识别 遇到直接点击
|
||||
using var exclamationIconRa = region.Find(_autoSkipAssets.ExclamationIconRo);
|
||||
if (!exclamationIconRa.IsEmpty())
|
||||
if (!_config.IsClickNoneChatOption())
|
||||
{
|
||||
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
|
||||
exclamationIconRa.Click();
|
||||
AutoSkipLog("点击感叹号选项");
|
||||
return true;
|
||||
// 感叹号识别 遇到直接点击
|
||||
using var exclamationIconRa = region.Find(_autoSkipAssets.ExclamationIconRo);
|
||||
if (!exclamationIconRa.IsEmpty())
|
||||
{
|
||||
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
|
||||
exclamationIconRa.Click();
|
||||
AutoSkipLog("点击感叹号选项");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 气泡识别
|
||||
@@ -549,8 +549,8 @@ public partial class AutoSkipTrigger : ITaskTrigger
|
||||
|
||||
if (rs.Count > 0)
|
||||
{
|
||||
// 自定义优先选项匹配
|
||||
if (_config.IsClickCustomPriorityOption() && !string.IsNullOrEmpty(_config.CustomPriorityOptions))
|
||||
// 自定义优先选项匹配
|
||||
if (_config.CustomPriorityOptionsEnabled && !string.IsNullOrEmpty(_config.CustomPriorityOptions))
|
||||
{
|
||||
var customOptions = _config.CustomPriorityOptions
|
||||
.Split(new[] { '\r', '\n', ';', ';' }, StringSplitOptions.RemoveEmptyEntries)
|
||||
@@ -570,66 +570,75 @@ public partial class AutoSkipTrigger : ITaskTrigger
|
||||
}
|
||||
}
|
||||
}
|
||||
// 内置关键词 匹配
|
||||
foreach (var item in rs)
|
||||
{
|
||||
// 选择关键词
|
||||
if (_selectList.Any(s => item.Text.Contains(s)))
|
||||
{
|
||||
ClickOcrRegion(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 不选择关键词
|
||||
if (_pauseList.Any(s => item.Text.Contains(s)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if(_config.IsClickNoneChatOption()){
|
||||
return false;
|
||||
}
|
||||
|
||||
// 橙色选项
|
||||
foreach (var item in rs)
|
||||
|
||||
|
||||
if (!_config.SkipBuiltInClickOptions)
|
||||
{
|
||||
var textMat = item.ToImageRegion().SrcMat;
|
||||
if (IsOrangeOption(textMat))
|
||||
// 内置关键词 匹配
|
||||
foreach (var item in rs)
|
||||
{
|
||||
if (_config.AutoGetDailyRewardsEnabled && (item.Text.Contains("每日") || item.Text.Contains("委托")))
|
||||
{
|
||||
ClickOcrRegion(item, "每日委托");
|
||||
TaskControl.Sleep(800);
|
||||
|
||||
// 6.2 每日提示确认
|
||||
var ra1 = TaskControl.CaptureToRectArea();
|
||||
if (Bv.ClickBlackConfirmButton(ra1))
|
||||
{
|
||||
_logger.LogInformation("存在提示并确认");
|
||||
}
|
||||
ra1.Dispose();
|
||||
|
||||
_prevGetDailyRewardsTime = DateTime.Now; // 记录领取时间
|
||||
}
|
||||
else if (_config.AutoReExploreEnabled && (item.Text.Contains("探索") || item.Text.Contains("派遣")))
|
||||
{
|
||||
ClickOcrRegion(item, "探索派遣");
|
||||
Thread.Sleep(800); // 等待探索派遣界面打开
|
||||
new OneKeyExpeditionTask().Run(_autoSkipAssets);
|
||||
}
|
||||
else
|
||||
// 选择关键词
|
||||
if (_selectList.Any(s => item.Text.Contains(s)))
|
||||
{
|
||||
ClickOcrRegion(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
// 不选择关键词
|
||||
if (_pauseList.Any(s => item.Text.Contains(s)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 默认不选择关键词
|
||||
foreach (var item in rs)
|
||||
{
|
||||
// 不选择关键词
|
||||
if (_defaultPauseList.Any(s => item.Text.Contains(s)))
|
||||
// 橙色选项
|
||||
foreach (var item in rs)
|
||||
{
|
||||
return true;
|
||||
var textMat = item.ToImageRegion().SrcMat;
|
||||
if (IsOrangeOption(textMat))
|
||||
{
|
||||
if (_config.AutoGetDailyRewardsEnabled && (item.Text.Contains("每日") || item.Text.Contains("委托")))
|
||||
{
|
||||
ClickOcrRegion(item, "每日委托");
|
||||
TaskControl.Sleep(800);
|
||||
|
||||
// 6.2 每日提示确认
|
||||
var ra1 = TaskControl.CaptureToRectArea();
|
||||
if (Bv.ClickBlackConfirmButton(ra1))
|
||||
{
|
||||
_logger.LogInformation("存在提示并确认");
|
||||
}
|
||||
ra1.Dispose();
|
||||
|
||||
_prevGetDailyRewardsTime = DateTime.Now; // 记录领取时间
|
||||
}
|
||||
else if (_config.AutoReExploreEnabled && (item.Text.Contains("探索") || item.Text.Contains("派遣")))
|
||||
{
|
||||
ClickOcrRegion(item, "探索派遣");
|
||||
Thread.Sleep(800); // 等待探索派遣界面打开
|
||||
new OneKeyExpeditionTask().Run(_autoSkipAssets);
|
||||
}
|
||||
else
|
||||
{
|
||||
ClickOcrRegion(item);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认不选择关键词
|
||||
foreach (var item in rs)
|
||||
{
|
||||
// 不选择关键词
|
||||
if (_defaultPauseList.Any(s => item.Text.Contains(s)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ public class GiPathPoint
|
||||
var pt = MapManager.GetMap(MapTypes.Teyvat, matchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(point);
|
||||
return new GiPathPoint
|
||||
{
|
||||
Pt = pt,
|
||||
// pt will not be null
|
||||
Pt = pt ?? new Point2f(0, 0),
|
||||
MatchPt = point,
|
||||
Index = index,
|
||||
Time = DateTime.Now
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 原神世界坐标
|
||||
@@ -6,12 +8,6 @@
|
||||
/// </summary>
|
||||
public class GiWorldPosition
|
||||
{
|
||||
/// <summary>
|
||||
/// 坐标描述和
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 坐标 x,y,z 三个值,分别代表纵向、高度、横向,采用原神实际的坐标系
|
||||
/// 由于这个坐标系和一般的坐标系不同,所以为了方便理解,设这3个值为a,b,c
|
||||
@@ -37,11 +33,16 @@ public class GiTpPosition: GiWorldPosition
|
||||
public string? Name { get; set; } // tp 名称
|
||||
public string? Type { get; set; } // tp 类型
|
||||
public string? Country { get; set; } // 所在国家
|
||||
public string? Area { get; set; } // 所在区域
|
||||
|
||||
[JsonIgnore]
|
||||
public string[] Areas { get; set; } = []; // 所在区域
|
||||
[JsonIgnore]
|
||||
public string[] Rewards { get; set; } = [];
|
||||
[JsonIgnore]
|
||||
public string Level1Area => Areas[0]; // 一级区域
|
||||
// 实际传送的坐标
|
||||
public decimal[] TranPosition { get; set; } = new decimal[3];
|
||||
public double TranX => (double)TranPosition[2];
|
||||
public double TranY => (double)TranPosition[0];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ public class TpTask
|
||||
var center = GetBigMapCenterPoint(MapTypes.Teyvat.ToString());
|
||||
var giTpPoint = GetNearestGoddess(center.X, center.Y);
|
||||
country = giTpPoint.Country;
|
||||
area = giTpPoint.Area;
|
||||
area = giTpPoint.Level1Area;
|
||||
x = giTpPoint.X;
|
||||
y = giTpPoint.Y;
|
||||
revivePoint = giTpPoint;
|
||||
@@ -245,6 +245,7 @@ public class TpTask
|
||||
// 直接切换地区
|
||||
await SwitchArea(MapTypesExtensions.ParseFromName(mapName).GetDescription());
|
||||
}
|
||||
await Delay(50, ct);
|
||||
|
||||
|
||||
// 3. 调整初始缩放等级,避免识别中心点失败
|
||||
@@ -389,7 +390,7 @@ public class TpTask
|
||||
/// <returns></returns>
|
||||
private (double clickX, double clickY) ConvertToGameRegionPosition(string mapName, Rect bigMapInAllMapRect, double x, double y)
|
||||
{
|
||||
var (picX, picY) = MapManager.GetMap(mapName, _mapMatchingMethod).ConvertGenshinMapCoordinatesToImageCoordinates((float)x, (float)y);
|
||||
var (picX, picY) = MapManager.GetMap(mapName, _mapMatchingMethod).ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f((float)x, (float)y));
|
||||
var picRect = MapManager.GetMap(mapName, _mapMatchingMethod).ConvertGenshinMapCoordinatesToImageCoordinates(bigMapInAllMapRect);
|
||||
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
|
||||
var clickX = (picX - picRect.X) / picRect.Width * _captureRect.Width;
|
||||
@@ -769,7 +770,7 @@ public class TpTask
|
||||
rect = new Rect(rect.X * s, rect.Y * s, rect.Width * s, rect.Height * s);
|
||||
}
|
||||
|
||||
return MapManager.GetMap(mapName, _mapMatchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(rect);
|
||||
return MapManager.GetMap(mapName, _mapMatchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(rect)!.Value;
|
||||
}
|
||||
|
||||
public Point2f GetBigMapCenterPoint(string mapName)
|
||||
@@ -793,7 +794,7 @@ public class TpTask
|
||||
(x, y) = (p.X * TeyvatMap.BigMap256ScaleTo2048, p.Y * TeyvatMap.BigMap256ScaleTo2048);
|
||||
}
|
||||
|
||||
return MapManager.GetMap(mapName, _mapMatchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(x, y));
|
||||
return MapManager.GetMap(mapName, _mapMatchingMethod).ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(x, y))!.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -927,6 +928,7 @@ public class TpTask
|
||||
|
||||
// 2. 判断是否已经点出传送按钮
|
||||
var hasTeleportButton = CheckTeleportButton(imageRegion);
|
||||
await Delay(50, ct);
|
||||
if (hasTeleportButton) return; // 可以传送了,结束
|
||||
// 3. 没点出传送按钮,且不存在外部地图关闭按钮
|
||||
// 说明只有两种可能,a. 点出来的是未激活传送点或者标点 b. 选择传送点选项列表
|
||||
|
||||
@@ -21,6 +21,12 @@ public partial class AutoWoodConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool _woodCountOcrEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 使用进出千星奇域刷新CD
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _useWonderlandRefresh = true;
|
||||
|
||||
// /// <summary>
|
||||
// /// 按下两次ESC键,原因见:
|
||||
// /// https://github.com/babalae/better-genshin-impact/issues/235
|
||||
|
||||
@@ -4,6 +4,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.AutoWood.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoWood.Utils;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Genshin.Settings;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
@@ -45,6 +46,8 @@ public partial class AutoWoodTask : ISoloTask
|
||||
|
||||
private CancellationToken _ct;
|
||||
|
||||
private EnterAndExitWonderlandJob _enterAndExitWonderlandJob;
|
||||
|
||||
public AutoWoodTask(WoodTaskParam taskParam)
|
||||
{
|
||||
this._taskParam = taskParam;
|
||||
@@ -52,10 +55,11 @@ public partial class AutoWoodTask : ISoloTask
|
||||
AutoWoodAssets.DestroyInstance();
|
||||
}
|
||||
|
||||
public Task Start(CancellationToken ct)
|
||||
public async Task Start(CancellationToken ct)
|
||||
{
|
||||
_assets = AutoWoodAssets.Instance;
|
||||
_printer = new WoodStatisticsPrinter(_assets);
|
||||
_enterAndExitWonderlandJob = new EnterAndExitWonderlandJob();
|
||||
var runTimeWatch = new Stopwatch();
|
||||
_ct = ct;
|
||||
_printer.Ct = _ct;
|
||||
@@ -112,12 +116,12 @@ public partial class AutoWoodTask : ISoloTask
|
||||
break;
|
||||
}
|
||||
|
||||
Felling(_taskParam, i + 1 == _taskParam.WoodRoundNum);
|
||||
await Felling(_taskParam, i + 1 == _taskParam.WoodRoundNum);
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
Sleep(500, _ct);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -382,7 +386,7 @@ public partial class AutoWoodTask : ISoloTask
|
||||
}
|
||||
}
|
||||
|
||||
private void Felling(WoodTaskParam taskParam, bool isLast = false)
|
||||
private async Task Felling(WoodTaskParam taskParam, bool isLast = false)
|
||||
{
|
||||
// 1. 按 z 触发「王树瑞佑」
|
||||
PressZ(taskParam);
|
||||
@@ -399,11 +403,19 @@ public partial class AutoWoodTask : ISoloTask
|
||||
if (_printer.WoodStatisticsAlwaysEmpty() || _printer.ReachedWoodMaxCount) return;
|
||||
}
|
||||
|
||||
// 2. 按下 ESC 打开菜单 并退出游戏
|
||||
PressEsc(taskParam);
|
||||
if (TaskContext.Instance().Config.AutoWoodConfig.UseWonderlandRefresh)
|
||||
{
|
||||
// 使用进出千星奇域刷新CD
|
||||
await _enterAndExitWonderlandJob.Start(_ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 2. 按下 ESC 打开菜单 并退出游戏
|
||||
PressEsc(taskParam);
|
||||
|
||||
// 3. 等待进入游戏
|
||||
EnterGame(taskParam);
|
||||
// 3. 等待进入游戏
|
||||
EnterGame(taskParam);
|
||||
}
|
||||
|
||||
// 手动 GC
|
||||
GC.Collect();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask;
|
||||
@@ -17,6 +18,8 @@ public class CaptureContent : IDisposable
|
||||
public int FrameRate => (int)(1000 / TimerInterval);
|
||||
|
||||
public ImageRegion CaptureRectArea { get; }
|
||||
|
||||
public GameUiCategory CurrentGameUiCategory;
|
||||
|
||||
public CaptureContent(Mat image, int frameIndex, double interval)
|
||||
{
|
||||
|
||||
@@ -17,20 +17,58 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
|
||||
/// <summary>
|
||||
/// 模仿OpenCv的静态类
|
||||
/// 用于原神的各类识别与控制操作
|
||||
///
|
||||
/// 此处主要是对游戏内的一些状态进行识别
|
||||
/// </summary>
|
||||
public enum GameUiCategory
|
||||
{
|
||||
Unknown,
|
||||
Main,
|
||||
Talk,
|
||||
BigMap
|
||||
}
|
||||
|
||||
public static partial class Bv
|
||||
{
|
||||
|
||||
public static string WhichGameUi()
|
||||
public static GameUiCategory WhichGameUi()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
using var region = TaskControl.CaptureToRectArea();
|
||||
return WhichGameUi(region);
|
||||
}
|
||||
|
||||
public static GameUiCategory WhichGameUi(ImageRegion region)
|
||||
{
|
||||
if (IsInTalkUi(region))
|
||||
{
|
||||
return GameUiCategory.Talk;
|
||||
}
|
||||
|
||||
if (IsInBigMapUi(region))
|
||||
{
|
||||
return GameUiCategory.BigMap;
|
||||
}
|
||||
|
||||
if (IsInMainUi(region))
|
||||
{
|
||||
return GameUiCategory.Main;
|
||||
}
|
||||
|
||||
return GameUiCategory.Unknown;
|
||||
}
|
||||
|
||||
public static GameUiCategory WhichGameUiForTriggers(ImageRegion region)
|
||||
{
|
||||
if (IsInTalkUi(region))
|
||||
{
|
||||
return GameUiCategory.Talk;
|
||||
}
|
||||
|
||||
if (IsInBigMapUi(region))
|
||||
{
|
||||
return GameUiCategory.BigMap;
|
||||
}
|
||||
|
||||
return GameUiCategory.Unknown;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 是否在主界面
|
||||
/// </summary>
|
||||
@@ -38,7 +76,8 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInMainUi(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(ElementAssets.Instance.PaimonMenuRo).IsExist() && !IsInRevivePrompt(captureRa);
|
||||
using var ra = captureRa.Find(ElementAssets.Instance.PaimonMenuRo);
|
||||
return ra.IsExist() && !IsInRevivePrompt(captureRa);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -108,7 +147,8 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInAnyClosableUi(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(QuickTeleportAssets.Instance.MapCloseButtonRo).IsExist();
|
||||
using var ra = captureRa.Find(QuickTeleportAssets.Instance.MapCloseButtonRo);
|
||||
return ra.IsExist();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -118,7 +158,8 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInPartyViewUi(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(ElementAssets.Instance.PartyBtnChooseView).IsExist();
|
||||
using var ra = captureRa.Find(ElementAssets.Instance.PartyBtnChooseView);
|
||||
return ra.IsExist();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,7 +170,11 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> WaitForPartyViewUi(CancellationToken ct, int retryTimes = 5)
|
||||
{
|
||||
return await NewRetry.WaitForAction(() => IsInPartyViewUi(TaskControl.CaptureToRectArea()), ct, retryTimes);
|
||||
return await NewRetry.WaitForAction(() =>
|
||||
{
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
return IsInPartyViewUi(ra);
|
||||
}, ct, retryTimes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -139,7 +184,14 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInBigMapUi(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(QuickTeleportAssets.Instance.MapScaleButtonRo).IsExist() || captureRa.Find(QuickTeleportAssets.Instance.MapSettingsButtonRo).IsExist();
|
||||
using var scaleRa = captureRa.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
|
||||
if (scaleRa.IsExist())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
using var settingsRa = captureRa.Find(QuickTeleportAssets.Instance.MapSettingsButtonRo);
|
||||
return settingsRa.IsExist();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -150,12 +202,13 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool BigMapIsUnderground(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(QuickTeleportAssets.Instance.MapUndergroundSwitchButtonRo).IsExist();
|
||||
using var ra = captureRa.Find(QuickTeleportAssets.Instance.MapUndergroundSwitchButtonRo);
|
||||
return ra.IsExist();
|
||||
}
|
||||
|
||||
public static double GetBigMapScale(ImageRegion region)
|
||||
{
|
||||
var scaleRa = region.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
|
||||
using var scaleRa = region.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
|
||||
if (scaleRa.IsEmpty())
|
||||
{
|
||||
throw new Exception("当前未处于大地图界面,不能使用GetBigMapScale方法");
|
||||
@@ -171,8 +224,10 @@ public static partial class Bv
|
||||
|
||||
public static MotionStatus GetMotionStatus(ImageRegion captureRa)
|
||||
{
|
||||
var spaceExist = captureRa.Find(ElementAssets.Instance.SpaceKey).IsExist();
|
||||
var xExist = captureRa.Find(ElementAssets.Instance.XKey).IsExist();
|
||||
using var spaceRa = captureRa.Find(ElementAssets.Instance.SpaceKey);
|
||||
var spaceExist = spaceRa.IsExist();
|
||||
using var xRa = captureRa.Find(ElementAssets.Instance.XKey);
|
||||
var xExist = xRa.IsExist();
|
||||
if (spaceExist)
|
||||
{
|
||||
return xExist ? MotionStatus.Climb : MotionStatus.Fly;
|
||||
@@ -223,7 +278,7 @@ public static partial class Bv
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect(0, region.Height / 4 * 3, region.Width, region.Height / 4)
|
||||
});
|
||||
var r = list.FirstOrDefault(r => r.Text.Contains("复苏"));
|
||||
using var r = list.FirstOrDefault(r => r.Text.Contains("复苏"));
|
||||
if (r != null)
|
||||
{
|
||||
r.Click();
|
||||
@@ -258,12 +313,14 @@ public static partial class Bv
|
||||
{
|
||||
var ra = captureRa;
|
||||
|
||||
if (ra.Find(GameLoadingAssets.Instance.GirlMoonRo).IsExist())
|
||||
using var girlRa = ra.Find(GameLoadingAssets.Instance.GirlMoonRo);
|
||||
if (girlRa.IsExist())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return ra.Find(GameLoadingAssets.Instance.WelkinMoonRo).IsExist();
|
||||
|
||||
using var moonRa = ra.Find(GameLoadingAssets.Instance.WelkinMoonRo);
|
||||
return moonRa.IsExist();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -273,7 +330,8 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInTalkUi(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(AutoSkipAssets.Instance.DisabledUiButtonRo).IsExist();
|
||||
using var ra = captureRa.Find(AutoSkipAssets.Instance.DisabledUiButtonRo);
|
||||
return ra.IsExist();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -284,7 +342,11 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> WaitAndSkipForTalkUi(CancellationToken ct, int retryTimes = 5)
|
||||
{
|
||||
return await NewRetry.WaitForAction(() => IsInTalkUi(TaskControl.CaptureToRectArea()), ct, retryTimes, 500);
|
||||
return await NewRetry.WaitForAction(() =>
|
||||
{
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
return IsInTalkUi(ra);
|
||||
}, ct, retryTimes, 500);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -295,7 +357,8 @@ public static partial class Bv
|
||||
/// <returns></returns>
|
||||
public static bool IsInPromptDialog(ImageRegion captureRa)
|
||||
{
|
||||
return captureRa.Find(ElementAssets.Instance.PromptDialogLeftBottomStar).IsExist();
|
||||
using var ra = captureRa.Find(ElementAssets.Instance.PromptDialogLeftBottomStar);
|
||||
return ra.IsExist();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,4 +367,4 @@ public enum MotionStatus
|
||||
Normal, // 正常
|
||||
Fly, // 飞行
|
||||
Climb, // 攀爬
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 810 B |
@@ -15,6 +15,7 @@ public class ElementAssets : BaseAssets<ElementAssets>
|
||||
public RecognitionObject BtnWhiteCancel;
|
||||
public RecognitionObject BtnBlackConfirm;
|
||||
public RecognitionObject BtnBlackCancel;
|
||||
public RecognitionObject BtnBackTeyvat;
|
||||
public RecognitionObject BtnOnlineYes;
|
||||
public RecognitionObject BtnOnlineNo;
|
||||
public Lazy<RecognitionObject> BtnExitDoor;
|
||||
@@ -88,6 +89,11 @@ public class ElementAssets : BaseAssets<ElementAssets>
|
||||
|
||||
public RecognitionObject LeylineDisorderIconRo;
|
||||
|
||||
public RecognitionObject EscDown;
|
||||
public RecognitionObject EscWonderlandHome;
|
||||
public RecognitionObject WonderlandEnter;
|
||||
public RecognitionObject WonderlandClose;
|
||||
|
||||
public RecognitionObject Index1;
|
||||
public RecognitionObject Index2;
|
||||
public RecognitionObject Index3;
|
||||
@@ -147,6 +153,12 @@ public class ElementAssets : BaseAssets<ElementAssets>
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "btn_black_cancel.png", systemInfo),
|
||||
Use3Channels = true
|
||||
}.InitTemplate();
|
||||
BtnBackTeyvat = new RecognitionObject
|
||||
{
|
||||
Name = "BtnBackTeyvat",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "btn_back_teyvat.png", systemInfo),
|
||||
}.InitTemplate();
|
||||
BtnOnlineYes = new RecognitionObject
|
||||
{
|
||||
Name = "BtnOnlineYes",
|
||||
@@ -678,7 +690,31 @@ public class ElementAssets : BaseAssets<ElementAssets>
|
||||
RegionOfInterest = new Rect(0, 0, (int)(200 * AssetScale), (int)(200 * AssetScale)),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
|
||||
EscDown = new RecognitionObject
|
||||
{
|
||||
Name = "EscDown",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "esc_down.png", systemInfo),
|
||||
}.InitTemplate();
|
||||
EscWonderlandHome = new RecognitionObject
|
||||
{
|
||||
Name = "EscWonderlandHome",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "esc_wonderland_home.png", systemInfo),
|
||||
}.InitTemplate();
|
||||
WonderlandEnter = new RecognitionObject
|
||||
{
|
||||
Name = "WonderlandEnter",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "wonderland_enter.png", systemInfo),
|
||||
}.InitTemplate();
|
||||
WonderlandClose = new RecognitionObject
|
||||
{
|
||||
Name = "WonderlandClose",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "wonderland_close.png", systemInfo),
|
||||
}.InitTemplate();
|
||||
|
||||
Rect partyRect = new Rect(CaptureRect.Width - (int)(65 * AssetScale), (int)(155 * AssetScale), (int)(35 * AssetScale), (int)(600 * AssetScale));
|
||||
// 1 2 3 4 按键
|
||||
|
||||
@@ -1,28 +1,48 @@
|
||||
{
|
||||
{
|
||||
"info": {
|
||||
"authors": [
|
||||
{
|
||||
"links": "",
|
||||
"name": "起个名字好难的喵"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"last_modified_time": 1769335370377,
|
||||
"map_match_method": "",
|
||||
"map_name": "Teyvat",
|
||||
"name": "冒险家协会_枫丹",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"author": "yemaxul",
|
||||
"version": "2.0",
|
||||
"description": "传送到枫丹冒险家协会",
|
||||
"bgiVersion": "0.35.0"
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"x": 4508.97509765625,
|
||||
"y": 3630.557373046875,
|
||||
"type": "teleport",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "teleport",
|
||||
"x": 4509.001953125,
|
||||
"y": 3630.5986328125
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"x": 4495.0,
|
||||
"y": 3638.0,
|
||||
"type": "target",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 4500.5625,
|
||||
"y": 3630.69677734375
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"move_mode": "walk",
|
||||
"type": "target",
|
||||
"x": 4495.94140625,
|
||||
"y": 3638.5205078125
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,60 +1,93 @@
|
||||
{
|
||||
{
|
||||
"info": {
|
||||
"name": "璃月凯瑟琳",
|
||||
"type": "collect",
|
||||
"author": "½",
|
||||
"version": "1.0",
|
||||
"authors": [
|
||||
{
|
||||
"links": "",
|
||||
"name": "起个名字好难的喵"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"bgiVersion": "0.35.1"
|
||||
"last_modified_time": 1769343676091,
|
||||
"map_match_method": "",
|
||||
"map_name": "Teyvat",
|
||||
"name": "冒险家协会_璃月",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"id": 1,
|
||||
"x": 267.958984375,
|
||||
"y": -665.10888671875,
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport"
|
||||
"type": "teleport",
|
||||
"x": 267.947265625,
|
||||
"y": -665.119140625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"x": 258.3662109375,
|
||||
"y": -663.82177734375,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 247.734375,
|
||||
"y": -662.94921875
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"x": 246.689453125,
|
||||
"y": -662.83740234375,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 230.8896484375,
|
||||
"y": -660.6494140625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 4,
|
||||
"x": 233.8564453125,
|
||||
"y": -661.95849609375,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 227.0048828125,
|
||||
"y": -658.09765625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 5,
|
||||
"x": 219.0625,
|
||||
"y": -657.271484375,
|
||||
"type": "target",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 217.0625,
|
||||
"y": -657.5771484375
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 6,
|
||||
"x": 203.84765625,
|
||||
"y": -659.7158203125,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": 209.7392578125,
|
||||
"y": -659.1416015625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 7,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 204.67578125,
|
||||
"y": -662.45703125
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 8,
|
||||
"move_mode": "walk",
|
||||
"type": "target",
|
||||
"x": 203.5126953125,
|
||||
"y": -659.86328125
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,36 +1,57 @@
|
||||
{
|
||||
{
|
||||
"info": {
|
||||
"name": "稻妻凯瑟琳",
|
||||
"type": "collect",
|
||||
"author": "½",
|
||||
"version": "1.0",
|
||||
"authors": [
|
||||
{
|
||||
"links": "",
|
||||
"name": "起个名字好难的喵"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"bgiVersion": "0.35.1"
|
||||
"last_modified_time": 1769342575161,
|
||||
"map_match_method": "",
|
||||
"map_name": "Teyvat",
|
||||
"name": "冒险家协会_稻妻",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"id": 1,
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport",
|
||||
"x": -4402.556640625,
|
||||
"y": -3053.041015625
|
||||
"x": -4402.544921875,
|
||||
"y": -3052.9765625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"x": -4408.984375,
|
||||
"y": -3068.2470703125,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": -4416.03515625,
|
||||
"y": -3081.666015625
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"x": -4418.185546875,
|
||||
"y": -3086.4326171875,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": ""
|
||||
"type": "path",
|
||||
"x": -4419.468791093892,
|
||||
"y": -3086.062542740572
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 4,
|
||||
"move_mode": "walk",
|
||||
"type": "target",
|
||||
"x": -4418.54296875,
|
||||
"y": -3086.87890625
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"info": {
|
||||
"authors": [
|
||||
{
|
||||
"links": "",
|
||||
"name": "起个名字好难的喵"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"last_modified_time": 1769342917860,
|
||||
"map_match_method": "",
|
||||
"map_name": "Teyvat",
|
||||
"name": "冒险家协会_须弥",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport",
|
||||
"x": 2786.9990234375,
|
||||
"y": -503.1044921875
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 2786.93359375,
|
||||
"y": -488.0771484375
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 2771.9033203125,
|
||||
"y": -476.23046875
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 4,
|
||||
"move_mode": "walk",
|
||||
"type": "target",
|
||||
"x": 2765.5185546875,
|
||||
"y": -476.056640625
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -4,7 +4,6 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Newtonsoft.Json;
|
||||
@@ -37,13 +36,13 @@ public class MapLazyAssets : Singleton<MapLazyAssets>
|
||||
public MapLazyAssets()
|
||||
{
|
||||
var json = File.ReadAllText(Global.Absolute(@"GameTask\AutoTrackPath\Assets\tp.json"));
|
||||
var worldScenes = JsonConvert.DeserializeObject<List<GiWorldScene>>(json) ?? throw new Exception("tp.json deserialize failed");
|
||||
var worldScenes = Newtonsoft.Json.Linq.JObject.Parse(json)["data"]?.ToObject<List<GiWorldScene>>() ?? throw new Exception("tp.json deserialization failed");
|
||||
ScenesDic = worldScenes.ToDictionary(x => x.MapName, x => x);
|
||||
|
||||
|
||||
// 取出秘境 description=Domain
|
||||
var teyvatTpPositions = ScenesDic[nameof(MapTypes.Teyvat)].Points;
|
||||
foreach (var tp in teyvatTpPositions.Where(tp => tp.Description != null && (tp.Description == "天赋" || tp.Description == "武器" || tp.Description.StartsWith("圣遗物"))))
|
||||
foreach (var tp in teyvatTpPositions.Where(tp => tp.Type == "BlessDomain" || tp.Type == "ForgeryDomain" || tp.Type == "MasteryDomain"))
|
||||
{
|
||||
DomainPositionMap[tp.Name!] = tp;
|
||||
DomainNameList.Add(tp.Name!);
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Vanara.PInvoke;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Job;
|
||||
|
||||
public class EnterAndExitWonderlandJob
|
||||
{
|
||||
private ElementAssets _assets = ElementAssets.Instance;
|
||||
|
||||
public async Task Start(CancellationToken ct)
|
||||
{
|
||||
Logger.LogInformation("进入千星奇域");
|
||||
SystemControl.FocusWindow(TaskContext.Instance().GameHandle);
|
||||
|
||||
// 等待千星奇域界面出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.WonderlandClose,
|
||||
() => Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F6),
|
||||
ct,
|
||||
10,
|
||||
1000
|
||||
);
|
||||
|
||||
// 点击一个奇域并等待大厅按钮出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.BtnBlackConfirm,
|
||||
() => GameCaptureRegion.GameRegion1080PPosClick(680, 310),
|
||||
ct,
|
||||
5,
|
||||
800
|
||||
);
|
||||
|
||||
// // 点击大厅按钮并等待公共大厅按钮出现
|
||||
// await NewRetry.WaitForElementAppear(
|
||||
// _assets.WonderlandEnter,
|
||||
// () =>
|
||||
// {
|
||||
// using var ra = CaptureToRectArea();
|
||||
// Bv.FindAndClick(ra, _assets.EscWonderlandHome);
|
||||
// },
|
||||
// ct,
|
||||
// 5,
|
||||
// 1000
|
||||
// );
|
||||
//
|
||||
// // 点击公共大厅按钮并等待确认弹窗出现
|
||||
// await NewRetry.WaitForElementAppear(
|
||||
// _assets.BtnBlackConfirm,
|
||||
// () =>
|
||||
// {
|
||||
// using var ra = CaptureToRectArea();
|
||||
// Bv.FindAndClick(ra, _assets.WonderlandEnter);
|
||||
// },
|
||||
// ct,
|
||||
// 5,
|
||||
// 800
|
||||
// );
|
||||
|
||||
// 点击前往大厅并等待弹窗消失
|
||||
await NewRetry.WaitForElementDisappear(
|
||||
_assets.BtnBlackConfirm,
|
||||
screen =>
|
||||
{
|
||||
// 接收当前截图作为参数
|
||||
screen.Find(_assets.BtnBlackConfirm, ra =>
|
||||
{
|
||||
ra.Click();
|
||||
ra.Dispose();
|
||||
});
|
||||
},
|
||||
ct,
|
||||
5,
|
||||
1000
|
||||
);
|
||||
await Delay(1000, ct);
|
||||
|
||||
// 等待主界面出现
|
||||
var mainUiFound1 = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PaimonMenuRo,
|
||||
() => { },
|
||||
ct,
|
||||
120,
|
||||
1000
|
||||
);
|
||||
|
||||
if (mainUiFound1)
|
||||
{
|
||||
Logger.LogInformation("已进入千星奇域大厅,准备返回提瓦特");
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("未检测到主界面,可能未处于千星奇域");
|
||||
}
|
||||
|
||||
await Delay(500, ct);
|
||||
|
||||
// 等待菜单界面出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.BtnBackTeyvat,
|
||||
() => Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE),
|
||||
ct,
|
||||
20,
|
||||
800
|
||||
);
|
||||
|
||||
// 点击返回提瓦特按钮并等待确认弹窗出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.BtnBlackConfirm,
|
||||
() =>
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
Bv.FindAndClick(ra, _assets.BtnBackTeyvat);
|
||||
},
|
||||
ct,
|
||||
5,
|
||||
800
|
||||
);
|
||||
|
||||
// 点击确认并等待确认弹窗消失
|
||||
await NewRetry.WaitForElementDisappear(
|
||||
_assets.BtnBlackConfirm,
|
||||
screen =>
|
||||
{
|
||||
// 接收当前截图作为参数
|
||||
screen.Find(_assets.BtnBlackConfirm, ra =>
|
||||
{
|
||||
ra.Click();
|
||||
ra.Dispose();
|
||||
});
|
||||
},
|
||||
ct,
|
||||
5,
|
||||
1000
|
||||
);
|
||||
await Delay(1000, ct);
|
||||
|
||||
// 等待主界面出现
|
||||
var mainUiFound2 = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PaimonMenuRo,
|
||||
() => { },
|
||||
ct,
|
||||
120,
|
||||
1000
|
||||
);
|
||||
|
||||
if (mainUiFound2)
|
||||
{
|
||||
Logger.LogInformation("已返回提瓦特");
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("未检测到主界面,可能未处于提瓦特");
|
||||
}
|
||||
|
||||
await Delay(500, ct);
|
||||
}
|
||||
}
|
||||
@@ -143,7 +143,7 @@ public class SwitchPartyTask
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
await Task.Delay(450, ct);
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
await Task.Delay(200, ct);
|
||||
await Task.Delay(100, ct);
|
||||
|
||||
Rect regionOfInterest = new Rect(0, (int)(80 * _assetScale), partyDeleteBtn.Right, partyDeleteBtn.Top - (int)(80 * _assetScale));
|
||||
RecognitionObject recognitionObject = new RecognitionObject
|
||||
@@ -198,6 +198,7 @@ public class SwitchPartyTask
|
||||
{
|
||||
// #ebe4d8 首次点一下第一个,防止第五个被点击过
|
||||
page.ClickTo(600 * _assetScale, 200 * _assetScale);
|
||||
await Task.Delay(300, ct); // 等待动画
|
||||
}
|
||||
|
||||
page.ClickTo(regionOfInterest.X + regionOfInterest.Width / 2, lowest.Bottom); // 点击最下方队伍下移
|
||||
|
||||
@@ -9,6 +9,8 @@ namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
/// </summary>
|
||||
public interface ISceneMap
|
||||
{
|
||||
void WarmUp();
|
||||
|
||||
/// <summary>
|
||||
/// 获取大地图在整张地图上的位置
|
||||
/// </summary>
|
||||
@@ -47,22 +49,18 @@ public interface ISceneMap
|
||||
/// </summary>
|
||||
/// <param name="imageCoordinates"></param>
|
||||
/// <returns></returns>
|
||||
Point2f ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates);
|
||||
Point2f? ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates);
|
||||
|
||||
(float x, float y) ConvertImageCoordinatesToGenshinMapCoordinates(float x, float y);
|
||||
|
||||
Rect ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect);
|
||||
Rect? ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect);
|
||||
|
||||
/// <summary>
|
||||
/// 原神游戏坐标系 -> 地图图像坐标系
|
||||
/// </summary>
|
||||
/// <param name="genshinMapCoordinates"></param>
|
||||
/// <returns></returns>
|
||||
Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f genshinMapCoordinates);
|
||||
|
||||
(float x, float y) ConvertGenshinMapCoordinatesToImageCoordinates(float c, float a);
|
||||
Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f? genshinMapCoordinates);
|
||||
|
||||
Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect rect);
|
||||
Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect? rect);
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
@@ -63,11 +64,33 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
/// 分层地图特征列表
|
||||
/// 0 是主地图
|
||||
/// </summary>
|
||||
public List<BaseMapLayer> Layers { get; set; } = [];
|
||||
private List<BaseMapLayer> _layers = [];
|
||||
private readonly object _layersLock = new();
|
||||
|
||||
public List<BaseMapLayer> Layers
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_layers.Count == 0)
|
||||
{
|
||||
lock (_layersLock)
|
||||
{
|
||||
if (_layers.Count == 0)
|
||||
{
|
||||
TaskControl.Logger.LogInformation("[SIFT]地图特征点加载中,预计耗时2秒,请等待...");
|
||||
_layers = BaseMapLayer.LoadLayers(this);
|
||||
TaskControl.Logger.LogInformation("地图特征点加载完成!");
|
||||
}
|
||||
}
|
||||
}
|
||||
return _layers;
|
||||
}
|
||||
set => _layers = value ?? [];
|
||||
}
|
||||
|
||||
protected BaseMapLayer MainLayer => Layers[0];
|
||||
|
||||
protected readonly Feature2D SiftMatcher = Feature2DFactory.Get(Feature2DType.SIFT);
|
||||
public readonly Feature2D SiftMatcher = Feature2DFactory.Get(Feature2DType.SIFT);
|
||||
|
||||
protected void ExtractAndSaveFeature(string basePath)
|
||||
{
|
||||
@@ -85,6 +108,11 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
SiftMatcher.SaveFeatures(basePath, trainKeyPointsPath, trainDescriptorsPath);
|
||||
}
|
||||
|
||||
public virtual void WarmUp()
|
||||
{
|
||||
Console.WriteLine("提前加载地图,层数:" + Layers.Count);
|
||||
}
|
||||
|
||||
public virtual Point2f GetBigMapPosition(Mat greyBigMapMat)
|
||||
{
|
||||
return SiftMatcher.Match(MainLayer.TrainKeyPoints, MainLayer.TrainDescriptors, greyBigMapMat);
|
||||
@@ -151,47 +179,54 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
|
||||
#region 坐标系转换
|
||||
|
||||
public Point2f ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates)
|
||||
public Point2f? ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates)
|
||||
{
|
||||
if (imageCoordinates.X == 0 && imageCoordinates.Y == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// 原神坐标系是 1024 级别的,当图像坐标系不是 1024 级别的时候要做转换
|
||||
return new Point2f((MapOriginInImageCoordinate.X - imageCoordinates.X) / _mapImageBlockWidthScale,
|
||||
(MapOriginInImageCoordinate.Y - imageCoordinates.Y) / _mapImageBlockWidthScale);
|
||||
}
|
||||
|
||||
public (float x, float y) ConvertImageCoordinatesToGenshinMapCoordinates(float x, float y)
|
||||
{
|
||||
return new((MapOriginInImageCoordinate.X - x) / _mapImageBlockWidthScale,
|
||||
(MapOriginInImageCoordinate.Y - y) / _mapImageBlockWidthScale);
|
||||
}
|
||||
|
||||
public Rect ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect)
|
||||
public Rect? ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect)
|
||||
{
|
||||
if (rect.X == 0 && rect.Y == 0 && rect.Width == 0 && rect.Height == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var center = rect.GetCenterPoint();
|
||||
var (x, y) = ConvertImageCoordinatesToGenshinMapCoordinates(center.X, center.Y);
|
||||
return new Rect((int)(x - rect.Width / 2f / _mapImageBlockWidthScale), (int)(y - rect.Height / 2f / _mapImageBlockWidthScale),
|
||||
(int)(rect.Width / _mapImageBlockWidthScale), (int)(rect.Height / _mapImageBlockWidthScale));
|
||||
var nullablePoint = ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(center.X, center.Y));
|
||||
if (nullablePoint is Point2f p)
|
||||
{
|
||||
return new Rect((int)(p.X - rect.Width / 2f / _mapImageBlockWidthScale), (int)(p.Y - rect.Height / 2f / _mapImageBlockWidthScale),
|
||||
(int)(rect.Width / _mapImageBlockWidthScale), (int)(rect.Height / _mapImageBlockWidthScale));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f genshinMapCoordinates)
|
||||
public Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f? genshinMapCoordinates)
|
||||
{
|
||||
return new Point2f(MapOriginInImageCoordinate.X - genshinMapCoordinates.X * _mapImageBlockWidthScale,
|
||||
MapOriginInImageCoordinate.Y - genshinMapCoordinates.Y * _mapImageBlockWidthScale);
|
||||
if (genshinMapCoordinates is Point2f p)
|
||||
{
|
||||
return new Point2f(MapOriginInImageCoordinate.X - p.X * _mapImageBlockWidthScale,
|
||||
MapOriginInImageCoordinate.Y - p.Y * _mapImageBlockWidthScale);
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
public (float x, float y) ConvertGenshinMapCoordinatesToImageCoordinates(float c, float a)
|
||||
public Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect? genshinMapRect)
|
||||
{
|
||||
return new(MapOriginInImageCoordinate.X - c * _mapImageBlockWidthScale,
|
||||
MapOriginInImageCoordinate.Y - a * _mapImageBlockWidthScale);
|
||||
}
|
||||
|
||||
public Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect rect)
|
||||
{
|
||||
var center = rect.GetCenterPoint();
|
||||
var (x, y) = ConvertGenshinMapCoordinatesToImageCoordinates(center.X, center.Y);
|
||||
return new Rect((int)Math.Round(x - rect.Width / 2f * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(y - rect.Height / 2f * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(rect.Width * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(rect.Height * _mapImageBlockWidthScale));
|
||||
if (genshinMapRect is Rect rect)
|
||||
{
|
||||
var (x, y) = ConvertGenshinMapCoordinatesToImageCoordinates(rect.GetCenterPoint());
|
||||
return new Rect((int)Math.Round(x - rect.Width / 2f * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(y - rect.Height / 2f * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(rect.Width * _mapImageBlockWidthScale),
|
||||
(int)Math.Round(rect.Height * _mapImageBlockWidthScale));
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -6,6 +6,7 @@ using BetterGenshinImpact.Core.Recognition.OpenCv.TemplateMatch;
|
||||
using OpenCvSharp;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.MiniMap;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
|
||||
@@ -15,7 +16,28 @@ public abstract class SceneBaseMapByTemplateMatch : SceneBaseMap
|
||||
{
|
||||
private readonly MiniMapPreprocessor _miniMapPreprocessor = new();
|
||||
|
||||
public new List<BaseMapLayerByTemplateMatch> Layers { get; set; } = [];
|
||||
private List<BaseMapLayerByTemplateMatch> _layers = [];
|
||||
private readonly object _layersLock = new();
|
||||
public new List<BaseMapLayerByTemplateMatch> Layers
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_layers.Count == 0)
|
||||
{
|
||||
lock (_layersLock)
|
||||
{
|
||||
if (_layers.Count == 0)
|
||||
{
|
||||
TaskControl.Logger.LogInformation("[TemplateMatch]提瓦特大陆地图模板加载中,可能耗时较久,请耐心等待...");
|
||||
Layers = BaseMapLayerByTemplateMatch.LoadLayers(this);
|
||||
TaskControl.Logger.LogInformation("地图特征点加载完成!");
|
||||
}
|
||||
}
|
||||
}
|
||||
return _layers;
|
||||
}
|
||||
set => _layers = value ?? [];
|
||||
}
|
||||
|
||||
public MatchResult PrevSuccessResult;
|
||||
|
||||
@@ -43,10 +65,10 @@ public abstract class SceneBaseMapByTemplateMatch : SceneBaseMap
|
||||
: base(type, mapSize, mapOriginInImageCoordinate, mapImageBlockWidth, splitRow, splitCol)
|
||||
{
|
||||
}
|
||||
|
||||
protected void SetBaseLayers(List<BaseMapLayer> layers)
|
||||
|
||||
public override void WarmUp()
|
||||
{
|
||||
base.Layers = layers;
|
||||
Console.WriteLine("提前加载地图,层数:" + Layers.Count);
|
||||
}
|
||||
|
||||
public override Point2f GetMiniMapPosition(Mat colorMiniMapMat)
|
||||
@@ -84,7 +106,7 @@ public abstract class SceneBaseMapByTemplateMatch : SceneBaseMap
|
||||
using (miniMap)
|
||||
using (mask)
|
||||
{
|
||||
LocalMatch(miniMap, mask, ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(prevX, prevY)), ref curResult);
|
||||
LocalMatch(miniMap, mask, ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(prevX, prevY))!.Value, ref curResult);
|
||||
return UpdateResult(curResult, rank);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ public class EnkanomiyaMap : SceneBaseMap
|
||||
splitCol: 0)
|
||||
{
|
||||
ExtractAndSaveFeature(Global.Absolute("Assets/Map/Enkanomiya/Enkanomiya_0_1024.png"));
|
||||
Layers = BaseMapLayer.LoadLayers(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -27,8 +27,6 @@ public class EnkanomiyaMapTest : SceneBaseMapByTemplateMatch
|
||||
splitRow: 0,
|
||||
splitCol: 0)
|
||||
{
|
||||
Layers = BaseMapLayerByTemplateMatch.LoadLayers(this);
|
||||
ExtractAndSaveFeature(Global.Absolute("Assets/Map/Enkanomiya/Enkanomiya_0_1024.png"));
|
||||
SetBaseLayers(BaseMapLayer.LoadLayers(this));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Layer;
|
||||
|
||||
public class BigMapTeyvat256Layer : BaseMapLayer
|
||||
{
|
||||
// 大地图使用256 相对 2048 区块的缩放比例 2048/256=8
|
||||
public const int BigMap256ScaleTo2048 = 8;
|
||||
|
||||
private static BigMapTeyvat256Layer? _instance;
|
||||
private static readonly object LockObject = new();
|
||||
|
||||
private readonly Size _mapSize256;
|
||||
private readonly Feature2D _siftMatcher;
|
||||
|
||||
private BigMapTeyvat256Layer(SceneBaseMap baseMap) : base(baseMap)
|
||||
{
|
||||
Floor = 0;
|
||||
var layerDir = Path.Combine(Global.Absolute(@"Assets\Map\"), baseMap.Type.ToString());
|
||||
var kpFilePath = Path.Combine(layerDir, "Teyvat_0_256_SIFT.kp.bin");
|
||||
var matFilePath = Path.Combine(layerDir, "Teyvat_0_256_SIFT.mat.png");
|
||||
TrainKeyPoints = FeatureStorageHelper.LoadKeyPointArray(kpFilePath) ?? throw new Exception($"地图数据加载失败,文件: {kpFilePath}");
|
||||
TrainDescriptors = FeatureStorageHelper.LoadDescriptorMat(matFilePath) ?? throw new Exception($"地图数据加载失败,文件: {matFilePath}");
|
||||
|
||||
_mapSize256 = new Size(baseMap.MapSize.Width / BigMap256ScaleTo2048, baseMap.MapSize.Height / BigMap256ScaleTo2048);
|
||||
SplitBlocks = KeyPointFeatureBlockHelper.SplitFeatures(_mapSize256, TeyvatMap.GameMapRows * 4, TeyvatMap.GameMapCols * 4, TrainKeyPoints, TrainDescriptors);
|
||||
|
||||
_siftMatcher = baseMap.SiftMatcher;
|
||||
}
|
||||
|
||||
public static BigMapTeyvat256Layer GetInstance(SceneBaseMap baseMap)
|
||||
{
|
||||
if (_instance != null)
|
||||
{
|
||||
return _instance;
|
||||
}
|
||||
|
||||
lock (LockObject)
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = new BigMapTeyvat256Layer(baseMap);
|
||||
}
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
|
||||
public Rect GetBigMapRect(Mat greyBigMapMat)
|
||||
{
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
return _siftMatcher.KnnMatchRect(TrainKeyPoints, TrainDescriptors, greyBigMapMat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据上一个矩形位置,自适应地扩大搜索范围
|
||||
/// 自适应扩展:
|
||||
/// - blockWidth = colEnd - colStart + 1 , blockHeight 类似,得到该矩形覆盖了多少个块。
|
||||
/// - maxBlock = max(blockWidth, blockHeight) 作为尺度。
|
||||
/// - expand = Max(1, Min(4, maxBlock / 2)) :
|
||||
/// - 小矩形(块数少)至少扩展 1 个块;
|
||||
/// - 大矩形(块数多)根据块数扩展,但最多扩展到 4 个块,避免一下子把全图拉进来。
|
||||
/// - 在块索引上做扩展,而不是继续固定 3×3,也就实现了“根据块多少决定扩展大小”。
|
||||
/// </summary>
|
||||
/// <param name="greyBigMapMat"></param>
|
||||
/// <param name="prevRect"></param>
|
||||
/// <returns></returns>
|
||||
public Rect GetBigMapRect(Mat greyBigMapMat, Rect prevRect)
|
||||
{
|
||||
var rows = SplitBlocks.Length;
|
||||
if (prevRect == default || rows == 0)
|
||||
{
|
||||
return GetBigMapRect(greyBigMapMat);
|
||||
}
|
||||
|
||||
var cols = SplitBlocks[0].Length;
|
||||
|
||||
var (rowStart, rowEnd, colStart, colEnd) = KeyPointFeatureBlockHelper.GetCellRange(_mapSize256, rows, cols, prevRect);
|
||||
|
||||
var blockWidth = colEnd - colStart + 1;
|
||||
var blockHeight = rowEnd - rowStart + 1;
|
||||
var maxBlock = Math.Max(blockWidth, blockHeight);
|
||||
|
||||
var expand = 1;
|
||||
// var expand = Math.Max(1, Math.Min(2, maxBlock / 2));
|
||||
// Debug.WriteLine($"[提瓦特大地图]自适应扩展搜索,块范围扩展: {expand},原范围行({rowStart},{rowEnd})列({colStart},{colEnd})");
|
||||
|
||||
rowStart -= expand;
|
||||
rowEnd += expand;
|
||||
colStart -= expand;
|
||||
colEnd += expand;
|
||||
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
var mergedBlock = KeyPointFeatureBlockHelper.MergeFeaturesInRange(SplitBlocks, TrainDescriptors, rowStart, rowEnd, colStart, colEnd);
|
||||
var keyPoints = mergedBlock.KeyPointArray;
|
||||
var descriptors = mergedBlock.Descriptor!;
|
||||
|
||||
var res = _siftMatcher.KnnMatchRect(keyPoints, descriptors, greyBigMapMat);
|
||||
if (res == default)
|
||||
{
|
||||
Debug.WriteLine("[提瓦特大地图]自适应扩展搜索失败,退回全图搜索");
|
||||
return _siftMatcher.KnnMatchRect(TrainKeyPoints, TrainDescriptors, greyBigMapMat);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
|
||||
@@ -54,30 +55,10 @@ public class SeaOfBygoneErasMap : SceneBaseMap
|
||||
ExtractAndSaveFeature(Global.Absolute("Assets/Map/SeaOfBygoneEras/SeaOfBygoneEras_-2_1024.webp"));
|
||||
Layers = BaseMapLayer.LoadLayers(this);
|
||||
|
||||
var mapTeleports = new List<Point>();
|
||||
var tpJson = System.IO.File.ReadAllText(Global.Absolute(@"GameTask\AutoTrackPath\Assets\tp.json"));
|
||||
|
||||
JArray j = JArray.Parse(tpJson);
|
||||
foreach (JObject i in j)
|
||||
{
|
||||
var sceneId = i["sceneId"];
|
||||
if (sceneId != null && (int)sceneId == 11)
|
||||
{
|
||||
foreach (var p in i["points"]!)
|
||||
{
|
||||
if ((string)p["type"]! != "Teleport")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var x = (float)p["position"]![2]!;
|
||||
var y = (float)p["position"]![0]!;
|
||||
var (x1, y1) = ConvertGenshinMapCoordinatesToImageCoordinates(x, y);
|
||||
mapTeleports.Add(new Point(x1, y1));
|
||||
}
|
||||
}
|
||||
}
|
||||
mapTeleports = mapTeleports.OrderBy(i => i.X).ThenBy(i => i.Y).ToList();
|
||||
MapTeleports = mapTeleports;
|
||||
MapTeleports = MapLazyAssets.Instance.ScenesDic["SeaOfBygoneEras"].Points.
|
||||
Where(i => i.Type == "TeleportWaypoint").
|
||||
Select(i => ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f((float)i.TranX, (float)i.TranY))).
|
||||
Select(i => new Point(i.X, i.Y)).OrderBy(i => i.X).ThenBy(i => i.Y).ToList();
|
||||
}
|
||||
|
||||
public override Point2f GetBigMapPosition(Mat greyBigMapMat)
|
||||
@@ -152,7 +133,8 @@ public class SeaOfBygoneErasMap : SceneBaseMap
|
||||
{
|
||||
return default;
|
||||
}
|
||||
teleportPoints = teleportPoints.OrderBy(i => i.X).ThenBy(i => i.Y).ToList();
|
||||
teleportPoints = teleportPoints.Select(i => new Point(i.X + 12, i.Y + 12)).
|
||||
OrderBy(i => i.X).ThenBy(i => i.Y).ToList();
|
||||
/*
|
||||
foreach (var p in teleportPoints) {
|
||||
Logger.LogInformation("Teleport point: {a}", p);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using System.IO;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Layer;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
@@ -25,8 +26,6 @@ public class TeyvatMap : SceneBaseMap
|
||||
|
||||
public static readonly int TeyvatMapImageBlockWidth = 2048;
|
||||
|
||||
private readonly BaseMapLayer _teyvat256MapLayer;
|
||||
|
||||
public TeyvatMap() : base(type: MapTypes.Teyvat,
|
||||
mapSize: new Size(GameMapCols * TeyvatMapImageBlockWidth, GameMapRows * TeyvatMapImageBlockWidth),
|
||||
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * TeyvatMapImageBlockWidth, (GameMapUpRows + 1) * TeyvatMapImageBlockWidth),
|
||||
@@ -34,15 +33,6 @@ public class TeyvatMap : SceneBaseMap
|
||||
splitRow: GameMapRows * 2,
|
||||
splitCol: GameMapCols * 2)
|
||||
{
|
||||
TaskControl.Logger.LogInformation("[SIFT]提瓦特大陆地图特征点加载中,预计耗时2秒,请等待...");
|
||||
|
||||
Layers = BaseMapLayer.LoadLayers(this);
|
||||
var layerDir = Path.Combine(Global.Absolute(@"Assets\Map\"), Type.ToString());
|
||||
|
||||
// 256用于大地图匹配
|
||||
_teyvat256MapLayer = BaseMapLayer.LoadLayer(this, Path.Combine(layerDir, "Teyvat_0_256_SIFT.kp.bin"), Path.Combine(layerDir, "Teyvat_0_256_SIFT.mat.png"));
|
||||
TaskControl.Logger.LogInformation("地图特征点加载完成!");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -52,12 +42,17 @@ public class TeyvatMap : SceneBaseMap
|
||||
public override Point2f GetBigMapPosition(Mat greyBigMapMat)
|
||||
{
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
return SiftMatcher.Match(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
|
||||
var layer = BigMapTeyvat256Layer.GetInstance(this);
|
||||
return SiftMatcher.Match(layer.TrainKeyPoints, layer.TrainDescriptors, greyBigMapMat);
|
||||
}
|
||||
|
||||
public override Rect GetBigMapRect(Mat greyBigMapMat)
|
||||
{
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
return SiftMatcher.KnnMatchRect(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
|
||||
return BigMapTeyvat256Layer.GetInstance(this).GetBigMapRect(greyBigMapMat);
|
||||
}
|
||||
}
|
||||
|
||||
public Rect GetBigMapRect(Mat greyBigMapMat, Rect prevRect)
|
||||
{
|
||||
return BigMapTeyvat256Layer.GetInstance(this).GetBigMapRect(greyBigMapMat, prevRect);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
using System.IO;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Layer;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
@@ -23,8 +24,6 @@ public class TeyvatMapTest : SceneBaseMapByTemplateMatch
|
||||
#endregion 每次地图扩大都要更新的参数
|
||||
static readonly int TeyvatMapImageBlockWidth = TeyvatMap.TeyvatMapImageBlockWidth;
|
||||
|
||||
private readonly BaseMapLayer _teyvat256MapLayer;
|
||||
|
||||
public TeyvatMapTest() : base(type: MapTypes.Teyvat,
|
||||
mapSize: new Size(GameMapCols * TeyvatMapImageBlockWidth, GameMapRows * TeyvatMapImageBlockWidth),
|
||||
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * TeyvatMapImageBlockWidth, (GameMapUpRows + 1) * TeyvatMapImageBlockWidth),
|
||||
@@ -32,29 +31,17 @@ public class TeyvatMapTest : SceneBaseMapByTemplateMatch
|
||||
splitRow: GameMapRows * 2,
|
||||
splitCol: GameMapCols * 2)
|
||||
{
|
||||
TaskControl.Logger.LogInformation("[TemplateMatch]提瓦特大陆地图模板加载中,可能耗时较久,请耐心等待...");
|
||||
|
||||
Layers = BaseMapLayerByTemplateMatch.LoadLayers(this);
|
||||
var layerDir = Path.Combine(Global.Absolute(@"Assets\Map\"), Type.ToString());
|
||||
|
||||
// 256用于大地图匹配
|
||||
_teyvat256MapLayer = BaseMapLayer.LoadLayer(this, Path.Combine(layerDir, "Teyvat_0_256_SIFT.kp.bin"), Path.Combine(layerDir, "Teyvat_0_256_SIFT.mat.png"));
|
||||
TaskControl.Logger.LogInformation("地图特征点加载完成!");
|
||||
|
||||
}
|
||||
|
||||
// 大地图使用256 相对 2048 区块的缩放比例 2048/256=8
|
||||
public const int BigMap256ScaleTo2048 = 8;
|
||||
|
||||
public override Point2f GetBigMapPosition(Mat greyBigMapMat)
|
||||
{
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
return SiftMatcher.Match(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
|
||||
var layer = BigMapTeyvat256Layer.GetInstance(this);
|
||||
return SiftMatcher.Match(layer.TrainKeyPoints, layer.TrainDescriptors, greyBigMapMat);
|
||||
}
|
||||
|
||||
public override Rect GetBigMapRect(Mat greyBigMapMat)
|
||||
{
|
||||
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
|
||||
return SiftMatcher.KnnMatchRect(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
|
||||
return BigMapTeyvat256Layer.GetInstance(this).GetBigMapRect(greyBigMapMat);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ public class TheChasmMap : SceneBaseMap
|
||||
splitCol: 0)
|
||||
{
|
||||
ExtractAndSaveFeature(Global.Absolute("Assets/Map/TheChasm/TheChasm_0_1024.png"));
|
||||
Layers = BaseMapLayer.LoadLayers(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -28,8 +28,6 @@ public class TheChasmMapTest : SceneBaseMapByTemplateMatch
|
||||
splitRow: 0,
|
||||
splitCol: 0)
|
||||
{
|
||||
Layers = BaseMapLayerByTemplateMatch.LoadLayers(this);
|
||||
ExtractAndSaveFeature(Global.Absolute("Assets/Map/TheChasm/TheChasm_0_1024.png"));
|
||||
SetBaseLayers(BaseMapLayer.LoadLayers(this));
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,13 @@ using BetterGenshinImpact.GameTask.Placeholder;
|
||||
using BetterGenshinImpact.GameTask.QuickSereniteaPot.Assets;
|
||||
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.Mvvm.Messaging.Messages;
|
||||
using OpenCvSharp;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip;
|
||||
using BetterGenshinImpact.GameTask.MapMask;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask;
|
||||
|
||||
@@ -48,6 +47,7 @@ internal class GameTaskManager
|
||||
TriggerDictionary.TryAdd("AutoFish", new AutoFishing.AutoFishingTrigger());
|
||||
TriggerDictionary.TryAdd("AutoCook", new AutoCook.AutoCookTrigger());
|
||||
TriggerDictionary.TryAdd("AutoEat", new AutoEat.AutoEatTrigger());
|
||||
TriggerDictionary.TryAdd("MapMask", new MapMaskTrigger());
|
||||
|
||||
return ConvertToTriggerList();
|
||||
}
|
||||
@@ -122,6 +122,7 @@ internal class GameTaskManager
|
||||
// TriggerDictionary.GetValueOrDefault("GameLoading")?.Init();
|
||||
TriggerDictionary.GetValueOrDefault("AutoCook")?.Init();
|
||||
TriggerDictionary.GetValueOrDefault("AutoEat")?.Init();
|
||||
TriggerDictionary.GetValueOrDefault("MapMask")?.Init();
|
||||
// 清理画布
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
}
|
||||
@@ -191,4 +192,4 @@ internal class GameTaskManager
|
||||
|
||||
return mat;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask;
|
||||
|
||||
/// <summary>
|
||||
/// 触发器接口
|
||||
@@ -34,6 +36,8 @@ public interface ITaskTrigger
|
||||
/// 处于可以后台运行的状态(原神窗口不处于激活状态)
|
||||
/// </summary>
|
||||
bool IsBackgroundRunning => false;
|
||||
|
||||
GameUiCategory SupportedGameUiCategory => GameUiCategory.Unknown;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.MapMask;
|
||||
|
||||
/// <summary>
|
||||
/// 自动吃药配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class MapMaskConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enabled = true;
|
||||
|
||||
private MapPointApiProvider _mapPointApiProvider = MapPointApiProvider.MihoyoMap;
|
||||
|
||||
[JsonConverter(typeof(JsonStringEnumConverter))]
|
||||
public MapPointApiProvider MapPointApiProvider
|
||||
{
|
||||
get => _mapPointApiProvider;
|
||||
set => SetProperty(ref _mapPointApiProvider, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Layer;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.View;
|
||||
using BetterGenshinImpact.ViewModel;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.MapMask;
|
||||
|
||||
/// <summary>
|
||||
/// 地图遮罩触发器
|
||||
/// </summary>
|
||||
public class MapMaskTrigger : ITaskTrigger
|
||||
{
|
||||
private readonly ILogger<MapMaskTrigger> _logger = App.GetLogger<MapMaskTrigger>();
|
||||
|
||||
public string Name => "地图遮罩";
|
||||
public bool IsEnabled { get; set; }
|
||||
public int Priority => 1; // 低优先级
|
||||
public bool IsExclusive => false;
|
||||
|
||||
public GameUiCategory SupportedGameUiCategory => GameUiCategory.BigMap;
|
||||
|
||||
private readonly MapMaskConfig _config = TaskContext.Instance().Config.MapMaskConfig;
|
||||
private readonly string _mapMatchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
|
||||
|
||||
private readonly TemplateMatchStabilityDetector _detector = new();
|
||||
|
||||
private DateTime _prevExecute = DateTime.MinValue;
|
||||
|
||||
// 图像连续稳定次数
|
||||
private int _stableCount = 0;
|
||||
|
||||
private ISceneMap _teyvatMap => MapManager.GetMap(MapTypes.Teyvat, _mapMatchingMethod);
|
||||
private OpenCvSharp.Rect _prevRect = default;
|
||||
|
||||
private const int RectDebounceThreshold = 3;
|
||||
|
||||
public void Init()
|
||||
{
|
||||
IsEnabled = _config.Enabled;
|
||||
}
|
||||
|
||||
public void OnCapture(CaptureContent content)
|
||||
{
|
||||
if ((DateTime.Now - _prevExecute).TotalMilliseconds <= 50)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_prevExecute = DateTime.Now;
|
||||
|
||||
try
|
||||
{
|
||||
var region = content.CaptureRectArea;
|
||||
var inBigMapUi = content.CurrentGameUiCategory == GameUiCategory.BigMap || Bv.IsInBigMapUi(region);
|
||||
UIDispatcherHelper.Invoke(() =>
|
||||
{
|
||||
var vm = MaskWindow.Instance().DataContext as MaskWindowViewModel;
|
||||
if (vm != null)
|
||||
{
|
||||
vm.IsInBigMapUi = inBigMapUi;
|
||||
}
|
||||
});
|
||||
|
||||
if (inBigMapUi)
|
||||
{
|
||||
if (_detector.IsStable(region.CacheGreyMat))
|
||||
{
|
||||
_stableCount++;
|
||||
if (_stableCount >= 20)
|
||||
{
|
||||
_stableCount = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_stableCount = 0;
|
||||
}
|
||||
|
||||
if (_stableCount == 0)
|
||||
{
|
||||
var rect256 = BigMapTeyvat256Layer.GetInstance((SceneBaseMap)_teyvatMap).GetBigMapRect(region.CacheGreyMat, _prevRect);
|
||||
if (rect256 != default)
|
||||
{
|
||||
// 过大或过小的区域不处理
|
||||
if (rect256 is { Width: < 50, Height: < 40 } || rect256 is { Width: > 3000, Height: > 1800 })
|
||||
{
|
||||
_prevRect = default;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// if (_prevRect != default)
|
||||
// {
|
||||
// var dx = Math.Abs(rect256.X - _prevRect.X);
|
||||
// var dy = Math.Abs(rect256.Y - _prevRect.Y);
|
||||
// if (dx <= RectDebounceThreshold && dy <= RectDebounceThreshold)
|
||||
// {
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
|
||||
_prevRect = rect256;
|
||||
}
|
||||
|
||||
const int s = TeyvatMap.BigMap256ScaleTo2048; // 相对2048做8倍缩放
|
||||
var rect2048 = new Rect(rect256.X * s, rect256.Y * s, rect256.Width * s, rect256.Height * s);
|
||||
UIDispatcherHelper.Invoke(() => { MaskWindow.Instance().PointsCanvasControl.UpdateViewport(rect2048.X, rect2048.Y, rect2048.Width, rect2048.Height); });
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_prevRect = default;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug(e, "实时地图定位时发生异常");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace BetterGenshinImpact.GameTask.MapMask;
|
||||
|
||||
public enum MapPointApiProvider
|
||||
{
|
||||
MihoyoMap = 0,
|
||||
KongyingTavern = 1
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class DesktopRegion : Region
|
||||
throw new System.NullReferenceException();
|
||||
}
|
||||
mouse.MoveMouseTo((x + (w * 1d / 2)) * 65535 / Width,
|
||||
(y + (h * 1d / 2)) * 65535 / Height).LeftButtonDown().Sleep(50).LeftButtonUp();
|
||||
(y + (h * 1d / 2)) * 65535 / Height).LeftButtonDown().Sleep(50).LeftButtonUp().Sleep(50);
|
||||
}
|
||||
|
||||
public void DesktopRegionMove(int x, int y, int w, int h)
|
||||
@@ -61,7 +61,7 @@ public class DesktopRegion : Region
|
||||
public static void DesktopRegionClick(double cx, double cy)
|
||||
{
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(cx * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
|
||||
cy * 65535 * 1d / PrimaryScreen.WorkingArea.Height).LeftButtonDown().Sleep(50).LeftButtonUp();
|
||||
cy * 65535 * 1d / PrimaryScreen.WorkingArea.Height).LeftButtonDown().Sleep(50).LeftButtonUp().Sleep(50);
|
||||
}
|
||||
|
||||
public static void DesktopRegionMove(double cx, double cy)
|
||||
|
||||
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
@@ -36,6 +36,8 @@ public class QuickTeleportAssets : BaseAssets<QuickTeleportAssets>
|
||||
BuildMapChooseIconRo("PortableWaypoint.png"),
|
||||
BuildMapChooseIconRo("Mansion.png"),
|
||||
BuildMapChooseIconRo("SubSpaceWaypoint.png"),
|
||||
BuildMapChooseIconRo("NodKraiMeetingPoint.png"),
|
||||
BuildMapChooseIconRo("TabletOfTona.png"),
|
||||
];
|
||||
MapChooseIconGreyMatList = MapChooseIconRoList.ConvertAll(x => x.TemplateImageGreyMat ?? new Mat());
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ using OpenCvSharp;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.QuickTeleport;
|
||||
|
||||
@@ -20,6 +21,8 @@ internal class QuickTeleportTrigger : ITaskTrigger
|
||||
public int Priority => 21;
|
||||
public bool IsExclusive { get; set; }
|
||||
|
||||
public GameUiCategory SupportedGameUiCategory => GameUiCategory.BigMap;
|
||||
|
||||
private readonly QuickTeleportAssets _assets;
|
||||
|
||||
private DateTime _prevClickOptionButtonTime = DateTime.MinValue;
|
||||
@@ -64,10 +67,9 @@ internal class QuickTeleportTrigger : ITaskTrigger
|
||||
_prevExecute = DateTime.Now;
|
||||
|
||||
// 1.判断是否在地图界面
|
||||
content.CaptureRectArea.Find(_assets.MapScaleButtonRo, _ =>
|
||||
if (content.CurrentGameUiCategory == GameUiCategory.BigMap
|
||||
|| Bv.IsInBigMapUi(content.CaptureRectArea))
|
||||
{
|
||||
IsExclusive = true;
|
||||
|
||||
// 2. 判断是否有传送按钮
|
||||
var hasTeleportButton = CheckTeleportButton(content.CaptureRectArea);
|
||||
|
||||
@@ -95,7 +97,7 @@ internal class QuickTeleportTrigger : ITaskTrigger
|
||||
CheckTeleportButton(TaskControl.CaptureToRectArea(forceNew: true));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private bool CheckTeleportButton(ImageRegion imageRegion)
|
||||
@@ -139,7 +141,7 @@ internal class QuickTeleportTrigger : ITaskTrigger
|
||||
{
|
||||
// RecognitionType = RecognitionTypes.Ocr,
|
||||
RecognitionType = RecognitionTypes.ColorRangeAndOcr,
|
||||
LowerColor = new Scalar(249, 249, 249), // 只取白色文字
|
||||
LowerColor = new Scalar(249, 249, 249), // 只取白色文字
|
||||
UpperColor = new Scalar(255, 255, 255),
|
||||
});
|
||||
if (string.IsNullOrEmpty(textRegion.Text) || textRegion.Text.Length == 1)
|
||||
@@ -247,4 +249,4 @@ internal class QuickTeleportTrigger : ITaskTrigger
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.View;
|
||||
using Fischless.GameCapture;
|
||||
@@ -12,10 +11,13 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.GameTask.GameLoading;
|
||||
using Fischless.GameCapture.Graphics;
|
||||
using BetterGenshinImpact.Service;
|
||||
using Vanara.PInvoke;
|
||||
using Rect = OpenCvSharp.Rect;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask
|
||||
{
|
||||
@@ -53,6 +55,8 @@ namespace BetterGenshinImpact.GameTask
|
||||
|
||||
public event EventHandler? UiTaskStartTickEvent;
|
||||
|
||||
public GameUiCategory PrevGameUiCategory = GameUiCategory.Unknown;
|
||||
|
||||
public TaskTriggerDispatcher()
|
||||
{
|
||||
_instance = this;
|
||||
@@ -111,6 +115,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
SetTriggers(GameTaskManager.ConvertToTriggerList(true));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -128,7 +133,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
// 初始化触发器(一定要在任务上下文初始化完毕后使用)
|
||||
_triggers = GameTaskManager.LoadInitialTriggers();
|
||||
GameLoadingTrigger.GlobalEnabled = TaskContext.Instance().Config.GenshinStartConfig.AutoEnterGameEnabled;
|
||||
|
||||
|
||||
// if (GraphicsCapture.IsHdrEnabled(hWnd))
|
||||
// {
|
||||
// _logger.LogError("游戏窗口在HDR模式下无法获取正常颜色的截图,请关闭HDR模式!");
|
||||
@@ -141,13 +146,13 @@ namespace BetterGenshinImpact.GameTask
|
||||
{ "autoFixWin11BitBlt", OsVersionHelper.IsWindows11_OrGreater && TaskContext.Instance().Config.AutoFixWin11BitBlt }
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
// 使用 SetWinEventHook 监听窗口移动和大小变化事件
|
||||
_winEventProc = WinEventCallback;
|
||||
var flags = (User32.WINEVENT)(WINEVENT_SKIPOWNPROCESS | WINEVENT_SKIPOWNTHREAD);
|
||||
_winEventHookMoveSize = User32.SetWinEventHook(EVENT_SYSTEM_MOVESIZESTART, EVENT_SYSTEM_MOVESIZEEND, default, _winEventProc, 0, 0, flags);
|
||||
_winEventHookLocation = User32.SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, default, _winEventProc, 0, 0, flags);
|
||||
|
||||
|
||||
// 启动定时器
|
||||
_frameIndex = 0;
|
||||
_timer.Interval = interval;
|
||||
@@ -169,6 +174,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
User32.UnhookWinEvent(_winEventHookMoveSize);
|
||||
_winEventHookMoveSize = default;
|
||||
}
|
||||
|
||||
if (_winEventHookLocation != default)
|
||||
{
|
||||
User32.UnhookWinEvent(_winEventHookLocation);
|
||||
@@ -224,15 +230,15 @@ namespace BetterGenshinImpact.GameTask
|
||||
|
||||
PictureInPictureService.Hide(resetManual: true);
|
||||
UiTaskStopTickEvent?.Invoke(sender, e);
|
||||
maskWindow.Invoke(maskWindow.Hide);
|
||||
maskWindow.Invoke(maskWindow.HideSelf);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查游戏是否在前台
|
||||
var hasBackgroundTriggerToRun = false;
|
||||
var autoSkipConfig = TaskContext.Instance().Config.AutoSkipConfig;
|
||||
var shouldShowPictureInPicture = autoSkipConfig.Enabled
|
||||
&& autoSkipConfig.PictureInPictureEnabled
|
||||
var shouldShowPictureInPicture = autoSkipConfig.Enabled
|
||||
&& autoSkipConfig.PictureInPictureEnabled
|
||||
&& !PictureInPictureService.IsManuallyClosed
|
||||
&& TaskControl.TaskSemaphore.CurrentCount == 1; // 没有任务持有锁(也就是没有任务正在运行)
|
||||
var active = SystemControl.IsGenshinImpactActive();
|
||||
@@ -254,9 +260,10 @@ namespace BetterGenshinImpact.GameTask
|
||||
if (!TaskContext.Instance().Config.MaskWindowConfig.UseSubform)
|
||||
{
|
||||
var pName = SystemControl.GetActiveProcessName();
|
||||
if (pName != "BetterGI" && pName != "YuanShen" && pName != "GenshinImpact" && pName != "Genshin Impact Cloud Game")
|
||||
if (pName != "Idle" && pName != "BetterGI" && pName != "YuanShen" && pName != "GenshinImpact" && pName != "Genshin Impact Cloud Game")
|
||||
{
|
||||
maskWindow.Invoke(() => { maskWindow.Hide(); });
|
||||
// Debug.WriteLine(pName + ":hide mask window");
|
||||
maskWindow.Invoke(() => { maskWindow.HideSelf(); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,6 +284,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasBackgroundTriggerToRun && shouldShowPictureInPicture)
|
||||
{
|
||||
hasBackgroundTriggerToRun = true;
|
||||
@@ -312,10 +320,10 @@ namespace BetterGenshinImpact.GameTask
|
||||
|
||||
_prevGameActive = active;
|
||||
// // 移动游戏窗口的时候同步遮罩窗口的位置,此时不进行捕获
|
||||
// if (SyncMaskWindowPosition())
|
||||
// {
|
||||
// return;
|
||||
// }
|
||||
if (SyncMaskWindowPosition())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_triggers == null || !_triggers.Exists(t => t.IsEnabled))
|
||||
@@ -323,7 +331,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
// Debug.WriteLine("没有可用的触发器且不处于仅截屏状态, 不再进行截屏");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 帧序号自增 1分钟后归零(MaxFrameIndexSecond)
|
||||
_frameIndex = (_frameIndex + 1) % (int)(CaptureContent.MaxFrameIndexSecond * 1000d / _timer.Interval);
|
||||
|
||||
@@ -352,11 +360,11 @@ namespace BetterGenshinImpact.GameTask
|
||||
|
||||
lock (_triggerListLocker)
|
||||
{
|
||||
var needRunTriggers = new List<ITaskTrigger>(); // 最终要执行的触发器列表
|
||||
var exclusiveTrigger = _triggers!.FirstOrDefault(t => t is { IsEnabled: true, IsExclusive: true });
|
||||
if (exclusiveTrigger != null)
|
||||
{
|
||||
exclusiveTrigger.OnCapture(content);
|
||||
speedTimer.Record(exclusiveTrigger.Name);
|
||||
needRunTriggers.Add(exclusiveTrigger);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -366,11 +374,25 @@ namespace BetterGenshinImpact.GameTask
|
||||
runningTriggers = runningTriggers.Where(t => t.IsBackgroundRunning);
|
||||
}
|
||||
|
||||
foreach (var trigger in runningTriggers)
|
||||
needRunTriggers.AddRange(runningTriggers);
|
||||
}
|
||||
|
||||
if (needRunTriggers.Count > 0)
|
||||
{
|
||||
// 判断当前UI
|
||||
content.CurrentGameUiCategory = Bv.WhichGameUiForTriggers(content.CaptureRectArea);
|
||||
|
||||
foreach (var trigger in needRunTriggers)
|
||||
{
|
||||
trigger.OnCapture(content);
|
||||
speedTimer.Record(trigger.Name);
|
||||
if (PrevGameUiCategory != content.CurrentGameUiCategory // UI变化了则所有触发器执行一遍
|
||||
|| trigger.SupportedGameUiCategory == content.CurrentGameUiCategory)
|
||||
{
|
||||
trigger.OnCapture(content);
|
||||
speedTimer.Record(trigger.Name);
|
||||
}
|
||||
}
|
||||
|
||||
PrevGameUiCategory = content.CurrentGameUiCategory;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,10 +459,12 @@ namespace BetterGenshinImpact.GameTask
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (idObject != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var hwndPtr = hwnd.DangerousGetHandle();
|
||||
if (hwndPtr == target)
|
||||
{
|
||||
@@ -468,6 +492,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
_logger.LogInformation("截图失败,未获取到图像");
|
||||
return;
|
||||
}
|
||||
|
||||
var name = $@"{DateTime.Now:yyyyMMddHHmmssffff}.png";
|
||||
var savePath = Global.Absolute($@"log\screenshot\{name}");
|
||||
if (TaskContext.Instance().Config.CommonConfig.ScreenshotUidCoverEnabled)
|
||||
@@ -496,4 +521,4 @@ namespace BetterGenshinImpact.GameTask
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ using System.Windows.Media;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
|
||||
namespace BetterGenshinImpact.Helpers.Ui;
|
||||
|
||||
public class WindowHelper
|
||||
@@ -20,15 +20,15 @@ public class WindowHelper
|
||||
{
|
||||
ApplyThemeToWindow(window, themeType);
|
||||
}
|
||||
catch
|
||||
catch
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to apply theme in Wine");
|
||||
Debug.WriteLine($"Failed to apply theme in Wine");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ApplyThemeToWindow(window, themeType);
|
||||
};
|
||||
{
|
||||
ApplyThemeToWindow(window, themeType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
public static class GameWebMapCoordinateConverter
|
||||
{
|
||||
public const double MysWebOffsetOriginX = -749.75;
|
||||
public const double MysWebOffsetOriginY = 2322.0;
|
||||
|
||||
|
||||
public const double KongyingTavernOffsetOriginX = 396.125;
|
||||
public const double KongyingTavernOffsetOriginY = -619.9375;
|
||||
|
||||
|
||||
public static (double x, double y) GameToMysWeb(double gameX, double gameY)
|
||||
{
|
||||
var x = -(gameX - MysWebOffsetOriginX);
|
||||
var y = -(gameY - MysWebOffsetOriginY);
|
||||
return (x, y);
|
||||
}
|
||||
|
||||
public static (double x, double y) MysWebToGame(double webX, double webY)
|
||||
{
|
||||
var x = MysWebOffsetOriginX - webX;
|
||||
var y = MysWebOffsetOriginY - webY;
|
||||
return (x, y);
|
||||
}
|
||||
|
||||
public static (double x, double y) KongyingTavernToGame(double webX, double webY)
|
||||
{
|
||||
var x = KongyingTavernOffsetOriginX - webX / 4.0 * 3;
|
||||
var y = KongyingTavernOffsetOriginY - webY / 4.0 * 3;
|
||||
return (x, y);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
public class MaskMapPoint
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 游戏中的坐标 X
|
||||
/// </summary>
|
||||
public double GameX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 游戏中的坐标 Y
|
||||
/// </summary>
|
||||
public double GameY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 游戏图像地图的坐标 X
|
||||
/// </summary>
|
||||
public double ImageX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 游戏图像地图的坐标 Y
|
||||
/// </summary>
|
||||
public double ImageY { get; set; }
|
||||
|
||||
public string LabelId { get; set; } = string.Empty;
|
||||
|
||||
public List<MaskMapLink> VideoUrls { get; set; } = new();
|
||||
|
||||
public bool Contains(double px, double py)
|
||||
{
|
||||
return px >= X - MaskMapPointStatic.Width / 2 && px <= X + MaskMapPointStatic.Width / 2 &&
|
||||
py >= Y - MaskMapPointStatic.Height / 2 && py <= Y + MaskMapPointStatic.Height / 2;
|
||||
}
|
||||
}
|
||||
|
||||
public class MaskMapPointStatic
|
||||
{
|
||||
public static readonly int Width = 32;
|
||||
|
||||
public static readonly int Height = 32;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
public sealed class MaskMapPointClickArgs
|
||||
{
|
||||
public MaskMapPointClickArgs(MaskMapPoint point, Point anchorPosition)
|
||||
{
|
||||
Point = point;
|
||||
AnchorPosition = anchorPosition;
|
||||
}
|
||||
|
||||
public MaskMapPoint Point { get; }
|
||||
|
||||
public Point AnchorPosition { get; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
|
||||
namespace BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
/// <summary>
|
||||
/// 点位类型标签
|
||||
/// </summary>
|
||||
public class MaskMapPointLabel
|
||||
{
|
||||
public string LabelId { get; set; } = string.Empty;
|
||||
|
||||
public IReadOnlyList<string> LabelIds { get; set; } = Array.Empty<string>();
|
||||
|
||||
public string ParentId { get; set; } = string.Empty;
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string IconUrl { get; set; } = string.Empty;
|
||||
|
||||
public int PointCount { get; set; }
|
||||
|
||||
public IReadOnlyList<MaskMapPointLabel> Children { get; set; } = Array.Empty<MaskMapPointLabel>();
|
||||
|
||||
/// <summary>
|
||||
/// 颜色(如果没有图片时使用,为空则随机生成)
|
||||
/// </summary>
|
||||
public Color? Color { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
public sealed class MaskMapPointsResult
|
||||
{
|
||||
public IReadOnlyList<MaskMapPointLabel> Labels { get; set; } = Array.Empty<MaskMapPointLabel>();
|
||||
|
||||
public IReadOnlyList<MaskMapPoint> Points { get; set; } = Array.Empty<MaskMapPoint>();
|
||||
}
|
||||
|
||||
public sealed class MaskMapPointInfo
|
||||
{
|
||||
public string Text { get; set; } = string.Empty;
|
||||
|
||||
public string ImageUrl { get; set; } = string.Empty;
|
||||
|
||||
public IReadOnlyList<MaskMapLink> UrlList { get; set; } = Array.Empty<MaskMapLink>();
|
||||
}
|
||||
|
||||
public sealed class MaskMapLink
|
||||
{
|
||||
public string Text { get; set; } = string.Empty;
|
||||
|
||||
public string Url { get; set; } = string.Empty;
|
||||
|
||||
public string DisplayText => string.IsNullOrWhiteSpace(Text) ? "视频攻略" : Text;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
@@ -6,6 +6,7 @@ using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Data;
|
||||
using BetterGenshinImpact.View.Controls;
|
||||
|
||||
namespace BetterGenshinImpact.Model;
|
||||
|
||||
@@ -18,6 +19,8 @@ public class SettingItem
|
||||
|
||||
public List<string>? Options { get; set; }
|
||||
|
||||
public Dictionary<string, List<string>>? CascadeOptions { get; set; }
|
||||
|
||||
public object? Default { get; set; }
|
||||
|
||||
public List<UIElement> ToControl(dynamic context)
|
||||
@@ -171,6 +174,35 @@ public class SettingItem
|
||||
break;
|
||||
}
|
||||
|
||||
case "cascade-select":
|
||||
{
|
||||
if (CascadeOptions == null || CascadeOptions.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var cascadeSelector = new CascadeSelector
|
||||
{
|
||||
CascadeOptions = CascadeOptions,
|
||||
DefaultValue = Default?.ToString(),
|
||||
Margin = new Thickness(0, 0, 0, 10)
|
||||
};
|
||||
|
||||
if (Default != null)
|
||||
{
|
||||
if (context is IDictionary<string, object?> ctx)
|
||||
{
|
||||
ctx.TryAdd(Name, Default.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
BindingOperations.SetBinding(cascadeSelector, CascadeSelector.SelectedValueProperty,
|
||||
new Binding(Name) { Source = context, Mode = BindingMode.TwoWay });
|
||||
|
||||
list.Add(cascadeSelector);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Exception($"Unknown setting type: {Type}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Service.Model.Oauth;
|
||||
using BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Interface
|
||||
{
|
||||
public interface IKongyingTavernApiService
|
||||
{
|
||||
Task<OauthTokenResponse> GetTokenAsync(CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<ItemTypeVo>> GetItemTypeListAsync(CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<MarkerVo>> GetMarkerListAsync(CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<IconVo>> GetIconListAsync(CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Model.MaskMap;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Interface;
|
||||
|
||||
public interface IMaskMapPointService
|
||||
{
|
||||
Task<IReadOnlyList<MaskMapPointLabel>> GetLabelCategoriesAsync(CancellationToken ct = default);
|
||||
|
||||
Task<MaskMapPointsResult> GetPointsAsync(IReadOnlyList<MaskMapPointLabel> selectedItems, CancellationToken ct = default);
|
||||
|
||||
Task<MaskMapPointInfo> GetPointInfoAsync(MaskMapPoint point, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Requests;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Responses;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Interface
|
||||
{
|
||||
public interface IMihoyoMapApiService
|
||||
{
|
||||
/**
|
||||
* 获取点位类型树
|
||||
*/
|
||||
Task<ApiResponse<LabelTreeData>> GetLabelTreeAsync(LabelTreeRequest request, CancellationToken ct = default);
|
||||
/**
|
||||
* 获取点位信息明细
|
||||
*/
|
||||
Task<ApiResponse<PointInfoData>> GetPointInfoAsync(PointInfoRequest request, CancellationToken ct = default);
|
||||
/**
|
||||
* 通过父类型获取所有点位
|
||||
*/
|
||||
Task<ApiResponse<PointListData>> GetPointListAsync(PointListRequest request, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,738 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.GameTask.MapMask;
|
||||
using BetterGenshinImpact.Model.MaskMap;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Requests;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Responses;
|
||||
using BetterGenshinImpact.Service.Tavern;
|
||||
using BetterGenshinImpact.Service.Tavern.Model;
|
||||
using LazyCache;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Service;
|
||||
|
||||
public sealed class MaskMapPointService : IMaskMapPointService
|
||||
{
|
||||
public static readonly TimeSpan CacheDuration = TimeSpan.FromHours(5);
|
||||
|
||||
// 酒馆(空荧酒馆)点位标签树的第一层 Label 类别定义(固定、手工维护),用于构建第一层节点以及限定第二层归类范围。
|
||||
private static readonly IReadOnlyList<(long Id, long IconId, string Name)> KongyingFirstLayerLabelDefinitions = new (long Id, long IconId, string Name)[]
|
||||
{
|
||||
(10, 290, "宝箱-品质"),
|
||||
(11, 290, "宝箱-获取"),
|
||||
(2, 291, "见闻"),
|
||||
(3, 292, "特产"),
|
||||
(4, 293, "矿物"),
|
||||
(5, 294, "怪物"),
|
||||
(6, 295, "食材"),
|
||||
(7, 296, "素材"),
|
||||
(8, 297, "家园"),
|
||||
(1, 298, "活动")
|
||||
};
|
||||
|
||||
private readonly ILogger<MaskMapPointService> _logger;
|
||||
private readonly IAppCache _cache;
|
||||
private readonly IMihoyoMapApiService _mihoyoMapApi;
|
||||
private readonly IKongyingTavernApiService _kongyingTavernApi;
|
||||
|
||||
public MaskMapPointService(
|
||||
ILogger<MaskMapPointService> logger,
|
||||
IAppCache cache,
|
||||
IMihoyoMapApiService mihoyoMapApi,
|
||||
IKongyingTavernApiService kongyingTavernApi)
|
||||
{
|
||||
_logger = logger;
|
||||
_cache = cache;
|
||||
_mihoyoMapApi = mihoyoMapApi;
|
||||
_kongyingTavernApi = kongyingTavernApi;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<MaskMapPointLabel>> GetLabelCategoriesAsync(CancellationToken ct = default)
|
||||
{
|
||||
return GetProvider() switch
|
||||
{
|
||||
MapPointApiProvider.KongyingTavern => GetKongyingLabelCategoriesAsync(ct),
|
||||
_ => GetMihoyoLabelCategoriesAsync(ct)
|
||||
};
|
||||
}
|
||||
|
||||
public Task<MaskMapPointsResult> GetPointsAsync(IReadOnlyList<MaskMapPointLabel> selectedItems, CancellationToken ct = default)
|
||||
{
|
||||
return GetProvider() switch
|
||||
{
|
||||
MapPointApiProvider.KongyingTavern => GetKongyingPointsAsync(selectedItems, ct),
|
||||
_ => GetMihoyoPointsAsync(selectedItems, ct)
|
||||
};
|
||||
}
|
||||
|
||||
public Task<MaskMapPointInfo> GetPointInfoAsync(MaskMapPoint point, CancellationToken ct = default)
|
||||
{
|
||||
return GetProvider() switch
|
||||
{
|
||||
MapPointApiProvider.KongyingTavern => GetKongyingPointInfoAsync(point, ct),
|
||||
_ => GetMihoyoPointInfoAsync(point, ct)
|
||||
};
|
||||
}
|
||||
|
||||
private static MapPointApiProvider GetProvider()
|
||||
{
|
||||
return TaskContext.Instance().Config.MapMaskConfig.MapPointApiProvider;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<MaskMapPointLabel>> GetMihoyoLabelCategoriesAsync(CancellationToken ct)
|
||||
{
|
||||
ApiResponse<LabelTreeData>? resp = null;
|
||||
try
|
||||
{
|
||||
resp = await _mihoyoMapApi.GetLabelTreeAsync(new LabelTreeRequest(), ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "调用米游社地图接口获取点位树失败");
|
||||
}
|
||||
|
||||
if (resp == null || resp.Retcode != 0 || resp.Data == null)
|
||||
{
|
||||
resp = TryLoadLabelTreeFromLocalExample();
|
||||
}
|
||||
|
||||
if (resp == null || resp.Retcode != 0 || resp.Data == null)
|
||||
{
|
||||
return Array.Empty<MaskMapPointLabel>();
|
||||
}
|
||||
|
||||
var categories = resp.Data.Tree
|
||||
.OrderBy(x => x.Sort)
|
||||
.ThenBy(x => x.DisplayPriority)
|
||||
.Select(cat =>
|
||||
{
|
||||
var itemsSource = cat.Children != null && cat.Children.Count > 0
|
||||
? cat.Children
|
||||
: new List<LabelNode> { cat };
|
||||
var children = itemsSource
|
||||
.OrderBy(x => x.Sort)
|
||||
.ThenBy(x => x.DisplayPriority)
|
||||
.Select(x => new MaskMapPointLabel
|
||||
{
|
||||
LabelId = x.Id.ToString(CultureInfo.InvariantCulture),
|
||||
ParentId = cat.Id.ToString(CultureInfo.InvariantCulture),
|
||||
Name = x.Name,
|
||||
IconUrl = x.Icon,
|
||||
PointCount = x.PointCount
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return new MaskMapPointLabel
|
||||
{
|
||||
LabelId = cat.Id.ToString(CultureInfo.InvariantCulture),
|
||||
Name = cat.Name,
|
||||
IconUrl = cat.Icon,
|
||||
Children = children
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
private async Task<MaskMapPointsResult> GetMihoyoPointsAsync(IReadOnlyList<MaskMapPointLabel> selectedItems, CancellationToken ct)
|
||||
{
|
||||
if (selectedItems.Count == 0)
|
||||
{
|
||||
return new MaskMapPointsResult();
|
||||
}
|
||||
|
||||
var selectedSecondLevelIds = selectedItems.Select(x => x.LabelId).ToHashSet(StringComparer.Ordinal);
|
||||
var parentLabelIds = selectedItems
|
||||
.Select(x => x.ParentId)
|
||||
.Where(x => int.TryParse(x, out _))
|
||||
.Select(x => int.Parse(x, CultureInfo.InvariantCulture))
|
||||
.Distinct()
|
||||
.OrderBy(x => x)
|
||||
.ToList();
|
||||
|
||||
var labels = selectedItems
|
||||
.GroupBy(x => x.LabelId, StringComparer.Ordinal)
|
||||
.Select(g => g.First())
|
||||
.Select(x => new MaskMapPointLabel
|
||||
{
|
||||
LabelId = x.LabelId,
|
||||
Name = x.Name,
|
||||
IconUrl = x.IconUrl
|
||||
})
|
||||
.ToList();
|
||||
|
||||
if (parentLabelIds.Count == 0)
|
||||
{
|
||||
return new MaskMapPointsResult
|
||||
{
|
||||
Labels = labels,
|
||||
Points = Array.Empty<MaskMapPoint>()
|
||||
};
|
||||
}
|
||||
|
||||
ApiResponse<PointListData> resp;
|
||||
try
|
||||
{
|
||||
resp = await GetMihoyoPointListCacheAsync(parentLabelIds, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "调用米游社地图接口获取点位列表失败");
|
||||
return new MaskMapPointsResult { Labels = labels, Points = Array.Empty<MaskMapPoint>() };
|
||||
}
|
||||
|
||||
if (resp.Retcode != 0 || resp.Data == null)
|
||||
{
|
||||
_logger.LogWarning("获取地图点位列表失败: {Retcode} {Message}", resp.Retcode, resp.Message);
|
||||
return new MaskMapPointsResult { Labels = labels, Points = Array.Empty<MaskMapPoint>() };
|
||||
}
|
||||
|
||||
var map = MapManager.GetMap(MapTypes.Teyvat, TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod);
|
||||
var points = resp.Data.PointList
|
||||
.Where(x => selectedSecondLevelIds.Contains(x.LabelId.ToString(CultureInfo.InvariantCulture)))
|
||||
.Select(x =>
|
||||
{
|
||||
var m = new MaskMapPoint
|
||||
{
|
||||
Id = x.Id.ToString(CultureInfo.InvariantCulture),
|
||||
X = x.XPos,
|
||||
Y = x.YPos,
|
||||
LabelId = x.LabelId.ToString(CultureInfo.InvariantCulture)
|
||||
};
|
||||
|
||||
(m.GameX, m.GameY) = GameWebMapCoordinateConverter.MysWebToGame(m.X, m.Y);
|
||||
var imageCoordinates = map.ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f((float)m.GameX, (float)m.GameY));
|
||||
(m.ImageX, m.ImageY) = (imageCoordinates.X, imageCoordinates.Y);
|
||||
return m;
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return new MaskMapPointsResult
|
||||
{
|
||||
Labels = labels,
|
||||
Points = points
|
||||
};
|
||||
}
|
||||
|
||||
private Task<ApiResponse<PointListData>> GetMihoyoPointListCacheAsync(IReadOnlyList<int> parentLabelIds, CancellationToken ct)
|
||||
{
|
||||
var labelIds = parentLabelIds?.Distinct().OrderBy(x => x).ToArray() ?? Array.Empty<int>();
|
||||
var key = $"mihoyo-map:point-list:2:ys_obc:zh-cn:{string.Join(",", labelIds)}";
|
||||
var request = new PointListRequest
|
||||
{
|
||||
LabelIds = labelIds.ToList()
|
||||
};
|
||||
|
||||
return _cache.GetOrAddAsync(
|
||||
key,
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
return await _mihoyoMapApi.GetPointListAsync(request, CancellationToken.None);
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<MaskMapPointInfo> GetMihoyoPointInfoAsync(MaskMapPoint point, CancellationToken ct)
|
||||
{
|
||||
if (!int.TryParse(point.Id, out var pointId))
|
||||
{
|
||||
return new MaskMapPointInfo { Text = $"点位 ID 非法: {point.Id}" };
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var resp = await _mihoyoMapApi.GetPointInfoAsync(new PointInfoRequest { PointId = pointId }, ct);
|
||||
if (resp.Retcode != 0 || resp.Data == null)
|
||||
{
|
||||
return new MaskMapPointInfo { Text = $"查询失败: {resp.Retcode} {resp.Message}" };
|
||||
}
|
||||
|
||||
var content = (resp.Data.Info.Content ?? string.Empty).Trim();
|
||||
var imageUrl = resp.Data.Info.Img ?? string.Empty;
|
||||
var urlList = resp.Data.Info.UrlList
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x?.Url))
|
||||
.Select(x => new MaskMapLink
|
||||
{
|
||||
Text = x.Text ?? string.Empty,
|
||||
Url = x.Url ?? string.Empty
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return new MaskMapPointInfo
|
||||
{
|
||||
Text = string.IsNullOrEmpty(content) ? "暂无描述" : content,
|
||||
ImageUrl = imageUrl,
|
||||
UrlList = urlList
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "查询米游社地图点位详情失败");
|
||||
return new MaskMapPointInfo { Text = "查询失败" };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<MaskMapPointLabel>> GetKongyingLabelCategoriesAsync(CancellationToken ct)
|
||||
{
|
||||
var iconUrlById = await GetKongyingIconUrlByIdCachedAsync(ct);
|
||||
var childrenByCategoryId = await GetKongyingChildrenByCategoryIdCachedAsync(KongyingFirstLayerLabelDefinitions, ct);
|
||||
|
||||
var categories = new List<MaskMapPointLabel>(KongyingFirstLayerLabelDefinitions.Count);
|
||||
foreach (var def in KongyingFirstLayerLabelDefinitions)
|
||||
{
|
||||
var catIconUrl = iconUrlById.TryGetValue(def.IconId, out var iconUrl) ? iconUrl : string.Empty;
|
||||
var children = childrenByCategoryId.TryGetValue(def.Id, out var list) ? list : Array.Empty<MaskMapPointLabel>();
|
||||
|
||||
categories.Add(new MaskMapPointLabel
|
||||
{
|
||||
LabelId = def.Id.ToString(CultureInfo.InvariantCulture),
|
||||
ParentId = "KongyingTavern",
|
||||
Name = def.Name,
|
||||
IconUrl = catIconUrl,
|
||||
PointCount = children.Sum(x => x.PointCount),
|
||||
Children = children
|
||||
});
|
||||
}
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
private Task<IReadOnlyDictionary<long, IReadOnlyList<MaskMapPointLabel>>> GetKongyingChildrenByCategoryIdCachedAsync(
|
||||
IReadOnlyList<(long Id, long IconId, string Name)> firstLayerLabelDefinitions,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var categoryIds = firstLayerLabelDefinitions
|
||||
.Select(x => x.Id)
|
||||
.Distinct()
|
||||
.OrderBy(x => x)
|
||||
.ToArray();
|
||||
var key = $"kongying-tavern:children-by-category-id:{string.Join(",", categoryIds)}";
|
||||
|
||||
return _cache.GetOrAddAsync<IReadOnlyDictionary<long, IReadOnlyList<MaskMapPointLabel>>>(
|
||||
key,
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var items = await GetKongyingItemTypeListCachedAsync(CancellationToken.None);
|
||||
var iconUrlById = await GetKongyingIconUrlByIdCachedAsync(CancellationToken.None);
|
||||
|
||||
var dict = categoryIds.ToDictionary(x => x, _ => new Dictionary<string, (long MinId, List<long> LabelIds, string IconUrl, int PointCount)>(StringComparer.Ordinal));
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item.Id == null || item.TypeIdList == null || item.TypeIdList.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var itemId = item.Id.Value;
|
||||
var itemCount = item.Count ?? 0;
|
||||
var itemIconUrl = (item.IconId != null && iconUrlById.TryGetValue(item.IconId.Value, out var url)) ? url : string.Empty;
|
||||
var nameKey = (item.Name ?? string.Empty).Trim();
|
||||
foreach (var typeId in item.TypeIdList)
|
||||
{
|
||||
if (!dict.TryGetValue(typeId, out var byName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!byName.TryGetValue(nameKey, out var acc))
|
||||
{
|
||||
acc = (itemId, new List<long>(), itemIconUrl, 0);
|
||||
}
|
||||
|
||||
acc.LabelIds.Add(itemId);
|
||||
acc.PointCount += itemCount;
|
||||
if (itemId < acc.MinId)
|
||||
{
|
||||
acc.MinId = itemId;
|
||||
}
|
||||
|
||||
byName[nameKey] = acc;
|
||||
}
|
||||
}
|
||||
|
||||
var result = dict.ToDictionary(
|
||||
x => x.Key,
|
||||
x =>
|
||||
{
|
||||
var parentId = x.Key.ToString(CultureInfo.InvariantCulture);
|
||||
var list = x.Value
|
||||
.Select(kv =>
|
||||
{
|
||||
var acc = kv.Value;
|
||||
var ids = acc.LabelIds
|
||||
.Distinct()
|
||||
.OrderBy(id => id)
|
||||
.Select(id => id.ToString(CultureInfo.InvariantCulture))
|
||||
.ToArray();
|
||||
|
||||
return new MaskMapPointLabel
|
||||
{
|
||||
LabelId = acc.MinId.ToString(CultureInfo.InvariantCulture),
|
||||
LabelIds = ids,
|
||||
ParentId = parentId,
|
||||
Name = kv.Key,
|
||||
IconUrl = acc.IconUrl,
|
||||
PointCount = acc.PointCount
|
||||
};
|
||||
})
|
||||
.OrderBy(i => i.Name, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
return (IReadOnlyList<MaskMapPointLabel>)list;
|
||||
});
|
||||
return result;
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<MaskMapPointsResult> GetKongyingPointsAsync(IReadOnlyList<MaskMapPointLabel> selectedItems, CancellationToken ct)
|
||||
{
|
||||
if (selectedItems.Count == 0)
|
||||
{
|
||||
return new MaskMapPointsResult();
|
||||
}
|
||||
|
||||
IEnumerable<string> GetEffectiveIds(MaskMapPointLabel item) =>
|
||||
item.LabelIds is { Count: > 0 } ? item.LabelIds : new[] { item.LabelId };
|
||||
|
||||
var selectedItemIdsInOrder = new List<long>(capacity: selectedItems.Count);
|
||||
var selectedItemIds = new HashSet<long>();
|
||||
foreach (var item in selectedItems)
|
||||
{
|
||||
foreach (var idStr in GetEffectiveIds(item))
|
||||
{
|
||||
if (!long.TryParse(idStr, out var id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (selectedItemIds.Add(id))
|
||||
{
|
||||
selectedItemIdsInOrder.Add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var labelsById = new Dictionary<string, MaskMapPointLabel>(StringComparer.Ordinal);
|
||||
foreach (var item in selectedItems)
|
||||
{
|
||||
foreach (var idStr in GetEffectiveIds(item))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(idStr))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!labelsById.ContainsKey(idStr))
|
||||
{
|
||||
labelsById.Add(idStr, new MaskMapPointLabel
|
||||
{
|
||||
LabelId = idStr,
|
||||
Name = item.Name,
|
||||
IconUrl = item.IconUrl
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var labels = labelsById.Values.ToList();
|
||||
|
||||
if (selectedItemIds.Count == 0)
|
||||
{
|
||||
return new MaskMapPointsResult { Labels = labels, Points = Array.Empty<MaskMapPoint>() };
|
||||
}
|
||||
|
||||
var markersByItemId = await GetKongyingMarkersByItemIdCachedAsync(ct);
|
||||
var map = MapManager.GetMap(MapTypes.Teyvat, TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod);
|
||||
|
||||
var markerById = new Dictionary<long, (MarkerVo Marker, long LabelItemId)>();
|
||||
foreach (var selectedItemId in selectedItemIdsInOrder)
|
||||
{
|
||||
if (!markersByItemId.TryGetValue(selectedItemId, out var markers))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var marker in markers)
|
||||
{
|
||||
if (marker.Id == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var markerId = marker.Id.Value;
|
||||
if (markerById.ContainsKey(markerId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
markerById.Add(markerId, (marker, selectedItemId));
|
||||
}
|
||||
}
|
||||
|
||||
var points = new List<MaskMapPoint>(capacity: Math.Min(markerById.Count, 4096));
|
||||
foreach (var kv in markerById)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var markerId = kv.Key;
|
||||
var marker = kv.Value.Marker;
|
||||
var labelItemId = kv.Value.LabelItemId;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(marker.Position))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryParseKongyingPosition(marker.Position, out var x, out var y))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var m = new MaskMapPoint
|
||||
{
|
||||
Id = markerId.ToString(CultureInfo.InvariantCulture),
|
||||
X = x,
|
||||
Y = y,
|
||||
LabelId = labelItemId.ToString(CultureInfo.InvariantCulture),
|
||||
VideoUrls = string.IsNullOrWhiteSpace(marker.VideoPath)
|
||||
? new List<MaskMapLink>()
|
||||
: new List<MaskMapLink>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Text = string.Empty,
|
||||
Url = marker.VideoPath!.Trim()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
(m.GameX, m.GameY) = GameWebMapCoordinateConverter.KongyingTavernToGame(m.X, m.Y);
|
||||
var imageCoordinates = map.ConvertGenshinMapCoordinatesToImageCoordinates(new Point2f((float)m.GameX, (float)m.GameY));
|
||||
(m.ImageX, m.ImageY) = (imageCoordinates.X, imageCoordinates.Y);
|
||||
points.Add(m);
|
||||
}
|
||||
|
||||
return new MaskMapPointsResult
|
||||
{
|
||||
Labels = labels,
|
||||
Points = points
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<MaskMapPointInfo> GetKongyingPointInfoAsync(MaskMapPoint point, CancellationToken ct)
|
||||
{
|
||||
if (!long.TryParse(point.Id, out var markerId))
|
||||
{
|
||||
return new MaskMapPointInfo { Text = $"点位 ID 非法: {point.Id}" };
|
||||
}
|
||||
|
||||
var markerById = await GetKongyingMarkerByIdCachedAsync(ct);
|
||||
if (!markerById.TryGetValue(markerId, out var marker))
|
||||
{
|
||||
return new MaskMapPointInfo { Text = "暂无描述" };
|
||||
}
|
||||
|
||||
var text = (marker.Content ?? string.Empty).Trim();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
text = (marker.MarkerTitle ?? string.Empty).Trim();
|
||||
}
|
||||
|
||||
return new MaskMapPointInfo
|
||||
{
|
||||
Text = string.IsNullOrWhiteSpace(text) ? "暂无描述" : text,
|
||||
ImageUrl = marker.Picture ?? string.Empty,
|
||||
UrlList = string.IsNullOrWhiteSpace(marker.VideoPath)
|
||||
? Array.Empty<MaskMapLink>()
|
||||
: new[]
|
||||
{
|
||||
new MaskMapLink
|
||||
{
|
||||
Text = string.Empty,
|
||||
Url = marker.VideoPath!.Trim()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Task<IReadOnlyList<ItemTypeVo>> GetKongyingItemTypeListCachedAsync(CancellationToken ct)
|
||||
{
|
||||
const string cacheKey = "kongying-tavern:item-types:area-filter-v1";
|
||||
return _cache.GetOrAddAsync<IReadOnlyList<ItemTypeVo>>(
|
||||
cacheKey,
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var list = await _kongyingTavernApi.GetItemTypeListAsync(CancellationToken.None);
|
||||
return list
|
||||
.Where(x => x.AreaId == null || !KongyingTavernApiService.MaskMapItemTypeExcludedAreaIds.Contains(x.AreaId.Value))
|
||||
.ToList();
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private Task<IReadOnlyList<MarkerVo>> GetKongyingMarkerListCachedAsync(CancellationToken ct)
|
||||
{
|
||||
return _cache.GetOrAddAsync(
|
||||
"kongying-tavern:markers",
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var list = await _kongyingTavernApi.GetMarkerListAsync(CancellationToken.None);
|
||||
return list;
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private Task<IReadOnlyDictionary<long, MarkerVo>> GetKongyingMarkerByIdCachedAsync(CancellationToken ct)
|
||||
{
|
||||
return _cache.GetOrAddAsync<IReadOnlyDictionary<long, MarkerVo>>(
|
||||
"kongying-tavern:markers-by-id",
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var markers = await GetKongyingMarkerListCachedAsync(CancellationToken.None);
|
||||
|
||||
return markers
|
||||
.Where(x => x.Id != null)
|
||||
.GroupBy(x => x.Id!.Value)
|
||||
.ToDictionary(g => g.Key, g => g.First());
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private Task<IReadOnlyDictionary<long, IReadOnlyList<MarkerVo>>> GetKongyingMarkersByItemIdCachedAsync(CancellationToken ct)
|
||||
{
|
||||
return _cache.GetOrAddAsync<IReadOnlyDictionary<long, IReadOnlyList<MarkerVo>>>(
|
||||
"kongying-tavern:markers-by-item-id",
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var apiStart = Stopwatch.GetTimestamp();
|
||||
var markers = await GetKongyingMarkerListCachedAsync(CancellationToken.None);
|
||||
var apiElapsed = Stopwatch.GetElapsedTime(apiStart);
|
||||
|
||||
var responseStart = Stopwatch.GetTimestamp();
|
||||
var markerListByItemId = new Dictionary<long, List<MarkerVo>>(capacity: 4096);
|
||||
|
||||
foreach (var marker in markers)
|
||||
{
|
||||
if (marker.Id == null || string.IsNullOrWhiteSpace(marker.Position) || marker.ItemList == null || marker.ItemList.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var seen = new HashSet<long>();
|
||||
foreach (var markerItem in marker.ItemList)
|
||||
{
|
||||
if (markerItem.ItemId == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!seen.Add(markerItem.ItemId.Value))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!markerListByItemId.TryGetValue(markerItem.ItemId.Value, out var list))
|
||||
{
|
||||
list = new List<MarkerVo>();
|
||||
markerListByItemId[markerItem.ItemId.Value] = list;
|
||||
}
|
||||
|
||||
list.Add(marker);
|
||||
}
|
||||
}
|
||||
|
||||
var result = markerListByItemId.ToDictionary(
|
||||
x => x.Key,
|
||||
x => (IReadOnlyList<MarkerVo>)x.Value);
|
||||
var responseElapsed = Stopwatch.GetElapsedTime(responseStart);
|
||||
|
||||
// _logger.LogInformation(
|
||||
// "空荧酒馆 markers-by-item-id: API {ApiMs}ms, 响应处理 {ResponseMs}ms, markers {MarkerCount}, itemIds {ItemIdCount}",
|
||||
// apiElapsed.TotalMilliseconds,
|
||||
// responseElapsed.TotalMilliseconds,
|
||||
// markers.Count,
|
||||
// result.Count);
|
||||
|
||||
return result;
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private Task<Dictionary<long, string>> GetKongyingIconUrlByIdCachedAsync(CancellationToken ct)
|
||||
{
|
||||
return _cache.GetOrAddAsync(
|
||||
"kongying-tavern:icons-by-id",
|
||||
async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = CacheDuration;
|
||||
var icons = await _kongyingTavernApi.GetIconListAsync(CancellationToken.None);
|
||||
return icons
|
||||
.Where(x => x.Id != null && !string.IsNullOrWhiteSpace(x.Url))
|
||||
.GroupBy(x => x.Id!.Value)
|
||||
.ToDictionary(g => g.Key, g => g.First().Url!);
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
private static bool TryParseKongyingPosition(string position, out double x, out double y)
|
||||
{
|
||||
x = 0;
|
||||
y = 0;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(position))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = position
|
||||
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out x)
|
||||
&& double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out y);
|
||||
}
|
||||
|
||||
private static ApiResponse<LabelTreeData>? TryLoadLabelTreeFromLocalExample()
|
||||
{
|
||||
try
|
||||
{
|
||||
var root = AppContext.BaseDirectory;
|
||||
var path = Path.Combine(root, ".trae", "documents", "tree.json");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = File.ReadAllText(path);
|
||||
return JsonConvert.DeserializeObject<ApiResponse<LabelTreeData>>(json);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Helpers.Security;
|
||||
using LazyCache;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Service;
|
||||
|
||||
public sealed class MemoryFileCache
|
||||
{
|
||||
private readonly IAppCache _memoryCache;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly ILogger<MemoryFileCache> _logger;
|
||||
public static readonly string CacheRootDirectory = Global.Absolute(Path.Combine("User", "Cache", "MemoryFileCache"));
|
||||
|
||||
public MemoryFileCache(
|
||||
IAppCache memoryCache,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<MemoryFileCache> logger)
|
||||
{
|
||||
_memoryCache = memoryCache;
|
||||
_timeProvider = timeProvider;
|
||||
_logger = logger;
|
||||
Directory.CreateDirectory(CacheRootDirectory);
|
||||
}
|
||||
|
||||
public Task<T?> GetOrAddAsync<T>(
|
||||
string cacheType,
|
||||
string cacheKey,
|
||||
TimeSpan ttl,
|
||||
Func<CancellationToken, Task<T?>> factory,
|
||||
Func<T, byte[]> serialize,
|
||||
Func<byte[], T?> deserialize,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cacheKey))
|
||||
{
|
||||
throw new ArgumentException("cacheKey cannot be empty.", nameof(cacheKey));
|
||||
}
|
||||
|
||||
var normalizedCacheType = NormalizeCacheType(cacheType);
|
||||
var memoryCacheKey = $"{normalizedCacheType}:{cacheKey}";
|
||||
Directory.CreateDirectory(GetCacheTypeDirectory(normalizedCacheType));
|
||||
|
||||
return _memoryCache.GetOrAddAsync<T?>(
|
||||
memoryCacheKey,
|
||||
async entry =>
|
||||
{
|
||||
if (TryReadPayload(normalizedCacheType, cacheKey, ttl, out var payload, out var remaining))
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = remaining;
|
||||
try
|
||||
{
|
||||
return deserialize(payload);
|
||||
}
|
||||
catch
|
||||
{
|
||||
TryDeletePayload(normalizedCacheType, cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
entry.AbsoluteExpirationRelativeToNow = ttl;
|
||||
var obj = await factory(CancellationToken.None).ConfigureAwait(false);
|
||||
if (obj == null)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
byte[] bytes;
|
||||
try
|
||||
{
|
||||
bytes = serialize(obj);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (bytes is { Length: > 0 })
|
||||
{
|
||||
TryWritePayload(normalizedCacheType, cacheKey, bytes);
|
||||
}
|
||||
|
||||
return obj;
|
||||
})
|
||||
.WaitAsync(ct);
|
||||
}
|
||||
|
||||
public Task<T?> GetOrAddAsync<T>(
|
||||
string cacheKey,
|
||||
TimeSpan ttl,
|
||||
Func<CancellationToken, Task<T?>> factory,
|
||||
Func<T, byte[]> serialize,
|
||||
Func<byte[], T?> deserialize,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
return GetOrAddAsync(
|
||||
"default",
|
||||
cacheKey,
|
||||
ttl,
|
||||
factory,
|
||||
serialize,
|
||||
deserialize,
|
||||
ct);
|
||||
}
|
||||
|
||||
private static string NormalizeCacheType(string? cacheType)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cacheType))
|
||||
{
|
||||
return "default";
|
||||
}
|
||||
|
||||
cacheType = cacheType.Trim();
|
||||
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var sb = new StringBuilder(cacheType.Length);
|
||||
for (var i = 0; i < cacheType.Length; i++)
|
||||
{
|
||||
var ch = cacheType[i];
|
||||
if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar)
|
||||
{
|
||||
sb.Append('_');
|
||||
continue;
|
||||
}
|
||||
|
||||
var isInvalid = false;
|
||||
for (var j = 0; j < invalidChars.Length; j++)
|
||||
{
|
||||
if (ch == invalidChars[j])
|
||||
{
|
||||
isInvalid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sb.Append(isInvalid ? '_' : ch);
|
||||
}
|
||||
|
||||
var normalized = sb.ToString().Trim();
|
||||
if (normalized.Length == 0 || normalized is "." or "..")
|
||||
{
|
||||
return "default";
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static string GetCacheTypeDirectory(string cacheType)
|
||||
{
|
||||
return Path.Combine(CacheRootDirectory, cacheType);
|
||||
}
|
||||
|
||||
public void PurgeCacheTypeByCacheKeys(string cacheType, IReadOnlyCollection<string> keepCacheKeys)
|
||||
{
|
||||
var normalizedCacheType = NormalizeCacheType(cacheType);
|
||||
var dir = GetCacheTypeDirectory(normalizedCacheType);
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var keepFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var cacheKey in keepCacheKeys)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cacheKey))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var hash = ComputeHash(cacheKey);
|
||||
keepFileNames.Add(hash + ".bin");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
TryDeleteFile(file);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (name.EndsWith(".bin", StringComparison.OrdinalIgnoreCase) && !keepFileNames.Contains(name))
|
||||
{
|
||||
TryDeleteFile(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private string GetPayloadPath(string cacheType, string cacheKey)
|
||||
{
|
||||
var hash = ComputeHash(cacheKey);
|
||||
return Path.Combine(GetCacheTypeDirectory(cacheType), hash + ".bin");
|
||||
}
|
||||
|
||||
private static string ComputeHash(string cacheKey)
|
||||
{
|
||||
return MD5Helper.ComputeMD5(cacheKey);
|
||||
}
|
||||
|
||||
private bool TryReadPayload(string cacheType, string cacheKey, TimeSpan ttl, out byte[] payload, out TimeSpan remaining)
|
||||
{
|
||||
payload = [];
|
||||
remaining = default;
|
||||
var path = GetPayloadPath(cacheType, cacheKey);
|
||||
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var lastWriteUtc = File.GetLastWriteTimeUtc(path);
|
||||
var nowUtc = _timeProvider.GetUtcNow().UtcDateTime;
|
||||
var age = nowUtc - lastWriteUtc;
|
||||
if (age >= ttl)
|
||||
{
|
||||
TryDeleteFile(path);
|
||||
return false;
|
||||
}
|
||||
|
||||
remaining = ttl - age;
|
||||
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
if (fs.Length <= 0 || fs.Length > int.MaxValue)
|
||||
{
|
||||
TryDeleteFile(path);
|
||||
return false;
|
||||
}
|
||||
|
||||
payload = ReadAllBytesByCopyTo(fs);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "读取缓存文件失败: {CacheKey}", cacheKey);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void TryWritePayload(string cacheType, string cacheKey, byte[] payload)
|
||||
{
|
||||
TryWritePayload(cacheType, cacheKey, payload, _timeProvider.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
|
||||
private void TryWritePayload(string cacheType, string cacheKey, byte[] payload, DateTime nowUtc)
|
||||
{
|
||||
var path = GetPayloadPath(cacheType, cacheKey);
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrWhiteSpace(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
var tmpPath = path + ".tmp";
|
||||
|
||||
try
|
||||
{
|
||||
using (var fs = new FileStream(tmpPath, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
WriteAllBytesByCopyTo(fs, payload);
|
||||
fs.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
File.Move(tmpPath, path, overwrite: true);
|
||||
File.SetLastWriteTimeUtc(path, nowUtc);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "写入缓存文件失败: {CacheKey}", cacheKey);
|
||||
TryDeleteFile(tmpPath);
|
||||
}
|
||||
}
|
||||
|
||||
private void TryDeletePayload(string cacheType, string cacheKey)
|
||||
{
|
||||
TryDeleteFile(GetPayloadPath(cacheType, cacheKey));
|
||||
}
|
||||
|
||||
private static unsafe byte[] ReadAllBytesByCopyTo(FileStream fs)
|
||||
{
|
||||
if (fs.Length <= 0 || fs.Length > int.MaxValue)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var bytes = new byte[(int)fs.Length];
|
||||
fixed (byte* p = bytes)
|
||||
{
|
||||
using var ms = new UnmanagedMemoryStream(p, fs.Length, fs.Length, FileAccess.Write);
|
||||
fs.Position = 0;
|
||||
fs.CopyTo(ms);
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static unsafe void WriteAllBytesByCopyTo(FileStream fs, byte[] bytes)
|
||||
{
|
||||
if (bytes.Length <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
fixed (byte* p = bytes)
|
||||
{
|
||||
using var ms = new UnmanagedMemoryStream(p, bytes.Length, bytes.Length, FileAccess.Read);
|
||||
ms.CopyTo(fs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Helpers.Http;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Requests;
|
||||
using BetterGenshinImpact.Service.Model.MihoyoMap.Responses;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service
|
||||
{
|
||||
public class MihoyoMapApiService : IMihoyoMapApiService
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private const string TreeEndpoint = "https://waf-api-takumi.mihoyo.com/common/map_user/ys_obc/v2/map/label/tree";
|
||||
private const string ListEndpoint = "https://waf-api-takumi.mihoyo.com/common/map_user/ys_obc/v3/map/point/list";
|
||||
private const string InfoEndpoint = "https://waf-api-takumi.mihoyo.com/common/map_user/ys_obc/v1/map/point/info";
|
||||
|
||||
public MihoyoMapApiService()
|
||||
{
|
||||
_httpClient = HttpClientFactory.GetCommonSendClient();
|
||||
}
|
||||
|
||||
private static HttpRequestMessage CreateRequest(HttpMethod method, string url)
|
||||
{
|
||||
var request = new HttpRequestMessage(method, url);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
request.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
|
||||
request.Headers.Referrer = new Uri("https://act.mihoyo.com/");
|
||||
return request;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<LabelTreeData>> GetLabelTreeAsync(LabelTreeRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var url = $"{TreeEndpoint}?map_id={request.MapId}&app_sn={Uri.EscapeDataString(request.AppSn)}&lang={Uri.EscapeDataString(request.Lang)}";
|
||||
using var httpRequest = CreateRequest(HttpMethod.Get, url);
|
||||
using var resp = await _httpClient.SendAsync(httpRequest, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
return JsonConvert.DeserializeObject<ApiResponse<LabelTreeData>>(json)!;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<PointInfoData>> GetPointInfoAsync(PointInfoRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var url = $"{InfoEndpoint}?map_id={request.MapId}&point_id={request.PointId}&app_sn={Uri.EscapeDataString(request.AppSn)}&lang={Uri.EscapeDataString(request.Lang)}";
|
||||
using var httpRequest = CreateRequest(HttpMethod.Get, url);
|
||||
httpRequest.Headers.Add("x-rpc-map_version", "4.5");
|
||||
using var resp = await _httpClient.SendAsync(httpRequest, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
return JsonConvert.DeserializeObject<ApiResponse<PointInfoData>>(json)!;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<PointListData>> GetPointListAsync(PointListRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var labelIds = request.LabelIds != null && request.LabelIds.Count > 0
|
||||
? string.Join(",", request.LabelIds.Select(x => x.ToString()))
|
||||
: string.Empty;
|
||||
var url = $"{ListEndpoint}?map_id={request.MapId}&app_sn={Uri.EscapeDataString(request.AppSn)}&lang={Uri.EscapeDataString(request.Lang)}&label_ids={Uri.EscapeDataString(labelIds)}";
|
||||
using var httpRequest = CreateRequest(HttpMethod.Get, url);
|
||||
using var resp = await _httpClient.SendAsync(httpRequest, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
return JsonConvert.DeserializeObject<ApiResponse<PointListData>>(json)!;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Requests
|
||||
{
|
||||
public class LabelTreeRequest
|
||||
{
|
||||
[JsonProperty("map_id")] public int MapId { get; set; } = 2;
|
||||
[JsonProperty("app_sn")] public string AppSn { get; set; } = "ys_obc";
|
||||
[JsonProperty("lang")] public string Lang { get; set; } = "zh-cn";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Requests
|
||||
{
|
||||
public class PointInfoRequest
|
||||
{
|
||||
[JsonProperty("map_id")] public int MapId { get; set; } = 2;
|
||||
[JsonProperty("app_sn")] public string AppSn { get; set; } = "ys_obc";
|
||||
[JsonProperty("lang")] public string Lang { get; set; } = "zh-cn";
|
||||
[JsonProperty("point_id")] public int PointId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Requests
|
||||
{
|
||||
public class PointListRequest
|
||||
{
|
||||
[JsonProperty("map_id")] public int MapId { get; set; } = 2;
|
||||
[JsonProperty("app_sn")] public string AppSn { get; set; } = "ys_obc";
|
||||
[JsonProperty("lang")] public string Lang { get; set; } = "zh-cn";
|
||||
[JsonProperty("label_ids")] public List<int> LabelIds { get; set; } = new();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class ApiResponse<T>
|
||||
{
|
||||
[JsonProperty("retcode")] public int Retcode { get; set; }
|
||||
[JsonProperty("message")] public string Message { get; set; } = string.Empty;
|
||||
[JsonProperty("data")] public T Data { get; set; } = default!;
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class LabelNode
|
||||
{
|
||||
[JsonProperty("id")] public int Id { get; set; }
|
||||
[JsonProperty("name")] public string Name { get; set; } = string.Empty;
|
||||
[JsonProperty("icon")] public string Icon { get; set; } = string.Empty;
|
||||
[JsonProperty("parent_id")] public int ParentId { get; set; }
|
||||
[JsonProperty("depth")] public int Depth { get; set; }
|
||||
[JsonProperty("node_type")] public int NodeType { get; set; }
|
||||
[JsonProperty("jump_type")] public int JumpType { get; set; }
|
||||
[JsonProperty("jump_target_id")] public int JumpTargetId { get; set; }
|
||||
[JsonProperty("wiki_jump_url")] public string WikiJumpUrl { get; set; } = string.Empty;
|
||||
[JsonProperty("display_priority")] public int DisplayPriority { get; set; }
|
||||
[JsonProperty("children")] public List<LabelNode> Children { get; set; } = new();
|
||||
[JsonProperty("activity_page_label")] public int ActivityPageLabel { get; set; }
|
||||
[JsonProperty("area_page_label")] public List<int> AreaPageLabel { get; set; } = new();
|
||||
[JsonProperty("is_all_area")] public bool IsAllArea { get; set; }
|
||||
[JsonProperty("default_show")] public bool DefaultShow { get; set; }
|
||||
[JsonProperty("ch_ext")] public string ChExt { get; set; } = string.Empty;
|
||||
[JsonProperty("sort")] public int Sort { get; set; }
|
||||
[JsonProperty("area_label_list")] public List<int> AreaLabelList { get; set; } = new();
|
||||
[JsonProperty("ext_attr_list")] public List<object> ExtAttrList { get; set; } = new();
|
||||
[JsonProperty("recommend_route_list")] public List<object> RecommendRouteList { get; set; } = new();
|
||||
[JsonProperty("point_count")] public int PointCount { get; set; }
|
||||
[JsonProperty("alias_name")] public string AliasName { get; set; } = string.Empty;
|
||||
[JsonProperty("item_id")] public int ItemId { get; set; }
|
||||
[JsonProperty("rec_refresh_hour")] public int RecRefreshHour { get; set; }
|
||||
[JsonProperty("tips")] public string Tips { get; set; } = string.Empty;
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class LabelTreeData
|
||||
{
|
||||
[JsonProperty("tree")] public List<LabelNode> Tree { get; set; } = new();
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class PointGroup
|
||||
{
|
||||
[JsonProperty("group_id")] public int GroupId { get; set; }
|
||||
[JsonProperty("floor_id")] public int FloorId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class PointInfoData
|
||||
{
|
||||
[JsonProperty("info")] public PointInfo Info { get; set; } = new PointInfo();
|
||||
[JsonProperty("correct_user_list")] public List<PointCorrectUser> CorrectUserList { get; set; } = new List<PointCorrectUser>();
|
||||
[JsonProperty("last_update_time")] public string LastUpdateTime { get; set; } = string.Empty;
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
|
||||
public class PointInfo
|
||||
{
|
||||
[JsonProperty("id")] public int Id { get; set; }
|
||||
[JsonProperty("map_id")] public int MapId { get; set; }
|
||||
[JsonProperty("label_id")] public int LabelId { get; set; }
|
||||
[JsonProperty("x_pos")] public double XPos { get; set; }
|
||||
[JsonProperty("y_pos")] public double YPos { get; set; }
|
||||
[JsonProperty("expansion")] public string Expansion { get; set; } = string.Empty;
|
||||
[JsonProperty("display_state")] public int DisplayState { get; set; }
|
||||
[JsonProperty("version")] public int Version { get; set; }
|
||||
[JsonProperty("editor")] public string Editor { get; set; } = string.Empty;
|
||||
[JsonProperty("editor_name")] public string EditorName { get; set; } = string.Empty;
|
||||
[JsonProperty("author")] public string Author { get; set; } = string.Empty;
|
||||
[JsonProperty("author_name")] public string AuthorName { get; set; } = string.Empty;
|
||||
[JsonProperty("ctime")] public string Ctime { get; set; } = string.Empty;
|
||||
[JsonProperty("content")] public string Content { get; set; } = string.Empty;
|
||||
[JsonProperty("img")] public string Img { get; set; } = string.Empty;
|
||||
[JsonProperty("url_list")] public List<PointInfoUrlItem> UrlList { get; set; } = new List<PointInfoUrlItem>();
|
||||
[JsonProperty("record_id")] public string RecordId { get; set; } = string.Empty;
|
||||
[JsonProperty("area_id")] public int AreaId { get; set; }
|
||||
[JsonProperty("ext_attrs")] public string ExtAttrs { get; set; } = string.Empty;
|
||||
[JsonProperty("z_level")] public int ZLevel { get; set; }
|
||||
[JsonProperty("icon_sign")] public int IconSign { get; set; }
|
||||
[JsonProperty("video")] public PointInfoVideo Video { get; set; } = new PointInfoVideo();
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
|
||||
public class PointInfoUrlItem
|
||||
{
|
||||
[JsonProperty("text")] public string Text { get; set; } = string.Empty;
|
||||
[JsonProperty("url")] public string Url { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class PointInfoVideo
|
||||
{
|
||||
[JsonProperty("cover_url")] public string CoverUrl { get; set; } = string.Empty;
|
||||
[JsonProperty("duration")] public int Duration { get; set; }
|
||||
[JsonProperty("detail")] public JToken? Detail { get; set; }
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
|
||||
public class PointCorrectUser
|
||||
{
|
||||
[JsonProperty("name")] public string Name { get; set; } = string.Empty;
|
||||
[JsonProperty("img")] public string Img { get; set; } = string.Empty;
|
||||
[JsonProperty("ctime")] public string Ctime { get; set; } = string.Empty;
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class PointItem
|
||||
{
|
||||
[JsonProperty("id")] public int Id { get; set; }
|
||||
[JsonProperty("label_id")] public int LabelId { get; set; }
|
||||
[JsonProperty("x_pos")] public double XPos { get; set; }
|
||||
[JsonProperty("y_pos")] public double YPos { get; set; }
|
||||
[JsonProperty("author_name")] public string AuthorName { get; set; } = string.Empty;
|
||||
[JsonProperty("ctime")] public string Ctime { get; set; } = string.Empty;
|
||||
[JsonProperty("display_state")] public int DisplayState { get; set; }
|
||||
[JsonProperty("area_id")] public int AreaId { get; set; }
|
||||
[JsonProperty("ext_attrs")] public string ExtAttrs { get; set; } = string.Empty;
|
||||
[JsonProperty("ext_attrs_map")] public Dictionary<string, object> ExtAttrsMap { get; set; } = new();
|
||||
[JsonProperty("z_level")] public int ZLevel { get; set; }
|
||||
[JsonProperty("icon_sign")] public int IconSign { get; set; }
|
||||
[JsonProperty("point_group")] public PointGroup PointGroup { get; set; } = new();
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.MihoyoMap.Responses
|
||||
{
|
||||
public class PointListData
|
||||
{
|
||||
[JsonProperty("point_list")] public List<PointItem> PointList { get; set; } = new();
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Model.Oauth
|
||||
{
|
||||
public class OauthTokenResponse
|
||||
{
|
||||
[JsonProperty("access_token")] public string AccessToken { get; set; } = string.Empty;
|
||||
[JsonProperty("token_type")] public string TokenType { get; set; } = string.Empty;
|
||||
[JsonProperty("refresh_token")] public string RefreshToken { get; set; } = string.Empty;
|
||||
[JsonProperty("expires_in")] public int ExpiresIn { get; set; }
|
||||
[JsonProperty("scope")] public string Scope { get; set; } = string.Empty;
|
||||
[JsonProperty("jti")] public string Jti { get; set; } = string.Empty;
|
||||
[JsonExtensionData] public IDictionary<string, JToken>? Extra { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Helpers.Http;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Model.Oauth;
|
||||
using BetterGenshinImpact.Service.Tavern.Model;
|
||||
using LazyCache;
|
||||
using LazyCache.Providers;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Tavern;
|
||||
|
||||
public class KongyingTavernApiService : IKongyingTavernApiService
|
||||
{
|
||||
private const string DefaultBaseUrl = "https://cloud.yuanshen.site";
|
||||
private const string DefaultBasicAuthorization = "YmV0dGVyX2dpOjRmNjc4M2I1LTY1M2MtNGVmMC1iYzc3LTViODMyMzA3YTA2NA==";
|
||||
|
||||
private const string OauthTokenPath = "oauth/token";
|
||||
private const string ItemDocListPageBinMd5Path = "api/item_doc/list_page_bin_md5";
|
||||
private const string ItemDocListPageBinPathPrefix = "api/item_doc/list_page_bin/";
|
||||
private const string MarkerDocListPageBinMd5Path = "api/marker_doc/list_page_bin_md5";
|
||||
private const string MarkerDocListPageBinPathPrefix = "api/marker_doc/list_page_bin/";
|
||||
private const string IconDocAllBinPath = "api/icon_doc/all_bin";
|
||||
|
||||
private const string MarkerDocJsonCacheType = "kongying-tavern-marker-doc-json";
|
||||
private static readonly TimeSpan MarkerDocJsonCacheTtl = TimeSpan.FromDays(30);
|
||||
private const int MarkerDocMaxConcurrency = 5;
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly MemoryFileCache _memoryFileCache;
|
||||
private readonly SemaphoreSlim _tokenGate = new(1, 1);
|
||||
private OauthTokenResponse? _cachedToken;
|
||||
private DateTimeOffset _cachedTokenExpiresAt = DateTimeOffset.MinValue;
|
||||
private static readonly TimeSpan RefreshBeforeExpiry = TimeSpan.FromMinutes(1);
|
||||
|
||||
internal static readonly IReadOnlySet<long> MaskMapItemTypeExcludedAreaIds = new HashSet<long> { 7, 25, 42, 16, 4, 8, 10, 26, 32, 43 };
|
||||
|
||||
public KongyingTavernApiService()
|
||||
: this(CreateDefaultMemoryFileCache())
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
public KongyingTavernApiService(MemoryFileCache memoryFileCache)
|
||||
{
|
||||
_memoryFileCache = memoryFileCache;
|
||||
_httpClient = HttpClientFactory.GetClient(
|
||||
"KongyingTavern",
|
||||
() => new HttpClient { Timeout = TimeSpan.FromSeconds(30) });
|
||||
}
|
||||
private static MemoryFileCache CreateDefaultMemoryFileCache()
|
||||
{
|
||||
var memoryCache = new MemoryCache(new MemoryCacheOptions());
|
||||
var provider = new MemoryCacheProvider(memoryCache);
|
||||
var appCache = new CachingService(new Lazy<ICacheProvider>(() => provider));
|
||||
return new MemoryFileCache(appCache, TimeProvider.System, NullLogger<MemoryFileCache>.Instance);
|
||||
}
|
||||
|
||||
|
||||
private static Uri BuildApiUri(string baseUrl, string apiPath, string? query = null)
|
||||
{
|
||||
var normalizedBaseUrl = baseUrl.EndsWith("/", StringComparison.Ordinal) ? baseUrl : $"{baseUrl}/";
|
||||
var normalizedApiPath = apiPath.TrimStart('/');
|
||||
{
|
||||
normalizedApiPath = normalizedApiPath.Replace("//", "/", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var endpoint = new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), normalizedApiPath);
|
||||
if (string.IsNullOrWhiteSpace(query))
|
||||
{
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
return new UriBuilder(endpoint) { Query = query }.Uri;
|
||||
}
|
||||
|
||||
private static Uri BuildUri(string apiPath, string? query = null)
|
||||
{
|
||||
return BuildApiUri(DefaultBaseUrl, apiPath, query);
|
||||
}
|
||||
|
||||
private static Uri BuildUriWithId(string apiPathPrefix, string id)
|
||||
{
|
||||
var apiPath = apiPathPrefix + Uri.EscapeDataString(id);
|
||||
return BuildUri(apiPath);
|
||||
}
|
||||
|
||||
private static HttpRequestMessage CreateRequest(HttpMethod method, Uri uri)
|
||||
{
|
||||
var request = new HttpRequestMessage(method, uri);
|
||||
request.Headers.Accept.ParseAdd("application/json, text/plain, */*");
|
||||
request.Headers.TryAddWithoutValidation("accept-language", "zh-CN,zh;q=0.9");
|
||||
request.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36");
|
||||
return request;
|
||||
}
|
||||
|
||||
public async Task<OauthTokenResponse> GetTokenAsync(CancellationToken ct = default)
|
||||
{
|
||||
var uri = BuildUri(OauthTokenPath, query: "refresh_token=all&grant_type=client_credentials");
|
||||
using var request = CreateRequest(HttpMethod.Post, uri);
|
||||
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", DefaultBasicAuthorization);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
var result = JsonConvert.DeserializeObject<OauthTokenResponse>(json);
|
||||
return result ?? throw new InvalidOperationException("oauth/token 返回内容无法反序列化");
|
||||
}
|
||||
|
||||
public async Task RefreshToken(CancellationToken ct)
|
||||
{
|
||||
var token = await GetTokenAsync(ct);
|
||||
SetCachedToken(token);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<ItemTypeVo>> GetItemTypeListAsync(CancellationToken ct = default)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var pages = await GetItemDocPageMd5ListAsync(ct);
|
||||
if (pages.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var resList = new List<ItemTypeVo>();
|
||||
|
||||
foreach (var page in pages.Where(x => !string.IsNullOrWhiteSpace(x.Md5)).DistinctBy(x => x.Md5))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var pageBytes = await GetItemDocPageBinAsync(page.Md5, ct);
|
||||
var jsonBytes = TryDecompressGzip(pageBytes, out var decompressed) ? decompressed : pageBytes;
|
||||
var json = Encoding.UTF8.GetString(jsonBytes);
|
||||
var pageList = JsonConvert.DeserializeObject<List<ItemTypeVo>>(json);
|
||||
if (pageList is null)
|
||||
{
|
||||
throw new InvalidOperationException($"item_doc/list_page_bin/{page.Md5} 返回内容无法反序列化为 List<ItemTypeVo>");
|
||||
}
|
||||
|
||||
foreach (var item in pageList)
|
||||
{
|
||||
resList.Add(item);
|
||||
}
|
||||
}
|
||||
return resList;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MarkerVo>> GetMarkerListAsync(CancellationToken ct = default)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var pages = await GetMarkerDocPageMd5ListAsync(ct);
|
||||
if (pages.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var distinctPages = pages
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x.Md5))
|
||||
.DistinctBy(x => x.Md5)
|
||||
.ToArray();
|
||||
|
||||
var keepCacheKeys = distinctPages
|
||||
.Select(x => GetMarkerPageJsonCacheKey(x.Md5))
|
||||
.ToArray();
|
||||
_memoryFileCache.PurgeCacheTypeByCacheKeys(MarkerDocJsonCacheType, keepCacheKeys);
|
||||
|
||||
var result = new ConcurrentBag<MarkerVo>();
|
||||
await Parallel.ForEachAsync(
|
||||
distinctPages,
|
||||
new ParallelOptions
|
||||
{
|
||||
CancellationToken = ct,
|
||||
MaxDegreeOfParallelism = MarkerDocMaxConcurrency
|
||||
},
|
||||
async (page, token) =>
|
||||
{
|
||||
var pageList = await LoadMarkerPageAsync(page.Md5, token);
|
||||
foreach (var item in pageList)
|
||||
{
|
||||
result.Add(item);
|
||||
}
|
||||
});
|
||||
|
||||
return result.ToList();
|
||||
}
|
||||
|
||||
private static string GetMarkerPageJsonCacheKey(string pageMd5)
|
||||
{
|
||||
return $"marker_doc/list_page_json/{pageMd5}";
|
||||
}
|
||||
|
||||
private async Task<List<MarkerVo>> LoadMarkerPageAsync(string pageMd5, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var cacheKey = GetMarkerPageJsonCacheKey(pageMd5);
|
||||
var jsonBytes = await _memoryFileCache.GetOrAddAsync<byte[]>(
|
||||
MarkerDocJsonCacheType,
|
||||
cacheKey,
|
||||
MarkerDocJsonCacheTtl,
|
||||
async _ =>
|
||||
{
|
||||
var pageBytes = await GetMarkerDocPageBinAsync(pageMd5, ct);
|
||||
return TryDecompressGzip(pageBytes, out var decompressed) ? decompressed : pageBytes;
|
||||
},
|
||||
static x => x,
|
||||
static x => x,
|
||||
ct);
|
||||
|
||||
if (jsonBytes is not { Length: > 0 })
|
||||
{
|
||||
throw new InvalidOperationException($"marker_doc/list_page_bin/{pageMd5} 返回内容为空");
|
||||
}
|
||||
|
||||
var json = Encoding.UTF8.GetString(jsonBytes);
|
||||
var pageList = JsonConvert.DeserializeObject<List<MarkerVo>>(json);
|
||||
if (pageList is null)
|
||||
{
|
||||
throw new InvalidOperationException($"marker_doc/list_page_bin/{pageMd5} 返回内容无法反序列化为 List<MarkerVo>");
|
||||
}
|
||||
|
||||
return pageList;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IconVo>> GetIconListAsync(CancellationToken ct = default)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var pageBytes = await GetIconDocAllBinAsync(ct);
|
||||
var jsonBytes = TryDecompressGzip(pageBytes, out var decompressed) ? decompressed : pageBytes;
|
||||
var json = Encoding.UTF8.GetString(jsonBytes);
|
||||
var list = JsonConvert.DeserializeObject<List<IconVo>>(json);
|
||||
if (list is null)
|
||||
{
|
||||
throw new InvalidOperationException($"icon_doc/all_bin/ 返回内容无法反序列化为 List<IconVo>");
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private async Task<List<ListPageBinMd5Item>> GetItemDocPageMd5ListAsync(CancellationToken ct)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var uri = BuildUri(ItemDocListPageBinMd5Path);
|
||||
using var request = CreateRequest(HttpMethod.Get, uri);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
|
||||
var result = JsonConvert.DeserializeObject<KongyingTavernResponse<List<ListPageBinMd5Item>>>(json);
|
||||
if (result is null)
|
||||
{
|
||||
throw new InvalidOperationException("item_doc/list_page_bin_md5 返回内容无法反序列化");
|
||||
}
|
||||
|
||||
if (result.Error)
|
||||
{
|
||||
throw new InvalidOperationException($"item_doc/list_page_bin_md5 返回错误: {result.Message ?? "未知错误"}");
|
||||
}
|
||||
|
||||
return result.Data ?? [];
|
||||
}
|
||||
|
||||
private async Task<byte[]> GetItemDocPageBinAsync(string md5, CancellationToken ct)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var uri = BuildUriWithId(ItemDocListPageBinPathPrefix, md5);
|
||||
using var request = CreateRequest(HttpMethod.Get, uri);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
return await resp.Content.ReadAsByteArrayAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<List<ListPageBinMd5Item>> GetMarkerDocPageMd5ListAsync(CancellationToken ct)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var uri = BuildUri(MarkerDocListPageBinMd5Path);
|
||||
using var request = CreateRequest(HttpMethod.Get, uri);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
|
||||
var result = JsonConvert.DeserializeObject<KongyingTavernResponse<List<ListPageBinMd5Item>>>(json);
|
||||
if (result is null)
|
||||
{
|
||||
throw new InvalidOperationException("marker_doc/list_page_bin_md5 返回内容无法反序列化");
|
||||
}
|
||||
|
||||
if (result.Error)
|
||||
{
|
||||
throw new InvalidOperationException($"marker_doc/list_page_bin_md5 返回错误: {result.Message ?? "未知错误"}");
|
||||
}
|
||||
|
||||
return result.Data ?? [];
|
||||
}
|
||||
|
||||
private async Task<byte[]> GetMarkerDocPageBinAsync(string md5, CancellationToken ct)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var uri = BuildUriWithId(MarkerDocListPageBinPathPrefix, md5);
|
||||
using var request = CreateRequest(HttpMethod.Get, uri);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
return await resp.Content.ReadAsByteArrayAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<byte[]> GetIconDocAllBinAsync(CancellationToken ct)
|
||||
{
|
||||
await EnsureAccessTokenAsync(ct);
|
||||
var uri = BuildUri(IconDocAllBinPath);
|
||||
using var request = CreateRequest(HttpMethod.Get, uri);
|
||||
using var resp = await _httpClient.SendAsync(request, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
return await resp.Content.ReadAsByteArrayAsync(ct);
|
||||
}
|
||||
|
||||
private void SetCachedToken(OauthTokenResponse token)
|
||||
{
|
||||
_cachedToken = token;
|
||||
_cachedTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(Math.Max(0, token.ExpiresIn));
|
||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
|
||||
}
|
||||
|
||||
private bool IsTokenStillValid()
|
||||
{
|
||||
return _cachedToken is not null
|
||||
&& DateTimeOffset.UtcNow < _cachedTokenExpiresAt.Subtract(RefreshBeforeExpiry);
|
||||
}
|
||||
|
||||
private async Task EnsureAccessTokenAsync(CancellationToken ct)
|
||||
{
|
||||
if (IsTokenStillValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _tokenGate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (IsTokenStillValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await RefreshToken(ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_tokenGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryDecompressGzip(byte[] input, out byte[] output)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var inputStream = new MemoryStream(input);
|
||||
using var gzip = new GZipStream(inputStream, CompressionMode.Decompress);
|
||||
using var outputStream = new MemoryStream();
|
||||
gzip.CopyTo(outputStream);
|
||||
output = outputStream.ToArray();
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
output = [];
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
/// <summary>
|
||||
/// 图标主表前端封装
|
||||
/// </summary>
|
||||
public sealed class IconVo
|
||||
{
|
||||
/// <summary>
|
||||
/// 乐观锁
|
||||
/// </summary>
|
||||
public long? Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ID
|
||||
/// </summary>
|
||||
public long? Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建人
|
||||
/// </summary>
|
||||
public long? CreatorId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间(时间戳毫秒)
|
||||
/// </summary>
|
||||
public string? CreateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 更新人
|
||||
/// </summary>
|
||||
public long? UpdaterId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 更新时间(时间戳毫秒)
|
||||
/// </summary>
|
||||
public string? UpdateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标标签
|
||||
/// </summary>
|
||||
public string? Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标类型ID列表
|
||||
/// </summary>
|
||||
public List<long>? TypeIdList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标url
|
||||
/// </summary>
|
||||
public string? Url { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标变体url
|
||||
/// </summary>
|
||||
public Dictionary<string, string>? UrlVariants { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标描述
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
internal sealed class KongyingTavernResponse<T>
|
||||
{
|
||||
[JsonProperty("error")]
|
||||
public bool Error { get; set; }
|
||||
|
||||
[JsonProperty("errorStatus")]
|
||||
public int ErrorStatus { get; set; }
|
||||
|
||||
[JsonProperty("errorData")]
|
||||
public string? ErrorData { get; set; }
|
||||
|
||||
[JsonProperty("message")]
|
||||
public string? Message { get; set; }
|
||||
|
||||
[JsonProperty("data")]
|
||||
public T? Data { get; set; }
|
||||
|
||||
[JsonProperty("users")]
|
||||
public JToken? Users { get; set; }
|
||||
|
||||
[JsonProperty("time")]
|
||||
public string? Time { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ListPageBinMd5Item
|
||||
{
|
||||
[JsonProperty("md5")]
|
||||
public string Md5 { get; set; } = string.Empty;
|
||||
|
||||
[JsonProperty("time")]
|
||||
public long Time { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
public sealed class ItemTypeVo
|
||||
{
|
||||
/// <summary>
|
||||
/// 乐观锁
|
||||
/// </summary>
|
||||
public long? Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ID
|
||||
/// </summary>
|
||||
public long? Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建人
|
||||
/// </summary>
|
||||
public long? CreatorId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间
|
||||
/// </summary>
|
||||
public string? CreateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 更新人
|
||||
/// </summary>
|
||||
public long? UpdaterId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 更新时间
|
||||
/// </summary>
|
||||
public string? UpdateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 物品名称
|
||||
/// </summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 地区ID(须确保是末端地区)
|
||||
/// </summary>
|
||||
public long? AreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 默认刷新时间;单位:毫秒
|
||||
/// </summary>
|
||||
public long? DefaultRefreshTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 默认描述模板;用于提交新物品点位时的描述模板
|
||||
/// </summary>
|
||||
public string? DefaultContent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 默认数量
|
||||
/// </summary>
|
||||
public int? DefaultCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标ID
|
||||
/// </summary>
|
||||
public long? IconId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标样式类型
|
||||
/// </summary>
|
||||
public int? IconStyleType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 隐藏标志
|
||||
/// </summary>
|
||||
public int? HiddenFlag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 物品排序
|
||||
/// </summary>
|
||||
public int? SortIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 特殊物品标记;二进制表示;低位第一位:前台是否显示
|
||||
/// </summary>
|
||||
public int? SpecialFlag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 物品类型ID列表
|
||||
/// </summary>
|
||||
public List<long>? TypeIdList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 查询条件下物品总数
|
||||
/// </summary>
|
||||
public int? Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 物品总数区分
|
||||
/// </summary>
|
||||
public Dictionary<int, int> CountSplit { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
public sealed class MarkerExtraVo
|
||||
{
|
||||
public sealed class UndergroundVo
|
||||
{
|
||||
[JsonProperty("is_underground")]
|
||||
public bool? IsUnderground { get; set; }
|
||||
|
||||
[JsonProperty("is_global")]
|
||||
public bool? IsGlobal { get; set; }
|
||||
|
||||
[JsonProperty("region_levels")]
|
||||
public List<string>? RegionLevels { get; set; }
|
||||
}
|
||||
|
||||
public sealed class IconOverrideVo
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public long? Id { get; set; }
|
||||
|
||||
[JsonProperty("minZoom")]
|
||||
public decimal? MinZoom { get; set; }
|
||||
|
||||
[JsonProperty("maxZoom")]
|
||||
public decimal? MaxZoom { get; set; }
|
||||
}
|
||||
|
||||
public sealed class V2_8_IslandVo
|
||||
{
|
||||
[JsonProperty("island_name")]
|
||||
public string? IslandName { get; set; }
|
||||
|
||||
[JsonProperty("island_state")]
|
||||
public List<string>? IslandState { get; set; }
|
||||
}
|
||||
|
||||
[JsonProperty("underground")]
|
||||
public UndergroundVo? Underground { get; set; }
|
||||
|
||||
[JsonProperty("iconOverride")]
|
||||
public IconOverrideVo? IconOverride { get; set; }
|
||||
|
||||
[JsonProperty("1_6_island")]
|
||||
public List<string>? V1_6_Island { get; set; }
|
||||
|
||||
[JsonProperty("2_8_island")]
|
||||
public V2_8_IslandVo? V2_8_Island { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace BetterGenshinImpact.Service.Tavern.Model;
|
||||
|
||||
public sealed class MarkerItemLinkVo
|
||||
{
|
||||
/// <summary>
|
||||
/// 关联物品ID
|
||||
/// BetterGenshinImpact.Service.Tavern.Model.ItemTypeVo.Id
|
||||
/// </summary>
|
||||
public long? ItemId { get; set; }
|
||||
|
||||
public int? Count { get; set; }
|
||||
|
||||
public long? IconId { get; set; }
|
||||
}
|
||||