diff --git a/Spectrum/Config.cs b/Spectrum/Config.cs index 9af3095..041dad5 100644 --- a/Spectrum/Config.cs +++ b/Spectrum/Config.cs @@ -7,70 +7,281 @@ namespace Spectrum { public class ConfigManager where T : new() { - private readonly string _fileName; - private FileSystemWatcher? _watcher; + private readonly string _defaultFilename; + private readonly string _configDirectory; + private FileSystemWatcher? _fileWatcher; + private FileSystemWatcher? _directoryWatcher; private T _data; + private string _currentConfigName; + private List _availableConfigs; public T Data => _data; + public string CurrentConfigName => _currentConfigName; + public IReadOnlyList AvailableConfigs => _availableConfigs.AsReadOnly(); - public ConfigManager(string fileName) + public ConfigManager(string fileName, string configDirectory = "configs") { - _fileName = fileName; + _defaultFilename = fileName; + _configDirectory = configDirectory; + _currentConfigName = Path.GetFileNameWithoutExtension(fileName); _data = new T(); + _availableConfigs = new List(); + + if (!Directory.Exists(_configDirectory)) + { + Directory.CreateDirectory(_configDirectory); + } + + UpdateAvailableConfigs(); + StartDirectoryWatcher(); LoadConfig(); } - public void LoadConfig(bool silent = false) + public void LoadConfig(bool silent = false, string filename = "") { - if (File.Exists(_fileName)) + if (string.IsNullOrEmpty(filename)) + filename = _defaultFilename; + + try { - try + if (File.Exists(filename)) { - var json = File.ReadAllText(_fileName); - _data = JsonConvert.DeserializeObject(json) ?? new T(); - if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info); + try + { + var json = File.ReadAllText(filename); + _data = JsonConvert.DeserializeObject(json) ?? new T(); + _currentConfigName = Path.GetFileNameWithoutExtension(filename); + if (!silent) LogManager.Log($"Loaded config {filename}.", LogLevel.Info); + } + catch + { + LogManager.Log($"Failed to parse {filename}, using default values.", LogLevel.Error); + _data = new T(); + SaveConfig(); + } } - catch + else { - LogManager.Log($"Failed to parse {_fileName}, using default values.", LogLevel.Error); + LogManager.Log($"{filename} not found, creating a new one with default values.", LogLevel.Error); _data = new T(); SaveConfig(); } } - else + catch (Exception ex) { - LogManager.Log($"{_fileName} not found, creating a new one with default values.", LogLevel.Error); + LogManager.Log($"Error loading config {filename}: {ex.Message}", LogLevel.Error); _data = new T(); - SaveConfig(); } } - public void SaveConfig() + public void SaveConfig(string filename = "") { - File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented)); + if (string.IsNullOrEmpty(filename)) + filename = _defaultFilename; + + try + { + File.WriteAllText(filename, JsonConvert.SerializeObject(_data, Formatting.Indented)); + _currentConfigName = Path.GetFileNameWithoutExtension(filename); + LogManager.Log($"Saved config to {filename}.", LogLevel.Info); + } + 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(false, 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() + .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; + + LogManager.Log($"Directory watcher started for {_configDirectory}.", LogLevel.Info); + } + 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; + + LogManager.Log($"Directory watcher stopped for {_configDirectory}.", LogLevel.Info); + } + + 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); + LogManager.Log($"Deleted config {configName}.", LogLevel.Info); + 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; + LogManager.Log($"Renamed config from {oldName} to {newName}.", LogLevel.Info); + return true; + } + catch (Exception ex) + { + LogManager.Log($"Error renaming config: {ex.Message}", LogLevel.Error); + return false; + } } public void StartFileWatcher() { - if (_watcher != null) return; + if (_fileWatcher != null) return; - _watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName) + _fileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _defaultFilename) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size }; - _watcher.Changed += OnConfigFileChanged; - _watcher.EnableRaisingEvents = true; - LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info); + _fileWatcher.Changed += OnConfigFileChanged; + _fileWatcher.EnableRaisingEvents = true; + LogManager.Log($"File watcher started for {_defaultFilename}.", LogLevel.Info); } public void StopFileWatcher() { - if (_watcher == null) return; - _watcher.EnableRaisingEvents = false; - _watcher.Changed -= OnConfigFileChanged; - _watcher.Dispose(); - _watcher = null; - LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info); + if (_fileWatcher == null) return; + _fileWatcher.EnableRaisingEvents = false; + _fileWatcher.Changed -= OnConfigFileChanged; + _fileWatcher.Dispose(); + _fileWatcher = null; + LogManager.Log($"File watcher stopped for {_defaultFilename}.", LogLevel.Info); } private void OnConfigFileChanged(object sender, FileSystemEventArgs e) @@ -79,15 +290,22 @@ namespace Spectrum try { LoadConfig(true); - LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info); + LogManager.Log($"Configuration reloaded successfully for {_defaultFilename}.", LogLevel.Info); } catch (Exception ex) { - LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error); + LogManager.Log($"Failed to reload configuration for {_defaultFilename}: {ex.Message}", LogLevel.Error); } } + + public void Dispose() + { + StopFileWatcher(); + StopDirectoryWatcher(); + } } + #region Enums public enum MovementType { Linear, @@ -112,19 +330,27 @@ namespace Spectrum GDI, DirectX } + #endregion public class ConfigData { - // Image settings + #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 - // Offset settings + #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 - // Aim settings + #region Aim Settings public bool EnableAim { get; set; } = true; public bool ClosestToMouse { get; set; } = true; public Keys Keybind { get; set; } = Keys.XButton2; @@ -134,37 +360,47 @@ namespace Spectrum public double EmaSmootheningFactor { get; set; } = 0.1; public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent; + #endregion - // Triggerbot settings + #region Trigger Settings public bool TriggerBot { get; set; } = false; public Keys TriggerKey { get; set; } = Keys.XButton2; public int TriggerDelay { get; set; } = 50; // milliseconds - public int TriggerRadius { get; set; } = 15; // pixels + public int TriggerFov { get; set; } = 15; // pixels public int TriggerDuration { get; set; } = 100; // milliseconds - public bool DrawTriggerRadius { get; set; } = false; + public bool DrawTriggerFov { get; set; } = false; public Vector4 TriggerRadiusColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); + #endregion - // Display settings + #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); + #endregion - // Data collection settings + #region Data Collection Settings public bool CollectData { get; set; } = false; public bool AutoLabel { get; set; } = false; public int BackgroundImageInterval { get; set; } = 10; + #endregion - // Color settings + #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 - // Misc + #region Misc public bool DebugMode { get; set; } = false; + #endregion } public class ColorData { diff --git a/Spectrum/Detection/CaptureManager.cs b/Spectrum/Detection/CaptureManager.cs index 3c9fd99..1a9ee92 100644 --- a/Spectrum/Detection/CaptureManager.cs +++ b/Spectrum/Detection/CaptureManager.cs @@ -40,13 +40,12 @@ namespace Spectrum.Detection adapter, DriverType.Unknown, DeviceCreationFlags.BgraSupport, - new[] - { + [ FeatureLevel.Level_12_1, FeatureLevel.Level_12_0, FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 - }, + ], out _device); if (hr.Failure || _device == null) diff --git a/Spectrum/Detection/DetectionManager.cs b/Spectrum/Detection/DetectionManager.cs index 80147d6..bd4df9c 100644 --- a/Spectrum/Detection/DetectionManager.cs +++ b/Spectrum/Detection/DetectionManager.cs @@ -1,4 +1,5 @@ -using OpenCvSharp; +using ImGuiNET; +using OpenCvSharp; using Spectrum.Input; using System.Diagnostics; @@ -6,16 +7,18 @@ namespace Spectrum.Detection { class DetectionManager { - private long iterationCount = 0; - private long totalTime = 0; - private Stopwatch stopwatch = new Stopwatch(); + private readonly Stopwatch stopwatch = new Stopwatch(); private Rectangle bounds = new Rectangle(0, 0, 0, 0); - private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize(); - private ConfigManager mainConfig = Program.mainConfig; - private Renderer? renderer; - private Thread? _detectionThread; + private readonly (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize(); + private readonly int minArea; + private readonly ConfigManager mainConfig = Program.mainConfig; + private readonly Renderer? renderer; + private readonly Thread? _detectionThread; private DateTime lastMenuToggle = DateTime.MinValue; private readonly CaptureManager _captureManager; + private readonly Queue processTimes = new Queue(100); + private DateTime lastFpsUpdate = DateTime.Now; + private int frameCount = 0; public DetectionManager(Renderer renderer) { @@ -27,6 +30,7 @@ namespace Spectrum.Detection Name = "Spectrum Detection Thread", Priority = ThreadPriority.AboveNormal }; + minArea = (100 / 1440) * screenSize.Height; _detectionThread.Start(); } @@ -38,15 +42,20 @@ namespace Spectrum.Detection { if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey)) { - stopwatch.Restart(); + var config = mainConfig.Data; + if (config.DebugMode) + stopwatch.Restart(); + + renderer?.ClearDetectionDrawCommands(); + bounds = new Rectangle( - (screenSize.Width - mainConfig.Data.ImageWidth) / 2, - (screenSize.Height - mainConfig.Data.ImageHeight) / 2, - mainConfig.Data.ImageWidth, - mainConfig.Data.ImageHeight + (screenSize.Width - config.ImageWidth) / 2, + (screenSize.Height - config.ImageHeight) / 2, + config.ImageWidth, + config.ImageHeight ); var screenshot = null as Bitmap; - if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable) + if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable) screenshot = _captureManager.CaptureScreenshotDirectX(bounds); else { @@ -61,135 +70,165 @@ namespace Spectrum.Detection Thread.Sleep(2); continue; } + Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); - Mat drawing = mat.Clone(); + screenshot.Dispose(); + + Mat? drawing = (config.AutoLabel || config.CollectData) ? mat.Clone() : null; + Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); - Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat); + Cv2.InRange(mat, config.LowerHSV, config.UpperHSV, mat); Cv2.Dilate(mat, mat, null, iterations: 2); Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); - var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray(); + var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= minArea).ToArray(); var processedContours = MergeOverlappingContours(filteredContours); if (processedContours.Length > 0) { int refX = bounds.X + bounds.Width / 2; - int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent); + int refY = bounds.Y + (int)(bounds.Height * config.YOffsetPercent); - double minDist = double.MaxValue; + double minDistSquared = double.MaxValue; OpenCvSharp.Point[]? closestContour = null; - int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0; + Rect bestRect = default; + + bool shouldDrawDetections = config.DrawDetections && renderer != null; foreach (var contour in processedContours) { - int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; - foreach (var point in contour) - { - if (point.X < minX) minX = point.X; - if (point.Y < minY) minY = point.Y; - if (point.X > maxX) maxX = point.X; - if (point.Y > maxY) maxY = point.Y; - } - int centerX = (minX + maxX) / 2; - int centerY = (minY + maxY) / 2; + 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 dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2)); + + double distSquared = (absCenterX - refX) * (absCenterX - refX) + + (absCenterY - refY) * (absCenterY - refY); - if (dist < minDist) + if (distSquared < minDistSquared) { - minDist = dist; + minDistSquared = distSquared; closestContour = contour; - bestMinX = minX; - bestMinY = minY; - bestMaxX = maxX; - bestMaxY = maxY; + bestRect = rect; } - if (renderer != null) + if (shouldDrawDetections) { - if (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); - } + var _rect = new Rectangle( + rect.X + bounds.X, + rect.Y + bounds.Y, + rect.Width, + rect.Height + ); + renderer!.AddRect(_rect, config.DetectionColor, 1.0f); } - } if (closestContour != null) { - int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent)); - int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent)); + + 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, 2.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 (mainConfig.Data.AutoLabel) + if (config.DrawAimPoint) + { + renderer!.AddLine(new System.Numerics.Vector2(targetX - 10, targetY), new System.Numerics.Vector2(targetX + 10, targetY), config.AimPointColor, 2); + renderer!.AddLine(new System.Numerics.Vector2(targetX, targetY - 10), new System.Numerics.Vector2(targetX, targetY + 10), config.AimPointColor, 2); + renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20); + } + + if (config.AutoLabel && drawing != null) { AutoLabeling.AddToQueue(drawing, bounds, processedContours); AutoLabeling.AddBackgroundImage(drawing, true); } - if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData) + if (!config.AutoLabel && config.CollectData && drawing != null) { AutoLabeling.AddBackgroundImage(drawing, false); } InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY)); - if (mainConfig.Data.EnableAim) + if (config.EnableAim) { InputManager.MoveMouse(); } - if (mainConfig.Data.TriggerBot) + if (config.TriggerBot) { var _ = InputManager.ClickMouse(); } - if (renderer != null && mainConfig.Data.DrawTriggerRadius) + if (renderer != null && config.DrawTriggerFov && config.TriggerBot) { - renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), mainConfig.Data.TriggerRadius, new System.Numerics.Vector4(1.0f, 0.0f, 0.0f, 1.0f), 100); + renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100); } } - if (mainConfig.Data.DebugMode) - { - iterationCount++; - totalTime += stopwatch.ElapsedMilliseconds; - } } - else if (mainConfig.Data.CollectData) + else if (config.CollectData && drawing != null) { - if (mainConfig.Data.CollectData) - AutoLabeling.AddBackgroundImage(drawing, false); + AutoLabeling.AddBackgroundImage(drawing, false); } - screenshot?.Dispose(); - mat.Dispose(); - drawing.Dispose(); + + renderer?.CommitDetectionDrawCommands(); - if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel)) + mat.Dispose(); + drawing?.Dispose(); + + if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel)) { AutoLabeling.StartLabeling(); } - else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel) + else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel) { AutoLabeling.StopLabeling(); } - if (iterationCount >= 1000 && mainConfig.Data.DebugMode) + if (config.DebugMode) { - LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info); - int fps = (int)(iterationCount * 1000 / totalTime); - LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info); - LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info); - iterationCount = 0; - totalTime = 0; + stopwatch.Stop(); + double processTime = stopwatch.Elapsed.TotalMilliseconds; + processTimes.Enqueue(processTime); + if (processTimes.Count > 100) + processTimes.Dequeue(); + + frameCount++; + var now = DateTime.Now; + var timeSinceLastUpdate = (now - lastFpsUpdate).TotalSeconds; + if (timeSinceLastUpdate >= 1.0) + { + int fps = (int)(frameCount / timeSinceLastUpdate); + double avgProcessTime = processTimes.Count > 0 ? processTimes.Average() : 0; + Program.statistics = (fps, avgProcessTime); + frameCount = 0; + lastFpsUpdate = now; + } } } else if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey)) @@ -201,6 +240,12 @@ namespace Spectrum.Detection lastMenuToggle = now; } } + else + { + renderer?.ClearDetectionDrawCommands(); + renderer?.CommitDetectionDrawCommands(); + Thread.Sleep(5); + } } catch (Exception ex) { @@ -213,19 +258,23 @@ namespace Spectrum.Detection } } } - OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) + static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) { - var contourRects = new List<(Rect rect, List indices)>(); + if (contours.Length <= 1) + return contours; + + var contourRects = new List<(Rect rect, List indices)>(contours.Length); for (int i = 0; i < contours.Length; i++) { var rect = Cv2.BoundingRect(contours[i]); contourRects.Add((rect, new List { i })); } + bool merged; do { merged = false; - for (int i = 0; i < contourRects.Count; i++) + for (int i = 0; i < contourRects.Count - 1; i++) { var (rectA, indicesA) = contourRects[i]; for (int j = i + 1; j < contourRects.Count; j++) @@ -239,10 +288,8 @@ namespace Spectrum.Detection 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(); - newIndices.AddRange(indicesA); - newIndices.AddRange(indicesB); - contourRects[i] = (newRect, newIndices); + indicesA.AddRange(indicesB); + contourRects[i] = (newRect, indicesA); contourRects.RemoveAt(j); merged = true; break; @@ -252,15 +299,15 @@ namespace Spectrum.Detection } } while (merged); - var mergedContours = new List(); + var mergedContours = new List(contourRects.Count); foreach (var (rect, indices) in contourRects) { - var points = new List(); + var pointsList = new List(indices.Count * 10); foreach (var idx in indices) { - points.AddRange(contours[idx]); + pointsList.AddRange(contours[idx]); } - var hull = Cv2.ConvexHull(points); + var hull = Cv2.ConvexHull(pointsList); mergedContours.Add(hull); } return mergedContours.ToArray(); diff --git a/Spectrum/Input/InputManager.cs b/Spectrum/Input/InputManager.cs index 9240fc5..10c1c66 100644 --- a/Spectrum/Input/InputManager.cs +++ b/Spectrum/Input/InputManager.cs @@ -124,7 +124,7 @@ namespace Spectrum.Input if (mainConfig.Data.TriggerDelay > 0) await Task.Delay(mainConfig.Data.TriggerDelay); - int radius = mainConfig.Data.TriggerRadius; + int radius = mainConfig.Data.TriggerFov; if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius) { @@ -181,9 +181,9 @@ namespace Spectrum.Input 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 ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null) { diff --git a/Spectrum/Input/MovementPaths.cs b/Spectrum/Input/MovementPaths.cs index 4585000..5860098 100644 --- a/Spectrum/Input/MovementPaths.cs +++ b/Spectrum/Input/MovementPaths.cs @@ -150,8 +150,6 @@ namespace Spectrum.Input int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor)); return new Point(x, y); } - - private static int[] GeneratePermutation() { int[] perm = new int[256]; diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index 7a232bd..3703d8e 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -9,9 +9,8 @@ namespace Spectrum static Renderer? renderer = null; public static ConfigManager mainConfig = new ConfigManager("bin\\configs\\config.json"); public static ConfigManager colorConfig = new ConfigManager("bin\\configs\\colors.json"); - public static long iterationCount = 0; - public static long totalTime = 0; private static DetectionManager? detectionManager; + public static (int fps, double avgProcessTime) statistics = (0, 0); public static CaptureManager SharedCaptureManager { get; } = new CaptureManager(); diff --git a/Spectrum/Renderer.HSVRangeWindow.cs b/Spectrum/Renderer.HSVRangeWindow.cs new file mode 100644 index 0000000..3a78985 --- /dev/null +++ b/Spectrum/Renderer.HSVRangeWindow.cs @@ -0,0 +1,521 @@ +using ImGuiNET; +using OpenCvSharp; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using System.Numerics; + +namespace Spectrum +{ + partial class Renderer + { + private bool _showHSVRangeWindow = false; + private Mat? _originalImage = null; + private Mat? _maskedImage = null; + private Image? _originalImageSharp = null; + private Image? _maskedImageSharp = null; + private IntPtr _originalTextureId = IntPtr.Zero; + private IntPtr _maskedTextureId = IntPtr.Zero; + private Scalar _lowerHSV = new Scalar(0, 0, 0); + private Scalar _upperHSV = new Scalar(179, 255, 255); + private string _loadedImagePath = ""; + private bool _needsTextureUpdate = false; + private string _colorName = ""; + + private int _maskDisplayMode = 0; + private Vector3 _maskTintColor = new Vector3(1.0f, 1.0f, 1.0f); + private float _maskOpacity = 1.0f; + private Vector3 _backgroundColor = new Vector3(0.0f, 0.0f, 0.0f); + private bool _showOnlyMaskedRegion = true; + + void RenderHSVRangeWindow() + { + if (!_showHSVRangeWindow) + return; + + ImGui.SetNextWindowSize(new Vector2(900, 700), ImGuiCond.FirstUseEver); + 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)) + { + var existingColor = Program.colorConfig.Data.Colors.Find(c => c.Name == _colorName); + if (existingColor != null) + { + existingColor.Lower = _lowerHSV; + existingColor.Upper = _upperHSV; + LogManager.Log($"Updated existing color: {_colorName}", LogManager.LogLevel.Info); + } + else + { + Program.colorConfig.Data.Colors.Add(new ColorInfo(_colorName, _upperHSV, _lowerHSV)); + LogManager.Log($"Created new color: {_colorName}", LogManager.LogLevel.Info); + } + Program.colorConfig.SaveConfig(); + _colorName = ""; + } + else + { + LogManager.Log("Please enter a color name", LogManager.LogLevel.Warning); + } + } + } + + ImGui.End(); + } + + private void OpenImageFileDialog() + { + Thread thread = new Thread(() => + { + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + 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 : IWin32Window + { + private readonly IntPtr _handle; + + public WindowWrapper(IntPtr handle) + { + _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 Mat()) + { + Cv2.CvtColor(_originalImage, hsvImage, ColorConversionCodes.BGR2HSV); + + using (Mat mask = new Mat()) + { + 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 Mat(_originalImage.Size(), _originalImage.Type(), + new Scalar(_backgroundColor.Z * 255, _backgroundColor.Y * 255, _backgroundColor.X * 255))) + { + using (Mat maskedForeground = new Mat()) + { + Cv2.BitwiseAnd(_originalImage, _originalImage, maskedForeground, mask); + + using (Mat invertedMask = new Mat()) + { + Cv2.BitwiseNot(mask, invertedMask); + using (Mat maskedBackground = new Mat()) + { + Cv2.BitwiseAnd(background, background, maskedBackground, invertedMask); + Cv2.Add(maskedForeground, maskedBackground, _maskedImage); + } + } + } + } + } + break; + + case 1: + using (Mat coloredMask = new Mat(_originalImage.Size(), _originalImage.Type())) + { + Cv2.CvtColor(mask, coloredMask, ColorConversionCodes.GRAY2BGR); + + using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3, + new Scalar(_maskTintColor.Z, _maskTintColor.Y, _maskTintColor.X))) + { + using (Mat coloredMaskFloat = new Mat()) + using (Mat tinted = new Mat()) + { + coloredMask.ConvertTo(coloredMaskFloat, MatType.CV_32FC3, 1.0 / 255.0); + Cv2.Multiply(coloredMaskFloat, tintMat, tinted); + tinted.ConvertTo(_maskedImage, _originalImage.Type(), 255.0); + } + } + } + break; + + case 2: + using (Mat maskedResult = new Mat()) + { + Cv2.BitwiseAnd(_originalImage, _originalImage, maskedResult, mask); + + using (Mat maskColored = new Mat(_originalImage.Size(), _originalImage.Type())) + { + Cv2.CvtColor(mask, maskColored, ColorConversionCodes.GRAY2BGR); + + using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3, + new Scalar(_maskTintColor.Z * _maskOpacity, _maskTintColor.Y * _maskOpacity, _maskTintColor.X * _maskOpacity))) + { + using (Mat maskColoredFloat = new Mat()) + using (Mat tinted = new Mat()) + using (Mat tintedByte = new Mat()) + { + maskColored.ConvertTo(maskColoredFloat, MatType.CV_32FC3, 1.0 / 255.0); + Cv2.Multiply(maskColoredFloat, tintMat, tinted); + tinted.ConvertTo(tintedByte, _originalImage.Type(), 255.0); + + using (Mat originalFloat = new Mat()) + using (Mat tintedFloat = new Mat()) + using (Mat blended = new Mat()) + { + _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 MatToImageSharp(Mat mat) + { + Mat rgbaMat = new Mat(); + Cv2.CvtColor(mat, rgbaMat, ColorConversionCodes.BGR2RGBA); + + int width = rgbaMat.Width; + int height = rgbaMat.Height; + + var config = new SixLabors.ImageSharp.Configuration(); + config.PreferContiguousImageBuffers = true; + var image = new Image(config, width, height); + + if (image.DangerousTryGetSinglePixelMemory(out Memory 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 = ""; + } + } +} diff --git a/Spectrum/Renderer.ImGuiExtensions.cs b/Spectrum/Renderer.ImGuiExtensions.cs new file mode 100644 index 0000000..eac96ff --- /dev/null +++ b/Spectrum/Renderer.ImGuiExtensions.cs @@ -0,0 +1,470 @@ +using ImGuiNET; +using OpenCvSharp; +using System.Globalization; +using System.Numerics; + +namespace Spectrum +{ + public static class ImGuiExtensions + { + private static readonly Dictionary _sliderEditBuffers = new(); + 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 Vector2(previewWidth, previewWidth); + Vector4 previewCol4 = new Vector4(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; + + double r1 = 0, g1 = 0, b1 = 0; + + int region = (int)Math.Floor(huePrime); + if (region >= 6) + region = 0; + + 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 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.Substring(pos + 2, fPos - (pos + 2)); + 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.Substring(pos + 2, fPos - (pos + 2)); + 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 = Math.Clamp(typed, min, max); + 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); + 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 _paneGroups = new(); + private static readonly Stack _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) + { + 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 Vector2(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); + } + + 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; + } + } +} diff --git a/Spectrum/Renderer.cs b/Spectrum/Renderer.cs index ee083a8..1ea4543 100644 --- a/Spectrum/Renderer.cs +++ b/Spectrum/Renderer.cs @@ -7,7 +7,6 @@ using Spectrum.Input.InputLibraries.Arduino; using Spectrum.Input.InputLibraries.Makcu; using System.Collections.Concurrent; using System.Diagnostics; -using System.Globalization; using System.Numerics; namespace Spectrum @@ -15,8 +14,9 @@ namespace Spectrum partial class Renderer : Overlay { static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize(); - private List> drawCommands = new List>(); - private readonly object drawCommandsLock = new object(); + private List> detectionDrawCommands = new List>(); + private List> activeDrawCommands = new List>(); + private readonly object detectionDrawLock = new object(); private readonly CaptureManager _captureManager; private bool _vsync = true; @@ -30,6 +30,8 @@ namespace Spectrum private string ColorName = "New Color"; private static bool scrollToBottom = true; private ColorInfo? selectedColor = null; + private string configName = "New Config"; + private string? selectedConfigName = null; public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width) { @@ -43,9 +45,10 @@ namespace Spectrum } override protected void Render() { - if (mainConfig.Data.DrawDetections || mainConfig.Data.DrawFOV) + var config = mainConfig.Data; + if (config.DrawDetections || config.DrawFOV || config.DebugMode || config.DrawAimPoint) RenderOverlay(); - if (!mainConfig.Data.ShowMenu) + if (!config.ShowMenu) return; AddStyling(); @@ -72,19 +75,17 @@ namespace Spectrum if (ImGuiExtensions.BeginPane("Aim Assist")) { - bool enableAiming = mainConfig.Data.EnableAim; + bool enableAiming = config.EnableAim; if (ImGui.Checkbox("##Enable Aiming", ref enableAiming)) - { - mainConfig.Data.EnableAim = enableAiming; - } + config.EnableAim = enableAiming; ImGui.SameLine(); ImGui.TextUnformatted("Enable Aiming"); - ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Aiming") ? "Listening..." : mainConfig.Data.Keybind.ToString()).X); + ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Aiming") ? "Listening..." : config.Keybind.ToString()).X); if (!_waitingForKeybind.GetValueOrDefault("Aiming", false)) { - if (ImGui.Button($"{mainConfig.Data.Keybind.ToString()}###AimKeybind")) + if (ImGui.Button($"{config.Keybind.ToString()}###AimKeybind")) { _waitingForKeybind["Aiming"] = true; _pendingKeybind["Aiming"] = Keys.None; @@ -100,42 +101,32 @@ namespace Spectrum ImGui.Button("Listening... ###AimListening"); if (_pendingKeybind.GetValueOrDefault("Aiming", Keys.None) != Keys.None) { - mainConfig.Data.Keybind = _pendingKeybind["Aiming"]; + config.Keybind = _pendingKeybind["Aiming"]; _pendingKeybind["Aiming"] = Keys.None; _waitingForKeybind["Aiming"] = false; } } - bool closestToMouse = mainConfig.Data.ClosestToMouse; + bool closestToMouse = config.ClosestToMouse; if (ImGui.Checkbox(" Closest to Mouse", ref closestToMouse)) - { - mainConfig.Data.ClosestToMouse = closestToMouse; - } + config.ClosestToMouse = closestToMouse; - float sensitivity = (float)mainConfig.Data.Sensitivity; + float sensitivity = (float)config.Sensitivity; if (ImGuiExtensions.SliderFill("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f")) - { - mainConfig.Data.Sensitivity = sensitivity; - } + config.Sensitivity = sensitivity; - float EmaSmootheningFactor = (float)mainConfig.Data.EmaSmootheningFactor; - bool EmaSmoothening = mainConfig.Data.EmaSmoothening; + float EmaSmootheningFactor = (float)config.EmaSmootheningFactor; + bool EmaSmoothening = config.EmaSmoothening; if (ImGui.Checkbox("Ema Smoothening", ref EmaSmoothening)) - { - mainConfig.Data.EmaSmoothening = EmaSmoothening; - } + config.EmaSmoothening = EmaSmoothening; if (EmaSmoothening) - { if (ImGuiExtensions.SliderFill("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f)) - { - mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor; - } - } + config.EmaSmootheningFactor = EmaSmootheningFactor; ImGui.TextUnformatted("Movement Type"); ImGui.SetNextItemWidth(-1); - MovementType AimPath = mainConfig.Data.AimMovementType; + MovementType AimPath = config.AimMovementType; if (ImGui.BeginCombo("##Movement Type", AimPath.ToString())) { foreach (MovementType type in Enum.GetValues(typeof(MovementType))) @@ -143,80 +134,109 @@ namespace Spectrum bool isSelected = (type == AimPath); string displayName = string.Concat(type.ToString().Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString())); // just adds a space before capitals except for the first if (ImGui.Selectable(displayName, isSelected)) - { - mainConfig.Data.AimMovementType = type; - } + config.AimMovementType = type; if (isSelected) - { ImGui.SetItemDefaultFocus(); - } } ImGui.EndCombo(); } - float YOffset = (int)(mainConfig.Data.YOffsetPercent * 100); - if (ImGuiExtensions.SliderFill("Y Offset (%)", ref YOffset, 0, 100, "%d%%")) + bool YPixelOffset = config.YPixelOffset; + if (ImGui.Checkbox("Pixel Based Offset (Y)", ref YPixelOffset)) + config.YPixelOffset = YPixelOffset; + bool XPixelOffset = config.XPixelOffset; + if (ImGui.Checkbox("Pixel Based Offset (X)", ref XPixelOffset)) + config.XPixelOffset = XPixelOffset; + + if (!YPixelOffset) { - mainConfig.Data.YOffsetPercent = ((double)YOffset / 100); + float YOffset = (int)(config.YOffsetPercent * 100); + if (ImGuiExtensions.SliderFill("Y Offset (%)", ref YOffset, 0, 100, "%d%%")) + { + config.YOffsetPercent = ((double)YOffset / 100); + } + } + else + { + int YOffset = config.YOffsetPixels; + if (ImGuiExtensions.SliderFill("Y Offset (px)", ref YOffset, -200, 200)) + config.YOffsetPixels = Math.Max(-200, YOffset); } - float XOffset = (int)(mainConfig.Data.XOffsetPercent * 100); - if (ImGuiExtensions.SliderFill("X Offset (%)", ref XOffset, 0, 100, "%d%%")) + if (!XPixelOffset) { - mainConfig.Data.XOffsetPercent = ((double)XOffset / 100); + float XOffset = (int)(config.XOffsetPercent * 100); + if (ImGuiExtensions.SliderFill("X Offset (%)", ref XOffset, 0, 100, "%d%%")) + { + config.XOffsetPercent = ((double)XOffset / 100); + } + } + else + { + int XOffset = config.XOffsetPixels; + if (ImGuiExtensions.SliderFill("X Offset (px)", ref XOffset, -200, 200)) + config.XOffsetPixels = Math.Max(-200, XOffset); } ImGui.SeparatorText("Overlay Settings"); - bool DrawFOV = mainConfig.Data.DrawFOV; + bool DrawFOV = config.DrawFOV; if (ImGui.Checkbox("##Draw FOV", ref DrawFOV)) - { - mainConfig.Data.DrawFOV = DrawFOV; - } + config.DrawFOV = DrawFOV; ImGui.SameLine(); ImGui.Text("Draw FOV"); ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); - Vector4 FOVColor = mainConfig.Data.FOVColor; + Vector4 FOVColor = config.FOVColor; if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) - { - mainConfig.Data.FOVColor = FOVColor; - } + config.FOVColor = FOVColor; - bool DrawDetections = mainConfig.Data.DrawDetections; + bool DrawDetections = config.DrawDetections; if (ImGui.Checkbox("##Draw Detections", ref DrawDetections)) - { - mainConfig.Data.DrawDetections = DrawDetections; - } + config.DrawDetections = DrawDetections; ImGui.SameLine(); ImGui.Text("Draw Detections"); ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); - Vector4 DetectionColor = mainConfig.Data.DetectionColor; + Vector4 DetectionColor = config.DetectionColor; if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + config.DetectionColor = DetectionColor; + if (DrawDetections) { - mainConfig.Data.DetectionColor = DetectionColor; + bool HighlightTarget = config.HighlightTarget; + if (ImGui.Checkbox("Highlight Target", ref HighlightTarget)) + config.HighlightTarget = HighlightTarget; + ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); + Vector4 HighlightColor = config.TargetColor; + if (ImGui.ColorEdit4("Highlight Color", ref HighlightColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + config.TargetColor = HighlightColor; } + bool DrawAimPoint = config.DrawAimPoint; + if (ImGui.Checkbox("##Draw Aim Point", ref DrawAimPoint)) + config.DrawAimPoint = DrawAimPoint; + ImGui.SameLine(); + ImGui.Text("Draw Aim Point"); + ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); + Vector4 AimPointColor = config.AimPointColor; + if (ImGui.ColorEdit4("Aim Point Color", ref AimPointColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + config.AimPointColor = AimPointColor; + if (DrawFOV) { ImGui.TextUnformatted("FOV Type"); ImGui.SetNextItemWidth(-1); - FovType fovType = mainConfig.Data.FOVType; + FovType fovType = config.FOVType; if (ImGui.BeginCombo("##FOV Type", fovType.ToString())) { foreach (FovType type in Enum.GetValues(typeof(FovType))) { bool isSelected = (type == fovType); if (ImGui.Selectable(type.ToString(), isSelected)) - { - mainConfig.Data.FOVType = type; - } + config.FOVType = type; if (isSelected) - { ImGui.SetItemDefaultFocus(); - } } ImGui.EndCombo(); } @@ -226,15 +246,13 @@ namespace Spectrum if (ImGuiExtensions.BeginPane("Triggerbot")) { - bool triggerBot = mainConfig.Data.TriggerBot; + bool triggerBot = config.TriggerBot; if (ImGui.Checkbox(" Enabled", ref triggerBot)) - { - mainConfig.Data.TriggerBot = triggerBot; - } - ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Trigger Key") ? "Listening..." : mainConfig.Data.TriggerKey.ToString()).X); + config.TriggerBot = triggerBot; + ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Trigger Key") ? "Listening..." : config.TriggerKey.ToString()).X); if (!_waitingForKeybind.GetValueOrDefault("Trigger Key", false)) { - if (ImGui.Button($"{mainConfig.Data.TriggerKey}###TriggerKeybind")) + if (ImGui.Button($"{config.TriggerKey}###TriggerKeybind")) { _waitingForKeybind["Trigger Key"] = true; _pendingKeybind["Trigger Key"] = Keys.None; @@ -250,7 +268,7 @@ namespace Spectrum ImGui.Button("Listening... ###TriggerListening"); if (_pendingKeybind.GetValueOrDefault("Trigger Key", Keys.None) != Keys.None) { - mainConfig.Data.TriggerKey = _pendingKeybind["Trigger Key"]; + config.TriggerKey = _pendingKeybind["Trigger Key"]; _pendingKeybind["Trigger Key"] = Keys.None; _waitingForKeybind["Trigger Key"] = false; } @@ -258,37 +276,27 @@ namespace Spectrum if (triggerBot) { - int triggerDelay = mainConfig.Data.TriggerDelay; + int triggerDelay = config.TriggerDelay; if (ImGuiExtensions.SliderFill("Trigger Delay (ms)", ref triggerDelay, 1, 1000)) - { - mainConfig.Data.TriggerDelay = triggerDelay; - } + config.TriggerDelay = triggerDelay; - int triggerRadius = mainConfig.Data.TriggerRadius; - if (ImGuiExtensions.SliderFill("Trigger Radius (px)", ref triggerRadius, 1, 100)) - { - mainConfig.Data.TriggerRadius = triggerRadius; - } + int triggerFov = config.TriggerFov; + if (ImGuiExtensions.SliderFill("Trigger FOV (px)", ref triggerFov, 1, 100)) + config.TriggerFov = triggerFov; - int triggerDuration = mainConfig.Data.TriggerDuration; + int triggerDuration = config.TriggerDuration; if (ImGuiExtensions.SliderFill("Trigger Duration (ms)", ref triggerDuration, 1, 1000)) - { - mainConfig.Data.TriggerDuration = triggerDuration; - } + config.TriggerDuration = triggerDuration; - bool DrawTriggerRadius = mainConfig.Data.DrawTriggerRadius; - if (ImGui.Checkbox("##Draw Trigger Radius", ref DrawTriggerRadius)) - { - mainConfig.Data.DrawTriggerRadius = DrawTriggerRadius; - } + bool DrawTriggerFov = config.DrawTriggerFov; + if (ImGui.Checkbox("##Draw Trigger FOV", ref DrawTriggerFov)) + config.DrawTriggerFov = DrawTriggerFov; ImGui.SameLine(); - ImGui.TextUnformatted("Draw Trigger Radius"); + ImGui.TextUnformatted("Draw Trigger FOV"); ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); - Vector4 RadiusColor = mainConfig.Data.TriggerRadiusColor; + Vector4 RadiusColor = config.TriggerRadiusColor; if (ImGui.ColorEdit4("Trigger Color", ref RadiusColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) - { - mainConfig.Data.DetectionColor = RadiusColor; - } + config.TriggerRadiusColor = RadiusColor; } ImGuiExtensions.EndPane(); @@ -307,39 +315,42 @@ namespace Spectrum { ImGui.TextUnformatted("Image Width"); ImGui.SetNextItemWidth(-1); - int ImageWidth = mainConfig.Data.ImageWidth; + int ImageWidth = config.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; + config.ImageWidth = ImageWidth; } ImGui.TextUnformatted("Image Height"); ImGui.SetNextItemWidth(-1); - int ImageHeight = mainConfig.Data.ImageHeight; + int ImageHeight = config.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; + config.ImageHeight = ImageHeight; } ImGui.SetNextItemWidth(-1); - Scalar upperHSV = mainConfig.Data.UpperHSV; + Scalar upperHSV = config.UpperHSV; if (ImGuiExtensions.ColorEditHSV3("Upper HSV", ref upperHSV)) - { - mainConfig.Data.UpperHSV = upperHSV; - } - Scalar lowerHSV = mainConfig.Data.LowerHSV; + config.UpperHSV = upperHSV; + Scalar lowerHSV = config.LowerHSV; if (ImGuiExtensions.ColorEditHSV3("Lower HSV", ref lowerHSV)) - { - mainConfig.Data.LowerHSV = lowerHSV; - } + config.LowerHSV = lowerHSV; + + int Threshold = config.Threshold; + if (ImGuiExtensions.SliderFill("Threshold", ref Threshold, 1, 255)) + config.Threshold = Threshold; + + if (ImGui.Button("Open HSV Range Selector")) + _showHSVRangeWindow = true; ImGuiExtensions.EndPane(); } @@ -356,7 +367,7 @@ namespace Spectrum { selectedColor = color; ColorName = color.Name; - mainConfig.Data.SelectedColor = selectedColor.Name; + config.SelectedColor = selectedColor.Name; } } ImGui.EndChild(); @@ -370,9 +381,9 @@ namespace Spectrum { if (selectedColor != null) { - mainConfig.Data.SelectedColor = selectedColor.Name; - mainConfig.Data.UpperHSV = selectedColor.Upper; - mainConfig.Data.LowerHSV = selectedColor.Lower; + config.SelectedColor = selectedColor.Name; + config.UpperHSV = selectedColor.Upper; + config.LowerHSV = selectedColor.Lower; ColorName = selectedColor.Name; } } @@ -382,13 +393,12 @@ namespace Spectrum { if (colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)) is ColorInfo existingColor) { - existingColor.Upper = mainConfig.Data.UpperHSV; - existingColor.Lower = mainConfig.Data.LowerHSV; - selectedColor = existingColor; + existingColor.Upper = config.UpperHSV; + existingColor.Lower = config.LowerHSV; } else { - colors.Add(new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV)); + colors.Add(new ColorInfo(ColorName, config.UpperHSV, config.LowerHSV)); colorConfig.SaveConfig(); selectedColor = colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)); } @@ -403,12 +413,15 @@ namespace Spectrum colorConfig.SaveConfig(); if (colors.Count > 0) { - int nextIndex = Math.Max(0, currentIndex - 1); - selectedColor = colors[currentIndex - 1]; - mainConfig.Data.SelectedColor = selectedColor.Name; - mainConfig.Data.UpperHSV = selectedColor.Upper; - mainConfig.Data.LowerHSV = selectedColor.Lower; - ColorName = selectedColor.Name; + if (selectedColor.Name == config.SelectedColor) + { + int nextIndex = Math.Max(0, currentIndex - 1); + selectedColor = colors[currentIndex - 1]; + config.SelectedColor = selectedColor.Name; + config.UpperHSV = selectedColor.Upper; + config.LowerHSV = selectedColor.Lower; + ColorName = selectedColor.Name; + } } else { @@ -423,6 +436,114 @@ namespace Spectrum ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Configs")) + { + ImGuiExtensions.BeginPaneGroup("Config Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f); + + if (ImGuiExtensions.BeginPane("Config Management")) + { + ImGui.TextUnformatted("Available Configs"); + ImGui.PushStyleColor(ImGuiCol.ChildBg, new Vector4(0.110f, 0.110f, 0.125f, 1.000f)); + ImGui.BeginChild("##ConfigListChild", new Vector2(0, ImGui.GetContentRegionAvail().Y / 2), ImGuiChildFlags.None); + ImGui.Dummy(new Vector2(0, 4)); + + var availableConfigs = mainConfig.AvailableConfigs; + foreach (var _config in availableConfigs) + { + if (ImGui.Selectable(" " + _config, selectedConfigName == _config)) + { + selectedConfigName = _config; + configName = _config; + } + } + + ImGui.EndChild(); + ImGui.PopStyleColor(); + + ImGui.SetNextItemWidth(-1); + ImGui.InputTextWithHint("##ConfigName", "Config Name", ref configName, 100); + + Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22); + + if (ImGui.Button("Load Config", size)) + { + if (!string.IsNullOrEmpty(selectedConfigName)) + { + bool success = mainConfig.LoadConfigFromDirectory(selectedConfigName); + if (success) + configName = selectedConfigName; + } + } + + ImGui.SameLine(); + if (ImGui.Button("Save Config", size)) + { + if (!string.IsNullOrEmpty(configName)) + { + mainConfig.SaveConfigToDirectory(configName); + selectedConfigName = configName; + } + } + + ImGui.SameLine(); + if (ImGui.Button("Delete Config", size)) + { + if (!string.IsNullOrEmpty(selectedConfigName)) + { + bool success = mainConfig.DeleteConfigFromDirectory(selectedConfigName); + if (success) + { + selectedConfigName = null; + configName = "New Config"; + } + } + } + + ImGuiExtensions.EndPane(); + } + + if (ImGuiExtensions.BeginPane("Current Config")) + { + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.110f, 0.110f, 0.125f, 1.000f)); + ImGui.SetNextItemWidth(-1); + string currentConfig = mainConfig.CurrentConfigName; + ImGui.InputText("##CurrentConfig", ref currentConfig, 256, ImGuiInputTextFlags.ReadOnly); + ImGui.PopStyleColor(); + + Vector2 fullSize = new Vector2(ImGui.GetContentRegionAvail().X, 22); + + if (ImGui.Button("Save Current to Default", fullSize)) + mainConfig.SaveConfig(); + + if (ImGui.Button("Save Current Config", fullSize)) + if (!string.IsNullOrEmpty(configName)) + mainConfig.SaveConfigToDirectory(configName); + + if (ImGui.Button("Open Configs Folder", fullSize)) + { + string configDir = Path.Combine(Directory.GetCurrentDirectory(), "configs"); + if (Directory.Exists(configDir)) + { + Process.Start(new ProcessStartInfo + { + FileName = "explorer.exe", + Arguments = configDir, + UseShellExecute = true + }); + } + else + { + LogManager.Log($"Directory doesn't exist: {configDir}", LogManager.LogLevel.Error); + } + } + + ImGuiExtensions.EndPane(); + } + + ImGui.EndTabItem(); + } + + if (ImGui.BeginTabItem("Settings")) { ImGuiExtensions.BeginPaneGroup("Settings Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f); @@ -431,7 +552,7 @@ namespace Spectrum { ImGui.TextUnformatted("Movement Method"); ImGui.SetNextItemWidth(-1); - MovementMethod movementMethod = mainConfig.Data.MovementMethod; + MovementMethod movementMethod = config.MovementMethod; if (ImGui.BeginCombo("##Movement Method", movementMethod.ToString())) { foreach (MovementMethod method in Enum.GetValues(typeof(MovementMethod))) @@ -439,7 +560,7 @@ namespace Spectrum bool isSelected = (method == movementMethod); if (ImGui.Selectable(method.ToString(), isSelected)) { - mainConfig.Data.MovementMethod = method; + config.MovementMethod = method; switch (method) { case MovementMethod.Makcu: @@ -449,7 +570,7 @@ namespace Spectrum if (!ok) { LogManager.Log("Makcu failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - mainConfig.Data.MovementMethod = MovementMethod.MouseEvent; + config.MovementMethod = MovementMethod.MouseEvent; MakcuMain.Unload(); } break; @@ -461,7 +582,7 @@ namespace Spectrum if (!ok) { LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - mainConfig.Data.MovementMethod = MovementMethod.MouseEvent; + config.MovementMethod = MovementMethod.MouseEvent; ArduinoMain.Close(); } break; @@ -473,16 +594,14 @@ namespace Spectrum } } if (isSelected) - { ImGui.SetItemDefaultFocus(); - } } ImGui.EndCombo(); } ImGui.TextUnformatted("Capture Method"); ImGui.SetNextItemWidth(-1); - CaptureMethod captureMethod = mainConfig.Data.CaptureMethod; + CaptureMethod captureMethod = config.CaptureMethod; if (ImGui.BeginCombo("##Capture Method", captureMethod.ToString())) { foreach (CaptureMethod method in Enum.GetValues(typeof(CaptureMethod))) @@ -500,53 +619,41 @@ namespace Spectrum _method = CaptureMethod.GDI; } } - mainConfig.Data.CaptureMethod = _method; + config.CaptureMethod = _method; } if (isSelected) - { ImGui.SetItemDefaultFocus(); - } } ImGui.EndCombo(); } - bool CollectData = mainConfig.Data.CollectData; + bool CollectData = config.CollectData; if (ImGui.Checkbox("Collect Data", ref CollectData)) - { - mainConfig.Data.CollectData = CollectData; - } + config.CollectData = CollectData; - bool AutoLabel = mainConfig.Data.AutoLabel; + bool AutoLabel = config.AutoLabel; if (ImGui.Checkbox("Auto Label", ref AutoLabel)) { if (!CollectData && AutoLabel) - mainConfig.Data.CollectData = true; + config.CollectData = true; - mainConfig.Data.AutoLabel = AutoLabel; + config.AutoLabel = AutoLabel; } if (ImGui.Checkbox("VSync", ref _vsync)) - { VSync = _vsync; - } - bool DebugMode = mainConfig.Data.DebugMode; + bool DebugMode = config.DebugMode; if (ImGui.Checkbox("Debug Mode", ref DebugMode)) - { - mainConfig.Data.DebugMode = DebugMode; - } + config.DebugMode = DebugMode; if (!VSync) - { if (ImGuiExtensions.SliderFill("FPS Limit", ref _fpsLimit, 30, 480)) - { FPSLimit = _fpsLimit; - } - } ImGui.TextUnformatted("Background Image Interval"); ImGui.SetNextItemWidth(-1); - int BackgroundImageInterval = mainConfig.Data.BackgroundImageInterval; + int BackgroundImageInterval = config.BackgroundImageInterval; if (ImGui.InputInt("##Background Image Interval", ref BackgroundImageInterval, 1, 1000)) { if (BackgroundImageInterval < 1) @@ -554,12 +661,12 @@ namespace Spectrum else if (BackgroundImageInterval > 1000) BackgroundImageInterval = 1000; - mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval; + config.BackgroundImageInterval = BackgroundImageInterval; } if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false)) { - if (ImGui.Button(mainConfig.Data.MenuKey.ToString())) + if (ImGui.Button(config.MenuKey.ToString())) { _waitingForKeybind["Menu Key"] = true; _pendingKeybind["Menu Key"] = Keys.None; @@ -575,7 +682,7 @@ namespace Spectrum ImGui.Button("Listening..."); if (_pendingKeybind.GetValueOrDefault("Menu Key", Keys.None) != Keys.None) { - mainConfig.Data.MenuKey = _pendingKeybind["Menu Key"]; + config.MenuKey = _pendingKeybind["Menu Key"]; _pendingKeybind["Menu Key"] = Keys.None; _waitingForKeybind["Menu Key"] = false; } @@ -583,29 +690,6 @@ namespace Spectrum ImGui.SameLine(); ImGui.Text("Menu Keybind"); - 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); - } - } ImGuiExtensions.EndPane(); } @@ -634,23 +718,17 @@ namespace Spectrum 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(); - } ImGuiExtensions.EndPane(); } @@ -659,9 +737,12 @@ namespace Spectrum ImGui.EndTabItem(); } + ImGui.EndTabBar(); ImGui.End(); + + RenderHSVRangeWindow(); } @@ -671,29 +752,37 @@ namespace Spectrum 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(); + var config = mainConfig.Data; - if (mainConfig.Data.DrawFOV) + if (config.DrawFOV) { - if (mainConfig.Data.FOVType == FovType.Rectangle) + if (config.FOVType == FovType.Rectangle) { - 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); + drawList.AddRect(new Vector2((screenSize.width - config.ImageWidth) / 2, (screenSize.height - config.ImageHeight) / 2), + new Vector2((screenSize.width + config.ImageWidth) / 2, (screenSize.height + config.ImageHeight) / 2), + ImGui.GetColorU32(config.FOVColor), 0.0f, ImDrawFlags.None, 1.0f); } - else if (mainConfig.Data.FOVType == FovType.Circle) + else if (config.FOVType == FovType.Circle) { - AddCircle(new Vector2(screenSize.width / 2, screenSize.height / 2), mainConfig.Data.ImageWidth / 2, mainConfig.Data.FOVColor, 100, 1.0f); - } + drawList.AddCircle(new Vector2(screenSize.width / 2, screenSize.height / 2), config.ImageWidth / 2, + ImGui.GetColorU32(config.FOVColor), 100, 1.0f); + } // added straight to drawlist to prevent caching/flickering + } + + if (config.DebugMode) + { + var stats = Program.statistics; + double avgTime = Math.Round(stats.avgProcessTime, 2); + Vector2 textSize = ImGui.CalcTextSize($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms"); + drawList.AddRectFilled(new Vector2(10, 10), new Vector2(10 + textSize.X + 10, 10 + textSize.Y + 10), ImGui.GetColorU32(new Vector4(0, 0, 0, 0.8f)), 5.0f); + ImGui.SetCursorPos(new Vector2(15, 15)); + ImGui.TextUnformatted($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms"); } List> _drawCommands; - lock (drawCommandsLock) + lock (detectionDrawLock) { - _drawCommands = drawCommands.ToList(); - drawCommands.Clear(); + _drawCommands = activeDrawCommands.ToList(); } foreach (var cmd in _drawCommands) @@ -787,17 +876,17 @@ namespace Spectrum } public void AddRect(Rectangle rect, Vector4 color, float thickness = 1.0f) { - lock (drawCommandsLock) + lock (detectionDrawLock) { - drawCommands.Add(drawList => drawList.AddRect(new Vector2(rect.Left, rect.Top), new Vector2(rect.Right, rect.Bottom), ColorFromVector4(color), 0, 0, thickness)); + detectionDrawCommands.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) + lock (detectionDrawLock) { - drawCommands.Add(drawList => drawList.AddLine(p1, p2, ColorFromVector4(color), thickness)); + detectionDrawCommands.Add(drawList => drawList.AddLine(p1, p2, ColorFromVector4(color), thickness)); } } @@ -806,9 +895,9 @@ namespace Spectrum if (numSegments <= 0) numSegments = (int)(Math.Max(1, radius / 2.0f)); - lock (drawCommandsLock) + lock (detectionDrawLock) { - drawCommands.Add(drawList => drawList.AddCircle(center, radius, ColorFromVector4(color), numSegments, thickness)); + detectionDrawCommands.Add(drawList => drawList.AddCircle(center, radius, ColorFromVector4(color), numSegments, thickness)); } } @@ -816,9 +905,26 @@ namespace Spectrum { if (string.IsNullOrEmpty(text)) return; - lock (drawCommandsLock) + lock (detectionDrawLock) { - drawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ColorFromVector4(color), text)); + detectionDrawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ColorFromVector4(color), text)); + } + } + + public void CommitDetectionDrawCommands() + { + lock (detectionDrawLock) + { + activeDrawCommands = detectionDrawCommands; + detectionDrawCommands = new List>(); + } + } + + public void ClearDetectionDrawCommands() + { + lock (detectionDrawLock) + { + detectionDrawCommands.Clear(); } } @@ -838,466 +944,4 @@ namespace Spectrum return (uint)((a << 24) | (b << 16) | (g << 8) | r); } } - public static class ImGuiExtensions - { - private static readonly Dictionary _sliderEditBuffers = new(); - 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 Vector2(previewWidth, previewWidth); - Vector4 previewCol4 = new Vector4(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; - - double r1 = 0, g1 = 0, b1 = 0; - - int region = (int)Math.Floor(huePrime); - if (region >= 6) - region = 0; - - 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 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.Substring(pos + 2, fPos - (pos + 2)); - 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.Substring(pos + 2, fPos - (pos + 2)); - 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 = Math.Clamp(typed, min, max); - 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); - 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 _paneGroups = new(); - private static readonly Stack _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) - { - 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 Vector2(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); - } - - 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; - } - } } \ No newline at end of file