mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c227396a3
|
||
|
|
5800221000 | ||
|
|
03596041d3 | ||
|
|
c4013a2adc | ||
|
|
181e234bb2
|
||
|
|
e2aaf54216
|
||
|
|
0fbc91fde4
|
||
|
|
d8a71f9d91
|
||
|
|
c4075c4894
|
||
|
|
07de8e3012
|
||
|
|
dce1f835f0
|
||
|
|
3ff7bee7c7 | ||
|
|
f89fd135b4
|
||
|
|
51744ca9c7
|
||
|
|
4b4cebd517
|
||
|
|
55bc1e9c3a
|
||
|
|
859e2e1b43 | ||
|
|
dd13b99249 | ||
|
|
f8b90d7b63 | ||
|
|
8b529af9c4 | ||
|
|
aed83ebacd | ||
|
|
206135368a | ||
|
|
77d4b5d21b | ||
|
|
6a6fb2e2ee | ||
|
|
6bb49b90b7 |
@@ -1,159 +1,26 @@
|
||||
# Spectrum
|
||||
|
||||
A real-time computer vision application for object detection and automated targeting using OpenCV and C#. Spectrum captures screen regions, detects objects based on HSV color filtering, and can automatically move the mouse cursor to target detected objects.
|
||||
|
||||
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
||||
<img width="600" height="502" alt="Spectrum Menu" src="https://upld.zip/d9Z8Evjm.png" />
|
||||
## Features
|
||||
|
||||
- **Real-time Screen Capture**: Captures specific screen regions for processing
|
||||
- **HSV Color-based Detection**: Uses HSV color space filtering to detect objects
|
||||
- **Automated Targeting**: Automatically moves mouse cursor to detected targets
|
||||
- **Dataset Collection**: Automatically generates labeled datasets for machine learning
|
||||
- **Configurable Parameters**: Extensive configuration options via JSON file
|
||||
- **Visual Feedback**: Optional detection window showing real-time results
|
||||
- **Hotkey Support**: Configurable keybinding for activation
|
||||
|
||||
## Requirements
|
||||
|
||||
- .NET 8.0 or later
|
||||
- Windows operating system
|
||||
- OpenCV 4.11.0+
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository:
|
||||
```powershell
|
||||
git clone https://github.com/whoswhip/Spectrum.git
|
||||
cd Spectrum
|
||||
```
|
||||
|
||||
2. Build the project:
|
||||
```powershell
|
||||
dotnet build
|
||||
```
|
||||
|
||||
3. Run the application:
|
||||
```powershell
|
||||
dotnet run --project Spectrum
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The application uses a `config.json` file for configuration. On first run, a default configuration file will be created. You can modify the following parameters:
|
||||
|
||||
### Display Settings
|
||||
- `ImageWidth`: Width of the capture region (default: 640)
|
||||
- `ImageHeight`: Height of the capture region (default: 640)
|
||||
- `ShowDetectionWindow`: Show real-time detection window (default: true)
|
||||
|
||||
### Detection Settings
|
||||
- `UpperHSV`: Upper HSV color bounds for detection
|
||||
- `LowerHSV`: Lower HSV color bounds for detection
|
||||
- `YOffsetPercent`: Y-axis offset percentage for targeting (default: 0.8)
|
||||
- `XOffsetPercent`: X-axis offset percentage for targeting (default: 0.5)
|
||||
|
||||
### Control Settings
|
||||
- `EnableAim`: Enable automatic mouse movement (default: true)
|
||||
- `ClosestToMouse`: Target closest object to mouse cursor (default: true)
|
||||
- `Keybind`: Activation key code (default: 6 - mouse side button)
|
||||
- `Sensitivity`: Mouse movement sensitivity (default: 0.5)
|
||||
|
||||
### Data Collection
|
||||
- `CollectData`: Enable dataset collection (default: false)
|
||||
- `AutoLabel`: Enable automatic labeling for YOLO format (default: false)
|
||||
- `BackgroundImageInterval`: Interval for background image collection (default: 10)
|
||||
|
||||
### Example Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"ImageWidth": 640,
|
||||
"ImageHeight": 640,
|
||||
"YOffsetPercent": 0.8,
|
||||
"XOffsetPercent": 0.5,
|
||||
"EnableAim": true,
|
||||
"ClosestToMouse": true,
|
||||
"Keybind": 6,
|
||||
"Sensitivity": 0.1,
|
||||
"ShowDetectionWindow": true,
|
||||
"CollectData": false,
|
||||
"AutoLabel": false,
|
||||
"BackgroundImageInterval": 10,
|
||||
"UpperHSV": {
|
||||
"Val0": 150.0,
|
||||
"Val1": 255.0,
|
||||
"Val2": 229.0,
|
||||
"Val3": 0.0
|
||||
},
|
||||
"LowerHSV": {
|
||||
"Val0": 150.0,
|
||||
"Val1": 255.0,
|
||||
"Val2": 229.0,
|
||||
"Val3": 0.0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Start the application**: Run the executable or use `dotnet run`
|
||||
2. **Configure detection**: Adjust HSV values in `config.json` for your target objects
|
||||
3. **Activate detection**: Press the configured keybind (default: mouse side button)
|
||||
4. **Real-time targeting**: The application will automatically detect and target objects
|
||||
5. **Reload configuration**: Press F5 or R to reload configuration without restarting
|
||||
|
||||
### Keyboard Controls
|
||||
|
||||
- **Escape**: Exit the application
|
||||
- **F5/R**: Reload configuration from file
|
||||
- **Configured Keybind**: Activate detection and targeting
|
||||
- Extensive configuration file
|
||||
- Dataset collection
|
||||
- Multiple mouse movement paths
|
||||
- IMGui Menu
|
||||
- FOV Overlay
|
||||
- Detection Overlay
|
||||
- Triggerbot
|
||||
- Makcu Support
|
||||
|
||||
## Dataset Collection
|
||||
|
||||
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
|
||||
|
||||
- **Images**: Captured screenshots saved to `dataset/images/`
|
||||
- **Labels**: YOLO format annotation files saved to `dataset/labels/`
|
||||
- **Background Images**: Non-detection samples for training balance
|
||||
|
||||
This feature is useful for creating training datasets for machine learning models.
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **OpenCvSharp4**: OpenCV bindings for .NET
|
||||
- **Newtonsoft.Json**: JSON configuration handling
|
||||
- **System.Drawing.Common**: Screen capture and image processing
|
||||
|
||||
### Architecture
|
||||
|
||||
- **Program.cs**: Main application loop and screen capture
|
||||
- **Config.cs**: Configuration management and validation
|
||||
- **AutoLabeling.cs**: Dataset generation and YOLO labeling
|
||||
- **InputManager.cs**: Mouse input simulation
|
||||
|
||||
### Detection Pipeline
|
||||
|
||||
1. **Screen Capture**: Captures specified screen region
|
||||
2. **Color Space Conversion**: Converts BGR to HSV
|
||||
3. **Color Filtering**: Applies HSV range mask
|
||||
4. **Morphological Operations**: Dilates image to fill gaps
|
||||
5. **Contour Detection**: Finds object boundaries
|
||||
6. **Filtering**: Removes small contours (area < 100)
|
||||
7. **Target Selection**: Chooses closest target to reference point
|
||||
8. **Mouse Movement**: Moves cursor to calculated target position
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch
|
||||
3. Make your changes
|
||||
4. Test thoroughly
|
||||
5. Submit a pull request
|
||||
- **Images**: Captured screenshots saved to `dataset/images`
|
||||
- **Labels**: YOLO format annotation files saved to `dataset/labels`
|
||||
- **Background Images**: Screenshots without any labels, helps training balance
|
||||
This feature is very useful for creating training datasets for machine learning models.
|
||||
|
||||
## License
|
||||
|
||||
See LICENSE.txt for license information.
|
||||
See [LICENSE.txt](LICENSE.txt) for license information.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
|
||||
+156
-121
@@ -1,148 +1,183 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenCvSharp;
|
||||
using System.Numerics;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
public static class Config
|
||||
public class ConfigManager<T> where T : new()
|
||||
{
|
||||
#region Variables
|
||||
public static int ImageWidth { get; set; } = 640;
|
||||
public static int ImageHeight { get; set; } = 640;
|
||||
private readonly string _fileName;
|
||||
private FileSystemWatcher? _watcher;
|
||||
private T _data;
|
||||
|
||||
public static double YOffsetPercent { get; set; } = 0.8;
|
||||
public static double XOffsetPercent { get; set; } = 0.5;
|
||||
public static bool EnableAim { get; set; } = true;
|
||||
public static bool ClosestToMouse { get; set; } = true; // if false it will use the center of the screen
|
||||
public static int Keybind { get; set; } = 0x06; // first side button on mouse
|
||||
public static double Sensitivity { get; set; } = 0.5;
|
||||
public T Data => _data;
|
||||
|
||||
public static bool ShowDetectionWindow { get; set; } = true;
|
||||
|
||||
public static bool CollectData { get; set; } = false;
|
||||
public static bool AutoLabel { get; set; } = false; // collect data needs to be enabled
|
||||
public static int BackgroundImageInterval { get; set; } = 10; // after 10 loops with no detection, save a background image
|
||||
|
||||
public static Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public static Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
#endregion
|
||||
|
||||
public static void LoadConfig(bool silent = false)
|
||||
public ConfigManager(string fileName)
|
||||
{
|
||||
if (File.Exists("config.json"))
|
||||
_fileName = fileName;
|
||||
_data = new T();
|
||||
LoadConfig();
|
||||
}
|
||||
|
||||
public void LoadConfig(bool silent = false)
|
||||
{
|
||||
if (File.Exists(_fileName))
|
||||
{
|
||||
string config_content = File.ReadAllText("config.json");
|
||||
try
|
||||
{
|
||||
var config = JObject.Parse(config_content);
|
||||
ImageWidth = config["ImageWidth"]?.Value<int>() ?? ImageWidth;
|
||||
ImageHeight = config["ImageHeight"]?.Value<int>() ?? ImageHeight;
|
||||
|
||||
YOffsetPercent = config["YOffsetPercent"]?.Value<double>() ?? YOffsetPercent;
|
||||
XOffsetPercent = config["XOffsetPercent"]?.Value<double>() ?? XOffsetPercent;
|
||||
EnableAim = config["EnableAim"]?.Value<bool>() ?? EnableAim;
|
||||
ClosestToMouse = config["ClosestToMouse"]?.Value<bool>() ?? ClosestToMouse;
|
||||
Keybind = config["Keybind"]?.Value<int>() ?? Keybind;
|
||||
Sensitivity = config["Sensitivity"]?.Value<double>() ?? Sensitivity;
|
||||
|
||||
ShowDetectionWindow = config["ShowDetectionWindow"]?.Value<bool>() ?? ShowDetectionWindow;
|
||||
|
||||
CollectData = config["CollectData"]?.Value<bool>() ?? CollectData;
|
||||
AutoLabel = config["AutoLabel"]?.Value<bool>() ?? AutoLabel;
|
||||
BackgroundImageInterval = config["BackgroundImageInterval"]?.Value<int>() ?? BackgroundImageInterval;
|
||||
|
||||
UpperHSV = config["UpperHSV"]?.ToObject<Scalar>() ?? UpperHSV;
|
||||
LowerHSV = config["LowerHSV"]?.ToObject<Scalar>() ?? LowerHSV;
|
||||
|
||||
if (ImageWidth <= 0 || ImageHeight <= 0)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values.");
|
||||
Console.ResetColor();
|
||||
ImageWidth = 640;
|
||||
ImageHeight = 640;
|
||||
}
|
||||
if (YOffsetPercent < 0 || YOffsetPercent > 1 || XOffsetPercent < 0 || XOffsetPercent > 1)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Invalid offset percentages in config.json, using default values.");
|
||||
Console.ResetColor();
|
||||
YOffsetPercent = 0.8;
|
||||
XOffsetPercent = 0.5;
|
||||
}
|
||||
if (Keybind < 0 || Keybind > 255)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Invalid keybind in config.json, using default value.");
|
||||
Console.ResetColor();
|
||||
Keybind = 0x06;
|
||||
}
|
||||
if (Sensitivity < 0 || Sensitivity > 1)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Invalid sensitivity in config.json, using default value.");
|
||||
Console.ResetColor();
|
||||
Sensitivity = 0.5;
|
||||
}
|
||||
if (AutoLabel && !CollectData )
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
Console.WriteLine("[WARNING] AutoLabel is enabled but CollectData is not. Disabling AutoLabel.");
|
||||
Console.ResetColor();
|
||||
AutoLabel = false;
|
||||
}
|
||||
if (BackgroundImageInterval <= 0)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Invalid BackgroundImageInterval in config.json, using default value.");
|
||||
Console.ResetColor();
|
||||
}
|
||||
|
||||
SaveConfig();
|
||||
if (!silent)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine("[INFO] Configuration loaded successfully.");
|
||||
Console.ResetColor();
|
||||
}
|
||||
var json = File.ReadAllText(_fileName);
|
||||
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
|
||||
if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Error parsing config.json, using default values.");
|
||||
Console.ResetColor();
|
||||
LogManager.Log($"Failed to parse {_fileName}, using default values.", LogLevel.Error);
|
||||
_data = new T();
|
||||
SaveConfig();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
Console.WriteLine("[WARNING] config.json not found, using default values.");
|
||||
Console.ResetColor();
|
||||
LogManager.Log($"{_fileName} not found, creating a new one with default values.", LogLevel.Error);
|
||||
_data = new T();
|
||||
SaveConfig();
|
||||
}
|
||||
}
|
||||
public static void SaveConfig()
|
||||
|
||||
public void SaveConfig()
|
||||
{
|
||||
var config = new JObject
|
||||
{
|
||||
["ImageWidth"] = ImageWidth,
|
||||
["ImageHeight"] = ImageHeight,
|
||||
["YOffsetPercent"] = YOffsetPercent,
|
||||
["XOffsetPercent"] = XOffsetPercent,
|
||||
["EnableAim"] = EnableAim,
|
||||
["ClosestToMouse"] = ClosestToMouse,
|
||||
["Keybind"] = Keybind,
|
||||
["Sensitivity"] = Sensitivity,
|
||||
["ShowDetectionWindow"] = ShowDetectionWindow,
|
||||
["CollectData"] = CollectData,
|
||||
["AutoLabel"] = AutoLabel,
|
||||
["BackgroundImageInterval"] = BackgroundImageInterval,
|
||||
["UpperHSV"] = JToken.FromObject(UpperHSV),
|
||||
["LowerHSV"] = JToken.FromObject(LowerHSV)
|
||||
};
|
||||
File.WriteAllText("config.json", config.ToString(Formatting.Indented));
|
||||
File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented));
|
||||
}
|
||||
|
||||
public void StartFileWatcher()
|
||||
{
|
||||
if (_watcher != null) return;
|
||||
|
||||
_watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName)
|
||||
{
|
||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
|
||||
};
|
||||
_watcher.Changed += OnConfigFileChanged;
|
||||
_watcher.EnableRaisingEvents = true;
|
||||
LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info);
|
||||
}
|
||||
|
||||
public void StopFileWatcher()
|
||||
{
|
||||
if (_watcher == null) return;
|
||||
_watcher.EnableRaisingEvents = false;
|
||||
_watcher.Changed -= OnConfigFileChanged;
|
||||
_watcher.Dispose();
|
||||
_watcher = null;
|
||||
LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info);
|
||||
}
|
||||
|
||||
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
try
|
||||
{
|
||||
LoadConfig(true);
|
||||
LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum MovementType
|
||||
{
|
||||
Linear,
|
||||
CubicBezier,
|
||||
QuadraticBezier,
|
||||
Adaptive
|
||||
}
|
||||
public enum MovementMethod
|
||||
{
|
||||
MouseEvent,
|
||||
Makcu
|
||||
}
|
||||
public enum FovType
|
||||
{
|
||||
Circle,
|
||||
Rectangle
|
||||
}
|
||||
public enum CaptureMethod
|
||||
{
|
||||
GDI,
|
||||
DirectX
|
||||
}
|
||||
public class ConfigData
|
||||
{
|
||||
|
||||
// Image settings
|
||||
public int ImageWidth { get; set; } = 640;
|
||||
public int ImageHeight { get; set; } = 640;
|
||||
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||
|
||||
// Offset settings
|
||||
public double YOffsetPercent { get; set; } = 0.8;
|
||||
public double XOffsetPercent { get; set; } = 0.5;
|
||||
|
||||
// Aim settings
|
||||
public bool EnableAim { get; set; } = true;
|
||||
public bool ClosestToMouse { get; set; } = true;
|
||||
public Keys Keybind { get; set; } = Keys.XButton2;
|
||||
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 MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
||||
|
||||
// Triggerbot settings
|
||||
public bool TriggerBot { get; set; } = false;
|
||||
public Keys TriggerKey { get; set; } = Keys.XButton2;
|
||||
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||
public int TriggerRadius { get; set; } = 15; // pixels
|
||||
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||
|
||||
// Display settings
|
||||
public bool DrawDetections { get; set; } = true;
|
||||
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.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);
|
||||
|
||||
// Data collection settings
|
||||
public bool CollectData { get; set; } = false;
|
||||
public bool AutoLabel { get; set; } = false;
|
||||
public int BackgroundImageInterval { get; set; } = 10;
|
||||
|
||||
// Color settings
|
||||
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||
|
||||
// Misc
|
||||
public bool DebugMode { get; set; } = false;
|
||||
}
|
||||
public class ColorData
|
||||
{
|
||||
public List<ColorInfo> Colors { get; set; } = new List<ColorInfo>();
|
||||
}
|
||||
|
||||
public class ColorInfo
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Scalar Upper { get; set; }
|
||||
public Scalar Lower { get; set; }
|
||||
public ColorInfo(string name, Scalar upper, Scalar lower)
|
||||
{
|
||||
Name = name;
|
||||
Upper = upper;
|
||||
Lower = lower;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
public static class AutoLabeling
|
||||
{
|
||||
@@ -18,6 +14,8 @@ namespace Spectrum
|
||||
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;
|
||||
public static bool Started = false;
|
||||
|
||||
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
||||
{
|
||||
@@ -52,6 +50,9 @@ namespace Spectrum
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
|
||||
var labelContent = new StringBuilder();
|
||||
foreach (var box in boundingBoxes)
|
||||
{
|
||||
@@ -59,22 +60,22 @@ namespace Spectrum
|
||||
}
|
||||
File.WriteAllText(path, labelContent.ToString());
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Failed to save labels to " + path);
|
||||
Console.ResetColor();
|
||||
LogManager.Log($"[ERROR] Failed to save labels. Error: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
private static void SaveMatAsImage(Mat mat, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
Cv2.ImWrite(path, mat);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error saving image: {ex.Message}");
|
||||
LogManager.Log($"[ERROR] Failed to save image: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,9 +91,7 @@ namespace Spectrum
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Failed to process labeling data.");
|
||||
Console.ResetColor();
|
||||
LogManager.Log("[ERROR] Failed to process labeling data.", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,9 +103,7 @@ namespace Spectrum
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine("[ERROR] Failed to process background image data.");
|
||||
Console.ResetColor();
|
||||
LogManager.Log("[ERROR] Failed to process background image data.", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,12 +111,18 @@ namespace Spectrum
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||
{
|
||||
if (!Config.AutoLabel || filteredContours.Length == 0)
|
||||
|
||||
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
|
||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||
return;
|
||||
|
||||
Mat clone = mat.Clone();
|
||||
|
||||
if (labelingQueue.Count > 250)
|
||||
return;
|
||||
|
||||
Mat clone = mat.Clone();
|
||||
labelingQueue.Enqueue(new LabelingData
|
||||
{
|
||||
Mat = clone,
|
||||
@@ -130,12 +133,12 @@ namespace Spectrum
|
||||
|
||||
public static void AddBackgroundImage(Mat mat, bool detected)
|
||||
{
|
||||
if (!Config.AutoLabel)
|
||||
return;
|
||||
|
||||
detectionAttemps++;
|
||||
|
||||
if (detectionAttemps < Config.BackgroundImageInterval || detected)
|
||||
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
|
||||
return;
|
||||
|
||||
if (backgroundQueue.Count > 250)
|
||||
return;
|
||||
|
||||
Mat clone = mat.Clone();
|
||||
@@ -161,8 +164,8 @@ namespace Spectrum
|
||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
||||
string labelFileName = $"image_{imageCount:D6}.txt";
|
||||
|
||||
string imagePath = Path.Combine("dataset/images", imageFileName);
|
||||
string labelPath = Path.Combine("dataset/labels", labelFileName);
|
||||
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
|
||||
string labelPath = Path.Combine("bin/dataset/labels", labelFileName);
|
||||
|
||||
SaveMatAsImage(data.Mat, imagePath);
|
||||
|
||||
@@ -186,7 +189,7 @@ namespace Spectrum
|
||||
lock (lockObject)
|
||||
{
|
||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
||||
string imagePath = Path.Combine("dataset/images", imageFileName);
|
||||
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
|
||||
|
||||
SaveMatAsImage(data.Mat, imagePath);
|
||||
|
||||
@@ -204,6 +207,8 @@ namespace Spectrum
|
||||
{
|
||||
if (cancellationTokenSource != null)
|
||||
return;
|
||||
LogManager.Log("Starting auto labeling...", LogLevel.Info);
|
||||
Started = true;
|
||||
cancellationTokenSource = new CancellationTokenSource();
|
||||
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
||||
}
|
||||
@@ -211,6 +216,9 @@ namespace Spectrum
|
||||
{
|
||||
if (cancellationTokenSource == null)
|
||||
return;
|
||||
|
||||
LogManager.Log("Stopping auto labeling...", LogLevel.Info);
|
||||
Started = false;
|
||||
cancellationTokenSource.Cancel();
|
||||
backgroundTask?.Wait();
|
||||
cancellationTokenSource.Dispose();
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Drawing.Imaging;
|
||||
using Vortice.Direct3D;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using Size = System.Drawing.Size;
|
||||
using Rectangle = System.Drawing.Rectangle;
|
||||
using Point = System.Drawing.Point;
|
||||
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
public class CaptureManager : IDisposable
|
||||
{
|
||||
private readonly object _sync = new();
|
||||
private ID3D11Device? _device;
|
||||
private ID3D11DeviceContext? _context;
|
||||
private IDXGIOutputDuplication? _duplication;
|
||||
private ID3D11Texture2D? _stagingTex;
|
||||
private Size _desktopSize;
|
||||
public bool IsDirectXAvailable { get; private set; }
|
||||
public bool IsInitialized => _device != null && _duplication != null && _stagingTex != null;
|
||||
|
||||
public bool TryInitialize(int adapterIndex = 0, int outputIndex = 0)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
try
|
||||
{
|
||||
DisposeDxgiResources();
|
||||
|
||||
using var factory = DXGI.CreateDXGIFactory1<IDXGIFactory1>();
|
||||
if (factory.EnumAdapters1(adapterIndex, out var adapter).Failure)
|
||||
return false;
|
||||
if (adapter.EnumOutputs(outputIndex, out var output).Failure)
|
||||
{
|
||||
adapter.Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
var hr = D3D11.D3D11CreateDevice(
|
||||
adapter,
|
||||
DriverType.Unknown,
|
||||
DeviceCreationFlags.BgraSupport,
|
||||
new[]
|
||||
{
|
||||
FeatureLevel.Level_12_1,
|
||||
FeatureLevel.Level_12_0,
|
||||
FeatureLevel.Level_11_1,
|
||||
FeatureLevel.Level_11_0
|
||||
},
|
||||
out _device);
|
||||
|
||||
if (hr.Failure || _device == null)
|
||||
{
|
||||
output.Dispose();
|
||||
adapter.Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
_context = _device.ImmediateContext;
|
||||
|
||||
_duplication = output.QueryInterface<IDXGIOutput1>().DuplicateOutput(_device);
|
||||
var desc = output.Description;
|
||||
_desktopSize = new Size(desc.DesktopCoordinates.Right - desc.DesktopCoordinates.Left,
|
||||
desc.DesktopCoordinates.Bottom - desc.DesktopCoordinates.Top);
|
||||
|
||||
output.Dispose();
|
||||
adapter.Dispose();
|
||||
|
||||
EnsureStagingTexture(_desktopSize);
|
||||
|
||||
IsDirectXAvailable = true;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
IsDirectXAvailable = false;
|
||||
DisposeDxgiResources();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Bitmap? CaptureScreenshotDirectX(Rectangle bounds)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (!IsInitialized)
|
||||
{
|
||||
if (!TryInitialize())
|
||||
return null;
|
||||
}
|
||||
|
||||
bounds = Rectangle.Intersect(new Rectangle(Point.Empty, _desktopSize), bounds);
|
||||
if (bounds.Width <= 0 || bounds.Height <= 0) return null;
|
||||
|
||||
EnsureStagingTexture(_desktopSize);
|
||||
|
||||
IDXGIResource? desktopResource = null;
|
||||
bool frameAcquired = false;
|
||||
try
|
||||
{
|
||||
var result = _duplication!.AcquireNextFrame(16, out var frameInfo, out desktopResource);
|
||||
if (result.Failure)
|
||||
{
|
||||
if (result.Code == unchecked((int)Vortice.DXGI.ResultCode.AccessLost) ||
|
||||
result.Code == unchecked((int)Vortice.DXGI.ResultCode.DeviceRemoved))
|
||||
{
|
||||
TryInitialize();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
frameAcquired = true;
|
||||
|
||||
using var fullTex = desktopResource.QueryInterface<ID3D11Texture2D>();
|
||||
|
||||
_context!.CopySubresourceRegion(
|
||||
_stagingTex!,
|
||||
0,
|
||||
bounds.X,
|
||||
bounds.Y,
|
||||
0,
|
||||
fullTex,
|
||||
0,
|
||||
new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1)
|
||||
);
|
||||
|
||||
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);
|
||||
var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height),
|
||||
ImageLockMode.WriteOnly,
|
||||
PixelFormat.Format32bppArgb);
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
byte* srcBase = (byte*)map.DataPointer + bounds.Y * map.RowPitch + bounds.X * 4;
|
||||
int srcStride = map.RowPitch;
|
||||
int dstStride = bmpData.Stride;
|
||||
int rowBytes = bounds.Width * 4;
|
||||
|
||||
byte* dst = (byte*)bmpData.Scan0;
|
||||
byte* src = srcBase;
|
||||
for (int y = 0; y < bounds.Height; y++)
|
||||
{
|
||||
Buffer.MemoryCopy(src, dst, rowBytes, rowBytes);
|
||||
src += srcStride;
|
||||
dst += dstStride;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
bmp.UnlockBits(bmpData);
|
||||
_context.Unmap(_stagingTex!, 0);
|
||||
}
|
||||
|
||||
return bmp;
|
||||
}
|
||||
finally
|
||||
{
|
||||
desktopResource?.Dispose();
|
||||
if (frameAcquired)
|
||||
{
|
||||
try { _duplication?.ReleaseFrame(); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureStagingTexture(Size desktopSize)
|
||||
{
|
||||
if (_device == null) return;
|
||||
if (_stagingTex != null &&
|
||||
_stagingTex.Description.Width == desktopSize.Width &&
|
||||
_stagingTex.Description.Height == desktopSize.Height)
|
||||
return;
|
||||
|
||||
_stagingTex?.Dispose();
|
||||
_stagingTex = _device.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = desktopSize.Width,
|
||||
Height = desktopSize.Height,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.B8G8R8A8_UNorm,
|
||||
SampleDescription = new(1, 0),
|
||||
Usage = ResourceUsage.Staging,
|
||||
CPUAccessFlags = CpuAccessFlags.Read,
|
||||
BindFlags = BindFlags.None
|
||||
});
|
||||
}
|
||||
|
||||
public Bitmap? CaptureScreenshotGdi(Rectangle bounds)
|
||||
{
|
||||
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
using var g = Graphics.FromImage(bmp);
|
||||
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy);
|
||||
return bmp;
|
||||
}
|
||||
public bool TryInitializeDirectX(int adapterIndex = 0, int outputIndex = 0) => TryInitialize(adapterIndex, outputIndex);
|
||||
|
||||
private void DisposeDxgiResources()
|
||||
{
|
||||
_duplication?.Dispose();
|
||||
_stagingTex?.Dispose();
|
||||
_context?.Dispose();
|
||||
_device?.Dispose();
|
||||
_duplication = null;
|
||||
_stagingTex = null;
|
||||
_context = null;
|
||||
_device = null;
|
||||
IsDirectXAvailable = false;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
DisposeDxgiResources();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Input;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
class DetectionManager
|
||||
{
|
||||
private long iterationCount = 0;
|
||||
private long totalTime = 0;
|
||||
private Stopwatch stopwatch = new Stopwatch();
|
||||
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||
private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
private Renderer? renderer;
|
||||
private Thread? _detectionThread;
|
||||
private DateTime lastMenuToggle = DateTime.MinValue;
|
||||
private readonly CaptureManager _captureManager;
|
||||
|
||||
public DetectionManager(Renderer renderer)
|
||||
{
|
||||
this.renderer = renderer;
|
||||
_captureManager = Program.SharedCaptureManager;
|
||||
_detectionThread = new Thread(DetectionLoop)
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Spectrum Detection Thread",
|
||||
Priority = ThreadPriority.AboveNormal
|
||||
};
|
||||
_detectionThread.Start();
|
||||
}
|
||||
|
||||
private void DetectionLoop()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey))
|
||||
{
|
||||
stopwatch.Restart();
|
||||
bounds = new Rectangle(
|
||||
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
|
||||
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
|
||||
mainConfig.Data.ImageWidth,
|
||||
mainConfig.Data.ImageHeight
|
||||
);
|
||||
var screenshot = null as Bitmap;
|
||||
if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
||||
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
|
||||
else
|
||||
{
|
||||
if (_captureManager.IsInitialized)
|
||||
_captureManager.Dispose();
|
||||
screenshot = _captureManager.CaptureScreenshotGdi(bounds);
|
||||
}
|
||||
|
||||
if (screenshot == null)
|
||||
{
|
||||
LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug);
|
||||
Thread.Sleep(2);
|
||||
continue;
|
||||
}
|
||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||
Mat drawing = mat.Clone();
|
||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
||||
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
||||
Cv2.Dilate(mat, mat, null, iterations: 2);
|
||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
||||
|
||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray();
|
||||
|
||||
var processedContours = MergeOverlappingContours(filteredContours);
|
||||
|
||||
if (processedContours.Length > 0)
|
||||
{
|
||||
int refX = bounds.X + bounds.Width / 2;
|
||||
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
||||
|
||||
double minDist = double.MaxValue;
|
||||
OpenCvSharp.Point[]? closestContour = null;
|
||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
||||
|
||||
foreach (var contour in processedContours)
|
||||
{
|
||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
||||
foreach (var point in contour)
|
||||
{
|
||||
if (point.X < minX) minX = point.X;
|
||||
if (point.Y < minY) minY = point.Y;
|
||||
if (point.X > maxX) maxX = point.X;
|
||||
if (point.Y > maxY) maxY = point.Y;
|
||||
}
|
||||
int centerX = (minX + maxX) / 2;
|
||||
int centerY = (minY + maxY) / 2;
|
||||
|
||||
int absCenterX = centerX + bounds.X;
|
||||
int absCenterY = centerY + bounds.Y;
|
||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
||||
|
||||
if (dist < minDist)
|
||||
{
|
||||
minDist = dist;
|
||||
closestContour = contour;
|
||||
bestMinX = minX;
|
||||
bestMinY = minY;
|
||||
bestMaxX = maxX;
|
||||
bestMaxY = maxY;
|
||||
}
|
||||
|
||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
minX + bounds.X,
|
||||
minY + bounds.Y,
|
||||
(maxX - minX + 1),
|
||||
(maxY - minY + 1)
|
||||
);
|
||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
if (closestContour != null)
|
||||
{
|
||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
||||
int targetX = groupX + bounds.X;
|
||||
int targetY = groupY + bounds.Y;
|
||||
|
||||
if (mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||
}
|
||||
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
||||
{
|
||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||
}
|
||||
|
||||
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
||||
|
||||
if (mainConfig.Data.EnableAim)
|
||||
{
|
||||
InputManager.MoveMouse();
|
||||
}
|
||||
if (mainConfig.Data.TriggerBot)
|
||||
{
|
||||
var _ = InputManager.ClickMouse();
|
||||
}
|
||||
}
|
||||
if (mainConfig.Data.DebugMode)
|
||||
{
|
||||
iterationCount++;
|
||||
totalTime += stopwatch.ElapsedMilliseconds;
|
||||
}
|
||||
}
|
||||
else if (mainConfig.Data.CollectData)
|
||||
{
|
||||
if (mainConfig.Data.CollectData)
|
||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||
}
|
||||
screenshot?.Dispose();
|
||||
mat.Dispose();
|
||||
drawing.Dispose();
|
||||
|
||||
if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel))
|
||||
{
|
||||
AutoLabeling.StartLabeling();
|
||||
}
|
||||
else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.StopLabeling();
|
||||
}
|
||||
|
||||
if (iterationCount >= 1000 && mainConfig.Data.DebugMode)
|
||||
{
|
||||
LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info);
|
||||
int fps = (int)(iterationCount * 1000 / totalTime);
|
||||
LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info);
|
||||
LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info);
|
||||
iterationCount = 0;
|
||||
totalTime = 0;
|
||||
}
|
||||
}
|
||||
else if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
||||
{
|
||||
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
|
||||
lastMenuToggle = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||
{
|
||||
var contourRects = new List<(Rect rect, List<int> indices)>();
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
var rect = Cv2.BoundingRect(contours[i]);
|
||||
contourRects.Add((rect, new List<int> { i }));
|
||||
}
|
||||
bool merged;
|
||||
do
|
||||
{
|
||||
merged = false;
|
||||
for (int i = 0; i < contourRects.Count; i++)
|
||||
{
|
||||
var (rectA, indicesA) = contourRects[i];
|
||||
for (int j = i + 1; j < contourRects.Count; j++)
|
||||
{
|
||||
var (rectB, indicesB) = contourRects[j];
|
||||
if (rectA.IntersectsWith(rectB))
|
||||
{
|
||||
var newRect = new Rect(
|
||||
Math.Min(rectA.X, rectB.X),
|
||||
Math.Min(rectA.Y, rectB.Y),
|
||||
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
||||
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
||||
);
|
||||
var newIndices = new List<int>();
|
||||
newIndices.AddRange(indicesA);
|
||||
newIndices.AddRange(indicesB);
|
||||
contourRects[i] = (newRect, newIndices);
|
||||
contourRects.RemoveAt(j);
|
||||
merged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (merged) break;
|
||||
}
|
||||
} while (merged);
|
||||
|
||||
var mergedContours = new List<OpenCvSharp.Point[]>();
|
||||
foreach (var (rect, indices) in contourRects)
|
||||
{
|
||||
var points = new List<OpenCvSharp.Point>();
|
||||
foreach (var idx in indices)
|
||||
{
|
||||
points.AddRange(contours[idx]);
|
||||
}
|
||||
var hull = Cv2.ConvexHull(points);
|
||||
mergedContours.Add(hull);
|
||||
}
|
||||
return mergedContours.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||
<Costura />
|
||||
</Weavers>
|
||||
@@ -0,0 +1,115 @@
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{
|
||||
internal class MakcuMain
|
||||
{
|
||||
public static MakcuMouse MakcuInstance { get; private set; }
|
||||
|
||||
private static bool _isMakcuLoaded = false;
|
||||
|
||||
private static bool _isSubscribedToButtonEvents = false;
|
||||
|
||||
private const bool DefaultDebugLoggingForInternalCreation = false;
|
||||
private const bool DefaultSendInitCommandsForInternalCreation = true;
|
||||
|
||||
public static void ConfigureMakcuInstance(bool debugEnabled, bool sendInitCmds)
|
||||
{
|
||||
|
||||
LogManager.Log($"MakcuMain: Configuring MakcuInstance. Debug: {debugEnabled}, SendInitCmds: {sendInitCmds}", LogLevel.Debug);
|
||||
UnsubscribeFromButtonEvents();
|
||||
MakcuInstance?.Dispose();
|
||||
|
||||
MakcuInstance = new MakcuMouse(debugEnabled, sendInitCmds);
|
||||
_isMakcuLoaded = false;
|
||||
}
|
||||
|
||||
private static async Task<bool> InitializeMakcuDevice()
|
||||
{
|
||||
if (_isMakcuLoaded && MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||
{
|
||||
LogManager.Log("MakcuMain: InitializeMakcuDevice called, but Makcu is already loaded and connected.", LogLevel.Debug);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (MakcuInstance == null)
|
||||
{
|
||||
ConfigureMakcuInstance(true, DefaultSendInitCommandsForInternalCreation);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (MakcuInstance == null || !MakcuInstance.Init())
|
||||
{
|
||||
_isMakcuLoaded = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
string version = MakcuInstance.GetKmVersion();
|
||||
|
||||
_isMakcuLoaded = true;
|
||||
|
||||
SubscribeToButtonEvents();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_isMakcuLoaded = false;
|
||||
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||
{
|
||||
MakcuInstance.Close();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> Load() => await InitializeMakcuDevice();
|
||||
|
||||
public static void Unload()
|
||||
{
|
||||
UnsubscribeFromButtonEvents();
|
||||
if (MakcuInstance != null)
|
||||
{
|
||||
MakcuInstance.Close();
|
||||
}
|
||||
_isMakcuLoaded = false;
|
||||
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
||||
}
|
||||
|
||||
private static void SubscribeToButtonEvents()
|
||||
{
|
||||
if (MakcuInstance != null && !_isSubscribedToButtonEvents)
|
||||
{
|
||||
MakcuInstance.ButtonStateChanged += OnMakcuButtonStateChanged;
|
||||
_isSubscribedToButtonEvents = true;
|
||||
LogManager.Log("MakcuMain: Subscribed to MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
private static void UnsubscribeFromButtonEvents()
|
||||
{
|
||||
if (MakcuInstance != null && _isSubscribedToButtonEvents)
|
||||
{
|
||||
MakcuInstance.ButtonStateChanged -= OnMakcuButtonStateChanged;
|
||||
_isSubscribedToButtonEvents = false;
|
||||
LogManager.Log("MakcuMain: Unsubscribed from MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnMakcuButtonStateChanged(MakcuMouseButton button, bool isPressed)
|
||||
{
|
||||
|
||||
string state = isPressed ? "Pressed" : "Released";
|
||||
LogManager.Log($"{button} physical {state}!", LogLevel.Debug);
|
||||
}
|
||||
public static void DisposeInstance()
|
||||
{
|
||||
Unload();
|
||||
MakcuInstance?.Dispose();
|
||||
MakcuInstance = null;
|
||||
_isMakcuLoaded = false;
|
||||
LogManager.Log("MakcuMain: MakcuMouse instance disposed (null).", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
/// https://github.com/sdfgasfgr/Aimmy-Makcu/blob/master/Aimmy2/MouseMovementLibraries/MakcuSupport/MakcuMouse.cs
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{
|
||||
public enum MakcuMouseButton
|
||||
{
|
||||
Left = 0, Right = 1, Middle = 2, Mouse4 = 3, Mouse5 = 4
|
||||
}
|
||||
|
||||
public class MakcuMouse : IDisposable
|
||||
{
|
||||
private static readonly byte[] BaudChangeCommand = { 0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00 };
|
||||
|
||||
private SerialPort _serialPort;
|
||||
private readonly bool _debugLogging;
|
||||
private readonly bool _sendInitCommands;
|
||||
|
||||
private readonly object _serialLock = new object();
|
||||
private bool _isInitializedAndConnected = false;
|
||||
private Thread _listenerThread;
|
||||
private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false);
|
||||
private volatile bool _pauseListener = false;
|
||||
|
||||
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = new Dictionary<MakcuMouseButton, bool>();
|
||||
|
||||
public event Action<MakcuMouseButton, bool> ButtonStateChanged;
|
||||
|
||||
public string PortName { get; private set; }
|
||||
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
|
||||
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
||||
|
||||
|
||||
public MakcuMouse(bool debugLogging = false, bool sendInitCommands = true)
|
||||
{
|
||||
_debugLogging = debugLogging;
|
||||
_sendInitCommands = sendInitCommands;
|
||||
foreach (MakcuMouseButton btn in Enum.GetValues(typeof(MakcuMouseButton)))
|
||||
{
|
||||
_buttonStates[btn] = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Log(string message)
|
||||
{
|
||||
if (_debugLogging)
|
||||
{
|
||||
LogManager.Log($"[MakcuMouse {DateTime.Now:HH:mm:ss}] {message}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private string FindComPortInternal()
|
||||
{
|
||||
Log("Searching for COM port for Makcu device using SerialPort.GetPortNames() and connection test...");
|
||||
string[] availablePorts;
|
||||
try
|
||||
{
|
||||
availablePorts = SerialPort.GetPortNames();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (availablePorts == null || !availablePorts.Any())
|
||||
{
|
||||
Log("No COM ports available according to SerialPort.GetPortNames().");
|
||||
return null;
|
||||
}
|
||||
|
||||
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
||||
|
||||
foreach (string portName in availablePorts)
|
||||
{
|
||||
Log($"Testing port: {portName}");
|
||||
SerialPort testPort = null;
|
||||
try
|
||||
{
|
||||
|
||||
testPort = new SerialPort(portName, 115200)
|
||||
{
|
||||
ReadTimeout = 250,
|
||||
WriteTimeout = 500,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true
|
||||
};
|
||||
testPort.Open();
|
||||
Log($"Port {portName} opened at 115200 baud.");
|
||||
|
||||
Log($"Sending command to change baudrate to 4M on {portName}.");
|
||||
testPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||
testPort.BaseStream.Flush();
|
||||
Thread.Sleep(150);
|
||||
|
||||
testPort.Close();
|
||||
testPort.BaudRate = 4000000;
|
||||
testPort.Open();
|
||||
Log($"Port {portName} reopened at 4000000 baud.");
|
||||
|
||||
testPort.DiscardInBuffer();
|
||||
testPort.Write("km.version()\r\n");
|
||||
Log($"Command 'km.version()' sent to {portName}. Waiting for response...");
|
||||
|
||||
string response = "";
|
||||
try
|
||||
{
|
||||
response = testPort.ReadLine().Trim();
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Log($"Timeout waiting for 'km.version()' response on {portName}. Probably not the Makcu device.");
|
||||
testPort.Close();
|
||||
continue;
|
||||
}
|
||||
|
||||
Log($"Response from 'km.version()' on {portName}: '{response}'");
|
||||
|
||||
if (!string.IsNullOrEmpty(response) && (response.Contains("KMBOX") || response.Contains("Makcu") || response.Contains("MAKCU") || response.StartsWith("v") || char.IsDigit(response.FirstOrDefault())))
|
||||
{
|
||||
Log($"Makcu device found on port: {portName}! Version response: '{response}'");
|
||||
testPort.Close();
|
||||
return portName;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log($"Response from 'km.version()' on {portName} does not seem to be from a Makcu device. Response: '{response}'");
|
||||
}
|
||||
|
||||
testPort.Close();
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
Log($"Unauthorized access error on {portName}: {ex.Message} (Port might be in use).");
|
||||
}
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
Log($"Timeout on {portName} (possibly during baud rate change or write): {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to test port {portName}: {ex.GetType().Name} - {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (testPort != null && testPort.IsOpen)
|
||||
{
|
||||
testPort.Close();
|
||||
}
|
||||
testPort?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Log("Makcu device not found on any available COM ports after connection test.");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private bool OpenSerialPort(string portNameToOpen, int baudRate)
|
||||
{
|
||||
try
|
||||
{
|
||||
_serialPort?.Close();
|
||||
_serialPort?.Dispose();
|
||||
|
||||
Log($"Attempting to open {portNameToOpen} at {baudRate} baud.");
|
||||
_serialPort = new SerialPort(portNameToOpen, baudRate)
|
||||
{
|
||||
ReadTimeout = 100,
|
||||
WriteTimeout = 500,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true
|
||||
};
|
||||
_serialPort.Open();
|
||||
PortName = portNameToOpen;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to open {portNameToOpen} at {baudRate} baud. Error: {ex.Message}");
|
||||
_serialPort?.Dispose(); _serialPort = null; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ChangeBaudRateTo4M()
|
||||
{
|
||||
if (_serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Log("ChangeBaudRateTo4M: _serialPort is null or not open.");
|
||||
return false;
|
||||
}
|
||||
Log("Sending command to change baudrate to 4M.");
|
||||
try
|
||||
{
|
||||
_serialPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||
_serialPort.BaseStream.Flush();
|
||||
Thread.Sleep(150);
|
||||
|
||||
string currentPortName = _serialPort.PortName;
|
||||
_serialPort.Close();
|
||||
|
||||
_serialPort.BaudRate = 4000000;
|
||||
_serialPort.Open();
|
||||
|
||||
Log("Successfully changed to 4M baud."); return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error changing baudrate to 4M: {ex.Message}");
|
||||
|
||||
_serialPort?.Close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Init()
|
||||
{
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (_isInitializedAndConnected) { Log("MakcuMouse is already initialized."); return true; }
|
||||
|
||||
string portToUse = FindComPortInternal();
|
||||
if (string.IsNullOrEmpty(portToUse))
|
||||
{ Log("Init failed: Could not find a valid COM port for Makcu."); return false; }
|
||||
|
||||
|
||||
if (!OpenSerialPort(portToUse, 115200))
|
||||
{ Log($"Init failed: Could not open port {portToUse} at 115200 baud."); return false; }
|
||||
|
||||
if (!ChangeBaudRateTo4M())
|
||||
{ Log("Init failed: Could not change to 4M baud."); Close(); return false; }
|
||||
|
||||
_isInitializedAndConnected = true;
|
||||
PortName = portToUse;
|
||||
|
||||
if (_sendInitCommands)
|
||||
{
|
||||
if (!SendCommandInternal("km.buttons(1)", false, out _))
|
||||
{ Log("Init failed: Could not send 'km.buttons(1)'."); Close(); return false; }
|
||||
|
||||
_stopListenerEvent.Reset();
|
||||
_listenerThread = new Thread(() => ListenForButtonEvents(_debugLogging))
|
||||
{ IsBackground = true, Name = "MakcuButtonListener" };
|
||||
_listenerThread.Start();
|
||||
}
|
||||
Log($"MakcuMouse initialized successfully on port {PortName} at {BaudRate} baud."); return true;
|
||||
}
|
||||
}
|
||||
|
||||
private bool SendCommandInternal(string command, bool expectResponse, out string responseText, int responseTimeoutMs = 200)
|
||||
{
|
||||
responseText = null;
|
||||
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Log($"Error in SendCommand: Connection not open or initialized. Command: {command}");
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (!_serialPort.IsOpen)
|
||||
{
|
||||
Log($"Error in SendCommand (lock): Port not open. Command: {command}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_pauseListener = true;
|
||||
int originalReadTimeout = _serialPort.ReadTimeout;
|
||||
|
||||
try
|
||||
{
|
||||
if (expectResponse)
|
||||
{
|
||||
_serialPort.ReadTimeout = responseTimeoutMs;
|
||||
_serialPort.DiscardInBuffer();
|
||||
}
|
||||
|
||||
Log($"Sending: {command}");
|
||||
_serialPort.Write(command + "\r\n");
|
||||
|
||||
if (expectResponse)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string commandTrimmed = command.Trim();
|
||||
bool firstLineIsEcho = true;
|
||||
|
||||
while (stopwatch.ElapsedMilliseconds < responseTimeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = _serialPort.ReadLine().Trim();
|
||||
if (!string.IsNullOrEmpty(line))
|
||||
{
|
||||
Log($"Received (raw): {line}");
|
||||
if (line.Equals(commandTrimmed, StringComparison.OrdinalIgnoreCase) && firstLineIsEcho)
|
||||
{
|
||||
firstLineIsEcho = false;
|
||||
continue;
|
||||
}
|
||||
if (line.Equals("OK", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (sb.Length > 0) continue;
|
||||
}
|
||||
if (sb.Length > 0) sb.Append("\n");
|
||||
sb.Append(line);
|
||||
}
|
||||
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
||||
{
|
||||
Thread.Sleep(15);
|
||||
if (_serialPort.BytesToRead == 0) break;
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Log($"ReadLine() timeout in SendCommandInternal for '{command}'.");
|
||||
break;
|
||||
}
|
||||
catch (InvalidOperationException ioe) { Log($"InvalidOperationException in ReadLine (SendCommandInternal): {ioe.Message}"); _isInitializedAndConnected = false; Close(); return false; }
|
||||
catch (Exception ex) { Log($"Exception in ReadLine (SendCommandInternal): {ex.Message}"); break; }
|
||||
}
|
||||
stopwatch.Stop();
|
||||
responseText = sb.ToString().Trim();
|
||||
Log($"Final response for '{command}': '{responseText}' (Time: {stopwatch.ElapsedMilliseconds}ms)");
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (TimeoutException tex)
|
||||
{
|
||||
Log($"General timeout in SendCommandInternal for '{command}': {tex.Message}");
|
||||
return false;
|
||||
}
|
||||
catch (InvalidOperationException ioe)
|
||||
{
|
||||
Log($"General InvalidOperationException in SendCommandInternal (possibly port closed): {ioe.Message}");
|
||||
_isInitializedAndConnected = false; Close();
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"General exception in SendCommandInternal for '{command}': {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pauseListener = false;
|
||||
if (expectResponse)
|
||||
{
|
||||
_serialPort.ReadTimeout = originalReadTimeout;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ListenForButtonEvents(bool debug)
|
||||
{
|
||||
Log("Listener thread started. (PACKET PARSING MODE)");
|
||||
byte lastMask = 0x00; // <<-- CAMBIO CLAVE: Inicializar como todos los botones liberados
|
||||
var buttonMap = new Dictionary<int, MakcuMouseButton> {
|
||||
{0, MakcuMouseButton.Left}, {1, MakcuMouseButton.Right}, {2, MakcuMouseButton.Middle},
|
||||
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
||||
};
|
||||
|
||||
byte[] packetHeader = { 0x6B, 0x6D, 0x2E };
|
||||
int currentHeaderIndex = 0;
|
||||
|
||||
while (!_stopListenerEvent.IsSet)
|
||||
{
|
||||
if (!IsInitializedAndConnected || _pauseListener || _serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Thread.Sleep(20);
|
||||
currentHeaderIndex = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte byteRead = (byte)_serialPort.ReadByte();
|
||||
|
||||
if (byteRead == packetHeader[currentHeaderIndex])
|
||||
{
|
||||
currentHeaderIndex++;
|
||||
if (currentHeaderIndex == packetHeader.Length)
|
||||
{
|
||||
if (debug) Log($"Listener: Packet header {string.Join(",", packetHeader.Select(b => b.ToString("X2")))} detected!");
|
||||
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte currentMask = (byte)_serialPort.ReadByte();
|
||||
if (debug) Log($"Listener: Potential button mask byte: 0x{currentMask:X2}");
|
||||
|
||||
if (currentMask <= 0b00011111)
|
||||
{
|
||||
if (currentMask != lastMask)
|
||||
{
|
||||
if (debug) Log($"Listener: Processing button mask. New: 0x{currentMask:X2}, Prev: 0x{lastMask:X2}");
|
||||
byte changedBits = (byte)(currentMask ^ lastMask);
|
||||
|
||||
lock (_buttonStates)
|
||||
{
|
||||
foreach (var pair in buttonMap)
|
||||
{
|
||||
if ((changedBits & (1 << pair.Key)) != 0)
|
||||
{
|
||||
bool isPressed = (currentMask & (1 << pair.Key)) != 0;
|
||||
_buttonStates[pair.Value] = isPressed;
|
||||
if (debug) Log($"Listener: ---> EVENT: Button: {pair.Value}, IsPressed: {isPressed}");
|
||||
try
|
||||
{
|
||||
ButtonStateChanged?.Invoke(pair.Value, isPressed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Exception in ButtonStateChanged handler: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lastMask = currentMask;
|
||||
if (debug)
|
||||
{
|
||||
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
||||
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Any() ? string.Join(", ", pressedButtons) : "None")}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int expectedTailBytes = 2;
|
||||
for (int i = 0; i < expectedTailBytes; i++)
|
||||
{
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte consumedByte = (byte)_serialPort.ReadByte();
|
||||
if (debug) Log($"Listener: Consumed tail byte {i + 1}: 0x{consumedByte:X2}");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (debug) Log($"Listener: Expected tail byte {i + 1} but no data. Packet might be short.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (debug) Log("Listener: Header found, but no data for button mask byte. Packet might be short.");
|
||||
}
|
||||
currentHeaderIndex = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentHeaderIndex > 0 && debug)
|
||||
{
|
||||
Log($"Listener: Byte 0x{byteRead:X2} broke header sequence at index {currentHeaderIndex}. Resetting search.");
|
||||
}
|
||||
currentHeaderIndex = 0;
|
||||
if (byteRead == packetHeader[0])
|
||||
{
|
||||
currentHeaderIndex = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
if (debug) Log("Listener: TimeoutException during serial read.");
|
||||
currentHeaderIndex = 0;
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Log($"Listener: InvalidOperationException (port probably closed): {ex.Message}. Stopping listener.");
|
||||
_isInitializedAndConnected = false;
|
||||
currentHeaderIndex = 0;
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error in listener: {ex.GetType().Name} - {ex.Message}");
|
||||
currentHeaderIndex = 0;
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
Log("Listener thread terminated.");
|
||||
}
|
||||
|
||||
public bool Press(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(1)", false, out _);
|
||||
public bool Release(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(0)", false, out _);
|
||||
public bool Move(int x, int y) => SendCommandInternal($"km.move({x},{y})", false, out _);
|
||||
public bool MoveSmooth(int x, int y, int segments) => SendCommandInternal($"km.move({x},{y},{segments})", false, out _);
|
||||
public bool MoveBezier(int x, int y, int segments, int ctrlX, int ctrlY) => SendCommandInternal($"km.move({x},{y},{segments},{ctrlX},{ctrlY})", false, out _);
|
||||
public bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _);
|
||||
|
||||
public string GetKmVersion()
|
||||
{
|
||||
return SendCommandInternal("km.version()", true, out string response, 500) ? response : null;
|
||||
}
|
||||
private string GetButtonString(MakcuMouseButton button)
|
||||
{
|
||||
switch (button)
|
||||
{
|
||||
case MakcuMouseButton.Left: return "left";
|
||||
case MakcuMouseButton.Right: return "right";
|
||||
case MakcuMouseButton.Middle: return "middle";
|
||||
default: throw new ArgumentException($"Button {button} not supported for direct press/release actions (left/right/middle).");
|
||||
}
|
||||
}
|
||||
private string GetButtonLockString(MakcuMouseButton button)
|
||||
{
|
||||
switch (button)
|
||||
{
|
||||
case MakcuMouseButton.Left: return "ml";
|
||||
case MakcuMouseButton.Right: return "mr";
|
||||
case MakcuMouseButton.Middle: return "mm";
|
||||
case MakcuMouseButton.Mouse4: return "ms1";
|
||||
case MakcuMouseButton.Mouse5: return "ms2";
|
||||
default: throw new ArgumentException($"Button not supported for lock/catch: {button}");
|
||||
}
|
||||
}
|
||||
public Dictionary<MakcuMouseButton, bool> GetCurrentButtonStates()
|
||||
{ lock (_buttonStates) { return new Dictionary<MakcuMouseButton, bool>(_buttonStates); } }
|
||||
|
||||
public int GetCurrentButtonMask()
|
||||
{
|
||||
int mask = 0;
|
||||
lock (_buttonStates)
|
||||
{
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Left, out bool l) && l) mask |= (1 << (int)MakcuMouseButton.Left);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Right, out bool r) && r) mask |= (1 << (int)MakcuMouseButton.Right);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Middle, out bool m) && m) mask |= (1 << (int)MakcuMouseButton.Middle);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse4, out bool m4) && m4) mask |= (1 << (int)MakcuMouseButton.Mouse4);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse5, out bool m5) && m5) mask |= (1 << (int)MakcuMouseButton.Mouse5);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
private bool _disposedValue;
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
Close();
|
||||
_stopListenerEvent?.Dispose();
|
||||
}
|
||||
_disposedValue = true;
|
||||
}
|
||||
}
|
||||
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
|
||||
~MakcuMouse() { Dispose(false); }
|
||||
|
||||
public void Close()
|
||||
{
|
||||
Log("Closing MakcuMouse connection...");
|
||||
_isInitializedAndConnected = false;
|
||||
|
||||
if (_listenerThread != null)
|
||||
{
|
||||
_stopListenerEvent.Set();
|
||||
if (_listenerThread.IsAlive)
|
||||
{
|
||||
if (!_listenerThread.Join(TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
Log("Listener thread did not terminate in time.");
|
||||
}
|
||||
}
|
||||
_listenerThread = null;
|
||||
}
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (_serialPort != null)
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
{
|
||||
try { _serialPort.Close(); }
|
||||
catch (Exception ex) { Log($"Error closing port: {ex.Message}"); }
|
||||
}
|
||||
_serialPort.Dispose();
|
||||
_serialPort = null;
|
||||
}
|
||||
}
|
||||
PortName = null;
|
||||
Log("MakcuMouse connection closed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.MouseEvent
|
||||
{
|
||||
public class MouseMain
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
public static void Move(int x, int y)
|
||||
{
|
||||
mouse_event(0x0001, (uint)x, (uint)y, 0, 0);
|
||||
}
|
||||
|
||||
public static void ClickDown()
|
||||
{
|
||||
mouse_event(0x0002, 0, 0, 0, 0);
|
||||
}
|
||||
public static void ClickUp()
|
||||
{
|
||||
mouse_event(0x0004, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
public static class InputManager
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool GetCursorPos(out Point lpPoint);
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
private static Point lastDetection = new Point();
|
||||
private static long _lastMoveTicks = 0;
|
||||
private static readonly double _dtRef = 1.0 / 120.0;
|
||||
|
||||
private static double GetDeltaSeconds()
|
||||
{
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (_lastMoveTicks == 0)
|
||||
{
|
||||
_lastMoveTicks = now;
|
||||
return _dtRef;
|
||||
}
|
||||
long deltaTicks = now - _lastMoveTicks;
|
||||
_lastMoveTicks = now;
|
||||
double dt = (double)deltaTicks / Stopwatch.Frequency;
|
||||
|
||||
if (dt < 0.0001) dt = 0.0001; // 10k fps cap
|
||||
if (dt > 0.05) dt = 0.05; // 20 fps floor
|
||||
return dt;
|
||||
}
|
||||
|
||||
private static double TimeScaleFactor(double baseFactor, double deltaSeconds)
|
||||
{
|
||||
if (baseFactor <= 0) return 0;
|
||||
if (baseFactor >= 1) return 1;
|
||||
double k = deltaSeconds / _dtRef;
|
||||
return 1 - Math.Pow(1 - baseFactor, k);
|
||||
}
|
||||
|
||||
public static void MoveMouse()
|
||||
{
|
||||
Point reference = new Point();
|
||||
if (mainConfig.Data.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out reference);
|
||||
}
|
||||
else
|
||||
{
|
||||
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
Point start = new Point(reference.X, reference.Y);
|
||||
Point end = new Point(lastDetection.X, lastDetection.Y);
|
||||
|
||||
double dt = GetDeltaSeconds();
|
||||
double effSensitivity = TimeScaleFactor(mainConfig.Data.Sensitivity, dt);
|
||||
|
||||
Point newPosition = mainConfig.Data.AimMovementType switch
|
||||
{
|
||||
MovementType.CubicBezier => MovementPaths.CubicBezierMovement(start, end, effSensitivity),
|
||||
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
||||
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
||||
_ => end
|
||||
};
|
||||
|
||||
if (mainConfig.Data.EmaSmoothening)
|
||||
{
|
||||
double emaAlpha = TimeScaleFactor(mainConfig.Data.EmaSmootheningFactor, dt);
|
||||
newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha));
|
||||
newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha));
|
||||
}
|
||||
|
||||
int deltaX = newPosition.X - reference.X;
|
||||
int deltaY = newPosition.Y - reference.Y;
|
||||
|
||||
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
||||
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
|
||||
return;
|
||||
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
||||
else
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ClickMouse()
|
||||
{
|
||||
if (!mainConfig.Data.TriggerBot)
|
||||
return;
|
||||
if (!IsKeyOrMouseDown(mainConfig.Data.TriggerKey) || mainConfig.Data.TriggerKey == Keys.None)
|
||||
return;
|
||||
|
||||
var currentPosition = new Point();
|
||||
if (mainConfig.Data.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out currentPosition);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentPosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
if (mainConfig.Data.TriggerDelay > 0)
|
||||
await Task.Delay(mainConfig.Data.TriggerDelay);
|
||||
|
||||
int radius = mainConfig.Data.TriggerRadius;
|
||||
|
||||
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
|
||||
{
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
}
|
||||
await Task.Delay(mainConfig.Data.TriggerDuration);
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var dist = Math.Sqrt(Math.Pow(currentPosition.X - lastDetection.X, 2) + Math.Pow(currentPosition.Y - lastDetection.Y, 2));
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetLastDetection(Point point)
|
||||
{
|
||||
lastDetection = point;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern short GetAsyncKeyState(int vKey);
|
||||
|
||||
private static readonly Keys[] MouseKeys =
|
||||
{
|
||||
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
||||
};
|
||||
|
||||
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<Keys>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
||||
bool subscribedToMakcu = false;
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady())
|
||||
{
|
||||
makcuHandler = (btn, isPressed) =>
|
||||
{
|
||||
if (!isPressed) return;
|
||||
var key = MapMakcuButtonToKeys(btn);
|
||||
if (key.HasValue)
|
||||
{
|
||||
tcs.TrySetResult(key.Value);
|
||||
}
|
||||
};
|
||||
MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler;
|
||||
subscribedToMakcu = true;
|
||||
}
|
||||
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (tcs.Task.IsCompleted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (int key = 0x08; key <= 0xFE; key++)
|
||||
{
|
||||
if ((GetAsyncKeyState(key) & 0x8000) != 0)
|
||||
{
|
||||
tcs.TrySetResult((Keys)key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var mouseKey in MouseKeys)
|
||||
{
|
||||
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
||||
{
|
||||
tcs.TrySetResult(mouseKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (cancellationToken?.IsCancellationRequested == true)
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
return;
|
||||
}
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||
{
|
||||
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||
}
|
||||
}
|
||||
})
|
||||
{ IsBackground = true };
|
||||
|
||||
tcs.Task.ContinueWith(_ =>
|
||||
{
|
||||
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||
{
|
||||
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
|
||||
thread.Start();
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private static bool EnsureMakcuReady()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||
var ok = MakcuMain.Load().GetAwaiter().GetResult();
|
||||
if (ok && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||
|
||||
LogManager.Log("Makcu not ready. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
MakcuMain.Unload();
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
LogManager.Log("Makcu initialization threw an exception. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
MakcuMain.Unload();
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Keys? MapMakcuButtonToKeys(MakcuMouseButton btn)
|
||||
{
|
||||
return btn switch
|
||||
{
|
||||
MakcuMouseButton.Left => Keys.LButton,
|
||||
MakcuMouseButton.Right => Keys.RButton,
|
||||
MakcuMouseButton.Middle => Keys.MButton,
|
||||
MakcuMouseButton.Mouse4 => Keys.XButton1,
|
||||
MakcuMouseButton.Mouse5 => Keys.XButton2,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
public static bool IsKeyOrMouseDown(Keys key)
|
||||
{
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true)
|
||||
{
|
||||
var makcuBtn = MapKeysToMakcuButton(key);
|
||||
if (makcuBtn.HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var states = MakcuMain.MakcuInstance.GetCurrentButtonStates();
|
||||
|
||||
return states.TryGetValue(makcuBtn.Value, out var pressed) && pressed;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
|
||||
}
|
||||
|
||||
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
|
||||
{
|
||||
return key switch
|
||||
{
|
||||
Keys.LButton => MakcuMouseButton.Left,
|
||||
Keys.RButton => MakcuMouseButton.Right,
|
||||
Keys.MButton => MakcuMouseButton.Middle,
|
||||
Keys.XButton1 => MakcuMouseButton.Mouse4,
|
||||
Keys.XButton2 => MakcuMouseButton.Mouse5,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
public class MovementPaths
|
||||
{
|
||||
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||
public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
|
||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
||||
|
||||
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||
}
|
||||
public static Point CubicBezierMovement(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
||||
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
||||
return CubicBezier(start, end, control1, control2, t);
|
||||
}
|
||||
|
||||
public static Point CubicBezierCurvedMovement(Point start, Point end, double t, double curvature = 0.25)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
curvature = Math.Max(0, Math.Min(1, curvature));
|
||||
double dx = end.X - start.X;
|
||||
double dy = end.Y - start.Y;
|
||||
double dist = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (dist == 0) return start;
|
||||
double nx = -dy / dist;
|
||||
double ny = dx / dist;
|
||||
double offset = dist * curvature;
|
||||
var control1 = new Point((int)Math.Round(start.X + dx / 3 + nx * offset), (int)Math.Round(start.Y + dy / 3 + ny * offset));
|
||||
var control2 = new Point((int)Math.Round(start.X + 2 * dx / 3 + nx * offset), (int)Math.Round(start.Y + 2 * dy / 3 + ny * offset));
|
||||
return CubicBezier(start, end, control1, control2, t);
|
||||
}
|
||||
|
||||
public static Point LinearInterpolation(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
int x = (int)Math.Round(start.X + t * (end.X - start.X));
|
||||
int y = (int)Math.Round(start.Y + t * (end.Y - start.Y));
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
public static Point CurvedMovement(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
||||
return QuadraticBezier(start, end, control, t);
|
||||
}
|
||||
public static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
||||
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
||||
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||
}
|
||||
|
||||
public static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
||||
{
|
||||
double dx = end.X - start.X;
|
||||
double dy = end.Y - start.Y;
|
||||
double distance = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (distance == 0) return start;
|
||||
double stepSize = Math.Max(0, sensitivity) * distance;
|
||||
stepSize = Math.Min(stepSize, distance);
|
||||
double directionX = dx / distance;
|
||||
double directionY = dy / distance;
|
||||
int newX = (int)Math.Round(start.X + directionX * stepSize);
|
||||
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
||||
return new Point(newX, newY);
|
||||
}
|
||||
public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor)
|
||||
{
|
||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||
return currentValue * smoothingFactor + previousValue * (1 - smoothingFactor);
|
||||
}
|
||||
|
||||
public static Point EmaSmoothing(Point previous, Point current, double smoothingFactor)
|
||||
{
|
||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||
int x = (int)Math.Round(EmaSmoothing(previous.X, current.X, smoothingFactor));
|
||||
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
||||
return new Point(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
public static class InputManager
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetCursorPos(out POINT lpPoint);
|
||||
|
||||
private struct POINT
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
}
|
||||
// AIMMY V2 CODE - https://github.com/babyhamsta/Aimmy/blob/Aimmy-V2/Aimmy2/InputLogic/MouseManager.cs Line 34 - 50
|
||||
private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||
{
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
|
||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
||||
|
||||
return new Point((int)x, (int)y);
|
||||
}
|
||||
|
||||
public static void MoveMouse(Point target)
|
||||
{
|
||||
POINT reference = new POINT();
|
||||
if (Config.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out reference);
|
||||
}
|
||||
else
|
||||
{
|
||||
// center of the screen
|
||||
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Point start = new Point(reference.X, reference.Y);
|
||||
Point end = new Point(target.X, target.Y);
|
||||
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);
|
||||
Point newPosition = CubicBezier(start, end, control1, control2, Config.Sensitivity);
|
||||
|
||||
int deltaX = newPosition.X - reference.X;
|
||||
int deltaY = newPosition.Y - reference.Y;
|
||||
|
||||
|
||||
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
public class LogManager
|
||||
{
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
public enum LogLevel
|
||||
{
|
||||
Debug,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Critical
|
||||
}
|
||||
public class LogEntry
|
||||
{
|
||||
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 override string ToString()
|
||||
{
|
||||
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
||||
}
|
||||
}
|
||||
private static List<LogEntry> _logEntries = new List<LogEntry>();
|
||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
if (mainConfig == null)
|
||||
mainConfig = Program.mainConfig;
|
||||
if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached))
|
||||
return;
|
||||
|
||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||
Debug.WriteLine(logMessage);
|
||||
_logEntries.Add(new LogEntry(level, message));
|
||||
}
|
||||
public static void SaveLog(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var logContent = new StringBuilder();
|
||||
foreach (var entry in _logEntries)
|
||||
{
|
||||
logContent.AppendLine(entry.ToString());
|
||||
}
|
||||
File.WriteAllText(filePath, logContent.ToString());
|
||||
Log($"Log saved to {filePath}", LogLevel.Info);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to save log: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
public static void ClearLog()
|
||||
{
|
||||
_logEntries.Clear();
|
||||
Log("Log cleared.", LogLevel.Info);
|
||||
}
|
||||
|
||||
public static void OpenLogFolder()
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "explorer.exe",
|
||||
Arguments = Directory.GetCurrentDirectory(),
|
||||
UseShellExecute = true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-143
@@ -1,165 +1,80 @@
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Internal.Vectors;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using Spectrum.Detection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||
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 long iterationCount = 0;
|
||||
public static long totalTime = 0;
|
||||
private static DetectionManager? detectionManager;
|
||||
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
|
||||
|
||||
|
||||
static void Main()
|
||||
{
|
||||
Config.LoadConfig();
|
||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
bounds = new Rectangle(
|
||||
(screenSize.Width - Config.ImageWidth) / 2,
|
||||
(screenSize.Height - Config.ImageHeight) / 2,
|
||||
Config.ImageWidth,
|
||||
Config.ImageHeight
|
||||
);
|
||||
|
||||
if (Config.ShowDetectionWindow)
|
||||
Thread renderThread = new Thread(() =>
|
||||
{
|
||||
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
|
||||
Cv2.WaitKey(1);
|
||||
try
|
||||
{
|
||||
renderer = new Renderer(SharedCaptureManager);
|
||||
bool dxok = SharedCaptureManager.TryInitializeDirectX();
|
||||
if (!dxok)
|
||||
{
|
||||
LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning);
|
||||
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
||||
}
|
||||
renderer.Run();
|
||||
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"Failed to start renderer: {ex.Message}", LogManager.LogLevel.Error);
|
||||
}
|
||||
});
|
||||
renderThread.Start();
|
||||
|
||||
string[] dirs = { "bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs" };
|
||||
foreach (var dir in dirs)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
LogManager.Log($"Created directory: {dir}", LogManager.LogLevel.Info);
|
||||
}
|
||||
}
|
||||
if (Config.AutoLabel)
|
||||
|
||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
mainConfig.LoadConfig();
|
||||
mainConfig.StartFileWatcher();
|
||||
|
||||
if (mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.StartLabeling();
|
||||
}
|
||||
|
||||
Directory.CreateDirectory("dataset");
|
||||
Directory.CreateDirectory("dataset/images");
|
||||
Directory.CreateDirectory("dataset/labels");
|
||||
|
||||
while (true)
|
||||
if (colorConfig.Data.Colors.Count == 0)
|
||||
{
|
||||
if (Console.KeyAvailable)
|
||||
{
|
||||
var key = Console.ReadKey(true).Key;
|
||||
if (key == ConsoleKey.Escape)
|
||||
{
|
||||
if (Config.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.DestroyAllWindows();
|
||||
}
|
||||
}
|
||||
else if (key == ConsoleKey.F5 || key == ConsoleKey.R)
|
||||
{
|
||||
Config.LoadConfig(true);
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine("[INFO] Configuration reloaded.");
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
|
||||
if (SystemHelper.GetAsyncKeyState(Config.Keybind) < 0)
|
||||
{
|
||||
var screenshot = CaptureScreenshot(bounds);
|
||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||
Mat drawing = mat.Clone(); // clone for drawing
|
||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); // convert to hsv
|
||||
Cv2.InRange(mat, Config.LowerHSV, Config.UpperHSV, mat); // apply mask
|
||||
Cv2.Dilate(mat, mat, null, iterations: 2); // dilate to fill gaps
|
||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); // threshold to binary
|
||||
|
||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray();
|
||||
if (filteredContours.Length > 0)
|
||||
{
|
||||
int refX = bounds.X + bounds.Width / 2;
|
||||
int refY = bounds.Y + (int)(bounds.Height * Config.YOffsetPercent);
|
||||
|
||||
double minDist = double.MaxValue;
|
||||
OpenCvSharp.Point[]? closestContour = null;
|
||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
||||
|
||||
foreach (var contour in filteredContours)
|
||||
{
|
||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
||||
foreach (var point in contour)
|
||||
{
|
||||
if (point.X < minX) minX = point.X;
|
||||
if (point.Y < minY) minY = point.Y;
|
||||
if (point.X > maxX) maxX = point.X;
|
||||
if (point.Y > maxY) maxY = point.Y;
|
||||
}
|
||||
int centerX = (minX + maxX) / 2;
|
||||
int centerY = (minY + maxY) / 2;
|
||||
|
||||
int absCenterX = centerX + bounds.X;
|
||||
int absCenterY = centerY + bounds.Y;
|
||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
||||
|
||||
if (dist < minDist)
|
||||
{
|
||||
minDist = dist;
|
||||
closestContour = contour;
|
||||
bestMinX = minX;
|
||||
bestMinY = minY;
|
||||
bestMaxX = maxX;
|
||||
bestMaxY = maxY;
|
||||
}
|
||||
}
|
||||
|
||||
if (closestContour != null)
|
||||
{
|
||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - Config.XOffsetPercent));
|
||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - Config.YOffsetPercent));
|
||||
int targetX = groupX + bounds.X;
|
||||
int targetY = groupY + bounds.Y;
|
||||
|
||||
if (Config.AutoLabel)
|
||||
{
|
||||
AutoLabeling.AddToQueue(drawing, bounds, filteredContours);
|
||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||
}
|
||||
|
||||
if (Config.EnableAim)
|
||||
{
|
||||
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
|
||||
}
|
||||
|
||||
if (Config.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.DrawContours(drawing, filteredContours, -1, Scalar.Red, 2);
|
||||
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
|
||||
Cv2.ImShow("Spectrum Detection", drawing);
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (Config.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.ImShow("Spectrum Detection", drawing);
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Config.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
}
|
||||
colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(150, 255, 229), new Scalar(150, 255, 229)));
|
||||
colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
|
||||
colorConfig.SaveConfig();
|
||||
colorConfig.LoadConfig(true);
|
||||
mainConfig.LoadConfig(true);
|
||||
}
|
||||
}
|
||||
public static Bitmap CaptureScreenshot(Rectangle bounds)
|
||||
{
|
||||
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
using (Graphics g = Graphics.FromImage(bitmap))
|
||||
|
||||
Thread.Sleep(1000);
|
||||
|
||||
if (renderer == null)
|
||||
{
|
||||
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
|
||||
LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error);
|
||||
return;
|
||||
}
|
||||
return bitmap;
|
||||
|
||||
detectionManager = new DetectionManager(renderer);
|
||||
}
|
||||
}
|
||||
public static class SystemHelper
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<PublishAot>False</PublishAot>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<UseWindowsForms>True</UseWindowsForms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<TargetFrameworks></TargetFrameworks>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ClickableTransparentOverlay" Version="11.1.0" />
|
||||
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.6" />
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.2.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spectrum", "Spectrum.csproj", "{C33459B7-8D67-9FB2-0CDB-25002B06AE60}"
|
||||
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
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.Build.0 = Debug|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.ActiveCfg = Release|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {44E9592E-6BC3-403A-9503-398EC3EFC57C}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
Reference in New Issue
Block a user