mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92bea63815
|
||
|
|
4e4a57a9b2
|
||
|
|
4d7dfffc5c
|
||
|
|
fa500f4c30
|
||
|
|
c75c0551ee
|
||
|
|
db712a54f9
|
||
|
|
23a28d56ff
|
||
|
|
b9756609ee
|
||
|
|
313cea1c35
|
||
|
|
378c189f03
|
||
|
|
3b5ebc789b
|
||
|
|
8ca185a0fb
|
||
|
|
529576d972
|
||
|
|
153c719eb5
|
||
|
|
b0529cd841
|
||
|
|
c66aa20fca
|
||
|
|
57a3a1782b
|
||
|
|
daf595b47f
|
||
|
|
4e3f39a323
|
||
|
|
cce3b91be8
|
||
|
|
f1ca1ee9ee
|
||
|
|
f0014bc65d
|
||
|
|
a6f65b1f17
|
||
|
|
3f220c7de9
|
||
|
|
b556351010
|
||
|
|
f1d376174b
|
||
|
|
4a0af6bb1b | ||
|
|
bdf3be13ab
|
||
|
|
2fa0b4ac2d
|
||
|
|
ab0ca784f4
|
||
|
|
86d7e3ffbd
|
||
|
|
c14427bf81
|
||
|
|
5832f92edc
|
||
|
|
c92517af5c
|
||
|
|
0deecc8663
|
||
|
|
d0d417e6ab
|
||
|
|
3c227396a3
|
||
|
|
5800221000 | ||
|
|
03596041d3 | ||
|
|
c4013a2adc | ||
|
|
181e234bb2
|
||
|
|
e2aaf54216
|
||
|
|
0fbc91fde4
|
||
|
|
d8a71f9d91
|
||
|
|
c4075c4894
|
||
|
|
07de8e3012
|
||
|
|
dce1f835f0
|
||
|
|
3ff7bee7c7 | ||
|
|
f89fd135b4
|
||
|
|
51744ca9c7
|
||
|
|
4b4cebd517
|
||
|
|
55bc1e9c3a
|
||
|
|
859e2e1b43 | ||
|
|
dd13b99249 | ||
|
|
f8b90d7b63 |
@@ -361,3 +361,4 @@ MigrationBackup/
|
|||||||
|
|
||||||
# Fody - auto-generated XML schema
|
# Fody - auto-generated XML schema
|
||||||
FodyWeavers.xsd
|
FodyWeavers.xsd
|
||||||
|
Spectrum/imgui.ini
|
||||||
|
|||||||
@@ -1,55 +1,15 @@
|
|||||||
# Spectrum
|
# Spectrum
|
||||||
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
||||||
|
<img width="700" height="603" alt="Spectrum Menu" src="https://upld.zip/PYRXWN5Y.png" />
|
||||||
## Features
|
## Features
|
||||||
- Extensive configuration file
|
- Extensive configuration file
|
||||||
- Dataset collection
|
- Dataset collection
|
||||||
- Multiple mouse movement paths
|
- Multiple mouse movement paths
|
||||||
|
- IMGui Menu
|
||||||
## Configuration
|
- FOV Overlay
|
||||||
On first run, a default configuration file is created.
|
- Detection Overlay
|
||||||
### Parameters
|
- Triggerbot
|
||||||
#### `ImageSettings`
|
- Makcu Support
|
||||||
`ImageWidth`: 1 - ScreenSize (Default: 640)
|
|
||||||
|
|
||||||
`ImageHeight`: 1 - ScreenSize (Default: 640)
|
|
||||||
#### `OffsetSettings
|
|
||||||
`YOffsetPercent`: 0.0 - 1 (Default: 0.8)
|
|
||||||
|
|
||||||
`XOffsetPercent`: 0.0 - 1 (Default: 0.5)
|
|
||||||
#### `AimSettings`
|
|
||||||
`EnableAim`: true or false (Default: true)
|
|
||||||
|
|
||||||
`ClosestToMouse`: true or false (Default: true)
|
|
||||||
|
|
||||||
`Keybind`: 1 - 254 (Default: 6), these are [virtual key codes](https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes)
|
|
||||||
|
|
||||||
`Sensitivity`: 0.1 - 2 (Default: 0.5)
|
|
||||||
|
|
||||||
`AimMovementType`: CubicBezier, Linear & Adaptive (Default: CubicBezier)
|
|
||||||
|
|
||||||
#### `DisplaySettings`
|
|
||||||
`ShowDetectionWindow`: true or false (Default: true)
|
|
||||||
|
|
||||||
#### `DataCollectionSettings`
|
|
||||||
`CollectData`: true or false (Default: false)
|
|
||||||
|
|
||||||
`AutoLabel`: true or false (Default: false), this is dependent on `CollectData`
|
|
||||||
|
|
||||||
`BackgroundImageInterval`: 1 - 100 (Default: 10)
|
|
||||||
|
|
||||||
#### `ColorSettings`
|
|
||||||
`UpperHSV`
|
|
||||||
- `Val0`: 0 - 255 (Default: 150) Hue
|
|
||||||
- `Val1`: 0 - 255 (Default: 255) Saturation
|
|
||||||
- `Val2`: 0 - 255 (Default: 229) Value
|
|
||||||
- `Val3`: 0 (Default: 0) ?
|
|
||||||
|
|
||||||
`LowerHSV`
|
|
||||||
- `Val0`: 0 - 255 (Default: 150) Hue
|
|
||||||
- `Val1`: 0 - 255 (Default: 255) Saturation
|
|
||||||
- `Val2`: 0 - 255 (Default: 229) Value
|
|
||||||
- `Val3`: 0 (Default: 0) ?
|
|
||||||
|
|
||||||
## Dataset Collection
|
## Dataset Collection
|
||||||
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
|
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 308 B |
+590
-223
@@ -1,257 +1,624 @@
|
|||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Linq;
|
|
||||||
using OpenCvSharp;
|
using OpenCvSharp;
|
||||||
|
using Spectrum.Utilities;
|
||||||
|
using System.Numerics;
|
||||||
|
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum
|
||||||
{
|
{
|
||||||
public static class Config
|
public class ConfigManager<T> where T : new()
|
||||||
{
|
{
|
||||||
private static FileSystemWatcher? _configWatcher;
|
private readonly string _defaultFilePath;
|
||||||
#region Variables
|
private readonly string _configDirectory;
|
||||||
|
private FileSystemWatcher? _fileWatcher;
|
||||||
|
private FileSystemWatcher? _directoryWatcher;
|
||||||
|
private T _data;
|
||||||
|
private string _currentConfigName;
|
||||||
|
private string _currentFilePath;
|
||||||
|
private readonly List<string> _availableConfigs;
|
||||||
|
|
||||||
public enum MovementType
|
public T Data => _data;
|
||||||
|
public string CurrentConfigName => _currentConfigName;
|
||||||
|
public IReadOnlyList<string> AvailableConfigs => _availableConfigs.AsReadOnly();
|
||||||
|
|
||||||
|
public ConfigManager(string defaultFilePath, string configDirectory = "")
|
||||||
{
|
{
|
||||||
Linear,
|
_defaultFilePath = defaultFilePath;
|
||||||
CubicBezier,
|
_configDirectory = string.IsNullOrWhiteSpace(configDirectory)
|
||||||
QuadraticBezier,
|
? Path.GetDirectoryName(defaultFilePath) ?? "configs"
|
||||||
Adaptive
|
: configDirectory;
|
||||||
|
_currentConfigName = Path.GetFileNameWithoutExtension(defaultFilePath);
|
||||||
|
_currentFilePath = defaultFilePath;
|
||||||
|
_data = new T();
|
||||||
|
_availableConfigs = [];
|
||||||
|
|
||||||
|
if (!Directory.Exists(_configDirectory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(_configDirectory);
|
||||||
}
|
}
|
||||||
// Image settings
|
|
||||||
public static int ImageWidth { get; set; } = 640;
|
|
||||||
public static int ImageHeight { get; set; } = 640;
|
|
||||||
|
|
||||||
// Offset settings
|
UpdateAvailableConfigs();
|
||||||
public static double YOffsetPercent { get; set; } = 0.8;
|
StartDirectoryWatcher();
|
||||||
public static double XOffsetPercent { get; set; } = 0.5;
|
LoadConfig();
|
||||||
|
}
|
||||||
|
|
||||||
// Aim settings
|
public void LoadConfig(string filename = "")
|
||||||
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 static MovementType AimMovementType { get; set; } = MovementType.CubicBezier;
|
|
||||||
|
|
||||||
// Display settings
|
|
||||||
public static bool ShowDetectionWindow { get; set; } = true;
|
|
||||||
|
|
||||||
// Data collection settings
|
|
||||||
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
|
|
||||||
|
|
||||||
// Color settings
|
|
||||||
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)
|
|
||||||
{
|
{
|
||||||
if (File.Exists("config.json"))
|
if (string.IsNullOrEmpty(filename))
|
||||||
{
|
filename = _defaultFilePath;
|
||||||
string config_content = File.ReadAllText("config.json");
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var config = JObject.Parse(config_content);
|
if (File.Exists(filename))
|
||||||
bool error = false;
|
|
||||||
|
|
||||||
var imageSettings = config["ImageSettings"];
|
|
||||||
ImageWidth = imageSettings?["ImageWidth"]?.Value<int>() ?? config["ImageWidth"]?.Value<int>() ?? ImageWidth;
|
|
||||||
ImageHeight = imageSettings?["ImageHeight"]?.Value<int>() ?? config["ImageHeight"]?.Value<int>() ?? ImageHeight;
|
|
||||||
|
|
||||||
var offsetSettings = config["OffsetSettings"];
|
|
||||||
YOffsetPercent = offsetSettings?["YOffsetPercent"]?.Value<double>() ?? config["YOffsetPercent"]?.Value<double>() ?? YOffsetPercent;
|
|
||||||
XOffsetPercent = offsetSettings?["XOffsetPercent"]?.Value<double>() ?? config["XOffsetPercent"]?.Value<double>() ?? XOffsetPercent;
|
|
||||||
|
|
||||||
var aimSettings = config["AimSettings"];
|
|
||||||
EnableAim = aimSettings?["EnableAim"]?.Value<bool>() ?? config["EnableAim"]?.Value<bool>() ?? EnableAim;
|
|
||||||
ClosestToMouse = aimSettings?["ClosestToMouse"]?.Value<bool>() ?? config["ClosestToMouse"]?.Value<bool>() ?? ClosestToMouse;
|
|
||||||
Keybind = aimSettings?["Keybind"]?.Value<int>() ?? config["Keybind"]?.Value<int>() ?? Keybind;
|
|
||||||
Sensitivity = aimSettings?["Sensitivity"]?.Value<double>() ?? config["Sensitivity"]?.Value<double>() ?? Sensitivity;
|
|
||||||
AimMovementType = aimSettings?["AimMovementType"]?.Value<string>() switch
|
|
||||||
{
|
{
|
||||||
"Linear" => MovementType.Linear,
|
try
|
||||||
"CubicBezier" => MovementType.CubicBezier,
|
|
||||||
"Adaptive" => MovementType.Adaptive,
|
|
||||||
_ => AimMovementType
|
|
||||||
};
|
|
||||||
|
|
||||||
var displaySettings = config["DisplaySettings"];
|
|
||||||
ShowDetectionWindow = displaySettings?["ShowDetectionWindow"]?.Value<bool>() ?? config["ShowDetectionWindow"]?.Value<bool>() ?? ShowDetectionWindow;
|
|
||||||
|
|
||||||
var dataSettings = config["DataCollectionSettings"];
|
|
||||||
CollectData = dataSettings?["CollectData"]?.Value<bool>() ?? config["CollectData"]?.Value<bool>() ?? CollectData;
|
|
||||||
AutoLabel = dataSettings?["AutoLabel"]?.Value<bool>() ?? config["AutoLabel"]?.Value<bool>() ?? AutoLabel;
|
|
||||||
BackgroundImageInterval = dataSettings?["BackgroundImageInterval"]?.Value<int>() ?? config["BackgroundImageInterval"]?.Value<int>() ?? BackgroundImageInterval;
|
|
||||||
|
|
||||||
var colorSettings = config["ColorSettings"];
|
|
||||||
UpperHSV = colorSettings?["UpperHSV"]?.ToObject<Scalar>() ?? config["UpperHSV"]?.ToObject<Scalar>() ?? UpperHSV;
|
|
||||||
LowerHSV = colorSettings?["LowerHSV"]?.ToObject<Scalar>() ?? config["LowerHSV"]?.ToObject<Scalar>() ?? LowerHSV;
|
|
||||||
|
|
||||||
if (ImageWidth <= 0 || ImageHeight <= 0)
|
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
var json = File.ReadAllText(filename);
|
||||||
Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values.");
|
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
|
||||||
Console.ResetColor();
|
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
|
||||||
ImageWidth = 640;
|
_currentFilePath = filename;
|
||||||
ImageHeight = 640;
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
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;
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
if (Keybind < 0 || Keybind > 255)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[ERROR] Invalid keybind in config.json, using default value.");
|
|
||||||
Console.ResetColor();
|
|
||||||
Keybind = 0x06;
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
if (Sensitivity < 0 || Sensitivity > 2)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[ERROR] Invalid sensitivity in config.json, using default value.");
|
|
||||||
Console.ResetColor();
|
|
||||||
Sensitivity = 0.5;
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
if (AutoLabel && !CollectData )
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
|
||||||
Console.WriteLine("[WARNING] AutoLabel is enabled but CollectData is not. Disabling AutoLabel.");
|
|
||||||
Console.ResetColor();
|
|
||||||
AutoLabel = false;
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
if (BackgroundImageInterval <= 0)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[ERROR] Invalid BackgroundImageInterval in config.json, using default value.");
|
|
||||||
Console.ResetColor();
|
|
||||||
error = true;
|
|
||||||
}
|
|
||||||
if (error)
|
|
||||||
SaveConfig();
|
|
||||||
|
|
||||||
if (!silent)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Configuration loaded successfully.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
LogManager.Log($"Failed to parse {filename}, using default values.", LogLevel.Error);
|
||||||
Console.WriteLine("[ERROR] Error parsing config.json, using default values.");
|
_data = new T();
|
||||||
Console.ResetColor();
|
|
||||||
SaveConfig();
|
SaveConfig();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
LogManager.Log($"{filename} not found, creating a new one with default values.", LogLevel.Error);
|
||||||
Console.WriteLine("[WARNING] config.json not found, using default values.");
|
_data = new T();
|
||||||
Console.ResetColor();
|
|
||||||
SaveConfig();
|
SaveConfig();
|
||||||
}
|
}
|
||||||
} public static void SaveConfig()
|
|
||||||
{
|
|
||||||
var config = new JObject
|
|
||||||
{
|
|
||||||
["ImageSettings"] = new JObject
|
|
||||||
{
|
|
||||||
["ImageWidth"] = ImageWidth,
|
|
||||||
["ImageHeight"] = ImageHeight
|
|
||||||
},
|
|
||||||
["OffsetSettings"] = new JObject
|
|
||||||
{
|
|
||||||
["YOffsetPercent"] = YOffsetPercent,
|
|
||||||
["XOffsetPercent"] = XOffsetPercent
|
|
||||||
},
|
|
||||||
["AimSettings"] = new JObject
|
|
||||||
{
|
|
||||||
["EnableAim"] = EnableAim,
|
|
||||||
["ClosestToMouse"] = ClosestToMouse,
|
|
||||||
["Keybind"] = Keybind,
|
|
||||||
["Sensitivity"] = Sensitivity,
|
|
||||||
["AimMovementType"] = AimMovementType.ToString()
|
|
||||||
},
|
|
||||||
["DisplaySettings"] = new JObject
|
|
||||||
{
|
|
||||||
["ShowDetectionWindow"] = ShowDetectionWindow
|
|
||||||
},
|
|
||||||
["DataCollectionSettings"] = new JObject
|
|
||||||
{
|
|
||||||
["CollectData"] = CollectData,
|
|
||||||
["AutoLabel"] = AutoLabel,
|
|
||||||
["BackgroundImageInterval"] = BackgroundImageInterval
|
|
||||||
},
|
|
||||||
["ColorSettings"] = new JObject
|
|
||||||
{
|
|
||||||
["UpperHSV"] = JToken.FromObject(UpperHSV),
|
|
||||||
["LowerHSV"] = JToken.FromObject(LowerHSV)
|
|
||||||
}
|
|
||||||
}; File.WriteAllText("config.json", config.ToString(Formatting.Indented));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void StartFileWatcher()
|
|
||||||
{
|
|
||||||
if (_configWatcher != null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
_configWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "config.json")
|
|
||||||
{
|
|
||||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
|
|
||||||
};
|
|
||||||
|
|
||||||
_configWatcher.Changed += OnConfigFileChanged;
|
|
||||||
_configWatcher.EnableRaisingEvents = true;
|
|
||||||
|
|
||||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
|
||||||
Console.WriteLine("[INFO] File watcher started for config.json");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void StopFileWatcher()
|
|
||||||
{
|
|
||||||
if (_configWatcher != null)
|
|
||||||
{
|
|
||||||
_configWatcher.EnableRaisingEvents = false;
|
|
||||||
_configWatcher.Changed -= OnConfigFileChanged;
|
|
||||||
_configWatcher.Dispose();
|
|
||||||
_configWatcher = null;
|
|
||||||
|
|
||||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
|
||||||
Console.WriteLine("[INFO] File watcher stopped for config.json");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void OnConfigFileChanged(object sender, FileSystemEventArgs e)
|
|
||||||
{
|
|
||||||
Thread.Sleep(100);
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
LoadConfig(true);
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Configuration automatically reloaded due to file change.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
LogManager.Log($"Error loading config {filename}: {ex.Message}", LogLevel.Error);
|
||||||
Console.WriteLine($"[ERROR] Failed to reload configuration: {ex.Message}");
|
_data = new T();
|
||||||
Console.ResetColor();
|
}
|
||||||
|
|
||||||
|
if (_fileWatcher != null)
|
||||||
|
{
|
||||||
|
StopFileWatcher();
|
||||||
|
StartFileWatcher();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void SaveConfig(string filename = "")
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(filename))
|
||||||
|
filename = _defaultFilePath;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(filename, JsonConvert.SerializeObject(_data, Formatting.Indented));
|
||||||
|
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
|
||||||
|
_currentFilePath = filename;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error saving config {filename}: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveConfigToDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
SaveConfig(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool LoadConfigFromDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {configName} not found in directory.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
LoadConfig(filePath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateAvailableConfigs()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(_configDirectory))
|
||||||
|
{
|
||||||
|
_availableConfigs.Clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs = Directory.GetFiles(_configDirectory, "*.json")
|
||||||
|
.Select(Path.GetFileNameWithoutExtension)
|
||||||
|
.Where(name => !string.IsNullOrEmpty(name))
|
||||||
|
.Cast<string>()
|
||||||
|
.Where(name => !name.Equals(Path.GetFileNameWithoutExtension(_defaultFilePath), StringComparison.OrdinalIgnoreCase))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
_availableConfigs.Clear();
|
||||||
|
_availableConfigs.AddRange(configs);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating available configs: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartDirectoryWatcher()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_directoryWatcher != null) return;
|
||||||
|
|
||||||
|
_directoryWatcher = new FileSystemWatcher(_configDirectory, "*.json")
|
||||||
|
{
|
||||||
|
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
|
||||||
|
};
|
||||||
|
|
||||||
|
_directoryWatcher.Created += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Deleted += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Renamed += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Changed += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.EnableRaisingEvents = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error starting directory watcher: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StopDirectoryWatcher()
|
||||||
|
{
|
||||||
|
if (_directoryWatcher == null) return;
|
||||||
|
|
||||||
|
_directoryWatcher.EnableRaisingEvents = false;
|
||||||
|
_directoryWatcher.Created -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Deleted -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Renamed -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Changed -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Dispose();
|
||||||
|
_directoryWatcher = null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDirectoryChanged(object sender, FileSystemEventArgs e)
|
||||||
|
{
|
||||||
|
Thread.Sleep(50);
|
||||||
|
UpdateAvailableConfigs();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool DeleteConfigFromDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {configName} not found.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Delete(filePath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error deleting config {configName}: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool RenameConfigInDirectory(string oldName, string newName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(oldName) || string.IsNullOrEmpty(newName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config names cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var oldPath = Path.Combine(_configDirectory, $"{oldName}.json");
|
||||||
|
var newPath = Path.Combine(_configDirectory, $"{newName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(oldPath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {oldName} not found.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(newPath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {newName} already exists.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(oldPath, newPath);
|
||||||
|
if (_currentConfigName == oldName)
|
||||||
|
_currentConfigName = newName;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error renaming config: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void StartFileWatcher()
|
||||||
|
{
|
||||||
|
if (_fileWatcher != null) return;
|
||||||
|
|
||||||
|
var directory = Path.GetDirectoryName(_currentFilePath) ?? Directory.GetCurrentDirectory();
|
||||||
|
var fileName = Path.GetFileName(_currentFilePath);
|
||||||
|
_fileWatcher = new FileSystemWatcher(directory, fileName)
|
||||||
|
{
|
||||||
|
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
|
||||||
|
};
|
||||||
|
_fileWatcher.Changed += OnConfigFileChanged;
|
||||||
|
_fileWatcher.EnableRaisingEvents = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void StopFileWatcher()
|
||||||
|
{
|
||||||
|
if (_fileWatcher == null) return;
|
||||||
|
_fileWatcher.EnableRaisingEvents = false;
|
||||||
|
_fileWatcher.Changed -= OnConfigFileChanged;
|
||||||
|
_fileWatcher.Dispose();
|
||||||
|
_fileWatcher = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LoadConfig(_currentFilePath);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Failed to reload configuration for {_currentFilePath}: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
StopFileWatcher();
|
||||||
|
StopDirectoryWatcher();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ColorConfigManager
|
||||||
|
{
|
||||||
|
private readonly string _colorsDirectory;
|
||||||
|
private readonly List<ColorInfo> _colors;
|
||||||
|
private readonly object _lock = new();
|
||||||
|
private int _version;
|
||||||
|
private FileSystemWatcher? _directoryWatcher;
|
||||||
|
|
||||||
|
public IReadOnlyList<ColorInfo> Colors => GetColorsSnapshot();
|
||||||
|
public int Version => _version;
|
||||||
|
|
||||||
|
public ColorConfigManager(string colorsDirectory)
|
||||||
|
{
|
||||||
|
_colorsDirectory = colorsDirectory;
|
||||||
|
_colors = [];
|
||||||
|
|
||||||
|
if (!Directory.Exists(_colorsDirectory))
|
||||||
|
Directory.CreateDirectory(_colorsDirectory);
|
||||||
|
|
||||||
|
Reload();
|
||||||
|
StartDirectoryWatcher();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reload()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(_colorsDirectory))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var loadedColors = new List<ColorInfo>();
|
||||||
|
var files = Directory.GetFiles(_colorsDirectory, "*.json")
|
||||||
|
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var json = File.ReadAllText(file);
|
||||||
|
var color = JsonConvert.DeserializeObject<ColorInfo>(json);
|
||||||
|
if (color == null)
|
||||||
|
continue;
|
||||||
|
if (string.IsNullOrWhiteSpace(color.Name))
|
||||||
|
color.Name = Path.GetFileNameWithoutExtension(file);
|
||||||
|
loadedColors.RemoveAll(c => c.Name.Equals(color.Name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
loadedColors.Add(color);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Failed to load color config {file}: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_colors.Clear();
|
||||||
|
_colors.AddRange(loadedColors);
|
||||||
|
_version++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error loading colors: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ColorInfo? GetColor(string name)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(name))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _colors.Find(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<ColorInfo> GetColorsSnapshot()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return [.. _colors];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool SaveColor(ColorInfo color)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(color.Name))
|
||||||
|
{
|
||||||
|
LogManager.Log("Color name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var filePath = GetColorFilePath(color.Name);
|
||||||
|
File.WriteAllText(filePath, JsonConvert.SerializeObject(color, Formatting.Indented));
|
||||||
|
Reload();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error saving color {color.Name}: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool DeleteColor(string name)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(name))
|
||||||
|
{
|
||||||
|
LogManager.Log("Color name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var filePath = GetColorFilePath(name);
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Color {name} not found.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File.Delete(filePath);
|
||||||
|
Reload();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error deleting color {name}: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetColorFilePath(string colorName)
|
||||||
|
{
|
||||||
|
var safeName = string.Join("_", colorName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
|
||||||
|
if (string.IsNullOrWhiteSpace(safeName))
|
||||||
|
safeName = "color";
|
||||||
|
return Path.Combine(_colorsDirectory, $"{safeName}.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartDirectoryWatcher()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_directoryWatcher != null) return;
|
||||||
|
|
||||||
|
_directoryWatcher = new FileSystemWatcher(_colorsDirectory, "*.json")
|
||||||
|
{
|
||||||
|
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
|
||||||
|
};
|
||||||
|
|
||||||
|
_directoryWatcher.Created += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Deleted += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Renamed += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Changed += OnDirectoryChanged;
|
||||||
|
_directoryWatcher.EnableRaisingEvents = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error starting color directory watcher: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDirectoryChanged(object sender, FileSystemEventArgs e)
|
||||||
|
{
|
||||||
|
Thread.Sleep(50);
|
||||||
|
Reload();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Enums
|
||||||
|
public enum MovementType
|
||||||
|
{
|
||||||
|
Linear,
|
||||||
|
CubicBezier,
|
||||||
|
Adaptive,
|
||||||
|
PerlinNoise,
|
||||||
|
WindMouse
|
||||||
|
}
|
||||||
|
public enum MovementMethod
|
||||||
|
{
|
||||||
|
MouseEvent,
|
||||||
|
Arduino,
|
||||||
|
HID
|
||||||
|
}
|
||||||
|
public enum FovType
|
||||||
|
{
|
||||||
|
Circle,
|
||||||
|
Rectangle
|
||||||
|
}
|
||||||
|
public enum AimpointType
|
||||||
|
{
|
||||||
|
Crosshair,
|
||||||
|
Dot,
|
||||||
|
Circle
|
||||||
|
}
|
||||||
|
public enum CaptureMethod
|
||||||
|
{
|
||||||
|
GDI,
|
||||||
|
DirectX
|
||||||
|
}
|
||||||
|
public enum KeybindType
|
||||||
|
{
|
||||||
|
Hold,
|
||||||
|
Toggle,
|
||||||
|
Always
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
public class ConfigData
|
||||||
|
{
|
||||||
|
|
||||||
|
#region Image Settings
|
||||||
|
public int ImageWidth { get; set; } = 640;
|
||||||
|
public int ImageHeight { get; set; } = 640;
|
||||||
|
public int Threshold { get; set; } = 200;
|
||||||
|
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Offset Settings
|
||||||
|
public double YOffsetPercent { get; set; } = 0.8;
|
||||||
|
public double XOffsetPercent { get; set; } = 0.5;
|
||||||
|
public int YOffsetPixels { get; set; } = 100;
|
||||||
|
public int XOffsetPixels { get; set; } = 100;
|
||||||
|
public bool XPixelOffset { get; set; } = false;
|
||||||
|
public bool YPixelOffset { get; set; } = false;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Aim Settings
|
||||||
|
public bool EnableAim { get; set; } = true;
|
||||||
|
public bool ClosestToMouse { get; set; } = true;
|
||||||
|
public Keybind Keybind = new(Keys.XButton2, KeybindType.Hold);
|
||||||
|
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;
|
||||||
|
|
||||||
|
public double WindMouseGravity { get; set; } = 9.0;
|
||||||
|
public double WindMouseWind { get; set; } = 3.0;
|
||||||
|
public double WindMouseMaxStep { get; set; } = 10.0;
|
||||||
|
public bool WindMouseOvershoot { get; set; } = false;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Trigger Settings
|
||||||
|
public bool TriggerBot { get; set; } = false;
|
||||||
|
public Keybind TriggerKeybind = new(Keys.XButton1, KeybindType.Hold);
|
||||||
|
public bool TriggerRandomDelay { get; set; } = false;
|
||||||
|
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||||
|
public bool TriggerSpray = false; // if true ignore duration
|
||||||
|
public bool TriggerRandomDuration { get; set; } = false;
|
||||||
|
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||||
|
public bool TriggerInBoundsOnly { get; set; } = false;
|
||||||
|
public int TriggerFov { get; set; } = 15; // pixels
|
||||||
|
public bool DrawTriggerFov { get; set; } = false;
|
||||||
|
public Vector4 TriggerRadiusColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Display Settings
|
||||||
|
public bool DrawDetections { get; set; } = true;
|
||||||
|
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
|
public bool HighlightTarget { get; set; } = false;
|
||||||
|
public Vector4 TargetColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
public bool ShowMenu { get; set; } = true;
|
||||||
|
public Keys MenuKey { get; set; } = Keys.Insert;
|
||||||
|
public bool DrawFOV { get; set; } = false;
|
||||||
|
public FovType FOVType { get; set; } = FovType.Rectangle;
|
||||||
|
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
|
public bool DrawAimPoint { get; set; } = true;
|
||||||
|
public Vector4 AimPointColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
public AimpointType AimPointType { get; set; } = AimpointType.Dot;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Data Collection Settings
|
||||||
|
public bool CollectData { get; set; } = false;
|
||||||
|
public bool AutoLabel { get; set; } = false;
|
||||||
|
public int BackgroundImageInterval { get; set; } = 10;
|
||||||
|
public int LabeledImageInterval { get; set; } = 5;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Color Settings
|
||||||
|
public Scalar UpperHSV { get; set; } = new Scalar(179, 255, 255);
|
||||||
|
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 255);
|
||||||
|
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Misc
|
||||||
|
public bool DebugMode { get; set; } = false;
|
||||||
|
public bool AntiCapture { get; set; } = false;
|
||||||
|
public int MinAreaPx { get; set; } = 100;
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
public class ColorInfo(string name, Scalar upper, Scalar lower)
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = name;
|
||||||
|
public Scalar Upper { get; set; } = upper;
|
||||||
|
public Scalar Lower { get; set; } = lower;
|
||||||
|
}
|
||||||
|
public class Keybind(Keys key, KeybindType type)
|
||||||
|
{
|
||||||
|
public Keys Key { get; set; } = key;
|
||||||
|
|
||||||
|
public KeybindType Type { get; set; } = type;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,23 @@
|
|||||||
using OpenCvSharp;
|
using OpenCvSharp;
|
||||||
using System;
|
using Spectrum.Utilities;
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Drawing;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum.Detection
|
||||||
{
|
{
|
||||||
public static class AutoLabeling
|
public static class AutoLabeling
|
||||||
{
|
{
|
||||||
private static int imageCount = 0;
|
private static int imageCount = 0;
|
||||||
private static int detectionAttemps = 0;
|
private static int detectionAttemps = 0;
|
||||||
private static readonly object lockObject = new object();
|
private static int labeledImageAttempts = 0;
|
||||||
|
private static readonly object lockObject = new();
|
||||||
private static CancellationTokenSource? cancellationTokenSource;
|
private static CancellationTokenSource? cancellationTokenSource;
|
||||||
private static Task? backgroundTask;
|
private static Task? backgroundTask;
|
||||||
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
|
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new();
|
||||||
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
|
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new();
|
||||||
|
private static readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
public static bool Started = false;
|
||||||
|
|
||||||
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
||||||
{
|
{
|
||||||
@@ -52,6 +52,9 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
|
|
||||||
var labelContent = new StringBuilder();
|
var labelContent = new StringBuilder();
|
||||||
foreach (var box in boundingBoxes)
|
foreach (var box in boundingBoxes)
|
||||||
{
|
{
|
||||||
@@ -59,22 +62,22 @@ namespace Spectrum
|
|||||||
}
|
}
|
||||||
File.WriteAllText(path, labelContent.ToString());
|
File.WriteAllText(path, labelContent.ToString());
|
||||||
}
|
}
|
||||||
catch
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
LogManager.Log($"[ERROR] Failed to save labels. Error: {ex.Message}", LogLevel.Error);
|
||||||
Console.WriteLine("[ERROR] Failed to save labels to " + path);
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static void SaveMatAsImage(Mat mat, string path)
|
private static void SaveMatAsImage(Mat mat, string path)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
Cv2.ImWrite(path, mat);
|
Cv2.ImWrite(path, mat);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Error saving image: {ex.Message}");
|
LogManager.Log($"[ERROR] Failed to save image: {ex.Message}", LogLevel.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,9 +93,7 @@ namespace Spectrum
|
|||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
LogManager.Log("[ERROR] Failed to process labeling data.", LogLevel.Error);
|
||||||
Console.WriteLine("[ERROR] Failed to process labeling data.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,9 +105,7 @@ namespace Spectrum
|
|||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
LogManager.Log("[ERROR] Failed to process background image data.", LogLevel.Error);
|
||||||
Console.WriteLine("[ERROR] Failed to process background image data.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,9 +113,20 @@ namespace Spectrum
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||||
{
|
{
|
||||||
if (!Config.AutoLabel || filteredContours.Length == 0)
|
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
labeledImageAttempts++;
|
||||||
|
|
||||||
|
if (labeledImageAttempts < mainConfig.Data.LabeledImageInterval)
|
||||||
|
return;
|
||||||
|
|
||||||
|
labeledImageAttempts = 0;
|
||||||
|
|
||||||
|
if (labelingQueue.Count > 250)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
Mat clone = mat.Clone();
|
Mat clone = mat.Clone();
|
||||||
@@ -130,12 +140,14 @@ namespace Spectrum
|
|||||||
|
|
||||||
public static void AddBackgroundImage(Mat mat, bool detected)
|
public static void AddBackgroundImage(Mat mat, bool detected)
|
||||||
{
|
{
|
||||||
if (!Config.AutoLabel)
|
|
||||||
return;
|
|
||||||
|
|
||||||
detectionAttemps++;
|
detectionAttemps++;
|
||||||
|
|
||||||
if (detectionAttemps < Config.BackgroundImageInterval || detected)
|
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
|
||||||
|
return;
|
||||||
|
|
||||||
|
detectionAttemps = 0;
|
||||||
|
|
||||||
|
if (backgroundQueue.Count > 250)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
Mat clone = mat.Clone();
|
Mat clone = mat.Clone();
|
||||||
@@ -161,8 +173,8 @@ namespace Spectrum
|
|||||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
string imageFileName = $"image_{imageCount:D6}.jpg";
|
||||||
string labelFileName = $"image_{imageCount:D6}.txt";
|
string labelFileName = $"image_{imageCount:D6}.txt";
|
||||||
|
|
||||||
string imagePath = Path.Combine("dataset/images", imageFileName);
|
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
|
||||||
string labelPath = Path.Combine("dataset/labels", labelFileName);
|
string labelPath = Path.Combine("bin/dataset/labels", labelFileName);
|
||||||
|
|
||||||
SaveMatAsImage(data.Mat, imagePath);
|
SaveMatAsImage(data.Mat, imagePath);
|
||||||
|
|
||||||
@@ -186,7 +198,7 @@ namespace Spectrum
|
|||||||
lock (lockObject)
|
lock (lockObject)
|
||||||
{
|
{
|
||||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
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);
|
SaveMatAsImage(data.Mat, imagePath);
|
||||||
|
|
||||||
@@ -204,6 +216,11 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
if (cancellationTokenSource != null)
|
if (cancellationTokenSource != null)
|
||||||
return;
|
return;
|
||||||
|
LogManager.Log("Starting auto labeling...", LogLevel.Info);
|
||||||
|
int existingImages = Directory.Exists("bin/dataset/images") ?
|
||||||
|
Directory.GetFiles("bin/dataset/images", "image_*.jpg").Length : 0;
|
||||||
|
imageCount = existingImages;
|
||||||
|
Started = true;
|
||||||
cancellationTokenSource = new CancellationTokenSource();
|
cancellationTokenSource = new CancellationTokenSource();
|
||||||
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
||||||
}
|
}
|
||||||
@@ -211,6 +228,9 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
if (cancellationTokenSource == null)
|
if (cancellationTokenSource == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
LogManager.Log("Stopping auto labeling...", LogLevel.Info);
|
||||||
|
Started = false;
|
||||||
cancellationTokenSource.Cancel();
|
cancellationTokenSource.Cancel();
|
||||||
backgroundTask?.Wait();
|
backgroundTask?.Wait();
|
||||||
cancellationTokenSource.Dispose();
|
cancellationTokenSource.Dispose();
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
using System.Drawing.Imaging;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Direct3D11;
|
||||||
|
using Vortice.DXGI;
|
||||||
|
using Point = System.Drawing.Point;
|
||||||
|
using Rectangle = System.Drawing.Rectangle;
|
||||||
|
using Size = System.Drawing.Size;
|
||||||
|
|
||||||
|
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;
|
||||||
|
private Bitmap? _captureBitmap;
|
||||||
|
private Size _captureBitmapSize;
|
||||||
|
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,
|
||||||
|
[
|
||||||
|
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(new Size(bounds.Width, bounds.Height));
|
||||||
|
EnsureCaptureBitmap(new Size(bounds.Width, bounds.Height));
|
||||||
|
|
||||||
|
IDXGIResource? desktopResource = null;
|
||||||
|
bool frameAcquired = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = _duplication!.AcquireNextFrame(0, 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,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
fullTex,
|
||||||
|
0,
|
||||||
|
new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
var bmp = _captureBitmap!;
|
||||||
|
var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);
|
||||||
|
var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height),
|
||||||
|
ImageLockMode.WriteOnly,
|
||||||
|
PixelFormat.Format32bppArgb);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* srcBase = (byte*)map.DataPointer;
|
||||||
|
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.Clone(new Rectangle(0, 0, bounds.Width, bounds.Height), PixelFormat.Format32bppArgb);
|
||||||
|
}
|
||||||
|
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
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureCaptureBitmap(Size size)
|
||||||
|
{
|
||||||
|
if (_captureBitmap != null && _captureBitmapSize.Width == size.Width && _captureBitmapSize.Height == size.Height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_captureBitmap?.Dispose();
|
||||||
|
_captureBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
|
||||||
|
_captureBitmapSize = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Bitmap? CaptureScreenshotGdi(Rectangle bounds)
|
||||||
|
{
|
||||||
|
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||||
|
using var g = Graphics.FromImage(bmp);
|
||||||
|
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();
|
||||||
|
_captureBitmap?.Dispose();
|
||||||
|
_captureBitmap = null;
|
||||||
|
}
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,427 @@
|
|||||||
|
using OpenCvSharp;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using Spectrum.Utilities;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Drawing.Imaging;
|
||||||
|
|
||||||
|
namespace Spectrum.Detection
|
||||||
|
{
|
||||||
|
class DetectionManager
|
||||||
|
{
|
||||||
|
private readonly Stopwatch stopwatch = new();
|
||||||
|
private Rectangle bounds = new(0, 0, 0, 0);
|
||||||
|
private readonly Rectangle monitorBounds = Program.MonitorBounds;
|
||||||
|
private readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
private readonly Renderer? renderer;
|
||||||
|
private readonly Thread? _detectionThread;
|
||||||
|
private DateTime lastMenuToggle = DateTime.MinValue;
|
||||||
|
private readonly CaptureManager _captureManager;
|
||||||
|
private Mat? hsvBuffer;
|
||||||
|
private Mat? maskBuffer;
|
||||||
|
private Mat? bgrBuffer;
|
||||||
|
private OpenCvSharp.Size bufferSize;
|
||||||
|
private OpenCvSharp.Size bgrBufferSize;
|
||||||
|
private static void AddTiming(string name, long ticks) => Program.Timings.Add(name, ticks);
|
||||||
|
|
||||||
|
public DetectionManager(Renderer renderer)
|
||||||
|
{
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
var config = mainConfig.Data;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && !config.ShowMenu)
|
||||||
|
{
|
||||||
|
if (config.DebugMode)
|
||||||
|
stopwatch.Restart();
|
||||||
|
|
||||||
|
var t0 = Stopwatch.GetTimestamp();
|
||||||
|
renderer?.ClearDetectionDrawCommands();
|
||||||
|
AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0);
|
||||||
|
|
||||||
|
if (!config.ClosestToMouse)
|
||||||
|
{
|
||||||
|
bounds = new Rectangle(
|
||||||
|
monitorBounds.X + (monitorBounds.Width - config.ImageWidth) / 2,
|
||||||
|
monitorBounds.Y + (monitorBounds.Height - config.ImageHeight) / 2,
|
||||||
|
config.ImageWidth,
|
||||||
|
config.ImageHeight
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var tCursor = Stopwatch.GetTimestamp();
|
||||||
|
_ = InputManager.GetCursorPos(out System.Drawing.Point mousePos);
|
||||||
|
AddTiming("Get Cursor Pos", Stopwatch.GetTimestamp() - tCursor);
|
||||||
|
bounds = new Rectangle(
|
||||||
|
mousePos.X - (config.ImageWidth / 2),
|
||||||
|
mousePos.Y - (config.ImageHeight / 2),
|
||||||
|
config.ImageWidth,
|
||||||
|
config.ImageHeight
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bounds = Rectangle.Intersect(bounds, monitorBounds);
|
||||||
|
if (bounds.Width <= 0 || bounds.Height <= 0)
|
||||||
|
{
|
||||||
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
Thread.Sleep(2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bitmap? screenshot = null;
|
||||||
|
var tCapture = Stopwatch.GetTimestamp();
|
||||||
|
if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
||||||
|
{
|
||||||
|
var dxBounds = new Rectangle(
|
||||||
|
bounds.X - monitorBounds.X,
|
||||||
|
bounds.Y - monitorBounds.Y,
|
||||||
|
bounds.Width,
|
||||||
|
bounds.Height
|
||||||
|
);
|
||||||
|
screenshot = _captureManager.CaptureScreenshotDirectX(dxBounds);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_captureManager.IsInitialized)
|
||||||
|
_captureManager.Dispose();
|
||||||
|
screenshot = CaptureManager.CaptureScreenshotGdi(bounds);
|
||||||
|
}
|
||||||
|
AddTiming("Screen Capture", Stopwatch.GetTimestamp() - tCapture);
|
||||||
|
|
||||||
|
if (screenshot == null)
|
||||||
|
{
|
||||||
|
LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug);
|
||||||
|
Thread.Sleep(2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tMat = Stopwatch.GetTimestamp();
|
||||||
|
Mat mat = ConvertBitmapToMat(screenshot);
|
||||||
|
screenshot.Dispose();
|
||||||
|
AddTiming("Bitmap to Mat", Stopwatch.GetTimestamp() - tMat);
|
||||||
|
|
||||||
|
EnsureBuffers(mat.Size());
|
||||||
|
|
||||||
|
var tConvert = Stopwatch.GetTimestamp();
|
||||||
|
Cv2.CvtColor(mat, hsvBuffer!, ColorConversionCodes.BGR2HSV);
|
||||||
|
AddTiming("Color Conversion", Stopwatch.GetTimestamp() - tConvert);
|
||||||
|
|
||||||
|
var tRange = Stopwatch.GetTimestamp();
|
||||||
|
Cv2.InRange(hsvBuffer!, config.LowerHSV, config.UpperHSV, maskBuffer!);
|
||||||
|
AddTiming("Range Check", Stopwatch.GetTimestamp() - tRange);
|
||||||
|
|
||||||
|
var tDilate = Stopwatch.GetTimestamp();
|
||||||
|
Cv2.Dilate(maskBuffer!, maskBuffer!, null, iterations: 2);
|
||||||
|
AddTiming("Dilation", Stopwatch.GetTimestamp() - tDilate);
|
||||||
|
|
||||||
|
var tThresh = Stopwatch.GetTimestamp();
|
||||||
|
Cv2.Threshold(maskBuffer!, maskBuffer!, 127, 255, ThresholdTypes.Binary);
|
||||||
|
AddTiming("Thresholding", Stopwatch.GetTimestamp() - tThresh);
|
||||||
|
|
||||||
|
var tContours = Stopwatch.GetTimestamp();
|
||||||
|
Cv2.FindContours(maskBuffer!, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||||
|
AddTiming("Find Contours", Stopwatch.GetTimestamp() - tContours);
|
||||||
|
|
||||||
|
var tFilter = Stopwatch.GetTimestamp();
|
||||||
|
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= config.MinAreaPx).ToArray();
|
||||||
|
AddTiming("Filter Contours", Stopwatch.GetTimestamp() - tFilter);
|
||||||
|
|
||||||
|
var tMerge = Stopwatch.GetTimestamp();
|
||||||
|
var processedContours = MergeOverlappingContours(filteredContours);
|
||||||
|
AddTiming("Merge Contours", Stopwatch.GetTimestamp() - tMerge);
|
||||||
|
|
||||||
|
if (processedContours.Length > 0)
|
||||||
|
{
|
||||||
|
int refX = bounds.X + bounds.Width / 2;
|
||||||
|
int refY = bounds.Y + (int)(bounds.Height * config.YOffsetPercent);
|
||||||
|
|
||||||
|
double minDistSquared = double.MaxValue;
|
||||||
|
OpenCvSharp.Point[]? closestContour = null;
|
||||||
|
Rect bestRect = default;
|
||||||
|
|
||||||
|
bool shouldDrawDetections = config.DrawDetections && renderer != null;
|
||||||
|
|
||||||
|
var tProcess = Stopwatch.GetTimestamp();
|
||||||
|
foreach (var contour in processedContours)
|
||||||
|
{
|
||||||
|
var rect = Cv2.BoundingRect(contour);
|
||||||
|
|
||||||
|
int centerX = rect.X + rect.Width / 2;
|
||||||
|
int centerY = rect.Y + rect.Height / 2;
|
||||||
|
|
||||||
|
int absCenterX = centerX + bounds.X;
|
||||||
|
int absCenterY = centerY + bounds.Y;
|
||||||
|
|
||||||
|
double distSquared = (absCenterX - refX) * (absCenterX - refX) +
|
||||||
|
(absCenterY - refY) * (absCenterY - refY);
|
||||||
|
|
||||||
|
if (distSquared < minDistSquared)
|
||||||
|
{
|
||||||
|
minDistSquared = distSquared;
|
||||||
|
closestContour = contour;
|
||||||
|
bestRect = rect;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldDrawDetections)
|
||||||
|
{
|
||||||
|
var _rect = new Rectangle(
|
||||||
|
rect.X + bounds.X,
|
||||||
|
rect.Y + bounds.Y,
|
||||||
|
rect.Width,
|
||||||
|
rect.Height
|
||||||
|
);
|
||||||
|
renderer!.AddRect(_rect, config.DetectionColor, 1.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AddTiming("Process Contours", Stopwatch.GetTimestamp() - tProcess);
|
||||||
|
|
||||||
|
if (closestContour != null)
|
||||||
|
{
|
||||||
|
|
||||||
|
if (shouldDrawDetections && config.HighlightTarget)
|
||||||
|
{
|
||||||
|
var _rect = new Rectangle(
|
||||||
|
bestRect.X + bounds.X,
|
||||||
|
bestRect.Y + bounds.Y,
|
||||||
|
bestRect.Width,
|
||||||
|
bestRect.Height
|
||||||
|
);
|
||||||
|
renderer!.AddRect(_rect, config.TargetColor, 1.0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
int groupX;
|
||||||
|
int groupY;
|
||||||
|
if (config.XPixelOffset)
|
||||||
|
groupX = bestRect.X + config.XOffsetPixels;
|
||||||
|
else
|
||||||
|
groupX = (int)(bestRect.X + bestRect.Width * config.XOffsetPercent);
|
||||||
|
if (config.YPixelOffset)
|
||||||
|
groupY = bestRect.Y + config.YOffsetPixels;
|
||||||
|
else
|
||||||
|
groupY = (int)(bestRect.Y + bestRect.Height * (1 - config.YOffsetPercent));
|
||||||
|
|
||||||
|
int targetX = groupX + bounds.X;
|
||||||
|
int targetY = groupY + bounds.Y;
|
||||||
|
|
||||||
|
if (config.DrawAimPoint)
|
||||||
|
{
|
||||||
|
if (config.AimPointType == AimpointType.Crosshair)
|
||||||
|
{
|
||||||
|
renderer!.AddLine(new System.Numerics.Vector2(targetX - 10, targetY), new System.Numerics.Vector2(targetX + 10, targetY), config.AimPointColor, 2);
|
||||||
|
renderer!.AddLine(new System.Numerics.Vector2(targetX, targetY - 10), new System.Numerics.Vector2(targetX, targetY + 10), config.AimPointColor, 2);
|
||||||
|
renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||||
|
}
|
||||||
|
else if (config.AimPointType == AimpointType.Dot)
|
||||||
|
{
|
||||||
|
renderer!.AddCircleFilled(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||||
|
}
|
||||||
|
else if (config.AimPointType == AimpointType.Circle)
|
||||||
|
{
|
||||||
|
renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 10, config.AimPointColor, 20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.AutoLabel)
|
||||||
|
{
|
||||||
|
AutoLabeling.AddToQueue(mat, bounds, processedContours);
|
||||||
|
AutoLabeling.AddBackgroundImage(mat, true);
|
||||||
|
}
|
||||||
|
if (!config.AutoLabel && config.CollectData)
|
||||||
|
{
|
||||||
|
AutoLabeling.AddBackgroundImage(mat, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
||||||
|
InputManager.SetLastDetectionBox(new Rectangle(
|
||||||
|
bestRect.X + bounds.X,
|
||||||
|
bestRect.Y + bounds.Y,
|
||||||
|
bestRect.Width,
|
||||||
|
bestRect.Height));
|
||||||
|
|
||||||
|
if (config.EnableAim && InputManager.IsKeyOrMouseDown(config.Keybind))
|
||||||
|
{
|
||||||
|
var tMove = Stopwatch.GetTimestamp();
|
||||||
|
InputManager.MoveMouse();
|
||||||
|
AddTiming("Mouse Movement", Stopwatch.GetTimestamp() - tMove);
|
||||||
|
}
|
||||||
|
if (config.TriggerBot)
|
||||||
|
{
|
||||||
|
var _ = InputManager.ClickMouse();
|
||||||
|
}
|
||||||
|
if (renderer != null && config.DrawTriggerFov && config.TriggerBot && !config.TriggerInBoundsOnly)
|
||||||
|
{
|
||||||
|
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (config.CollectData)
|
||||||
|
{
|
||||||
|
AutoLabeling.AddBackgroundImage(mat, false);
|
||||||
|
MovementPaths.ResetWindMouse();
|
||||||
|
}
|
||||||
|
|
||||||
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
|
||||||
|
if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel))
|
||||||
|
AutoLabeling.StartLabeling();
|
||||||
|
else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel)
|
||||||
|
AutoLabeling.StopLabeling();
|
||||||
|
|
||||||
|
if (config.DebugMode)
|
||||||
|
{
|
||||||
|
stopwatch.Stop();
|
||||||
|
AddTiming("Frame", stopwatch.ElapsedTicks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
renderer?.ClearDetectionDrawCommands();
|
||||||
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
MovementPaths.ResetWindMouse();
|
||||||
|
Thread.Sleep(5);
|
||||||
|
}
|
||||||
|
if (InputManager.IsKeyOrMouseDown(config.MenuKey))
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
||||||
|
{
|
||||||
|
config.ShowMenu = !config.ShowMenu;
|
||||||
|
lastMenuToggle = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (config.AntiCapture && !Win32.IsWindowHidden)
|
||||||
|
Win32.EnableAntiCapture(renderer!.window.Handle);
|
||||||
|
else if (!config.AntiCapture && Win32.IsWindowHidden)
|
||||||
|
Win32.DisableAntiCapture(renderer!.window.Handle);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
|
||||||
|
Thread.Sleep(5);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Thread.Sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||||
|
{
|
||||||
|
if (contours.Length <= 1)
|
||||||
|
return contours;
|
||||||
|
|
||||||
|
var contourRects = new List<(Rect rect, List<int> indices)>(contours.Length);
|
||||||
|
for (int i = 0; i < contours.Length; i++)
|
||||||
|
{
|
||||||
|
var rect = Cv2.BoundingRect(contours[i]);
|
||||||
|
contourRects.Add((rect, new List<int> { i }));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool merged;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
merged = false;
|
||||||
|
for (int i = 0; i < contourRects.Count - 1; 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)
|
||||||
|
);
|
||||||
|
indicesA.AddRange(indicesB);
|
||||||
|
contourRects[i] = (newRect, indicesA);
|
||||||
|
contourRects.RemoveAt(j);
|
||||||
|
merged = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (merged) break;
|
||||||
|
}
|
||||||
|
} while (merged);
|
||||||
|
|
||||||
|
var mergedContours = new List<OpenCvSharp.Point[]>(contourRects.Count);
|
||||||
|
foreach (var (_, indices) in contourRects)
|
||||||
|
{
|
||||||
|
var pointsList = new List<OpenCvSharp.Point>(indices.Count * 10);
|
||||||
|
foreach (var idx in indices)
|
||||||
|
{
|
||||||
|
pointsList.AddRange(contours[idx]);
|
||||||
|
}
|
||||||
|
var hull = Cv2.ConvexHull(pointsList);
|
||||||
|
mergedContours.Add(hull);
|
||||||
|
}
|
||||||
|
return [.. mergedContours];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureBuffers(OpenCvSharp.Size size)
|
||||||
|
{
|
||||||
|
if (size == bufferSize && hsvBuffer != null && maskBuffer != null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
hsvBuffer?.Dispose();
|
||||||
|
maskBuffer?.Dispose();
|
||||||
|
|
||||||
|
hsvBuffer = new Mat(size, MatType.CV_8UC3);
|
||||||
|
maskBuffer = new Mat(size, MatType.CV_8UC1);
|
||||||
|
bufferSize = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mat ConvertBitmapToMat(Bitmap bitmap)
|
||||||
|
{
|
||||||
|
var size = new OpenCvSharp.Size(bitmap.Width, bitmap.Height);
|
||||||
|
if (bgrBuffer == null || size != bgrBufferSize)
|
||||||
|
{
|
||||||
|
bgrBuffer?.Dispose();
|
||||||
|
bgrBuffer = new Mat(size, MatType.CV_8UC4);
|
||||||
|
bgrBufferSize = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
|
||||||
|
var bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* src = (byte*)bmpData.Scan0;
|
||||||
|
byte* dst = bgrBuffer!.DataPointer;
|
||||||
|
int srcStride = bmpData.Stride;
|
||||||
|
int dstStride = (int)bgrBuffer.Step();
|
||||||
|
int rowBytes = bitmap.Width * 4;
|
||||||
|
for (int y = 0; y < bitmap.Height; y++)
|
||||||
|
{
|
||||||
|
Buffer.MemoryCopy(src, dst, rowBytes, rowBytes);
|
||||||
|
src += srcStride;
|
||||||
|
dst += dstStride;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
bitmap.UnlockBits(bmpData);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bgrBuffer!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||||
|
<Costura />
|
||||||
|
</Weavers>
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
using Spectrum.Utilities;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO.Ports;
|
||||||
|
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.Arduino
|
||||||
|
{
|
||||||
|
class ArduinoMain
|
||||||
|
{
|
||||||
|
private static readonly byte PingCommand = 0x02;
|
||||||
|
private static readonly byte PingResponse = 0xAA;
|
||||||
|
private const int BaudRate = 115200;
|
||||||
|
private const int HandshakeTimeoutMs = 1500;
|
||||||
|
private const int OpenResetDelayMs = 1200;
|
||||||
|
private static SerialPort? serial;
|
||||||
|
private static readonly object sync = new();
|
||||||
|
|
||||||
|
public static bool Load()
|
||||||
|
{
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
if (serial != null && serial.IsOpen)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
serial = FindArduino();
|
||||||
|
if (serial != null)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Connected to Arduino on {serial.PortName}.", LogLevel.Info);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log("ArduinoMain: Failed to connect to Arduino.", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SerialPort? FindArduino()
|
||||||
|
{
|
||||||
|
string[] candidates = SerialPort.GetPortNames();
|
||||||
|
|
||||||
|
if (candidates.Length == 0)
|
||||||
|
{
|
||||||
|
LogManager.Log("ArduinoMain: No serial ports detected.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (string portName in candidates)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Probing {portName}…", LogLevel.Debug);
|
||||||
|
var sp = new SerialPort(portName, BaudRate)
|
||||||
|
{
|
||||||
|
ReadTimeout = 250,
|
||||||
|
WriteTimeout = 500,
|
||||||
|
DtrEnable = true,
|
||||||
|
RtsEnable = true
|
||||||
|
};
|
||||||
|
|
||||||
|
sp.Open();
|
||||||
|
|
||||||
|
Thread.Sleep(OpenResetDelayMs);
|
||||||
|
|
||||||
|
sp.DiscardInBuffer();
|
||||||
|
sp.DiscardOutBuffer();
|
||||||
|
|
||||||
|
sp.Write([PingCommand], 0, 1);
|
||||||
|
|
||||||
|
if (AwaitResponse(sp, PingResponse, HandshakeTimeoutMs))
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Handshake success on {portName}.", LogLevel.Debug);
|
||||||
|
return sp;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log($"ArduinoMain: No valid response on {portName}.", LogLevel.Debug);
|
||||||
|
sp.Close();
|
||||||
|
sp.Dispose();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Probe failed on {portName}: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AwaitResponse(SerialPort sp, byte expected, int timeoutMs)
|
||||||
|
{
|
||||||
|
var sw = Stopwatch.StartNew();
|
||||||
|
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (sp.BytesToRead > 0)
|
||||||
|
{
|
||||||
|
int b = sp.ReadByte();
|
||||||
|
if (b < 0) break;
|
||||||
|
LogManager.Log($"ArduinoMain: Received 0x{b:X2} (expect 0x{expected:X2}).", LogLevel.Debug);
|
||||||
|
if (b == expected)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException) { }
|
||||||
|
Thread.Sleep(10);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Close()
|
||||||
|
{
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
if (serial != null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
serial.Close();
|
||||||
|
serial.Dispose();
|
||||||
|
LogManager.Log("ArduinoMain: Serial port closed.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Error closing port: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
serial = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Move(int x, int y)
|
||||||
|
{
|
||||||
|
SerialPort? sp;
|
||||||
|
lock (sync) sp = serial;
|
||||||
|
if (sp == null || !sp.IsOpen) return;
|
||||||
|
|
||||||
|
while (x != 0 || y != 0)
|
||||||
|
{
|
||||||
|
int stepX = Math.Max(-127, Math.Min(127, x));
|
||||||
|
int stepY = Math.Max(-127, Math.Min(127, y));
|
||||||
|
byte bX = unchecked((byte)stepX);
|
||||||
|
byte bY = unchecked((byte)stepY);
|
||||||
|
|
||||||
|
var packet = new byte[] { 0x01, bX, bY };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sp.Write(packet, 0, packet.Length);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Move write failed: {ex.Message}", LogLevel.Debug);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
x -= stepX;
|
||||||
|
y -= stepY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void ClickDown(int button = 0x03)
|
||||||
|
{
|
||||||
|
SendClick(button, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ClickUp(int button = 0x03)
|
||||||
|
{
|
||||||
|
SendClick(button, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SendClick(int buttonBase, bool expectDown)
|
||||||
|
{
|
||||||
|
SerialPort? sp;
|
||||||
|
lock (sync) sp = serial;
|
||||||
|
if (sp == null || !sp.IsOpen) return;
|
||||||
|
|
||||||
|
if (buttonBase != 0x03 && buttonBase != 0x05)
|
||||||
|
throw new ArgumentException("Button must be 0x03 (left) or 0x05 (right).", nameof(buttonBase));
|
||||||
|
|
||||||
|
byte code = (byte)(expectDown ? buttonBase : (buttonBase + 1));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sp.Write([code], 0, 1);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#include <Mouse.h>
|
||||||
|
|
||||||
|
enum ParseState : uint8_t { WAIT_CMD, WAIT_MOVE_X, WAIT_MOVE_Y };
|
||||||
|
ParseState state = WAIT_CMD;
|
||||||
|
uint8_t cmd = 0;
|
||||||
|
int8_t moveX = 0, moveY = 0;
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(2000);
|
||||||
|
Mouse.begin();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
while (Serial.available() > 0) {
|
||||||
|
int b = Serial.read();
|
||||||
|
if (b < 0) return;
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case WAIT_CMD:
|
||||||
|
cmd = (uint8_t)b;
|
||||||
|
switch (cmd) {
|
||||||
|
case 0x01: // move: need two more bytes
|
||||||
|
state = WAIT_MOVE_X;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x02:
|
||||||
|
Serial.write(0xAA); // ping
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x03: // left down
|
||||||
|
Mouse.press(MOUSE_LEFT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x04: // left up
|
||||||
|
Mouse.release(MOUSE_LEFT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x05: // right down
|
||||||
|
Mouse.press(MOUSE_RIGHT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x06: // right up
|
||||||
|
Mouse.release(MOUSE_RIGHT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_MOVE_X:
|
||||||
|
moveX = (int8_t)b;
|
||||||
|
state = WAIT_MOVE_Y;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_MOVE_Y:
|
||||||
|
moveY = (int8_t)b;
|
||||||
|
Mouse.move(moveX, moveY, 0);
|
||||||
|
state = WAIT_CMD;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
using HidSharp;
|
||||||
|
using Spectrum.Utilities;
|
||||||
|
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.HID
|
||||||
|
{
|
||||||
|
internal class HIDMain(int? vid = null, int? pid = null)
|
||||||
|
{
|
||||||
|
readonly int[] ExpectedVIDs =
|
||||||
|
[
|
||||||
|
0x046D,
|
||||||
|
0x1532,
|
||||||
|
0x1038,
|
||||||
|
0x1B1C,
|
||||||
|
0x0B05,
|
||||||
|
0x0951,
|
||||||
|
0x258A,
|
||||||
|
0x3057
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly byte BUTTON_LEFT = 0x01;
|
||||||
|
public static readonly byte BUTTON_RIGHT = 0x02;
|
||||||
|
public static readonly byte BUTTON_MIDDLE = 0x04;
|
||||||
|
public static readonly byte BUTTON_BACK = 0x08;
|
||||||
|
public static readonly byte BUTTON_FORWARD = 0x10;
|
||||||
|
|
||||||
|
const byte CMD_MOVE = 0x01;
|
||||||
|
const byte CMD_CLICK = 0x02;
|
||||||
|
const byte CMD_PRESS = 0x03;
|
||||||
|
const byte CMD_RELEASE = 0x04;
|
||||||
|
const byte CMD_SCROLL = 0x05;
|
||||||
|
const byte CMD_PING = 0x09;
|
||||||
|
|
||||||
|
const byte HID_REPORT_ID_VENDOR = 0x06;
|
||||||
|
const int FEATURE_REPORT_SIZE = 64;
|
||||||
|
const int PING_TIMEOUT_MS = 500;
|
||||||
|
|
||||||
|
int vid = vid ?? 0, pid = pid ?? 0;
|
||||||
|
HidDevice? device;
|
||||||
|
HidStream? stream;
|
||||||
|
private readonly object _syncLock = new();
|
||||||
|
|
||||||
|
IEnumerable<HidDevice> FindDevice()
|
||||||
|
{
|
||||||
|
var devices = DeviceList.Local.GetHidDevices();
|
||||||
|
foreach (var device in devices)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string name;
|
||||||
|
try { name = device.GetProductName(); }
|
||||||
|
catch { name = "<unavailable>"; }
|
||||||
|
LogManager.Log($"HIDMain: Found device: VID={device.VendorID:X4}, PID={device.ProductID:X4}, Name={name}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Error accessing device info: {e.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return devices.Where(device =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return
|
||||||
|
ExpectedVIDs.Contains(device.VendorID) &&
|
||||||
|
(vid == 0 || device.VendorID == vid) &&
|
||||||
|
(pid == 0 || device.ProductID == pid) &&
|
||||||
|
device.GetMaxFeatureReportLength() == FEATURE_REPORT_SIZE;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TestDeviceWithPing(HidDevice dev, HidStream testStream)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] pingPayload = [0x70, 0x69, 0x6E, 0x67, 0x70, 0x6F, 0x6E, 0x67];
|
||||||
|
byte[] pingPacket = new byte[FEATURE_REPORT_SIZE];
|
||||||
|
pingPacket[0] = HID_REPORT_ID_VENDOR;
|
||||||
|
pingPacket[1] = CMD_PING;
|
||||||
|
Array.Copy(pingPayload, 0, pingPacket, 2, pingPayload.Length);
|
||||||
|
|
||||||
|
LogManager.Log($"HIDMain: Sending ping to {dev.GetProductName()}...", LogLevel.Debug);
|
||||||
|
|
||||||
|
testStream.SetFeature(pingPacket);
|
||||||
|
Thread.Sleep(50);
|
||||||
|
|
||||||
|
byte[] response = new byte[FEATURE_REPORT_SIZE];
|
||||||
|
testStream.ReadTimeout = PING_TIMEOUT_MS;
|
||||||
|
|
||||||
|
int bytesRead = testStream.Read(response, 0, response.Length);
|
||||||
|
|
||||||
|
if (bytesRead > 0)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Received {bytesRead} bytes from {dev.GetProductName()}", LogLevel.Debug);
|
||||||
|
|
||||||
|
if (response[1] == CMD_PING)
|
||||||
|
{
|
||||||
|
bool payloadMatches = true;
|
||||||
|
for (int i = 0; i < pingPayload.Length; i++)
|
||||||
|
{
|
||||||
|
if (response[2 + i] != pingPayload[i])
|
||||||
|
{
|
||||||
|
payloadMatches = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payloadMatches)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Ping successful for {dev.GetProductName()}", LogLevel.Debug);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string responseString = "";
|
||||||
|
for (int i = 0; i < bytesRead; i++)
|
||||||
|
{
|
||||||
|
responseString += $"0x{response[i]:X2} ";
|
||||||
|
}
|
||||||
|
LogManager.Log($"HIDMain: Ping response payload mismatch for {dev.GetProductName()}: {responseString}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string responseString = "";
|
||||||
|
for (int i = 0; i < bytesRead; i++)
|
||||||
|
{
|
||||||
|
responseString += $"0x{response[i]:X2} ";
|
||||||
|
}
|
||||||
|
LogManager.Log($"HIDMain: Unexpected response from {dev.GetProductName()}: {responseString}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: No response from {dev.GetProductName()}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Ping timeout for {dev.GetProductName()}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Ping error for {dev.GetProductName()}: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Init()
|
||||||
|
{
|
||||||
|
lock (_syncLock)
|
||||||
|
{
|
||||||
|
if (stream != null && device != null)
|
||||||
|
{
|
||||||
|
LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug);
|
||||||
|
var candidates = FindDevice().ToList();
|
||||||
|
|
||||||
|
if (candidates.Count == 0)
|
||||||
|
{
|
||||||
|
LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var dev in candidates)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug);
|
||||||
|
|
||||||
|
if (dev.TryOpen(out stream))
|
||||||
|
{
|
||||||
|
if (TestDeviceWithPing(dev, stream))
|
||||||
|
{
|
||||||
|
device = dev;
|
||||||
|
vid = dev.VendorID;
|
||||||
|
pid = dev.ProductID;
|
||||||
|
LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug);
|
||||||
|
stream.Close();
|
||||||
|
stream.Dispose();
|
||||||
|
stream = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug);
|
||||||
|
stream?.Close();
|
||||||
|
stream?.Dispose();
|
||||||
|
stream = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool SendFeatureReport(byte[] data)
|
||||||
|
{
|
||||||
|
lock (_syncLock)
|
||||||
|
{
|
||||||
|
if (stream == null || device == null)
|
||||||
|
{
|
||||||
|
LogManager.Log("HIDMain: Device not connected.", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] report = new byte[FEATURE_REPORT_SIZE];
|
||||||
|
report[0] = HID_REPORT_ID_VENDOR;
|
||||||
|
|
||||||
|
int copyLength = Math.Min(data.Length, FEATURE_REPORT_SIZE - 1);
|
||||||
|
Array.Copy(data, 0, report, 1, copyLength);
|
||||||
|
|
||||||
|
stream.SetFeature(report);
|
||||||
|
Thread.Sleep(10);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Error sending feature report: {ex.Message}", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Move(int x, int y)
|
||||||
|
{
|
||||||
|
x = Math.Clamp(x, -127, 127);
|
||||||
|
y = Math.Clamp(y, -127, 127);
|
||||||
|
|
||||||
|
byte xByte = unchecked((byte)x);
|
||||||
|
byte yByte = unchecked((byte)y);
|
||||||
|
|
||||||
|
byte[] data = [CMD_MOVE, xByte, yByte];
|
||||||
|
bool success = SendFeatureReport(data);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Click(byte button)
|
||||||
|
{
|
||||||
|
byte[] data = [CMD_CLICK, button];
|
||||||
|
bool success = SendFeatureReport(data);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Press(byte button)
|
||||||
|
{
|
||||||
|
byte[] data = [CMD_PRESS, button];
|
||||||
|
bool success = SendFeatureReport(data);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Release(byte button)
|
||||||
|
{
|
||||||
|
byte[] data = [CMD_RELEASE, button];
|
||||||
|
bool success = SendFeatureReport(data);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Scroll(int amount)
|
||||||
|
{
|
||||||
|
amount = Math.Clamp(amount, -127, 127);
|
||||||
|
byte amountByte = unchecked((byte)amount);
|
||||||
|
|
||||||
|
byte[] data = [CMD_SCROLL, amountByte];
|
||||||
|
bool success = SendFeatureReport(data);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Close()
|
||||||
|
{
|
||||||
|
lock (_syncLock)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stream?.Close();
|
||||||
|
stream?.Dispose();
|
||||||
|
LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
stream = null;
|
||||||
|
device = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsConnected => stream != null && device != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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,363 @@
|
|||||||
|
using Spectrum.Input.InputLibraries.Arduino;
|
||||||
|
using Spectrum.Input.InputLibraries.HID;
|
||||||
|
using Spectrum.Utilities;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||||
|
|
||||||
|
namespace Spectrum.Input
|
||||||
|
{
|
||||||
|
public static class InputManager
|
||||||
|
{
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern bool GetCursorPos(out Point lpPoint);
|
||||||
|
private static readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
|
private static Point lastDetection = new();
|
||||||
|
private static Point _prevEnd = new();
|
||||||
|
private static Rectangle lastDetectionBox = new();
|
||||||
|
private static long _lastMoveTicks = 0;
|
||||||
|
private static readonly double _dtRef = 1.0 / 120.0;
|
||||||
|
private static bool isSpraying = false;
|
||||||
|
private static readonly HIDMain? hid = Program.HIDMain;
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
double k = deltaSeconds / _dtRef;
|
||||||
|
return Math.Pow(baseFactor, 3) * k;
|
||||||
|
}
|
||||||
|
double kLow = deltaSeconds / _dtRef;
|
||||||
|
return 1 - Math.Pow(1 - baseFactor, kLow);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void MoveMouse()
|
||||||
|
{
|
||||||
|
var config = mainConfig.Data;
|
||||||
|
Point reference = new();
|
||||||
|
if (config.ClosestToMouse)
|
||||||
|
{
|
||||||
|
GetCursorPos(out reference);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var bounds = Program.MonitorBounds;
|
||||||
|
reference.X = bounds.X + bounds.Width / 2;
|
||||||
|
reference.Y = bounds.Y + bounds.Height / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point start = new(reference.X, reference.Y);
|
||||||
|
Point end = new(lastDetection.X, lastDetection.Y);
|
||||||
|
|
||||||
|
double dt = GetDeltaSeconds();
|
||||||
|
|
||||||
|
double tDist = Math.Sqrt(Math.Pow(end.X - _prevEnd.X, 2) + Math.Pow(end.Y - _prevEnd.Y, 2));
|
||||||
|
if (tDist > 150 || dt > 0.1) MovementPaths.ResetWindMouse();
|
||||||
|
_prevEnd = end;
|
||||||
|
|
||||||
|
double effSensitivity = TimeScaleFactor(config.Sensitivity, dt);
|
||||||
|
|
||||||
|
bool insideBoundingBox = lastDetectionBox.Contains(start);
|
||||||
|
|
||||||
|
var tPath = Stopwatch.GetTimestamp();
|
||||||
|
Point newPosition = CalculateMovement(start, end, effSensitivity, config.AimMovementType, insideBoundingBox);
|
||||||
|
Program.Timings.Add("Movement Path", Stopwatch.GetTimestamp() - tPath);
|
||||||
|
|
||||||
|
if (config.EmaSmoothening)
|
||||||
|
{
|
||||||
|
double emaAlpha = TimeScaleFactor(config.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;
|
||||||
|
|
||||||
|
double maxMove = config.ClosestToMouse ? 75.0 : 120.0;
|
||||||
|
double moveDist = Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||||
|
if (moveDist > maxMove)
|
||||||
|
{
|
||||||
|
double r = maxMove / moveDist;
|
||||||
|
deltaX = (int)Math.Round(deltaX * r);
|
||||||
|
deltaY = (int)Math.Round(deltaY * r);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
||||||
|
if (deltaX > config.ImageWidth || deltaX < -config.ImageWidth || deltaY > config.ImageHeight || deltaY < -config.ImageHeight)
|
||||||
|
return;
|
||||||
|
|
||||||
|
switch (config.MovementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
case MovementMethod.HID:
|
||||||
|
if (hid != null && hid.IsConnected)
|
||||||
|
hid.Move(deltaX, deltaY);
|
||||||
|
else
|
||||||
|
LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point CalculateMovement(Point start, Point end, double sensitivity, MovementType movementType, bool insideBoundingBox)
|
||||||
|
{
|
||||||
|
return movementType switch
|
||||||
|
{
|
||||||
|
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(start, end, sensitivity),
|
||||||
|
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity),
|
||||||
|
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity),
|
||||||
|
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity),
|
||||||
|
MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox),
|
||||||
|
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Point TrackWindMouse(Point start, Point end, double sensitivity, bool insideBoundingBox)
|
||||||
|
{
|
||||||
|
var t0 = Stopwatch.GetTimestamp();
|
||||||
|
var result = MovementPaths.WindMouse(start, end,
|
||||||
|
mainConfig.Data.WindMouseGravity,
|
||||||
|
mainConfig.Data.WindMouseWind,
|
||||||
|
mainConfig.Data.WindMouseMaxStep,
|
||||||
|
sensitivity,
|
||||||
|
mainConfig.Data.WindMouseOvershoot,
|
||||||
|
insideBoundingBox);
|
||||||
|
Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task ClickMouse()
|
||||||
|
{
|
||||||
|
var config = mainConfig.Data;
|
||||||
|
if (!config.TriggerBot)
|
||||||
|
return;
|
||||||
|
if (!IsKeyOrMouseDown(config.TriggerKeybind) || config.TriggerKeybind.Key == Keys.None)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var currentPosition = new Point();
|
||||||
|
if (config.ClosestToMouse)
|
||||||
|
{
|
||||||
|
GetCursorPos(out currentPosition);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var bounds = Program.MonitorBounds;
|
||||||
|
currentPosition.X = bounds.X + bounds.Width / 2;
|
||||||
|
currentPosition.Y = bounds.Y + bounds.Height / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.TriggerDelay > 0 && !config.TriggerRandomDelay)
|
||||||
|
await Task.Delay(config.TriggerDelay);
|
||||||
|
else if (config.TriggerRandomDelay)
|
||||||
|
await Task.Delay(Random.Shared.Next(10, config.TriggerDelay + 1));
|
||||||
|
|
||||||
|
int radius = config.TriggerFov;
|
||||||
|
bool shouldClick;
|
||||||
|
if (config.TriggerInBoundsOnly)
|
||||||
|
shouldClick = lastDetectionBox.Contains(currentPosition);
|
||||||
|
else
|
||||||
|
shouldClick = Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius;
|
||||||
|
|
||||||
|
|
||||||
|
if (shouldClick)
|
||||||
|
{
|
||||||
|
if (config.TriggerSpray && !isSpraying)
|
||||||
|
{
|
||||||
|
isSpraying = true;
|
||||||
|
ClickDown(config.MovementMethod);
|
||||||
|
}
|
||||||
|
else if (!config.TriggerSpray)
|
||||||
|
{
|
||||||
|
ClickDown(config.MovementMethod);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.TriggerRandomDuration && !config.TriggerSpray)
|
||||||
|
await Task.Delay(config.TriggerDuration);
|
||||||
|
else if (!config.TriggerSpray)
|
||||||
|
await Task.Delay(Random.Shared.Next(20, config.TriggerDuration));
|
||||||
|
|
||||||
|
if (!config.TriggerSpray)
|
||||||
|
ClickUp(config.MovementMethod);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (isSpraying)
|
||||||
|
{
|
||||||
|
isSpraying = false;
|
||||||
|
ClickUp(config.MovementMethod);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ClickDown(MovementMethod movementMethod)
|
||||||
|
{
|
||||||
|
switch (movementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.ClickDown();
|
||||||
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.ClickDown();
|
||||||
|
break;
|
||||||
|
case MovementMethod.HID:
|
||||||
|
if (hid != null && hid.IsConnected)
|
||||||
|
hid.Press(HIDMain.BUTTON_LEFT);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.ClickDown();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static void ClickUp(MovementMethod movementMethod)
|
||||||
|
{
|
||||||
|
switch (movementMethod)
|
||||||
|
{
|
||||||
|
case MovementMethod.MouseEvent:
|
||||||
|
MouseEvent.ClickUp();
|
||||||
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.ClickUp();
|
||||||
|
break;
|
||||||
|
case MovementMethod.HID:
|
||||||
|
if (hid != null && hid.IsConnected)
|
||||||
|
hid.Release(HIDMain.BUTTON_LEFT);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
MouseEvent.ClickUp();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SetLastDetection(Point point) { lastDetection = point; }
|
||||||
|
|
||||||
|
public static void SetLastDetectionBox(Rectangle box) { lastDetectionBox = box; }
|
||||||
|
|
||||||
|
[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);
|
||||||
|
|
||||||
|
CancellationTokenRegistration ctr = default;
|
||||||
|
if (cancellationToken?.CanBeCanceled == true)
|
||||||
|
{
|
||||||
|
ctr = cancellationToken.Value.Register(() => tcs.TrySetCanceled());
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = tcs.Task.ContinueWith(_ =>
|
||||||
|
{
|
||||||
|
try { ctr.Dispose(); } catch { }
|
||||||
|
}, TaskScheduler.Default);
|
||||||
|
|
||||||
|
Task.Run(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (tcs.Task.IsCompleted)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var mouseKey in MouseKeys)
|
||||||
|
{
|
||||||
|
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
||||||
|
{
|
||||||
|
tcs.TrySetResult(mouseKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int key = 0x08; key <= 0xFE; key++)
|
||||||
|
{
|
||||||
|
if ((GetAsyncKeyState(key) & 0x8000) != 0)
|
||||||
|
{
|
||||||
|
tcs.TrySetResult((Keys)key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancellationToken?.IsCancellationRequested == true)
|
||||||
|
{
|
||||||
|
tcs.TrySetCanceled();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Thread.Sleep(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return tcs.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsKeyOrMouseDown(Keys key)
|
||||||
|
{
|
||||||
|
return (GetAsyncKeyState((int)key) & 0x8000) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, bool> _keybindToggleStates = [];
|
||||||
|
|
||||||
|
public static bool IsKeyOrMouseDown(Keybind keybind)
|
||||||
|
{
|
||||||
|
if (keybind.Type == KeybindType.Always)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
bool isKeyDown = IsKeyOrMouseDown(keybind.Key);
|
||||||
|
|
||||||
|
if (keybind.Type == KeybindType.Hold)
|
||||||
|
return isKeyDown;
|
||||||
|
|
||||||
|
string toggleKey = keybind.Key.ToString();
|
||||||
|
|
||||||
|
if (!_keybindToggleStates.ContainsKey(toggleKey))
|
||||||
|
_keybindToggleStates[toggleKey] = false;
|
||||||
|
|
||||||
|
if (isKeyDown && !_keybindToggleStates.ContainsKey($"{toggleKey}_pressed"))
|
||||||
|
{
|
||||||
|
_keybindToggleStates[$"{toggleKey}_pressed"] = true;
|
||||||
|
_keybindToggleStates[toggleKey] = !_keybindToggleStates[toggleKey];
|
||||||
|
}
|
||||||
|
else if (!isKeyDown)
|
||||||
|
{
|
||||||
|
_keybindToggleStates.Remove($"{toggleKey}_pressed");
|
||||||
|
}
|
||||||
|
|
||||||
|
return _keybindToggleStates[toggleKey];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
namespace Spectrum.Input
|
||||||
|
{
|
||||||
|
public class MovementPaths
|
||||||
|
{
|
||||||
|
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||||
|
private static readonly int[] _permutation = GeneratePermutation();
|
||||||
|
private static readonly int[] _p;
|
||||||
|
private static double _perlinTime = 0.0;
|
||||||
|
|
||||||
|
private static Point _lastMove = new(0, 0);
|
||||||
|
private static double _windX = 0.0;
|
||||||
|
private static double _windY = 0.0;
|
||||||
|
private static double _velocityX = 0.0;
|
||||||
|
private static double _velocityY = 0.0;
|
||||||
|
|
||||||
|
static MovementPaths()
|
||||||
|
{
|
||||||
|
_p = new int[512];
|
||||||
|
for (int i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
_p[256 + i] = _p[i] = _permutation[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10);
|
||||||
|
private static double Lerp(double a, double b, double t) => a + t * (b - a);
|
||||||
|
private static double Grad(int hash, double x)
|
||||||
|
{
|
||||||
|
int h = hash & 15;
|
||||||
|
double grad = 1 + (h & 7);
|
||||||
|
if ((h & 8) != 0) grad = -grad;
|
||||||
|
return grad * x;
|
||||||
|
}
|
||||||
|
private static double Perlin1D(double x)
|
||||||
|
{
|
||||||
|
int X = (int)Math.Floor(x) & 255;
|
||||||
|
x -= Math.Floor(x);
|
||||||
|
double u = Fade(x);
|
||||||
|
int a = _p[X];
|
||||||
|
int b = _p[X + 1];
|
||||||
|
double res = Lerp(Grad(a, x), Grad(b, x - 1), u);
|
||||||
|
return res * 0.188;
|
||||||
|
}
|
||||||
|
|
||||||
|
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(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
||||||
|
Point control2 = new(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
||||||
|
return CubicBezier(start, end, control1, control2, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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 < 1) return end;
|
||||||
|
double maxStep = 50.0 + (sensitivity * 20.0);
|
||||||
|
double adaptiveStep = sensitivity * (1.0 + (distance / 800.0));
|
||||||
|
double stepSize = Math.Min(distance * adaptiveStep, maxStep);
|
||||||
|
stepSize = Math.Min(stepSize, distance);
|
||||||
|
double ux = dx / distance;
|
||||||
|
double uy = dy / distance;
|
||||||
|
double jitterMag = Math.Min(Math.Sqrt(distance), 20.0) * sensitivity * 0.15;
|
||||||
|
double jitter = (Random.Shared.NextDouble() - 0.5) * jitterMag;
|
||||||
|
int nx = (int)Math.Round(start.X + ux * stepSize + (-uy * jitter));
|
||||||
|
int ny = (int)Math.Round(start.Y + uy * stepSize + (ux * jitter));
|
||||||
|
return new Point(nx, ny);
|
||||||
|
}
|
||||||
|
public static Point PerlinNoiseMovement(Point start, Point end, double t, double amplitudeFraction = 0.2, double frequency = 1.5)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
double dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double distance = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (distance == 0 || t == 0) return start;
|
||||||
|
|
||||||
|
double baseX = start.X + dx * t;
|
||||||
|
double baseY = start.Y + dy * t;
|
||||||
|
|
||||||
|
_perlinTime += t * 0.75;
|
||||||
|
double noise = Perlin1D(_perlinTime * frequency);
|
||||||
|
|
||||||
|
double nx = -dy / distance;
|
||||||
|
double ny = dx / distance;
|
||||||
|
|
||||||
|
double offsetMag = amplitudeFraction * distance * t;
|
||||||
|
double ox = nx * noise * offsetMag;
|
||||||
|
double oy = ny * noise * offsetMag;
|
||||||
|
|
||||||
|
int finalX = (int)Math.Round(baseX + ox);
|
||||||
|
int finalY = (int)Math.Round(baseY + oy);
|
||||||
|
return new Point(finalX, finalY);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool _isOvershooting = false;
|
||||||
|
private static Point _overshootTarget = new(0, 0);
|
||||||
|
|
||||||
|
public static Point WindMouse(Point start, Point end, double gravity = 9.0, double wind = 3.0,
|
||||||
|
double maxStep = 10.0, double sensitivity = 1.0, bool enableOvershoot = false, bool insideBoundingBox = false)
|
||||||
|
{
|
||||||
|
double dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double d = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (d <= 0) return start;
|
||||||
|
double inv = 1.0 / d;
|
||||||
|
double dirX = dx * inv;
|
||||||
|
double dirY = dy * inv;
|
||||||
|
|
||||||
|
if (insideBoundingBox)
|
||||||
|
{
|
||||||
|
double s = Math.Min(d * 0.35, maxStep * sensitivity * 0.6);
|
||||||
|
_perlinTime += 0.03;
|
||||||
|
double n = Math.Sin(_perlinTime * 1.1) * 0.3 + Math.Cos(_perlinTime * 0.9) * 0.2;
|
||||||
|
int x = (int)Math.Round(start.X + dirX * s + n);
|
||||||
|
int y = (int)Math.Round(start.Y + dirY * s + n * 0.7);
|
||||||
|
_windX *= 0.15;
|
||||||
|
_windY *= 0.15;
|
||||||
|
_velocityX *= 0.3;
|
||||||
|
_velocityY *= 0.3;
|
||||||
|
_isOvershooting = false;
|
||||||
|
return _lastMove = new Point(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
double distScale = Math.Min(d / 100.0, 3.0);
|
||||||
|
double sens = Math.Max(0.1, sensitivity);
|
||||||
|
double dyn = maxStep * sens * (1.0 + distScale);
|
||||||
|
if (enableOvershoot)
|
||||||
|
{
|
||||||
|
double currentVelocity = Math.Sqrt(_velocityX * _velocityX + _velocityY * _velocityY);
|
||||||
|
|
||||||
|
if (!_isOvershooting && d < 50 && currentVelocity > 3.0)
|
||||||
|
{
|
||||||
|
double overshootDistance = Math.Min(currentVelocity * 2.5, 30.0);
|
||||||
|
_overshootTarget = new Point(
|
||||||
|
(int)Math.Round(end.X + dirX * overshootDistance),
|
||||||
|
(int)Math.Round(end.Y + dirY * overshootDistance)
|
||||||
|
);
|
||||||
|
_isOvershooting = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isOvershooting)
|
||||||
|
{
|
||||||
|
double distToOvershoot = Math.Sqrt(
|
||||||
|
Math.Pow(_overshootTarget.X - start.X, 2) +
|
||||||
|
Math.Pow(_overshootTarget.Y - start.Y, 2)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
Point currentTarget;
|
||||||
|
if (distToOvershoot < 5.0 || currentVelocity < 1.5)
|
||||||
|
{
|
||||||
|
_isOvershooting = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
currentTarget = _overshootTarget;
|
||||||
|
dx = currentTarget.X - start.X;
|
||||||
|
dy = currentTarget.Y - start.Y;
|
||||||
|
d = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (d > 0)
|
||||||
|
{
|
||||||
|
inv = 1.0 / d;
|
||||||
|
dirX = dx * inv;
|
||||||
|
dirY = dy * inv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
double g = gravity * (1.0 + distScale * 0.3) * sens * (enableOvershoot && !_isOvershooting ? 1.3 : 1.0);
|
||||||
|
double prox = insideBoundingBox ? 0.0 : 1.0;
|
||||||
|
double w = wind * Math.Pow(prox, 4.0) * (enableOvershoot ? 1.3 : 1.0);
|
||||||
|
|
||||||
|
if (insideBoundingBox)
|
||||||
|
{
|
||||||
|
double damp = 0.25;
|
||||||
|
_velocityX *= damp;
|
||||||
|
_velocityY *= damp;
|
||||||
|
double wd = Math.Pow(damp, 4.0);
|
||||||
|
_windX *= wd;
|
||||||
|
_windY *= wd;
|
||||||
|
}
|
||||||
|
|
||||||
|
_windX = _windX / Math.Sqrt(3) + (Random.Shared.NextDouble() * 2 - 1) * w;
|
||||||
|
_windY = _windY / Math.Sqrt(3) + (Random.Shared.NextDouble() * 2 - 1) * w;
|
||||||
|
|
||||||
|
_velocityX += _windX + g * dirX;
|
||||||
|
_velocityY += _windY + g * dirY;
|
||||||
|
|
||||||
|
double vm = Math.Sqrt(_velocityX * _velocityX + _velocityY * _velocityY);
|
||||||
|
if (vm > dyn)
|
||||||
|
{
|
||||||
|
double r = dyn / vm;
|
||||||
|
_velocityX *= r;
|
||||||
|
_velocityY *= r;
|
||||||
|
vm = dyn;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!enableOvershoot && insideBoundingBox)
|
||||||
|
{
|
||||||
|
double limit = d * 0.4;
|
||||||
|
if (vm > limit && vm > 0)
|
||||||
|
{
|
||||||
|
double r = limit / vm;
|
||||||
|
_velocityX *= r;
|
||||||
|
_velocityY *= r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (enableOvershoot && !_isOvershooting && d < 30)
|
||||||
|
{
|
||||||
|
double correctionDamp = 0.7;
|
||||||
|
_velocityX *= correctionDamp;
|
||||||
|
_velocityY *= correctionDamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
int nx = (int)Math.Round(start.X + _velocityX);
|
||||||
|
int ny = (int)Math.Round(start.Y + _velocityY);
|
||||||
|
return _lastMove = new Point(nx, ny);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ResetWindMouse()
|
||||||
|
{
|
||||||
|
_windX = 0.0;
|
||||||
|
_windY = 0.0;
|
||||||
|
_velocityX = 0.0;
|
||||||
|
_velocityY = 0.0;
|
||||||
|
_lastMove = new Point(0, 0);
|
||||||
|
_isOvershooting = false;
|
||||||
|
_overshootTarget = new Point(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] GeneratePermutation()
|
||||||
|
{
|
||||||
|
int[] perm = new int[256];
|
||||||
|
for (int i = 0; i < 256; i++) perm[i] = i;
|
||||||
|
for (int i = 255; i > 0; i--)
|
||||||
|
{
|
||||||
|
int j = Random.Shared.Next(i + 1);
|
||||||
|
(perm[i], perm[j]) = (perm[j], perm[i]);
|
||||||
|
}
|
||||||
|
return perm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,107 +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/2e906552673e359ded90383c5e97d79c8f38a2f2/Aimmy2/InputLogic/MouseManager.cs#L34-L50
|
|
||||||
private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
|
||||||
{
|
|
||||||
double u = 1 - t;
|
|
||||||
double tt = t * t;
|
|
||||||
double uu = u * u;
|
|
||||||
|
|
||||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
|
||||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
|
||||||
|
|
||||||
return new Point((int)x, (int)y);
|
|
||||||
}
|
|
||||||
private static Point CubicBezierMovement(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
|
||||||
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
|
||||||
return CubicBezier(start, end, control1, control2, t);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point LinearInterpolation(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
int x = (int)(start.X + t * (end.X - start.X));
|
|
||||||
int y = (int)(start.Y + t * (end.Y - start.Y));
|
|
||||||
return new Point(x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point CurvedMovement(Point start, Point end, double t)
|
|
||||||
{
|
|
||||||
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
|
||||||
return QuadraticBezier(start, end, control, t);
|
|
||||||
}
|
|
||||||
private static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
|
||||||
{
|
|
||||||
double u = 1 - t;
|
|
||||||
double tt = t * t;
|
|
||||||
double uu = u * u;
|
|
||||||
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
|
||||||
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
|
||||||
return new Point((int)x, (int)y);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
|
||||||
{
|
|
||||||
double distance = Math.Sqrt(Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2));
|
|
||||||
double stepSize = distance * sensitivity;
|
|
||||||
|
|
||||||
double directionX = (end.X - start.X) / distance;
|
|
||||||
double directionY = (end.Y - start.Y) / distance;
|
|
||||||
|
|
||||||
int newX = (int)(start.X + directionX * stepSize);
|
|
||||||
int newY = (int)(start.Y + directionY * stepSize);
|
|
||||||
return new Point(newX, newY);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 newPosition = Config.AimMovementType switch
|
|
||||||
{
|
|
||||||
Config.MovementType.CubicBezier => CubicBezierMovement(start, end, Config.Sensitivity),
|
|
||||||
Config.MovementType.Linear => LinearInterpolation(start, end, Config.Sensitivity),
|
|
||||||
Config.MovementType.Adaptive => AdaptiveMovement(start, end, Config.Sensitivity),
|
|
||||||
Config.MovementType.QuadraticBezier => CurvedMovement(start, end, Config.Sensitivity),
|
|
||||||
_ => end
|
|
||||||
};
|
|
||||||
|
|
||||||
int deltaX = newPosition.X - reference.X;
|
|
||||||
int deltaY = newPosition.Y - reference.Y;
|
|
||||||
|
|
||||||
|
|
||||||
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+105
-271
@@ -1,314 +1,148 @@
|
|||||||
using OpenCvSharp;
|
using OpenCvSharp;
|
||||||
using OpenCvSharp.Internal.Vectors;
|
using Spectrum.Detection;
|
||||||
using System.Drawing;
|
using Spectrum.Input.InputLibraries.HID;
|
||||||
using System.Drawing.Imaging;
|
using Spectrum.Utilities;
|
||||||
using System.Runtime.InteropServices;
|
using System.CommandLine;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum
|
||||||
{
|
{
|
||||||
class Program
|
class Program
|
||||||
{
|
{
|
||||||
static Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
static Renderer? renderer = null;
|
||||||
static void Main()
|
public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs");
|
||||||
{
|
public static ColorConfigManager colorConfig = new("bin\\configs\\colors");
|
||||||
Config.LoadConfig();
|
public static HIDMain HIDMain = new();
|
||||||
Config.StartFileWatcher();
|
private static DetectionManager? detectionManager;
|
||||||
|
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
|
||||||
|
public static TimingStats Timings { get; } = new TimingStats();
|
||||||
|
public static int MonitorIndex { get; private set; } = 1;
|
||||||
|
public static Rectangle MonitorBounds { get; private set; } = Screen.PrimaryScreen?.Bounds ?? Screen.AllScreens[0].Bounds;
|
||||||
|
|
||||||
|
static int Main(string[] args)
|
||||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
|
||||||
bounds = new Rectangle(
|
|
||||||
(screenSize.Width - Config.ImageWidth) / 2,
|
|
||||||
(screenSize.Height - Config.ImageHeight) / 2,
|
|
||||||
Config.ImageWidth,
|
|
||||||
Config.ImageHeight
|
|
||||||
);
|
|
||||||
|
|
||||||
if (Config.ShowDetectionWindow)
|
|
||||||
{
|
{
|
||||||
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
|
var monitorOption = new Option<int>(["--monitor", "-m"], () => 1);
|
||||||
Cv2.WaitKey(1);
|
var debugOption = new Option<bool>(["--debug", "-d"], () => false);
|
||||||
}
|
var rootCommand = new RootCommand();
|
||||||
if (Config.AutoLabel)
|
rootCommand.AddOption(monitorOption);
|
||||||
{
|
rootCommand.AddOption(debugOption);
|
||||||
AutoLabeling.StartLabeling();
|
rootCommand.SetHandler((monitor, debug) => Run(monitor, debug), monitorOption, debugOption);
|
||||||
|
return rootCommand.Invoke(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
Directory.CreateDirectory("dataset");
|
private static void Run(int monitor, bool debug)
|
||||||
Directory.CreateDirectory("dataset/images");
|
|
||||||
Directory.CreateDirectory("dataset/labels");
|
|
||||||
|
|
||||||
while (true)
|
|
||||||
{
|
{
|
||||||
if (Console.KeyAvailable)
|
LogManager.SetDebugOverride(debug);
|
||||||
{
|
if (debug && !System.Diagnostics.Debugger.IsAttached)
|
||||||
var key = Console.ReadKey(true).Key;
|
Win32.EnsureConsoleAttached();
|
||||||
if (key == ConsoleKey.Escape)
|
ConfigureMonitor(monitor);
|
||||||
{
|
LogManager.Log($"Monitor arg: {monitor}", LogManager.LogLevel.Debug);
|
||||||
if (Config.ShowDetectionWindow)
|
LogManager.Log($"Monitor index: {MonitorIndex}", LogManager.LogLevel.Debug);
|
||||||
{
|
LogManager.Log($"Monitor bounds: {MonitorBounds.X},{MonitorBounds.Y} {MonitorBounds.Width}x{MonitorBounds.Height}", LogManager.LogLevel.Debug);
|
||||||
Cv2.DestroyAllWindows();
|
Thread renderThread = new(() =>
|
||||||
}
|
|
||||||
Config.StopFileWatcher();
|
|
||||||
Environment.Exit(0);
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.O)
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json");
|
renderer = new Renderer(SharedCaptureManager);
|
||||||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
|
bool dxok = SharedCaptureManager.TryInitializeDirectX(0, MonitorIndex - 1);
|
||||||
|
if (!dxok)
|
||||||
{
|
{
|
||||||
FileName = configFilePath,
|
LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning);
|
||||||
UseShellExecute = true,
|
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
||||||
CreateNoWindow = true
|
}
|
||||||
});
|
renderer.Run();
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Opened config file in default application.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Failed to open config file: {ex.Message}");
|
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", "bin/configs/colors"];
|
||||||
|
foreach (var dir in dirs)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(dir))
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
}
|
}
|
||||||
else if (key == ConsoleKey.F1)
|
|
||||||
|
mainConfig.LoadConfig();
|
||||||
|
mainConfig.StartFileWatcher();
|
||||||
|
|
||||||
|
if (mainConfig.Data.AutoLabel)
|
||||||
{
|
{
|
||||||
Config.ShowDetectionWindow = !Config.ShowDetectionWindow;
|
|
||||||
if (Config.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Enabled detection window.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Cv2.DestroyAllWindows();
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[INFO] Disabled detection window.");
|
|
||||||
}
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.F2)
|
|
||||||
{
|
|
||||||
Config.AutoLabel = !Config.AutoLabel;
|
|
||||||
if (Config.AutoLabel)
|
|
||||||
{
|
|
||||||
Config.CollectData = true;
|
|
||||||
AutoLabeling.StartLabeling();
|
AutoLabeling.StartLabeling();
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Enabled auto-labeling.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
AutoLabeling.StopLabeling();
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[INFO] Disabled auto-labeling.");
|
|
||||||
}
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.F3)
|
|
||||||
{
|
|
||||||
Config.CollectData = !Config.CollectData;
|
|
||||||
if (Config.CollectData)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Enabled data collection.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[INFO] Disabled data collection.");
|
|
||||||
}
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.F4)
|
|
||||||
{
|
|
||||||
Config.EnableAim = !Config.EnableAim;
|
|
||||||
if (Config.EnableAim)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Enabled aiming.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[INFO] Disabled aiming.");
|
|
||||||
}
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.F5)
|
|
||||||
{
|
|
||||||
Config.ClosestToMouse = !Config.ClosestToMouse;
|
|
||||||
if (Config.ClosestToMouse)
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Green;
|
|
||||||
Console.WriteLine("[INFO] Enabled closest to mouse aiming.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
|
||||||
Console.WriteLine("[INFO] Disabled closest to mouse aiming.");
|
|
||||||
}
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
else if (key == ConsoleKey.H || key == ConsoleKey.Help)
|
|
||||||
{
|
|
||||||
Console.WriteLine("Spectrum Keybinds:");
|
|
||||||
Console.WriteLine("F1: Toggle detection window");
|
|
||||||
Console.WriteLine("F2: Toggle auto-labeling");
|
|
||||||
Console.WriteLine("F3: Toggle data collection");
|
|
||||||
Console.WriteLine("F4: Toggle aiming");
|
|
||||||
Console.WriteLine("F5: Toggle closest to mouse aiming");
|
|
||||||
Console.WriteLine("O: Open config file in default application");
|
|
||||||
Console.WriteLine("ESC: Exit the application");
|
|
||||||
Console.WriteLine("H: Show this help message");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
|
||||||
Console.WriteLine("[WARNING] Unrecognized key pressed. Press H for help.");
|
|
||||||
Console.ResetColor();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (SystemHelper.GetAsyncKeyState(Config.Keybind) < 0)
|
if (colorConfig.Colors.Count == 0)
|
||||||
{
|
{
|
||||||
var screenshot = CaptureScreenshot(bounds);
|
colorConfig.SaveColor(new ColorInfo("Arsenal [Magenta]", new Scalar(179, 255, 255), new Scalar(150, 255, 255)));
|
||||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
colorConfig.SaveColor(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
|
||||||
Mat drawing = mat.Clone(); // clone for drawing
|
mainConfig.LoadConfig();
|
||||||
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)
|
Thread.Sleep(1000);
|
||||||
{
|
|
||||||
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)
|
if (renderer == null)
|
||||||
{
|
{
|
||||||
AutoLabeling.AddToQueue(drawing, bounds, filteredContours);
|
LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error);
|
||||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
return;
|
||||||
}
|
|
||||||
if (!Config.AutoLabel && Config.CollectData)
|
|
||||||
{
|
|
||||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Config.EnableAim)
|
detectionManager = new DetectionManager(renderer);
|
||||||
{
|
|
||||||
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Config.ShowDetectionWindow)
|
private static void ConfigureMonitor(int monitor)
|
||||||
{
|
{
|
||||||
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
|
var screens = Screen.AllScreens;
|
||||||
Cv2.ImShow("Spectrum Detection", drawing);
|
if (screens.Length == 0)
|
||||||
Cv2.WaitKey(1);
|
return;
|
||||||
}
|
|
||||||
}
|
var index = monitor < 1 ? 1 : monitor;
|
||||||
}
|
LogManager.Log($"Detected monitors: {screens.Length}", LogManager.LogLevel.Debug);
|
||||||
else if (Config.ShowDetectionWindow)
|
for (int i = 0; i < screens.Length; i++)
|
||||||
|
LogManager.Log($"Monitor {i + 1}: {screens[i].DeviceName} {screens[i].Bounds.X},{screens[i].Bounds.Y} {screens[i].Bounds.Width}x{screens[i].Bounds.Height}", LogManager.LogLevel.Debug);
|
||||||
|
|
||||||
|
var selected = GetScreenByDeviceNumber(screens, index);
|
||||||
|
if (selected == null)
|
||||||
{
|
{
|
||||||
Cv2.ImShow("Spectrum Detection", drawing);
|
if (index > screens.Length)
|
||||||
Cv2.WaitKey(1);
|
index = 1;
|
||||||
}
|
selected = screens[index - 1];
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (Config.ShowDetectionWindow)
|
|
||||||
{
|
|
||||||
Cv2.WaitKey(1);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Thread.Sleep(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
MonitorIndex = index;
|
||||||
}
|
MonitorBounds = selected.Bounds;
|
||||||
}
|
|
||||||
public static Bitmap CaptureScreenshot(Rectangle bounds)
|
|
||||||
{
|
|
||||||
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
|
||||||
using (Graphics g = Graphics.FromImage(bitmap))
|
|
||||||
{
|
|
||||||
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
|
|
||||||
}
|
|
||||||
return bitmap;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public static class SystemHelper
|
|
||||||
{
|
|
||||||
[DllImport("user32.dll")]
|
|
||||||
private static extern int GetSystemMetrics(int nIndex);
|
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
|
||||||
public static extern short GetAsyncKeyState(int vKey);
|
|
||||||
|
|
||||||
private const int SM_CXSCREEN = 0;
|
|
||||||
private const int SM_CYSCREEN = 1;
|
|
||||||
private const int SM_XVIRTUALSCREEN = 76;
|
|
||||||
private const int SM_YVIRTUALSCREEN = 77;
|
|
||||||
private const int SM_CXVIRTUALSCREEN = 78;
|
|
||||||
private const int SM_CYVIRTUALSCREEN = 79;
|
|
||||||
|
|
||||||
public static (int Width, int Height) GetPrimaryScreenSize()
|
|
||||||
{
|
|
||||||
return (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (int X, int Y, int Width, int Height) GetVirtualScreenBounds()
|
private static Screen? GetScreenByDeviceNumber(Screen[] screens, int index)
|
||||||
{
|
{
|
||||||
return (
|
foreach (var screen in screens)
|
||||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
{
|
||||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
var number = TryGetDisplayNumber(screen.DeviceName);
|
||||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
if (number.HasValue && number.Value == index)
|
||||||
GetSystemMetrics(SM_CYVIRTUALSCREEN)
|
return screen;
|
||||||
);
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int? TryGetDisplayNumber(string deviceName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(deviceName))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
int i = deviceName.Length - 1;
|
||||||
|
while (i >= 0 && char.IsDigit(deviceName[i]))
|
||||||
|
i--;
|
||||||
|
|
||||||
|
if (i == deviceName.Length - 1)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var numberText = deviceName[(i + 1)..];
|
||||||
|
if (int.TryParse(numberText, out var value))
|
||||||
|
return value;
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using OpenCvSharp;
|
||||||
|
using SixLabors.ImageSharp;
|
||||||
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
|
using Spectrum.Utilities;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
partial class Renderer
|
||||||
|
{
|
||||||
|
private bool _showHSVRangeWindow = false;
|
||||||
|
private Mat? _originalImage = null;
|
||||||
|
private Mat? _maskedImage = null;
|
||||||
|
private Image<Rgba32>? _originalImageSharp = null;
|
||||||
|
private Image<Rgba32>? _maskedImageSharp = null;
|
||||||
|
private IntPtr _originalTextureId = IntPtr.Zero;
|
||||||
|
private IntPtr _maskedTextureId = IntPtr.Zero;
|
||||||
|
private Scalar _lowerHSV = new(0, 0, 0);
|
||||||
|
private Scalar _upperHSV = new(179, 255, 255);
|
||||||
|
private string _loadedImagePath = "";
|
||||||
|
private bool _needsTextureUpdate = false;
|
||||||
|
private string _colorName = "";
|
||||||
|
|
||||||
|
private int _maskDisplayMode = 0;
|
||||||
|
private Vector3 _maskTintColor = new(1.0f, 1.0f, 1.0f);
|
||||||
|
private float _maskOpacity = 1.0f;
|
||||||
|
private Vector3 _backgroundColor = new(0.0f, 0.0f, 0.0f);
|
||||||
|
private bool _showOnlyMaskedRegion = true;
|
||||||
|
|
||||||
|
void RenderHSVRangeWindow()
|
||||||
|
{
|
||||||
|
if (!_showHSVRangeWindow)
|
||||||
|
return;
|
||||||
|
|
||||||
|
ImGui.SetNextWindowSize(new Vector2(900, 700), ImGuiCond.FirstUseEver);
|
||||||
|
ImGui.SetNextWindowSizeConstraints(new Vector2(700, 500), new Vector2(float.MaxValue, float.MaxValue));
|
||||||
|
ImGui.Begin("HSV Range Selector", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar);
|
||||||
|
|
||||||
|
ImGui.Text("HSV Range Selector");
|
||||||
|
ImGui.SameLine();
|
||||||
|
float currentWidth = ImGui.GetWindowWidth();
|
||||||
|
ImGui.SetCursorPosX(currentWidth - 30);
|
||||||
|
if (ImGui.Button("X##HSVClose", new Vector2(22, 22)))
|
||||||
|
{
|
||||||
|
_showHSVRangeWindow = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ImGui.Button("Load Image"))
|
||||||
|
{
|
||||||
|
OpenImageFileDialog();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(_loadedImagePath))
|
||||||
|
{
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.TextDisabled($"Loaded: {Path.GetFileName(_loadedImagePath)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
if (_originalImage != null && !_originalImage.Empty())
|
||||||
|
{
|
||||||
|
float availWidth = ImGui.GetContentRegionAvail().X;
|
||||||
|
float availHeight = ImGui.GetContentRegionAvail().Y;
|
||||||
|
|
||||||
|
float controlsHeight = 500;
|
||||||
|
float maxImageHeight = Math.Max(100, availHeight - controlsHeight);
|
||||||
|
|
||||||
|
float imageDisplayWidth = (availWidth - 20) / 2;
|
||||||
|
float aspectRatio = (float)_originalImage.Height / _originalImage.Width;
|
||||||
|
float imageDisplayHeight = Math.Min(imageDisplayWidth * aspectRatio, maxImageHeight);
|
||||||
|
imageDisplayWidth = imageDisplayHeight / aspectRatio;
|
||||||
|
|
||||||
|
if (_needsTextureUpdate)
|
||||||
|
{
|
||||||
|
UpdateTextures();
|
||||||
|
_needsTextureUpdate = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.BeginGroup();
|
||||||
|
ImGui.Text("Original Image");
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
ImGui.Image(_originalTextureId, new Vector2(imageDisplayWidth, imageDisplayHeight));
|
||||||
|
}
|
||||||
|
ImGui.EndGroup();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
|
||||||
|
ImGui.BeginGroup();
|
||||||
|
ImGui.Text("Masked Image");
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
ImGui.Image(_maskedTextureId, new Vector2(imageDisplayWidth, imageDisplayHeight));
|
||||||
|
}
|
||||||
|
ImGui.EndGroup();
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
if (ImGui.CollapsingHeader("Visual Settings", ImGuiTreeNodeFlags.DefaultOpen))
|
||||||
|
{
|
||||||
|
bool visualChanged = false;
|
||||||
|
|
||||||
|
ImGui.Text("Display Mode");
|
||||||
|
if (ImGui.RadioButton("Masked Result", ref _maskDisplayMode, 0))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.SameLine();
|
||||||
|
if (ImGui.RadioButton("Mask Only", ref _maskDisplayMode, 1))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.SameLine();
|
||||||
|
if (ImGui.RadioButton("Overlay", ref _maskDisplayMode, 2))
|
||||||
|
visualChanged = true;
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 1 || _maskDisplayMode == 2)
|
||||||
|
{
|
||||||
|
if (ImGui.ColorEdit3("Mask Tint", ref _maskTintColor))
|
||||||
|
visualChanged = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 2)
|
||||||
|
{
|
||||||
|
if (ImGui.SliderFloat("Mask Opacity", ref _maskOpacity, 0.0f, 1.0f, "%.2f"))
|
||||||
|
visualChanged = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 0)
|
||||||
|
if (ImGui.Checkbox("Show Only Masked Region", ref _showOnlyMaskedRegion))
|
||||||
|
visualChanged = true;
|
||||||
|
|
||||||
|
if (!_showOnlyMaskedRegion && _maskDisplayMode == 0)
|
||||||
|
{
|
||||||
|
ImGui.Indent();
|
||||||
|
if (ImGui.ColorEdit3("Background Color", ref _backgroundColor))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.Unindent();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (visualChanged)
|
||||||
|
{
|
||||||
|
UpdateMask();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
bool changed = false;
|
||||||
|
|
||||||
|
ImGui.Text("Lower HSV Bound");
|
||||||
|
|
||||||
|
int lowerH = (int)_lowerHSV.Val0;
|
||||||
|
int lowerS = (int)_lowerHSV.Val1;
|
||||||
|
int lowerV = (int)_lowerHSV.Val2;
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
if (ImGui.SliderInt("##LowerH", ref lowerH, 0, 179, "H: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##LowerS", ref lowerS, 0, 255, "S: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##LowerV", ref lowerV, 0, 255, "V: %d"))
|
||||||
|
changed = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.Text("Upper HSV Bound");
|
||||||
|
|
||||||
|
int upperH = (int)_upperHSV.Val0;
|
||||||
|
int upperS = (int)_upperHSV.Val1;
|
||||||
|
int upperV = (int)_upperHSV.Val2;
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
if (ImGui.SliderInt("##UpperH", ref upperH, 0, 179, "H: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##UpperS", ref upperS, 0, 255, "S: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##UpperV", ref upperV, 0, 255, "V: %d"))
|
||||||
|
changed = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
if (changed)
|
||||||
|
{
|
||||||
|
_lowerHSV = new Scalar(
|
||||||
|
Math.Clamp(lowerH, 0, 179),
|
||||||
|
Math.Clamp(lowerS, 0, 255),
|
||||||
|
Math.Clamp(lowerV, 0, 255)
|
||||||
|
);
|
||||||
|
|
||||||
|
_upperHSV = new Scalar(
|
||||||
|
Math.Clamp(upperH, 0, 179),
|
||||||
|
Math.Clamp(upperS, 0, 255),
|
||||||
|
Math.Clamp(upperV, 0, 255)
|
||||||
|
);
|
||||||
|
|
||||||
|
UpdateMask();
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.Text("Save as New Color");
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
ImGui.InputText("##ColorName", ref _colorName, 256);
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
if (ImGui.Button("Create Color", new Vector2(-1, 0)))
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(_colorName))
|
||||||
|
{
|
||||||
|
Program.colorConfig.SaveColor(new ColorInfo(_colorName, _upperHSV, _lowerHSV));
|
||||||
|
_colorName = "";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogManager.Log("Please enter a color name", LogManager.LogLevel.Warning);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenImageFileDialog()
|
||||||
|
{
|
||||||
|
Thread thread = new(() =>
|
||||||
|
{
|
||||||
|
using OpenFileDialog openFileDialog = new();
|
||||||
|
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png|All Files|*.*";
|
||||||
|
openFileDialog.Title = "Select an Image";
|
||||||
|
openFileDialog.Multiselect = false;
|
||||||
|
|
||||||
|
var windowWrapper = new WindowWrapper(window.Handle);
|
||||||
|
if (openFileDialog.ShowDialog(windowWrapper) == DialogResult.OK)
|
||||||
|
{
|
||||||
|
LoadImage(openFileDialog.FileName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
thread.SetApartmentState(ApartmentState.STA);
|
||||||
|
thread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class WindowWrapper(IntPtr handle) : IWin32Window
|
||||||
|
{
|
||||||
|
private readonly IntPtr _handle = handle;
|
||||||
|
|
||||||
|
public IntPtr Handle => _handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadImage(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DisposeImageResources();
|
||||||
|
|
||||||
|
_originalImage = Cv2.ImRead(path, ImreadModes.Color);
|
||||||
|
|
||||||
|
if (_originalImage == null || _originalImage.Empty())
|
||||||
|
{
|
||||||
|
LogManager.Log($"Failed to load image: {path}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_loadedImagePath = path;
|
||||||
|
UpdateMask();
|
||||||
|
_needsTextureUpdate = true;
|
||||||
|
|
||||||
|
LogManager.Log($"Loaded image: {path} ({_originalImage.Width}x{_originalImage.Height})", LogManager.LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error loading image: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateMask()
|
||||||
|
{
|
||||||
|
if (_originalImage == null || _originalImage.Empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (Mat hsvImage = new())
|
||||||
|
{
|
||||||
|
Cv2.CvtColor(_originalImage, hsvImage, ColorConversionCodes.BGR2HSV);
|
||||||
|
|
||||||
|
using Mat mask = new();
|
||||||
|
Cv2.InRange(hsvImage, _lowerHSV, _upperHSV, mask);
|
||||||
|
|
||||||
|
_maskedImage?.Dispose();
|
||||||
|
_maskedImage = new Mat();
|
||||||
|
|
||||||
|
switch (_maskDisplayMode)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
if (_showOnlyMaskedRegion)
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, _maskedImage, mask);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
using Mat background = new(_originalImage.Size(), _originalImage.Type(),
|
||||||
|
new Scalar(_backgroundColor.Z * 255, _backgroundColor.Y * 255, _backgroundColor.X * 255));
|
||||||
|
|
||||||
|
using Mat maskedForeground = new();
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedForeground, mask);
|
||||||
|
|
||||||
|
using Mat invertedMask = new();
|
||||||
|
Cv2.BitwiseNot(mask, invertedMask);
|
||||||
|
using Mat maskedBackground = new();
|
||||||
|
Cv2.BitwiseAnd(background, background, maskedBackground, invertedMask);
|
||||||
|
Cv2.Add(maskedForeground, maskedBackground, _maskedImage);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
using (Mat coloredMask = new(_originalImage.Size(), _originalImage.Type()))
|
||||||
|
{
|
||||||
|
Cv2.CvtColor(mask, coloredMask, ColorConversionCodes.GRAY2BGR);
|
||||||
|
|
||||||
|
using Mat tintMat = new(_originalImage.Size(), MatType.CV_32FC3,
|
||||||
|
new Scalar(_maskTintColor.Z, _maskTintColor.Y, _maskTintColor.X));
|
||||||
|
using Mat coloredMaskFloat = new();
|
||||||
|
using Mat tinted = new();
|
||||||
|
|
||||||
|
coloredMask.ConvertTo(coloredMaskFloat, MatType.CV_32FC3, 1.0 / 255.0);
|
||||||
|
Cv2.Multiply(coloredMaskFloat, tintMat, tinted);
|
||||||
|
tinted.ConvertTo(_maskedImage, _originalImage.Type(), 255.0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
using (Mat maskedResult = new())
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedResult, mask);
|
||||||
|
|
||||||
|
using Mat maskColored = new(_originalImage.Size(), _originalImage.Type());
|
||||||
|
Cv2.CvtColor(mask, maskColored, ColorConversionCodes.GRAY2BGR);
|
||||||
|
|
||||||
|
using Mat tintMat = new(_originalImage.Size(), MatType.CV_32FC3,
|
||||||
|
new Scalar(_maskTintColor.Z * _maskOpacity, _maskTintColor.Y * _maskOpacity, _maskTintColor.X * _maskOpacity));
|
||||||
|
using Mat maskColoredFloat = new();
|
||||||
|
using Mat tinted = new();
|
||||||
|
using Mat tintedByte = new();
|
||||||
|
|
||||||
|
maskColored.ConvertTo(maskColoredFloat, MatType.CV_32FC3, 1.0 / 255.0);
|
||||||
|
Cv2.Multiply(maskColoredFloat, tintMat, tinted);
|
||||||
|
tinted.ConvertTo(tintedByte, _originalImage.Type(), 255.0);
|
||||||
|
|
||||||
|
using Mat originalFloat = new();
|
||||||
|
using Mat tintedFloat = new();
|
||||||
|
using Mat blended = new();
|
||||||
|
|
||||||
|
_originalImage.ConvertTo(originalFloat, MatType.CV_32FC3);
|
||||||
|
tintedByte.ConvertTo(tintedFloat, MatType.CV_32FC3);
|
||||||
|
Cv2.AddWeighted(originalFloat, 1.0 - _maskOpacity, tintedFloat, _maskOpacity, 0, blended);
|
||||||
|
blended.ConvertTo(_maskedImage, _originalImage.Type());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_needsTextureUpdate = true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating mask: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateTextures()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_originalImage != null && !_originalImage.Empty())
|
||||||
|
{
|
||||||
|
_originalImageSharp?.Dispose();
|
||||||
|
_originalImageSharp = MatToImageSharp(_originalImage);
|
||||||
|
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
RemoveImage("hsv_original");
|
||||||
|
|
||||||
|
AddOrGetImagePointer("hsv_original", _originalImageSharp, false, out _originalTextureId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskedImage != null && !_maskedImage.Empty())
|
||||||
|
{
|
||||||
|
_maskedImageSharp?.Dispose();
|
||||||
|
_maskedImageSharp = MatToImageSharp(_maskedImage);
|
||||||
|
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
RemoveImage("hsv_masked");
|
||||||
|
|
||||||
|
AddOrGetImagePointer("hsv_masked", _maskedImageSharp, false, out _maskedTextureId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating textures: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Image<Rgba32> MatToImageSharp(Mat mat)
|
||||||
|
{
|
||||||
|
Mat rgbaMat = new();
|
||||||
|
Cv2.CvtColor(mat, rgbaMat, ColorConversionCodes.BGR2RGBA);
|
||||||
|
|
||||||
|
int width = rgbaMat.Width;
|
||||||
|
int height = rgbaMat.Height;
|
||||||
|
|
||||||
|
var config = new Configuration
|
||||||
|
{
|
||||||
|
PreferContiguousImageBuffers = true
|
||||||
|
};
|
||||||
|
var image = new Image<Rgba32>(config, width, height);
|
||||||
|
|
||||||
|
if (image.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> memory))
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* matData = (byte*)rgbaMat.Data;
|
||||||
|
var span = memory.Span;
|
||||||
|
|
||||||
|
fixed (Rgba32* destPtr = &span[0])
|
||||||
|
{
|
||||||
|
byte* dest = (byte*)destPtr;
|
||||||
|
int totalBytes = width * height * 4;
|
||||||
|
Buffer.MemoryCopy(matData, dest, totalBytes, totalBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* matData = (byte*)rgbaMat.Data;
|
||||||
|
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int idx = (y * width + x) * 4;
|
||||||
|
image[x, y] = new Rgba32(
|
||||||
|
matData[idx + 0],
|
||||||
|
matData[idx + 1],
|
||||||
|
matData[idx + 2],
|
||||||
|
matData[idx + 3]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rgbaMat.Dispose();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeImageResources()
|
||||||
|
{
|
||||||
|
_originalImage?.Dispose();
|
||||||
|
_originalImage = null;
|
||||||
|
|
||||||
|
_maskedImage?.Dispose();
|
||||||
|
_maskedImage = null;
|
||||||
|
|
||||||
|
_originalImageSharp?.Dispose();
|
||||||
|
_originalImageSharp = null;
|
||||||
|
|
||||||
|
_maskedImageSharp?.Dispose();
|
||||||
|
_maskedImageSharp = null;
|
||||||
|
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
RemoveImage("hsv_original");
|
||||||
|
_originalTextureId = IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
RemoveImage("hsv_masked");
|
||||||
|
_maskedTextureId = IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
_loadedImagePath = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,556 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using OpenCvSharp;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
public static class ImGuiExtensions
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, string> _sliderEditBuffers = [];
|
||||||
|
public static bool ColorEditHSV3(string label, ref Scalar hsv)
|
||||||
|
{
|
||||||
|
ImGui.PushID(label);
|
||||||
|
|
||||||
|
int h = (int)Math.Clamp(Math.Round(hsv.Val0), 0, 179);
|
||||||
|
int s = (int)Math.Clamp(Math.Round(hsv.Val1), 0, 255);
|
||||||
|
int v = (int)Math.Clamp(Math.Round(hsv.Val2), 0, 255);
|
||||||
|
|
||||||
|
bool changed = false;
|
||||||
|
bool inputChanged = false;
|
||||||
|
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
|
||||||
|
var style = ImGui.GetStyle();
|
||||||
|
float avail = ImGui.GetContentRegionAvail().X;
|
||||||
|
float previewWidth = 21.0f;
|
||||||
|
float totalSpacing = style.ItemSpacing.X * 3;
|
||||||
|
float partWidth = Math.Max(24.0f, (avail - totalSpacing - previewWidth) / 3.0f);
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}H", ref h, 0, 179))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}S", ref s, 0, 255))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}V", ref v, 0, 255))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
if (inputChanged)
|
||||||
|
{
|
||||||
|
hsv = new Scalar(h, s, v);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector3 rgbColor = OpenCvHsvToRgb(hsv);
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
Vector2 btnSize = new(previewWidth, previewWidth);
|
||||||
|
Vector4 previewCol4 = new(rgbColor.X, rgbColor.Y, rgbColor.Z, 1.0f);
|
||||||
|
string previewBtnId = $"##ColorPreview_{label}";
|
||||||
|
if (ImGui.ColorButton(previewBtnId, previewCol4, ImGuiColorEditFlags.NoInputs, btnSize))
|
||||||
|
{
|
||||||
|
ImGui.OpenPopup($"##ColorPicker_{label}");
|
||||||
|
}
|
||||||
|
if (ImGui.BeginPopup($"##ColorPicker_{label}"))
|
||||||
|
{
|
||||||
|
Vector3 picker = rgbColor;
|
||||||
|
if (ImGui.ColorPicker3($"##ColorPickerPicker_{label}", ref picker))
|
||||||
|
{
|
||||||
|
rgbColor = picker;
|
||||||
|
Scalar newHsv = RgbToOpenCvHsv(rgbColor);
|
||||||
|
hsv = newHsv;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.PopID();
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Vector3 OpenCvHsvToRgb(Scalar hsv)
|
||||||
|
{
|
||||||
|
double h = Math.Clamp(hsv.Val0, 0.0, 179.0);
|
||||||
|
double s = Math.Clamp(hsv.Val1, 0.0, 255.0);
|
||||||
|
double v = Math.Clamp(hsv.Val2, 0.0, 255.0);
|
||||||
|
|
||||||
|
double hueDeg = (h / 179.0) * 360.0;
|
||||||
|
if (hueDeg >= 360.0)
|
||||||
|
hueDeg -= 360.0;
|
||||||
|
|
||||||
|
double saturation = s / 255.0;
|
||||||
|
double value = v / 255.0;
|
||||||
|
|
||||||
|
if (saturation <= double.Epsilon)
|
||||||
|
{
|
||||||
|
return new Vector3((float)value, (float)value, (float)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
double c = value * saturation;
|
||||||
|
double huePrime = hueDeg / 60.0;
|
||||||
|
double x = c * (1 - Math.Abs(huePrime % 2 - 1));
|
||||||
|
double m = value - c;
|
||||||
|
int region = (int)Math.Floor(huePrime);
|
||||||
|
if (region >= 6)
|
||||||
|
region = 0;
|
||||||
|
double r1;
|
||||||
|
double b1;
|
||||||
|
double g1;
|
||||||
|
switch (region)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
r1 = c;
|
||||||
|
g1 = x;
|
||||||
|
b1 = 0;
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
r1 = x;
|
||||||
|
g1 = c;
|
||||||
|
b1 = 0;
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
r1 = 0;
|
||||||
|
g1 = c;
|
||||||
|
b1 = x;
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
r1 = 0;
|
||||||
|
g1 = x;
|
||||||
|
b1 = c;
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
r1 = x;
|
||||||
|
g1 = 0;
|
||||||
|
b1 = c;
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
default:
|
||||||
|
r1 = c;
|
||||||
|
g1 = 0;
|
||||||
|
b1 = x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
double r = r1 + m;
|
||||||
|
double g = g1 + m;
|
||||||
|
double b = b1 + m;
|
||||||
|
|
||||||
|
return new Vector3(
|
||||||
|
(float)Math.Clamp(r, 0.0, 1.0),
|
||||||
|
(float)Math.Clamp(g, 0.0, 1.0),
|
||||||
|
(float)Math.Clamp(b, 0.0, 1.0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scalar RgbToOpenCvHsv(Vector3 rgb)
|
||||||
|
{
|
||||||
|
double r = Math.Clamp(rgb.X, 0f, 1f);
|
||||||
|
double g = Math.Clamp(rgb.Y, 0f, 1f);
|
||||||
|
double b = Math.Clamp(rgb.Z, 0f, 1f);
|
||||||
|
|
||||||
|
double max = Math.Max(r, Math.Max(g, b));
|
||||||
|
double min = Math.Min(r, Math.Min(g, b));
|
||||||
|
double delta = max - min;
|
||||||
|
|
||||||
|
double hueDeg;
|
||||||
|
if (delta <= double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 0;
|
||||||
|
}
|
||||||
|
else if (Math.Abs(max - r) < double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((g - b) / delta) % 6.0);
|
||||||
|
}
|
||||||
|
else if (Math.Abs(max - g) < double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((b - r) / delta) + 2.0);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((r - g) / delta) + 4.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hueDeg < 0)
|
||||||
|
hueDeg += 360.0;
|
||||||
|
|
||||||
|
double saturation = max <= double.Epsilon ? 0.0 : (delta / max);
|
||||||
|
double value = max;
|
||||||
|
|
||||||
|
int h = (int)Math.Round((hueDeg / 360.0) * 179.0);
|
||||||
|
int s = (int)Math.Round(saturation * 255.0);
|
||||||
|
int v = (int)Math.Round(value * 255.0);
|
||||||
|
|
||||||
|
h = Math.Clamp(h, 0, 179);
|
||||||
|
s = Math.Clamp(s, 0, 255);
|
||||||
|
v = Math.Clamp(v, 0, 255);
|
||||||
|
|
||||||
|
return new Scalar(h, s, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool SliderFill(string label, ref float value, float min, float max, string format = "%.2f", bool enforceRange = true)
|
||||||
|
{
|
||||||
|
bool changed = false;
|
||||||
|
|
||||||
|
string FormatValue(float v)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(format))
|
||||||
|
return v.ToString(CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
bool percent = format.Contains("%%");
|
||||||
|
string core = format.Replace("%%", "");
|
||||||
|
|
||||||
|
string result;
|
||||||
|
if (core.Contains("%d"))
|
||||||
|
{
|
||||||
|
result = ((int)Math.Round(v)).ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int pos = core.IndexOf("%.");
|
||||||
|
if (pos >= 0)
|
||||||
|
{
|
||||||
|
int fPos = core.IndexOf('f', pos + 2);
|
||||||
|
if (fPos > pos)
|
||||||
|
{
|
||||||
|
string digits = core[(pos + 2)..fPos];
|
||||||
|
if (int.TryParse(digits, out int prec))
|
||||||
|
result = v.ToString("F" + prec, CultureInfo.InvariantCulture);
|
||||||
|
else
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else if (core.Contains("%f"))
|
||||||
|
{
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
result = v.ToString(core, CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (percent) result += "%";
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
string valueStr = FormatValue(value);
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(valueStr).X + 12);
|
||||||
|
ImGui.TextUnformatted(valueStr);
|
||||||
|
|
||||||
|
float sliderWidth = ImGui.GetContentRegionAvail().X;
|
||||||
|
float sliderHeight = ImGui.GetFrameHeight();
|
||||||
|
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
|
||||||
|
ImGui.InvisibleButton("##" + label, new Vector2(sliderWidth, sliderHeight));
|
||||||
|
bool active = ImGui.IsItemActive();
|
||||||
|
bool activated = ImGui.IsItemActivated();
|
||||||
|
var io = ImGui.GetIO();
|
||||||
|
|
||||||
|
if (activated && (io.KeyCtrl))
|
||||||
|
{
|
||||||
|
string popupId = $"##SliderFillEditPopup_{label}";
|
||||||
|
string seed = value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
if (!_sliderEditBuffers.ContainsKey(label))
|
||||||
|
_sliderEditBuffers[label] = seed;
|
||||||
|
ImGui.OpenPopup(popupId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (active && !io.KeyCtrl)
|
||||||
|
{
|
||||||
|
float mouseDelta = ImGui.GetIO().MousePos.X - ImGui.GetItemRectMin().X;
|
||||||
|
float newValue = min + (mouseDelta / sliderWidth) * (max - min);
|
||||||
|
newValue = Math.Clamp(newValue, min, max);
|
||||||
|
if (format.Contains("%d"))
|
||||||
|
{
|
||||||
|
newValue = (int)Math.Round(newValue);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int pos = format.IndexOf("%.");
|
||||||
|
if (pos >= 0)
|
||||||
|
{
|
||||||
|
int fPos = format.IndexOf('f', pos + 2);
|
||||||
|
if (fPos > pos)
|
||||||
|
{
|
||||||
|
string digits = format[(pos + 2)..fPos];
|
||||||
|
if (int.TryParse(digits, out int prec))
|
||||||
|
newValue = (float)Math.Round(newValue, prec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Math.Abs(newValue - value) > float.Epsilon)
|
||||||
|
{
|
||||||
|
value = newValue;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
string popupIdOuter = $"##SliderFillEditPopup_{label}";
|
||||||
|
if (ImGui.BeginPopup(popupIdOuter))
|
||||||
|
{
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
ImGui.Separator();
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
string buffer = value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 4));
|
||||||
|
var inputFlags = ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.CharsNoBlank;
|
||||||
|
if (ImGui.InputText($"##SliderFillEdit_{label}", ref buffer, 32, inputFlags))
|
||||||
|
{
|
||||||
|
string parseStr = buffer.Trim();
|
||||||
|
if (parseStr.EndsWith('%')) parseStr = parseStr.TrimEnd('%');
|
||||||
|
if (float.TryParse(parseStr, NumberStyles.Float, CultureInfo.InvariantCulture, out float typed))
|
||||||
|
{
|
||||||
|
float clamped;
|
||||||
|
if (enforceRange)
|
||||||
|
clamped = Math.Clamp(typed, min, max);
|
||||||
|
else
|
||||||
|
clamped = typed;
|
||||||
|
if (Math.Abs(clamped - value) > float.Epsilon)
|
||||||
|
{
|
||||||
|
value = clamped;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ImGui.CloseCurrentPopup();
|
||||||
|
}
|
||||||
|
ImGui.PopStyleVar();
|
||||||
|
|
||||||
|
_sliderEditBuffers[label] = buffer;
|
||||||
|
if (ImGui.IsKeyPressed(ImGuiKey.Escape))
|
||||||
|
{
|
||||||
|
ImGui.CloseCurrentPopup();
|
||||||
|
}
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
Vector2 p0 = ImGui.GetItemRectMin();
|
||||||
|
Vector2 p1 = ImGui.GetItemRectMax();
|
||||||
|
|
||||||
|
drawList.AddRectFilled(p0, p1, ImGui.GetColorU32(ImGuiCol.FrameBg), 4f);
|
||||||
|
|
||||||
|
float fillWidth = ((value - min) / (max - min)) * (p1.X - p0.X);
|
||||||
|
fillWidth = Math.Clamp(fillWidth, 0f, p1.X - p0.X);
|
||||||
|
drawList.AddRectFilled(p0, new Vector2(p0.X + fillWidth, p1.Y), ImGui.GetColorU32(ImGuiCol.SliderGrabActive), 4f);
|
||||||
|
|
||||||
|
ImGui.PopStyleVar();
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool SliderFill(string label, ref int value, int min, int max)
|
||||||
|
{
|
||||||
|
float temp = value;
|
||||||
|
bool changed = SliderFill(label, ref temp, min, max, "");
|
||||||
|
if (changed)
|
||||||
|
value = (int)Math.Round(temp);
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
private class PaneGroupState
|
||||||
|
{
|
||||||
|
public string Id = "";
|
||||||
|
public int Count;
|
||||||
|
public float Spacing;
|
||||||
|
public int Index;
|
||||||
|
public float Width;
|
||||||
|
public Vector2? Padding;
|
||||||
|
public ImGuiChildFlags ChildFlags;
|
||||||
|
public ImGuiWindowFlags WindowFlags;
|
||||||
|
public float Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Stack<PaneGroupState> _paneGroups = new();
|
||||||
|
private static readonly Stack<bool> _paneInnerStack = new();
|
||||||
|
|
||||||
|
public static void BeginPaneGroup(string id, int count, float spacing = 12f,
|
||||||
|
Vector2? padding = null,
|
||||||
|
ImGuiChildFlags childFlags = ImGuiChildFlags.None,
|
||||||
|
ImGuiWindowFlags windowFlags = ImGuiWindowFlags.None,
|
||||||
|
float height = 0f)
|
||||||
|
{
|
||||||
|
if (count < 1) count = 1;
|
||||||
|
var avail = ImGui.GetContentRegionAvail();
|
||||||
|
float width = (avail.X - spacing * (count - 1)) / count;
|
||||||
|
_paneGroups.Push(new PaneGroupState
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
Count = count,
|
||||||
|
Spacing = spacing,
|
||||||
|
Index = 0,
|
||||||
|
Width = width,
|
||||||
|
Padding = padding,
|
||||||
|
ChildFlags = childFlags,
|
||||||
|
WindowFlags = windowFlags,
|
||||||
|
Height = height <= 0 ? avail.Y : height
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool BeginPane(string localId, bool showHeader = true, float headerRightWidth = 0f, Action? headerRight = null)
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Peek();
|
||||||
|
if (g.Index > 0)
|
||||||
|
ImGui.SameLine(0, g.Spacing);
|
||||||
|
|
||||||
|
string outerId = $"{g.Id}_{g.Index}_{localId}_OUTER";
|
||||||
|
bool outerOpen = ImGui.BeginChild(outerId, new Vector2(g.Width, g.Height), ImGuiChildFlags.None);
|
||||||
|
if (!outerOpen)
|
||||||
|
{
|
||||||
|
ImGui.EndChild();
|
||||||
|
_paneInnerStack.Push(false);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var style = ImGui.GetStyle();
|
||||||
|
float padX = (g.Padding?.X ?? style.WindowPadding.X);
|
||||||
|
float padY = (g.Padding?.Y ?? style.WindowPadding.Y);
|
||||||
|
|
||||||
|
float headerHeight = 0f;
|
||||||
|
if (showHeader)
|
||||||
|
{
|
||||||
|
string headerText = localId;
|
||||||
|
float textHeight = ImGui.GetTextLineHeight();
|
||||||
|
headerHeight = textHeight + style.FramePadding.Y * 2f;
|
||||||
|
|
||||||
|
Vector2 headerMin = ImGui.GetCursorScreenPos();
|
||||||
|
|
||||||
|
Vector2 headerMax = new(headerMin.X + g.Width, headerMin.Y + headerHeight);
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
uint bgCol = ImGui.GetColorU32(ImGuiCol.FrameBg);
|
||||||
|
uint borderCol = ImGui.GetColorU32(ImGuiCol.Border);
|
||||||
|
drawList.AddRectFilled(headerMin, headerMax, bgCol, style.ChildRounding);
|
||||||
|
drawList.AddLine(new Vector2(headerMin.X, headerMax.Y - 1), new Vector2(headerMax.X, headerMax.Y - 1), borderCol);
|
||||||
|
drawList.AddRect(headerMin, headerMax, borderCol, style.ChildRounding);
|
||||||
|
|
||||||
|
ImGui.SetCursorPos(new Vector2(padX, style.FramePadding.Y));
|
||||||
|
ImGui.TextUnformatted(headerText);
|
||||||
|
if (headerRight != null && headerRightWidth > 0f)
|
||||||
|
{
|
||||||
|
float rightX = g.Width - padX - headerRightWidth;
|
||||||
|
if (rightX < padX)
|
||||||
|
rightX = padX;
|
||||||
|
ImGui.SetCursorPos(new Vector2(rightX, style.FramePadding.Y));
|
||||||
|
headerRight();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float innerHeight = g.Height - headerHeight;
|
||||||
|
if (innerHeight < 0) innerHeight = 0;
|
||||||
|
ImGui.SetCursorPos(new Vector2(0, headerHeight));
|
||||||
|
|
||||||
|
bool pushedPad = false;
|
||||||
|
if (g.Padding.HasValue)
|
||||||
|
{
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, g.Padding.Value);
|
||||||
|
pushedPad = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool innerOpen = ImGui.BeginChild($"{outerId}_INNER", new Vector2(0, innerHeight), ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||||
|
_paneInnerStack.Push(pushedPad);
|
||||||
|
return innerOpen;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EndPane()
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Peek();
|
||||||
|
bool hadPad = _paneInnerStack.Pop();
|
||||||
|
ImGui.EndChild(); // inner
|
||||||
|
if (hadPad) ImGui.PopStyleVar();
|
||||||
|
ImGui.EndChild(); // outer
|
||||||
|
g.Index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EndPaneGroup()
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Pop();
|
||||||
|
g.Index = g.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, bool> _keybindListening = [];
|
||||||
|
private static readonly Dictionary<string, Keys> _keybindPending = [];
|
||||||
|
private static readonly Dictionary<string, Task?> _keybindTasks = [];
|
||||||
|
|
||||||
|
public static bool KeybindInput(string label, ref Keybind keybind, bool inline = false)
|
||||||
|
{
|
||||||
|
bool changed = false;
|
||||||
|
ImGui.PushID(label);
|
||||||
|
|
||||||
|
if (!inline)
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
|
||||||
|
string buttonText = _keybindListening.GetValueOrDefault(label)
|
||||||
|
? "Listening..."
|
||||||
|
: keybind.Key.ToString();
|
||||||
|
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(buttonText).X);
|
||||||
|
|
||||||
|
if (!_keybindListening.GetValueOrDefault(label, false))
|
||||||
|
{
|
||||||
|
if (ImGui.Button($"{buttonText}###{label}_Button"))
|
||||||
|
{
|
||||||
|
_keybindListening[label] = true;
|
||||||
|
_keybindPending[label] = Keys.None;
|
||||||
|
_keybindTasks[label] = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
var key = await InputManager.ListenForNextKeyOrMouseAsync();
|
||||||
|
_keybindPending[label] = key;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ImGui.BeginPopupContextItem($"###{label}_Context"))
|
||||||
|
{
|
||||||
|
bool isHold = keybind.Type == KeybindType.Hold;
|
||||||
|
if (ImGui.MenuItem("Hold", null, isHold))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Hold;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isToggle = keybind.Type == KeybindType.Toggle;
|
||||||
|
if (ImGui.MenuItem("Toggle", null, isToggle))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Toggle;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isAlways = keybind.Type == KeybindType.Always;
|
||||||
|
if (ImGui.MenuItem("Always", null, isAlways))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Always;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ImGui.Button($"{buttonText}###{label}_Listening");
|
||||||
|
if (_keybindPending.GetValueOrDefault(label, Keys.None) != Keys.None)
|
||||||
|
{
|
||||||
|
keybind.Key = _keybindPending[label];
|
||||||
|
_keybindPending[label] = Keys.None;
|
||||||
|
_keybindListening[label] = false;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.PopID();
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
partial class Renderer
|
||||||
|
{
|
||||||
|
private bool _showMovementPreview = false;
|
||||||
|
private Point _previewStartPoint = new(100, 100);
|
||||||
|
private Point _previewEndPoint = new(400, 300);
|
||||||
|
private readonly List<(Point point, double speed)> _previewPath = [];
|
||||||
|
private int UpdatePreviewInterval = 10; // ms
|
||||||
|
private DateTime _lastPreviewUpdate = DateTime.MinValue;
|
||||||
|
private bool _isDragging = false;
|
||||||
|
private bool _isMovingStart = false;
|
||||||
|
|
||||||
|
private void RenderMovementPreview()
|
||||||
|
{
|
||||||
|
if (!_showMovementPreview)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var config = mainConfig.Data;
|
||||||
|
|
||||||
|
ImGui.SetNextWindowSize(new Vector2(500, 500), ImGuiCond.Always);
|
||||||
|
ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 300, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver);
|
||||||
|
|
||||||
|
if (!ImGui.Begin("Movement Path Preview", ref _showMovementPreview, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar))
|
||||||
|
{
|
||||||
|
ImGui.End();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.TextUnformatted("Movement Path Preview");
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 14);
|
||||||
|
if (ImGui.Button("X", new Vector2(22, 22)))
|
||||||
|
{
|
||||||
|
_showMovementPreview = false;
|
||||||
|
ImGui.End();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var boundingBox = new Rectangle(_previewEndPoint.X - 20, _previewEndPoint.Y - 40, 40, 80);
|
||||||
|
|
||||||
|
if ((DateTime.Now - _lastPreviewUpdate).TotalMilliseconds > UpdatePreviewInterval)
|
||||||
|
{
|
||||||
|
_lastPreviewUpdate = DateTime.Now;
|
||||||
|
_previewPath.Clear();
|
||||||
|
|
||||||
|
MovementPaths.ResetWindMouse();
|
||||||
|
Point current = _previewStartPoint;
|
||||||
|
int steps = 0;
|
||||||
|
int maxSteps = 10000;
|
||||||
|
|
||||||
|
_previewPath.Add((current, 0.0));
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
double distance = Math.Sqrt(Math.Pow(_previewEndPoint.X - current.X, 2) + Math.Pow(_previewEndPoint.Y - current.Y, 2));
|
||||||
|
|
||||||
|
if (distance < 2.0 || steps++ >= maxSteps)
|
||||||
|
break;
|
||||||
|
|
||||||
|
bool isInBox = boundingBox.Contains(current);
|
||||||
|
Point nextPoint = InputManager.CalculateMovement(current, _previewEndPoint, config.Sensitivity, config.AimMovementType, isInBox);
|
||||||
|
if (config.EmaSmoothening)
|
||||||
|
nextPoint = MovementPaths.EmaSmoothing(current, nextPoint, config.EmaSmootheningFactor);
|
||||||
|
|
||||||
|
double speed = Math.Sqrt(Math.Pow(nextPoint.X - current.X, 2) + Math.Pow(nextPoint.Y - current.Y, 2));
|
||||||
|
_previewPath.Add((nextPoint, speed));
|
||||||
|
current = nextPoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_previewPath.Count > 0)
|
||||||
|
{
|
||||||
|
var lastPoint = _previewPath[^1].point;
|
||||||
|
double finalDistance = Math.Sqrt(Math.Pow(_previewEndPoint.X - lastPoint.X, 2) + Math.Pow(_previewEndPoint.Y - lastPoint.Y, 2));
|
||||||
|
if (finalDistance > 2.0)
|
||||||
|
_previewPath.Add((_previewEndPoint, finalDistance));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
Vector2 canvasPos = ImGui.GetCursorScreenPos();
|
||||||
|
canvasPos.Y += 5;
|
||||||
|
Vector2 canvasSize = ImGui.GetContentRegionAvail();
|
||||||
|
Vector2 size = new(canvasSize.X, canvasSize.Y - 60);
|
||||||
|
drawList.AddRectFilled(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.12f, 0.12f, 0.14f, 1.0f)), 3f);
|
||||||
|
drawList.AddRect(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.17f, 0.17f, 0.20f, 1.0f)), 3f);
|
||||||
|
drawList.PushClipRect(canvasPos, canvasPos + size, true);
|
||||||
|
drawList.AddRect(
|
||||||
|
new Vector2(boundingBox.X + canvasPos.X, boundingBox.Top + canvasPos.Y),
|
||||||
|
new Vector2(boundingBox.X + boundingBox.Width + canvasPos.X, boundingBox.Y + boundingBox.Height + canvasPos.Y),
|
||||||
|
ImGui.GetColorU32(new Vector4(0, 0, 1, 1)), 0.0f, ImDrawFlags.None, 2.0f);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if (_previewPath.Count > 1)
|
||||||
|
{
|
||||||
|
double maxSpeed = _previewPath.Max(p => p.speed);
|
||||||
|
for (int i = 1; i < _previewPath.Count; i++)
|
||||||
|
{
|
||||||
|
var (prevPoint, prevSpeed) = _previewPath[i - 1];
|
||||||
|
var (currPoint, currSpeed) = _previewPath[i];
|
||||||
|
Vector2 p1 = new(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y);
|
||||||
|
Vector2 p2 = new(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y);
|
||||||
|
|
||||||
|
double avgSpeed = (prevSpeed + currSpeed) / 2.0;
|
||||||
|
float normalizedSpeed = (float)(avgSpeed / maxSpeed);
|
||||||
|
|
||||||
|
Vector4 color;
|
||||||
|
if (normalizedSpeed < 0.33f) // green -> yellow
|
||||||
|
color = Vector4.Lerp(new Vector4(0, 1, 0, 1), new Vector4(1, 1, 0, 1), normalizedSpeed / 0.33f);
|
||||||
|
else if (normalizedSpeed < 0.66f) // yellow -> orange
|
||||||
|
color = Vector4.Lerp(new Vector4(1, 1, 0, 1), new Vector4(1, 0.5f, 0, 1), (normalizedSpeed - 0.33f) / 0.33f);
|
||||||
|
else // orange -> red
|
||||||
|
color = Vector4.Lerp(new Vector4(1, 0.5f, 0, 1), new Vector4(1, 0, 0, 1), (normalizedSpeed - 0.66f) / 0.34f);
|
||||||
|
|
||||||
|
drawList.AddLine(p1, p2, ImGui.GetColorU32(color), 2.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewStartPoint.X, canvasPos.Y + _previewStartPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(0, 1, 0, 1)));
|
||||||
|
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewEndPoint.X, canvasPos.Y + _previewEndPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(1, 0, 0, 1)));
|
||||||
|
|
||||||
|
drawList.PopClipRect();
|
||||||
|
|
||||||
|
ImGui.InvisibleButton("canvas", size);
|
||||||
|
var io = ImGui.GetIO();
|
||||||
|
var mousePos = io.MousePos;
|
||||||
|
bool isMouseInCanvas = mousePos.X >= canvasPos.X && mousePos.X <= canvasPos.X + size.X &&
|
||||||
|
mousePos.Y >= canvasPos.Y && mousePos.Y <= canvasPos.Y + size.Y;
|
||||||
|
|
||||||
|
bool isMouseDown = ImGui.IsMouseDown(ImGuiMouseButton.Left);
|
||||||
|
bool isMouseClicked = ImGui.IsMouseClicked(ImGuiMouseButton.Left);
|
||||||
|
bool isMouseReleased = ImGui.IsMouseReleased(ImGuiMouseButton.Left);
|
||||||
|
|
||||||
|
if (!_isDragging && isMouseInCanvas && isMouseClicked)
|
||||||
|
{
|
||||||
|
Vector2 localMousePos = mousePos - canvasPos;
|
||||||
|
float distToStart = Vector2.Distance(localMousePos, new Vector2(_previewStartPoint.X, _previewStartPoint.Y));
|
||||||
|
float distToEnd = Vector2.Distance(localMousePos, new Vector2(_previewEndPoint.X, _previewEndPoint.Y));
|
||||||
|
if (distToStart < 10.0f)
|
||||||
|
{
|
||||||
|
_isMovingStart = true;
|
||||||
|
_isDragging = true;
|
||||||
|
}
|
||||||
|
else if (distToEnd < 10.0f)
|
||||||
|
{
|
||||||
|
_isMovingStart = false;
|
||||||
|
_isDragging = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_isDragging = false;
|
||||||
|
_isMovingStart = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isDragging && isMouseDown)
|
||||||
|
{
|
||||||
|
Vector2 localMousePos = mousePos - canvasPos;
|
||||||
|
if (localMousePos.X < 15) localMousePos.X = 15;
|
||||||
|
if (localMousePos.Y < 15) localMousePos.Y = 15;
|
||||||
|
if (localMousePos.X > size.X - 15) localMousePos.X = size.X - 15;
|
||||||
|
if (localMousePos.Y > size.Y - 15) localMousePos.Y = size.Y - 15;
|
||||||
|
if (_isMovingStart)
|
||||||
|
{
|
||||||
|
_previewStartPoint = new Point((int)localMousePos.X, (int)localMousePos.Y);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_previewEndPoint = new Point((int)localMousePos.X, (int)localMousePos.Y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isDragging && isMouseReleased)
|
||||||
|
{
|
||||||
|
_isDragging = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Dummy(new(ImGui.GetContentRegionAvail().X, 10));
|
||||||
|
int interval = UpdatePreviewInterval;
|
||||||
|
if (ImGuiExtensions.SliderFill("Update Interval (ms)", ref interval, 1, 100))
|
||||||
|
UpdatePreviewInterval = interval;
|
||||||
|
|
||||||
|
ImGui.End();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,39 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0-windows</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<PublishAot>true</PublishAot>
|
<PublishAot>False</PublishAot>
|
||||||
<InvariantGlobalization>true</InvariantGlobalization>
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
<UseWindowsForms>True</UseWindowsForms>
|
||||||
|
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||||
|
<TargetFrameworks></TargetFrameworks>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<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="HidSharp" Version="2.6.4" />
|
||||||
|
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
|
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
|
||||||
<PackageReference Include="OpenCvSharp4.Extensions" 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.runtime.win" Version="4.11.0.20250507" />
|
||||||
<PackageReference Include="OpenCvSharp4.Windows" 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" />
|
||||||
|
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="Assets\copy.png" CopyToOutputDirectory="PreserveNewest" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -7,13 +7,19 @@ EndProject
|
|||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Debug|x64 = Debug|x64
|
||||||
Release|Any CPU = Release|Any CPU
|
Release|Any CPU = Release|Any CPU
|
||||||
|
Release|x64 = Release|x64
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.ActiveCfg = Debug|x64
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.Build.0 = Debug|x64
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.ActiveCfg = Release|x64
|
||||||
|
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.Build.0 = Release|x64
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
|
||||||
|
namespace Spectrum.Utilities
|
||||||
|
{
|
||||||
|
public class LogManager
|
||||||
|
{
|
||||||
|
private static List<LogEntry> _logEntries = [];
|
||||||
|
private static readonly object _logLock = new();
|
||||||
|
private static ConfigManager<ConfigData>? mainConfig;
|
||||||
|
private static bool? debugOverride;
|
||||||
|
public enum LogLevel
|
||||||
|
{
|
||||||
|
Debug,
|
||||||
|
Info,
|
||||||
|
Warning,
|
||||||
|
Error,
|
||||||
|
Critical
|
||||||
|
}
|
||||||
|
public class LogEntry(LogLevel level, string message)
|
||||||
|
{
|
||||||
|
public DateTime Timestamp { get; set; } = DateTime.Now;
|
||||||
|
public LogLevel Level { get; set; } = level;
|
||||||
|
public string Message { get; set; } = message;
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||||
|
public static void SetDebugOverride(bool enabled)
|
||||||
|
{
|
||||||
|
debugOverride = enabled;
|
||||||
|
}
|
||||||
|
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(message)) return;
|
||||||
|
if (mainConfig == null)
|
||||||
|
{
|
||||||
|
try { mainConfig = Program.mainConfig; } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
bool debugEnabled = Debugger.IsAttached;
|
||||||
|
if (debugOverride.HasValue)
|
||||||
|
debugEnabled = debugOverride.Value;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
debugEnabled = debugEnabled || (mainConfig?.Data?.DebugMode ?? false);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
if (level == LogLevel.Debug && !debugEnabled)
|
||||||
|
return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||||
|
Debug.WriteLine(logMessage);
|
||||||
|
if (debugEnabled && !Debugger.IsAttached)
|
||||||
|
{
|
||||||
|
try { Console.WriteLine(logMessage); } catch { }
|
||||||
|
}
|
||||||
|
lock (_logLock)
|
||||||
|
{
|
||||||
|
_logEntries ??= [];
|
||||||
|
_logEntries.Add(new LogEntry(level, message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[LogManager ERROR] Failed to append log entry: {ex.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();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void OpenLogFolder()
|
||||||
|
{
|
||||||
|
Process.Start(new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = "explorer.exe",
|
||||||
|
Arguments = Path.Combine(Directory.GetCurrentDirectory(), "bin", "logs"),
|
||||||
|
UseShellExecute = true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
namespace Spectrum.Utilities
|
||||||
|
{
|
||||||
|
public sealed class TimingStats
|
||||||
|
{
|
||||||
|
private sealed class TimingEntry
|
||||||
|
{
|
||||||
|
public long TotalTicks;
|
||||||
|
public long Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class TimingSnapshot(string name, long count, double averageTicks)
|
||||||
|
{
|
||||||
|
public string Name { get; } = name;
|
||||||
|
public long Count { get; } = count;
|
||||||
|
public double AverageTicks { get; } = averageTicks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly object sync = new();
|
||||||
|
private readonly Dictionary<string, TimingEntry> entries = [];
|
||||||
|
|
||||||
|
public void Add(string name, long ticks)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(name))
|
||||||
|
return;
|
||||||
|
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
if (!entries.TryGetValue(name, out var entry))
|
||||||
|
{
|
||||||
|
entry = new TimingEntry();
|
||||||
|
entries[name] = entry;
|
||||||
|
}
|
||||||
|
entry.TotalTicks += ticks;
|
||||||
|
entry.Count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TimingSnapshot> GetSnapshot(IEnumerable<string>? orderedNames = null)
|
||||||
|
{
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
var result = new List<TimingSnapshot>();
|
||||||
|
if (orderedNames == null)
|
||||||
|
{
|
||||||
|
foreach (var kvp in entries)
|
||||||
|
{
|
||||||
|
if (kvp.Value.Count == 0) continue;
|
||||||
|
result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
var used = new HashSet<string>();
|
||||||
|
foreach (var orderedName in orderedNames)
|
||||||
|
{
|
||||||
|
if (!entries.TryGetValue(orderedName, out var entry) || entry.Count == 0)
|
||||||
|
continue;
|
||||||
|
result.Add(new TimingSnapshot(orderedName, entry.Count, entry.TotalTicks / (double)entry.Count));
|
||||||
|
used.Add(orderedName);
|
||||||
|
}
|
||||||
|
foreach (var kvp in entries)
|
||||||
|
{
|
||||||
|
if (used.Contains(kvp.Key) || kvp.Value.Count == 0)
|
||||||
|
continue;
|
||||||
|
result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace Spectrum.Utilities
|
||||||
|
{
|
||||||
|
class Win32
|
||||||
|
{
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern int GetSystemMetrics(int nIndex);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern short GetAsyncKeyState(int vKey);
|
||||||
|
|
||||||
|
private const int SM_CXSCREEN = 0;
|
||||||
|
private const int SM_CYSCREEN = 1;
|
||||||
|
private const int SM_XVIRTUALSCREEN = 76;
|
||||||
|
private const int SM_YVIRTUALSCREEN = 77;
|
||||||
|
private const int SM_CXVIRTUALSCREEN = 78;
|
||||||
|
private const int SM_CYVIRTUALSCREEN = 79;
|
||||||
|
public static bool IsWindowHidden = false;
|
||||||
|
|
||||||
|
public static (int Width, int Height) GetPrimaryScreenSize()
|
||||||
|
{
|
||||||
|
return (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static (int X, int Y, int Width, int Height) GetVirtualScreenBounds()
|
||||||
|
{
|
||||||
|
return (
|
||||||
|
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||||
|
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||||
|
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||||
|
GetSystemMetrics(SM_CYVIRTUALSCREEN)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll")]
|
||||||
|
private static extern bool AttachConsole(int dwProcessId);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll")]
|
||||||
|
private static extern bool AllocConsole();
|
||||||
|
|
||||||
|
private const uint WDA_NONE = 0x00000000;
|
||||||
|
private const uint WDA_MONITOR = 0x00000001;
|
||||||
|
private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011;
|
||||||
|
private const uint SWP_NOSIZE = 0x0001;
|
||||||
|
private const uint SWP_NOZORDER = 0x0004;
|
||||||
|
private const uint SWP_NOACTIVATE = 0x0010;
|
||||||
|
private const int ATTACH_PARENT_PROCESS = -1;
|
||||||
|
|
||||||
|
public static bool EnableAntiCapture(IntPtr windowHandle)
|
||||||
|
{
|
||||||
|
IsWindowHidden = true;
|
||||||
|
return SetWindowDisplayAffinity(windowHandle, WDA_EXCLUDEFROMCAPTURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool DisableAntiCapture(IntPtr windowHandle)
|
||||||
|
{
|
||||||
|
IsWindowHidden = false;
|
||||||
|
return SetWindowDisplayAffinity(windowHandle, WDA_NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SetWindowPosition(IntPtr windowHandle, int x, int y)
|
||||||
|
{
|
||||||
|
SetWindowPos(windowHandle, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SetWindowBounds(IntPtr windowHandle, int x, int y, int width, int height)
|
||||||
|
{
|
||||||
|
SetWindowPos(windowHandle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EnsureConsoleAttached()
|
||||||
|
{
|
||||||
|
if (!AttachConsole(ATTACH_PARENT_PROCESS))
|
||||||
|
AllocConsole();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user