mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
massive overhaul
- split code into folders and separate files (Detection & Input) - triggerbot - ui overhaul - panes - filled sliders - improved layout - capture methods (directx and gdi) - input methods (mouse event & makcu) - fix autolabeling there is likely some that i forgot, but there is quite alot
This commit is contained in:
+25
-1
@@ -96,12 +96,28 @@ namespace Spectrum
|
|||||||
QuadraticBezier,
|
QuadraticBezier,
|
||||||
Adaptive
|
Adaptive
|
||||||
}
|
}
|
||||||
|
public enum MovementMethod
|
||||||
|
{
|
||||||
|
MouseEvent,
|
||||||
|
Makcu
|
||||||
|
}
|
||||||
|
public enum FovType
|
||||||
|
{
|
||||||
|
Circle,
|
||||||
|
Rectangle
|
||||||
|
}
|
||||||
|
public enum CaptureMethod
|
||||||
|
{
|
||||||
|
GDI,
|
||||||
|
DirectX
|
||||||
|
}
|
||||||
public class ConfigData
|
public class ConfigData
|
||||||
{
|
{
|
||||||
|
|
||||||
// Image settings
|
// Image settings
|
||||||
public int ImageWidth { get; set; } = 640;
|
public int ImageWidth { get; set; } = 640;
|
||||||
public int ImageHeight { get; set; } = 640;
|
public int ImageHeight { get; set; } = 640;
|
||||||
|
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||||
|
|
||||||
// Offset settings
|
// Offset settings
|
||||||
public double YOffsetPercent { get; set; } = 0.8;
|
public double YOffsetPercent { get; set; } = 0.8;
|
||||||
@@ -115,15 +131,23 @@ namespace Spectrum
|
|||||||
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
|
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
|
||||||
public bool EmaSmoothening { get; set; } = true;
|
public bool EmaSmoothening { get; set; } = true;
|
||||||
public double EmaSmootheningFactor { get; set; } = 0.1;
|
public double EmaSmootheningFactor { get; set; } = 0.1;
|
||||||
|
|
||||||
|
public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
||||||
|
|
||||||
|
// Triggerbot settings
|
||||||
public bool TriggerBot { get; set; } = false;
|
public bool TriggerBot { get; set; } = false;
|
||||||
|
public Keys TriggerKey { get; set; } = Keys.XButton2;
|
||||||
|
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||||
|
public int TriggerRadius { get; set; } = 15; // pixels
|
||||||
|
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||||
|
|
||||||
// Display settings
|
// Display settings
|
||||||
public bool ShowDetectionWindow { get; set; } = true;
|
|
||||||
public bool DrawDetections { get; set; } = true;
|
public bool DrawDetections { get; set; } = true;
|
||||||
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
public bool ShowMenu { get; set; } = true;
|
public bool ShowMenu { get; set; } = true;
|
||||||
public Keys MenuKey { get; set; } = Keys.Insert;
|
public Keys MenuKey { get; set; } = Keys.Insert;
|
||||||
public bool DrawFOV { get; set; } = false;
|
public bool DrawFOV { get; set; } = false;
|
||||||
|
public FovType FOVType { get; set; } = FovType.Rectangle;
|
||||||
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
|
|
||||||
// Data collection settings
|
// Data collection settings
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ using System.Collections.Concurrent;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum.Detection
|
||||||
{
|
{
|
||||||
public static class AutoLabeling
|
public static class AutoLabeling
|
||||||
{
|
{
|
||||||
@@ -15,6 +15,7 @@ namespace Spectrum
|
|||||||
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
|
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
|
||||||
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
|
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
|
||||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
public static bool Started = false;
|
||||||
|
|
||||||
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
||||||
{
|
{
|
||||||
@@ -49,6 +50,9 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
|
|
||||||
var labelContent = new StringBuilder();
|
var labelContent = new StringBuilder();
|
||||||
foreach (var box in boundingBoxes)
|
foreach (var box in boundingBoxes)
|
||||||
{
|
{
|
||||||
@@ -56,15 +60,17 @@ namespace Spectrum
|
|||||||
}
|
}
|
||||||
File.WriteAllText(path, labelContent.ToString());
|
File.WriteAllText(path, labelContent.ToString());
|
||||||
}
|
}
|
||||||
catch
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
LogManager.Log("[ERROR] Failed to save labels.", LogLevel.Error);
|
LogManager.Log($"[ERROR] Failed to save labels. Error: {ex.Message}", LogLevel.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static void SaveMatAsImage(Mat mat, string path)
|
private static void SaveMatAsImage(Mat mat, string path)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
Cv2.ImWrite(path, mat);
|
Cv2.ImWrite(path, mat);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -108,6 +114,8 @@ namespace Spectrum
|
|||||||
|
|
||||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
|
||||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -125,9 +133,6 @@ namespace Spectrum
|
|||||||
|
|
||||||
public static void AddBackgroundImage(Mat mat, bool detected)
|
public static void AddBackgroundImage(Mat mat, bool detected)
|
||||||
{
|
{
|
||||||
if (!mainConfig.Data.AutoLabel)
|
|
||||||
return;
|
|
||||||
|
|
||||||
detectionAttemps++;
|
detectionAttemps++;
|
||||||
|
|
||||||
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
|
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
|
||||||
@@ -202,6 +207,8 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
if (cancellationTokenSource != null)
|
if (cancellationTokenSource != null)
|
||||||
return;
|
return;
|
||||||
|
LogManager.Log("Starting auto labeling...", LogLevel.Info);
|
||||||
|
Started = true;
|
||||||
cancellationTokenSource = new CancellationTokenSource();
|
cancellationTokenSource = new CancellationTokenSource();
|
||||||
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
||||||
}
|
}
|
||||||
@@ -209,6 +216,9 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
if (cancellationTokenSource == null)
|
if (cancellationTokenSource == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
LogManager.Log("Stopping auto labeling...", LogLevel.Info);
|
||||||
|
Started = false;
|
||||||
cancellationTokenSource.Cancel();
|
cancellationTokenSource.Cancel();
|
||||||
backgroundTask?.Wait();
|
backgroundTask?.Wait();
|
||||||
cancellationTokenSource.Dispose();
|
cancellationTokenSource.Dispose();
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
using System.Drawing.Imaging;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Direct3D11;
|
||||||
|
using Vortice.DXGI;
|
||||||
|
using Size = System.Drawing.Size;
|
||||||
|
using Rectangle = System.Drawing.Rectangle;
|
||||||
|
using Point = System.Drawing.Point;
|
||||||
|
|
||||||
|
namespace Spectrum.Detection
|
||||||
|
{
|
||||||
|
public class CaptureManager : IDisposable
|
||||||
|
{
|
||||||
|
private readonly object _sync = new();
|
||||||
|
private ID3D11Device? _device;
|
||||||
|
private ID3D11DeviceContext? _context;
|
||||||
|
private IDXGIOutputDuplication? _duplication;
|
||||||
|
private ID3D11Texture2D? _stagingTex;
|
||||||
|
private Size _desktopSize;
|
||||||
|
public bool IsDirectXAvailable { get; private set; }
|
||||||
|
public bool IsInitialized => _device != null && _duplication != null && _stagingTex != null;
|
||||||
|
|
||||||
|
public bool TryInitialize(int adapterIndex = 0, int outputIndex = 0)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DisposeDxgiResources();
|
||||||
|
|
||||||
|
using var factory = DXGI.CreateDXGIFactory1<IDXGIFactory1>();
|
||||||
|
if (factory.EnumAdapters1(adapterIndex, out var adapter).Failure)
|
||||||
|
return false;
|
||||||
|
if (adapter.EnumOutputs(outputIndex, out var output).Failure)
|
||||||
|
{
|
||||||
|
adapter.Dispose();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var hr = D3D11.D3D11CreateDevice(
|
||||||
|
adapter,
|
||||||
|
DriverType.Unknown,
|
||||||
|
DeviceCreationFlags.BgraSupport,
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
FeatureLevel.Level_12_1,
|
||||||
|
FeatureLevel.Level_12_0,
|
||||||
|
FeatureLevel.Level_11_1,
|
||||||
|
FeatureLevel.Level_11_0
|
||||||
|
},
|
||||||
|
out _device);
|
||||||
|
|
||||||
|
if (hr.Failure || _device == null)
|
||||||
|
{
|
||||||
|
output.Dispose();
|
||||||
|
adapter.Dispose();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_context = _device.ImmediateContext;
|
||||||
|
|
||||||
|
_duplication = output.QueryInterface<IDXGIOutput1>().DuplicateOutput(_device);
|
||||||
|
var desc = output.Description;
|
||||||
|
_desktopSize = new Size(desc.DesktopCoordinates.Right - desc.DesktopCoordinates.Left,
|
||||||
|
desc.DesktopCoordinates.Bottom - desc.DesktopCoordinates.Top);
|
||||||
|
|
||||||
|
output.Dispose();
|
||||||
|
adapter.Dispose();
|
||||||
|
|
||||||
|
EnsureStagingTexture(_desktopSize);
|
||||||
|
|
||||||
|
IsDirectXAvailable = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
IsDirectXAvailable = false;
|
||||||
|
DisposeDxgiResources();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Bitmap? CaptureScreenshotDirectX(Rectangle bounds)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (!IsInitialized)
|
||||||
|
{
|
||||||
|
if (!TryInitialize())
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
bounds = Rectangle.Intersect(new Rectangle(Point.Empty, _desktopSize), bounds);
|
||||||
|
if (bounds.Width <= 0 || bounds.Height <= 0) return null;
|
||||||
|
|
||||||
|
EnsureStagingTexture(_desktopSize);
|
||||||
|
|
||||||
|
IDXGIResource? desktopResource = null;
|
||||||
|
bool frameAcquired = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = _duplication!.AcquireNextFrame(16, out var frameInfo, out desktopResource);
|
||||||
|
if (result.Failure)
|
||||||
|
{
|
||||||
|
if (result.Code == unchecked((int)Vortice.DXGI.ResultCode.AccessLost) ||
|
||||||
|
result.Code == unchecked((int)Vortice.DXGI.ResultCode.DeviceRemoved))
|
||||||
|
{
|
||||||
|
TryInitialize();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
frameAcquired = true;
|
||||||
|
|
||||||
|
using var fullTex = desktopResource.QueryInterface<ID3D11Texture2D>();
|
||||||
|
|
||||||
|
_context!.CopySubresourceRegion(
|
||||||
|
_stagingTex!,
|
||||||
|
0,
|
||||||
|
bounds.X,
|
||||||
|
bounds.Y,
|
||||||
|
0,
|
||||||
|
fullTex,
|
||||||
|
0,
|
||||||
|
new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||||
|
var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);
|
||||||
|
var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height),
|
||||||
|
ImageLockMode.WriteOnly,
|
||||||
|
PixelFormat.Format32bppArgb);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* srcBase = (byte*)map.DataPointer + bounds.Y * map.RowPitch + bounds.X * 4;
|
||||||
|
int srcStride = map.RowPitch;
|
||||||
|
int dstStride = bmpData.Stride;
|
||||||
|
int rowBytes = bounds.Width * 4;
|
||||||
|
|
||||||
|
byte* dst = (byte*)bmpData.Scan0;
|
||||||
|
byte* src = srcBase;
|
||||||
|
for (int y = 0; y < bounds.Height; y++)
|
||||||
|
{
|
||||||
|
Buffer.MemoryCopy(src, dst, rowBytes, rowBytes);
|
||||||
|
src += srcStride;
|
||||||
|
dst += dstStride;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
bmp.UnlockBits(bmpData);
|
||||||
|
_context.Unmap(_stagingTex!, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bmp;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
desktopResource?.Dispose();
|
||||||
|
if (frameAcquired)
|
||||||
|
{
|
||||||
|
try { _duplication?.ReleaseFrame(); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureStagingTexture(Size desktopSize)
|
||||||
|
{
|
||||||
|
if (_device == null) return;
|
||||||
|
if (_stagingTex != null &&
|
||||||
|
_stagingTex.Description.Width == desktopSize.Width &&
|
||||||
|
_stagingTex.Description.Height == desktopSize.Height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_stagingTex?.Dispose();
|
||||||
|
_stagingTex = _device.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = desktopSize.Width,
|
||||||
|
Height = desktopSize.Height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new(1, 0),
|
||||||
|
Usage = ResourceUsage.Staging,
|
||||||
|
CPUAccessFlags = CpuAccessFlags.Read,
|
||||||
|
BindFlags = BindFlags.None
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Bitmap? CaptureScreenshotGdi(Rectangle bounds)
|
||||||
|
{
|
||||||
|
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||||
|
using var g = Graphics.FromImage(bmp);
|
||||||
|
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy);
|
||||||
|
return bmp;
|
||||||
|
}
|
||||||
|
public bool TryInitializeDirectX(int adapterIndex = 0, int outputIndex = 0) => TryInitialize(adapterIndex, outputIndex);
|
||||||
|
|
||||||
|
private void DisposeDxgiResources()
|
||||||
|
{
|
||||||
|
_duplication?.Dispose();
|
||||||
|
_stagingTex?.Dispose();
|
||||||
|
_context?.Dispose();
|
||||||
|
_device?.Dispose();
|
||||||
|
_duplication = null;
|
||||||
|
_stagingTex = null;
|
||||||
|
_context = null;
|
||||||
|
_device = null;
|
||||||
|
IsDirectXAvailable = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
DisposeDxgiResources();
|
||||||
|
}
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
using OpenCvSharp;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace Spectrum.Detection
|
||||||
|
{
|
||||||
|
class DetectionManager
|
||||||
|
{
|
||||||
|
private long iterationCount = 0;
|
||||||
|
private long totalTime = 0;
|
||||||
|
private Stopwatch stopwatch = new Stopwatch();
|
||||||
|
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||||
|
private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||||
|
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
private Renderer? renderer;
|
||||||
|
private Thread? _detectionThread;
|
||||||
|
private DateTime lastMenuToggle = DateTime.MinValue;
|
||||||
|
private readonly CaptureManager _captureManager;
|
||||||
|
|
||||||
|
public DetectionManager(Renderer renderer)
|
||||||
|
{
|
||||||
|
this.renderer = renderer;
|
||||||
|
_captureManager = Program.SharedCaptureManager;
|
||||||
|
_detectionThread = new Thread(DetectionLoop)
|
||||||
|
{
|
||||||
|
IsBackground = true,
|
||||||
|
Name = "Spectrum Detection Thread",
|
||||||
|
Priority = ThreadPriority.AboveNormal
|
||||||
|
};
|
||||||
|
_detectionThread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DetectionLoop()
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey))
|
||||||
|
{
|
||||||
|
stopwatch.Restart();
|
||||||
|
bounds = new Rectangle(
|
||||||
|
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
|
||||||
|
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
|
||||||
|
mainConfig.Data.ImageWidth,
|
||||||
|
mainConfig.Data.ImageHeight
|
||||||
|
);
|
||||||
|
var screenshot = null as Bitmap;
|
||||||
|
if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
||||||
|
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_captureManager.IsInitialized)
|
||||||
|
_captureManager.Dispose();
|
||||||
|
screenshot = _captureManager.CaptureScreenshotGdi(bounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (screenshot == null)
|
||||||
|
{
|
||||||
|
LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug);
|
||||||
|
Thread.Sleep(2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||||
|
Mat drawing = mat.Clone();
|
||||||
|
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
||||||
|
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
||||||
|
Cv2.Dilate(mat, mat, null, iterations: 2);
|
||||||
|
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
||||||
|
|
||||||
|
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||||
|
|
||||||
|
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray();
|
||||||
|
|
||||||
|
var processedContours = MergeOverlappingContours(filteredContours);
|
||||||
|
|
||||||
|
if (processedContours.Length > 0)
|
||||||
|
{
|
||||||
|
int refX = bounds.X + bounds.Width / 2;
|
||||||
|
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
||||||
|
|
||||||
|
double minDist = double.MaxValue;
|
||||||
|
OpenCvSharp.Point[]? closestContour = null;
|
||||||
|
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
||||||
|
|
||||||
|
foreach (var contour in processedContours)
|
||||||
|
{
|
||||||
|
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
||||||
|
foreach (var point in contour)
|
||||||
|
{
|
||||||
|
if (point.X < minX) minX = point.X;
|
||||||
|
if (point.Y < minY) minY = point.Y;
|
||||||
|
if (point.X > maxX) maxX = point.X;
|
||||||
|
if (point.Y > maxY) maxY = point.Y;
|
||||||
|
}
|
||||||
|
int centerX = (minX + maxX) / 2;
|
||||||
|
int centerY = (minY + maxY) / 2;
|
||||||
|
|
||||||
|
int absCenterX = centerX + bounds.X;
|
||||||
|
int absCenterY = centerY + bounds.Y;
|
||||||
|
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
||||||
|
|
||||||
|
if (dist < minDist)
|
||||||
|
{
|
||||||
|
minDist = dist;
|
||||||
|
closestContour = contour;
|
||||||
|
bestMinX = minX;
|
||||||
|
bestMinY = minY;
|
||||||
|
bestMaxX = maxX;
|
||||||
|
bestMaxY = maxY;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (renderer != null && mainConfig.Data.DrawDetections)
|
||||||
|
{
|
||||||
|
var _rect = new Rectangle(
|
||||||
|
minX + bounds.X,
|
||||||
|
minY + bounds.Y,
|
||||||
|
(maxX - minX + 1),
|
||||||
|
(maxY - minY + 1)
|
||||||
|
);
|
||||||
|
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (closestContour != null)
|
||||||
|
{
|
||||||
|
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
||||||
|
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
||||||
|
int targetX = groupX + bounds.X;
|
||||||
|
int targetY = groupY + bounds.Y;
|
||||||
|
|
||||||
|
if (mainConfig.Data.AutoLabel)
|
||||||
|
{
|
||||||
|
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
||||||
|
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||||
|
}
|
||||||
|
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
||||||
|
{
|
||||||
|
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
||||||
|
|
||||||
|
if (mainConfig.Data.EnableAim)
|
||||||
|
{
|
||||||
|
InputManager.MoveMouse();
|
||||||
|
}
|
||||||
|
if (mainConfig.Data.TriggerBot)
|
||||||
|
{
|
||||||
|
var _ = InputManager.ClickMouse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mainConfig.Data.DebugMode)
|
||||||
|
{
|
||||||
|
iterationCount++;
|
||||||
|
totalTime += stopwatch.ElapsedMilliseconds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (mainConfig.Data.CollectData)
|
||||||
|
{
|
||||||
|
if (mainConfig.Data.CollectData)
|
||||||
|
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||||
|
}
|
||||||
|
screenshot?.Dispose();
|
||||||
|
mat.Dispose();
|
||||||
|
drawing.Dispose();
|
||||||
|
|
||||||
|
if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel))
|
||||||
|
{
|
||||||
|
AutoLabeling.StartLabeling();
|
||||||
|
}
|
||||||
|
else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel)
|
||||||
|
{
|
||||||
|
AutoLabeling.StopLabeling();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iterationCount >= 1000 && mainConfig.Data.DebugMode)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info);
|
||||||
|
int fps = (int)(iterationCount * 1000 / totalTime);
|
||||||
|
LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info);
|
||||||
|
LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info);
|
||||||
|
iterationCount = 0;
|
||||||
|
totalTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
||||||
|
{
|
||||||
|
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
|
||||||
|
lastMenuToggle = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
|
||||||
|
Thread.Sleep(5);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Thread.Sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||||
|
{
|
||||||
|
var contourRects = new List<(Rect rect, List<int> indices)>();
|
||||||
|
for (int i = 0; i < contours.Length; i++)
|
||||||
|
{
|
||||||
|
var rect = Cv2.BoundingRect(contours[i]);
|
||||||
|
contourRects.Add((rect, new List<int> { i }));
|
||||||
|
}
|
||||||
|
bool merged;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
merged = false;
|
||||||
|
for (int i = 0; i < contourRects.Count; i++)
|
||||||
|
{
|
||||||
|
var (rectA, indicesA) = contourRects[i];
|
||||||
|
for (int j = i + 1; j < contourRects.Count; j++)
|
||||||
|
{
|
||||||
|
var (rectB, indicesB) = contourRects[j];
|
||||||
|
if (rectA.IntersectsWith(rectB))
|
||||||
|
{
|
||||||
|
var newRect = new Rect(
|
||||||
|
Math.Min(rectA.X, rectB.X),
|
||||||
|
Math.Min(rectA.Y, rectB.Y),
|
||||||
|
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
||||||
|
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
||||||
|
);
|
||||||
|
var newIndices = new List<int>();
|
||||||
|
newIndices.AddRange(indicesA);
|
||||||
|
newIndices.AddRange(indicesB);
|
||||||
|
contourRects[i] = (newRect, newIndices);
|
||||||
|
contourRects.RemoveAt(j);
|
||||||
|
merged = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (merged) break;
|
||||||
|
}
|
||||||
|
} while (merged);
|
||||||
|
|
||||||
|
var mergedContours = new List<OpenCvSharp.Point[]>();
|
||||||
|
foreach (var (rect, indices) in contourRects)
|
||||||
|
{
|
||||||
|
var points = new List<OpenCvSharp.Point>();
|
||||||
|
foreach (var idx in indices)
|
||||||
|
{
|
||||||
|
points.AddRange(contours[idx]);
|
||||||
|
}
|
||||||
|
var hull = Cv2.ConvexHull(points);
|
||||||
|
mergedContours.Add(hull);
|
||||||
|
}
|
||||||
|
return mergedContours.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.Makcu
|
||||||
|
{
|
||||||
|
internal class MakcuMain
|
||||||
|
{
|
||||||
|
public static MakcuMouse MakcuInstance { get; private set; }
|
||||||
|
|
||||||
|
private static bool _isMakcuLoaded = false;
|
||||||
|
|
||||||
|
private static bool _isSubscribedToButtonEvents = false;
|
||||||
|
|
||||||
|
private const bool DefaultDebugLoggingForInternalCreation = false;
|
||||||
|
private const bool DefaultSendInitCommandsForInternalCreation = true;
|
||||||
|
|
||||||
|
public static void ConfigureMakcuInstance(bool debugEnabled, bool sendInitCmds)
|
||||||
|
{
|
||||||
|
|
||||||
|
LogManager.Log($"MakcuMain: Configuring MakcuInstance. Debug: {debugEnabled}, SendInitCmds: {sendInitCmds}", LogLevel.Debug);
|
||||||
|
UnsubscribeFromButtonEvents();
|
||||||
|
MakcuInstance?.Dispose();
|
||||||
|
|
||||||
|
MakcuInstance = new MakcuMouse(debugEnabled, sendInitCmds);
|
||||||
|
_isMakcuLoaded = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> InitializeMakcuDevice()
|
||||||
|
{
|
||||||
|
if (_isMakcuLoaded && MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||||
|
{
|
||||||
|
LogManager.Log("MakcuMain: InitializeMakcuDevice called, but Makcu is already loaded and connected.", LogLevel.Debug);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MakcuInstance == null)
|
||||||
|
{
|
||||||
|
ConfigureMakcuInstance(true, DefaultSendInitCommandsForInternalCreation);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (MakcuInstance == null || !MakcuInstance.Init())
|
||||||
|
{
|
||||||
|
_isMakcuLoaded = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
string version = MakcuInstance.GetKmVersion();
|
||||||
|
|
||||||
|
_isMakcuLoaded = true;
|
||||||
|
|
||||||
|
SubscribeToButtonEvents();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_isMakcuLoaded = false;
|
||||||
|
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||||
|
{
|
||||||
|
MakcuInstance.Close();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<bool> Load() => await InitializeMakcuDevice();
|
||||||
|
|
||||||
|
public static void Unload()
|
||||||
|
{
|
||||||
|
UnsubscribeFromButtonEvents();
|
||||||
|
if (MakcuInstance != null)
|
||||||
|
{
|
||||||
|
MakcuInstance.Close();
|
||||||
|
}
|
||||||
|
_isMakcuLoaded = false;
|
||||||
|
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SubscribeToButtonEvents()
|
||||||
|
{
|
||||||
|
if (MakcuInstance != null && !_isSubscribedToButtonEvents)
|
||||||
|
{
|
||||||
|
MakcuInstance.ButtonStateChanged += OnMakcuButtonStateChanged;
|
||||||
|
_isSubscribedToButtonEvents = true;
|
||||||
|
LogManager.Log("MakcuMain: Subscribed to MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void UnsubscribeFromButtonEvents()
|
||||||
|
{
|
||||||
|
if (MakcuInstance != null && _isSubscribedToButtonEvents)
|
||||||
|
{
|
||||||
|
MakcuInstance.ButtonStateChanged -= OnMakcuButtonStateChanged;
|
||||||
|
_isSubscribedToButtonEvents = false;
|
||||||
|
LogManager.Log("MakcuMain: Unsubscribed from MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnMakcuButtonStateChanged(MakcuMouseButton button, bool isPressed)
|
||||||
|
{
|
||||||
|
|
||||||
|
string state = isPressed ? "Pressed" : "Released";
|
||||||
|
LogManager.Log($"{button} physical {state}!", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
public static void DisposeInstance()
|
||||||
|
{
|
||||||
|
Unload();
|
||||||
|
MakcuInstance?.Dispose();
|
||||||
|
MakcuInstance = null;
|
||||||
|
_isMakcuLoaded = false;
|
||||||
|
LogManager.Log("MakcuMain: MakcuMouse instance disposed (null).", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,598 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO.Ports;
|
||||||
|
using System.Text;
|
||||||
|
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||||
|
|
||||||
|
/// https://github.com/sdfgasfgr/Aimmy-Makcu/blob/master/Aimmy2/MouseMovementLibraries/MakcuSupport/MakcuMouse.cs
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.Makcu
|
||||||
|
{
|
||||||
|
public enum MakcuMouseButton
|
||||||
|
{
|
||||||
|
Left = 0, Right = 1, Middle = 2, Mouse4 = 3, Mouse5 = 4
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MakcuMouse : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly byte[] BaudChangeCommand = { 0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00 };
|
||||||
|
|
||||||
|
private SerialPort _serialPort;
|
||||||
|
private readonly bool _debugLogging;
|
||||||
|
private readonly bool _sendInitCommands;
|
||||||
|
|
||||||
|
private readonly object _serialLock = new object();
|
||||||
|
private bool _isInitializedAndConnected = false;
|
||||||
|
private Thread _listenerThread;
|
||||||
|
private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false);
|
||||||
|
private volatile bool _pauseListener = false;
|
||||||
|
|
||||||
|
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = new Dictionary<MakcuMouseButton, bool>();
|
||||||
|
|
||||||
|
public event Action<MakcuMouseButton, bool> ButtonStateChanged;
|
||||||
|
|
||||||
|
public string PortName { get; private set; }
|
||||||
|
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
|
||||||
|
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
||||||
|
|
||||||
|
|
||||||
|
public MakcuMouse(bool debugLogging = false, bool sendInitCommands = true)
|
||||||
|
{
|
||||||
|
_debugLogging = debugLogging;
|
||||||
|
_sendInitCommands = sendInitCommands;
|
||||||
|
foreach (MakcuMouseButton btn in Enum.GetValues(typeof(MakcuMouseButton)))
|
||||||
|
{
|
||||||
|
_buttonStates[btn] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Log(string message)
|
||||||
|
{
|
||||||
|
if (_debugLogging)
|
||||||
|
{
|
||||||
|
LogManager.Log($"[MakcuMouse {DateTime.Now:HH:mm:ss}] {message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private string FindComPortInternal()
|
||||||
|
{
|
||||||
|
Log("Searching for COM port for Makcu device using SerialPort.GetPortNames() and connection test...");
|
||||||
|
string[] availablePorts;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
availablePorts = SerialPort.GetPortNames();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (availablePorts == null || !availablePorts.Any())
|
||||||
|
{
|
||||||
|
Log("No COM ports available according to SerialPort.GetPortNames().");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
||||||
|
|
||||||
|
foreach (string portName in availablePorts)
|
||||||
|
{
|
||||||
|
Log($"Testing port: {portName}");
|
||||||
|
SerialPort testPort = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
|
||||||
|
testPort = new SerialPort(portName, 115200)
|
||||||
|
{
|
||||||
|
ReadTimeout = 250,
|
||||||
|
WriteTimeout = 500,
|
||||||
|
DtrEnable = true,
|
||||||
|
RtsEnable = true
|
||||||
|
};
|
||||||
|
testPort.Open();
|
||||||
|
Log($"Port {portName} opened at 115200 baud.");
|
||||||
|
|
||||||
|
Log($"Sending command to change baudrate to 4M on {portName}.");
|
||||||
|
testPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||||
|
testPort.BaseStream.Flush();
|
||||||
|
Thread.Sleep(150);
|
||||||
|
|
||||||
|
testPort.Close();
|
||||||
|
testPort.BaudRate = 4000000;
|
||||||
|
testPort.Open();
|
||||||
|
Log($"Port {portName} reopened at 4000000 baud.");
|
||||||
|
|
||||||
|
testPort.DiscardInBuffer();
|
||||||
|
testPort.Write("km.version()\r\n");
|
||||||
|
Log($"Command 'km.version()' sent to {portName}. Waiting for response...");
|
||||||
|
|
||||||
|
string response = "";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
response = testPort.ReadLine().Trim();
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
Log($"Timeout waiting for 'km.version()' response on {portName}. Probably not the Makcu device.");
|
||||||
|
testPort.Close();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Log($"Response from 'km.version()' on {portName}: '{response}'");
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(response) && (response.Contains("KMBOX") || response.Contains("Makcu") || response.Contains("MAKCU") || response.StartsWith("v") || char.IsDigit(response.FirstOrDefault())))
|
||||||
|
{
|
||||||
|
Log($"Makcu device found on port: {portName}! Version response: '{response}'");
|
||||||
|
testPort.Close();
|
||||||
|
return portName;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Log($"Response from 'km.version()' on {portName} does not seem to be from a Makcu device. Response: '{response}'");
|
||||||
|
}
|
||||||
|
|
||||||
|
testPort.Close();
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException ex)
|
||||||
|
{
|
||||||
|
Log($"Unauthorized access error on {portName}: {ex.Message} (Port might be in use).");
|
||||||
|
}
|
||||||
|
catch (TimeoutException ex)
|
||||||
|
{
|
||||||
|
Log($"Timeout on {portName} (possibly during baud rate change or write): {ex.Message}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Failed to test port {portName}: {ex.GetType().Name} - {ex.Message}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (testPort != null && testPort.IsOpen)
|
||||||
|
{
|
||||||
|
testPort.Close();
|
||||||
|
}
|
||||||
|
testPort?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Log("Makcu device not found on any available COM ports after connection test.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private bool OpenSerialPort(string portNameToOpen, int baudRate)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_serialPort?.Close();
|
||||||
|
_serialPort?.Dispose();
|
||||||
|
|
||||||
|
Log($"Attempting to open {portNameToOpen} at {baudRate} baud.");
|
||||||
|
_serialPort = new SerialPort(portNameToOpen, baudRate)
|
||||||
|
{
|
||||||
|
ReadTimeout = 100,
|
||||||
|
WriteTimeout = 500,
|
||||||
|
DtrEnable = true,
|
||||||
|
RtsEnable = true
|
||||||
|
};
|
||||||
|
_serialPort.Open();
|
||||||
|
PortName = portNameToOpen;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Failed to open {portNameToOpen} at {baudRate} baud. Error: {ex.Message}");
|
||||||
|
_serialPort?.Dispose(); _serialPort = null; return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool ChangeBaudRateTo4M()
|
||||||
|
{
|
||||||
|
if (_serialPort == null || !_serialPort.IsOpen)
|
||||||
|
{
|
||||||
|
Log("ChangeBaudRateTo4M: _serialPort is null or not open.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Log("Sending command to change baudrate to 4M.");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_serialPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||||
|
_serialPort.BaseStream.Flush();
|
||||||
|
Thread.Sleep(150);
|
||||||
|
|
||||||
|
string currentPortName = _serialPort.PortName;
|
||||||
|
_serialPort.Close();
|
||||||
|
|
||||||
|
_serialPort.BaudRate = 4000000;
|
||||||
|
_serialPort.Open();
|
||||||
|
|
||||||
|
Log("Successfully changed to 4M baud."); return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Error changing baudrate to 4M: {ex.Message}");
|
||||||
|
|
||||||
|
_serialPort?.Close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Init()
|
||||||
|
{
|
||||||
|
lock (_serialLock)
|
||||||
|
{
|
||||||
|
if (_isInitializedAndConnected) { Log("MakcuMouse is already initialized."); return true; }
|
||||||
|
|
||||||
|
string portToUse = FindComPortInternal();
|
||||||
|
if (string.IsNullOrEmpty(portToUse))
|
||||||
|
{ Log("Init failed: Could not find a valid COM port for Makcu."); return false; }
|
||||||
|
|
||||||
|
|
||||||
|
if (!OpenSerialPort(portToUse, 115200))
|
||||||
|
{ Log($"Init failed: Could not open port {portToUse} at 115200 baud."); return false; }
|
||||||
|
|
||||||
|
if (!ChangeBaudRateTo4M())
|
||||||
|
{ Log("Init failed: Could not change to 4M baud."); Close(); return false; }
|
||||||
|
|
||||||
|
_isInitializedAndConnected = true;
|
||||||
|
PortName = portToUse;
|
||||||
|
|
||||||
|
if (_sendInitCommands)
|
||||||
|
{
|
||||||
|
if (!SendCommandInternal("km.buttons(1)", false, out _))
|
||||||
|
{ Log("Init failed: Could not send 'km.buttons(1)'."); Close(); return false; }
|
||||||
|
|
||||||
|
_stopListenerEvent.Reset();
|
||||||
|
_listenerThread = new Thread(() => ListenForButtonEvents(_debugLogging))
|
||||||
|
{ IsBackground = true, Name = "MakcuButtonListener" };
|
||||||
|
_listenerThread.Start();
|
||||||
|
}
|
||||||
|
Log($"MakcuMouse initialized successfully on port {PortName} at {BaudRate} baud."); return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool SendCommandInternal(string command, bool expectResponse, out string responseText, int responseTimeoutMs = 200)
|
||||||
|
{
|
||||||
|
responseText = null;
|
||||||
|
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
||||||
|
{
|
||||||
|
Log($"Error in SendCommand: Connection not open or initialized. Command: {command}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_serialLock)
|
||||||
|
{
|
||||||
|
if (!_serialPort.IsOpen)
|
||||||
|
{
|
||||||
|
Log($"Error in SendCommand (lock): Port not open. Command: {command}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_pauseListener = true;
|
||||||
|
int originalReadTimeout = _serialPort.ReadTimeout;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (expectResponse)
|
||||||
|
{
|
||||||
|
_serialPort.ReadTimeout = responseTimeoutMs;
|
||||||
|
_serialPort.DiscardInBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
Log($"Sending: {command}");
|
||||||
|
_serialPort.Write(command + "\r\n");
|
||||||
|
|
||||||
|
if (expectResponse)
|
||||||
|
{
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
string commandTrimmed = command.Trim();
|
||||||
|
bool firstLineIsEcho = true;
|
||||||
|
|
||||||
|
while (stopwatch.ElapsedMilliseconds < responseTimeoutMs)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string line = _serialPort.ReadLine().Trim();
|
||||||
|
if (!string.IsNullOrEmpty(line))
|
||||||
|
{
|
||||||
|
Log($"Received (raw): {line}");
|
||||||
|
if (line.Equals(commandTrimmed, StringComparison.OrdinalIgnoreCase) && firstLineIsEcho)
|
||||||
|
{
|
||||||
|
firstLineIsEcho = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (line.Equals("OK", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (sb.Length > 0) continue;
|
||||||
|
}
|
||||||
|
if (sb.Length > 0) sb.Append("\n");
|
||||||
|
sb.Append(line);
|
||||||
|
}
|
||||||
|
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
||||||
|
{
|
||||||
|
Thread.Sleep(15);
|
||||||
|
if (_serialPort.BytesToRead == 0) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
Log($"ReadLine() timeout in SendCommandInternal for '{command}'.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ioe) { Log($"InvalidOperationException in ReadLine (SendCommandInternal): {ioe.Message}"); _isInitializedAndConnected = false; Close(); return false; }
|
||||||
|
catch (Exception ex) { Log($"Exception in ReadLine (SendCommandInternal): {ex.Message}"); break; }
|
||||||
|
}
|
||||||
|
stopwatch.Stop();
|
||||||
|
responseText = sb.ToString().Trim();
|
||||||
|
Log($"Final response for '{command}': '{responseText}' (Time: {stopwatch.ElapsedMilliseconds}ms)");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (TimeoutException tex)
|
||||||
|
{
|
||||||
|
Log($"General timeout in SendCommandInternal for '{command}': {tex.Message}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ioe)
|
||||||
|
{
|
||||||
|
Log($"General InvalidOperationException in SendCommandInternal (possibly port closed): {ioe.Message}");
|
||||||
|
_isInitializedAndConnected = false; Close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"General exception in SendCommandInternal for '{command}': {ex.Message}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_pauseListener = false;
|
||||||
|
if (expectResponse)
|
||||||
|
{
|
||||||
|
_serialPort.ReadTimeout = originalReadTimeout;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ListenForButtonEvents(bool debug)
|
||||||
|
{
|
||||||
|
Log("Listener thread started. (PACKET PARSING MODE)");
|
||||||
|
byte lastMask = 0x00; // <<-- CAMBIO CLAVE: Inicializar como todos los botones liberados
|
||||||
|
var buttonMap = new Dictionary<int, MakcuMouseButton> {
|
||||||
|
{0, MakcuMouseButton.Left}, {1, MakcuMouseButton.Right}, {2, MakcuMouseButton.Middle},
|
||||||
|
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
||||||
|
};
|
||||||
|
|
||||||
|
byte[] packetHeader = { 0x6B, 0x6D, 0x2E };
|
||||||
|
int currentHeaderIndex = 0;
|
||||||
|
|
||||||
|
while (!_stopListenerEvent.IsSet)
|
||||||
|
{
|
||||||
|
if (!IsInitializedAndConnected || _pauseListener || _serialPort == null || !_serialPort.IsOpen)
|
||||||
|
{
|
||||||
|
Thread.Sleep(20);
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_serialPort.BytesToRead > 0)
|
||||||
|
{
|
||||||
|
byte byteRead = (byte)_serialPort.ReadByte();
|
||||||
|
|
||||||
|
if (byteRead == packetHeader[currentHeaderIndex])
|
||||||
|
{
|
||||||
|
currentHeaderIndex++;
|
||||||
|
if (currentHeaderIndex == packetHeader.Length)
|
||||||
|
{
|
||||||
|
if (debug) Log($"Listener: Packet header {string.Join(",", packetHeader.Select(b => b.ToString("X2")))} detected!");
|
||||||
|
|
||||||
|
if (_serialPort.BytesToRead > 0)
|
||||||
|
{
|
||||||
|
byte currentMask = (byte)_serialPort.ReadByte();
|
||||||
|
if (debug) Log($"Listener: Potential button mask byte: 0x{currentMask:X2}");
|
||||||
|
|
||||||
|
if (currentMask <= 0b00011111)
|
||||||
|
{
|
||||||
|
if (currentMask != lastMask)
|
||||||
|
{
|
||||||
|
if (debug) Log($"Listener: Processing button mask. New: 0x{currentMask:X2}, Prev: 0x{lastMask:X2}");
|
||||||
|
byte changedBits = (byte)(currentMask ^ lastMask);
|
||||||
|
|
||||||
|
lock (_buttonStates)
|
||||||
|
{
|
||||||
|
foreach (var pair in buttonMap)
|
||||||
|
{
|
||||||
|
if ((changedBits & (1 << pair.Key)) != 0)
|
||||||
|
{
|
||||||
|
bool isPressed = (currentMask & (1 << pair.Key)) != 0;
|
||||||
|
_buttonStates[pair.Value] = isPressed;
|
||||||
|
if (debug) Log($"Listener: ---> EVENT: Button: {pair.Value}, IsPressed: {isPressed}");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ButtonStateChanged?.Invoke(pair.Value, isPressed);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Exception in ButtonStateChanged handler: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lastMask = currentMask;
|
||||||
|
if (debug)
|
||||||
|
{
|
||||||
|
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
||||||
|
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Any() ? string.Join(", ", pressedButtons) : "None")}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int expectedTailBytes = 2;
|
||||||
|
for (int i = 0; i < expectedTailBytes; i++)
|
||||||
|
{
|
||||||
|
if (_serialPort.BytesToRead > 0)
|
||||||
|
{
|
||||||
|
byte consumedByte = (byte)_serialPort.ReadByte();
|
||||||
|
if (debug) Log($"Listener: Consumed tail byte {i + 1}: 0x{consumedByte:X2}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (debug) Log($"Listener: Expected tail byte {i + 1} but no data. Packet might be short.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (debug) Log("Listener: Header found, but no data for button mask byte. Packet might be short.");
|
||||||
|
}
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (currentHeaderIndex > 0 && debug)
|
||||||
|
{
|
||||||
|
Log($"Listener: Byte 0x{byteRead:X2} broke header sequence at index {currentHeaderIndex}. Resetting search.");
|
||||||
|
}
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
if (byteRead == packetHeader[0])
|
||||||
|
{
|
||||||
|
currentHeaderIndex = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Thread.Sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
if (debug) Log("Listener: TimeoutException during serial read.");
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
Log($"Listener: InvalidOperationException (port probably closed): {ex.Message}. Stopping listener.");
|
||||||
|
_isInitializedAndConnected = false;
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"Error in listener: {ex.GetType().Name} - {ex.Message}");
|
||||||
|
currentHeaderIndex = 0;
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log("Listener thread terminated.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Press(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(1)", false, out _);
|
||||||
|
public bool Release(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(0)", false, out _);
|
||||||
|
public bool Move(int x, int y) => SendCommandInternal($"km.move({x},{y})", false, out _);
|
||||||
|
public bool MoveSmooth(int x, int y, int segments) => SendCommandInternal($"km.move({x},{y},{segments})", false, out _);
|
||||||
|
public bool MoveBezier(int x, int y, int segments, int ctrlX, int ctrlY) => SendCommandInternal($"km.move({x},{y},{segments},{ctrlX},{ctrlY})", false, out _);
|
||||||
|
public bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _);
|
||||||
|
|
||||||
|
public string GetKmVersion()
|
||||||
|
{
|
||||||
|
return SendCommandInternal("km.version()", true, out string response, 500) ? response : null;
|
||||||
|
}
|
||||||
|
private string GetButtonString(MakcuMouseButton button)
|
||||||
|
{
|
||||||
|
switch (button)
|
||||||
|
{
|
||||||
|
case MakcuMouseButton.Left: return "left";
|
||||||
|
case MakcuMouseButton.Right: return "right";
|
||||||
|
case MakcuMouseButton.Middle: return "middle";
|
||||||
|
default: throw new ArgumentException($"Button {button} not supported for direct press/release actions (left/right/middle).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private string GetButtonLockString(MakcuMouseButton button)
|
||||||
|
{
|
||||||
|
switch (button)
|
||||||
|
{
|
||||||
|
case MakcuMouseButton.Left: return "ml";
|
||||||
|
case MakcuMouseButton.Right: return "mr";
|
||||||
|
case MakcuMouseButton.Middle: return "mm";
|
||||||
|
case MakcuMouseButton.Mouse4: return "ms1";
|
||||||
|
case MakcuMouseButton.Mouse5: return "ms2";
|
||||||
|
default: throw new ArgumentException($"Button not supported for lock/catch: {button}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public Dictionary<MakcuMouseButton, bool> GetCurrentButtonStates()
|
||||||
|
{ lock (_buttonStates) { return new Dictionary<MakcuMouseButton, bool>(_buttonStates); } }
|
||||||
|
|
||||||
|
public int GetCurrentButtonMask()
|
||||||
|
{
|
||||||
|
int mask = 0;
|
||||||
|
lock (_buttonStates)
|
||||||
|
{
|
||||||
|
if (_buttonStates.TryGetValue(MakcuMouseButton.Left, out bool l) && l) mask |= (1 << (int)MakcuMouseButton.Left);
|
||||||
|
if (_buttonStates.TryGetValue(MakcuMouseButton.Right, out bool r) && r) mask |= (1 << (int)MakcuMouseButton.Right);
|
||||||
|
if (_buttonStates.TryGetValue(MakcuMouseButton.Middle, out bool m) && m) mask |= (1 << (int)MakcuMouseButton.Middle);
|
||||||
|
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse4, out bool m4) && m4) mask |= (1 << (int)MakcuMouseButton.Mouse4);
|
||||||
|
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse5, out bool m5) && m5) mask |= (1 << (int)MakcuMouseButton.Mouse5);
|
||||||
|
}
|
||||||
|
return mask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool _disposedValue;
|
||||||
|
protected virtual void Dispose(bool disposing)
|
||||||
|
{
|
||||||
|
if (!_disposedValue)
|
||||||
|
{
|
||||||
|
if (disposing)
|
||||||
|
{
|
||||||
|
Close();
|
||||||
|
_stopListenerEvent?.Dispose();
|
||||||
|
}
|
||||||
|
_disposedValue = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
|
||||||
|
~MakcuMouse() { Dispose(false); }
|
||||||
|
|
||||||
|
public void Close()
|
||||||
|
{
|
||||||
|
Log("Closing MakcuMouse connection...");
|
||||||
|
_isInitializedAndConnected = false;
|
||||||
|
|
||||||
|
if (_listenerThread != null)
|
||||||
|
{
|
||||||
|
_stopListenerEvent.Set();
|
||||||
|
if (_listenerThread.IsAlive)
|
||||||
|
{
|
||||||
|
if (!_listenerThread.Join(TimeSpan.FromSeconds(1)))
|
||||||
|
{
|
||||||
|
Log("Listener thread did not terminate in time.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_listenerThread = null;
|
||||||
|
}
|
||||||
|
lock (_serialLock)
|
||||||
|
{
|
||||||
|
if (_serialPort != null)
|
||||||
|
{
|
||||||
|
if (_serialPort.IsOpen)
|
||||||
|
{
|
||||||
|
try { _serialPort.Close(); }
|
||||||
|
catch (Exception ex) { Log($"Error closing port: {ex.Message}"); }
|
||||||
|
}
|
||||||
|
_serialPort.Dispose();
|
||||||
|
_serialPort = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PortName = null;
|
||||||
|
Log("MakcuMouse connection closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.MouseEvent
|
||||||
|
{
|
||||||
|
public class MouseMain
|
||||||
|
{
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||||
|
|
||||||
|
public static void Move(int x, int y)
|
||||||
|
{
|
||||||
|
mouse_event(0x0001, (uint)x, (uint)y, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ClickDown()
|
||||||
|
{
|
||||||
|
mouse_event(0x0002, 0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
public static void ClickUp()
|
||||||
|
{
|
||||||
|
mouse_event(0x0004, 0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
using Spectrum.Input.InputLibraries.Makcu;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||||
|
|
||||||
|
namespace Spectrum.Input
|
||||||
|
{
|
||||||
|
public static class InputManager
|
||||||
|
{
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern bool GetCursorPos(out Point lpPoint);
|
||||||
|
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
private static Point lastDetection = new Point();
|
||||||
|
private static long _lastMoveTicks = 0;
|
||||||
|
private static readonly double _dtRef = 1.0 / 120.0;
|
||||||
|
|
||||||
|
private static double GetDeltaSeconds()
|
||||||
|
{
|
||||||
|
long now = Stopwatch.GetTimestamp();
|
||||||
|
if (_lastMoveTicks == 0)
|
||||||
|
{
|
||||||
|
_lastMoveTicks = now;
|
||||||
|
return _dtRef;
|
||||||
|
}
|
||||||
|
long deltaTicks = now - _lastMoveTicks;
|
||||||
|
_lastMoveTicks = now;
|
||||||
|
double dt = (double)deltaTicks / Stopwatch.Frequency;
|
||||||
|
|
||||||
|
if (dt < 0.0001) dt = 0.0001; // 10k fps cap
|
||||||
|
if (dt > 0.05) dt = 0.05; // 20 fps floor
|
||||||
|
return dt;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double TimeScaleFactor(double baseFactor, double deltaSeconds)
|
||||||
|
{
|
||||||
|
if (baseFactor <= 0) return 0;
|
||||||
|
if (baseFactor >= 1) return 1;
|
||||||
|
double k = deltaSeconds / _dtRef;
|
||||||
|
return 1 - Math.Pow(1 - baseFactor, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void MoveMouse()
|
||||||
|
{
|
||||||
|
Point reference = new Point();
|
||||||
|
if (mainConfig.Data.ClosestToMouse)
|
||||||
|
{
|
||||||
|
GetCursorPos(out reference);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||||
|
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point start = new Point(reference.X, reference.Y);
|
||||||
|
Point end = new Point(lastDetection.X, lastDetection.Y);
|
||||||
|
|
||||||
|
double dt = GetDeltaSeconds();
|
||||||
|
double effSensitivity = TimeScaleFactor(mainConfig.Data.Sensitivity, dt);
|
||||||
|
|
||||||
|
Point newPosition = mainConfig.Data.AimMovementType switch
|
||||||
|
{
|
||||||
|
MovementType.CubicBezier => MovementPaths.CubicBezierMovement(start, end, effSensitivity),
|
||||||
|
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||||
|
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
||||||
|
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
||||||
|
_ => end
|
||||||
|
};
|
||||||
|
|
||||||
|
if (mainConfig.Data.EmaSmoothening)
|
||||||
|
{
|
||||||
|
double emaAlpha = TimeScaleFactor(mainConfig.Data.EmaSmootheningFactor, dt);
|
||||||
|
newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha));
|
||||||
|
newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha));
|
||||||
|
}
|
||||||
|
|
||||||
|
int deltaX = newPosition.X - reference.X;
|
||||||
|
int deltaY = newPosition.Y - reference.Y;
|
||||||
|
|
||||||
|
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
||||||
|
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
|
||||||
|
return;
|
||||||
|
|
||||||
|
switch (mainConfig.Data.MovementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
case MovementMethod.Makcu:
|
||||||
|
if (EnsureMakcuReady())
|
||||||
|
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
||||||
|
else
|
||||||
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task ClickMouse()
|
||||||
|
{
|
||||||
|
if (!mainConfig.Data.TriggerBot)
|
||||||
|
return;
|
||||||
|
if (!IsKeyOrMouseDown(mainConfig.Data.TriggerKey) || mainConfig.Data.TriggerKey == Keys.None)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var currentPosition = new Point();
|
||||||
|
if (mainConfig.Data.ClosestToMouse)
|
||||||
|
{
|
||||||
|
GetCursorPos(out currentPosition);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
currentPosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||||
|
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mainConfig.Data.TriggerDelay > 0)
|
||||||
|
await Task.Delay(mainConfig.Data.TriggerDelay);
|
||||||
|
|
||||||
|
int radius = mainConfig.Data.TriggerRadius;
|
||||||
|
|
||||||
|
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
|
||||||
|
{
|
||||||
|
switch (mainConfig.Data.MovementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.ClickDown();
|
||||||
|
break;
|
||||||
|
case MovementMethod.Makcu:
|
||||||
|
if (EnsureMakcuReady())
|
||||||
|
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
||||||
|
else
|
||||||
|
MouseEvent.ClickDown();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.ClickDown();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await Task.Delay(mainConfig.Data.TriggerDuration);
|
||||||
|
switch (mainConfig.Data.MovementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.ClickUp();
|
||||||
|
break;
|
||||||
|
case MovementMethod.Makcu:
|
||||||
|
if (EnsureMakcuReady())
|
||||||
|
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
||||||
|
else
|
||||||
|
MouseEvent.ClickUp();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.ClickUp();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var dist = Math.Sqrt(Math.Pow(currentPosition.X - lastDetection.X, 2) + Math.Pow(currentPosition.Y - lastDetection.Y, 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SetLastDetection(Point point)
|
||||||
|
{
|
||||||
|
lastDetection = point;
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern short GetAsyncKeyState(int vKey);
|
||||||
|
|
||||||
|
private static readonly Keys[] MouseKeys =
|
||||||
|
{
|
||||||
|
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
||||||
|
};
|
||||||
|
|
||||||
|
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
||||||
|
{
|
||||||
|
var tcs = new TaskCompletionSource<Keys>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
|
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
||||||
|
bool subscribedToMakcu = false;
|
||||||
|
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady())
|
||||||
|
{
|
||||||
|
makcuHandler = (btn, isPressed) =>
|
||||||
|
{
|
||||||
|
if (!isPressed) return;
|
||||||
|
var key = MapMakcuButtonToKeys(btn);
|
||||||
|
if (key.HasValue)
|
||||||
|
{
|
||||||
|
tcs.TrySetResult(key.Value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler;
|
||||||
|
subscribedToMakcu = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (tcs.Task.IsCompleted)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int key = 0x08; key <= 0xFE; key++)
|
||||||
|
{
|
||||||
|
if ((GetAsyncKeyState(key) & 0x8000) != 0)
|
||||||
|
{
|
||||||
|
tcs.TrySetResult((Keys)key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var mouseKey in MouseKeys)
|
||||||
|
{
|
||||||
|
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
||||||
|
{
|
||||||
|
tcs.TrySetResult(mouseKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancellationToken?.IsCancellationRequested == true)
|
||||||
|
{
|
||||||
|
tcs.TrySetCanceled();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Thread.Sleep(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||||
|
{
|
||||||
|
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
{ IsBackground = true };
|
||||||
|
|
||||||
|
tcs.Task.ContinueWith(_ =>
|
||||||
|
{
|
||||||
|
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||||
|
{
|
||||||
|
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||||
|
}
|
||||||
|
}, TaskScheduler.Default);
|
||||||
|
|
||||||
|
thread.Start();
|
||||||
|
return tcs.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool EnsureMakcuReady()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||||
|
var ok = MakcuMain.Load().GetAwaiter().GetResult();
|
||||||
|
if (ok && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||||
|
|
||||||
|
LogManager.Log("Makcu not ready. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||||
|
MakcuMain.Unload();
|
||||||
|
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
LogManager.Log("Makcu initialization threw an exception. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||||
|
MakcuMain.Unload();
|
||||||
|
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Keys? MapMakcuButtonToKeys(MakcuMouseButton btn)
|
||||||
|
{
|
||||||
|
return btn switch
|
||||||
|
{
|
||||||
|
MakcuMouseButton.Left => Keys.LButton,
|
||||||
|
MakcuMouseButton.Right => Keys.RButton,
|
||||||
|
MakcuMouseButton.Middle => Keys.MButton,
|
||||||
|
MakcuMouseButton.Mouse4 => Keys.XButton1,
|
||||||
|
MakcuMouseButton.Mouse5 => Keys.XButton2,
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsKeyOrMouseDown(Keys key)
|
||||||
|
{
|
||||||
|
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true)
|
||||||
|
{
|
||||||
|
var makcuBtn = MapKeysToMakcuButton(key);
|
||||||
|
if (makcuBtn.HasValue)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var states = MakcuMain.MakcuInstance.GetCurrentButtonStates();
|
||||||
|
|
||||||
|
return states.TryGetValue(makcuBtn.Value, out var pressed) && pressed;
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
|
||||||
|
{
|
||||||
|
return key switch
|
||||||
|
{
|
||||||
|
Keys.LButton => MakcuMouseButton.Left,
|
||||||
|
Keys.RButton => MakcuMouseButton.Right,
|
||||||
|
Keys.MButton => MakcuMouseButton.Middle,
|
||||||
|
Keys.XButton1 => MakcuMouseButton.Mouse4,
|
||||||
|
Keys.XButton2 => MakcuMouseButton.Mouse5,
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
|
||||||
|
namespace Spectrum.Input
|
||||||
|
{
|
||||||
|
public class MovementPaths
|
||||||
|
{
|
||||||
|
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||||
|
public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
double u = 1 - t;
|
||||||
|
double tt = t * t;
|
||||||
|
double uu = u * u;
|
||||||
|
|
||||||
|
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
||||||
|
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
||||||
|
|
||||||
|
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||||
|
}
|
||||||
|
public static Point CubicBezierMovement(Point start, Point end, double t)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
||||||
|
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
||||||
|
return CubicBezier(start, end, control1, control2, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point CubicBezierCurvedMovement(Point start, Point end, double t, double curvature = 0.25)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
curvature = Math.Max(0, Math.Min(1, curvature));
|
||||||
|
double dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double dist = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (dist == 0) return start;
|
||||||
|
double nx = -dy / dist;
|
||||||
|
double ny = dx / dist;
|
||||||
|
double offset = dist * curvature;
|
||||||
|
var control1 = new Point((int)Math.Round(start.X + dx / 3 + nx * offset), (int)Math.Round(start.Y + dy / 3 + ny * offset));
|
||||||
|
var control2 = new Point((int)Math.Round(start.X + 2 * dx / 3 + nx * offset), (int)Math.Round(start.Y + 2 * dy / 3 + ny * offset));
|
||||||
|
return CubicBezier(start, end, control1, control2, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point LinearInterpolation(Point start, Point end, double t)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
int x = (int)Math.Round(start.X + t * (end.X - start.X));
|
||||||
|
int y = (int)Math.Round(start.Y + t * (end.Y - start.Y));
|
||||||
|
return new Point(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point CurvedMovement(Point start, Point end, double t)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
||||||
|
return QuadraticBezier(start, end, control, t);
|
||||||
|
}
|
||||||
|
public static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
double u = 1 - t;
|
||||||
|
double tt = t * t;
|
||||||
|
double uu = u * u;
|
||||||
|
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
||||||
|
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
||||||
|
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
||||||
|
{
|
||||||
|
double dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double distance = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (distance == 0) return start;
|
||||||
|
double stepSize = Math.Max(0, sensitivity) * distance;
|
||||||
|
stepSize = Math.Min(stepSize, distance);
|
||||||
|
double directionX = dx / distance;
|
||||||
|
double directionY = dy / distance;
|
||||||
|
int newX = (int)Math.Round(start.X + directionX * stepSize);
|
||||||
|
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
||||||
|
return new Point(newX, newY);
|
||||||
|
}
|
||||||
|
public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor)
|
||||||
|
{
|
||||||
|
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||||
|
return currentValue * smoothingFactor + previousValue * (1 - smoothingFactor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point EmaSmoothing(Point previous, Point current, double smoothingFactor)
|
||||||
|
{
|
||||||
|
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||||
|
int x = (int)Math.Round(EmaSmoothing(previous.X, current.X, smoothingFactor));
|
||||||
|
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
||||||
|
return new Point(x, y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
using System.Runtime.InteropServices;
|
|
||||||
|
|
||||||
namespace Spectrum
|
|
||||||
{
|
|
||||||
public static class InputManager
|
|
||||||
{
|
|
||||||
[DllImport("user32.dll")]
|
|
||||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
|
||||||
private static extern bool GetCursorPos(out Point lpPoint);
|
|
||||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
|
||||||
private static Point lastDetection = new Point();
|
|
||||||
|
|
||||||
// AIMMY V2 CODE - https://github.com/Babyhamsta/Aimmy/blob/2e906552673e359ded90383c5e97d79c8f38a2f2/Aimmy2/InputLogic/MouseManager.cs#L34-L50
|
|
||||||
private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
|
||||||
{
|
|
||||||
double u = 1 - t;
|
|
||||||
double tt = t * t;
|
|
||||||
double uu = u * u;
|
|
||||||
|
|
||||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
|
||||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
|
||||||
|
|
||||||
return new Point((int)x, (int)y);
|
|
||||||
}
|
|
||||||
private static Point CubicBezierMovement(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
|
||||||
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
|
||||||
return CubicBezier(start, end, control1, control2, t);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point LinearInterpolation(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
int x = (int)(start.X + t * (end.X - start.X));
|
|
||||||
int y = (int)(start.Y + t * (end.Y - start.Y));
|
|
||||||
return new Point(x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point CurvedMovement(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
|
||||||
return QuadraticBezier(start, end, control, t);
|
|
||||||
}
|
|
||||||
private static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
|
||||||
{
|
|
||||||
double u = 1 - t;
|
|
||||||
double tt = t * t;
|
|
||||||
double uu = u * u;
|
|
||||||
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
|
||||||
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
|
||||||
return new Point((int)x, (int)y);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
|
||||||
{
|
|
||||||
double distance = Math.Sqrt(Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2));
|
|
||||||
double stepSize = distance * sensitivity;
|
|
||||||
|
|
||||||
double directionX = (end.X - start.X) / distance;
|
|
||||||
double directionY = (end.Y - start.Y) / distance;
|
|
||||||
|
|
||||||
int newX = (int)(start.X + directionX * stepSize);
|
|
||||||
int newY = (int)(start.Y + directionY * stepSize);
|
|
||||||
return new Point(newX, newY);
|
|
||||||
}
|
|
||||||
private static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) => (currentValue * smoothingFactor) + (previousValue * (1 - smoothingFactor));
|
|
||||||
|
|
||||||
public static void MoveMouse(Point target)
|
|
||||||
{
|
|
||||||
Point reference = new Point();
|
|
||||||
if (mainConfig.Data.ClosestToMouse)
|
|
||||||
{
|
|
||||||
GetCursorPos(out reference);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// center of the screen
|
|
||||||
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
|
||||||
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
lastDetection = target;
|
|
||||||
|
|
||||||
Point start = new Point(reference.X, reference.Y);
|
|
||||||
Point end = new Point(target.X, target.Y);
|
|
||||||
Point newPosition = mainConfig.Data.AimMovementType switch
|
|
||||||
{
|
|
||||||
MovementType.CubicBezier => CubicBezierMovement(start, end, mainConfig.Data.Sensitivity),
|
|
||||||
MovementType.Linear => LinearInterpolation(start, end, mainConfig.Data.Sensitivity),
|
|
||||||
MovementType.Adaptive => AdaptiveMovement(start, end, mainConfig.Data.Sensitivity),
|
|
||||||
MovementType.QuadraticBezier => CurvedMovement(start, end, mainConfig.Data.Sensitivity),
|
|
||||||
_ => end
|
|
||||||
};
|
|
||||||
|
|
||||||
if (mainConfig.Data.EmaSmoothening)
|
|
||||||
{
|
|
||||||
newPosition.X = (int)EmaSmoothing(reference.X, newPosition.X, mainConfig.Data.EmaSmootheningFactor);
|
|
||||||
newPosition.Y = (int)EmaSmoothing(reference.Y, newPosition.Y, mainConfig.Data.EmaSmootheningFactor);
|
|
||||||
}
|
|
||||||
|
|
||||||
int deltaX = newPosition.X - reference.X;
|
|
||||||
int deltaY = newPosition.Y - reference.Y;
|
|
||||||
|
|
||||||
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
|
||||||
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
|
|
||||||
return;
|
|
||||||
|
|
||||||
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
|
|
||||||
ClickMouse();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void ClickMouse()
|
|
||||||
{
|
|
||||||
if (!mainConfig.Data.TriggerBot)
|
|
||||||
return;
|
|
||||||
|
|
||||||
var currentMousePosition = new Point();
|
|
||||||
if (mainConfig.Data.ClosestToMouse)
|
|
||||||
{
|
|
||||||
GetCursorPos(out currentMousePosition);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// center of the screen
|
|
||||||
currentMousePosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
|
||||||
currentMousePosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Math.Abs(currentMousePosition.X - lastDetection.X) < 25 && Math.Abs(currentMousePosition.Y - lastDetection.Y) < 25)
|
|
||||||
{
|
|
||||||
mouse_event(0x0002, 0, 0, 0, 0);
|
|
||||||
Thread.Sleep(5);
|
|
||||||
mouse_event(0x0004, 0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[DllImport("user32.dll")]
|
|
||||||
private static extern short GetAsyncKeyState(int vKey);
|
|
||||||
|
|
||||||
private static readonly Keys[] MouseKeys =
|
|
||||||
{
|
|
||||||
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
|
||||||
};
|
|
||||||
|
|
||||||
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
|
||||||
{
|
|
||||||
var tcs = new TaskCompletionSource<Keys>();
|
|
||||||
var thread = new Thread(() =>
|
|
||||||
{
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
for (int key = 0x08; key <= 0xFE; key++)
|
|
||||||
{
|
|
||||||
if ((GetAsyncKeyState(key) & 0x8000) != 0)
|
|
||||||
{
|
|
||||||
tcs.TrySetResult((Keys)key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach (var mouseKey in MouseKeys)
|
|
||||||
{
|
|
||||||
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
|
||||||
{
|
|
||||||
tcs.TrySetResult(mouseKey);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (cancellationToken?.IsCancellationRequested == true)
|
|
||||||
{
|
|
||||||
tcs.TrySetCanceled();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Thread.Sleep(10);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
{
|
|
||||||
IsBackground = true
|
|
||||||
};
|
|
||||||
thread.Start();
|
|
||||||
return tcs.Task;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum
|
||||||
{
|
{
|
||||||
public class LogManager
|
public class LogManager
|
||||||
{
|
{
|
||||||
|
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
public enum LogLevel
|
public enum LogLevel
|
||||||
{
|
{
|
||||||
Debug,
|
Debug,
|
||||||
@@ -33,6 +35,12 @@ namespace Spectrum
|
|||||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||||
public static void Log(string message, LogLevel level = LogLevel.Info)
|
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||||
{
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(message)) return;
|
||||||
|
if (mainConfig == null)
|
||||||
|
mainConfig = Program.mainConfig;
|
||||||
|
if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached))
|
||||||
|
return;
|
||||||
|
|
||||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||||
Debug.WriteLine(logMessage);
|
Debug.WriteLine(logMessage);
|
||||||
_logEntries.Add(new LogEntry(level, message));
|
_logEntries.Add(new LogEntry(level, message));
|
||||||
|
|||||||
+26
-284
@@ -1,29 +1,33 @@
|
|||||||
using OpenCvSharp;
|
using OpenCvSharp;
|
||||||
using System.Diagnostics;
|
using Spectrum.Detection;
|
||||||
using System.Drawing.Imaging;
|
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum
|
||||||
{
|
{
|
||||||
class Program
|
class Program
|
||||||
{
|
{
|
||||||
static Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
|
||||||
static Renderer? renderer = null;
|
static Renderer? renderer = null;
|
||||||
private static DateTime lastMenuToggle = DateTime.MinValue;
|
|
||||||
public static ConfigManager<ConfigData> mainConfig = new ConfigManager<ConfigData>("bin\\configs\\config.json");
|
public static ConfigManager<ConfigData> mainConfig = new ConfigManager<ConfigData>("bin\\configs\\config.json");
|
||||||
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
|
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
|
||||||
public static long iterationCount = 0;
|
public static long iterationCount = 0;
|
||||||
public static long totalTime = 0;
|
public static long totalTime = 0;
|
||||||
private static Stopwatch stopwatch = new Stopwatch();
|
private static DetectionManager? detectionManager;
|
||||||
|
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
|
||||||
|
|
||||||
|
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
|
|
||||||
Thread renderThread = new Thread(() =>
|
Thread renderThread = new Thread(() =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
renderer = new Renderer();
|
renderer = new Renderer(SharedCaptureManager);
|
||||||
|
bool dxok = SharedCaptureManager.TryInitializeDirectX();
|
||||||
|
if (!dxok)
|
||||||
|
{
|
||||||
|
LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning);
|
||||||
|
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
||||||
|
}
|
||||||
renderer.Run();
|
renderer.Run();
|
||||||
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
|
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
|
||||||
}
|
}
|
||||||
@@ -34,22 +38,20 @@ namespace Spectrum
|
|||||||
});
|
});
|
||||||
renderThread.Start();
|
renderThread.Start();
|
||||||
|
|
||||||
Directory.CreateDirectory("bin");
|
string[] dirs = { "bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs" };
|
||||||
Directory.CreateDirectory("bin/dataset");
|
foreach (var dir in dirs)
|
||||||
Directory.CreateDirectory("bin/dataset/images");
|
{
|
||||||
Directory.CreateDirectory("bin/dataset/labels");
|
if (!Directory.Exists(dir))
|
||||||
Directory.CreateDirectory("bin/logs");
|
{
|
||||||
Directory.CreateDirectory("bin/configs");
|
Directory.CreateDirectory(dir);
|
||||||
|
LogManager.Log($"Created directory: {dir}", LogManager.LogLevel.Info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||||
mainConfig.LoadConfig();
|
mainConfig.LoadConfig();
|
||||||
mainConfig.StartFileWatcher();
|
mainConfig.StartFileWatcher();
|
||||||
|
|
||||||
if (mainConfig.Data.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
|
|
||||||
Cv2.WaitKey(1);
|
|
||||||
}
|
|
||||||
if (mainConfig.Data.AutoLabel)
|
if (mainConfig.Data.AutoLabel)
|
||||||
{
|
{
|
||||||
AutoLabeling.StartLabeling();
|
AutoLabeling.StartLabeling();
|
||||||
@@ -64,275 +66,15 @@ namespace Spectrum
|
|||||||
mainConfig.LoadConfig(true);
|
mainConfig.LoadConfig(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (true)
|
Thread.Sleep(1000);
|
||||||
|
|
||||||
|
if (renderer == null)
|
||||||
{
|
{
|
||||||
if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.Keybind) < 0)
|
LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error);
|
||||||
{
|
return;
|
||||||
stopwatch.Restart();
|
|
||||||
bounds = new Rectangle(
|
|
||||||
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
|
|
||||||
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
|
|
||||||
mainConfig.Data.ImageWidth,
|
|
||||||
mainConfig.Data.ImageHeight
|
|
||||||
);
|
|
||||||
var screenshot = CaptureScreenshot(bounds);
|
|
||||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
|
||||||
Mat drawing = mat.Clone();
|
|
||||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
|
||||||
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
|
||||||
Cv2.Dilate(mat, mat, null, iterations: 2);
|
|
||||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
|
||||||
|
|
||||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
|
||||||
|
|
||||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray();
|
|
||||||
|
|
||||||
var mergedContours = MergeOverlappingContours(filteredContours);
|
|
||||||
|
|
||||||
var processedContours = mergedContours.Select(ShrinkWideContour).ToArray();
|
|
||||||
|
|
||||||
if (processedContours.Length > 0)
|
|
||||||
{
|
|
||||||
int refX = bounds.X + bounds.Width / 2;
|
|
||||||
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
|
||||||
|
|
||||||
double minDist = double.MaxValue;
|
|
||||||
OpenCvSharp.Point[]? closestContour = null;
|
|
||||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
|
||||||
|
|
||||||
foreach (var contour in processedContours)
|
|
||||||
{
|
|
||||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
|
||||||
foreach (var point in contour)
|
|
||||||
{
|
|
||||||
if (point.X < minX) minX = point.X;
|
|
||||||
if (point.Y < minY) minY = point.Y;
|
|
||||||
if (point.X > maxX) maxX = point.X;
|
|
||||||
if (point.Y > maxY) maxY = point.Y;
|
|
||||||
}
|
|
||||||
int centerX = (minX + maxX) / 2;
|
|
||||||
int centerY = (minY + maxY) / 2;
|
|
||||||
|
|
||||||
int absCenterX = centerX + bounds.X;
|
|
||||||
int absCenterY = centerY + bounds.Y;
|
|
||||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
|
||||||
|
|
||||||
if (dist < minDist)
|
|
||||||
{
|
|
||||||
minDist = dist;
|
|
||||||
closestContour = contour;
|
|
||||||
bestMinX = minX;
|
|
||||||
bestMinY = minY;
|
|
||||||
bestMaxX = maxX;
|
|
||||||
bestMaxY = maxY;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
|
||||||
{
|
|
||||||
var _rect = new Rectangle(
|
|
||||||
minX + bounds.X,
|
|
||||||
minY + bounds.Y,
|
|
||||||
(maxX - minX + 1),
|
|
||||||
(maxY - minY + 1)
|
|
||||||
);
|
|
||||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (closestContour != null)
|
|
||||||
{
|
|
||||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
|
||||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
|
||||||
int targetX = groupX + bounds.X;
|
|
||||||
int targetY = groupY + bounds.Y;
|
|
||||||
|
|
||||||
if (mainConfig.Data.AutoLabel)
|
|
||||||
{
|
|
||||||
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
|
||||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
|
||||||
}
|
|
||||||
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
|
||||||
{
|
|
||||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mainConfig.Data.EnableAim)
|
|
||||||
{
|
|
||||||
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mainConfig.Data.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
|
|
||||||
Cv2.ImShow("Spectrum Detection", drawing);
|
|
||||||
Cv2.WaitKey(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (mainConfig.Data.DebugMode)
|
|
||||||
{
|
|
||||||
iterationCount++;
|
|
||||||
totalTime += stopwatch.ElapsedMilliseconds;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (mainConfig.Data.ShowDetectionWindow || mainConfig.Data.CollectData)
|
|
||||||
{
|
|
||||||
Cv2.ImShow("Spectrum Detection", drawing);
|
|
||||||
Cv2.WaitKey(1);
|
|
||||||
if (mainConfig.Data.CollectData)
|
|
||||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
|
||||||
}
|
|
||||||
screenshot?.Dispose();
|
|
||||||
mat.Dispose();
|
|
||||||
drawing.Dispose();
|
|
||||||
|
|
||||||
if (iterationCount >= 1000 && mainConfig.Data.DebugMode)
|
|
||||||
{
|
|
||||||
LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info);
|
|
||||||
int fps = (int)(iterationCount * 1000 / totalTime);
|
|
||||||
LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info);
|
|
||||||
iterationCount = 0;
|
|
||||||
totalTime = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.MenuKey) < 0)
|
|
||||||
{
|
|
||||||
var now = DateTime.Now;
|
|
||||||
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
|
||||||
{
|
|
||||||
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
|
|
||||||
lastMenuToggle = now;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (mainConfig.Data.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
Cv2.WaitKey(1);
|
|
||||||
}
|
|
||||||
else if (!mainConfig.Data.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
if (Cv2.GetWindowProperty("Spectrum Detection", WindowPropertyFlags.Visible) >= 0)
|
|
||||||
{
|
|
||||||
Cv2.DestroyAllWindows();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
|
||||||
{
|
|
||||||
var contourRects = new List<(Rect rect, List<int> indices)>();
|
|
||||||
for (int i = 0; i < contours.Length; i++)
|
|
||||||
{
|
|
||||||
var rect = Cv2.BoundingRect(contours[i]);
|
|
||||||
contourRects.Add((rect, new List<int> { i }));
|
|
||||||
}
|
|
||||||
bool merged;
|
|
||||||
do
|
|
||||||
{
|
|
||||||
merged = false;
|
|
||||||
for (int i = 0; i < contourRects.Count; i++)
|
|
||||||
{
|
|
||||||
var (rectA, indicesA) = contourRects[i];
|
|
||||||
for (int j = i + 1; j < contourRects.Count; j++)
|
|
||||||
{
|
|
||||||
var (rectB, indicesB) = contourRects[j];
|
|
||||||
if (rectA.IntersectsWith(rectB))
|
|
||||||
{
|
|
||||||
var newRect = new Rect(
|
|
||||||
Math.Min(rectA.X, rectB.X),
|
|
||||||
Math.Min(rectA.Y, rectB.Y),
|
|
||||||
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
|
||||||
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
|
||||||
);
|
|
||||||
var newIndices = new List<int>();
|
|
||||||
newIndices.AddRange(indicesA);
|
|
||||||
newIndices.AddRange(indicesB);
|
|
||||||
contourRects[i] = (newRect, newIndices);
|
|
||||||
contourRects.RemoveAt(j);
|
|
||||||
merged = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (merged) break;
|
|
||||||
}
|
|
||||||
} while (merged);
|
|
||||||
|
|
||||||
var mergedContours = new List<OpenCvSharp.Point[]>();
|
|
||||||
foreach (var (rect, indices) in contourRects)
|
|
||||||
{
|
|
||||||
var points = new List<OpenCvSharp.Point>();
|
|
||||||
foreach (var idx in indices)
|
|
||||||
{
|
|
||||||
points.AddRange(contours[idx]);
|
|
||||||
}
|
|
||||||
var hull = Cv2.ConvexHull(points);
|
|
||||||
mergedContours.Add(hull);
|
|
||||||
}
|
|
||||||
return mergedContours.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
static OpenCvSharp.Point[] ShrinkWideContour(OpenCvSharp.Point[] contour)
|
|
||||||
{
|
|
||||||
var rect = Cv2.BoundingRect(contour);
|
|
||||||
double aspect = rect.Width / (double)rect.Height;
|
|
||||||
if (aspect <= 1.2)
|
|
||||||
return contour;
|
|
||||||
|
|
||||||
int[] xs = contour.Select(p => p.X).ToArray();
|
|
||||||
int minX = xs.Min();
|
|
||||||
int maxX = xs.Max();
|
|
||||||
|
|
||||||
int binCount = Math.Max(10, (maxX - minX + 1) / 5);
|
|
||||||
int[] bins = new int[binCount];
|
|
||||||
int binWidth = (int)Math.Ceiling((maxX - minX + 1) / (double)binCount);
|
|
||||||
|
|
||||||
foreach (var pt in contour)
|
|
||||||
{
|
|
||||||
int binIdx = (pt.X - minX) / binWidth;
|
|
||||||
if (binIdx < 0) binIdx = 0;
|
|
||||||
if (binIdx >= binCount) binIdx = binCount - 1;
|
|
||||||
bins[binIdx]++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int maxMass = bins.Max();
|
detectionManager = new DetectionManager(renderer);
|
||||||
int left = 0, right = binCount - 1;
|
|
||||||
for (int i = 0; i < binCount; i++)
|
|
||||||
{
|
|
||||||
if (bins[i] == maxMass)
|
|
||||||
{
|
|
||||||
left = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (int i = binCount - 1; i >= 0; i--)
|
|
||||||
{
|
|
||||||
if (bins[i] == maxMass)
|
|
||||||
{
|
|
||||||
right = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
int cropMinX = minX + left * binWidth;
|
|
||||||
int cropMaxX = minX + (right + 1) * binWidth - 1;
|
|
||||||
|
|
||||||
var shrunken = contour.Where(p => p.X >= cropMinX && p.X <= cropMaxX).ToArray();
|
|
||||||
if (shrunken.Length < 3)
|
|
||||||
return contour;
|
|
||||||
|
|
||||||
return Cv2.ConvexHull(shrunken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Bitmap CaptureScreenshot(Rectangle bounds)
|
|
||||||
{
|
|
||||||
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
|
||||||
using (Graphics g = Graphics.FromImage(bitmap))
|
|
||||||
{
|
|
||||||
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
|
|
||||||
}
|
|
||||||
return bitmap;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public static class SystemHelper
|
public static class SystemHelper
|
||||||
|
|||||||
+794
-312
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,9 @@
|
|||||||
<PublishAot>False</PublishAot>
|
<PublishAot>False</PublishAot>
|
||||||
<InvariantGlobalization>true</InvariantGlobalization>
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
<UseWindowsForms>True</UseWindowsForms>
|
<UseWindowsForms>True</UseWindowsForms>
|
||||||
|
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||||
|
<TargetFrameworks></TargetFrameworks>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -24,6 +27,7 @@
|
|||||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||||
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
|
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
|
||||||
|
<PackageReference Include="System.IO.Ports" Version="9.0.8" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -7,13 +7,19 @@ EndProject
|
|||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Debug|x64 = Debug|x64
|
||||||
Release|Any CPU = Release|Any CPU
|
Release|Any CPU = Release|Any CPU
|
||||||
|
Release|x64 = Release|x64
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.ActiveCfg = Debug|x64
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.Build.0 = Debug|x64
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.ActiveCfg = Release|x64
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.Build.0 = Release|x64
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
Reference in New Issue
Block a user