diff --git a/Spectrum.sln b/Spectrum.sln index c83e948..da9e025 100644 --- a/Spectrum.sln +++ b/Spectrum.sln @@ -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 diff --git a/Spectrum/Config.cs b/Spectrum/Config.cs index c20efd8..9aa0688 100644 --- a/Spectrum/Config.cs +++ b/Spectrum/Config.cs @@ -57,6 +57,12 @@ namespace Spectrum _data = JsonConvert.DeserializeObject(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) diff --git a/Spectrum/Detection/AutoLabeling.cs b/Spectrum/Detection/AutoLabeling.cs index 5723ec3..0d1b251 100644 --- a/Spectrum/Detection/AutoLabeling.cs +++ b/Spectrum/Detection/AutoLabeling.cs @@ -19,12 +19,12 @@ namespace Spectrum.Detection private static readonly ConfigManager mainConfig = Program.mainConfig; public static bool Started = false; - private static List GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight) + private static List GetBoundingBoxes(List contours, int imageWidth, int imageHeight) { var boundingBoxes = new List(); 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 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 FilteredContours { get; set; } = null!; } public class BackgroundImageData { diff --git a/Spectrum/Detection/DetectionManager.cs b/Spectrum/Detection/DetectionManager.cs index c14765a..c071715 100644 --- a/Spectrum/Detection/DetectionManager.cs +++ b/Spectrum/Detection/DetectionManager.cs @@ -3,6 +3,7 @@ using Spectrum.Input; using Spectrum.Utilities; using System.Diagnostics; using System.Drawing.Imaging; +using System.Numerics; namespace Spectrum.Detection { @@ -43,7 +44,7 @@ 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(); @@ -99,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); @@ -127,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; @@ -220,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); } } @@ -257,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); @@ -285,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)) { @@ -310,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 - { - Thread.Sleep(1); } } } - static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) + + static List MergeOverlappingContours(List contours) { - if (contours.Length <= 1) + if (contours.Count <= 1) return contours; - var contourRects = new List<(Rect rect, List indices)>(contours.Length); - for (int i = 0; i < contours.Length; i++) - { - var rect = Cv2.BoundingRect(contours[i]); - contourRects.Add((rect, new List { 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; } @@ -359,18 +349,7 @@ namespace Spectrum.Detection } } while (merged); - var mergedContours = new List(contourRects.Count); - foreach (var (_, indices) in contourRects) - { - var pointsList = new List(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) @@ -402,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 @@ -420,7 +390,7 @@ namespace Spectrum.Detection bitmap.UnlockBits(bmpData); } - return bgrBuffer!; + return bgrBuffer; } } } \ No newline at end of file diff --git a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs index c9a15f4..1e598e7 100644 --- a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs +++ b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs @@ -15,6 +15,8 @@ namespace Spectrum.Input.InputLibraries.Arduino private SerialPort? serial; private readonly object sync = new(); + public static ArduinoMain Instance { get; } = new ArduinoMain(); + public bool RequiresInitialization => true; public bool IsConnected => serial != null && serial.IsOpen; public bool Initialize() diff --git a/Spectrum/Input/InputLibraries/HID/HIDMain.cs b/Spectrum/Input/InputLibraries/HID/HIDMain.cs index 5f8f865..b8978c6 100644 --- a/Spectrum/Input/InputLibraries/HID/HIDMain.cs +++ b/Spectrum/Input/InputLibraries/HID/HIDMain.cs @@ -39,6 +39,7 @@ 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; diff --git a/Spectrum/Input/InputLibraries/InputLibraryManager.cs b/Spectrum/Input/InputLibraries/InputLibraryManager.cs new file mode 100644 index 0000000..8bfad66 --- /dev/null +++ b/Spectrum/Input/InputLibraries/InputLibraryManager.cs @@ -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; + } + } + } +} diff --git a/Spectrum/Input/InputLibraries/MakcuBinary/MakcuBinaryMain.cs b/Spectrum/Input/InputLibraries/MakcuBinary/MakcuBinaryMain.cs new file mode 100644 index 0000000..8eb956d --- /dev/null +++ b/Spectrum/Input/InputLibraries/MakcuBinary/MakcuBinaryMain.cs @@ -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? 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 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.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 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(); + 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); + } + } + } + } +} diff --git a/Spectrum/Input/InputLibraries/MakcuLegacy/MakcuLegacyMain.cs b/Spectrum/Input/InputLibraries/MakcuLegacy/MakcuLegacyMain.cs new file mode 100644 index 0000000..c8b1233 --- /dev/null +++ b/Spectrum/Input/InputLibraries/MakcuLegacy/MakcuLegacyMain.cs @@ -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 + { + } + } + } +} diff --git a/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs index 8221ba6..e88a586 100644 --- a/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs +++ b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs @@ -2,8 +2,11 @@ namespace Spectrum.Input.InputLibraries.MouseEvent { - public class MouseMain : IInputLibrary + 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; diff --git a/Spectrum/Input/InputManager.cs b/Spectrum/Input/InputManager.cs index 5b14ff2..15f0d07 100644 --- a/Spectrum/Input/InputManager.cs +++ b/Spectrum/Input/InputManager.cs @@ -1,4 +1,8 @@ -using Spectrum.Input.InputLibraries.HID; +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; @@ -16,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() { @@ -62,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); @@ -102,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: - Program.MouseMain.Move(deltaX, deltaY); + case InputLibraryType.MouseEvent: + MouseMain.Instance.Move(deltaX, deltaY); break; - case MovementMethod.Arduino: - Program.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: - Program.MouseMain.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 @@ -145,9 +176,7 @@ namespace Spectrum.Input { var config = mainConfig.Data; if (!config.TriggerBot) - return; - if (!IsKeyOrMouseDown(config.TriggerKeybind) || config.TriggerKeybind.Key == Keys.None) - return; + return; var currentPosition = new Point(); if (config.ClosestToMouse) @@ -179,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) @@ -192,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: - Program.MouseMain.Press(0x01); + case InputLibraryType.MouseEvent: + MouseMain.Instance.Press(0x01); break; - case MovementMethod.Arduino: - Program.ArduinoMain.Press(0x01); + 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: - Program.MouseMain.Press(0x01); + MouseMain.Instance.Press(0x01); break; } } - private static void ClickUp(MovementMethod movementMethod) + private static void ClickUp(InputLibraryType movementMethod) { switch (movementMethod) { - case MovementMethod.MouseEvent: - Program.MouseMain.Release(0x01); + case InputLibraryType.MouseEvent: + MouseMain.Instance.Release(0x01); break; - case MovementMethod.Arduino: - Program.ArduinoMain.Release(0x01); + 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: - Program.MouseMain.Release(0x01); + MouseMain.Instance.Release(0x01); break; } } @@ -283,7 +321,7 @@ namespace Spectrum.Input foreach (var mouseKey in MouseKeys) { - if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0) + if (IsKeyOrMouseDown(mouseKey)) { tcs.TrySetResult(mouseKey); return; @@ -317,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 _keybindToggleStates = []; public static bool IsKeyOrMouseDown(Keybind keybind) diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index 021135d..f40f7b6 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -1,8 +1,6 @@ using OpenCvSharp; using Spectrum.Detection; -using Spectrum.Input.InputLibraries.Arduino; -using Spectrum.Input.InputLibraries.HID; -using Spectrum.Input.InputLibraries.MouseEvent; +using Spectrum.Input.InputLibraries; using Spectrum.Utilities; using System.CommandLine; @@ -13,13 +11,11 @@ namespace Spectrum static Renderer? renderer = null; public static ConfigManager mainConfig = new("bin\\configs\\default.json", "bin\\configs"); public static ColorConfigManager colorConfig = new("bin\\configs\\colors"); - public static MouseMain MouseMain = new(); - public static ArduinoMain ArduinoMain = new(); - 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) diff --git a/Spectrum/Renderer/Renderer.cs b/Spectrum/Renderer/Renderer.cs index 4fc38af..11f21b3 100644 --- a/Spectrum/Renderer/Renderer.cs +++ b/Spectrum/Renderer/Renderer.cs @@ -5,6 +5,7 @@ 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; @@ -37,6 +38,7 @@ namespace Spectrum private bool _windowPositioned = false; private Image? _copyIconImage = null; private IntPtr _copyIconTextureId = IntPtr.Zero; + private readonly InputLibraryManager _inputManager = Program.InputLibraryManager; private static Vector2 ToOverlay(Vector2 point) { @@ -103,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; @@ -125,6 +127,9 @@ namespace Spectrum Environment.Exit(0); } + int ImageWidth = config.ImageWidth; + int ImageHeight = config.ImageHeight; + ImGui.BeginTabBar("##tabs"); if (ImGui.BeginTabItem("Aiming")) { @@ -144,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); @@ -330,44 +389,40 @@ 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; if (DrawDetections) { bool HighlightTarget = config.HighlightTarget; - if (ImGui.Checkbox("Highlight Target", ref 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; @@ -376,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(); } @@ -422,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) @@ -434,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) @@ -452,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; @@ -675,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.Dispose(); - var ok = Program.ArduinoMain.Initialize(); - if (!ok) - { - LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - config.MovementMethod = MovementMethod.MouseEvent; - Program.ArduinoMain.Dispose(); - } - break; - } - case MovementMethod.HID: - { - try - { - if (Program.HIDMain?.IsConnected == false) - Program.HIDMain.Initialize(); - } - catch (Exception ex) - { - LogManager.Log($"HID failed to initialize: {ex.Message}. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - config.MovementMethod = MovementMethod.MouseEvent; - } - break; - } - default: - Program.ArduinoMain.Dispose(); - if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) - Program.HIDMain.Dispose(); - break; - } + config.InputLibraryType = method; + bool success = _inputManager.Switch(method); + if (!success) + config.InputLibraryType = _inputManager.CurrentType; } if (isSelected) ImGui.SetItemDefaultFocus(); @@ -842,8 +861,17 @@ namespace Spectrum ImGuiExtensions.EndPane(); } - var _LogEntries = LogManager.LogEntries; - _LogEntries = [.. _LogEntries]; + List logs; + + try + { + logs = [.. LogManager.LogEntries]; + } + catch + { + logs = []; + } + if (ImGuiExtensions.BeginPane("Logs", true, 16f, () => { @@ -863,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()); } @@ -875,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) @@ -925,43 +965,72 @@ 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) { - Vector2 topLeft; - Vector2 bottomRight; - if (!config.ClosestToMouse) + if (config.CaptureFOVType == FovType.Rectangle) { - topLeft = new((screenSize.width - config.ImageWidth) / 2, (screenSize.height - config.ImageHeight) / 2); - bottomRight = new((screenSize.width + config.ImageWidth) / 2, (screenSize.height + config.ImageHeight) / 2); + Vector2 topLeft; + Vector2 bottomRight; + if (!config.ClosestToMouse) + { + topLeft = new((screenSize.width - config.ImageWidth) / 2, (screenSize.height - config.ImageHeight) / 2); + bottomRight = new((screenSize.width + config.ImageWidth) / 2, (screenSize.height + config.ImageHeight) / 2); + } + else + { + 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.CaptureFOVColor), 0.0f, ImDrawFlags.None, 1.0f); } - else + else if (config.CaptureFOVType == FovType.Circle) { - 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)); + 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); } - - - drawList.AddRect(topLeft, bottomRight, ImGui.GetColorU32(config.FOVColor), 0.0f, ImDrawFlags.None, 1.0f); } - else if (config.FOVType == FovType.Circle) + if (config.DrawAimFov) { - Vector2 center; - if (!config.ClosestToMouse) + if (config.AimFovType == FovType.Rectangle) { - center = new(screenSize.width / 2, screenSize.height / 2); + 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 + { + 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.AddRect(topLeft, bottomRight, ImGui.GetColorU32(config.AimFovColor), 0.0f, ImDrawFlags.None, 1.0f); } else { - _ = InputManager.GetCursorPos(out System.Drawing.Point mousePos); - center = ToOverlay(new Vector2(mousePos.X, mousePos.Y)); + 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); } + } + - drawList.AddCircle(center, config.ImageWidth / 2, ImGui.GetColorU32(config.FOVColor), 100, 1.0f); - } // added straight to drawlist to prevent caching/flickering } if (config.DebugMode) @@ -974,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; @@ -1094,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 + )); } } @@ -1178,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"; - } } } \ No newline at end of file diff --git a/Spectrum/Utilities/LogManager.cs b/Spectrum/Utilities/LogManager.cs index 5e28647..56c0708 100644 --- a/Spectrum/Utilities/LogManager.cs +++ b/Spectrum/Utilities/LogManager.cs @@ -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? 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 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 { } + try + { + mainConfig = Program.mainConfig; + } + catch { } } - bool debugEnabled = Debugger.IsAttached; - if (debugOverride.HasValue) - debugEnabled = debugOverride.Value; - try - { - debugEnabled = debugEnabled || (mainConfig?.Data?.DebugMode ?? false); - } - 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, + } + ); + } + + public static bool IsDebugEnabled() + { + if (mainConfig == null) { - FileName = "explorer.exe", - Arguments = Path.Combine(Directory.GetCurrentDirectory(), "bin", "logs"), - UseShellExecute = true - }); + 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; + } } } -} \ No newline at end of file +} diff --git a/Spectrum/Utilities/TimingStats.cs b/Spectrum/Utilities/TimingStats.cs index e63283e..4fc41d1 100644 --- a/Spectrum/Utilities/TimingStats.cs +++ b/Spectrum/Utilities/TimingStats.cs @@ -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 GetSnapshot(IEnumerable? orderedNames = null) { @@ -67,5 +76,31 @@ namespace Spectrum.Utilities return result; } } + public int GetCount(IEnumerable? 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"; + } } }