mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7604998d6
|
||
|
|
e08e971bf9
|
||
|
|
2deaca09b0 | ||
|
|
e7c5c4fff6
|
||
|
|
4225aeda33
|
@@ -1,6 +1,6 @@
|
||||
# Spectrum
|
||||
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
||||
<img width="700" height="603" alt="Spectrum Menu" src="https://upld.zip/PYRXWN5Y.png" />
|
||||
<img width="702" height="501" alt="1777422570-4729-HeHpx7" src="https://github.com/user-attachments/assets/9d3f8e29-b38c-4ebe-8818-e38f38c45324" />
|
||||
## Features
|
||||
- Extensive configuration file
|
||||
- Dataset collection
|
||||
@@ -9,7 +9,7 @@ Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processi
|
||||
- FOV Overlay
|
||||
- Detection Overlay
|
||||
- Triggerbot
|
||||
- Makcu Support
|
||||
- ~~Makcu Support~~ (Being reworked)
|
||||
|
||||
## Dataset Collection
|
||||
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
|
||||
|
||||
+8
-2
@@ -1,20 +1,26 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36203.30 d17.14
|
||||
# Visual Studio Version 18
|
||||
VisualStudioVersion = 18.3.11415.281 d18.3
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spectrum", "Spectrum\Spectrum.csproj", "{96A01B58-894F-4DFB-97D9-49563FD4BB75}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|x64.Build.0 = Debug|x64
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|x64.ActiveCfg = Release|x64
|
||||
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
+28
-14
@@ -57,6 +57,12 @@ namespace Spectrum
|
||||
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
|
||||
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
|
||||
_currentFilePath = filename;
|
||||
|
||||
if (_data is ConfigData configData)
|
||||
Program.InputLibraryManager?.Switch(configData.InputLibraryType);
|
||||
|
||||
LogManager.Log($"Loaded config: {filename}", LogLevel.Info);
|
||||
LogManager.Log($"Initialized Input Library: {Program.InputLibraryManager?.CurrentType}", LogLevel.Info);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -496,11 +502,13 @@ namespace Spectrum
|
||||
PerlinNoise,
|
||||
WindMouse
|
||||
}
|
||||
public enum MovementMethod
|
||||
public enum InputLibraryType
|
||||
{
|
||||
MouseEvent,
|
||||
Arduino,
|
||||
HID
|
||||
HID,
|
||||
MakcuBinary,
|
||||
MakcuLegacy
|
||||
}
|
||||
public enum FovType
|
||||
{
|
||||
@@ -531,7 +539,6 @@ namespace Spectrum
|
||||
#region Image Settings
|
||||
public int ImageWidth { get; set; } = 640;
|
||||
public int ImageHeight { get; set; } = 640;
|
||||
public int Threshold { get; set; } = 200;
|
||||
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||
#endregion
|
||||
|
||||
@@ -546,14 +553,19 @@ namespace Spectrum
|
||||
|
||||
#region Aim Settings
|
||||
public bool EnableAim { get; set; } = true;
|
||||
public bool ClosestToMouse { get; set; } = true;
|
||||
public bool ClosestToMouse { get; set; } = false;
|
||||
public Keybind Keybind = new(Keys.XButton2, KeybindType.Hold);
|
||||
public bool EnableAimFov { get; set; } = false;
|
||||
public int AimFovHeight { get; set; } = 200; // pixels
|
||||
public int AimFovWidth { get; set; } = 200; // pixels
|
||||
public FovType AimFovType { get; set; } = FovType.Rectangle;
|
||||
public Vector4 AimFovColor { get; set; } = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
|
||||
public double Sensitivity { get; set; } = 0.5;
|
||||
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
|
||||
public bool EmaSmoothening { get; set; } = true;
|
||||
public double EmaSmootheningFactor { get; set; } = 0.1;
|
||||
public bool EmaSmoothening { get; set; } = false;
|
||||
public double EmaSmootheningFactor { get; set; } = 0.5;
|
||||
|
||||
public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
||||
public InputLibraryType InputLibraryType { get; set; } = InputLibraryType.MouseEvent;
|
||||
|
||||
public double WindMouseGravity { get; set; } = 9.0;
|
||||
public double WindMouseWind { get; set; } = 3.0;
|
||||
@@ -576,16 +588,17 @@ namespace Spectrum
|
||||
#endregion
|
||||
|
||||
#region Display Settings
|
||||
public bool DrawDetections { get; set; } = true;
|
||||
public bool DrawDetections { get; set; } = false;
|
||||
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||
public bool HighlightTarget { get; set; } = false;
|
||||
public Vector4 TargetColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
public bool ShowMenu { get; set; } = true;
|
||||
public Keys MenuKey { get; set; } = Keys.Insert;
|
||||
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 bool DrawAimPoint { get; set; } = true;
|
||||
public bool DrawCaptureFov { get; set; } = false;
|
||||
public bool DrawAimFov { get; set; } = false;
|
||||
public FovType CaptureFOVType { get; set; } = FovType.Rectangle;
|
||||
public Vector4 CaptureFOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||
public bool DrawAimPoint { get; set; } = false;
|
||||
public Vector4 AimPointColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
public AimpointType AimPointType { get; set; } = AimpointType.Dot;
|
||||
#endregion
|
||||
@@ -597,16 +610,17 @@ namespace Spectrum
|
||||
public int LabeledImageInterval { get; set; } = 5;
|
||||
#endregion
|
||||
|
||||
#region Color Settings
|
||||
#region Detection Settings
|
||||
public Scalar UpperHSV { get; set; } = new Scalar(179, 255, 255);
|
||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 255);
|
||||
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||
public int MinAreaPx { get; set; } = 100;
|
||||
#endregion
|
||||
|
||||
#region Misc
|
||||
public bool DebugMode { get; set; } = false;
|
||||
public bool AntiCapture { get; set; } = false;
|
||||
public int MinAreaPx { get; set; } = 100;
|
||||
|
||||
#endregion
|
||||
}
|
||||
public class ColorInfo(string name, Scalar upper, Scalar lower)
|
||||
|
||||
@@ -19,12 +19,12 @@ namespace Spectrum.Detection
|
||||
private static readonly 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(List<OpenCvSharp.Point[]> contours, int imageWidth, int imageHeight)
|
||||
{
|
||||
var boundingBoxes = new List<YoloBoundingBox>();
|
||||
foreach (var contour in contours)
|
||||
{
|
||||
if (contour.Length < 3) continue; // probably not an actual enemy
|
||||
if (contour.Length < 4) continue; // we need 4 points to make a bounding box
|
||||
int minX = contour.Min(p => p.X);
|
||||
int minY = contour.Min(p => p.Y);
|
||||
int maxX = contour.Max(p => p.X);
|
||||
@@ -114,9 +114,9 @@ namespace Spectrum.Detection
|
||||
}
|
||||
|
||||
|
||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||
public static void AddToQueue(Mat mat, Rectangle bounds, List<OpenCvSharp.Point[]> filteredContours)
|
||||
{
|
||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||
if (!mainConfig.Data.AutoLabel || filteredContours.Count == 0)
|
||||
return;
|
||||
|
||||
labeledImageAttempts++;
|
||||
@@ -256,7 +256,7 @@ namespace Spectrum.Detection
|
||||
{
|
||||
public Mat Mat { get; set; } = null!;
|
||||
public Rectangle Bounds { get; set; }
|
||||
public OpenCvSharp.Point[][] FilteredContours { get; set; } = null!;
|
||||
public List<OpenCvSharp.Point[]> FilteredContours { get; set; } = null!;
|
||||
}
|
||||
public class BackgroundImageData
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using Spectrum.Input;
|
||||
using Spectrum.Utilities;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
@@ -43,14 +44,13 @@ namespace Spectrum.Detection
|
||||
var config = mainConfig.Data;
|
||||
try
|
||||
{
|
||||
if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && !config.ShowMenu)
|
||||
if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && (!config.ShowMenu || config.DebugMode))
|
||||
{
|
||||
if (config.DebugMode)
|
||||
stopwatch.Restart();
|
||||
|
||||
var t0 = Stopwatch.GetTimestamp();
|
||||
renderer?.ClearDetectionDrawCommands();
|
||||
AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0);
|
||||
|
||||
if (!config.ClosestToMouse)
|
||||
{
|
||||
@@ -100,14 +100,13 @@ namespace Spectrum.Detection
|
||||
_captureManager.Dispose();
|
||||
screenshot = CaptureManager.CaptureScreenshotGdi(bounds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
AddTiming("Screen Capture", Stopwatch.GetTimestamp() - tCapture);
|
||||
|
||||
if (screenshot == null)
|
||||
{
|
||||
LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug);
|
||||
Thread.Sleep(2);
|
||||
continue;
|
||||
}
|
||||
|
||||
var tMat = Stopwatch.GetTimestamp();
|
||||
Mat mat = ConvertBitmapToMat(screenshot);
|
||||
@@ -128,80 +127,65 @@ namespace Spectrum.Detection
|
||||
Cv2.Dilate(maskBuffer!, maskBuffer!, null, iterations: 2);
|
||||
AddTiming("Dilation", Stopwatch.GetTimestamp() - tDilate);
|
||||
|
||||
var tThresh = Stopwatch.GetTimestamp();
|
||||
Cv2.Threshold(maskBuffer!, maskBuffer!, 127, 255, ThresholdTypes.Binary);
|
||||
AddTiming("Thresholding", Stopwatch.GetTimestamp() - tThresh);
|
||||
|
||||
var tContours = Stopwatch.GetTimestamp();
|
||||
Cv2.FindContours(maskBuffer!, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||
AddTiming("Find Contours", Stopwatch.GetTimestamp() - tContours);
|
||||
|
||||
var tFilter = Stopwatch.GetTimestamp();
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= config.MinAreaPx).ToArray();
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= config.MinAreaPx).ToList();
|
||||
AddTiming("Filter Contours", Stopwatch.GetTimestamp() - tFilter);
|
||||
|
||||
var tMerge = Stopwatch.GetTimestamp();
|
||||
var processedContours = MergeOverlappingContours(filteredContours);
|
||||
AddTiming("Merge Contours", Stopwatch.GetTimestamp() - tMerge);
|
||||
|
||||
if (processedContours.Length > 0)
|
||||
if (processedContours.Count > 0)
|
||||
{
|
||||
int refX = bounds.X + bounds.Width / 2;
|
||||
int refY = bounds.Y + (int)(bounds.Height * config.YOffsetPercent);
|
||||
double refX = bounds.X + bounds.Width * 0.5;
|
||||
double refY = bounds.Y + bounds.Height * 0.5;
|
||||
|
||||
double minDistSquared = double.MaxValue;
|
||||
OpenCvSharp.Point[]? closestContour = null;
|
||||
Rect bestRect = default;
|
||||
|
||||
bool shouldDrawDetections = config.DrawDetections && renderer != null;
|
||||
|
||||
var tProcess = Stopwatch.GetTimestamp();
|
||||
|
||||
foreach (var contour in processedContours)
|
||||
{
|
||||
var rect = Cv2.BoundingRect(contour);
|
||||
|
||||
int centerX = rect.X + rect.Width / 2;
|
||||
int centerY = rect.Y + rect.Height / 2;
|
||||
var m = Cv2.Moments(contour);
|
||||
if (m.M00 == 0)
|
||||
continue;
|
||||
|
||||
int absCenterX = centerX + bounds.X;
|
||||
int absCenterY = centerY + bounds.Y;
|
||||
double centerX = m.M10 / m.M00;
|
||||
double centerY = m.M01 / m.M00;
|
||||
|
||||
double distSquared = (absCenterX - refX) * (absCenterX - refX) +
|
||||
(absCenterY - refY) * (absCenterY - refY);
|
||||
double absCenterX = centerX + bounds.X;
|
||||
double absCenterY = centerY + bounds.Y;
|
||||
|
||||
double dx = absCenterX - refX;
|
||||
double dy = absCenterY - refY;
|
||||
double distSquared = dx * dx + dy * dy;
|
||||
|
||||
if (distSquared < minDistSquared)
|
||||
{
|
||||
minDistSquared = distSquared;
|
||||
closestContour = contour;
|
||||
bestRect = rect;
|
||||
}
|
||||
|
||||
if (shouldDrawDetections)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
rect.X + bounds.X,
|
||||
rect.Y + bounds.Y,
|
||||
rect.Width,
|
||||
rect.Height
|
||||
);
|
||||
renderer!.AddRect(_rect, config.DetectionColor, 1.0f);
|
||||
}
|
||||
renderer!.AddRect(rect, config.DetectionColor, 1.0f, bounds);
|
||||
}
|
||||
|
||||
AddTiming("Process Contours", Stopwatch.GetTimestamp() - tProcess);
|
||||
|
||||
if (closestContour != null)
|
||||
if (bestRect != default)
|
||||
{
|
||||
|
||||
if (shouldDrawDetections && config.HighlightTarget)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
bestRect.X + bounds.X,
|
||||
bestRect.Y + bounds.Y,
|
||||
bestRect.Width,
|
||||
bestRect.Height
|
||||
);
|
||||
renderer!.AddRect(_rect, config.TargetColor, 1.0f);
|
||||
}
|
||||
renderer!.AddRect(bestRect, config.TargetColor, 1.0f, bounds);
|
||||
|
||||
int groupX;
|
||||
int groupY;
|
||||
@@ -221,17 +205,17 @@ namespace Spectrum.Detection
|
||||
{
|
||||
if (config.AimPointType == AimpointType.Crosshair)
|
||||
{
|
||||
renderer!.AddLine(new System.Numerics.Vector2(targetX - 10, targetY), new System.Numerics.Vector2(targetX + 10, targetY), config.AimPointColor, 2);
|
||||
renderer!.AddLine(new System.Numerics.Vector2(targetX, targetY - 10), new System.Numerics.Vector2(targetX, targetY + 10), config.AimPointColor, 2);
|
||||
renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||
renderer!.AddLine(new Vector2(targetX - 10, targetY), new Vector2(targetX + 10, targetY), config.AimPointColor, 2);
|
||||
renderer!.AddLine(new Vector2(targetX, targetY - 10), new Vector2(targetX, targetY + 10), config.AimPointColor, 2);
|
||||
renderer!.AddCircle(new Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||
}
|
||||
else if (config.AimPointType == AimpointType.Dot)
|
||||
{
|
||||
renderer!.AddCircleFilled(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||
renderer!.AddCircleFilled(new Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||
}
|
||||
else if (config.AimPointType == AimpointType.Circle)
|
||||
{
|
||||
renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 10, config.AimPointColor, 20);
|
||||
renderer!.AddCircle(new Vector2(targetX, targetY), 10, config.AimPointColor, 20);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,10 +242,12 @@ namespace Spectrum.Detection
|
||||
InputManager.MoveMouse();
|
||||
AddTiming("Mouse Movement", Stopwatch.GetTimestamp() - tMove);
|
||||
}
|
||||
if (config.TriggerBot)
|
||||
|
||||
if (config.TriggerBot && config.TriggerKeybind.Key != Keys.None && InputManager.IsKeyOrMouseDown(config.TriggerKeybind))
|
||||
{
|
||||
var _ = InputManager.ClickMouse();
|
||||
}
|
||||
|
||||
if (renderer != null && config.DrawTriggerFov && config.TriggerBot && !config.TriggerInBoundsOnly)
|
||||
{
|
||||
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100);
|
||||
@@ -286,13 +272,24 @@ namespace Spectrum.Detection
|
||||
stopwatch.Stop();
|
||||
AddTiming("Frame", stopwatch.ElapsedTicks);
|
||||
}
|
||||
if (Program.Timings.GetCount(["Frame"]) >= 10000)
|
||||
{
|
||||
LogManager.Log("---- Timing Summary ----", LogManager.LogLevel.Info);
|
||||
foreach (var timing in Program.Timings.GetSnapshot())
|
||||
{
|
||||
LogManager.Log($"{timing.Name}: Avg = {TimingStats.FormatDuration(timing.AverageTicks)} over {timing.Count} samples", LogManager.LogLevel.Info);
|
||||
}
|
||||
var frameTimings = Program.Timings.GetSnapshot(["Frame"]);
|
||||
LogManager.Log($"Total Overall: Avg = {TimingStats.FormatDuration(frameTimings[0].AverageTicks)} over {frameTimings[0].Count} samples", LogManager.LogLevel.Info);
|
||||
LogManager.Log("------------------------", LogManager.LogLevel.Info);
|
||||
Program.Timings.Clear();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
renderer?.ClearDetectionDrawCommands();
|
||||
renderer?.CommitDetectionDrawCommands();
|
||||
MovementPaths.ResetWindMouse();
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
if (InputManager.IsKeyOrMouseDown(config.MenuKey))
|
||||
{
|
||||
@@ -311,47 +308,39 @@ namespace Spectrum.Detection
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
finally
|
||||
}
|
||||
}
|
||||
|
||||
static List<OpenCvSharp.Point[]> MergeOverlappingContours(List<OpenCvSharp.Point[]> contours)
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||
{
|
||||
if (contours.Length <= 1)
|
||||
if (contours.Count <= 1)
|
||||
return contours;
|
||||
|
||||
var contourRects = new List<(Rect rect, List<int> indices)>(contours.Length);
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
var rect = Cv2.BoundingRect(contours[i]);
|
||||
contourRects.Add((rect, new List<int> { i }));
|
||||
}
|
||||
|
||||
var items = contours.Select(c => (Rect: Cv2.BoundingRect(c), Points: c.ToList())).ToList();
|
||||
bool merged;
|
||||
|
||||
do
|
||||
{
|
||||
merged = false;
|
||||
for (int i = 0; i < contourRects.Count - 1; i++)
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
var (rectA, indicesA) = contourRects[i];
|
||||
for (int j = i + 1; j < contourRects.Count; j++)
|
||||
for (int j = i + 1; j < items.Count; j++)
|
||||
{
|
||||
var (rectB, indicesB) = contourRects[j];
|
||||
if (rectA.IntersectsWith(rectB))
|
||||
if (items[i].Rect.IntersectsWith(items[j].Rect))
|
||||
{
|
||||
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 r1 = items[i].Rect;
|
||||
var r2 = items[j].Rect;
|
||||
var combinedRect = new Rect(
|
||||
Math.Min(r1.X, r2.X),
|
||||
Math.Min(r1.Y, r2.Y),
|
||||
Math.Max(r1.Right, r2.Right) - Math.Min(r1.X, r2.X),
|
||||
Math.Max(r1.Bottom, r2.Bottom) - Math.Min(r1.Y, r2.Y)
|
||||
);
|
||||
indicesA.AddRange(indicesB);
|
||||
contourRects[i] = (newRect, indicesA);
|
||||
contourRects.RemoveAt(j);
|
||||
|
||||
items[i].Points.AddRange(items[j].Points);
|
||||
items[i] = (combinedRect, items[i].Points);
|
||||
items.RemoveAt(j);
|
||||
merged = true;
|
||||
break;
|
||||
}
|
||||
@@ -360,18 +349,7 @@ namespace Spectrum.Detection
|
||||
}
|
||||
} while (merged);
|
||||
|
||||
var mergedContours = new List<OpenCvSharp.Point[]>(contourRects.Count);
|
||||
foreach (var (_, indices) in contourRects)
|
||||
{
|
||||
var pointsList = new List<OpenCvSharp.Point>(indices.Count * 10);
|
||||
foreach (var idx in indices)
|
||||
{
|
||||
pointsList.AddRange(contours[idx]);
|
||||
}
|
||||
var hull = Cv2.ConvexHull(pointsList);
|
||||
mergedContours.Add(hull);
|
||||
}
|
||||
return [.. mergedContours];
|
||||
return items.Select(x => Cv2.ConvexHull(x.Points)).ToList();
|
||||
}
|
||||
|
||||
private void EnsureBuffers(OpenCvSharp.Size size)
|
||||
@@ -403,17 +381,8 @@ namespace Spectrum.Detection
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
byte* src = (byte*)bmpData.Scan0;
|
||||
byte* dst = bgrBuffer!.DataPointer;
|
||||
int srcStride = bmpData.Stride;
|
||||
int dstStride = (int)bgrBuffer.Step();
|
||||
int rowBytes = bitmap.Width * 4;
|
||||
for (int y = 0; y < bitmap.Height; y++)
|
||||
{
|
||||
Buffer.MemoryCopy(src, dst, rowBytes, rowBytes);
|
||||
src += srcStride;
|
||||
dst += dstStride;
|
||||
}
|
||||
long bytesToCopy = (long)bmpData.Stride * bitmap.Height;
|
||||
Buffer.MemoryCopy((void*)bmpData.Scan0, (void*)bgrBuffer.DataPointer, bytesToCopy, bytesToCopy);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -421,7 +390,7 @@ namespace Spectrum.Detection
|
||||
bitmap.UnlockBits(bmpData);
|
||||
}
|
||||
|
||||
return bgrBuffer!;
|
||||
return bgrBuffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,21 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.Arduino
|
||||
{
|
||||
class ArduinoMain
|
||||
internal class ArduinoMain : IInputLibrary, IDisposable
|
||||
{
|
||||
private static readonly byte PingCommand = 0x02;
|
||||
private static readonly byte PingResponse = 0xAA;
|
||||
private const int BaudRate = 115200;
|
||||
private const int HandshakeTimeoutMs = 1500;
|
||||
private const int OpenResetDelayMs = 1200;
|
||||
private static SerialPort? serial;
|
||||
private static readonly object sync = new();
|
||||
private SerialPort? serial;
|
||||
private readonly object sync = new();
|
||||
|
||||
public static bool Load()
|
||||
public static ArduinoMain Instance { get; } = new ArduinoMain();
|
||||
|
||||
public bool RequiresInitialization => true;
|
||||
public bool IsConnected => serial != null && serial.IsOpen;
|
||||
public bool Initialize()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
@@ -106,7 +110,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void Close()
|
||||
public void Dispose()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
@@ -130,7 +134,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
|
||||
}
|
||||
}
|
||||
|
||||
public static void Move(int x, int y)
|
||||
public void Move(int x, int y)
|
||||
{
|
||||
SerialPort? sp;
|
||||
lock (sync) sp = serial;
|
||||
@@ -158,17 +162,17 @@ namespace Spectrum.Input.InputLibraries.Arduino
|
||||
y -= stepY;
|
||||
}
|
||||
}
|
||||
public static void ClickDown(int button = 0x03)
|
||||
public void Press(int button)
|
||||
{
|
||||
SendClick(button, true);
|
||||
SendMappedClick(button, true);
|
||||
}
|
||||
|
||||
public static void ClickUp(int button = 0x03)
|
||||
public void Release(int button)
|
||||
{
|
||||
SendClick(button, false);
|
||||
SendMappedClick(button, false);
|
||||
}
|
||||
|
||||
private static void SendClick(int buttonBase, bool expectDown)
|
||||
private void SendClick(int buttonBase, bool expectDown)
|
||||
{
|
||||
SerialPort? sp;
|
||||
lock (sync) sp = serial;
|
||||
@@ -188,5 +192,18 @@ namespace Spectrum.Input.InputLibraries.Arduino
|
||||
LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendMappedClick(int button, bool isDown)
|
||||
{
|
||||
int mapped = button switch
|
||||
{
|
||||
0x01 => 0x03,
|
||||
0x02 => 0x05,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
if (mapped == 0) return;
|
||||
SendClick(mapped, isDown);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.HID
|
||||
{
|
||||
internal class HIDMain(int? vid = null, int? pid = null)
|
||||
internal class HIDMain(int? vid = null, int? pid = null) : IInputLibrary, IDisposable
|
||||
{
|
||||
readonly int[] ExpectedVIDs =
|
||||
[
|
||||
@@ -39,6 +39,90 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
HidDevice? device;
|
||||
HidStream? stream;
|
||||
private readonly object _syncLock = new();
|
||||
public static HIDMain Instance { get; } = new();
|
||||
|
||||
public bool RequiresInitialization => true;
|
||||
public bool IsConnected => stream != null && device != null;
|
||||
public bool Initialize()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
if (stream != null && device != null)
|
||||
{
|
||||
LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug);
|
||||
var candidates = FindDevice().ToList();
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var dev in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug);
|
||||
|
||||
if (dev.TryOpen(out stream))
|
||||
{
|
||||
if (TestDeviceWithPing(dev, stream))
|
||||
{
|
||||
device = dev;
|
||||
vid = dev.VendorID;
|
||||
pid = dev.ProductID;
|
||||
LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info);
|
||||
return true;
|
||||
}
|
||||
LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug);
|
||||
stream.Close();
|
||||
stream.Dispose();
|
||||
stream = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug);
|
||||
stream?.Close();
|
||||
stream?.Dispose();
|
||||
stream = null;
|
||||
}
|
||||
}
|
||||
|
||||
LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
stream?.Close();
|
||||
stream?.Dispose();
|
||||
LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stream = null;
|
||||
device = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerable<HidDevice> FindDevice()
|
||||
{
|
||||
@@ -153,67 +237,6 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Init()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
if (stream != null && device != null)
|
||||
{
|
||||
LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug);
|
||||
var candidates = FindDevice().ToList();
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var dev in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug);
|
||||
|
||||
if (dev.TryOpen(out stream))
|
||||
{
|
||||
if (TestDeviceWithPing(dev, stream))
|
||||
{
|
||||
device = dev;
|
||||
vid = dev.VendorID;
|
||||
pid = dev.ProductID;
|
||||
LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug);
|
||||
stream.Close();
|
||||
stream.Dispose();
|
||||
stream = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug);
|
||||
stream?.Close();
|
||||
stream?.Dispose();
|
||||
stream = null;
|
||||
}
|
||||
}
|
||||
|
||||
LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool SendFeatureReport(byte[] data)
|
||||
{
|
||||
@@ -245,7 +268,7 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
}
|
||||
}
|
||||
|
||||
public bool Move(int x, int y)
|
||||
public void Move(int x, int y)
|
||||
{
|
||||
x = Math.Clamp(x, -127, 127);
|
||||
y = Math.Clamp(y, -127, 127);
|
||||
@@ -254,9 +277,7 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
byte yByte = unchecked((byte)y);
|
||||
|
||||
byte[] data = [CMD_MOVE, xByte, yByte];
|
||||
bool success = SendFeatureReport(data);
|
||||
|
||||
return success;
|
||||
SendFeatureReport(data);
|
||||
}
|
||||
|
||||
public bool Click(byte button)
|
||||
@@ -267,20 +288,16 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
return success;
|
||||
}
|
||||
|
||||
public bool Press(byte button)
|
||||
public void Press(int button)
|
||||
{
|
||||
byte[] data = [CMD_PRESS, button];
|
||||
bool success = SendFeatureReport(data);
|
||||
|
||||
return success;
|
||||
byte[] data = [CMD_PRESS, (byte)button];
|
||||
SendFeatureReport(data);
|
||||
}
|
||||
|
||||
public bool Release(byte button)
|
||||
public void Release(int button)
|
||||
{
|
||||
byte[] data = [CMD_RELEASE, button];
|
||||
bool success = SendFeatureReport(data);
|
||||
|
||||
return success;
|
||||
byte[] data = [CMD_RELEASE, (byte)button];
|
||||
SendFeatureReport(data);
|
||||
}
|
||||
|
||||
public bool Scroll(int amount)
|
||||
@@ -294,28 +311,6 @@ namespace Spectrum.Input.InputLibraries.HID
|
||||
return success;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
stream?.Close();
|
||||
stream?.Dispose();
|
||||
LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stream = null;
|
||||
device = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsConnected => stream != null && device != null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Spectrum.Input.InputLibraries
|
||||
{
|
||||
public interface IInputLibrary
|
||||
{
|
||||
bool RequiresInitialization { get; }
|
||||
bool IsConnected { get; }
|
||||
bool Initialize();
|
||||
void Dispose();
|
||||
void Move(int x, int y);
|
||||
void Press(int button);
|
||||
void Release(int button);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
|
||||
|
||||
namespace Spectrum.Input.InputLibraries
|
||||
{
|
||||
internal sealed class InputLibraryManager
|
||||
{
|
||||
private IInputLibrary? _current;
|
||||
private InputLibraryType _currentType = InputLibraryType.MouseEvent;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public InputLibraryType CurrentType => _currentType;
|
||||
public IInputLibrary? Current => _current;
|
||||
|
||||
public bool Switch(InputLibraryType type)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_currentType == type)
|
||||
return true;
|
||||
|
||||
_current?.Dispose();
|
||||
_current = null;
|
||||
_currentType = InputLibraryType.MouseEvent;
|
||||
|
||||
_current = type switch
|
||||
{
|
||||
InputLibraryType.HID => HID.HIDMain.Instance,
|
||||
InputLibraryType.Arduino => Arduino.ArduinoMain.Instance,
|
||||
InputLibraryType.MouseEvent => MouseEvent.MouseMain.Instance,
|
||||
InputLibraryType.MakcuBinary => MakcuBinary.MakcuBinaryMain.Instance,
|
||||
InputLibraryType.MakcuLegacy => MakcuLegacy.MakcuLegacyMain.Instance,
|
||||
_ => MouseEvent.MouseMain.Instance,
|
||||
};
|
||||
|
||||
if (_current == null)
|
||||
return true;
|
||||
|
||||
if (_current.RequiresInitialization && !_current.Initialize())
|
||||
{
|
||||
_current.Dispose();
|
||||
_current = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_currentType = type;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_current?.Dispose();
|
||||
_current = null;
|
||||
_currentType = InputLibraryType.MouseEvent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using Spectrum.Utilities;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.MakcuBinary
|
||||
{
|
||||
internal class MakcuBinaryMain : IInputLibrary, IDisposable
|
||||
{
|
||||
#region Frame Constants
|
||||
private const byte FrameStart = 0x50;
|
||||
private const byte CmdMove = 0x0D;
|
||||
private const byte CmdButtonsStream = 0x02;
|
||||
private const byte CmdLeft = 0x08;
|
||||
private const byte CmdRight = 0x11;
|
||||
private const byte CmdMiddle = 0x0A;
|
||||
private const byte CmdSide1 = 0x12;
|
||||
private const byte CmdSide2 = 0x13;
|
||||
private const byte CmdVersion = 0xBF;
|
||||
#endregion
|
||||
#region Serial Constants
|
||||
private const int BaudRate = 115200;
|
||||
private const int ReadTimeoutMs = 150;
|
||||
private const int WriteTimeoutMs = 250;
|
||||
private const int HandshakeTimeoutMs = 1200;
|
||||
private const int OpenResetDelayMs = 200;
|
||||
private const byte StreamModeRaw = 0x01;
|
||||
private const byte StreamPeriodMs = 10;
|
||||
#endregion
|
||||
private SerialPort? serial;
|
||||
private readonly object sync = new();
|
||||
private CancellationTokenSource? readerCts;
|
||||
private Thread? readerThread;
|
||||
public event Action<ushort>? ButtonsChanged;
|
||||
public bool RequiresInitialization => true;
|
||||
public bool IsConnected => serial != null && serial.IsOpen;
|
||||
public static MakcuBinaryMain Instance { get; } = new MakcuBinaryMain();
|
||||
|
||||
private MakcuBinaryMain() { }
|
||||
|
||||
public bool Initialize()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
if (serial != null && serial.IsOpen)
|
||||
return true;
|
||||
|
||||
serial = FindDevice();
|
||||
if (serial == null)
|
||||
{
|
||||
LogManager.Log("MakcuBinary: Failed to connect to device.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
|
||||
StartButtonStreaming();
|
||||
LogManager.Log($"MakcuBinary: Connected on {serial.PortName}.", LogLevel.Info);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
StopButtonStreaming();
|
||||
if (serial != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
serial.Close();
|
||||
serial.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuBinary: Error closing port: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
finally
|
||||
{
|
||||
serial = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Move(int x, int y)
|
||||
{
|
||||
var payload = BuildMovePayload(x, y);
|
||||
SendCommand(CmdMove, payload);
|
||||
}
|
||||
|
||||
public void Press(int button)
|
||||
{
|
||||
SendButtonState(button, 0x01);
|
||||
}
|
||||
|
||||
public void Release(int button)
|
||||
{
|
||||
SendButtonState(button, 0x00);
|
||||
}
|
||||
|
||||
private static byte[] BuildMovePayload(int x, int y)
|
||||
{
|
||||
short dx = (short)Math.Clamp(x, short.MinValue, short.MaxValue);
|
||||
short dy = (short)Math.Clamp(y, short.MinValue, short.MaxValue);
|
||||
var payload = new byte[7];
|
||||
BitConverter.GetBytes(dx).CopyTo(payload, 0);
|
||||
BitConverter.GetBytes(dy).CopyTo(payload, 2);
|
||||
payload[4] = 0x01;
|
||||
payload[5] = 0x00;
|
||||
payload[6] = 0x00;
|
||||
return payload;
|
||||
}
|
||||
|
||||
private void SendButtonState(int button, byte state)
|
||||
{
|
||||
byte cmd = MapButtonCommand(button);
|
||||
if (cmd == 0) return;
|
||||
SendCommand(cmd, new[] { state });
|
||||
}
|
||||
|
||||
private static byte MapButtonCommand(int button)
|
||||
{
|
||||
return button switch
|
||||
{
|
||||
0x01 => CmdLeft,
|
||||
0x02 => CmdRight,
|
||||
0x03 => CmdMiddle,
|
||||
0x04 => CmdSide1,
|
||||
0x05 => CmdSide2,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
|
||||
private bool SendCommand(byte cmd, ReadOnlySpan<byte> payload)
|
||||
{
|
||||
SerialPort? sp;
|
||||
lock (sync) sp = serial;
|
||||
if (sp == null || !sp.IsOpen) return false;
|
||||
|
||||
byte[] frame = new byte[4 + payload.Length];
|
||||
frame[0] = FrameStart;
|
||||
frame[1] = cmd;
|
||||
frame[2] = (byte)(payload.Length & 0xFF);
|
||||
frame[3] = (byte)((payload.Length >> 8) & 0xFF);
|
||||
payload.CopyTo(frame.AsSpan(4));
|
||||
|
||||
try
|
||||
{
|
||||
sp.Write(frame, 0, frame.Length);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuBinary: Write failed: {ex.Message}", LogLevel.Debug);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private SerialPort? FindDevice()
|
||||
{
|
||||
string[] candidates = SerialPort.GetPortNames();
|
||||
if (candidates.Length == 0)
|
||||
LogManager.Log("MakcuBinary: No serial ports detected.", LogLevel.Debug);
|
||||
|
||||
foreach (string portName in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogManager.Log($"MakcuBinary: Probing {portName}...", LogLevel.Debug);
|
||||
var sp = new SerialPort(portName, BaudRate)
|
||||
{
|
||||
ReadTimeout = ReadTimeoutMs,
|
||||
WriteTimeout = WriteTimeoutMs,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true
|
||||
};
|
||||
|
||||
sp.Open();
|
||||
Thread.Sleep(OpenResetDelayMs);
|
||||
sp.DiscardInBuffer();
|
||||
sp.DiscardOutBuffer();
|
||||
|
||||
if (ProbeDevice(sp))
|
||||
return sp;
|
||||
|
||||
sp.Close();
|
||||
sp.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuBinary: Probe failed on {portName}: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool ProbeDevice(SerialPort sp)
|
||||
{
|
||||
LogManager.Log("MakcuBinary: Sending version probe...", LogLevel.Debug);
|
||||
if (!SendCommandOn(sp, CmdVersion, ReadOnlySpan<byte>.Empty))
|
||||
return false;
|
||||
|
||||
if (TryReadFrame(sp, HandshakeTimeoutMs, out byte cmd, out _))
|
||||
{
|
||||
LogManager.Log($"MakcuBinary: Probe response cmd=0x{cmd:X2}.", LogLevel.Debug);
|
||||
return cmd == CmdVersion;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool SendCommandOn(SerialPort sp, byte cmd, ReadOnlySpan<byte> payload)
|
||||
{
|
||||
byte[] frame = new byte[4 + payload.Length];
|
||||
frame[0] = FrameStart;
|
||||
frame[1] = cmd;
|
||||
frame[2] = (byte)(payload.Length & 0xFF);
|
||||
frame[3] = (byte)((payload.Length >> 8) & 0xFF);
|
||||
payload.CopyTo(frame.AsSpan(4));
|
||||
|
||||
try
|
||||
{
|
||||
sp.Write(frame, 0, frame.Length);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadFrame(SerialPort sp, int timeoutMs, out byte cmd, out byte[] payload)
|
||||
{
|
||||
cmd = 0;
|
||||
payload = Array.Empty<byte>();
|
||||
var sw = Stopwatch.StartNew();
|
||||
int b = -1;
|
||||
|
||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out b))
|
||||
continue;
|
||||
if (b == FrameStart)
|
||||
break;
|
||||
}
|
||||
|
||||
if (b != FrameStart) return false;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int cmdVal)) return false;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int lenLo)) return false;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int lenHi)) return false;
|
||||
|
||||
int len = lenLo | (lenHi << 8);
|
||||
if (len < 0) return false;
|
||||
payload = new byte[len];
|
||||
if (!TryReadExact(sp, payload, ReadTimeoutMs)) return false;
|
||||
cmd = (byte)cmdVal;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadExact(SerialPort sp, byte[] buffer, int timeoutMs)
|
||||
{
|
||||
int offset = 0;
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (offset < buffer.Length && sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
int read = sp.Read(buffer, offset, buffer.Length - offset);
|
||||
if (read > 0)
|
||||
offset += read;
|
||||
}
|
||||
catch (TimeoutException) { }
|
||||
}
|
||||
return offset == buffer.Length;
|
||||
}
|
||||
|
||||
private static bool TryReadByte(SerialPort sp, int timeoutMs, out int value)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = sp.ReadByte();
|
||||
if (value >= 0) return true;
|
||||
}
|
||||
catch (TimeoutException) { }
|
||||
}
|
||||
value = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void StartButtonStreaming()
|
||||
{
|
||||
SendCommand(CmdButtonsStream, new[] { StreamModeRaw, StreamPeriodMs });
|
||||
if (readerThread != null) return;
|
||||
LogManager.Log("MakcuBinary: Starting button stream.", LogLevel.Debug);
|
||||
readerCts = new CancellationTokenSource();
|
||||
readerThread = new Thread(() => ReadLoop(readerCts.Token)) { IsBackground = true };
|
||||
readerThread.Start();
|
||||
}
|
||||
|
||||
private void StopButtonStreaming()
|
||||
{
|
||||
if (readerCts == null) return;
|
||||
LogManager.Log("MakcuBinary: Stopping button stream.", LogLevel.Debug);
|
||||
readerCts.Cancel();
|
||||
readerThread?.Join(200);
|
||||
readerThread = null;
|
||||
readerCts.Dispose();
|
||||
readerCts = null;
|
||||
}
|
||||
|
||||
private void ReadLoop(CancellationToken token)
|
||||
{
|
||||
SerialPort? sp;
|
||||
lock (sync) sp = serial;
|
||||
if (sp == null) return;
|
||||
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int b))
|
||||
continue;
|
||||
|
||||
if (b == FrameStart)
|
||||
{
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int cmdVal)) continue;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int lenLo)) continue;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int lenHi)) continue;
|
||||
int len = lenLo | (lenHi << 8);
|
||||
if (len < 0) continue;
|
||||
var payload = new byte[len];
|
||||
if (!TryReadExact(sp, payload, ReadTimeoutMs)) continue;
|
||||
if (cmdVal == CmdButtonsStream && len >= 2)
|
||||
{
|
||||
ushort mask = (ushort)(payload[0] | (payload[1] << 8));
|
||||
LogManager.Log($"MakcuBinary: Buttons mask 0x{mask:X4}.", LogLevel.Debug);
|
||||
ButtonsChanged?.Invoke(mask);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (b == CmdButtonsStream)
|
||||
{
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int lo)) continue;
|
||||
if (!TryReadByte(sp, ReadTimeoutMs, out int hi)) continue;
|
||||
ushort mask = (ushort)(lo | (hi << 8));
|
||||
LogManager.Log($"MakcuBinary: Buttons mask 0x{mask:X4}.", LogLevel.Debug);
|
||||
ButtonsChanged?.Invoke(mask);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using Spectrum.Utilities;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.MakcuLegacy
|
||||
{
|
||||
internal class MakcuLegacyMain : IInputLibrary, IDisposable
|
||||
{
|
||||
private const int BaudRate = 115200;
|
||||
private const int HighBaudRate = 4000000;
|
||||
private const int ReadTimeoutMs = 1000;
|
||||
private const int WriteTimeoutMs = 250;
|
||||
private const int HandshakeTimeoutMs = 3000;
|
||||
private const int OpenResetDelayMs = 200;
|
||||
private const int BaudSwitchDelayMs = 120;
|
||||
private const int PostOpenDelayMs = 200;
|
||||
private SerialPort? serial;
|
||||
private readonly object sync = new();
|
||||
public static MakcuLegacyMain Instance { get; } = new MakcuLegacyMain();
|
||||
public bool RequiresInitialization => true;
|
||||
public bool IsConnected => serial != null && serial.IsOpen;
|
||||
|
||||
private MakcuLegacyMain() { }
|
||||
|
||||
public bool Initialize()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
if (serial != null && serial.IsOpen)
|
||||
return true;
|
||||
|
||||
serial = FindDevice();
|
||||
if (serial == null)
|
||||
{
|
||||
LogManager.Log("MakcuLegacy: Failed to connect to device.", LogLevel.Warning);
|
||||
return false;
|
||||
}
|
||||
|
||||
LogManager.Log($"MakcuLegacy: Connected on {serial.PortName}.", LogLevel.Info);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
if (serial != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
serial.Close();
|
||||
serial.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Error closing port: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
finally
|
||||
{
|
||||
serial = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Move(int x, int y)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Move {x},{y}", LogLevel.Debug);
|
||||
SendCommand($"move({x},{y})");
|
||||
}
|
||||
|
||||
public void Press(int button)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Press {button}", LogLevel.Debug);
|
||||
SendButtonState(button, 1);
|
||||
}
|
||||
|
||||
public void Release(int button)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Release {button}", LogLevel.Debug);
|
||||
SendButtonState(button, 0);
|
||||
}
|
||||
|
||||
private void SendButtonState(int button, int state)
|
||||
{
|
||||
string? cmd = button switch
|
||||
{
|
||||
0x01 => "left",
|
||||
0x02 => "right",
|
||||
0x03 => "middle",
|
||||
0x04 => "side1",
|
||||
0x05 => "side2",
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (cmd == null) return;
|
||||
SendCommand($"{cmd}({state})");
|
||||
}
|
||||
|
||||
private bool SendCommand(string command)
|
||||
{
|
||||
SerialPort? sp;
|
||||
lock (sync) sp = serial;
|
||||
if (sp == null || !sp.IsOpen) return false;
|
||||
|
||||
string payload = NormalizeCommand(command);
|
||||
if (!payload.EndsWith(')'))
|
||||
payload += ")";
|
||||
|
||||
try
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: TX {payload}", LogLevel.Debug);
|
||||
sp.Write(payload + "\r");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Write failed: {ex.Message}", LogLevel.Debug);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static SerialPort? FindDevice()
|
||||
{
|
||||
string[] candidates = SerialPort.GetPortNames();
|
||||
if (candidates.Length == 0)
|
||||
LogManager.Log("MakcuLegacy: No serial ports detected.", LogLevel.Debug);
|
||||
|
||||
foreach (string portName in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Probing {portName}...", LogLevel.Debug);
|
||||
var sp = CreatePort(portName, BaudRate);
|
||||
sp.Open();
|
||||
Thread.Sleep(OpenResetDelayMs);
|
||||
sp.DiscardInBuffer();
|
||||
sp.DiscardOutBuffer();
|
||||
|
||||
if (TryChangeBaud(sp))
|
||||
{
|
||||
Thread.Sleep(PostOpenDelayMs);
|
||||
if (ProbeDevice(sp))
|
||||
return sp;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ProbeDevice(sp))
|
||||
return sp;
|
||||
}
|
||||
|
||||
ClosePort(sp);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Probe failed on {portName}: {ex.Message}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool ProbeDevice(SerialPort sp)
|
||||
{
|
||||
LogManager.Log("MakcuLegacy: Sending version probe...", LogLevel.Debug);
|
||||
if (!SendCommandOn(sp, "version()"))
|
||||
return false;
|
||||
|
||||
return TryReadResponse(sp, "km.MAKCU", HandshakeTimeoutMs);
|
||||
}
|
||||
|
||||
private static bool TryChangeBaud(SerialPort sp)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] frame = BuildBaudFrame(HighBaudRate);
|
||||
sp.Write(frame, 0, frame.Length);
|
||||
sp.BaseStream.Flush();
|
||||
Thread.Sleep(BaudSwitchDelayMs);
|
||||
sp.BaudRate = HighBaudRate;
|
||||
Thread.Sleep(BaudSwitchDelayMs);
|
||||
sp.DiscardInBuffer();
|
||||
sp.DiscardOutBuffer();
|
||||
LogManager.Log($"MakcuLegacy: Baud switched to {HighBaudRate}.", LogLevel.Debug);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: Baud switch failed: {ex.Message}", LogLevel.Debug);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SendCommandOn(SerialPort sp, string command)
|
||||
{
|
||||
string payload = NormalizeCommand(command);
|
||||
if (!payload.EndsWith(")"))
|
||||
payload += ")";
|
||||
|
||||
try
|
||||
{
|
||||
LogManager.Log($"MakcuLegacy: TX {payload}", LogLevel.Debug);
|
||||
sp.Write(payload + "\r");
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadResponse(SerialPort sp, string startsWith, int timeoutMs)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
bool matched = false;
|
||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = sp.ReadLine();
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
continue;
|
||||
|
||||
string trimmed = line.Trim();
|
||||
LogManager.Log($"MakcuLegacy: RX {trimmed}", LogLevel.Debug);
|
||||
if (trimmed.StartsWith(startsWith, StringComparison.OrdinalIgnoreCase))
|
||||
matched = true;
|
||||
if (trimmed.StartsWith(">>>"))
|
||||
{
|
||||
if (matched)
|
||||
return true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
|
||||
private static string NormalizeCommand(string command)
|
||||
{
|
||||
if (command.StartsWith("km.", StringComparison.OrdinalIgnoreCase))
|
||||
return command;
|
||||
if (command.StartsWith(".", StringComparison.Ordinal))
|
||||
return $"km.{command.TrimStart('.')}";
|
||||
return $"km.{command}";
|
||||
}
|
||||
|
||||
private static byte[] BuildBaudFrame(int baudRate)
|
||||
{
|
||||
byte[] frame = new byte[9];
|
||||
frame[0] = 0xDE;
|
||||
frame[1] = 0xAD;
|
||||
frame[2] = 0x05;
|
||||
frame[3] = 0x00;
|
||||
frame[4] = 0xA5;
|
||||
byte[] baudBytes = BitConverter.GetBytes(baudRate);
|
||||
Buffer.BlockCopy(baudBytes, 0, frame, 5, 4);
|
||||
return frame;
|
||||
}
|
||||
|
||||
private static SerialPort CreatePort(string portName, int baudRate)
|
||||
{
|
||||
return new SerialPort(portName, baudRate)
|
||||
{
|
||||
ReadTimeout = ReadTimeoutMs,
|
||||
WriteTimeout = WriteTimeoutMs,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true,
|
||||
NewLine = "\r\n",
|
||||
Encoding = Encoding.ASCII
|
||||
};
|
||||
}
|
||||
|
||||
private static void ClosePort(SerialPort sp)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (sp.IsOpen)
|
||||
sp.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
sp.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,47 @@
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.MouseEvent
|
||||
{
|
||||
public class MouseMain
|
||||
public sealed class MouseMain : IInputLibrary
|
||||
{
|
||||
public static MouseMain Instance { get; } = new MouseMain();
|
||||
private MouseMain() { }
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
public bool RequiresInitialization => false;
|
||||
public bool IsConnected => true;
|
||||
public bool Initialize() { return true; }
|
||||
public void Dispose() { }
|
||||
|
||||
public static void Move(int x, int y)
|
||||
public void Move(int x, int y)
|
||||
{
|
||||
mouse_event(0x0001, (uint)x, (uint)y, 0, 0);
|
||||
}
|
||||
|
||||
public static void ClickDown()
|
||||
public void Press(int button)
|
||||
{
|
||||
mouse_event(0x0002, 0, 0, 0, 0);
|
||||
}
|
||||
public static void ClickUp()
|
||||
uint downFlag = button switch
|
||||
{
|
||||
mouse_event(0x0004, 0, 0, 0, 0);
|
||||
0x01 => 0x0002, // left: down
|
||||
0x02 => 0x0008, // right: down
|
||||
0x03 => 0x0020, // middle: down
|
||||
_ => 0
|
||||
};
|
||||
if (downFlag != 0)
|
||||
mouse_event(downFlag, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
public void Release(int button)
|
||||
{
|
||||
uint upFlag = button switch
|
||||
{
|
||||
0x01 => 0x0004, // left: up
|
||||
0x02 => 0x0010, // right: up
|
||||
0x03 => 0x0040, // middle: up
|
||||
_ => 0
|
||||
};
|
||||
if (upFlag != 0)
|
||||
mouse_event(upFlag, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+134
-50
@@ -1,9 +1,11 @@
|
||||
using Spectrum.Input.InputLibraries.Arduino;
|
||||
using Spectrum.Input.InputLibraries.HID;
|
||||
using Spectrum.Input.InputLibraries.MakcuBinary;
|
||||
using Spectrum.Input.InputLibraries.MakcuLegacy;
|
||||
using Spectrum.Input.InputLibraries.MouseEvent;
|
||||
using Spectrum.Utilities;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
@@ -18,7 +20,10 @@ namespace Spectrum.Input
|
||||
private static long _lastMoveTicks = 0;
|
||||
private static readonly double _dtRef = 1.0 / 120.0;
|
||||
private static bool isSpraying = false;
|
||||
private static readonly HIDMain? hid = Program.HIDMain;
|
||||
private static readonly object makcuSync = new();
|
||||
private static bool makcuReady = false;
|
||||
private static bool makcuAttempted = false;
|
||||
private static ushort makcuButtons = 0;
|
||||
|
||||
private static double GetDeltaSeconds()
|
||||
{
|
||||
@@ -64,6 +69,26 @@ namespace Spectrum.Input
|
||||
reference.Y = bounds.Y + bounds.Height / 2;
|
||||
}
|
||||
|
||||
bool isInAimFov = true;
|
||||
if (config.EnableAimFov)
|
||||
{
|
||||
if (config.AimFovType == FovType.Circle)
|
||||
{
|
||||
double dist = Math.Sqrt(Math.Pow(reference.X - lastDetection.X, 2) + Math.Pow(reference.Y - lastDetection.Y, 2));
|
||||
double radius = Math.Min(config.AimFovWidth, config.AimFovHeight) / 2;
|
||||
isInAimFov &= dist < radius;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Math.Abs(reference.X - lastDetection.X) > config.AimFovWidth / 2 ||
|
||||
Math.Abs(reference.Y - lastDetection.Y) > config.AimFovHeight / 2)
|
||||
isInAimFov = false;
|
||||
}
|
||||
}
|
||||
if (!isInAimFov)
|
||||
return;
|
||||
|
||||
Point start = new(reference.X, reference.Y);
|
||||
Point end = new(lastDetection.X, lastDetection.Y);
|
||||
|
||||
@@ -104,26 +129,30 @@ namespace Spectrum.Input
|
||||
if (deltaX > config.ImageWidth || deltaX < -config.ImageWidth || deltaY > config.ImageHeight || deltaY < -config.ImageHeight)
|
||||
return;
|
||||
|
||||
switch (config.MovementMethod)
|
||||
switch (config.InputLibraryType)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
case InputLibraryType.MouseEvent:
|
||||
MouseMain.Instance.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.Move(deltaX, deltaY);
|
||||
case InputLibraryType.Arduino:
|
||||
if (ArduinoMain.Instance != null && ArduinoMain.Instance.IsConnected)
|
||||
ArduinoMain.Instance.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.HID:
|
||||
if (hid != null && hid.IsConnected)
|
||||
hid.Move(deltaX, deltaY);
|
||||
else
|
||||
LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}");
|
||||
case InputLibraryType.HID:
|
||||
if (HIDMain.Instance != null && HIDMain.Instance.IsConnected)
|
||||
HIDMain.Instance.Move(deltaX, deltaY);
|
||||
break;
|
||||
case InputLibraryType.MakcuLegacy:
|
||||
if (MakcuLegacyMain.Instance != null && MakcuLegacyMain.Instance.IsConnected)
|
||||
MakcuLegacyMain.Instance.Move(deltaX, deltaY);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
MouseMain.Instance.Move(deltaX, deltaY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Point CalculateMovement(Point start, Point end, double sensitivity, MovementType movementType, bool insideBoundingBox)
|
||||
{
|
||||
return movementType switch
|
||||
@@ -132,23 +161,15 @@ namespace Spectrum.Input
|
||||
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity),
|
||||
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity),
|
||||
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity),
|
||||
MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox),
|
||||
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
|
||||
};
|
||||
}
|
||||
|
||||
private static Point TrackWindMouse(Point start, Point end, double sensitivity, bool insideBoundingBox)
|
||||
{
|
||||
var t0 = Stopwatch.GetTimestamp();
|
||||
var result = MovementPaths.WindMouse(start, end,
|
||||
MovementType.WindMouse => MovementPaths.WindMouse(start, end,
|
||||
mainConfig.Data.WindMouseGravity,
|
||||
mainConfig.Data.WindMouseWind,
|
||||
mainConfig.Data.WindMouseMaxStep,
|
||||
sensitivity,
|
||||
mainConfig.Data.WindMouseOvershoot,
|
||||
insideBoundingBox);
|
||||
Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0);
|
||||
return result;
|
||||
insideBoundingBox),
|
||||
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
|
||||
};
|
||||
}
|
||||
|
||||
public static async Task ClickMouse()
|
||||
@@ -156,8 +177,6 @@ namespace Spectrum.Input
|
||||
var config = mainConfig.Data;
|
||||
if (!config.TriggerBot)
|
||||
return;
|
||||
if (!IsKeyOrMouseDown(config.TriggerKeybind) || config.TriggerKeybind.Key == Keys.None)
|
||||
return;
|
||||
|
||||
var currentPosition = new Point();
|
||||
if (config.ClosestToMouse)
|
||||
@@ -189,11 +208,11 @@ namespace Spectrum.Input
|
||||
if (config.TriggerSpray && !isSpraying)
|
||||
{
|
||||
isSpraying = true;
|
||||
ClickDown(config.MovementMethod);
|
||||
ClickDown(config.InputLibraryType);
|
||||
}
|
||||
else if (!config.TriggerSpray)
|
||||
{
|
||||
ClickDown(config.MovementMethod);
|
||||
ClickDown(config.InputLibraryType);
|
||||
}
|
||||
|
||||
if (!config.TriggerRandomDuration && !config.TriggerSpray)
|
||||
@@ -202,53 +221,62 @@ namespace Spectrum.Input
|
||||
await Task.Delay(Random.Shared.Next(20, config.TriggerDuration));
|
||||
|
||||
if (!config.TriggerSpray)
|
||||
ClickUp(config.MovementMethod);
|
||||
ClickUp(config.InputLibraryType);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isSpraying)
|
||||
{
|
||||
isSpraying = false;
|
||||
ClickUp(config.MovementMethod);
|
||||
ClickUp(config.InputLibraryType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ClickDown(MovementMethod movementMethod)
|
||||
private static void ClickDown(InputLibraryType movementMethod)
|
||||
{
|
||||
switch (movementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickDown();
|
||||
case InputLibraryType.MouseEvent:
|
||||
MouseMain.Instance.Press(0x01);
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.ClickDown();
|
||||
case InputLibraryType.Arduino:
|
||||
if (ArduinoMain.Instance != null && ArduinoMain.Instance.IsConnected)
|
||||
ArduinoMain.Instance.Press(0x01);
|
||||
break;
|
||||
case MovementMethod.HID:
|
||||
if (hid != null && hid.IsConnected)
|
||||
hid.Press(HIDMain.BUTTON_LEFT);
|
||||
case InputLibraryType.HID:
|
||||
if (HIDMain.Instance != null && HIDMain.Instance.IsConnected)
|
||||
HIDMain.Instance.Press(HIDMain.BUTTON_LEFT);
|
||||
break;
|
||||
case InputLibraryType.MakcuLegacy:
|
||||
if (MakcuLegacyMain.Instance != null && MakcuLegacyMain.Instance.IsConnected)
|
||||
MakcuLegacyMain.Instance.Press(0x01);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickDown();
|
||||
MouseMain.Instance.Press(0x01);
|
||||
break;
|
||||
}
|
||||
}
|
||||
private static void ClickUp(MovementMethod movementMethod)
|
||||
private static void ClickUp(InputLibraryType movementMethod)
|
||||
{
|
||||
switch (movementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickUp();
|
||||
case InputLibraryType.MouseEvent:
|
||||
MouseMain.Instance.Release(0x01);
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.ClickUp();
|
||||
case InputLibraryType.Arduino:
|
||||
ArduinoMain.Instance.Release(0x01);
|
||||
break;
|
||||
case MovementMethod.HID:
|
||||
if (hid != null && hid.IsConnected)
|
||||
hid.Release(HIDMain.BUTTON_LEFT);
|
||||
case InputLibraryType.HID:
|
||||
if (HIDMain.Instance != null && HIDMain.Instance.IsConnected)
|
||||
HIDMain.Instance.Release(HIDMain.BUTTON_LEFT);
|
||||
break;
|
||||
case InputLibraryType.MakcuLegacy:
|
||||
if (MakcuLegacyMain.Instance != null && MakcuLegacyMain.Instance.IsConnected)
|
||||
MakcuLegacyMain.Instance.Release(0x01);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickUp();
|
||||
MouseMain.Instance.Release(0x01);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -293,7 +321,7 @@ namespace Spectrum.Input
|
||||
|
||||
foreach (var mouseKey in MouseKeys)
|
||||
{
|
||||
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
||||
if (IsKeyOrMouseDown(mouseKey))
|
||||
{
|
||||
tcs.TrySetResult(mouseKey);
|
||||
return;
|
||||
@@ -327,9 +355,65 @@ namespace Spectrum.Input
|
||||
|
||||
public static bool IsKeyOrMouseDown(Keys key)
|
||||
{
|
||||
if (IsMouseKey(key) && EnsureMakcuReady())
|
||||
{
|
||||
if (IsMakcuMouseDown(key))
|
||||
return true;
|
||||
}
|
||||
|
||||
return (GetAsyncKeyState((int)key) & 0x8000) != 0;
|
||||
}
|
||||
|
||||
private static bool EnsureMakcuReady()
|
||||
{
|
||||
if (mainConfig.Data.InputLibraryType != InputLibraryType.MakcuBinary)
|
||||
return false;
|
||||
if (makcuReady) return true;
|
||||
lock (makcuSync)
|
||||
{
|
||||
if (makcuReady) return true;
|
||||
if (makcuAttempted) return false;
|
||||
makcuAttempted = true;
|
||||
try
|
||||
{
|
||||
if (MakcuBinaryMain.Instance.Initialize())
|
||||
{
|
||||
MakcuBinaryMain.Instance.ButtonsChanged += OnMakcuButtonsChanged;
|
||||
makcuReady = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnMakcuButtonsChanged(ushort mask)
|
||||
{
|
||||
makcuButtons = mask;
|
||||
}
|
||||
|
||||
private static bool IsMouseKey(Keys key)
|
||||
{
|
||||
return key == Keys.LButton || key == Keys.RButton || key == Keys.MButton || key == Keys.XButton1 || key == Keys.XButton2;
|
||||
}
|
||||
|
||||
private static bool IsMakcuMouseDown(Keys key)
|
||||
{
|
||||
ushort mask = makcuButtons;
|
||||
return key switch
|
||||
{
|
||||
Keys.LButton => (mask & 0x01) != 0,
|
||||
Keys.RButton => (mask & 0x02) != 0,
|
||||
Keys.MButton => (mask & 0x04) != 0,
|
||||
Keys.XButton1 => (mask & 0x08) != 0,
|
||||
Keys.XButton2 => (mask & 0x10) != 0,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, bool> _keybindToggleStates = [];
|
||||
|
||||
public static bool IsKeyOrMouseDown(Keybind keybind)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
namespace Spectrum.Input
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
public class MovementPaths
|
||||
{
|
||||
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||
private static readonly int[] _permutation = GeneratePermutation();
|
||||
private static readonly int[] _p;
|
||||
private static double _perlinTime = 0.0;
|
||||
|
||||
private static Point _lastMove = new(0, 0);
|
||||
@@ -13,15 +14,6 @@
|
||||
private static double _velocityX = 0.0;
|
||||
private static double _velocityY = 0.0;
|
||||
|
||||
static MovementPaths()
|
||||
{
|
||||
_p = new int[512];
|
||||
for (int i = 0; i < 256; i++)
|
||||
{
|
||||
_p[256 + i] = _p[i] = _permutation[i];
|
||||
}
|
||||
}
|
||||
|
||||
private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10);
|
||||
private static double Lerp(double a, double b, double t) => a + t * (b - a);
|
||||
private static double Grad(int hash, double x)
|
||||
@@ -36,8 +28,8 @@
|
||||
int X = (int)Math.Floor(x) & 255;
|
||||
x -= Math.Floor(x);
|
||||
double u = Fade(x);
|
||||
int a = _p[X];
|
||||
int b = _p[X + 1];
|
||||
int a = _permutation[X];
|
||||
int b = _permutation[X + 1];
|
||||
double res = Lerp(Grad(a, x), Grad(b, x - 1), u);
|
||||
return res * 0.188;
|
||||
}
|
||||
@@ -282,13 +274,20 @@
|
||||
|
||||
private static int[] GeneratePermutation()
|
||||
{
|
||||
int[] perm = new int[256];
|
||||
for (int i = 0; i < 256; i++) perm[i] = i;
|
||||
int[] perm = new int[512];
|
||||
|
||||
for (int i = 0; i < 256; i++)
|
||||
perm[i] = i;
|
||||
|
||||
for (int i = 255; i > 0; i--)
|
||||
{
|
||||
int j = Random.Shared.Next(i + 1);
|
||||
int j = RandomNumberGenerator.GetInt32(i + 1);
|
||||
(perm[i], perm[j]) = (perm[j], perm[i]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 256; i++)
|
||||
perm[i + 256] = perm[i];
|
||||
|
||||
return perm;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Detection;
|
||||
using Spectrum.Input.InputLibraries.HID;
|
||||
using Spectrum.Input.InputLibraries;
|
||||
using Spectrum.Utilities;
|
||||
using System.CommandLine;
|
||||
|
||||
@@ -11,11 +11,11 @@ namespace Spectrum
|
||||
static Renderer? renderer = null;
|
||||
public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs");
|
||||
public static ColorConfigManager colorConfig = new("bin\\configs\\colors");
|
||||
public static HIDMain HIDMain = new();
|
||||
private static DetectionManager? detectionManager;
|
||||
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
|
||||
public static TimingStats Timings { get; } = new TimingStats();
|
||||
public static int MonitorIndex { get; private set; } = 1;
|
||||
public static InputLibraryManager InputLibraryManager { get; private set; } = new InputLibraryManager();
|
||||
public static Rectangle MonitorBounds { get; private set; } = Screen.PrimaryScreen?.Bounds ?? Screen.AllScreens[0].Bounds;
|
||||
|
||||
static int Main(string[] args)
|
||||
|
||||
+177
-109
@@ -1,12 +1,12 @@
|
||||
using ClickableTransparentOverlay;
|
||||
using ImGuiNET;
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Detection;
|
||||
using Spectrum.Input;
|
||||
using Spectrum.Input.InputLibraries.Arduino;
|
||||
using Spectrum.Utilities;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Spectrum.Detection;
|
||||
using Spectrum.Input;
|
||||
using Spectrum.Input.InputLibraries;
|
||||
using Spectrum.Utilities;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
@@ -38,6 +38,7 @@ namespace Spectrum
|
||||
private bool _windowPositioned = false;
|
||||
private Image<Rgba32>? _copyIconImage = null;
|
||||
private IntPtr _copyIconTextureId = IntPtr.Zero;
|
||||
private readonly InputLibraryManager _inputManager = Program.InputLibraryManager;
|
||||
|
||||
private static Vector2 ToOverlay(Vector2 point)
|
||||
{
|
||||
@@ -104,7 +105,7 @@ namespace Spectrum
|
||||
LogManager.Log($"Renderer window positioned: {bounds.X},{bounds.Y} {bounds.Width}x{bounds.Height}", LogManager.LogLevel.Debug);
|
||||
}
|
||||
var config = mainConfig.Data;
|
||||
if (config.DrawDetections || config.DrawFOV || config.DebugMode || config.DrawAimPoint)
|
||||
if (config.DrawDetections || config.DrawCaptureFov || config.DebugMode || config.DrawAimPoint)
|
||||
RenderOverlay();
|
||||
if (!config.ShowMenu)
|
||||
return;
|
||||
@@ -126,6 +127,9 @@ namespace Spectrum
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
int ImageWidth = config.ImageWidth;
|
||||
int ImageHeight = config.ImageHeight;
|
||||
|
||||
ImGui.BeginTabBar("##tabs");
|
||||
if (ImGui.BeginTabItem("Aiming"))
|
||||
{
|
||||
@@ -145,6 +149,60 @@ namespace Spectrum
|
||||
if (ImGui.Checkbox(" Closest to Mouse", ref closestToMouse))
|
||||
config.ClosestToMouse = closestToMouse;
|
||||
|
||||
bool enableAimFov = config.EnableAimFov;
|
||||
if (ImGui.Checkbox(" Enable Aim Fov", ref enableAimFov))
|
||||
config.EnableAimFov = enableAimFov;
|
||||
|
||||
if (enableAimFov)
|
||||
{
|
||||
bool drawAimFov = config.DrawAimFov;
|
||||
if (ImGui.Checkbox(" Draw Aim FOV", ref drawAimFov))
|
||||
config.DrawAimFov = drawAimFov;
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
|
||||
|
||||
Vector4 aimFovColor = config.AimFovColor;
|
||||
if (ImGui.ColorEdit4("Aim FOV Color", ref aimFovColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
config.AimFovColor = aimFovColor;
|
||||
|
||||
int aimFovWidth = config.AimFovWidth;
|
||||
int aimFovHeight = config.AimFovHeight;
|
||||
FovType aimFovType = config.AimFovType;
|
||||
ImGui.TextUnformatted("Aim FOV Type");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
if (ImGui.BeginCombo("##Aim FOV Type", aimFovType.ToString()))
|
||||
{
|
||||
foreach (FovType type in Enum.GetValues(typeof(FovType)))
|
||||
{
|
||||
bool isSelected = (type == aimFovType);
|
||||
if (ImGui.Selectable(type.ToString(), isSelected))
|
||||
config.AimFovType = type;
|
||||
if (isSelected)
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
|
||||
if (aimFovType == FovType.Circle)
|
||||
{
|
||||
int aimFovRadius = Math.Min(aimFovWidth, aimFovHeight) / 2;
|
||||
if (ImGuiExtensions.SliderFill("Aim FOV Radius (px)", ref aimFovRadius, 1, Math.Min(ImageWidth, ImageHeight) / 2))
|
||||
{
|
||||
aimFovWidth = aimFovRadius * 2;
|
||||
aimFovHeight = aimFovRadius * 2;
|
||||
config.AimFovWidth = aimFovWidth;
|
||||
config.AimFovHeight = aimFovHeight;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ImGuiExtensions.SliderFill("Aim FOV Width (px)", ref aimFovWidth, 1, ImageWidth))
|
||||
config.AimFovWidth = aimFovWidth;
|
||||
if (ImGuiExtensions.SliderFill("Aim FOV Height (px)", ref aimFovHeight, 1, ImageHeight))
|
||||
config.AimFovHeight = aimFovHeight;
|
||||
}
|
||||
}
|
||||
|
||||
float sensitivity = (float)config.Sensitivity;
|
||||
if (ImGuiExtensions.SliderFill("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f", false))
|
||||
config.Sensitivity = Math.Clamp(sensitivity, 0.1, float.MaxValue);
|
||||
@@ -331,24 +389,20 @@ namespace Spectrum
|
||||
ImGuiExtensions.BeginPaneGroup("Overlay Panes", 1, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
if (ImGuiExtensions.BeginPane("Overlay"))
|
||||
{
|
||||
bool DrawFOV = config.DrawFOV;
|
||||
if (ImGui.Checkbox("##Draw FOV", ref DrawFOV))
|
||||
config.DrawFOV = DrawFOV;
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw FOV");
|
||||
bool DrawFOV = config.DrawCaptureFov;
|
||||
if (ImGui.Checkbox(" Draw FOV", ref DrawFOV))
|
||||
config.DrawCaptureFov = DrawFOV;
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
|
||||
Vector4 FOVColor = config.FOVColor;
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
|
||||
Vector4 FOVColor = config.CaptureFOVColor;
|
||||
if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
config.FOVColor = FOVColor;
|
||||
config.CaptureFOVColor = FOVColor;
|
||||
|
||||
bool DrawDetections = config.DrawDetections;
|
||||
if (ImGui.Checkbox("##Draw Detections", ref DrawDetections))
|
||||
if (ImGui.Checkbox(" Draw Detections", ref DrawDetections))
|
||||
config.DrawDetections = DrawDetections;
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw Detections");
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
|
||||
Vector4 DetectionColor = config.DetectionColor;
|
||||
if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
config.DetectionColor = DetectionColor;
|
||||
@@ -357,18 +411,18 @@ namespace Spectrum
|
||||
bool HighlightTarget = config.HighlightTarget;
|
||||
if (ImGui.Checkbox(" Highlight Target", ref HighlightTarget))
|
||||
config.HighlightTarget = HighlightTarget;
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
|
||||
Vector4 HighlightColor = config.TargetColor;
|
||||
if (ImGui.ColorEdit4("Highlight Color", ref HighlightColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
config.TargetColor = HighlightColor;
|
||||
}
|
||||
|
||||
bool DrawAimPoint = config.DrawAimPoint;
|
||||
if (ImGui.Checkbox("##Draw Aim Point", ref DrawAimPoint))
|
||||
if (ImGui.Checkbox(" Draw Aim Point", ref DrawAimPoint))
|
||||
config.DrawAimPoint = DrawAimPoint;
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw Aim Point");
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
|
||||
|
||||
Vector4 AimPointColor = config.AimPointColor;
|
||||
if (ImGui.ColorEdit4("Aim Point Color", ref AimPointColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
config.AimPointColor = AimPointColor;
|
||||
@@ -377,14 +431,14 @@ namespace Spectrum
|
||||
{
|
||||
ImGui.TextUnformatted("FOV Type");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
FovType fovType = config.FOVType;
|
||||
FovType fovType = config.CaptureFOVType;
|
||||
if (ImGui.BeginCombo("##FOV Type", fovType.ToString()))
|
||||
{
|
||||
foreach (FovType type in Enum.GetValues(typeof(FovType)))
|
||||
{
|
||||
bool isSelected = (type == fovType);
|
||||
if (ImGui.Selectable(type.ToString(), isSelected))
|
||||
config.FOVType = type;
|
||||
config.CaptureFOVType = type;
|
||||
if (isSelected)
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
@@ -423,7 +477,7 @@ namespace Spectrum
|
||||
{
|
||||
ImGui.TextUnformatted("Image Width");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
int ImageWidth = config.ImageWidth;
|
||||
|
||||
if (ImGui.InputInt("##Image Width", ref ImageWidth, 1, screenSize.width))
|
||||
{
|
||||
if (ImageWidth < 1)
|
||||
@@ -435,7 +489,7 @@ namespace Spectrum
|
||||
|
||||
ImGui.TextUnformatted("Image Height");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
int ImageHeight = config.ImageHeight;
|
||||
|
||||
if (ImGui.InputInt("##Image Height", ref ImageHeight, 1, screenSize.height))
|
||||
{
|
||||
if (ImageHeight < 1)
|
||||
@@ -453,10 +507,6 @@ namespace Spectrum
|
||||
if (ImGuiExtensions.ColorEditHSV3("Lower HSV", ref lowerHSV))
|
||||
config.LowerHSV = lowerHSV;
|
||||
|
||||
int Threshold = config.Threshold;
|
||||
if (ImGuiExtensions.SliderFill("Threshold", ref Threshold, 1, 255))
|
||||
config.Threshold = Threshold;
|
||||
|
||||
int minAreaPx = config.MinAreaPx;
|
||||
if (ImGuiExtensions.SliderFill("Min Area (px)", ref minAreaPx, 1, 10000))
|
||||
config.MinAreaPx = minAreaPx;
|
||||
@@ -676,51 +726,19 @@ namespace Spectrum
|
||||
{
|
||||
ImGui.TextUnformatted("Movement Method");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
MovementMethod movementMethod = config.MovementMethod;
|
||||
if (ImGui.BeginCombo("##Movement Method", movementMethod != MovementMethod.HID
|
||||
InputLibraryType movementMethod = config.InputLibraryType;
|
||||
if (ImGui.BeginCombo("##Movement Method", movementMethod != InputLibraryType.HID
|
||||
? FormatText(movementMethod.ToString()) : movementMethod.ToString()))
|
||||
{
|
||||
foreach (MovementMethod method in Enum.GetValues(typeof(MovementMethod)))
|
||||
foreach (InputLibraryType method in Enum.GetValues(typeof(InputLibraryType)))
|
||||
{
|
||||
bool isSelected = method == movementMethod;
|
||||
if (ImGui.Selectable(method != MovementMethod.HID ? FormatText(method.ToString()) : method.ToString(), isSelected))
|
||||
if (ImGui.Selectable(method != InputLibraryType.HID ? FormatText(method.ToString()) : method.ToString(), isSelected))
|
||||
{
|
||||
config.MovementMethod = method;
|
||||
switch (method)
|
||||
{
|
||||
case MovementMethod.Arduino:
|
||||
{
|
||||
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
|
||||
Program.HIDMain.Close();
|
||||
var ok = ArduinoMain.Load();
|
||||
if (!ok)
|
||||
{
|
||||
LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
config.MovementMethod = MovementMethod.MouseEvent;
|
||||
ArduinoMain.Close();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MovementMethod.HID:
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Program.HIDMain?.IsConnected == false)
|
||||
Program.HIDMain.Init();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"HID failed to initialize: {ex.Message}. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
config.MovementMethod = MovementMethod.MouseEvent;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ArduinoMain.Close();
|
||||
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
|
||||
Program.HIDMain.Close();
|
||||
break;
|
||||
}
|
||||
config.InputLibraryType = method;
|
||||
bool success = _inputManager.Switch(method);
|
||||
if (!success)
|
||||
config.InputLibraryType = _inputManager.CurrentType;
|
||||
}
|
||||
if (isSelected)
|
||||
ImGui.SetItemDefaultFocus();
|
||||
@@ -843,8 +861,17 @@ namespace Spectrum
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
var _LogEntries = LogManager.LogEntries;
|
||||
_LogEntries = [.. _LogEntries];
|
||||
List<LogManager.LogEntry?> logs;
|
||||
|
||||
try
|
||||
{
|
||||
logs = [.. LogManager.LogEntries];
|
||||
}
|
||||
catch
|
||||
{
|
||||
logs = [];
|
||||
}
|
||||
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Logs", true, 16f, () =>
|
||||
{
|
||||
@@ -864,9 +891,9 @@ namespace Spectrum
|
||||
if (copyClicked)
|
||||
{
|
||||
var logText = new System.Text.StringBuilder();
|
||||
foreach (var log in _LogEntries)
|
||||
foreach (var log in logs)
|
||||
{
|
||||
logText.AppendLine(log.ToString());
|
||||
logText.AppendLine(log?.ToString());
|
||||
}
|
||||
ImGui.SetClipboardText(logText.ToString());
|
||||
}
|
||||
@@ -876,11 +903,23 @@ namespace Spectrum
|
||||
|
||||
float scrollY = ImGui.GetScrollY();
|
||||
float scrollMaxY = ImGui.GetScrollMaxY();
|
||||
bool isAtBottom = (scrollY >= scrollMaxY - 1.0f);
|
||||
|
||||
foreach (var log in _LogEntries)
|
||||
bool isAtBottom = scrollY >= scrollMaxY - 1.0f;
|
||||
bool debugEnabled = LogManager.IsDebugEnabled();
|
||||
foreach (var log in logs)
|
||||
{
|
||||
ImGui.Text(log.ToString());
|
||||
if (log == null)
|
||||
continue;
|
||||
if (log.Level == LogManager.LogLevel.Debug && !debugEnabled)
|
||||
continue;
|
||||
var color = log.Level switch
|
||||
{
|
||||
LogManager.LogLevel.Debug => new Vector4(0.5f, 0.5f, 0.5f, 1f),
|
||||
LogManager.LogLevel.Info => new Vector4(1f, 1f, 1f, 1f),
|
||||
LogManager.LogLevel.Warning => new Vector4(1f, 1f, 0.5f, 1f),
|
||||
LogManager.LogLevel.Error => new Vector4(1f, 0.5f, 0.5f, 1f),
|
||||
_ => new Vector4(1f, 1f, 1f, 1f),
|
||||
};
|
||||
ImGui.TextColored(color, log.ToString());
|
||||
}
|
||||
|
||||
if (scrollToBottom || isAtBottom)
|
||||
@@ -926,9 +965,12 @@ namespace Spectrum
|
||||
var drawList = ImGui.GetWindowDrawList();
|
||||
var config = mainConfig.Data;
|
||||
|
||||
if (config.DrawFOV)
|
||||
if (config.DrawCaptureFov || (config.DrawAimFov && config.EnableAimFov))
|
||||
{
|
||||
if (config.FOVType == FovType.Rectangle)
|
||||
InputManager.GetCursorPos(out System.Drawing.Point mousePos);
|
||||
if (config.DrawCaptureFov)
|
||||
{
|
||||
if (config.CaptureFOVType == FovType.Rectangle)
|
||||
{
|
||||
Vector2 topLeft;
|
||||
Vector2 bottomRight;
|
||||
@@ -939,30 +981,56 @@ namespace Spectrum
|
||||
}
|
||||
else
|
||||
{
|
||||
InputManager.GetCursorPos(out System.Drawing.Point mousePos);
|
||||
var local = ToOverlay(new Vector2(mousePos.X, mousePos.Y));
|
||||
topLeft = new(local.X - (config.ImageWidth / 2), local.Y - (config.ImageHeight / 2));
|
||||
bottomRight = new(local.X + (config.ImageWidth / 2), local.Y + (config.ImageHeight / 2));
|
||||
}
|
||||
|
||||
|
||||
drawList.AddRect(topLeft, bottomRight, ImGui.GetColorU32(config.FOVColor), 0.0f, ImDrawFlags.None, 1.0f);
|
||||
drawList.AddRect(topLeft, bottomRight, ImGui.GetColorU32(config.CaptureFOVColor), 0.0f, ImDrawFlags.None, 1.0f);
|
||||
}
|
||||
else if (config.FOVType == FovType.Circle)
|
||||
else if (config.CaptureFOVType == FovType.Circle)
|
||||
{
|
||||
Vector2 center;
|
||||
if (!config.ClosestToMouse)
|
||||
{
|
||||
center = new(screenSize.width / 2, screenSize.height / 2);
|
||||
else
|
||||
center = ToOverlay(new Vector2(mousePos.X, mousePos.Y));
|
||||
|
||||
drawList.AddCircle(center, Math.Min(config.ImageHeight, config.ImageWidth) / 2, ImGui.GetColorU32(config.CaptureFOVColor), 100, 1.0f);
|
||||
}
|
||||
}
|
||||
if (config.DrawAimFov)
|
||||
{
|
||||
if (config.AimFovType == FovType.Rectangle)
|
||||
{
|
||||
Vector2 topLeft;
|
||||
Vector2 bottomRight;
|
||||
if (!config.ClosestToMouse)
|
||||
{
|
||||
topLeft = new((screenSize.width - config.AimFovWidth) / 2, (screenSize.height - config.AimFovHeight) / 2);
|
||||
bottomRight = new((screenSize.width + config.AimFovWidth) / 2, (screenSize.height + config.AimFovHeight) / 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = InputManager.GetCursorPos(out System.Drawing.Point mousePos);
|
||||
center = ToOverlay(new Vector2(mousePos.X, mousePos.Y));
|
||||
var local = ToOverlay(new Vector2(mousePos.X, mousePos.Y));
|
||||
topLeft = new(local.X - (config.AimFovWidth / 2), local.Y - (config.AimFovHeight / 2));
|
||||
bottomRight = new(local.X + (config.AimFovWidth / 2), local.Y + (config.AimFovHeight / 2));
|
||||
}
|
||||
|
||||
drawList.AddCircle(center, config.ImageWidth / 2, ImGui.GetColorU32(config.FOVColor), 100, 1.0f);
|
||||
} // added straight to drawlist to prevent caching/flickering
|
||||
drawList.AddRect(topLeft, bottomRight, ImGui.GetColorU32(config.AimFovColor), 0.0f, ImDrawFlags.None, 1.0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector2 center;
|
||||
if (!config.ClosestToMouse)
|
||||
center = new(screenSize.width / 2, screenSize.height / 2);
|
||||
else
|
||||
center = ToOverlay(new Vector2(mousePos.X, mousePos.Y));
|
||||
drawList.AddCircle(center, Math.Min(config.AimFovWidth, config.AimFovHeight) / 2, ImGui.GetColorU32(config.AimFovColor), 100, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
if (config.DebugMode)
|
||||
@@ -975,11 +1043,18 @@ namespace Spectrum
|
||||
$"FPS: {fps} | AVG Process Time: {avgTime}ms"
|
||||
};
|
||||
|
||||
var bitmapToMat = Program.Timings.GetSnapshot(["Bitmap to Mat"]).FirstOrDefault();
|
||||
var screenCapture = Program.Timings.GetSnapshot(["Screen Capture"]).FirstOrDefault();
|
||||
|
||||
long skippedFrames = (screenCapture?.Count ?? 0L) - (bitmapToMat?.Count ?? 0L);
|
||||
|
||||
lines.Add($"Skipped Frames: {skippedFrames}/{(screenCapture?.Count ?? 0L)}");
|
||||
|
||||
var stats = Program.Timings.GetSnapshot();
|
||||
stats = [.. stats.OrderByDescending(s => s.AverageTicks)];
|
||||
stats = [.. stats.Where(s => s.Name != "Frame")];
|
||||
foreach (var stat in stats)
|
||||
lines.Add($"{stat.Name}: {FormatDuration(stat.AverageTicks)}");
|
||||
lines.Add($"{stat.Name}: {TimingStats.FormatDuration(stat.AverageTicks)}");
|
||||
|
||||
float maxWidth = 0;
|
||||
float totalHeight = 0;
|
||||
@@ -1095,16 +1170,21 @@ namespace Spectrum
|
||||
colors[(int)ImGuiCol.ScrollbarGrabHovered] = new Vector4(0.43f, 0.43f, 0.45f, 1.0f);
|
||||
colors[(int)ImGuiCol.ScrollbarGrabActive] = new Vector4(0.50f, 0.50f, 0.52f, 1.0f);
|
||||
}
|
||||
public void AddRect(System.Drawing.Rectangle rect, Vector4 color, float thickness = 1.0f)
|
||||
public void AddRect(Rect rect, Vector4 color, float thickness = 1.0f, System.Drawing.Rectangle? bounds = null)
|
||||
{
|
||||
lock (detectionDrawLock)
|
||||
{
|
||||
var bounds = Program.MonitorBounds;
|
||||
var left = rect.Left - bounds.X;
|
||||
var top = rect.Top - bounds.Y;
|
||||
var right = rect.Right - bounds.X;
|
||||
var bottom = rect.Bottom - bounds.Y;
|
||||
detectionDrawCommands.Add(drawList => drawList.AddRect(new Vector2(left, top), new Vector2(right, bottom), ImGui.GetColorU32(color), 0, 0, thickness));
|
||||
var mb = Program.MonitorBounds;
|
||||
detectionDrawCommands.Add(drawList => drawList.AddRect(
|
||||
new Vector2(
|
||||
rect.Left + (bounds?.X ?? 0) - mb.X,
|
||||
rect.Top + (bounds?.Y ?? 0) - mb.Y),
|
||||
new Vector2(
|
||||
rect.Right + (bounds?.X ?? 0) - mb.X,
|
||||
rect.Bottom + (bounds?.Y ?? 0) - mb.Y),
|
||||
ImGui.GetColorU32(color),
|
||||
0, 0, thickness
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,17 +1259,5 @@ namespace Spectrum
|
||||
{
|
||||
return string.Concat(text.Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString()));
|
||||
}
|
||||
|
||||
private static string FormatDuration(double avgTicks)
|
||||
{
|
||||
double ns = avgTicks / Stopwatch.Frequency * 1_000_000_000.0;
|
||||
if (ns >= 1_000_000_000)
|
||||
return $"{Math.Round(ns / 1_000_000_000.0, 2)}s";
|
||||
if (ns >= 1_000_000)
|
||||
return $"{Math.Round(ns / 1_000_000.0, 2)}ms";
|
||||
if (ns >= 1_000)
|
||||
return $"{Math.Round(ns / 1_000.0, 2)}µs";
|
||||
return $"{Math.Round(ns, 2)}ns";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
|
||||
namespace Spectrum.Utilities
|
||||
{
|
||||
public class LogManager
|
||||
@@ -10,14 +9,16 @@ namespace Spectrum.Utilities
|
||||
private static readonly object _logLock = new();
|
||||
private static ConfigManager<ConfigData>? mainConfig;
|
||||
private static bool? debugOverride;
|
||||
|
||||
public enum LogLevel
|
||||
{
|
||||
Debug,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Critical
|
||||
Critical,
|
||||
}
|
||||
|
||||
public class LogEntry(LogLevel level, string message)
|
||||
{
|
||||
public DateTime Timestamp { get; set; } = DateTime.Now;
|
||||
@@ -29,36 +30,40 @@ namespace Spectrum.Utilities
|
||||
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
||||
}
|
||||
}
|
||||
|
||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||
|
||||
public static void SetDebugOverride(bool enabled)
|
||||
{
|
||||
debugOverride = enabled;
|
||||
}
|
||||
|
||||
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
return;
|
||||
if (mainConfig == null)
|
||||
{
|
||||
try { mainConfig = Program.mainConfig; } catch { }
|
||||
}
|
||||
|
||||
bool debugEnabled = Debugger.IsAttached;
|
||||
if (debugOverride.HasValue)
|
||||
debugEnabled = debugOverride.Value;
|
||||
try
|
||||
{
|
||||
debugEnabled = debugEnabled || (mainConfig?.Data?.DebugMode ?? false);
|
||||
mainConfig = Program.mainConfig;
|
||||
}
|
||||
catch { }
|
||||
if (level == LogLevel.Debug && !debugEnabled)
|
||||
return;
|
||||
}
|
||||
|
||||
bool debugEnabled = IsDebugEnabled();
|
||||
|
||||
try
|
||||
{
|
||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||
Debug.WriteLine(logMessage);
|
||||
if (debugEnabled && !Debugger.IsAttached)
|
||||
{
|
||||
try { Console.WriteLine(logMessage); } catch { }
|
||||
try
|
||||
{
|
||||
Console.WriteLine(logMessage);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
lock (_logLock)
|
||||
{
|
||||
@@ -71,6 +76,7 @@ namespace Spectrum.Utilities
|
||||
Debug.WriteLine($"[LogManager ERROR] Failed to append log entry: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void SaveLog(string filePath)
|
||||
{
|
||||
try
|
||||
@@ -88,6 +94,7 @@ namespace Spectrum.Utilities
|
||||
Log($"Failed to save log: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public static void ClearLog()
|
||||
{
|
||||
_logEntries.Clear();
|
||||
@@ -95,12 +102,38 @@ namespace Spectrum.Utilities
|
||||
|
||||
public static void OpenLogFolder()
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
Process.Start(
|
||||
new ProcessStartInfo
|
||||
{
|
||||
FileName = "explorer.exe",
|
||||
Arguments = Path.Combine(Directory.GetCurrentDirectory(), "bin", "logs"),
|
||||
UseShellExecute = true
|
||||
});
|
||||
UseShellExecute = true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public static bool IsDebugEnabled()
|
||||
{
|
||||
if (mainConfig == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
mainConfig = Program.mainConfig;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
bool debugEnabled = Debugger.IsAttached;
|
||||
if (debugOverride.HasValue)
|
||||
debugEnabled = debugOverride.Value;
|
||||
try
|
||||
{
|
||||
return debugEnabled || (mainConfig?.Data?.DebugMode ?? false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return debugEnabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Spectrum.Utilities
|
||||
{
|
||||
public sealed class TimingStats
|
||||
@@ -34,6 +36,13 @@ namespace Spectrum.Utilities
|
||||
entry.Count++;
|
||||
}
|
||||
}
|
||||
public void Clear()
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
entries.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public List<TimingSnapshot> GetSnapshot(IEnumerable<string>? orderedNames = null)
|
||||
{
|
||||
@@ -67,5 +76,31 @@ namespace Spectrum.Utilities
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public int GetCount(IEnumerable<string>? names = null)
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
if (names == null)
|
||||
return entries.Values.Sum(e => (int)e.Count);
|
||||
int total = 0;
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (entries.TryGetValue(name, out var entry))
|
||||
total += (int)entry.Count;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
public static string FormatDuration(double avgTicks)
|
||||
{
|
||||
double ns = avgTicks / Stopwatch.Frequency * 1_000_000_000.0;
|
||||
if (ns >= 1_000_000_000)
|
||||
return $"{Math.Round(ns / 1_000_000_000.0, 2)}s";
|
||||
if (ns >= 1_000_000)
|
||||
return $"{Math.Round(ns / 1_000_000.0, 2)}ms";
|
||||
if (ns >= 1_000)
|
||||
return $"{Math.Round(ns / 1_000.0, 2)}µs";
|
||||
return $"{Math.Round(ns, 2)}ns";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user