23 Commits
Author SHA1 Message Date
whoswhip a7604998d6 Merge branch 'master' of https://github.com/whoswhip/Spectrum 2026-08-30 10:33:22 -04:00
whoswhip e08e971bf9 old changes
all of these changes were done MONTHS ago, but i'll try to list them out:
- simplified input library switching & implementation
- implemented makcu binary, which is their new communication, have NOT tested
- renamed existing makcu implementation to makcuLegacy since they've changed their communication format
- overall simplification of code
- formatted code via csharpier
- minimal optimizations
2026-08-30 10:32:56 -04:00
whoswhip 2deaca09b0 Update README.md 2026-04-28 20:30:28 -04:00
whoswhip e7c5c4fff6 refactor: optimize permutation generation and replace static array with dynamic allocation 2026-04-12 16:06:59 -04:00
whoswhip 4225aeda33 refactor: implement InputLibrary Interface; make libraries support interface 2026-01-17 00:32:58 -05:00
whoswhip 92bea63815 feat: optimize detection loop; detailed performance statistics; selectable monitor via cli --monitor; forced debug mode via cli; configs auto update on file change; hid mouse movement; prevent super quick movements;
refactor: simplify log manager; simplify movement preview window; configs have their folder; remove maku movement (will be re added)
2026-01-16 17:13:37 -05:00
whoswhip 4e4a57a9b2 feat: improve screenshot capture by ensuring proper bitmap management and adjusting texture size 2026-01-16 14:10:01 -05:00
whoswhip 4d7dfffc5c feat: enhance adaptive movement with jitter for smoother transitions; simplify movement paths 2026-01-16 14:09:15 -05:00
whoswhip fa500f4c30 refactor: simplify imgui extensions 2026-01-16 14:08:08 -05:00
whoswhip c75c0551ee refactor: simplify hsv range window 2026-01-16 14:07:22 -05:00
whoswhip db712a54f9 feat: less obtrusive tooltips; Bounding box only tooltip 2026-01-16 14:05:28 -05:00
whoswhip 23a28d56ff refactor: improve readability and cleanup code 2025-11-10 17:36:13 -05:00
whoswhip b9756609ee feat: improve overshooting behavior to WindMouse 2025-11-10 17:35:54 -05:00
whoswhip 313cea1c35 feat: add configurable aimpoint types 2025-11-10 17:35:25 -05:00
whoswhip 378c189f03 fix: movement path preview 2025-11-08 16:32:25 -05:00
whoswhip 3b5ebc789b refactor: simplify movement logic and remove redundancy 2025-10-24 11:09:11 -04:00
whoswhip 8ca185a0fb chore: move renderer into its own folder 2025-10-22 20:41:19 -04:00
whoswhip 529576d972 feat: ensure anti capture visibility 2025-10-22 03:30:05 -04:00
whoswhip 153c719eb5 refactor: simplify canvas margin 2025-10-22 03:17:34 -04:00
whoswhip b0529cd841 feat: enhance movement preview rendering 2025-10-22 01:08:26 -04:00
whoswhip c66aa20fca feat:
- random trigger delay
- random trigger duration
- trigger spray mode
- trigger in bounds only
- anti capture
refactor:
- move system helper into Win32.cs
fix:
- only move mouse when holding the aim button
- load existing images on auto labeling start
2025-10-21 10:57:05 -04:00
whoswhip 57a3a1782b refactor: move overlay into its own tab 2025-10-18 17:42:55 -04:00
whoswhip daf595b47f refactor: simplify keybind checking 2025-10-18 17:42:34 -04:00
28 changed files with 2945 additions and 1581 deletions
+1
View File
@@ -361,3 +361,4 @@ MigrationBackup/
# Fody - auto-generated XML schema
FodyWeavers.xsd
Spectrum/imgui.ini
+2 -2
View File
@@ -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
View File
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 308 B

+249 -41
View File
@@ -1,29 +1,34 @@
using Newtonsoft.Json;
using OpenCvSharp;
using Spectrum.Utilities;
using System.Numerics;
using LogLevel = Spectrum.LogManager.LogLevel;
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum
{
public class ConfigManager<T> where T : new()
{
private readonly string _defaultFilename;
private readonly string _defaultFilePath;
private readonly string _configDirectory;
private FileSystemWatcher? _fileWatcher;
private FileSystemWatcher? _directoryWatcher;
private T _data;
private string _currentConfigName;
private List<string> _availableConfigs;
private string _currentFilePath;
private readonly List<string> _availableConfigs;
public T Data => _data;
public string CurrentConfigName => _currentConfigName;
public IReadOnlyList<string> AvailableConfigs => _availableConfigs.AsReadOnly();
public ConfigManager(string fileName, string configDirectory = "configs")
public ConfigManager(string defaultFilePath, string configDirectory = "")
{
_defaultFilename = fileName;
_configDirectory = configDirectory;
_currentConfigName = Path.GetFileNameWithoutExtension(fileName);
_defaultFilePath = defaultFilePath;
_configDirectory = string.IsNullOrWhiteSpace(configDirectory)
? Path.GetDirectoryName(defaultFilePath) ?? "configs"
: configDirectory;
_currentConfigName = Path.GetFileNameWithoutExtension(defaultFilePath);
_currentFilePath = defaultFilePath;
_data = new T();
_availableConfigs = [];
@@ -40,7 +45,7 @@ namespace Spectrum
public void LoadConfig(string filename = "")
{
if (string.IsNullOrEmpty(filename))
filename = _defaultFilename;
filename = _defaultFilePath;
try
{
@@ -51,6 +56,13 @@ namespace Spectrum
var json = File.ReadAllText(filename);
_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
{
@@ -71,17 +83,24 @@ namespace Spectrum
LogManager.Log($"Error loading config {filename}: {ex.Message}", LogLevel.Error);
_data = new T();
}
if (_fileWatcher != null)
{
StopFileWatcher();
StartFileWatcher();
}
}
public void SaveConfig(string filename = "")
{
if (string.IsNullOrEmpty(filename))
filename = _defaultFilename;
filename = _defaultFilePath;
try
{
File.WriteAllText(filename, JsonConvert.SerializeObject(_data, Formatting.Indented));
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
_currentFilePath = filename;
}
catch (Exception ex)
{
@@ -135,6 +154,7 @@ namespace Spectrum
.Select(Path.GetFileNameWithoutExtension)
.Where(name => !string.IsNullOrEmpty(name))
.Cast<string>()
.Where(name => !name.Equals(Path.GetFileNameWithoutExtension(_defaultFilePath), StringComparison.OrdinalIgnoreCase))
.ToList();
_availableConfigs.Clear();
@@ -259,7 +279,9 @@ namespace Spectrum
{
if (_fileWatcher != null) return;
_fileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _defaultFilename)
var directory = Path.GetDirectoryName(_currentFilePath) ?? Directory.GetCurrentDirectory();
var fileName = Path.GetFileName(_currentFilePath);
_fileWatcher = new FileSystemWatcher(directory, fileName)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
};
@@ -281,11 +303,11 @@ namespace Spectrum
Thread.Sleep(100);
try
{
LoadConfig();
LoadConfig(_currentFilePath);
}
catch (Exception ex)
{
LogManager.Log($"Failed to reload configuration for {_defaultFilename}: {ex.Message}", LogLevel.Error);
LogManager.Log($"Failed to reload configuration for {_currentFilePath}: {ex.Message}", LogLevel.Error);
}
}
@@ -296,27 +318,209 @@ namespace Spectrum
}
}
public class ColorConfigManager
{
private readonly string _colorsDirectory;
private readonly List<ColorInfo> _colors;
private readonly object _lock = new();
private int _version;
private FileSystemWatcher? _directoryWatcher;
public IReadOnlyList<ColorInfo> Colors => GetColorsSnapshot();
public int Version => _version;
public ColorConfigManager(string colorsDirectory)
{
_colorsDirectory = colorsDirectory;
_colors = [];
if (!Directory.Exists(_colorsDirectory))
Directory.CreateDirectory(_colorsDirectory);
Reload();
StartDirectoryWatcher();
}
public void Reload()
{
try
{
if (!Directory.Exists(_colorsDirectory))
return;
var loadedColors = new List<ColorInfo>();
var files = Directory.GetFiles(_colorsDirectory, "*.json")
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var file in files)
{
try
{
var json = File.ReadAllText(file);
var color = JsonConvert.DeserializeObject<ColorInfo>(json);
if (color == null)
continue;
if (string.IsNullOrWhiteSpace(color.Name))
color.Name = Path.GetFileNameWithoutExtension(file);
loadedColors.RemoveAll(c => c.Name.Equals(color.Name, StringComparison.OrdinalIgnoreCase));
loadedColors.Add(color);
}
catch (Exception ex)
{
LogManager.Log($"Failed to load color config {file}: {ex.Message}", LogLevel.Error);
}
}
lock (_lock)
{
_colors.Clear();
_colors.AddRange(loadedColors);
_version++;
}
}
catch (Exception ex)
{
LogManager.Log($"Error loading colors: {ex.Message}", LogLevel.Error);
}
}
public ColorInfo? GetColor(string name)
{
if (string.IsNullOrWhiteSpace(name))
return null;
lock (_lock)
{
return _colors.Find(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}
}
private List<ColorInfo> GetColorsSnapshot()
{
lock (_lock)
{
return [.. _colors];
}
}
public bool SaveColor(ColorInfo color)
{
if (string.IsNullOrWhiteSpace(color.Name))
{
LogManager.Log("Color name cannot be empty.", LogLevel.Error);
return false;
}
try
{
var filePath = GetColorFilePath(color.Name);
File.WriteAllText(filePath, JsonConvert.SerializeObject(color, Formatting.Indented));
Reload();
return true;
}
catch (Exception ex)
{
LogManager.Log($"Error saving color {color.Name}: {ex.Message}", LogLevel.Error);
return false;
}
}
public bool DeleteColor(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
LogManager.Log("Color name cannot be empty.", LogLevel.Error);
return false;
}
try
{
var filePath = GetColorFilePath(name);
if (!File.Exists(filePath))
{
LogManager.Log($"Color {name} not found.", LogLevel.Error);
return false;
}
File.Delete(filePath);
Reload();
return true;
}
catch (Exception ex)
{
LogManager.Log($"Error deleting color {name}: {ex.Message}", LogLevel.Error);
return false;
}
}
private string GetColorFilePath(string colorName)
{
var safeName = string.Join("_", colorName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
if (string.IsNullOrWhiteSpace(safeName))
safeName = "color";
return Path.Combine(_colorsDirectory, $"{safeName}.json");
}
private void StartDirectoryWatcher()
{
try
{
if (_directoryWatcher != null) return;
_directoryWatcher = new FileSystemWatcher(_colorsDirectory, "*.json")
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
};
_directoryWatcher.Created += OnDirectoryChanged;
_directoryWatcher.Deleted += OnDirectoryChanged;
_directoryWatcher.Renamed += OnDirectoryChanged;
_directoryWatcher.Changed += OnDirectoryChanged;
_directoryWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
LogManager.Log($"Error starting color directory watcher: {ex.Message}", LogLevel.Error);
}
}
private void OnDirectoryChanged(object sender, FileSystemEventArgs e)
{
Thread.Sleep(50);
Reload();
}
}
#region Enums
public enum MovementType
{
Linear,
CubicBezier,
QuadraticBezier,
Adaptive,
PerlinNoise,
WindMouse
}
public enum MovementMethod
public enum InputLibraryType
{
MouseEvent,
Makcu,
Arduino
Arduino,
HID,
MakcuBinary,
MakcuLegacy
}
public enum FovType
{
Circle,
Rectangle
}
public enum AimpointType
{
Crosshair,
Dot,
Circle
}
public enum CaptureMethod
{
GDI,
@@ -335,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
@@ -350,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;
@@ -368,63 +576,63 @@ namespace Spectrum
#region Trigger Settings
public bool TriggerBot { get; set; } = false;
public Keybind TriggerKeybind = new(Keys.XButton1, KeybindType.Hold);
public bool TriggerRandomDelay { get; set; } = false;
public int TriggerDelay { get; set; } = 50; // milliseconds
public int TriggerFov { get; set; } = 15; // pixels
public bool TriggerSpray = false; // if true ignore duration
public bool TriggerRandomDuration { get; set; } = false;
public int TriggerDuration { get; set; } = 100; // milliseconds
public bool TriggerInBoundsOnly { get; set; } = false;
public int TriggerFov { get; set; } = 15; // pixels
public bool DrawTriggerFov { get; set; } = false;
public Vector4 TriggerRadiusColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
#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
#region Data Collection Settings
public bool CollectData { get; set; } = false;
public bool AutoLabel { get; set; } = false;
public int BackgroundImageInterval { get; set; } = 10;
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;
#endregion
}
public class ColorData
{
public List<ColorInfo> Colors { get; set; } = [];
}
public class ColorInfo(string name, Scalar upper, Scalar lower)
{
public string Name { get; set; } = name;
public Scalar Upper { get; set; } = upper;
public Scalar Lower { get; set; } = lower;
}
public class Keybind
public class Keybind(Keys key, KeybindType type)
{
public Keys Key { get; set; }
public Keys Key { get; set; } = key;
public KeybindType Type { get; set; }
public Keybind(Keys key, KeybindType type)
{
Key = key;
Type = type;
}
public KeybindType Type { get; set; } = type;
}
}
+24 -10
View File
@@ -1,7 +1,8 @@
using OpenCvSharp;
using Spectrum.Utilities;
using System.Collections.Concurrent;
using System.Text;
using LogLevel = Spectrum.LogManager.LogLevel;
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Detection
{
@@ -9,20 +10,21 @@ namespace Spectrum.Detection
{
private static int imageCount = 0;
private static int detectionAttemps = 0;
private static readonly object lockObject = new object();
private static int labeledImageAttempts = 0;
private static readonly object lockObject = new();
private static CancellationTokenSource? cancellationTokenSource;
private static Task? backgroundTask;
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new();
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new();
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);
@@ -112,11 +114,18 @@ 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++;
if (labeledImageAttempts < mainConfig.Data.LabeledImageInterval)
return;
labeledImageAttempts = 0;
if (labelingQueue.Count > 250)
return;
@@ -136,6 +145,8 @@ namespace Spectrum.Detection
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
return;
detectionAttemps = 0;
if (backgroundQueue.Count > 250)
return;
@@ -206,6 +217,9 @@ namespace Spectrum.Detection
if (cancellationTokenSource != null)
return;
LogManager.Log("Starting auto labeling...", LogLevel.Info);
int existingImages = Directory.Exists("bin/dataset/images") ?
Directory.GetFiles("bin/dataset/images", "image_*.jpg").Length : 0;
imageCount = existingImages;
Started = true;
cancellationTokenSource = new CancellationTokenSource();
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
@@ -242,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
{
+23 -8
View File
@@ -16,6 +16,8 @@ namespace Spectrum.Detection
private IDXGIOutputDuplication? _duplication;
private ID3D11Texture2D? _stagingTex;
private Size _desktopSize;
private Bitmap? _captureBitmap;
private Size _captureBitmapSize;
public bool IsDirectXAvailable { get; private set; }
public bool IsInitialized => _device != null && _duplication != null && _stagingTex != null;
@@ -92,13 +94,14 @@ namespace Spectrum.Detection
bounds = Rectangle.Intersect(new Rectangle(Point.Empty, _desktopSize), bounds);
if (bounds.Width <= 0 || bounds.Height <= 0) return null;
EnsureStagingTexture(_desktopSize);
EnsureStagingTexture(new Size(bounds.Width, bounds.Height));
EnsureCaptureBitmap(new Size(bounds.Width, bounds.Height));
IDXGIResource? desktopResource = null;
bool frameAcquired = false;
try
{
var result = _duplication!.AcquireNextFrame(16, out var frameInfo, out desktopResource);
var result = _duplication!.AcquireNextFrame(0, out var frameInfo, out desktopResource);
if (result.Failure)
{
if (result.Code == unchecked((int)Vortice.DXGI.ResultCode.AccessLost) ||
@@ -115,15 +118,15 @@ namespace Spectrum.Detection
_context!.CopySubresourceRegion(
_stagingTex!,
0,
bounds.X,
bounds.Y,
0,
0,
0,
fullTex,
0,
new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1)
);
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
var bmp = _captureBitmap!;
var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);
var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height),
ImageLockMode.WriteOnly,
@@ -133,7 +136,7 @@ namespace Spectrum.Detection
{
unsafe
{
byte* srcBase = (byte*)map.DataPointer + bounds.Y * map.RowPitch + bounds.X * 4;
byte* srcBase = (byte*)map.DataPointer;
int srcStride = map.RowPitch;
int dstStride = bmpData.Stride;
int rowBytes = bounds.Width * 4;
@@ -154,7 +157,7 @@ namespace Spectrum.Detection
_context.Unmap(_stagingTex!, 0);
}
return bmp;
return bmp.Clone(new Rectangle(0, 0, bounds.Width, bounds.Height), PixelFormat.Format32bppArgb);
}
finally
{
@@ -190,7 +193,17 @@ namespace Spectrum.Detection
});
}
public Bitmap? CaptureScreenshotGdi(Rectangle bounds)
private void EnsureCaptureBitmap(Size size)
{
if (_captureBitmap != null && _captureBitmapSize.Width == size.Width && _captureBitmapSize.Height == size.Height)
return;
_captureBitmap?.Dispose();
_captureBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
_captureBitmapSize = size;
}
public static Bitmap? CaptureScreenshotGdi(Rectangle bounds)
{
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
using var g = Graphics.FromImage(bmp);
@@ -217,6 +230,8 @@ namespace Spectrum.Detection
lock (_sync)
{
DisposeDxgiResources();
_captureBitmap?.Dispose();
_captureBitmap = null;
}
GC.SuppressFinalize(this);
}
+184 -135
View File
@@ -1,23 +1,28 @@
using OpenCvSharp;
using Spectrum.Input;
using Spectrum.Utilities;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Numerics;
namespace Spectrum.Detection
{
class DetectionManager
{
private readonly Stopwatch stopwatch = new Stopwatch();
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
private readonly (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
private readonly int minArea;
private readonly Stopwatch stopwatch = new();
private Rectangle bounds = new(0, 0, 0, 0);
private readonly Rectangle monitorBounds = Program.MonitorBounds;
private readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private readonly Renderer? renderer;
private readonly Thread? _detectionThread;
private DateTime lastMenuToggle = DateTime.MinValue;
private readonly CaptureManager _captureManager;
private readonly Queue<double> processTimes = new Queue<double>(100);
private DateTime lastFpsUpdate = DateTime.Now;
private int frameCount = 0;
private Mat? hsvBuffer;
private Mat? maskBuffer;
private Mat? bgrBuffer;
private OpenCvSharp.Size bufferSize;
private OpenCvSharp.Size bgrBufferSize;
private static void AddTiming(string name, long ticks) => Program.Timings.Add(name, ticks);
public DetectionManager(Renderer renderer)
{
@@ -29,7 +34,6 @@ namespace Spectrum.Detection
Name = "Spectrum Detection Thread",
Priority = ThreadPriority.AboveNormal
};
minArea = (100 / 1440) * screenSize.Height;
_detectionThread.Start();
}
@@ -37,28 +41,31 @@ namespace Spectrum.Detection
{
while (true)
{
var config = mainConfig.Data;
try
{
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKeybind))
if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && (!config.ShowMenu || config.DebugMode))
{
var config = mainConfig.Data;
if (config.DebugMode)
stopwatch.Restart();
var t0 = Stopwatch.GetTimestamp();
renderer?.ClearDetectionDrawCommands();
if (!config.ClosestToMouse)
{
bounds = new Rectangle(
(screenSize.Width - config.ImageWidth) / 2,
(screenSize.Height - config.ImageHeight) / 2,
monitorBounds.X + (monitorBounds.Width - config.ImageWidth) / 2,
monitorBounds.Y + (monitorBounds.Height - config.ImageHeight) / 2,
config.ImageWidth,
config.ImageHeight
);
}
else
{
var tCursor = Stopwatch.GetTimestamp();
_ = InputManager.GetCursorPos(out System.Drawing.Point mousePos);
AddTiming("Get Cursor Pos", Stopwatch.GetTimestamp() - tCursor);
bounds = new Rectangle(
mousePos.X - (config.ImageWidth / 2),
mousePos.Y - (config.ImageHeight / 2),
@@ -67,8 +74,7 @@ namespace Spectrum.Detection
);
}
var screenRect = new Rectangle(0, 0, screenSize.Width, screenSize.Height);
bounds = Rectangle.Intersect(bounds, screenRect);
bounds = Rectangle.Intersect(bounds, monitorBounds);
if (bounds.Width <= 0 || bounds.Height <= 0)
{
renderer?.CommitDetectionDrawCommands();
@@ -77,96 +83,109 @@ namespace Spectrum.Detection
}
Bitmap? screenshot = null;
var tCapture = Stopwatch.GetTimestamp();
if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
{
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
var dxBounds = new Rectangle(
bounds.X - monitorBounds.X,
bounds.Y - monitorBounds.Y,
bounds.Width,
bounds.Height
);
screenshot = _captureManager.CaptureScreenshotDirectX(dxBounds);
}
else
{
if (_captureManager.IsInitialized)
_captureManager.Dispose();
screenshot = _captureManager.CaptureScreenshotGdi(bounds);
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;
}
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
var tMat = Stopwatch.GetTimestamp();
Mat mat = ConvertBitmapToMat(screenshot);
screenshot.Dispose();
AddTiming("Bitmap to Mat", Stopwatch.GetTimestamp() - tMat);
Mat? drawing = (config.AutoLabel || config.CollectData) ? mat.Clone() : null;
EnsureBuffers(mat.Size());
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
Cv2.InRange(mat, config.LowerHSV, config.UpperHSV, mat);
Cv2.Dilate(mat, mat, null, iterations: 2);
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
var tConvert = Stopwatch.GetTimestamp();
Cv2.CvtColor(mat, hsvBuffer!, ColorConversionCodes.BGR2HSV);
AddTiming("Color Conversion", Stopwatch.GetTimestamp() - tConvert);
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
var tRange = Stopwatch.GetTimestamp();
Cv2.InRange(hsvBuffer!, config.LowerHSV, config.UpperHSV, maskBuffer!);
AddTiming("Range Check", Stopwatch.GetTimestamp() - tRange);
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= minArea).ToArray();
var tDilate = Stopwatch.GetTimestamp();
Cv2.Dilate(maskBuffer!, maskBuffer!, null, iterations: 2);
AddTiming("Dilation", Stopwatch.GetTimestamp() - tDilate);
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).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);
}
if (closestContour != null)
AddTiming("Process Contours", Stopwatch.GetTimestamp() - tProcess);
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;
@@ -184,19 +203,30 @@ namespace Spectrum.Detection
if (config.DrawAimPoint)
{
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);
if (config.AimPointType == AimpointType.Crosshair)
{
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 Vector2(targetX, targetY), 5, config.AimPointColor, 20);
}
else if (config.AimPointType == AimpointType.Circle)
{
renderer!.AddCircle(new Vector2(targetX, targetY), 10, config.AimPointColor, 20);
}
}
if (config.AutoLabel && drawing != null)
if (config.AutoLabel)
{
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
AutoLabeling.AddBackgroundImage(drawing, true);
AutoLabeling.AddToQueue(mat, bounds, processedContours);
AutoLabeling.AddBackgroundImage(mat, true);
}
if (!config.AutoLabel && config.CollectData && drawing != null)
if (!config.AutoLabel && config.CollectData)
{
AutoLabeling.AddBackgroundImage(drawing, false);
AutoLabeling.AddBackgroundImage(mat, false);
}
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
@@ -206,59 +236,53 @@ namespace Spectrum.Detection
bestRect.Width,
bestRect.Height));
if (config.EnableAim)
if (config.EnableAim && InputManager.IsKeyOrMouseDown(config.Keybind))
{
var tMove = Stopwatch.GetTimestamp();
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)
if (renderer != null && config.DrawTriggerFov && config.TriggerBot && !config.TriggerInBoundsOnly)
{
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100);
}
}
}
else if (config.CollectData && drawing != null)
else if (config.CollectData)
{
AutoLabeling.AddBackgroundImage(drawing, false);
AutoLabeling.AddBackgroundImage(mat, false);
MovementPaths.ResetWindMouse();
}
renderer?.CommitDetectionDrawCommands();
mat.Dispose();
drawing?.Dispose();
if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel))
{
AutoLabeling.StartLabeling();
}
else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel)
{
AutoLabeling.StopLabeling();
}
if (config.DebugMode)
{
stopwatch.Stop();
double processTime = stopwatch.Elapsed.TotalMilliseconds;
processTimes.Enqueue(processTime);
if (processTimes.Count > 100)
processTimes.Dequeue();
frameCount++;
var now = DateTime.Now;
var timeSinceLastUpdate = (now - lastFpsUpdate).TotalSeconds;
if (timeSinceLastUpdate >= 1.0)
{
int fps = (int)(frameCount / timeSinceLastUpdate);
double avgProcessTime = processTimes.Count > 0 ? processTimes.Average() : 0;
Program.statistics = (fps, avgProcessTime);
frameCount = 0;
lastFpsUpdate = now;
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
@@ -266,62 +290,57 @@ namespace Spectrum.Detection
renderer?.ClearDetectionDrawCommands();
renderer?.CommitDetectionDrawCommands();
MovementPaths.ResetWindMouse();
Thread.Sleep(5);
}
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
if (InputManager.IsKeyOrMouseDown(config.MenuKey))
{
var now = DateTime.Now;
if ((now - lastMenuToggle).TotalMilliseconds > 175)
{
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
config.ShowMenu = !config.ShowMenu;
lastMenuToggle = now;
}
}
if (config.AntiCapture && !Win32.IsWindowHidden)
Win32.EnableAntiCapture(renderer!.window.Handle);
else if (!config.AntiCapture && Win32.IsWindowHidden)
Win32.DisableAntiCapture(renderer!.window.Handle);
}
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;
}
@@ -330,18 +349,48 @@ namespace Spectrum.Detection
}
} while (merged);
var mergedContours = new List<OpenCvSharp.Point[]>(contourRects.Count);
foreach (var (rect, indices) in contourRects)
{
var pointsList = new List<OpenCvSharp.Point>(indices.Count * 10);
foreach (var idx in indices)
{
pointsList.AddRange(contours[idx]);
return items.Select(x => Cv2.ConvexHull(x.Points)).ToList();
}
var hull = Cv2.ConvexHull(pointsList);
mergedContours.Add(hull);
private void EnsureBuffers(OpenCvSharp.Size size)
{
if (size == bufferSize && hsvBuffer != null && maskBuffer != null)
return;
hsvBuffer?.Dispose();
maskBuffer?.Dispose();
hsvBuffer = new Mat(size, MatType.CV_8UC3);
maskBuffer = new Mat(size, MatType.CV_8UC1);
bufferSize = size;
}
return mergedContours.ToArray();
private Mat ConvertBitmapToMat(Bitmap bitmap)
{
var size = new OpenCvSharp.Size(bitmap.Width, bitmap.Height);
if (bgrBuffer == null || size != bgrBufferSize)
{
bgrBuffer?.Dispose();
bgrBuffer = new Mat(size, MatType.CV_8UC4);
bgrBufferSize = size;
}
var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
var bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
try
{
unsafe
{
long bytesToCopy = (long)bmpData.Stride * bitmap.Height;
Buffer.MemoryCopy((void*)bmpData.Scan0, (void*)bgrBuffer.DataPointer, bytesToCopy, bytesToCopy);
}
}
finally
{
bitmap.UnlockBits(bmpData);
}
return bgrBuffer;
}
}
}
@@ -1,20 +1,25 @@
using System.Diagnostics;
using Spectrum.Utilities;
using System.Diagnostics;
using System.IO.Ports;
using LogLevel = Spectrum.LogManager.LogLevel;
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)
{
@@ -105,7 +110,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
return false;
}
public static void Close()
public void Dispose()
{
lock (sync)
{
@@ -129,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;
@@ -157,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;
@@ -187,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);
}
}
}
@@ -0,0 +1,316 @@
using HidSharp;
using Spectrum.Utilities;
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.HID
{
internal class HIDMain(int? vid = null, int? pid = null) : IInputLibrary, IDisposable
{
readonly int[] ExpectedVIDs =
[
0x046D,
0x1532,
0x1038,
0x1B1C,
0x0B05,
0x0951,
0x258A,
0x3057
];
public static readonly byte BUTTON_LEFT = 0x01;
public static readonly byte BUTTON_RIGHT = 0x02;
public static readonly byte BUTTON_MIDDLE = 0x04;
public static readonly byte BUTTON_BACK = 0x08;
public static readonly byte BUTTON_FORWARD = 0x10;
const byte CMD_MOVE = 0x01;
const byte CMD_CLICK = 0x02;
const byte CMD_PRESS = 0x03;
const byte CMD_RELEASE = 0x04;
const byte CMD_SCROLL = 0x05;
const byte CMD_PING = 0x09;
const byte HID_REPORT_ID_VENDOR = 0x06;
const int FEATURE_REPORT_SIZE = 64;
const int PING_TIMEOUT_MS = 500;
int vid = vid ?? 0, pid = pid ?? 0;
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()
{
var devices = DeviceList.Local.GetHidDevices();
foreach (var device in devices)
{
try
{
string name;
try { name = device.GetProductName(); }
catch { name = "<unavailable>"; }
LogManager.Log($"HIDMain: Found device: VID={device.VendorID:X4}, PID={device.ProductID:X4}, Name={name}", LogLevel.Debug);
}
catch (Exception e)
{
LogManager.Log($"HIDMain: Error accessing device info: {e.Message}", LogLevel.Debug);
}
}
return devices.Where(device =>
{
try
{
return
ExpectedVIDs.Contains(device.VendorID) &&
(vid == 0 || device.VendorID == vid) &&
(pid == 0 || device.ProductID == pid) &&
device.GetMaxFeatureReportLength() == FEATURE_REPORT_SIZE;
}
catch
{
return false;
}
});
}
private static bool TestDeviceWithPing(HidDevice dev, HidStream testStream)
{
try
{
byte[] pingPayload = [0x70, 0x69, 0x6E, 0x67, 0x70, 0x6F, 0x6E, 0x67];
byte[] pingPacket = new byte[FEATURE_REPORT_SIZE];
pingPacket[0] = HID_REPORT_ID_VENDOR;
pingPacket[1] = CMD_PING;
Array.Copy(pingPayload, 0, pingPacket, 2, pingPayload.Length);
LogManager.Log($"HIDMain: Sending ping to {dev.GetProductName()}...", LogLevel.Debug);
testStream.SetFeature(pingPacket);
Thread.Sleep(50);
byte[] response = new byte[FEATURE_REPORT_SIZE];
testStream.ReadTimeout = PING_TIMEOUT_MS;
int bytesRead = testStream.Read(response, 0, response.Length);
if (bytesRead > 0)
{
LogManager.Log($"HIDMain: Received {bytesRead} bytes from {dev.GetProductName()}", LogLevel.Debug);
if (response[1] == CMD_PING)
{
bool payloadMatches = true;
for (int i = 0; i < pingPayload.Length; i++)
{
if (response[2 + i] != pingPayload[i])
{
payloadMatches = false;
break;
}
}
if (payloadMatches)
{
LogManager.Log($"HIDMain: Ping successful for {dev.GetProductName()}", LogLevel.Debug);
return true;
}
else
{
string responseString = "";
for (int i = 0; i < bytesRead; i++)
{
responseString += $"0x{response[i]:X2} ";
}
LogManager.Log($"HIDMain: Ping response payload mismatch for {dev.GetProductName()}: {responseString}", LogLevel.Debug);
}
}
else
{
string responseString = "";
for (int i = 0; i < bytesRead; i++)
{
responseString += $"0x{response[i]:X2} ";
}
LogManager.Log($"HIDMain: Unexpected response from {dev.GetProductName()}: {responseString}", LogLevel.Debug);
}
}
else
{
LogManager.Log($"HIDMain: No response from {dev.GetProductName()}", LogLevel.Debug);
}
}
catch (TimeoutException)
{
LogManager.Log($"HIDMain: Ping timeout for {dev.GetProductName()}", LogLevel.Debug);
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Ping error for {dev.GetProductName()}: {ex.Message}", LogLevel.Debug);
}
return false;
}
private bool SendFeatureReport(byte[] data)
{
lock (_syncLock)
{
if (stream == null || device == null)
{
LogManager.Log("HIDMain: Device not connected.", LogLevel.Warning);
return false;
}
try
{
byte[] report = new byte[FEATURE_REPORT_SIZE];
report[0] = HID_REPORT_ID_VENDOR;
int copyLength = Math.Min(data.Length, FEATURE_REPORT_SIZE - 1);
Array.Copy(data, 0, report, 1, copyLength);
stream.SetFeature(report);
Thread.Sleep(10);
return true;
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Error sending feature report: {ex.Message}", LogLevel.Warning);
return false;
}
}
}
public void Move(int x, int y)
{
x = Math.Clamp(x, -127, 127);
y = Math.Clamp(y, -127, 127);
byte xByte = unchecked((byte)x);
byte yByte = unchecked((byte)y);
byte[] data = [CMD_MOVE, xByte, yByte];
SendFeatureReport(data);
}
public bool Click(byte button)
{
byte[] data = [CMD_CLICK, button];
bool success = SendFeatureReport(data);
return success;
}
public void Press(int button)
{
byte[] data = [CMD_PRESS, (byte)button];
SendFeatureReport(data);
}
public void Release(int button)
{
byte[] data = [CMD_RELEASE, (byte)button];
SendFeatureReport(data);
}
public bool Scroll(int amount)
{
amount = Math.Clamp(amount, -127, 127);
byte amountByte = unchecked((byte)amount);
byte[] data = [CMD_SCROLL, amountByte];
bool success = SendFeatureReport(data);
return success;
}
}
}
@@ -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;
}
}
}
}
@@ -1,112 +0,0 @@
using LogLevel = Spectrum.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.Makcu
{
internal class MakcuMain
{
public static MakcuMouse? MakcuInstance { get; private set; }
private static bool _isMakcuLoaded = false;
private static bool _isSubscribedToButtonEvents = false;
private const bool DefaultDebugLoggingForInternalCreation = false;
private const bool DefaultSendInitCommandsForInternalCreation = true;
public static void ConfigureMakcuInstance(bool debugEnabled, bool sendInitCmds)
{
LogManager.Log($"MakcuMain: Configuring MakcuInstance. Debug: {debugEnabled}, SendInitCmds: {sendInitCmds}", LogLevel.Debug);
UnsubscribeFromButtonEvents();
MakcuInstance?.Dispose();
MakcuInstance = new MakcuMouse(debugEnabled, sendInitCmds);
_isMakcuLoaded = false;
}
private static async Task<bool> InitializeMakcuDevice()
{
if (_isMakcuLoaded && MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
{
LogManager.Log("MakcuMain: InitializeMakcuDevice called, but Makcu is already loaded and connected.", LogLevel.Debug);
return true;
}
if (MakcuInstance == null)
{
ConfigureMakcuInstance(true, DefaultSendInitCommandsForInternalCreation);
}
try
{
if (MakcuInstance == null || !MakcuInstance.Init())
{
_isMakcuLoaded = false;
return false;
}
string? version = MakcuInstance.GetKmVersion();
_isMakcuLoaded = true;
SubscribeToButtonEvents();
return true;
}
catch
{
_isMakcuLoaded = false;
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
{
MakcuInstance.Close();
}
return false;
}
}
public static async Task<bool> Load() => await InitializeMakcuDevice();
public static void Unload()
{
UnsubscribeFromButtonEvents();
MakcuInstance?.Close();
_isMakcuLoaded = false;
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
}
private static void SubscribeToButtonEvents()
{
if (MakcuInstance != null && !_isSubscribedToButtonEvents)
{
MakcuInstance.ButtonStateChanged += OnMakcuButtonStateChanged;
_isSubscribedToButtonEvents = true;
LogManager.Log("MakcuMain: Subscribed to MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
}
}
private static void UnsubscribeFromButtonEvents()
{
if (MakcuInstance != null && _isSubscribedToButtonEvents)
{
MakcuInstance.ButtonStateChanged -= OnMakcuButtonStateChanged;
_isSubscribedToButtonEvents = false;
LogManager.Log("MakcuMain: Unsubscribed from MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
}
}
private static void OnMakcuButtonStateChanged(MakcuMouseButton button, bool isPressed)
{
string state = isPressed ? "Pressed" : "Released";
LogManager.Log($"{button} physical {state}!", LogLevel.Debug);
}
public static void DisposeInstance()
{
Unload();
MakcuInstance?.Dispose();
MakcuInstance = null;
_isMakcuLoaded = false;
LogManager.Log("MakcuMain: MakcuMouse instance disposed (null).", LogLevel.Debug);
}
}
}
@@ -1,598 +0,0 @@
using System.Diagnostics;
using System.IO.Ports;
using System.Text;
using LogLevel = Spectrum.LogManager.LogLevel;
/// https://github.com/sdfgasfgr/Aimmy-Makcu/blob/master/Aimmy2/MouseMovementLibraries/MakcuSupport/MakcuMouse.cs
namespace Spectrum.Input.InputLibraries.Makcu
{
public enum MakcuMouseButton
{
Left = 0, Right = 1, Middle = 2, Mouse4 = 3, Mouse5 = 4
}
public class MakcuMouse : IDisposable
{
private static readonly byte[] BaudChangeCommand = [0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00];
private SerialPort? _serialPort;
private readonly bool _debugLogging;
private readonly bool _sendInitCommands;
private readonly object _serialLock = new();
private bool _isInitializedAndConnected = false;
private Thread? _listenerThread;
private ManualResetEventSlim _stopListenerEvent = new(false);
private volatile bool _pauseListener = false;
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = [];
public event Action<MakcuMouseButton, bool>? ButtonStateChanged;
public string? PortName { get; private set; }
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
public MakcuMouse(bool debugLogging = false, bool sendInitCommands = true)
{
_debugLogging = debugLogging;
_sendInitCommands = sendInitCommands;
foreach (MakcuMouseButton btn in Enum.GetValues(typeof(MakcuMouseButton)))
{
_buttonStates[btn] = false;
}
}
private void Log(string message)
{
if (_debugLogging)
{
LogManager.Log($"[MakcuMouse {DateTime.Now:HH:mm:ss}] {message}", LogLevel.Debug);
}
}
private string FindComPortInternal()
{
Log("Searching for COM port for Makcu device using SerialPort.GetPortNames() and connection test...");
string[] availablePorts;
try
{
availablePorts = SerialPort.GetPortNames();
}
catch (Exception ex)
{
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
return "";
}
if (availablePorts == null || availablePorts.Length == 0)
{
Log("No COM ports available according to SerialPort.GetPortNames().");
return "";
}
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
foreach (string portName in availablePorts)
{
Log($"Testing port: {portName}");
SerialPort? testPort = null;
try
{
testPort = new SerialPort(portName, 115200)
{
ReadTimeout = 250,
WriteTimeout = 500,
DtrEnable = true,
RtsEnable = true
};
testPort.Open();
Log($"Port {portName} opened at 115200 baud.");
Log($"Sending command to change baudrate to 4M on {portName}.");
testPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
testPort.BaseStream.Flush();
Thread.Sleep(150);
testPort.Close();
testPort.BaudRate = 4000000;
testPort.Open();
Log($"Port {portName} reopened at 4000000 baud.");
testPort.DiscardInBuffer();
testPort.Write("km.version()\r\n");
Log($"Command 'km.version()' sent to {portName}. Waiting for response...");
string response = "";
try
{
response = testPort.ReadLine().Trim();
}
catch (TimeoutException)
{
Log($"Timeout waiting for 'km.version()' response on {portName}. Probably not the Makcu device.");
testPort.Close();
continue;
}
Log($"Response from 'km.version()' on {portName}: '{response}'");
if (!string.IsNullOrEmpty(response) && (response.Contains("KMBOX") || response.Contains("Makcu") || response.Contains("MAKCU") || response.StartsWith('v') || char.IsDigit(response.FirstOrDefault())))
{
Log($"Makcu device found on port: {portName}! Version response: '{response}'");
testPort.Close();
return portName;
}
else
{
Log($"Response from 'km.version()' on {portName} does not seem to be from a Makcu device. Response: '{response}'");
}
testPort.Close();
}
catch (UnauthorizedAccessException ex)
{
Log($"Unauthorized access error on {portName}: {ex.Message} (Port might be in use).");
}
catch (TimeoutException ex)
{
Log($"Timeout on {portName} (possibly during baud rate change or write): {ex.Message}");
}
catch (Exception ex)
{
Log($"Failed to test port {portName}: {ex.GetType().Name} - {ex.Message}");
}
finally
{
if (testPort != null && testPort.IsOpen)
{
testPort.Close();
}
testPort?.Dispose();
}
}
Log("Makcu device not found on any available COM ports after connection test.");
return "";
}
private bool OpenSerialPort(string portNameToOpen, int baudRate)
{
try
{
_serialPort?.Close();
_serialPort?.Dispose();
Log($"Attempting to open {portNameToOpen} at {baudRate} baud.");
_serialPort = new SerialPort(portNameToOpen, baudRate)
{
ReadTimeout = 100,
WriteTimeout = 500,
DtrEnable = true,
RtsEnable = true
};
_serialPort.Open();
PortName = portNameToOpen;
return true;
}
catch (Exception ex)
{
Log($"Failed to open {portNameToOpen} at {baudRate} baud. Error: {ex.Message}");
_serialPort?.Dispose(); _serialPort = null; return false;
}
}
private bool ChangeBaudRateTo4M()
{
if (_serialPort == null || !_serialPort.IsOpen)
{
Log("ChangeBaudRateTo4M: _serialPort is null or not open.");
return false;
}
Log("Sending command to change baudrate to 4M.");
try
{
_serialPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
_serialPort.BaseStream.Flush();
Thread.Sleep(150);
string currentPortName = _serialPort.PortName;
_serialPort.Close();
_serialPort.BaudRate = 4000000;
_serialPort.Open();
Log("Successfully changed to 4M baud."); return true;
}
catch (Exception ex)
{
Log($"Error changing baudrate to 4M: {ex.Message}");
_serialPort?.Close();
return false;
}
}
public bool Init()
{
lock (_serialLock)
{
if (_isInitializedAndConnected) { Log("MakcuMouse is already initialized."); return true; }
string portToUse = FindComPortInternal();
if (string.IsNullOrEmpty(portToUse))
{ Log("Init failed: Could not find a valid COM port for Makcu."); return false; }
if (!OpenSerialPort(portToUse, 115200))
{ Log($"Init failed: Could not open port {portToUse} at 115200 baud."); return false; }
if (!ChangeBaudRateTo4M())
{ Log("Init failed: Could not change to 4M baud."); Close(); return false; }
_isInitializedAndConnected = true;
PortName = portToUse;
if (_sendInitCommands)
{
if (!SendCommandInternal("km.buttons(1)", false, out _))
{ Log("Init failed: Could not send 'km.buttons(1)'."); Close(); return false; }
_stopListenerEvent.Reset();
_listenerThread = new Thread(() => ListenForButtonEvents(_debugLogging))
{ IsBackground = true, Name = "MakcuButtonListener" };
_listenerThread.Start();
}
Log($"MakcuMouse initialized successfully on port {PortName} at {BaudRate} baud."); return true;
}
}
private bool SendCommandInternal(string command, bool expectResponse, out string? responseText, int responseTimeoutMs = 200)
{
responseText = null;
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
{
Log($"Error in SendCommand: Connection not open or initialized. Command: {command}");
return false;
}
lock (_serialLock)
{
if (!_serialPort.IsOpen)
{
Log($"Error in SendCommand (lock): Port not open. Command: {command}");
return false;
}
_pauseListener = true;
int originalReadTimeout = _serialPort.ReadTimeout;
try
{
if (expectResponse)
{
_serialPort.ReadTimeout = responseTimeoutMs;
_serialPort.DiscardInBuffer();
}
Log($"Sending: {command}");
_serialPort.Write(command + "\r\n");
if (expectResponse)
{
var stopwatch = Stopwatch.StartNew();
StringBuilder sb = new();
string commandTrimmed = command.Trim();
bool firstLineIsEcho = true;
while (stopwatch.ElapsedMilliseconds < responseTimeoutMs)
{
try
{
string line = _serialPort.ReadLine().Trim();
if (!string.IsNullOrEmpty(line))
{
Log($"Received (raw): {line}");
if (line.Equals(commandTrimmed, StringComparison.OrdinalIgnoreCase) && firstLineIsEcho)
{
firstLineIsEcho = false;
continue;
}
if (line.Equals("OK", StringComparison.OrdinalIgnoreCase))
{
if (sb.Length > 0) continue;
}
if (sb.Length > 0) sb.Append('\n');
sb.Append(line);
}
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
{
Thread.Sleep(15);
if (_serialPort.BytesToRead == 0) break;
}
}
catch (TimeoutException)
{
Log($"ReadLine() timeout in SendCommandInternal for '{command}'.");
break;
}
catch (InvalidOperationException ioe) { Log($"InvalidOperationException in ReadLine (SendCommandInternal): {ioe.Message}"); _isInitializedAndConnected = false; Close(); return false; }
catch (Exception ex) { Log($"Exception in ReadLine (SendCommandInternal): {ex.Message}"); break; }
}
stopwatch.Stop();
responseText = sb.ToString().Trim();
Log($"Final response for '{command}': '{responseText}' (Time: {stopwatch.ElapsedMilliseconds}ms)");
return true;
}
return true;
}
catch (TimeoutException tex)
{
Log($"General timeout in SendCommandInternal for '{command}': {tex.Message}");
return false;
}
catch (InvalidOperationException ioe)
{
Log($"General InvalidOperationException in SendCommandInternal (possibly port closed): {ioe.Message}");
_isInitializedAndConnected = false; Close();
return false;
}
catch (Exception ex)
{
Log($"General exception in SendCommandInternal for '{command}': {ex.Message}");
return false;
}
finally
{
_pauseListener = false;
if (expectResponse)
{
_serialPort.ReadTimeout = originalReadTimeout;
}
}
}
}
private void ListenForButtonEvents(bool debug)
{
Log("Listener thread started. (PACKET PARSING MODE)");
byte lastMask = 0x00; // <<-- CAMBIO CLAVE: Inicializar como todos los botones liberados
var buttonMap = new Dictionary<int, MakcuMouseButton> {
{0, MakcuMouseButton.Left}, {1, MakcuMouseButton.Right}, {2, MakcuMouseButton.Middle},
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
};
byte[] packetHeader = [0x6B, 0x6D, 0x2E];
int currentHeaderIndex = 0;
while (!_stopListenerEvent.IsSet)
{
if (!IsInitializedAndConnected || _pauseListener || _serialPort == null || !_serialPort.IsOpen)
{
Thread.Sleep(20);
currentHeaderIndex = 0;
continue;
}
try
{
if (_serialPort.BytesToRead > 0)
{
byte byteRead = (byte)_serialPort.ReadByte();
if (byteRead == packetHeader[currentHeaderIndex])
{
currentHeaderIndex++;
if (currentHeaderIndex == packetHeader.Length)
{
if (debug) Log($"Listener: Packet header {string.Join(",", packetHeader.Select(b => b.ToString("X2")))} detected!");
if (_serialPort.BytesToRead > 0)
{
byte currentMask = (byte)_serialPort.ReadByte();
if (debug) Log($"Listener: Potential button mask byte: 0x{currentMask:X2}");
if (currentMask <= 0b00011111)
{
if (currentMask != lastMask)
{
if (debug) Log($"Listener: Processing button mask. New: 0x{currentMask:X2}, Prev: 0x{lastMask:X2}");
byte changedBits = (byte)(currentMask ^ lastMask);
lock (_buttonStates)
{
foreach (var pair in buttonMap)
{
if ((changedBits & (1 << pair.Key)) != 0)
{
bool isPressed = (currentMask & (1 << pair.Key)) != 0;
_buttonStates[pair.Value] = isPressed;
if (debug) Log($"Listener: ---> EVENT: Button: {pair.Value}, IsPressed: {isPressed}");
try
{
ButtonStateChanged?.Invoke(pair.Value, isPressed);
}
catch (Exception ex)
{
Log($"Exception in ButtonStateChanged handler: {ex.Message}");
}
}
}
}
lastMask = currentMask;
if (debug)
{
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Length != 0 ? string.Join(", ", pressedButtons) : "None")}");
}
}
}
int expectedTailBytes = 2;
for (int i = 0; i < expectedTailBytes; i++)
{
if (_serialPort.BytesToRead > 0)
{
byte consumedByte = (byte)_serialPort.ReadByte();
if (debug) Log($"Listener: Consumed tail byte {i + 1}: 0x{consumedByte:X2}");
}
else
{
if (debug) Log($"Listener: Expected tail byte {i + 1} but no data. Packet might be short.");
break;
}
}
}
else
{
if (debug) Log("Listener: Header found, but no data for button mask byte. Packet might be short.");
}
currentHeaderIndex = 0;
}
}
else
{
if (currentHeaderIndex > 0 && debug)
{
Log($"Listener: Byte 0x{byteRead:X2} broke header sequence at index {currentHeaderIndex}. Resetting search.");
}
currentHeaderIndex = 0;
if (byteRead == packetHeader[0])
{
currentHeaderIndex = 1;
}
}
}
else
{
Thread.Sleep(1);
}
}
catch (TimeoutException)
{
if (debug) Log("Listener: TimeoutException during serial read.");
currentHeaderIndex = 0;
}
catch (InvalidOperationException ex)
{
Log($"Listener: InvalidOperationException (port probably closed): {ex.Message}. Stopping listener.");
_isInitializedAndConnected = false;
currentHeaderIndex = 0;
break;
}
catch (Exception ex)
{
Log($"Error in listener: {ex.GetType().Name} - {ex.Message}");
currentHeaderIndex = 0;
Thread.Sleep(100);
}
}
Log("Listener thread terminated.");
}
public bool Press(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(1)", false, out _);
public bool Release(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(0)", false, out _);
public bool Move(int x, int y) => SendCommandInternal($"km.move({x},{y})", false, out _);
public bool MoveSmooth(int x, int y, int segments) => SendCommandInternal($"km.move({x},{y},{segments})", false, out _);
public bool MoveBezier(int x, int y, int segments, int ctrlX, int ctrlY) => SendCommandInternal($"km.move({x},{y},{segments},{ctrlX},{ctrlY})", false, out _);
public bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _);
public string? GetKmVersion()
{
return SendCommandInternal("km.version()", true, out string? response, 500) ? response : null;
}
private static string GetButtonString(MakcuMouseButton button)
{
switch (button)
{
case MakcuMouseButton.Left: return "left";
case MakcuMouseButton.Right: return "right";
case MakcuMouseButton.Middle: return "middle";
default: throw new ArgumentException($"Button {button} not supported for direct press/release actions (left/right/middle).");
}
}
private string GetButtonLockString(MakcuMouseButton button)
{
switch (button)
{
case MakcuMouseButton.Left: return "ml";
case MakcuMouseButton.Right: return "mr";
case MakcuMouseButton.Middle: return "mm";
case MakcuMouseButton.Mouse4: return "ms1";
case MakcuMouseButton.Mouse5: return "ms2";
default: throw new ArgumentException($"Button not supported for lock/catch: {button}");
}
}
public Dictionary<MakcuMouseButton, bool> GetCurrentButtonStates()
{ lock (_buttonStates) { return new Dictionary<MakcuMouseButton, bool>(_buttonStates); } }
public int GetCurrentButtonMask()
{
int mask = 0;
lock (_buttonStates)
{
if (_buttonStates.TryGetValue(MakcuMouseButton.Left, out bool l) && l) mask |= (1 << (int)MakcuMouseButton.Left);
if (_buttonStates.TryGetValue(MakcuMouseButton.Right, out bool r) && r) mask |= (1 << (int)MakcuMouseButton.Right);
if (_buttonStates.TryGetValue(MakcuMouseButton.Middle, out bool m) && m) mask |= (1 << (int)MakcuMouseButton.Middle);
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse4, out bool m4) && m4) mask |= (1 << (int)MakcuMouseButton.Mouse4);
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse5, out bool m5) && m5) mask |= (1 << (int)MakcuMouseButton.Mouse5);
}
return mask;
}
private bool _disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
Close();
_stopListenerEvent?.Dispose();
}
_disposedValue = true;
}
}
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
~MakcuMouse() { Dispose(false); }
public void Close()
{
Log("Closing MakcuMouse connection...");
_isInitializedAndConnected = false;
if (_listenerThread != null)
{
_stopListenerEvent.Set();
if (_listenerThread.IsAlive)
{
if (!_listenerThread.Join(TimeSpan.FromSeconds(1)))
{
Log("Listener thread did not terminate in time.");
}
}
_listenerThread = null;
}
lock (_serialLock)
{
if (_serialPort != null)
{
if (_serialPort.IsOpen)
{
try { _serialPort.Close(); }
catch (Exception ex) { Log($"Error closing port: {ex.Message}"); }
}
_serialPort.Dispose();
_serialPort = null;
}
}
PortName = null;
Log("MakcuMouse connection closed.");
}
}
}
@@ -0,0 +1,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);
uint downFlag = button switch
{
0x01 => 0x0002, // left: down
0x02 => 0x0008, // right: down
0x03 => 0x0020, // middle: down
_ => 0
};
if (downFlag != 0)
mouse_event(downFlag, 0, 0, 0, 0);
}
public static void ClickUp()
public void Release(int button)
{
mouse_event(0x0004, 0, 0, 0, 0);
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);
}
}
}
+239 -171
View File
@@ -1,8 +1,11 @@
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Input.InputLibraries.Makcu;
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
{
@@ -10,11 +13,17 @@ namespace Spectrum.Input
{
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point lpPoint);
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private static Point lastDetection = new Point();
private static Rectangle lastDetectionBox = new Rectangle();
private static readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private static Point lastDetection = new();
private static Point _prevEnd = new();
private static Rectangle lastDetectionBox = new();
private static long _lastMoveTicks = 0;
private static readonly double _dtRef = 1.0 / 120.0;
private static bool isSpraying = false;
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()
{
@@ -39,7 +48,7 @@ namespace Spectrum.Input
if (baseFactor >= 1)
{
double k = deltaSeconds / _dtRef;
return baseFactor * k;
return Math.Pow(baseFactor, 3) * k;
}
double kLow = deltaSeconds / _dtRef;
return 1 - Math.Pow(1 - baseFactor, kLow);
@@ -48,41 +57,54 @@ namespace Spectrum.Input
public static void MoveMouse()
{
var config = mainConfig.Data;
Point reference = new Point();
Point reference = new();
if (config.ClosestToMouse)
{
GetCursorPos(out reference);
}
else
{
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
var bounds = Program.MonitorBounds;
reference.X = bounds.X + bounds.Width / 2;
reference.Y = bounds.Y + bounds.Height / 2;
}
Point start = new Point(reference.X, reference.Y);
Point end = new Point(lastDetection.X, lastDetection.Y);
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);
double dt = GetDeltaSeconds();
double tDist = Math.Sqrt(Math.Pow(end.X - _prevEnd.X, 2) + Math.Pow(end.Y - _prevEnd.Y, 2));
if (tDist > 150 || dt > 0.1) MovementPaths.ResetWindMouse();
_prevEnd = end;
double effSensitivity = TimeScaleFactor(config.Sensitivity, dt);
bool insideBoundingBox = lastDetectionBox.Contains(start);
Point newPosition = config.AimMovementType switch
{
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(start, end, effSensitivity),
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, effSensitivity),
MovementType.WindMouse => MovementPaths.WindMouse(start, end,
config.WindMouseGravity,
config.WindMouseWind,
config.WindMouseMaxStep,
effSensitivity,
config.WindMouseOvershoot,
insideBoundingBox),
_ => MovementPaths.LinearInterpolation(start, end, effSensitivity),
};
var tPath = Stopwatch.GetTimestamp();
Point newPosition = CalculateMovement(start, end, effSensitivity, config.AimMovementType, insideBoundingBox);
Program.Timings.Add("Movement Path", Stopwatch.GetTimestamp() - tPath);
if (config.EmaSmoothening)
{
@@ -94,37 +116,67 @@ namespace Spectrum.Input
int deltaX = newPosition.X - reference.X;
int deltaY = newPosition.Y - reference.Y;
double maxMove = config.ClosestToMouse ? 75.0 : 120.0;
double moveDist = Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
if (moveDist > maxMove)
{
double r = maxMove / moveDist;
deltaX = (int)Math.Round(deltaX * r);
deltaY = (int)Math.Round(deltaY * r);
}
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
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.Makcu:
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
else
MouseEvent.Move(deltaX, deltaY);
case InputLibraryType.Arduino:
if (ArduinoMain.Instance != null && ArduinoMain.Instance.IsConnected)
ArduinoMain.Instance.Move(deltaX, deltaY);
break;
case MovementMethod.Arduino:
ArduinoMain.Move(deltaX, deltaY);
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
{
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(start, end, sensitivity),
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity),
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity),
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity),
MovementType.WindMouse => MovementPaths.WindMouse(start, end,
mainConfig.Data.WindMouseGravity,
mainConfig.Data.WindMouseWind,
mainConfig.Data.WindMouseMaxStep,
sensitivity,
mainConfig.Data.WindMouseOvershoot,
insideBoundingBox),
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
};
}
public static async Task ClickMouse()
{
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)
@@ -133,58 +185,99 @@ namespace Spectrum.Input
}
else
{
currentPosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
var bounds = Program.MonitorBounds;
currentPosition.X = bounds.X + bounds.Width / 2;
currentPosition.Y = bounds.Y + bounds.Height / 2;
}
if (config.TriggerDelay > 0)
if (config.TriggerDelay > 0 && !config.TriggerRandomDelay)
await Task.Delay(config.TriggerDelay);
else if (config.TriggerRandomDelay)
await Task.Delay(Random.Shared.Next(10, config.TriggerDelay + 1));
int radius = config.TriggerFov;
bool shouldClick;
if (config.TriggerInBoundsOnly)
shouldClick = lastDetectionBox.Contains(currentPosition);
else
shouldClick = Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius;
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
if (shouldClick)
{
switch (config.MovementMethod)
if (config.TriggerSpray && !isSpraying)
{
case MovementMethod.MouseEvent:
MouseEvent.ClickDown();
break;
case MovementMethod.Makcu:
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
else
MouseEvent.ClickDown();
break;
case MovementMethod.Arduino:
ArduinoMain.ClickDown();
break;
default:
MouseEvent.ClickDown();
break;
isSpraying = true;
ClickDown(config.InputLibraryType);
}
else if (!config.TriggerSpray)
{
ClickDown(config.InputLibraryType);
}
if (!config.TriggerRandomDuration && !config.TriggerSpray)
await Task.Delay(config.TriggerDuration);
switch (config.MovementMethod)
{
case MovementMethod.MouseEvent:
MouseEvent.ClickUp();
break;
case MovementMethod.Makcu:
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
else if (!config.TriggerSpray)
await Task.Delay(Random.Shared.Next(20, config.TriggerDuration));
if (!config.TriggerSpray)
ClickUp(config.InputLibraryType);
}
else
MouseEvent.ClickUp();
{
if (isSpraying)
{
isSpraying = false;
ClickUp(config.InputLibraryType);
}
}
}
private static void ClickDown(InputLibraryType movementMethod)
{
switch (movementMethod)
{
case InputLibraryType.MouseEvent:
MouseMain.Instance.Press(0x01);
break;
case MovementMethod.Arduino:
ArduinoMain.ClickUp();
case InputLibraryType.Arduino:
if (ArduinoMain.Instance != null && ArduinoMain.Instance.IsConnected)
ArduinoMain.Instance.Press(0x01);
break;
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.ClickUp();
MouseMain.Instance.Press(0x01);
break;
}
}
else
private static void ClickUp(InputLibraryType movementMethod)
{
var dist = Math.Sqrt(Math.Pow(currentPosition.X - lastDetection.X, 2) + Math.Pow(currentPosition.Y - lastDetection.Y, 2));
switch (movementMethod)
{
case InputLibraryType.MouseEvent:
MouseMain.Instance.Release(0x01);
break;
case InputLibraryType.Arduino:
ArduinoMain.Instance.Release(0x01);
break;
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:
MouseMain.Instance.Release(0x01);
break;
}
}
@@ -204,24 +297,18 @@ namespace Spectrum.Input
{
var tcs = new TaskCompletionSource<Keys>(TaskCreationOptions.RunContinuationsAsynchronously);
Action<MakcuMouseButton, bool>? makcuHandler = null;
bool subscribedToMakcu = false;
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
CancellationTokenRegistration ctr = default;
if (cancellationToken?.CanBeCanceled == true)
{
makcuHandler = (btn, isPressed) =>
{
if (!isPressed) return;
var key = MapMakcuButtonToKeys(btn);
if (key.HasValue)
{
tcs.TrySetResult(key.Value);
}
};
MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler;
subscribedToMakcu = true;
ctr = cancellationToken.Value.Register(() => tcs.TrySetCanceled());
}
var thread = new Thread(() =>
_ = tcs.Task.ContinueWith(_ =>
{
try { ctr.Dispose(); } catch { }
}, TaskScheduler.Default);
Task.Run(() =>
{
try
{
@@ -231,6 +318,16 @@ namespace Spectrum.Input
{
return;
}
foreach (var mouseKey in MouseKeys)
{
if (IsKeyOrMouseDown(mouseKey))
{
tcs.TrySetResult(mouseKey);
return;
}
}
for (int key = 0x08; key <= 0xFE; key++)
{
if ((GetAsyncKeyState(key) & 0x8000) != 0)
@@ -240,15 +337,6 @@ namespace Spectrum.Input
}
}
foreach (var mouseKey in MouseKeys)
{
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
{
tcs.TrySetResult(mouseKey);
return;
}
}
if (cancellationToken?.IsCancellationRequested == true)
{
tcs.TrySetCanceled();
@@ -259,81 +347,74 @@ namespace Spectrum.Input
}
finally
{
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
{
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
}
}
})
{ IsBackground = true };
});
tcs.Task.ContinueWith(_ =>
{
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
{
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
}
}, TaskScheduler.Default);
thread.Start();
return tcs.Task;
}
private static bool EnsureMakcuReady()
{
try
{
if (MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
var ok = MakcuMain.Load().GetAwaiter().GetResult();
if (ok && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
LogManager.Log("Makcu not ready. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
MakcuMain.Unload();
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
return false;
}
catch
{
LogManager.Log("Makcu initialization threw an exception. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
MakcuMain.Unload();
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
return false;
}
}
private static Keys? MapMakcuButtonToKeys(MakcuMouseButton btn)
{
return btn switch
{
MakcuMouseButton.Left => Keys.LButton,
MakcuMouseButton.Right => Keys.RButton,
MakcuMouseButton.Middle => Keys.MButton,
MakcuMouseButton.Mouse4 => Keys.XButton1,
MakcuMouseButton.Mouse5 => Keys.XButton2,
_ => null
};
}
public static bool IsKeyOrMouseDown(Keys key)
{
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true)
if (IsMouseKey(key) && EnsureMakcuReady())
{
var makcuBtn = MapKeysToMakcuButton(key);
if (makcuBtn.HasValue)
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
{
var states = MakcuMain.MakcuInstance.GetCurrentButtonStates();
return states.TryGetValue(makcuBtn.Value, out var pressed) && pressed;
}
catch { }
if (MakcuBinaryMain.Instance.Initialize())
{
MakcuBinaryMain.Instance.ButtonsChanged += OnMakcuButtonsChanged;
makcuReady = true;
return true;
}
}
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
catch
{
}
return false;
}
}
private static readonly Dictionary<string, bool> _keybindToggleStates = new();
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)
{
@@ -362,18 +443,5 @@ namespace Spectrum.Input
return _keybindToggleStates[toggleKey];
}
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
{
return key switch
{
Keys.LButton => MakcuMouseButton.Left,
Keys.RButton => MakcuMouseButton.Right,
Keys.MButton => MakcuMouseButton.Middle,
Keys.XButton1 => MakcuMouseButton.Mouse4,
Keys.XButton2 => MakcuMouseButton.Mouse5,
_ => null
};
}
}
}
+86 -45
View File
@@ -1,27 +1,19 @@
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 Point(0, 0);
private static Point _lastMove = new(0, 0);
private static double _windX = 0.0;
private static double _windY = 0.0;
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;
}
@@ -57,8 +49,8 @@
public static Point CubicBezierMovement(Point start, Point end, double t)
{
t = Clamp01(t);
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
Point control1 = new(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
Point control2 = new(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
return CubicBezier(start, end, control1, control2, t);
}
@@ -86,36 +78,23 @@
return new Point(x, y);
}
public static Point CurvedMovement(Point start, Point end, double t)
{
t = Clamp01(t);
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
return QuadraticBezier(start, end, control, t);
}
public static Point QuadraticBezier(Point start, Point end, Point control, double t)
{
t = Clamp01(t);
double u = 1 - t;
double tt = t * t;
double uu = u * u;
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
return new Point((int)Math.Round(x), (int)Math.Round(y));
}
public static Point AdaptiveMovement(Point start, Point end, double sensitivity)
{
double dx = end.X - start.X;
double dy = end.Y - start.Y;
double distance = Math.Sqrt(dx * dx + dy * dy);
if (distance == 0) return start;
double stepSize = Math.Max(0, sensitivity) * distance;
if (distance < 1) return end;
double maxStep = 50.0 + (sensitivity * 20.0);
double adaptiveStep = sensitivity * (1.0 + (distance / 800.0));
double stepSize = Math.Min(distance * adaptiveStep, maxStep);
stepSize = Math.Min(stepSize, distance);
double directionX = dx / distance;
double directionY = dy / distance;
int newX = (int)Math.Round(start.X + directionX * stepSize);
int newY = (int)Math.Round(start.Y + directionY * stepSize);
return new Point(newX, newY);
double ux = dx / distance;
double uy = dy / distance;
double jitterMag = Math.Min(Math.Sqrt(distance), 20.0) * sensitivity * 0.15;
double jitter = (Random.Shared.NextDouble() - 0.5) * jitterMag;
int nx = (int)Math.Round(start.X + ux * stepSize + (-uy * jitter));
int ny = (int)Math.Round(start.Y + uy * stepSize + (ux * jitter));
return new Point(nx, ny);
}
public static Point PerlinNoiseMovement(Point start, Point end, double t, double amplitudeFraction = 0.2, double frequency = 1.5)
{
@@ -156,6 +135,9 @@
return new Point(x, y);
}
private static bool _isOvershooting = false;
private static Point _overshootTarget = new(0, 0);
public static Point WindMouse(Point start, Point end, double gravity = 9.0, double wind = 3.0,
double maxStep = 10.0, double sensitivity = 1.0, bool enableOvershoot = false, bool insideBoundingBox = false)
{
@@ -178,15 +160,59 @@
_windY *= 0.15;
_velocityX *= 0.3;
_velocityY *= 0.3;
_isOvershooting = false;
return _lastMove = new Point(x, y);
}
double distScale = Math.Min(d / 100.0, 3.0);
double sens = Math.Max(0.1, sensitivity);
double dyn = maxStep * sens * (1.0 + distScale);
double g = gravity * (1.0 + distScale * 0.3) * sens * (enableOvershoot ? 1.15 : 1.0);
if (enableOvershoot)
{
double currentVelocity = Math.Sqrt(_velocityX * _velocityX + _velocityY * _velocityY);
if (!_isOvershooting && d < 50 && currentVelocity > 3.0)
{
double overshootDistance = Math.Min(currentVelocity * 2.5, 30.0);
_overshootTarget = new Point(
(int)Math.Round(end.X + dirX * overshootDistance),
(int)Math.Round(end.Y + dirY * overshootDistance)
);
_isOvershooting = true;
}
if (_isOvershooting)
{
double distToOvershoot = Math.Sqrt(
Math.Pow(_overshootTarget.X - start.X, 2) +
Math.Pow(_overshootTarget.Y - start.Y, 2)
);
Point currentTarget;
if (distToOvershoot < 5.0 || currentVelocity < 1.5)
{
_isOvershooting = false;
}
else
{
currentTarget = _overshootTarget;
dx = currentTarget.X - start.X;
dy = currentTarget.Y - start.Y;
d = Math.Sqrt(dx * dx + dy * dy);
if (d > 0)
{
inv = 1.0 / d;
dirX = dx * inv;
dirY = dy * inv;
}
}
}
}
double g = gravity * (1.0 + distScale * 0.3) * sens * (enableOvershoot && !_isOvershooting ? 1.3 : 1.0);
double prox = insideBoundingBox ? 0.0 : 1.0;
double w = wind * Math.Pow(prox, 4.0) * (enableOvershoot ? 1.2 : 1.0);
double w = wind * Math.Pow(prox, 4.0) * (enableOvershoot ? 1.3 : 1.0);
if (insideBoundingBox)
{
@@ -223,6 +249,12 @@
_velocityY *= r;
}
}
else if (enableOvershoot && !_isOvershooting && d < 30)
{
double correctionDamp = 0.7;
_velocityX *= correctionDamp;
_velocityY *= correctionDamp;
}
int nx = (int)Math.Round(start.X + _velocityX);
int ny = (int)Math.Round(start.Y + _velocityY);
@@ -236,17 +268,26 @@
_velocityX = 0.0;
_velocityY = 0.0;
_lastMove = new Point(0, 0);
_isOvershooting = false;
_overshootTarget = new Point(0, 0);
}
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;
}
}
+80 -36
View File
@@ -1,27 +1,49 @@
using OpenCvSharp;
using Spectrum.Detection;
using System.Runtime.InteropServices;
using Spectrum.Input.InputLibraries;
using Spectrum.Utilities;
using System.CommandLine;
namespace Spectrum
{
class Program
{
static Renderer? renderer = null;
public static ConfigManager<ConfigData> mainConfig = new ConfigManager<ConfigData>("bin\\configs\\config.json");
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs");
public static ColorConfigManager colorConfig = new("bin\\configs\\colors");
private static DetectionManager? detectionManager;
public static (int fps, double avgProcessTime) statistics = (0, 0);
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 void Main()
static int Main(string[] args)
{
Thread renderThread = new Thread(() =>
var monitorOption = new Option<int>(["--monitor", "-m"], () => 1);
var debugOption = new Option<bool>(["--debug", "-d"], () => false);
var rootCommand = new RootCommand();
rootCommand.AddOption(monitorOption);
rootCommand.AddOption(debugOption);
rootCommand.SetHandler((monitor, debug) => Run(monitor, debug), monitorOption, debugOption);
return rootCommand.Invoke(args);
}
private static void Run(int monitor, bool debug)
{
LogManager.SetDebugOverride(debug);
if (debug && !System.Diagnostics.Debugger.IsAttached)
Win32.EnsureConsoleAttached();
ConfigureMonitor(monitor);
LogManager.Log($"Monitor arg: {monitor}", LogManager.LogLevel.Debug);
LogManager.Log($"Monitor index: {MonitorIndex}", LogManager.LogLevel.Debug);
LogManager.Log($"Monitor bounds: {MonitorBounds.X},{MonitorBounds.Y} {MonitorBounds.Width}x{MonitorBounds.Height}", LogManager.LogLevel.Debug);
Thread renderThread = new(() =>
{
try
{
renderer = new Renderer(SharedCaptureManager);
bool dxok = SharedCaptureManager.TryInitializeDirectX();
bool dxok = SharedCaptureManager.TryInitializeDirectX(0, MonitorIndex - 1);
if (!dxok)
{
LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning);
@@ -36,7 +58,7 @@ namespace Spectrum
});
renderThread.Start();
string[] dirs = ["bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs"];
string[] dirs = ["bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs", "bin/configs/colors"];
foreach (var dir in dirs)
{
if (!Directory.Exists(dir))
@@ -51,12 +73,10 @@ namespace Spectrum
AutoLabeling.StartLabeling();
}
if (colorConfig.Data.Colors.Count == 0)
if (colorConfig.Colors.Count == 0)
{
colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(179, 255, 255), new Scalar(150, 255, 255)));
colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
colorConfig.SaveConfig();
colorConfig.LoadConfig();
colorConfig.SaveColor(new ColorInfo("Arsenal [Magenta]", new Scalar(179, 255, 255), new Scalar(150, 255, 255)));
colorConfig.SaveColor(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
mainConfig.LoadConfig();
}
@@ -70,35 +90,59 @@ namespace Spectrum
detectionManager = new DetectionManager(renderer);
}
}
public static class SystemHelper
private static void ConfigureMonitor(int monitor)
{
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
var screens = Screen.AllScreens;
if (screens.Length == 0)
return;
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
var index = monitor < 1 ? 1 : monitor;
LogManager.Log($"Detected monitors: {screens.Length}", LogManager.LogLevel.Debug);
for (int i = 0; i < screens.Length; i++)
LogManager.Log($"Monitor {i + 1}: {screens[i].DeviceName} {screens[i].Bounds.X},{screens[i].Bounds.Y} {screens[i].Bounds.Width}x{screens[i].Bounds.Height}", LogManager.LogLevel.Debug);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const int SM_XVIRTUALSCREEN = 76;
private const int SM_YVIRTUALSCREEN = 77;
private const int SM_CXVIRTUALSCREEN = 78;
private const int SM_CYVIRTUALSCREEN = 79;
public static (int Width, int Height) GetPrimaryScreenSize()
var selected = GetScreenByDeviceNumber(screens, index);
if (selected == null)
{
return (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
if (index > screens.Length)
index = 1;
selected = screens[index - 1];
}
public static (int X, int Y, int Width, int Height) GetVirtualScreenBounds()
MonitorIndex = index;
MonitorBounds = selected.Bounds;
}
private static Screen? GetScreenByDeviceNumber(Screen[] screens, int index)
{
return (
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN)
);
foreach (var screen in screens)
{
var number = TryGetDisplayNumber(screen.DeviceName);
if (number.HasValue && number.Value == index)
return screen;
}
return null;
}
private static int? TryGetDisplayNumber(string deviceName)
{
if (string.IsNullOrWhiteSpace(deviceName))
return null;
int i = deviceName.Length - 1;
while (i >= 0 && char.IsDigit(deviceName[i]))
i--;
if (i == deviceName.Length - 1)
return null;
var numberText = deviceName[(i + 1)..];
if (int.TryParse(numberText, out var value))
return value;
return null;
}
}
}
@@ -2,6 +2,7 @@
using OpenCvSharp;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Spectrum.Utilities;
using System.Numerics;
namespace Spectrum
@@ -15,16 +16,16 @@ namespace Spectrum
private Image<Rgba32>? _maskedImageSharp = null;
private IntPtr _originalTextureId = IntPtr.Zero;
private IntPtr _maskedTextureId = IntPtr.Zero;
private Scalar _lowerHSV = new Scalar(0, 0, 0);
private Scalar _upperHSV = new Scalar(179, 255, 255);
private Scalar _lowerHSV = new(0, 0, 0);
private Scalar _upperHSV = new(179, 255, 255);
private string _loadedImagePath = "";
private bool _needsTextureUpdate = false;
private string _colorName = "";
private int _maskDisplayMode = 0;
private Vector3 _maskTintColor = new Vector3(1.0f, 1.0f, 1.0f);
private Vector3 _maskTintColor = new(1.0f, 1.0f, 1.0f);
private float _maskOpacity = 1.0f;
private Vector3 _backgroundColor = new Vector3(0.0f, 0.0f, 0.0f);
private Vector3 _backgroundColor = new(0.0f, 0.0f, 0.0f);
private bool _showOnlyMaskedRegion = true;
void RenderHSVRangeWindow()
@@ -33,6 +34,7 @@ namespace Spectrum
return;
ImGui.SetNextWindowSize(new Vector2(900, 700), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSizeConstraints(new Vector2(700, 500), new Vector2(float.MaxValue, float.MaxValue));
ImGui.Begin("HSV Range Selector", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar);
ImGui.Text("HSV Range Selector");
@@ -206,18 +208,7 @@ namespace Spectrum
{
if (!string.IsNullOrWhiteSpace(_colorName))
{
var existingColor = Program.colorConfig.Data.Colors.Find(c => c.Name == _colorName);
if (existingColor != null)
{
existingColor.Lower = _lowerHSV;
existingColor.Upper = _upperHSV;
LogManager.Log($"Updated existing color: {_colorName}", LogManager.LogLevel.Info);
}
else
{
Program.colorConfig.Data.Colors.Add(new ColorInfo(_colorName, _upperHSV, _lowerHSV));
}
Program.colorConfig.SaveConfig();
Program.colorConfig.SaveColor(new ColorInfo(_colorName, _upperHSV, _lowerHSV));
_colorName = "";
}
else
@@ -232,10 +223,9 @@ namespace Spectrum
private void OpenImageFileDialog()
{
Thread thread = new Thread(() =>
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
Thread thread = new(() =>
{
using OpenFileDialog openFileDialog = new();
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png|All Files|*.*";
openFileDialog.Title = "Select an Image";
openFileDialog.Multiselect = false;
@@ -245,21 +235,15 @@ namespace Spectrum
{
LoadImage(openFileDialog.FileName);
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
private class WindowWrapper : IWin32Window
private class WindowWrapper(IntPtr handle) : IWin32Window
{
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle)
{
_handle = handle;
}
private readonly IntPtr _handle = handle;
public IntPtr Handle => _handle;
}
@@ -297,12 +281,11 @@ namespace Spectrum
try
{
using (Mat hsvImage = new Mat())
using (Mat hsvImage = new())
{
Cv2.CvtColor(_originalImage, hsvImage, ColorConversionCodes.BGR2HSV);
using (Mat mask = new Mat())
{
using Mat mask = new();
Cv2.InRange(hsvImage, _lowerHSV, _upperHSV, mask);
_maskedImage?.Dispose();
@@ -317,83 +300,66 @@ namespace Spectrum
}
else
{
using (Mat background = new Mat(_originalImage.Size(), _originalImage.Type(),
new Scalar(_backgroundColor.Z * 255, _backgroundColor.Y * 255, _backgroundColor.X * 255)))
{
using (Mat maskedForeground = new Mat())
{
using Mat background = new(_originalImage.Size(), _originalImage.Type(),
new Scalar(_backgroundColor.Z * 255, _backgroundColor.Y * 255, _backgroundColor.X * 255));
using Mat maskedForeground = new();
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedForeground, mask);
using (Mat invertedMask = new Mat())
{
using Mat invertedMask = new();
Cv2.BitwiseNot(mask, invertedMask);
using (Mat maskedBackground = new Mat())
{
using Mat maskedBackground = new();
Cv2.BitwiseAnd(background, background, maskedBackground, invertedMask);
Cv2.Add(maskedForeground, maskedBackground, _maskedImage);
}
}
}
}
}
break;
case 1:
using (Mat coloredMask = new Mat(_originalImage.Size(), _originalImage.Type()))
using (Mat coloredMask = new(_originalImage.Size(), _originalImage.Type()))
{
Cv2.CvtColor(mask, coloredMask, ColorConversionCodes.GRAY2BGR);
using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3,
new Scalar(_maskTintColor.Z, _maskTintColor.Y, _maskTintColor.X)))
{
using (Mat coloredMaskFloat = new Mat())
using (Mat tinted = new Mat())
{
using Mat tintMat = new(_originalImage.Size(), MatType.CV_32FC3,
new Scalar(_maskTintColor.Z, _maskTintColor.Y, _maskTintColor.X));
using Mat coloredMaskFloat = new();
using Mat tinted = new();
coloredMask.ConvertTo(coloredMaskFloat, MatType.CV_32FC3, 1.0 / 255.0);
Cv2.Multiply(coloredMaskFloat, tintMat, tinted);
tinted.ConvertTo(_maskedImage, _originalImage.Type(), 255.0);
}
}
}
break;
case 2:
using (Mat maskedResult = new Mat())
using (Mat maskedResult = new())
{
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedResult, mask);
using (Mat maskColored = new Mat(_originalImage.Size(), _originalImage.Type()))
{
using Mat maskColored = new(_originalImage.Size(), _originalImage.Type());
Cv2.CvtColor(mask, maskColored, ColorConversionCodes.GRAY2BGR);
using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3,
new Scalar(_maskTintColor.Z * _maskOpacity, _maskTintColor.Y * _maskOpacity, _maskTintColor.X * _maskOpacity)))
{
using (Mat maskColoredFloat = new Mat())
using (Mat tinted = new Mat())
using (Mat tintedByte = new Mat())
{
using Mat tintMat = new(_originalImage.Size(), MatType.CV_32FC3,
new Scalar(_maskTintColor.Z * _maskOpacity, _maskTintColor.Y * _maskOpacity, _maskTintColor.X * _maskOpacity));
using Mat maskColoredFloat = new();
using Mat tinted = new();
using Mat tintedByte = new();
maskColored.ConvertTo(maskColoredFloat, MatType.CV_32FC3, 1.0 / 255.0);
Cv2.Multiply(maskColoredFloat, tintMat, tinted);
tinted.ConvertTo(tintedByte, _originalImage.Type(), 255.0);
using (Mat originalFloat = new Mat())
using (Mat tintedFloat = new Mat())
using (Mat blended = new Mat())
{
using Mat originalFloat = new();
using Mat tintedFloat = new();
using Mat blended = new();
_originalImage.ConvertTo(originalFloat, MatType.CV_32FC3);
tintedByte.ConvertTo(tintedFloat, MatType.CV_32FC3);
Cv2.AddWeighted(originalFloat, 1.0 - _maskOpacity, tintedFloat, _maskOpacity, 0, blended);
blended.ConvertTo(_maskedImage, _originalImage.Type());
}
}
}
}
}
break;
}
}
}
_needsTextureUpdate = true;
}
@@ -437,14 +403,16 @@ namespace Spectrum
private Image<Rgba32> MatToImageSharp(Mat mat)
{
Mat rgbaMat = new Mat();
Mat rgbaMat = new();
Cv2.CvtColor(mat, rgbaMat, ColorConversionCodes.BGR2RGBA);
int width = rgbaMat.Width;
int height = rgbaMat.Height;
var config = new SixLabors.ImageSharp.Configuration();
config.PreferContiguousImageBuffers = true;
var config = new Configuration
{
PreferContiguousImageBuffers = true
};
var image = new Image<Rgba32>(config, width, height);
if (image.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> memory))
@@ -8,7 +8,7 @@ namespace Spectrum
{
public static class ImGuiExtensions
{
private static readonly Dictionary<string, string> _sliderEditBuffers = new();
private static readonly Dictionary<string, string> _sliderEditBuffers = [];
public static bool ColorEditHSV3(string label, ref Scalar hsv)
{
ImGui.PushID(label);
@@ -54,8 +54,8 @@ namespace Spectrum
Vector3 rgbColor = OpenCvHsvToRgb(hsv);
ImGui.SameLine();
Vector2 btnSize = new Vector2(previewWidth, previewWidth);
Vector4 previewCol4 = new Vector4(rgbColor.X, rgbColor.Y, rgbColor.Z, 1.0f);
Vector2 btnSize = new(previewWidth, previewWidth);
Vector4 previewCol4 = new(rgbColor.X, rgbColor.Y, rgbColor.Z, 1.0f);
string previewBtnId = $"##ColorPreview_{label}";
if (ImGui.ColorButton(previewBtnId, previewCol4, ImGuiColorEditFlags.NoInputs, btnSize))
{
@@ -101,13 +101,12 @@ namespace Spectrum
double huePrime = hueDeg / 60.0;
double x = c * (1 - Math.Abs(huePrime % 2 - 1));
double m = value - c;
double r1 = 0, g1 = 0, b1 = 0;
int region = (int)Math.Floor(huePrime);
if (region >= 6)
region = 0;
double r1;
double b1;
double g1;
switch (region)
{
case 0:
@@ -224,7 +223,7 @@ namespace Spectrum
int fPos = core.IndexOf('f', pos + 2);
if (fPos > pos)
{
string digits = core.Substring(pos + 2, fPos - (pos + 2));
string digits = core[(pos + 2)..fPos];
if (int.TryParse(digits, out int prec))
result = v.ToString("F" + prec, CultureInfo.InvariantCulture);
else
@@ -286,7 +285,7 @@ namespace Spectrum
int fPos = format.IndexOf('f', pos + 2);
if (fPos > pos)
{
string digits = format.Substring(pos + 2, fPos - (pos + 2));
string digits = format[(pos + 2)..fPos];
if (int.TryParse(digits, out int prec))
newValue = (float)Math.Round(newValue, prec);
}
@@ -311,7 +310,7 @@ namespace Spectrum
if (ImGui.InputText($"##SliderFillEdit_{label}", ref buffer, 32, inputFlags))
{
string parseStr = buffer.Trim();
if (parseStr.EndsWith("%")) parseStr = parseStr.TrimEnd('%');
if (parseStr.EndsWith('%')) parseStr = parseStr.TrimEnd('%');
if (float.TryParse(parseStr, NumberStyles.Float, CultureInfo.InvariantCulture, out float typed))
{
float clamped;
@@ -400,7 +399,7 @@ namespace Spectrum
});
}
public static bool BeginPane(string localId, bool showHeader = true)
public static bool BeginPane(string localId, bool showHeader = true, float headerRightWidth = 0f, Action? headerRight = null)
{
var g = _paneGroups.Peek();
if (g.Index > 0)
@@ -428,7 +427,7 @@ namespace Spectrum
Vector2 headerMin = ImGui.GetCursorScreenPos();
Vector2 headerMax = new Vector2(headerMin.X + g.Width, headerMin.Y + headerHeight);
Vector2 headerMax = new(headerMin.X + g.Width, headerMin.Y + headerHeight);
var drawList = ImGui.GetWindowDrawList();
uint bgCol = ImGui.GetColorU32(ImGuiCol.FrameBg);
@@ -439,6 +438,14 @@ namespace Spectrum
ImGui.SetCursorPos(new Vector2(padX, style.FramePadding.Y));
ImGui.TextUnformatted(headerText);
if (headerRight != null && headerRightWidth > 0f)
{
float rightX = g.Width - padX - headerRightWidth;
if (rightX < padX)
rightX = padX;
ImGui.SetCursorPos(new Vector2(rightX, style.FramePadding.Y));
headerRight();
}
}
float innerHeight = g.Height - headerHeight;
@@ -9,7 +9,7 @@ namespace Spectrum
private bool _showMovementPreview = false;
private Point _previewStartPoint = new(100, 100);
private Point _previewEndPoint = new(400, 300);
private List<(Point point, double speed)> _previewPath = [];
private readonly List<(Point point, double speed)> _previewPath = [];
private int UpdatePreviewInterval = 10; // ms
private DateTime _lastPreviewUpdate = DateTime.MinValue;
private bool _isDragging = false;
@@ -48,41 +48,35 @@ namespace Spectrum
_previewPath.Clear();
MovementPaths.ResetWindMouse();
double progress = 0.0;
double increment = config.Sensitivity * 0.02;
Point current = _previewStartPoint;
int steps = 0;
int maxSteps = 10000;
_previewPath.Add((current, 0.0));
while (true)
{
double distance = Math.Sqrt(Math.Pow(_previewEndPoint.X - current.X, 2) + Math.Pow(_previewEndPoint.Y - current.Y, 2));
if (steps++ >= maxSteps)
if (distance < 2.0 || steps++ >= maxSteps)
break;
bool isInBox = boundingBox.Contains(current);
Point nextPoint = config.AimMovementType switch
{
MovementType.Linear => MovementPaths.LinearInterpolation(current, _previewEndPoint, progress),
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(current, _previewEndPoint, progress),
MovementType.Adaptive => MovementPaths.AdaptiveMovement(current, _previewEndPoint, progress),
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(current, _previewEndPoint, progress),
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(current, _previewEndPoint, progress),
MovementType.WindMouse => MovementPaths.WindMouse(current, _previewEndPoint,
config.WindMouseGravity,
config.WindMouseWind,
config.WindMouseMaxStep,
config.Sensitivity,
config.WindMouseOvershoot,
isInBox),
_ => MovementPaths.LinearInterpolation(current, _previewEndPoint, progress),
};
Point nextPoint = InputManager.CalculateMovement(current, _previewEndPoint, config.Sensitivity, config.AimMovementType, isInBox);
if (config.EmaSmoothening)
nextPoint = MovementPaths.EmaSmoothing(current, nextPoint, config.EmaSmootheningFactor);
double speed = Math.Sqrt(Math.Pow(nextPoint.X - current.X, 2) + Math.Pow(nextPoint.Y - current.Y, 2));
_previewPath.Add((nextPoint, speed));
current = nextPoint;
progress += increment;
}
if (_previewPath.Count > 0)
{
var lastPoint = _previewPath[^1].point;
double finalDistance = Math.Sqrt(Math.Pow(_previewEndPoint.X - lastPoint.X, 2) + Math.Pow(_previewEndPoint.Y - lastPoint.Y, 2));
if (finalDistance > 2.0)
_previewPath.Add((_previewEndPoint, finalDistance));
}
}
@@ -90,26 +84,38 @@ namespace Spectrum
Vector2 canvasPos = ImGui.GetCursorScreenPos();
canvasPos.Y += 5;
Vector2 canvasSize = ImGui.GetContentRegionAvail();
Vector2 size = new Vector2(canvasSize.X, canvasSize.Y - 60);
Vector2 size = new(canvasSize.X, canvasSize.Y - 60);
drawList.AddRectFilled(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.12f, 0.12f, 0.14f, 1.0f)), 3f);
drawList.AddRect(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.17f, 0.17f, 0.20f, 1.0f)), 3f);
drawList.PushClipRect(canvasPos, canvasPos + size, true);
drawList.AddRect(
new Vector2(boundingBox.X + canvasPos.X, boundingBox.Top + canvasPos.Y),
new Vector2(boundingBox.X + boundingBox.Width + canvasPos.X, boundingBox.Y + boundingBox.Height + canvasPos.Y),
ImGui.GetColorU32(new Vector4(0, 0, 1, 1)), 0.0f, ImDrawFlags.None, 2.0f);
if (_previewPath.Count > 1)
{
double maxSpeed = _previewPath.Max(p => p.speed);
for (int i = 1; i < _previewPath.Count; i++)
{
var (prevPoint, _) = _previewPath[i - 1];
var (currPoint, speed) = _previewPath[i];
Vector2 p1 = new Vector2(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y);
Vector2 p2 = new Vector2(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y);
Vector4 color = speed < maxSpeed / 2 ?
Vector4.Lerp(new Vector4(0, 1, 0, 1), new Vector4(1, 1, 0, 1), (float)(speed / (maxSpeed / 2))) :
Vector4.Lerp(new Vector4(1, 1, 0, 1), new Vector4(1, 0, 0, 1), (float)((speed - (maxSpeed / 2)) / (maxSpeed / 2)));
var (prevPoint, prevSpeed) = _previewPath[i - 1];
var (currPoint, currSpeed) = _previewPath[i];
Vector2 p1 = new(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y);
Vector2 p2 = new(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y);
double avgSpeed = (prevSpeed + currSpeed) / 2.0;
float normalizedSpeed = (float)(avgSpeed / maxSpeed);
Vector4 color;
if (normalizedSpeed < 0.33f) // green -> yellow
color = Vector4.Lerp(new Vector4(0, 1, 0, 1), new Vector4(1, 1, 0, 1), normalizedSpeed / 0.33f);
else if (normalizedSpeed < 0.66f) // yellow -> orange
color = Vector4.Lerp(new Vector4(1, 1, 0, 1), new Vector4(1, 0.5f, 0, 1), (normalizedSpeed - 0.33f) / 0.33f);
else // orange -> red
color = Vector4.Lerp(new Vector4(1, 0.5f, 0, 1), new Vector4(1, 0, 0, 1), (normalizedSpeed - 0.66f) / 0.34f);
drawList.AddLine(p1, p2, ImGui.GetColorU32(color), 2.0f);
}
}
@@ -117,6 +123,8 @@ namespace Spectrum
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewStartPoint.X, canvasPos.Y + _previewStartPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(0, 1, 0, 1)));
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewEndPoint.X, canvasPos.Y + _previewEndPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(1, 0, 0, 1)));
drawList.PopClipRect();
ImGui.InvisibleButton("canvas", size);
var io = ImGui.GetIO();
var mousePos = io.MousePos;
@@ -152,10 +160,10 @@ namespace Spectrum
if (_isDragging && isMouseDown)
{
Vector2 localMousePos = mousePos - canvasPos;
if (localMousePos.X < 0) localMousePos.X = 0;
if (localMousePos.Y < 0) localMousePos.Y = 0;
if (localMousePos.X > size.X) localMousePos.X = size.X;
if (localMousePos.Y > size.Y) localMousePos.Y = size.Y;
if (localMousePos.X < 15) localMousePos.X = 15;
if (localMousePos.Y < 15) localMousePos.Y = 15;
if (localMousePos.X > size.X - 15) localMousePos.X = size.X - 15;
if (localMousePos.Y > size.Y - 15) localMousePos.Y = size.Y - 15;
if (_isMovingStart)
{
_previewStartPoint = new Point((int)localMousePos.X, (int)localMousePos.Y);
@@ -1,10 +1,12 @@
using ClickableTransparentOverlay;
using ImGuiNET;
using OpenCvSharp;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Spectrum.Detection;
using Spectrum.Input;
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Input.InputLibraries.Makcu;
using Spectrum.Input.InputLibraries;
using Spectrum.Utilities;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Numerics;
@@ -13,40 +15,97 @@ namespace Spectrum
{
partial class Renderer : Overlay
{
static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize();
private List<Action<ImDrawListPtr>> detectionDrawCommands = new List<Action<ImDrawListPtr>>();
private List<Action<ImDrawListPtr>> activeDrawCommands = new List<Action<ImDrawListPtr>>();
private readonly object detectionDrawLock = new object();
static (int width, int height) screenSize = (0, 0);
private List<Action<ImDrawListPtr>> detectionDrawCommands = [];
private List<Action<ImDrawListPtr>> activeDrawCommands = [];
private readonly object detectionDrawLock = new();
private readonly CaptureManager _captureManager;
private bool _vsync = true;
private int _fpsLimit = 240;
private readonly Dictionary<string, bool> _waitingForKeybind = new();
private readonly Dictionary<string, Keys> _pendingKeybind = new();
private readonly Dictionary<string, Task?> _keybindTask = new();
private readonly Dictionary<string, bool> _waitingForKeybind = [];
private readonly Dictionary<string, Keys> _pendingKeybind = [];
private readonly Dictionary<string, Task?> _keybindTask = [];
private readonly ConcurrentQueue<Keys> _keybindResults = new();
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private ConfigManager<ColorData> colorConfig = Program.colorConfig;
private readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private readonly ColorConfigManager colorConfig = Program.colorConfig;
private string ColorName = "New Color";
private static bool scrollToBottom = true;
private ColorInfo? selectedColor = null;
private int _colorConfigVersion = -1;
private string configName = "New Config";
private string? selectedConfigName = null;
private bool _windowPositioned = false;
private Image<Rgba32>? _copyIconImage = null;
private IntPtr _copyIconTextureId = IntPtr.Zero;
private readonly InputLibraryManager _inputManager = Program.InputLibraryManager;
public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width)
private static Vector2 ToOverlay(Vector2 point)
{
var bounds = Program.MonitorBounds;
return new Vector2(point.X - bounds.X, point.Y - bounds.Y);
}
private static string? ResolveAssetPath(string fileName)
{
string basePath = AppContext.BaseDirectory;
string basePathCandidate = Path.Combine(basePath, fileName);
if (File.Exists(basePathCandidate))
return basePathCandidate;
string cwdCandidate = Path.Combine(Directory.GetCurrentDirectory(), fileName);
if (File.Exists(cwdCandidate))
return cwdCandidate;
return null;
}
private bool TryLoadImageTexture(string key, string fileName, ref Image<Rgba32>? image, ref IntPtr textureId)
{
if (textureId != IntPtr.Zero)
return true;
string? imagePath = ResolveAssetPath(fileName);
if (string.IsNullOrEmpty(imagePath))
return false;
image?.Dispose();
image = SixLabors.ImageSharp.Image.Load<Rgba32>(imagePath);
AddOrGetImagePointer(key, image, false, out textureId);
return textureId != IntPtr.Zero;
}
public Renderer(CaptureManager captureManager) : base("Spectrum", Program.MonitorBounds.Width, Program.MonitorBounds.Height)
{
screenSize = (Program.MonitorBounds.Width, Program.MonitorBounds.Height);
_captureManager = captureManager;
VSync = _vsync;
FPSLimit = _fpsLimit;
ImGui.CreateContext();
var io = ImGui.GetIO();
io.Fonts.Clear();
io.Fonts.AddFontFromFileTTF("C:\\Windows\\Fonts\\Arial.ttf", 16.0f);
var bounds = Program.MonitorBounds;
if (window != null)
Win32.SetWindowBounds(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
LogManager.Log($"Renderer monitor bounds: {bounds.X},{bounds.Y} {bounds.Width}x{bounds.Height}", LogManager.LogLevel.Debug);
LogManager.Log($"Renderer screen size: {screenSize.width}x{screenSize.height}", LogManager.LogLevel.Debug);
}
override protected void Render()
{
if (!_windowPositioned && window != null)
{
var bounds = Program.MonitorBounds;
Win32.SetWindowBounds(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
screenSize = (bounds.Width, bounds.Height);
_windowPositioned = true;
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;
@@ -68,6 +127,9 @@ namespace Spectrum
Environment.Exit(0);
}
int ImageWidth = config.ImageWidth;
int ImageHeight = config.ImageHeight;
ImGui.BeginTabBar("##tabs");
if (ImGui.BeginTabItem("Aiming"))
{
@@ -87,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);
@@ -111,13 +227,12 @@ namespace Spectrum
_showMovementPreview = !_showMovementPreview;
ImGui.SetNextItemWidth(-1);
MovementType AimPath = config.AimMovementType;
if (ImGui.BeginCombo("##Movement Type", AimPath.ToString()))
if (ImGui.BeginCombo("##Movement Type", FormatText(AimPath.ToString())))
{
foreach (MovementType type in Enum.GetValues(typeof(MovementType)))
{
bool isSelected = (type == AimPath);
string displayName = string.Concat(type.ToString().Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString())); // just adds a space before capitals except for the first
if (ImGui.Selectable(displayName, isSelected))
if (ImGui.Selectable(FormatText(type.ToString()), isSelected))
config.AimMovementType = type;
if (isSelected)
ImGui.SetItemDefaultFocus();
@@ -180,70 +295,6 @@ namespace Spectrum
if (ImGuiExtensions.SliderFill("X Offset (px)", ref XOffset, -200, 200))
config.XOffsetPixels = Math.Max(-200, XOffset);
}
ImGui.SeparatorText("Overlay Settings");
bool DrawFOV = config.DrawFOV;
if (ImGui.Checkbox("##Draw FOV", ref DrawFOV))
config.DrawFOV = DrawFOV;
ImGui.SameLine();
ImGui.Text("Draw FOV");
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
Vector4 FOVColor = config.FOVColor;
if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
config.FOVColor = FOVColor;
bool DrawDetections = config.DrawDetections;
if (ImGui.Checkbox("##Draw Detections", ref DrawDetections))
config.DrawDetections = DrawDetections;
ImGui.SameLine();
ImGui.Text("Draw Detections");
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
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))
config.HighlightTarget = HighlightTarget;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
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))
config.DrawAimPoint = DrawAimPoint;
ImGui.SameLine();
ImGui.Text("Draw Aim Point");
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
Vector4 AimPointColor = config.AimPointColor;
if (ImGui.ColorEdit4("Aim Point Color", ref AimPointColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
config.AimPointColor = AimPointColor;
if (DrawFOV)
{
ImGui.TextUnformatted("FOV Type");
ImGui.SetNextItemWidth(-1);
FovType fovType = config.FOVType;
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;
if (isSelected)
ImGui.SetItemDefaultFocus();
}
ImGui.EndCombo();
}
}
ImGuiExtensions.EndPane();
}
@@ -256,17 +307,27 @@ namespace Spectrum
if (triggerBot)
{
bool BoundingBoxOnly = config.TriggerInBoundsOnly;
bool TriggerSpray = config.TriggerSpray;
int triggerDelay = config.TriggerDelay;
if (ImGuiExtensions.SliderFill("Trigger Delay (ms)", ref triggerDelay, 1, 1000))
config.TriggerDelay = triggerDelay;
int triggerFov = config.TriggerFov;
if (ImGuiExtensions.SliderFill("Trigger FOV (px)", ref triggerFov, 1, 100))
config.TriggerFov = triggerFov;
if (TriggerSpray)
ImGui.BeginDisabled();
int triggerDuration = config.TriggerDuration;
if (ImGuiExtensions.SliderFill("Trigger Duration (ms)", ref triggerDuration, 1, 1000))
config.TriggerDuration = triggerDuration;
if (TriggerSpray)
ImGui.EndDisabled();
if (BoundingBoxOnly)
ImGui.BeginDisabled();
int triggerFov = config.TriggerFov;
if (ImGuiExtensions.SliderFill("Trigger FOV (px)", ref triggerFov, 1, 100))
config.TriggerFov = triggerFov;
bool DrawTriggerFov = config.DrawTriggerFov;
if (ImGui.Checkbox("##Draw Trigger FOV", ref DrawTriggerFov))
@@ -278,6 +339,42 @@ namespace Spectrum
if (ImGui.ColorEdit4("Trigger Color", ref RadiusColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
config.TriggerRadiusColor = RadiusColor;
if (BoundingBoxOnly)
ImGui.EndDisabled();
bool RandomDelay = config.TriggerRandomDelay;
if (ImGui.Checkbox(" Random Delay", ref RandomDelay))
config.TriggerRandomDelay = RandomDelay;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
ImGui.TextDisabled("(?)");
if (ImGui.IsItemHovered(ImGuiHoveredFlags.None))
ImGui.SetTooltip("Randomizes the trigger delay between 10 and the set Trigger Delay.");
if (TriggerSpray)
ImGui.BeginDisabled();
bool RandomDuration = config.TriggerRandomDuration;
if (ImGui.Checkbox(" Random Duration", ref RandomDuration))
config.TriggerRandomDuration = RandomDuration;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
ImGui.TextDisabled("(?)");
if (ImGui.IsItemHovered(ImGuiHoveredFlags.None))
ImGui.SetTooltip("Randomizes the trigger duration between 20 and the set Trigger Duration.");
if (TriggerSpray)
ImGui.EndDisabled();
if (ImGui.Checkbox(" Trigger Spray", ref TriggerSpray))
config.TriggerSpray = TriggerSpray;
if (ImGui.Checkbox(" Bounding Box Only", ref BoundingBoxOnly))
config.TriggerInBoundsOnly = BoundingBoxOnly;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 10);
ImGui.TextDisabled("(?)");
if (ImGui.IsItemHovered(ImGuiHoveredFlags.None))
ImGui.SetTooltip("Only triggers when the detected object is within the bounding box.");
}
ImGuiExtensions.EndPane();
}
@@ -287,6 +384,91 @@ namespace Spectrum
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Overlay"))
{
ImGuiExtensions.BeginPaneGroup("Overlay Panes", 1, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
if (ImGuiExtensions.BeginPane("Overlay"))
{
bool DrawFOV = config.DrawCaptureFov;
if (ImGui.Checkbox(" Draw FOV", ref DrawFOV))
config.DrawCaptureFov = DrawFOV;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 11);
Vector4 FOVColor = config.CaptureFOVColor;
if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
config.CaptureFOVColor = FOVColor;
bool DrawDetections = config.DrawDetections;
if (ImGui.Checkbox(" Draw Detections", ref DrawDetections))
config.DrawDetections = DrawDetections;
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))
config.HighlightTarget = HighlightTarget;
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))
config.DrawAimPoint = DrawAimPoint;
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;
if (DrawFOV)
{
ImGui.TextUnformatted("FOV Type");
ImGui.SetNextItemWidth(-1);
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.CaptureFOVType = type;
if (isSelected)
ImGui.SetItemDefaultFocus();
}
ImGui.EndCombo();
}
}
if (DrawAimPoint)
{
AimpointType aimpointType = config.AimPointType;
ImGui.TextUnformatted("Aimpoint Type");
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo("##Aimpoint Type", aimpointType.ToString()))
{
foreach (AimpointType type in Enum.GetValues(typeof(AimpointType)))
{
bool isSelected = (type == aimpointType);
if (ImGui.Selectable(type.ToString(), isSelected))
config.AimPointType = type;
if (isSelected)
ImGui.SetItemDefaultFocus();
}
ImGui.EndCombo();
}
}
ImGuiExtensions.EndPane();
}
ImGuiExtensions.EndPaneGroup();
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Detection"))
{
ImGuiExtensions.BeginPaneGroup("Detection Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
@@ -295,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)
@@ -307,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)
@@ -325,9 +507,9 @@ 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;
if (ImGui.Button("Open HSV Range Selector"))
_showHSVRangeWindow = true;
@@ -337,13 +519,31 @@ namespace Spectrum
if (ImGuiExtensions.BeginPane("Color Configs"))
{
List<ColorInfo> colors = colorConfig.Data.Colors;
if (colorConfig.Version != _colorConfigVersion)
{
_colorConfigVersion = colorConfig.Version;
if (!string.IsNullOrWhiteSpace(config.SelectedColor))
{
var updatedColor = colorConfig.GetColor(config.SelectedColor);
if (updatedColor != null)
{
selectedColor = updatedColor;
ColorName = updatedColor.Name;
config.UpperHSV = updatedColor.Upper;
config.LowerHSV = updatedColor.Lower;
}
}
}
List<ColorInfo> colors = [.. colorConfig.Colors];
if (selectedColor != null)
selectedColor = colors.Find(c => c.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase));
ImGui.PushStyleColor(ImGuiCol.ChildBg, new Vector4(0.110f, 0.110f, 0.125f, 1.000f));
ImGui.BeginChild("##DColorConfigsChild", new Vector2(0, ImGui.GetContentRegionAvail().Y / 2), ImGuiChildFlags.None);
ImGui.Dummy(new Vector2(0, 4));
foreach (var color in colors)
{
if (ImGui.Selectable(" " + color.Name, selectedColor == color))
if (ImGui.Selectable(" " + color.Name, selectedColor != null && color.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase)))
{
selectedColor = color;
ColorName = color.Name;
@@ -356,7 +556,7 @@ namespace Spectrum
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##ColorName", "Color Name", ref ColorName, 100);
Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22);
Vector2 size = new((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22);
if (ImGui.Button("Load Color", size))
{
if (selectedColor != null)
@@ -371,16 +571,11 @@ namespace Spectrum
ImGui.SameLine();
if (ImGui.Button("Save Color", size))
{
if (colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)) is ColorInfo existingColor)
if (!string.IsNullOrWhiteSpace(ColorName))
{
existingColor.Upper = config.UpperHSV;
existingColor.Lower = config.LowerHSV;
}
else
{
colors.Add(new ColorInfo(ColorName, config.UpperHSV, config.LowerHSV));
colorConfig.SaveConfig();
selectedColor = colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase));
var colorToSave = new ColorInfo(ColorName, config.UpperHSV, config.LowerHSV);
if (colorConfig.SaveColor(colorToSave))
selectedColor = colorConfig.GetColor(ColorName);
}
}
ImGui.SameLine();
@@ -388,27 +583,27 @@ namespace Spectrum
{
if (selectedColor != null)
{
int currentIndex = colors.IndexOf(selectedColor);
colors.RemoveAll(c => c.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase));
colorConfig.SaveConfig();
var deletedName = selectedColor.Name;
int currentIndex = colors.FindIndex(c => c.Name.Equals(deletedName, StringComparison.OrdinalIgnoreCase));
if (colorConfig.DeleteColor(deletedName))
{
colors = [.. colorConfig.Colors];
if (colors.Count > 0)
{
if (selectedColor.Name == config.SelectedColor)
{
int nextIndex = Math.Max(0, currentIndex - 1);
selectedColor = colors[currentIndex - 1];
int nextIndex = Math.Clamp(currentIndex - 1, 0, colors.Count - 1);
selectedColor = colors[nextIndex];
config.SelectedColor = selectedColor.Name;
config.UpperHSV = selectedColor.Upper;
config.LowerHSV = selectedColor.Lower;
ColorName = selectedColor.Name;
}
}
else
{
selectedColor = null;
}
}
}
}
ImGuiExtensions.EndPane();
}
@@ -443,7 +638,7 @@ namespace Spectrum
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##ConfigName", "Config Name", ref configName, 100);
Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22);
Vector2 size = new((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22);
if (ImGui.Button("Load Config", size))
{
@@ -490,7 +685,7 @@ namespace Spectrum
ImGui.InputText("##CurrentConfig", ref currentConfig, 256, ImGuiInputTextFlags.ReadOnly);
ImGui.PopStyleColor();
Vector2 fullSize = new Vector2(ImGui.GetContentRegionAvail().X, 22);
Vector2 fullSize = new(ImGui.GetContentRegionAvail().X, 22);
if (ImGui.Button("Save Current to Default", fullSize))
mainConfig.SaveConfig();
@@ -501,7 +696,7 @@ namespace Spectrum
if (ImGui.Button("Open Configs Folder", fullSize))
{
string configDir = Path.Combine(Directory.GetCurrentDirectory(), "configs");
string configDir = Path.Combine(Directory.GetCurrentDirectory(), "bin", "configs");
if (Directory.Exists(configDir))
{
Process.Start(new ProcessStartInfo
@@ -523,7 +718,6 @@ namespace Spectrum
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Settings"))
{
ImGuiExtensions.BeginPaneGroup("Settings Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
@@ -532,46 +726,19 @@ namespace Spectrum
{
ImGui.TextUnformatted("Movement Method");
ImGui.SetNextItemWidth(-1);
MovementMethod movementMethod = config.MovementMethod;
if (ImGui.BeginCombo("##Movement Method", movementMethod.ToString()))
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.ToString(), isSelected))
bool isSelected = method == movementMethod;
if (ImGui.Selectable(method != InputLibraryType.HID ? FormatText(method.ToString()) : method.ToString(), isSelected))
{
config.MovementMethod = method;
switch (method)
{
case MovementMethod.Makcu:
{
ArduinoMain.Close();
var ok = MakcuMain.Load().GetAwaiter().GetResult();
if (!ok)
{
LogManager.Log("Makcu failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
config.MovementMethod = MovementMethod.MouseEvent;
MakcuMain.Unload();
}
break;
}
case MovementMethod.Arduino:
{
MakcuMain.Unload();
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;
}
default:
ArduinoMain.Close();
MakcuMain.Unload();
break;
}
config.InputLibraryType = method;
bool success = _inputManager.Switch(method);
if (!success)
config.InputLibraryType = _inputManager.CurrentType;
}
if (isSelected)
ImGui.SetItemDefaultFocus();
@@ -631,6 +798,16 @@ namespace Spectrum
if (ImGuiExtensions.SliderFill("FPS Limit", ref _fpsLimit, 30, 480))
FPSLimit = _fpsLimit;
bool AntiCapture = config.AntiCapture;
if (ImGui.Checkbox("Anti-Capture", ref AntiCapture))
{
config.AntiCapture = AntiCapture;
if (AntiCapture && window != null)
Win32.EnableAntiCapture(window.Handle);
else if (window != null)
Win32.DisableAntiCapture(window.Handle);
}
ImGui.TextUnformatted("Background Image Interval");
ImGui.SetNextItemWidth(-1);
int BackgroundImageInterval = config.BackgroundImageInterval;
@@ -643,6 +820,17 @@ namespace Spectrum
config.BackgroundImageInterval = BackgroundImageInterval;
}
ImGui.TextUnformatted("Labeled Image Interval");
ImGui.SetNextItemWidth(-1);
int LabeledImageInterval = config.LabeledImageInterval;
if (ImGui.InputInt("##Labeled Image Interval", ref LabeledImageInterval, 1, 1000))
{
if (LabeledImageInterval < 1)
LabeledImageInterval = 1;
else if (LabeledImageInterval > 1000)
LabeledImageInterval = 1000;
config.LabeledImageInterval = LabeledImageInterval;
}
if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false))
{
@@ -673,19 +861,65 @@ namespace Spectrum
ImGuiExtensions.EndPane();
}
if (ImGuiExtensions.BeginPane("Logs"))
List<LogManager.LogEntry?> logs;
try
{
logs = [.. LogManager.LogEntries];
}
catch
{
logs = [];
}
if (ImGuiExtensions.BeginPane("Logs", true, 16f, () =>
{
bool copyClicked = false;
if (TryLoadImageTexture("copy_icon", "assets/copy.png", ref _copyIconImage, ref _copyIconTextureId))
{
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
copyClicked = ImGui.ImageButton("##CopyLogs", _copyIconTextureId, new Vector2(16, 16));
ImGui.PopStyleVar();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Copy Logs");
}
else
{
copyClicked = ImGui.Button("Copy");
}
if (copyClicked)
{
var logText = new System.Text.StringBuilder();
foreach (var log in logs)
{
logText.AppendLine(log?.ToString());
}
ImGui.SetClipboardText(logText.ToString());
}
}))
{
ImGui.BeginChild("Logs", new Vector2(0, -34), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar);
float scrollY = ImGui.GetScrollY();
float scrollMaxY = ImGui.GetScrollMaxY();
bool isAtBottom = (scrollY >= scrollMaxY - 1.0f);
var _LogEntries = LogManager.LogEntries;
_LogEntries = [.. _LogEntries];
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)
@@ -731,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;
@@ -744,39 +981,98 @@ namespace Spectrum
}
else
{
InputManager.GetCursorPos(out System.Drawing.Point mousePos);
topLeft = new(mousePos.X - (config.ImageWidth / 2), mousePos.Y - (config.ImageHeight / 2));
bottomRight = new(mousePos.X + (config.ImageWidth / 2), mousePos.Y + (config.ImageHeight / 2));
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 = new(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)
{
var stats = Program.statistics;
double avgTime = Math.Round(stats.avgProcessTime, 2);
Vector2 textSize = ImGui.CalcTextSize($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms");
drawList.AddRectFilled(new Vector2(10, 10), new Vector2(10 + textSize.X + 10, 10 + textSize.Y + 10), ImGui.GetColorU32(new Vector4(0, 0, 0, 0.8f)), 5.0f);
var frameStats = Program.Timings.GetSnapshot(["Frame"]).FirstOrDefault();
double avgTime = frameStats == null ? 0 : Math.Round(frameStats.AverageTicks / Stopwatch.Frequency * 1000.0, 2);
int fps = frameStats == null || frameStats.AverageTicks <= 0 ? 0 : (int)Math.Round(Stopwatch.Frequency / frameStats.AverageTicks);
var lines = new List<string>
{
$"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}: {TimingStats.FormatDuration(stat.AverageTicks)}");
float maxWidth = 0;
float totalHeight = 0;
foreach (var line in lines)
{
var size = ImGui.CalcTextSize(line);
if (size.X > maxWidth)
maxWidth = size.X;
totalHeight += size.Y + 4;
}
drawList.AddRectFilled(new Vector2(10, 10), new Vector2(10 + maxWidth + 10, 10 + totalHeight + 10), ImGui.GetColorU32(new Vector4(0, 0, 0, 0.8f)), 5.0f);
ImGui.SetCursorPos(new Vector2(15, 15));
ImGui.TextUnformatted($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms");
foreach (var line in lines)
{
ImGui.SetCursorPosX(15);
ImGui.TextUnformatted(line);
}
}
List<Action<ImDrawListPtr>> _drawCommands;
@@ -874,11 +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(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)
{
detectionDrawCommands.Add(drawList => drawList.AddRect(new Vector2(rect.Left, rect.Top), new Vector2(rect.Right, rect.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
));
}
}
@@ -886,7 +1192,9 @@ namespace Spectrum
{
lock (detectionDrawLock)
{
detectionDrawCommands.Add(drawList => drawList.AddLine(p1, p2, ImGui.GetColorU32(color), thickness));
var p1Local = ToOverlay(p1);
var p2Local = ToOverlay(p2);
detectionDrawCommands.Add(drawList => drawList.AddLine(p1Local, p2Local, ImGui.GetColorU32(color), thickness));
}
}
@@ -897,7 +1205,18 @@ namespace Spectrum
lock (detectionDrawLock)
{
detectionDrawCommands.Add(drawList => drawList.AddCircle(center, radius, ImGui.GetColorU32(color), numSegments, thickness));
var local = ToOverlay(center);
detectionDrawCommands.Add(drawList => drawList.AddCircle(local, radius, ImGui.GetColorU32(color), numSegments, thickness));
}
}
public void AddCircleFilled(Vector2 center, float radius, Vector4 color, int numSegments = 0)
{
if (numSegments <= 0)
numSegments = (int)(Math.Max(1, radius / 2.0f));
lock (detectionDrawLock)
{
var local = ToOverlay(center);
detectionDrawCommands.Add(drawList => drawList.AddCircleFilled(local, radius, ImGui.GetColorU32(color), numSegments));
}
}
@@ -907,7 +1226,8 @@ namespace Spectrum
return;
lock (detectionDrawLock)
{
detectionDrawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ImGui.GetColorU32(color), text));
var local = ToOverlay(pos);
detectionDrawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, local, ImGui.GetColorU32(color), text));
}
}
@@ -916,7 +1236,7 @@ namespace Spectrum
lock (detectionDrawLock)
{
activeDrawCommands = detectionDrawCommands;
detectionDrawCommands = new List<Action<ImDrawListPtr>>();
detectionDrawCommands = [];
}
}
@@ -928,11 +1248,16 @@ namespace Spectrum
}
}
public Vector2 GetTextWidth(string text, int fontSize = 16)
public static Vector2 GetTextWidth(string text, int fontSize = 16)
{
if (string.IsNullOrEmpty(text))
return new Vector2(0, 0);
return ImGui.CalcTextSize(text, 0, text.Length, fontSize);
}
public static string FormatText(string text)
{
return string.Concat(text.Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString()));
}
}
}
+6
View File
@@ -19,6 +19,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="HidSharp" Version="2.6.4" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
@@ -28,6 +29,11 @@
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
<PackageReference Include="System.IO.Ports" Version="9.0.8" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
</ItemGroup>
<ItemGroup>
<None Update="Assets\copy.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -1,65 +1,73 @@
using System.Diagnostics;
using System.Text;
namespace Spectrum
namespace Spectrum.Utilities
{
public class LogManager
{
private static List<LogEntry> _logEntries = new List<LogEntry>();
private static readonly object _logLock = new object();
private static List<LogEntry> _logEntries = [];
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
public class LogEntry(LogLevel level, string message)
{
public DateTime Timestamp { get; set; }
public LogLevel Level { get; set; }
public string Message { get; set; }
public LogEntry(LogLevel level, string message)
{
Timestamp = DateTime.Now;
Level = level;
Message = message;
}
public DateTime Timestamp { get; set; } = DateTime.Now;
public LogLevel Level { get; set; } = level;
public string Message { get; set; } = message;
public override string ToString()
{
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
}
}
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
public static void Log(string message, LogLevel level = LogLevel.Info)
public static void SetDebugOverride(bool enabled)
{
if (string.IsNullOrWhiteSpace(message)) return;
if (mainConfig == null)
{
try { mainConfig = Program.mainConfig; } catch { }
debugOverride = enabled;
}
bool debugEnabled = Debugger.IsAttached;
public static void Log(string message, LogLevel level = LogLevel.Info)
{
if (string.IsNullOrWhiteSpace(message))
return;
if (mainConfig == null)
{
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 { }
}
lock (_logLock)
{
if (_logEntries == null)
{
_logEntries = new List<LogEntry>();
}
_logEntries ??= [];
_logEntries.Add(new LogEntry(level, message));
}
}
@@ -68,6 +76,7 @@ namespace Spectrum
Debug.WriteLine($"[LogManager ERROR] Failed to append log entry: {ex.Message}");
}
}
public static void SaveLog(string filePath)
{
try
@@ -85,6 +94,7 @@ namespace Spectrum
Log($"Failed to save log: {ex.Message}", LogLevel.Error);
}
}
public static void ClearLog()
{
_logEntries.Clear();
@@ -92,12 +102,38 @@ namespace Spectrum
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;
}
}
}
}
+106
View File
@@ -0,0 +1,106 @@
using System.Diagnostics;
namespace Spectrum.Utilities
{
public sealed class TimingStats
{
private sealed class TimingEntry
{
public long TotalTicks;
public long Count;
}
public sealed class TimingSnapshot(string name, long count, double averageTicks)
{
public string Name { get; } = name;
public long Count { get; } = count;
public double AverageTicks { get; } = averageTicks;
}
private readonly object sync = new();
private readonly Dictionary<string, TimingEntry> entries = [];
public void Add(string name, long ticks)
{
if (string.IsNullOrWhiteSpace(name))
return;
lock (sync)
{
if (!entries.TryGetValue(name, out var entry))
{
entry = new TimingEntry();
entries[name] = entry;
}
entry.TotalTicks += ticks;
entry.Count++;
}
}
public void Clear()
{
lock (sync)
{
entries.Clear();
}
}
public List<TimingSnapshot> GetSnapshot(IEnumerable<string>? orderedNames = null)
{
lock (sync)
{
var result = new List<TimingSnapshot>();
if (orderedNames == null)
{
foreach (var kvp in entries)
{
if (kvp.Value.Count == 0) continue;
result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count));
}
return result;
}
var used = new HashSet<string>();
foreach (var orderedName in orderedNames)
{
if (!entries.TryGetValue(orderedName, out var entry) || entry.Count == 0)
continue;
result.Add(new TimingSnapshot(orderedName, entry.Count, entry.TotalTicks / (double)entry.Count));
used.Add(orderedName);
}
foreach (var kvp in entries)
{
if (used.Contains(kvp.Key) || kvp.Value.Count == 0)
continue;
result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count));
}
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";
}
}
}
+83
View File
@@ -0,0 +1,83 @@
using System.Runtime.InteropServices;
namespace Spectrum.Utilities
{
class Win32
{
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const int SM_XVIRTUALSCREEN = 76;
private const int SM_YVIRTUALSCREEN = 77;
private const int SM_CXVIRTUALSCREEN = 78;
private const int SM_CYVIRTUALSCREEN = 79;
public static bool IsWindowHidden = false;
public static (int Width, int Height) GetPrimaryScreenSize()
{
return (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
}
public static (int X, int Y, int Width, int Height) GetVirtualScreenBounds()
{
return (
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN)
);
}
[DllImport("user32.dll")]
private static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
private const uint WDA_NONE = 0x00000000;
private const uint WDA_MONITOR = 0x00000001;
private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
private const int ATTACH_PARENT_PROCESS = -1;
public static bool EnableAntiCapture(IntPtr windowHandle)
{
IsWindowHidden = true;
return SetWindowDisplayAffinity(windowHandle, WDA_EXCLUDEFROMCAPTURE);
}
public static bool DisableAntiCapture(IntPtr windowHandle)
{
IsWindowHidden = false;
return SetWindowDisplayAffinity(windowHandle, WDA_NONE);
}
public static void SetWindowPosition(IntPtr windowHandle, int x, int y)
{
SetWindowPos(windowHandle, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
public static void SetWindowBounds(IntPtr windowHandle, int x, int y, int width, int height)
{
SetWindowPos(windowHandle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
public static void EnsureConsoleAttached()
{
if (!AttachConsole(ATTACH_PARENT_PROCESS))
AllocConsole();
}
}
}