4 Commits
Author SHA1 Message Date
whoswhip 55bc1e9c3a feat: use imgui for UI and refactor configurations
- Updated `AutoLabeling.cs` to use `LogManager` for error logging and a new `mainConfig` object for configuration settings.
- Transformed `Config.cs` into a generic `ConfigManager<T>` class, encapsulating settings in a new `ConfigData` class for better organization.
- Enhanced `InputManager.cs` to utilize the new configuration structure and added smoothing functionality for mouse movement.
- Modified `Program.cs` to initialize `mainConfig` and `colorConfig`, improving key event handling.
- Updated `Spectrum.csproj` to target `net8.0-windows` and added new package references.
- Created `FodyWeavers.xml` to include the `Costura` weaver for dependency embedding.
- Introduced `LogManager.cs` for centralized logging functionality.
- Added `Renderer.cs` for rendering overlays with ImGui, integrating with the new configuration system.
2025-07-16 22:52:02 -04:00
whoswhip 859e2e1b43 Update README.md 2025-07-07 02:42:09 -04:00
whoswhip dd13b99249 Clean up code 2025-06-18 13:41:31 -04:00
whoswhip f8b90d7b63 Optimizations and fix memory leak/build up by disposing the mats 2025-06-17 21:11:01 -04:00
9 changed files with 1021 additions and 445 deletions
+33 -36
View File
@@ -9,47 +9,44 @@ Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processi
## Configuration ## Configuration
On first run, a default configuration file is created. On first run, a default configuration file is created.
### Parameters ### Parameters
#### `ImageSettings` | Parameter | Range/Options | Default Value | Description |
`ImageWidth`: 1 - ScreenSize (Default: 640) |---------------|-----------------------|---------------|---------------------------------|
| `ImageWidth` | 1 - ScreenSize | 640 | Defines the width of the image |
| `ImageHeight` | 1 - ScreenSize | 640 | Defines the height of the image|
`ImageHeight`: 1 - ScreenSize (Default: 640) | Parameter | Range/Options | Default Value | Description |
#### `OffsetSettings |-------------------|---------------|---------------|---------------------------------|
`YOffsetPercent`: 0.0 - 1 (Default: 0.8) | `YOffsetPercent` | 0.0 - 1 | 0.8 | Sets the vertical offset |
| `XOffsetPercent` | 0.0 - 1 | 0.5 | Sets the horizontal offset |
`XOffsetPercent`: 0.0 - 1 (Default: 0.5) | Parameter | Range/Options | Default Value | Description |
#### `AimSettings` |--------------------|-------------------------------|---------------|---------------------------------------------------------|
`EnableAim`: true or false (Default: true) | `EnableAim` | true or false | true | Enables or disables aim functionality |
| `ClosestToMouse` | true or false | true | Determines aiming at the closest target to the mouse |
| `Keybind` | 1 - 254 | 6 | Virtual key codes are used for keybinding |
| `Sensitivity` | 0.1 - 2 | 0.5 | Defines the sensitivity of the aim |
| `AimMovementType` | CubicBezier, Linear, Adaptive| CubicBezier | Specifies the type of aim movement |
`ClosestToMouse`: true or false (Default: true) | Parameter | Range/Options | Default Value | Description |
|-----------------------|---------------|---------------|---------------------------------|
| `ShowDetectionWindow` | true or false | true | Displays the detection window |
`Keybind`: 1 - 254 (Default: 6), these are [virtual key codes](https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes) | Parameter | Range/Options | Default Value | Description |
|---------------------------|---------------|---------------|-----------------------------------------------|
| `CollectData` | true or false | false | Enables or disables data collection |
| `AutoLabel` | true or false | false | Depends on `CollectData`; auto-labels data |
| `BackgroundImageInterval` | 1 - 100 | 10 | Sets interval for background image collection|
`Sensitivity`: 0.1 - 2 (Default: 0.5) | Parameter | Sub-Parameter | Range/Options | Default Value | Description |
|-------------|---------------|---------------|---------------|---------------------------------|
`AimMovementType`: CubicBezier, Linear & Adaptive (Default: CubicBezier) | **UpperHSV**| `Val0` | 0 - 255 | 150 | Hue |
| | `Val1` | 0 - 255 | 255 | Saturation |
#### `DisplaySettings` | | `Val2` | 0 - 255 | 229 | Value |
`ShowDetectionWindow`: true or false (Default: true) | | `Val3` | 0 | 0 | |
| **LowerHSV**| `Val0` | 0 - 255 | 150 | Hue |
#### `DataCollectionSettings` | | `Val1` | 0 - 255 | 255 | Saturation |
`CollectData`: true or false (Default: false) | | `Val2` | 0 - 255 | 229 | Value |
| | `Val3` | 0 | 0 | |
`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:
+16 -18
View File
@@ -1,11 +1,7 @@
using OpenCvSharp; using OpenCvSharp;
using System;
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.LogManager.LogLevel;
namespace Spectrum namespace Spectrum
{ {
@@ -18,6 +14,7 @@ namespace Spectrum
private static Task? backgroundTask; private static Task? backgroundTask;
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>(); private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>(); private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight) private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
{ {
@@ -61,9 +58,7 @@ namespace Spectrum
} }
catch catch
{ {
Console.ForegroundColor = ConsoleColor.Red; LogManager.Log("[ERROR] Failed to save labels.", 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)
@@ -74,7 +69,7 @@ namespace Spectrum
} }
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 +85,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 +97,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 +105,13 @@ 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;
if (labelingQueue.Count > 250)
return; return;
Mat clone = mat.Clone(); Mat clone = mat.Clone();
@@ -130,12 +125,15 @@ namespace Spectrum
public static void AddBackgroundImage(Mat mat, bool detected) public static void AddBackgroundImage(Mat mat, bool detected)
{ {
if (!Config.AutoLabel) if (!mainConfig.Data.AutoLabel)
return; return;
detectionAttemps++; detectionAttemps++;
if (detectionAttemps < Config.BackgroundImageInterval || detected) if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
return;
if (backgroundQueue.Count > 250)
return; return;
Mat clone = mat.Clone(); Mat clone = mat.Clone();
+105 -208
View File
@@ -1,257 +1,154 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp; using OpenCvSharp;
using System.Numerics;
using System.Security.Cryptography.X509Certificates;
using LogLevel = Spectrum.LogManager.LogLevel;
namespace Spectrum namespace Spectrum
{ {
public static class Config public class ConfigManager<T> where T : new()
{ {
private static FileSystemWatcher? _configWatcher; private readonly string _fileName;
#region Variables private FileSystemWatcher? _watcher;
private T _data;
public enum MovementType public T Data => _data;
public ConfigManager(string fileName)
{ {
Linear, _fileName = fileName;
CubicBezier, _data = new T();
QuadraticBezier, LoadConfig();
Adaptive
} }
// Image settings
public static int ImageWidth { get; set; } = 640;
public static int ImageHeight { get; set; } = 640;
// Offset settings public void LoadConfig(bool silent = false)
public static double YOffsetPercent { get; set; } = 0.8;
public static double XOffsetPercent { get; set; } = 0.5;
// Aim settings
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 (File.Exists(_fileName))
{ {
string config_content = File.ReadAllText("config.json");
try try
{ {
var config = JObject.Parse(config_content); var json = File.ReadAllText(_fileName);
bool error = false; _data = JsonConvert.DeserializeObject<T>(json) ?? new T();
if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info);
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,
"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;
Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values.");
Console.ResetColor();
ImageWidth = 640;
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() public void SaveConfig()
{ {
if (_configWatcher != null) File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented));
return; }
_configWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "config.json") public void StartFileWatcher()
{
if (_watcher != null) return;
_watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName)
{ {
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
}; };
_watcher.Changed += OnConfigFileChanged;
_configWatcher.Changed += OnConfigFileChanged; _watcher.EnableRaisingEvents = true;
_configWatcher.EnableRaisingEvents = true; LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] File watcher started for config.json");
Console.ResetColor();
} }
public static void StopFileWatcher() public void StopFileWatcher()
{ {
if (_configWatcher != null) if (_watcher == null) return;
{ _watcher.EnableRaisingEvents = false;
_configWatcher.EnableRaisingEvents = false; _watcher.Changed -= OnConfigFileChanged;
_configWatcher.Changed -= OnConfigFileChanged; _watcher.Dispose();
_configWatcher.Dispose(); _watcher = null;
_configWatcher = null; LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] File watcher stopped for config.json");
Console.ResetColor();
}
} }
private static void OnConfigFileChanged(object sender, FileSystemEventArgs e) private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
{ {
Thread.Sleep(100); Thread.Sleep(100);
try try
{ {
LoadConfig(true); LoadConfig(true);
Console.ForegroundColor = ConsoleColor.Green; LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info);
Console.WriteLine("[INFO] Configuration automatically reloaded due to file change.");
Console.ResetColor();
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.ForegroundColor = ConsoleColor.Red; LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error);
Console.WriteLine($"[ERROR] Failed to reload configuration: {ex.Message}");
Console.ResetColor();
} }
} }
}
public enum MovementType
{
Linear,
CubicBezier,
QuadraticBezier,
Adaptive
}
public class ConfigData
{
// Image settings
public int ImageWidth { get; set; } = 640;
public int ImageHeight { get; set; } = 640;
// Offset settings
public double YOffsetPercent { get; set; } = 0.8;
public double XOffsetPercent { get; set; } = 0.5;
// Aim settings
public bool EnableAim { get; set; } = true;
public bool ClosestToMouse { get; set; } = true;
public Keys Keybind { get; set; } = Keys.XButton2;
public double Sensitivity { get; set; } = 0.5;
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
public bool EmaSmoothening { get; set; } = true;
public double EmaSmootheningFactor { get; set; } = 0.1;
// Display settings
public bool ShowDetectionWindow { get; set; } = true;
public bool DrawDetections { get; set; } = true;
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
public bool ShowMenu { get; set; } = true;
public bool DrawFOV { get; set; } = false;
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
// Data collection settings
public bool CollectData { get; set; } = false;
public bool AutoLabel { get; set; } = false;
public int BackgroundImageInterval { get; set; } = 10;
// Color settings
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
}
public class ColorData
{
public List<ColorInfo> Colors { get; set; } = new List<ColorInfo>();
}
public class ColorInfo
{
public string Name { get; set; }
public Scalar Upper { get; set; }
public Scalar Lower { get; set; }
public ColorInfo(string name, Scalar upper, Scalar lower)
{
Name = name;
Upper = upper;
Lower = lower;
}
} }
} }
+3
View File
@@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>
+64 -8
View File
@@ -1,5 +1,4 @@
using System.Drawing; using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
namespace Spectrum namespace Spectrum
{ {
@@ -10,6 +9,7 @@ namespace Spectrum
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT lpPoint); private static extern bool GetCursorPos(out POINT lpPoint);
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private struct POINT private struct POINT
{ {
@@ -69,11 +69,12 @@ namespace Spectrum
int newY = (int)(start.Y + directionY * stepSize); int newY = (int)(start.Y + directionY * stepSize);
return new Point(newX, newY); return new Point(newX, newY);
} }
private static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) => (currentValue * smoothingFactor) + (previousValue * (1 - smoothingFactor));
public static void MoveMouse(Point target) public static void MoveMouse(Point target)
{ {
POINT reference = new POINT(); POINT reference = new POINT();
if (Config.ClosestToMouse) if (mainConfig.Data.ClosestToMouse)
{ {
GetCursorPos(out reference); GetCursorPos(out reference);
} }
@@ -88,20 +89,75 @@ namespace Spectrum
Point start = new Point(reference.X, reference.Y); Point start = new Point(reference.X, reference.Y);
Point end = new Point(target.X, target.Y); Point end = new Point(target.X, target.Y);
Point newPosition = Config.AimMovementType switch Point newPosition = mainConfig.Data.AimMovementType switch
{ {
Config.MovementType.CubicBezier => CubicBezierMovement(start, end, Config.Sensitivity), MovementType.CubicBezier => CubicBezierMovement(start, end, mainConfig.Data.Sensitivity),
Config.MovementType.Linear => LinearInterpolation(start, end, Config.Sensitivity), MovementType.Linear => LinearInterpolation(start, end, mainConfig.Data.Sensitivity),
Config.MovementType.Adaptive => AdaptiveMovement(start, end, Config.Sensitivity), MovementType.Adaptive => AdaptiveMovement(start, end, mainConfig.Data.Sensitivity),
Config.MovementType.QuadraticBezier => CurvedMovement(start, end, Config.Sensitivity), MovementType.QuadraticBezier => CurvedMovement(start, end, mainConfig.Data.Sensitivity),
_ => end _ => end
}; };
if (mainConfig.Data.EmaSmoothening)
{
newPosition.X = (int)EmaSmoothing(reference.X, newPosition.X, mainConfig.Data.EmaSmootheningFactor);
newPosition.Y = (int)EmaSmoothing(reference.Y, newPosition.Y, mainConfig.Data.EmaSmootheningFactor);
}
int deltaX = newPosition.X - reference.X; int deltaX = newPosition.X - reference.X;
int deltaY = newPosition.Y - reference.Y; int deltaY = newPosition.Y - reference.Y;
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
return;
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0); mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
} }
[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>();
var thread = new Thread(() =>
{
while (true)
{
for (int key = 0x08; key <= 0xFE; key++)
{
if ((GetAsyncKeyState(key) & 0x8000) != 0)
{
tcs.TrySetResult((Keys)key);
return;
}
}
foreach (var mouseKey in MouseKeys)
{
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
{
tcs.TrySetResult(mouseKey);
return;
}
}
if (cancellationToken?.IsCancellationRequested == true)
{
tcs.TrySetCanceled();
return;
}
Thread.Sleep(10);
}
})
{
IsBackground = true
};
thread.Start();
return tcs.Task;
}
} }
} }
+73
View File
@@ -0,0 +1,73 @@
using System.Diagnostics;
using System.Text;
namespace Spectrum
{
public class LogManager
{
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
Critical
}
public class LogEntry
{
public DateTime Timestamp { get; set; }
public LogLevel Level { get; set; }
public string Message { get; set; }
public LogEntry(LogLevel level, string message)
{
Timestamp = DateTime.Now;
Level = level;
Message = message;
}
public override string ToString()
{
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
}
}
private static List<LogEntry> _logEntries = new List<LogEntry>();
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
public static void Log(string message, LogLevel level = LogLevel.Info)
{
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
Debug.WriteLine(logMessage);
_logEntries.Add(new LogEntry(level, message));
}
public static void SaveLog(string filePath)
{
try
{
var logContent = new StringBuilder();
foreach (var entry in _logEntries)
{
logContent.AppendLine(entry.ToString());
}
File.WriteAllText(filePath, logContent.ToString());
Log($"Log saved to {filePath}", LogLevel.Info);
}
catch (Exception ex)
{
Log($"Failed to save log: {ex.Message}", LogLevel.Error);
}
}
public static void ClearLog()
{
_logEntries.Clear();
Log("Log cleared.", LogLevel.Info);
}
public static void OpenLogFolder()
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = Directory.GetCurrentDirectory(),
UseShellExecute = true
});
}
}
}
+201 -167
View File
@@ -1,6 +1,4 @@
using OpenCvSharp; using OpenCvSharp;
using OpenCvSharp.Internal.Vectors;
using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -9,191 +7,94 @@ namespace Spectrum
class Program class Program
{ {
static Rectangle bounds = new Rectangle(0, 0, 0, 0); static Rectangle bounds = new Rectangle(0, 0, 0, 0);
static Renderer? renderer = null;
private static DateTime lastMenuToggle = DateTime.MinValue;
public static ConfigManager<ConfigData> mainConfig = new ConfigManager<ConfigData>("bin\\configs\\config.json");
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
static void Main() static void Main()
{ {
Config.LoadConfig(); Thread renderThread = new Thread(() =>
Config.StartFileWatcher(); {
try
{
renderer = new Renderer();
renderer.Run();
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
}
catch (Exception ex)
{
LogManager.Log($"Failed to start renderer: {ex.Message}", LogManager.LogLevel.Error);
}
});
renderThread.Start();
mainConfig.LoadConfig();
mainConfig.StartFileWatcher();
var screenSize = SystemHelper.GetPrimaryScreenSize(); var screenSize = SystemHelper.GetPrimaryScreenSize();
bounds = new Rectangle(
(screenSize.Width - Config.ImageWidth) / 2,
(screenSize.Height - Config.ImageHeight) / 2,
Config.ImageWidth,
Config.ImageHeight
);
if (Config.ShowDetectionWindow) if (mainConfig.Data.ShowDetectionWindow)
{ {
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize); Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
Cv2.WaitKey(1); Cv2.WaitKey(1);
} }
if (Config.AutoLabel) if (mainConfig.Data.AutoLabel)
{ {
AutoLabeling.StartLabeling(); AutoLabeling.StartLabeling();
} }
Directory.CreateDirectory("dataset"); Directory.CreateDirectory("bin");
Directory.CreateDirectory("dataset/images"); Directory.CreateDirectory("bin/dataset");
Directory.CreateDirectory("dataset/labels"); Directory.CreateDirectory("bin/dataset/images");
Directory.CreateDirectory("bin/dataset/labels");
Directory.CreateDirectory("bin/logs");
Directory.CreateDirectory("bin/configs");
if (colorConfig.Data.Colors.Count == 0)
{
colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(150, 255, 229), new Scalar(150, 255, 229)));
colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
colorConfig.SaveConfig();
colorConfig.LoadConfig(true);
mainConfig.LoadConfig(true);
}
while (true) while (true)
{ {
if (Console.KeyAvailable) if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.Keybind) < 0)
{
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Escape)
{
if (Config.ShowDetectionWindow)
{
Cv2.DestroyAllWindows();
}
Config.StopFileWatcher();
Environment.Exit(0);
}
else if (key == ConsoleKey.O)
{
try
{
string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json");
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = configFilePath,
UseShellExecute = true,
CreateNoWindow = true
});
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Opened config file in default application.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to open config file: {ex.Message}");
}
}
else if (key == ConsoleKey.F1)
{
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();
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)
{ {
bounds = new Rectangle(
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
mainConfig.Data.ImageWidth,
mainConfig.Data.ImageHeight
);
var screenshot = CaptureScreenshot(bounds); var screenshot = CaptureScreenshot(bounds);
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
Mat drawing = mat.Clone(); // clone for drawing Mat drawing = mat.Clone();
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); // convert to hsv Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
Cv2.InRange(mat, Config.LowerHSV, Config.UpperHSV, mat); // apply mask Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
Cv2.Dilate(mat, mat, null, iterations: 2); // dilate to fill gaps Cv2.Dilate(mat, mat, null, iterations: 2);
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); // threshold to binary Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray(); var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray();
if (filteredContours.Length > 0)
var mergedContours = MergeOverlappingContours(filteredContours);
var processedContours = mergedContours.Select(ShrinkWideContour).ToArray();
if (processedContours.Length > 0)
{ {
int refX = bounds.X + bounds.Width / 2; int refX = bounds.X + bounds.Width / 2;
int refY = bounds.Y + (int)(bounds.Height * Config.YOffsetPercent); int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
double minDist = double.MaxValue; double minDist = double.MaxValue;
OpenCvSharp.Point[]? closestContour = null; OpenCvSharp.Point[]? closestContour = null;
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0; int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
foreach (var contour in filteredContours) foreach (var contour in processedContours)
{ {
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
foreach (var point in contour) foreach (var point in contour)
@@ -219,31 +120,42 @@ namespace Spectrum
bestMaxX = maxX; bestMaxX = maxX;
bestMaxY = maxY; bestMaxY = maxY;
} }
if (renderer != null && mainConfig.Data.DrawDetections)
{
var _rect = new Rectangle(
minX + bounds.X,
minY + bounds.Y,
(maxX - minX + 1),
(maxY - minY + 1)
);
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
}
} }
if (closestContour != null) if (closestContour != null)
{ {
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - Config.XOffsetPercent)); int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - Config.YOffsetPercent)); int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
int targetX = groupX + bounds.X; int targetX = groupX + bounds.X;
int targetY = groupY + bounds.Y; int targetY = groupY + bounds.Y;
if (Config.AutoLabel) if (mainConfig.Data.AutoLabel)
{ {
AutoLabeling.AddToQueue(drawing, bounds, filteredContours); AutoLabeling.AddToQueue(drawing, bounds, processedContours);
AutoLabeling.AddBackgroundImage(drawing, true); AutoLabeling.AddBackgroundImage(drawing, true);
} }
if (!Config.AutoLabel && Config.CollectData) if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
{ {
AutoLabeling.AddBackgroundImage(drawing, false); AutoLabeling.AddBackgroundImage(drawing, false);
} }
if (Config.EnableAim) if (mainConfig.Data.EnableAim)
{ {
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY)); InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
} }
if (Config.ShowDetectionWindow) if (mainConfig.Data.ShowDetectionWindow)
{ {
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2); Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
Cv2.ImShow("Spectrum Detection", drawing); Cv2.ImShow("Spectrum Detection", drawing);
@@ -251,26 +163,148 @@ namespace Spectrum
} }
} }
} }
else if (Config.ShowDetectionWindow) else if (mainConfig.Data.ShowDetectionWindow || mainConfig.Data.CollectData)
{ {
Cv2.ImShow("Spectrum Detection", drawing); Cv2.ImShow("Spectrum Detection", drawing);
Cv2.WaitKey(1); Cv2.WaitKey(1);
if (mainConfig.Data.CollectData)
AutoLabeling.AddBackgroundImage(drawing, false);
}
screenshot?.Dispose();
mat.Dispose();
drawing.Dispose();
}
else if (SystemHelper.GetAsyncKeyState(0x2D) < 0)
{
var now = DateTime.Now;
if ((now - lastMenuToggle).TotalMilliseconds > 200)
{
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
lastMenuToggle = now;
} }
} }
else else
{ {
if (Config.ShowDetectionWindow) if (mainConfig.Data.ShowDetectionWindow)
{ {
Cv2.WaitKey(1); Cv2.WaitKey(1);
} }
else else if (!mainConfig.Data.ShowDetectionWindow)
{ {
Thread.Sleep(1); if (Cv2.GetWindowProperty("Spectrum Detection", WindowPropertyFlags.Visible) >= 0)
{
Cv2.DestroyAllWindows();
}
} }
} }
} }
} }
static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
{
var contourRects = new List<(Rect rect, List<int> indices)>();
for (int i = 0; i < contours.Length; i++)
{
var rect = Cv2.BoundingRect(contours[i]);
contourRects.Add((rect, new List<int> { i }));
}
bool merged;
do
{
merged = false;
for (int i = 0; i < contourRects.Count; i++)
{
var (rectA, indicesA) = contourRects[i];
for (int j = i + 1; j < contourRects.Count; j++)
{
var (rectB, indicesB) = contourRects[j];
if (rectA.IntersectsWith(rectB))
{
var newRect = new Rect(
Math.Min(rectA.X, rectB.X),
Math.Min(rectA.Y, rectB.Y),
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
);
var newIndices = new List<int>();
newIndices.AddRange(indicesA);
newIndices.AddRange(indicesB);
contourRects[i] = (newRect, newIndices);
contourRects.RemoveAt(j);
merged = true;
break;
}
}
if (merged) break;
}
} while (merged);
var mergedContours = new List<OpenCvSharp.Point[]>();
foreach (var (rect, indices) in contourRects)
{
var points = new List<OpenCvSharp.Point>();
foreach (var idx in indices)
{
points.AddRange(contours[idx]);
}
var hull = Cv2.ConvexHull(points);
mergedContours.Add(hull);
}
return mergedContours.ToArray();
}
static OpenCvSharp.Point[] ShrinkWideContour(OpenCvSharp.Point[] contour)
{
var rect = Cv2.BoundingRect(contour);
double aspect = rect.Width / (double)rect.Height;
if (aspect <= 1.2)
return contour;
int[] xs = contour.Select(p => p.X).ToArray();
int minX = xs.Min();
int maxX = xs.Max();
int binCount = Math.Max(10, (maxX - minX + 1) / 5);
int[] bins = new int[binCount];
int binWidth = (int)Math.Ceiling((maxX - minX + 1) / (double)binCount);
foreach (var pt in contour)
{
int binIdx = (pt.X - minX) / binWidth;
if (binIdx < 0) binIdx = 0;
if (binIdx >= binCount) binIdx = binCount - 1;
bins[binIdx]++;
}
int maxMass = bins.Max();
int left = 0, right = binCount - 1;
for (int i = 0; i < binCount; i++)
{
if (bins[i] == maxMass)
{
left = i;
break;
}
}
for (int i = binCount - 1; i >= 0; i--)
{
if (bins[i] == maxMass)
{
right = i;
break;
}
}
int cropMinX = minX + left * binWidth;
int cropMaxX = minX + (right + 1) * binWidth - 1;
var shrunken = contour.Where(p => p.X >= cropMinX && p.X <= cropMaxX).ToArray();
if (shrunken.Length < 3)
return contour;
return Cv2.ConvexHull(shrunken);
}
public static Bitmap CaptureScreenshot(Rectangle bounds) public static Bitmap CaptureScreenshot(Rectangle bounds)
{ {
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
+510
View File
@@ -0,0 +1,510 @@
using ClickableTransparentOverlay;
using ImGuiNET;
using OpenCvSharp;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Numerics;
namespace Spectrum
{
class Renderer : Overlay
{
static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize();
private List<Action<ImDrawListPtr>> drawCommands = new List<Action<ImDrawListPtr>>();
private readonly object drawCommandsLock = new object();
private bool _vsync = true;
private int _fpsLimit = 240;
private Keys _pendingKeybind = Keys.None;
private bool _waitingForKeybind = false;
private Task? _keybindTask = null;
private readonly ConcurrentQueue<Keys> _keybindResults = new();
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private ConfigManager<ColorData> colorConfig = Program.colorConfig;
public Renderer() : base("Spectrum", screenSize.width, screenSize.width)
{
VSync = _vsync;
FPSLimit = _fpsLimit;
ImGui.CreateContext();
var io = ImGui.GetIO();
io.Fonts.Clear();
io.Fonts.AddFontFromFileTTF("C:\\Windows\\Fonts\\Arial.ttf", 16.0f);
}
override protected void Render()
{
if (mainConfig.Data.DrawDetections || mainConfig.Data.DrawFOV)
RenderOverlay();
if (!mainConfig.Data.ShowMenu)
return;
AddStyling();
ImGui.SetNextWindowSize(new Vector2(600, 500), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 300, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSizeConstraints(new Vector2(600, 500), new Vector2(float.MaxValue, float.MaxValue));
ImGui.Begin("Spectrum", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar);
ImGui.Text("Spectrum");
ImGui.SameLine();
float currentWidth = ImGui.GetWindowWidth();
ImGui.SetCursorPosX(currentWidth - 30);
if (ImGui.Button("X", new Vector2(22, 22)))
{
Close();
Environment.Exit(0);
}
ImGui.BeginTabBar("##tabs");
if (ImGui.BeginTabItem("Aiming"))
{
bool enableAiming = mainConfig.Data.EnableAim;
if (ImGui.Checkbox("##Enable Aiming", ref enableAiming))
{
mainConfig.Data.EnableAim = enableAiming;
}
ImGui.SameLine();
if (!_waitingForKeybind)
{
if (ImGui.Button(mainConfig.Data.Keybind.ToString()))
{
_waitingForKeybind = true;
_pendingKeybind = Keys.None;
_keybindTask = Task.Run(async () =>
{
var key = await InputManager.ListenForNextKeyOrMouseAsync();
_pendingKeybind = key;
});
}
}
else
{
ImGui.Button("Listening...");
if (_pendingKeybind != Keys.None)
{
mainConfig.Data.Keybind = _pendingKeybind;
_pendingKeybind = Keys.None;
_waitingForKeybind = false;
}
}
ImGui.SameLine();
ImGui.Text("Enable Aiming");
bool closestToMouse = mainConfig.Data.ClosestToMouse;
if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse))
{
mainConfig.Data.ClosestToMouse = closestToMouse;
}
float sensitivity = (float)mainConfig.Data.Sensitivity;
if (ImGui.SliderFloat("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f"))
{
mainConfig.Data.Sensitivity = sensitivity;
}
float EmaSmootheningFactor = (float)mainConfig.Data.EmaSmootheningFactor;
bool EmaSmoothening = mainConfig.Data.EmaSmoothening;
if (ImGui.Checkbox("Ema Smoothening", ref EmaSmoothening))
{
mainConfig.Data.EmaSmoothening = EmaSmoothening;
}
if (ImGui.SliderFloat("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f, "%.2f"))
{
mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor;
}
MovementType AimPath = mainConfig.Data.AimMovementType;
if (ImGui.BeginCombo("Movement Type", AimPath.ToString()))
{
foreach (MovementType type in Enum.GetValues(typeof(MovementType)))
{
bool isSelected = (type == AimPath);
if (ImGui.Selectable(type.ToString(), isSelected))
{
mainConfig.Data.AimMovementType = type;
}
if (isSelected)
{
ImGui.SetItemDefaultFocus();
}
}
ImGui.EndCombo();
}
int YOffset = (int)(mainConfig.Data.YOffsetPercent * 100);
if (ImGui.SliderInt("Y Offset (%)", ref YOffset, 0, 100, "%d%%"))
{
mainConfig.Data.YOffsetPercent = ((double)YOffset / 100);
}
int XOffset = (int)(mainConfig.Data.XOffsetPercent * 100);
if (ImGui.SliderInt("X Offset (%)", ref XOffset, 0, 100, "%d%%"))
{
mainConfig.Data.XOffsetPercent = ((double)XOffset / 100);
}
ImGui.SeparatorText("Overlay Settings");
bool DrawFOV = mainConfig.Data.DrawFOV;
if (ImGui.Checkbox("##Draw FOV", ref DrawFOV))
{
mainConfig.Data.DrawFOV = DrawFOV;
}
ImGui.SameLine();
Vector4 FOVColor = mainConfig.Data.FOVColor;
if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
{
mainConfig.Data.FOVColor = FOVColor;
}
ImGui.SameLine();
ImGui.Text("Draw FOV");
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Detection"))
{
int ImageWidth = mainConfig.Data.ImageWidth;
if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width))
{
if (ImageWidth < 1)
ImageWidth = 1;
else if (ImageWidth > screenSize.width)
ImageWidth = screenSize.width;
mainConfig.Data.ImageWidth = ImageWidth;
}
int ImageHeight = mainConfig.Data.ImageHeight;
if (ImGui.InputInt("Image Height", ref ImageHeight, 1, screenSize.height))
{
if (ImageHeight < 1)
ImageHeight = 1;
else if (ImageHeight > screenSize.height)
ImageHeight = screenSize.height;
mainConfig.Data.ImageHeight = ImageHeight;
}
Scalar UpperHSV = mainConfig.Data.UpperHSV;
Vector3 UpperHSVVec3 = new Vector3((float)UpperHSV.Val0, (float)UpperHSV.Val1, (float)UpperHSV.Val2);
if (ImGui.InputFloat3("Upper HSV", ref UpperHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal))
{
mainConfig.Data.UpperHSV = new Scalar(UpperHSVVec3.X, UpperHSVVec3.Y, UpperHSVVec3.Z);
}
Scalar LowerHSV = mainConfig.Data.LowerHSV;
Vector3 LowerHSVVec3 = new Vector3((float)LowerHSV.Val0, (float)LowerHSV.Val1, (float)LowerHSV.Val2);
if (ImGui.InputFloat3("Lower HSV", ref LowerHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal))
{
mainConfig.Data.LowerHSV = new Scalar(LowerHSVVec3.X, LowerHSVVec3.Y, LowerHSVVec3.Z);
}
List<ColorInfo> colors = colorConfig.Data.Colors;
if (colors.Count != 0)
{
if (ImGui.BeginCombo("Colors", mainConfig.Data.SelectedColor))
{
foreach (ColorInfo color in colors)
{
bool isSelected = (color.Name == mainConfig.Data.SelectedColor);
if (ImGui.Selectable(color.Name, isSelected))
{
mainConfig.Data.SelectedColor = color.Name;
mainConfig.Data.UpperHSV = color.Upper;
mainConfig.Data.LowerHSV = color.Lower;
}
if (isSelected)
{
ImGui.SetItemDefaultFocus();
}
}
ImGui.EndCombo();
}
}
bool DrawDetections = mainConfig.Data.DrawDetections;
if (ImGui.Checkbox("##Draw Detections", ref DrawDetections))
{
mainConfig.Data.DrawDetections = DrawDetections;
}
ImGui.SameLine();
Vector4 DetectionColor = mainConfig.Data.DetectionColor;
if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
{
mainConfig.Data.DetectionColor = DetectionColor;
}
ImGui.SameLine();
ImGui.Text("Draw Detections");
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Misc."))
{
bool ShowDetectionWindow = mainConfig.Data.ShowDetectionWindow;
if (ImGui.Checkbox("Show Detection Window", ref ShowDetectionWindow))
{
mainConfig.Data.ShowDetectionWindow = ShowDetectionWindow;
}
bool CollectData = mainConfig.Data.CollectData;
if (ImGui.Checkbox("Collect Data", ref CollectData))
{
mainConfig.Data.CollectData = CollectData;
}
bool AutoLabel = mainConfig.Data.AutoLabel;
if (ImGui.Checkbox("Auto Label", ref AutoLabel))
{
if (!CollectData && AutoLabel)
mainConfig.Data.CollectData = true;
mainConfig.Data.AutoLabel = AutoLabel;
}
int BackgroundImageInterval = mainConfig.Data.BackgroundImageInterval;
if (ImGui.InputInt("Background Image Interval", ref BackgroundImageInterval, 1, 500))
{
if (BackgroundImageInterval < 1)
BackgroundImageInterval = 1;
else if (BackgroundImageInterval > 500)
BackgroundImageInterval = 500;
mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval;
}
if (ImGui.Checkbox("VSync", ref _vsync))
{
VSync = _vsync;
}
if (ImGui.SliderInt("FPS Limit", ref _fpsLimit, 30, 480, "%d"))
{
FPSLimit = _fpsLimit;
}
if (ImGui.Button("Save Configs"))
{
mainConfig.SaveConfig();
colorConfig.SaveConfig();
}
ImGui.SameLine();
if (ImGui.Button("Open Folder"))
{
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\configs");
if (Directory.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = folderPath,
UseShellExecute = true
});
}
else
{
LogManager.Log($"Directory doesnt exist: {folderPath}", LogManager.LogLevel.Error);
}
}
ImGui.SeparatorText("Logs");
ImGui.BeginChild("Logs", new Vector2(0, -34));
ImGui.Dummy(new Vector2(0, 4));
var _LogEntries = LogManager.LogEntries.ToList();
foreach (var log in _LogEntries)
{
ImGui.Indent(8);
ImGui.Text(log.ToString());
ImGui.Unindent(8);
}
ImGui.Dummy(new Vector2(0, 4));
ImGui.EndChild();
ImGui.Dummy(new Vector2(0, 1));
if (ImGui.Button("Save Logs"))
{
LogManager.SaveLog($"bin\\logs\\{DateTime.Now.ToString("MM-dd_HH-mm-ss")}_spectrum_log.txt");
}
ImGui.SameLine();
if (ImGui.Button("Clear Logs"))
{
LogManager.ClearLog();
}
ImGui.SameLine();
if (ImGui.Button("Open Log Folder"))
{
LogManager.OpenLogFolder();
}
ImGui.EndTabItem();
}
ImGui.EndTabBar();
ImGui.End();
}
protected void RenderOverlay()
{
ImGui.SetNextWindowSize(new Vector2(screenSize.width, screenSize.height), ImGuiCond.Always);
ImGui.SetNextWindowPos(new Vector2(0, 0), ImGuiCond.Always);
ImGui.Begin("Overlay", ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNavFocus);
var drawList = ImGui.GetWindowDrawList();
if (mainConfig.Data.DrawFOV)
{
AddRect(new Rectangle(
((screenSize.width - mainConfig.Data.ImageWidth) / 2) - 1,
((screenSize.height - mainConfig.Data.ImageHeight) / 2) - 1,
mainConfig.Data.ImageWidth + 2,
mainConfig.Data.ImageHeight + 2
), mainConfig.Data.FOVColor);
}
List<Action<ImDrawListPtr>> _drawCommands;
lock (drawCommandsLock)
{
_drawCommands = drawCommands.ToList();
drawCommands.Clear();
}
foreach (var cmd in _drawCommands)
{
cmd?.Invoke(drawList);
}
ImGui.End();
}
private void AddStyling()
{
var style = ImGui.GetStyle();
var colors = style.Colors;
style.WindowRounding = 4.0f;
style.FrameRounding = 3.0f;
style.ScrollbarRounding = 3.0f;
style.GrabRounding = 3.0f;
style.FrameBorderSize = 1.0f;
style.WindowBorderSize = 1.0f;
style.PopupRounding = 4.0f;
style.TabRounding = 3.0f;
style.ChildRounding = 3.0f;
style.PopupBorderSize = 1.0f;
style.GrabMinSize = 20.0f;
style.WindowPadding = new Vector2(8, 8);
style.FramePadding = new Vector2(6, 3);
style.ItemSpacing = new Vector2(8, 4);
colors[(int)ImGuiCol.WindowBg] = new Vector4(0.10f, 0.10f, 0.12f, 1.0f);
colors[(int)ImGuiCol.ChildBg] = new Vector4(0.12f, 0.12f, 0.14f, 1.0f);
colors[(int)ImGuiCol.PopupBg] = new Vector4(0.11f, 0.11f, 0.12f, 1.0f);
colors[(int)ImGuiCol.Border] = new Vector4(0.23f, 0.23f, 0.25f, 0.50f);
colors[(int)ImGuiCol.BorderShadow] = new Vector4(0.00f, 0.00f, 0.00f, 0.00f);
colors[(int)ImGuiCol.FrameBg] = new Vector4(0.17f, 0.17f, 0.20f, 1.0f);
colors[(int)ImGuiCol.FrameBgHovered] = new Vector4(0.22f, 0.22f, 0.26f, 1.0f);
colors[(int)ImGuiCol.FrameBgActive] = new Vector4(0.22f, 0.22f, 0.27f, 1.0f);
colors[(int)ImGuiCol.TitleBg] = new Vector4(0.10f, 0.10f, 0.12f, 1.0f);
colors[(int)ImGuiCol.TitleBgActive] = new Vector4(0.15f, 0.15f, 0.18f, 1.0f);
colors[(int)ImGuiCol.TitleBgCollapsed] = new Vector4(0.12f, 0.12f, 0.14f, 1.0f);
colors[(int)ImGuiCol.MenuBarBg] = new Vector4(0.15f, 0.15f, 0.17f, 1.0f);
colors[(int)ImGuiCol.CheckMark] = new Vector4(0.80f, 0.80f, 0.80f, 1.0f);
colors[(int)ImGuiCol.SliderGrab] = new Vector4(0.31f, 0.31f, 0.34f, 1.0f);
colors[(int)ImGuiCol.SliderGrabActive] = new Vector4(0.43f, 0.43f, 0.45f, 1.0f);
colors[(int)ImGuiCol.Button] = new Vector4(0.17f, 0.17f, 0.20f, 1.0f);
colors[(int)ImGuiCol.ButtonHovered] = new Vector4(0.24f, 0.24f, 0.28f, 1.0f);
colors[(int)ImGuiCol.ButtonActive] = new Vector4(0.29f, 0.29f, 0.33f, 1.0f);
colors[(int)ImGuiCol.Header] = new Vector4(0.14f, 0.14f, 0.16f, 1.0f);
colors[(int)ImGuiCol.HeaderHovered] = new Vector4(0.20f, 0.20f, 0.22f, 1.0f);
colors[(int)ImGuiCol.HeaderActive] = new Vector4(0.24f, 0.24f, 0.26f, 1.0f);
colors[(int)ImGuiCol.Separator] = new Vector4(0.23f, 0.23f, 0.25f, 0.5f);
colors[(int)ImGuiCol.SeparatorHovered] = new Vector4(0.33f, 0.33f, 0.35f, 0.78f);
colors[(int)ImGuiCol.SeparatorActive] = new Vector4(0.32f, 0.32f, 0.35f, 1.0f);
colors[(int)ImGuiCol.ResizeGrip] = new Vector4(0.23f, 0.23f, 0.25f, 0.2f);
colors[(int)ImGuiCol.ResizeGripHovered] = new Vector4(0.33f, 0.33f, 0.36f, 0.7f);
colors[(int)ImGuiCol.ResizeGripActive] = new Vector4(0.36f, 0.36f, 0.39f, 0.9f);
colors[(int)ImGuiCol.Tab] = new Vector4(0.13f, 0.13f, 0.15f, 1.0f);
colors[(int)ImGuiCol.TabHovered] = new Vector4(0.18f, 0.18f, 0.20f, 1.0f);
colors[(int)ImGuiCol.TabSelected] = new Vector4(0.22f, 0.22f, 0.25f, 1.0f);
colors[(int)ImGuiCol.TabDimmed] = new Vector4(0.13f, 0.13f, 0.15f, 1.0f);
colors[(int)ImGuiCol.TabDimmedSelected] = new Vector4(0.18f, 0.18f, 0.20f, 1.0f);
colors[(int)ImGuiCol.Text] = new Vector4(0.85f, 0.85f, 0.88f, 1.0f);
colors[(int)ImGuiCol.TextDisabled] = new Vector4(0.48f, 0.48f, 0.52f, 1.0f);
colors[(int)ImGuiCol.PlotLines] = new Vector4(0.61f, 0.61f, 0.62f, 1.0f);
colors[(int)ImGuiCol.PlotLinesHovered] = new Vector4(0.80f, 0.80f, 0.81f, 1.0f);
colors[(int)ImGuiCol.PlotHistogram] = new Vector4(0.61f, 0.61f, 0.62f, 1.0f);
colors[(int)ImGuiCol.PlotHistogramHovered] = new Vector4(0.80f, 0.80f, 0.81f, 1.0f);
colors[(int)ImGuiCol.DragDropTarget] = new Vector4(0.90f, 0.90f, 0.90f, 0.90f);
colors[(int)ImGuiCol.NavWindowingHighlight] = new Vector4(0.70f, 0.70f, 0.70f, 0.70f);
colors[(int)ImGuiCol.NavWindowingDimBg] = new Vector4(0.20f, 0.20f, 0.20f, 0.20f);
colors[(int)ImGuiCol.ModalWindowDimBg] = new Vector4(0.10f, 0.10f, 0.10f, 0.35f);
}
public void AddRect(Rectangle rect, Vector4 color, float thickness = 1.0f)
{
lock (drawCommandsLock)
{
drawCommands.Add(drawList => drawList.AddRect(new Vector2(rect.Left, rect.Top), new Vector2(rect.Right, rect.Bottom), ColorFromVector4(color), 0, 0, thickness));
}
}
public void AddLine(Vector2 p1, Vector2 p2, Vector4 color, float thickness = 1.0f)
{
lock (drawCommandsLock)
{
drawCommands.Add(drawList => drawList.AddLine(p1, p2, ColorFromVector4(color), thickness));
}
}
public void AddCircle(Vector2 center, float radius, Vector4 color, int numSegments = 0, float thickness = 1.0f)
{
if (numSegments <= 0)
numSegments = (int)(Math.Max(1, radius / 2.0f));
lock (drawCommandsLock)
{
drawCommands.Add(drawList => drawList.AddCircle(center, radius, ColorFromVector4(color), numSegments, thickness));
}
}
public void AddText(Vector2 pos, Vector4 color, string text)
{
if (string.IsNullOrEmpty(text))
return;
lock (drawCommandsLock)
{
drawCommands.Add(drawList => drawList.AddText(pos, ColorFromVector4(color), text));
}
}
private static uint ColorFromVector4(Vector4 color)
{
int r = (int)(Math.Clamp(color.X, 0f, 1f) * 255.0f);
int g = (int)(Math.Clamp(color.Y, 0f, 1f) * 255.0f);
int b = (int)(Math.Clamp(color.Z, 0f, 1f) * 255.0f);
int a = (int)(Math.Clamp(color.W, 0f, 1f) * 255.0f);
return (uint)((a << 24) | (b << 16) | (g << 8) | r);
}
}
}
+12 -4
View File
@@ -1,21 +1,29 @@
<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>
</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="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.10" />
<PackageReference Include="System.Drawing.Common" Version="9.0.7" />
</ItemGroup> </ItemGroup>
</Project> </Project>